Author SHA1 Message Date
cflmy 1e2a045cc7 perf: time the execution path, not the opt-in Observation document
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
The first rc.3 perf comparison reused the old workload commands but switched
them to `run/call --output json`, so the candidate was timed while producing
thousands of structural events that the beta baseline never emitted. The result
was a reproducible +240..+375% p50 and +130% RSS delta caused by the
measurement, not by the program's execution cost.

- Give each run/call workload a correctness command (current Observation
  snapshot, full contract digest) and a measurement command (plain execution
  path, committed text digest).
- Verify the correctness digest once per workload and the measurement digest on
  every timed sample; a wrong or changed output is never timed.
- Re-record the expected digests and extend the tooling tests.
- A protocol document that is produced only on request must not be billed as
  an execution regression.
2026-11-24 22:25:30 +08:00
cflmy f211568c42 docs: record the reviewed candidate status and mark the beta guide historical
ci/woodpecker/manual/performance Pipeline failed
ci/woodpecker/push/main Pipeline was successful
- docs/STATUS.md: snapshot the 3.0.0-rc.3 candidate, publish the reviewed local
  gate counts (607 workspace tests, docs-consistency 7, tools/ci 41) and add
  the review-closure record; label the earlier pipeline #70 results as the
  first pre-review candidate build.
- Mark the beta-era third-party integration guide as historical and point to
  the current spec/ and developer entry points from README and
  docs/developers/README.md.
2026-11-24 21:14:11 +08:00
cflmy 765c8350b0 fix: keep snapshots free of host paths and use the documented error phases
- runtime_error_json reports module_id/relative_path/line/column only; an
  absolute host path is environment data and must not be embedded in a
  shareable Observation snapshot.
- A bad --arg is a pre-start option error: report phase "options" as the
  schema defines instead of "prepare".
- Document that any provider transport failure, including an over-budget
  request frame, kills and reaps the helper and is never retried.
2026-11-24 21:06:05 +08:00
cflmy 847cf9fe33 docs: record the rc.3 release record, licensing and CI lanes truthfully
- CHANGELOG: add the Apache-2.0-only licensing change, the removed --trace
  path, the contract/test CI split with the checked-in stream verifier, the
  analysis-observation rename, and the post-review fixes; replace the stale
  pipeline #70/archive claim with the evidence-bound wording.
- docs/ci.md: describe the actual contract, test, minimum-rust and build lanes,
  the manual performance workflow and the new docs gate.
- Annotate RFC-OBS-0001, ADR-0059 and the Execution Events evidence as
  historical so their retired spec references are not read as current.
2026-11-24 20:59:50 +08:00
cflmy d11b261aca docs: make the current contracts describe the binary that exists
- spec/security.md: replace the retired --json/EffectTrace/--trace-file
  sections with the current strict output contract (text or one snapshot from
  the verified child, live/file destinations refused) and Observation effect
  events; drop the deleted trace.rs implementation row.
- spec/package-format.md, spec/value-wire.md, spec/evaluation.md,
  spec/resource-provider-v2.md, spec/foreign.md: describe the current
  --output/--observation-file and Observation events instead of run/call
  --json and Execution Events.
- spec/analysis.md: a load failure removes the previous artifact, not only a
  compile error.
- COMPATIBILITY.md and docs/developers/*: current axes are Analysis v3,
  Observation v1 and CLI Tool revision 1; Rust 1.89; rc.3 candidate status.
- Fix the Analysis v2 / Trace v2 / trace-file references in README,
  architecture overview, contributor guide, tool example, source comments and
  AGENTS.md.
- Add a docs-consistency gate that fails when spec/ or the current developer
  guides document a retired interface or a deleted spec path.
2026-11-24 20:57:13 +08:00
cflmy 682eae82b6 perf: measure run/call through the current Observation snapshot
The nine G4 workloads still requested the retired `run/call --json` option,
so every non-check workload exited 2 and was recorded as CORRECTNESS_FAIL; the
RC performance gate could not run at all.

- Request `--output json` for run/call workloads and re-record the committed
  expected digests.
- Pin correctness to the current snapshot: terminal status/result, committed
  stdout/stderr byte digests, and ordered event-kind counts with a sequence
  digest. Run ids, wall-clock stamps and host paths are excluded, so a correct
  program keeps one stable digest.
- Add tooling tests for the workload catalogue and digest stability.
2026-11-24 20:48:26 +08:00
cflmy 44a118003f fix: close rc.3 review defects in strict destinations and Analysis cleanup
- Reject strict live/file observation destinations before opening a session:
  a rejected destination no longer writes a partial JSONL stream or snapshot.
- Remove a previous `check --emit` artifact when the project cannot be loaded,
  not only when it has compile errors, so a consumer can never bind a run to a
  stale Analysis document.
- Report the concrete `fs.exists|metadata|list|mkdir|remove|rename` effect
  operation instead of collapsing all six into `resource.request`.
- Preserve the plugin ABI frame codes through the shared worker transport:
  an over-limit frame is `worker_frame_too_large` and an encode failure is
  `worker_encode_failed`, not a generic `worker_frame_invalid`.
- Give the event and snapshot schemas the same capture `level` enum and
  document the levels in spec/observation.md.
- Add a regression test for each fix.
2026-11-24 20:43:23 +08:00
cflmy 238e4065c1 ci: use a checked-in verifier for the one-run stream/snapshot assertion
ci/woodpecker/push/main Pipeline was successful
2026-11-24 19:31:50 +08:00
cflmy 72d49ab2a1 Merge pull request 'Protocol convergence for 3.0.0-rc.3 (issue #8)' (#9) from architecture/issue-8-protocols into master
ci/woodpecker/push/main Pipeline was canceled
One current contract per public boundary: Analysis single writer, Observation replaces Trace/Execution Events, exact CLI Tool requirements, shared worker transport, rejected retired formats.

Same-SHA CI: https://ci.cflmy.cn/repos/1/pipeline/71
2026-11-24 19:23:26 +08:00
cflmy 5c371a9bef evidence: record the same-SHA CI for the rc.3 candidate
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
2026-11-24 18:49:54 +08:00
cflmy 5a89a137c7 ci: pin the converged conformance fixtures
ci/woodpecker/push/main Pipeline was successful
2026-11-24 18:32:44 +08:00
cflmy f55559b531 ci: keep the contract lane compatible with the image shell
ci/woodpecker/push/main Pipeline failed
2026-11-24 18:20:41 +08:00
cflmy 6b509d344e ci: split a fast contract lane from the full Rust lane
ci/woodpecker/push/main Pipeline was canceled
2026-11-24 18:18:35 +08:00
cflmy 33b73f41e3 consumers: resolve the event schema on jsonschema before 4.18
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:49:24 +08:00
cflmy 4f3a9bff29 docs: describe the current CI protocol gates 2026-11-24 17:40:54 +08:00
cflmy 09ab131b96 ci: exercise only the current Analysis and Observation contracts
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:37:49 +08:00
cflmy 93fada3d92 evidence: record the rc.3 local protocol-convergence gate
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:16:05 +08:00
cflmy 291e521cec release: prepare 3.0.0-rc.3 with the converged contracts 2026-11-24 17:12:51 +08:00
cflmy ca0f0799e7 ext: reject retired descriptor revisions without migration 2026-11-24 17:05:38 +08:00
cflmy 867cd72ced docs: remove retired protocol names from current guides 2026-11-24 17:04:27 +08:00
cflmy 3fe1ca3c0c docs: record the single-contract policy and review gate 2026-11-24 17:04:03 +08:00
cflmy bf141a1f26 worker: share one bounded transport across plugin and provider workers 2026-11-24 16:55:19 +08:00
Codex 404d559b86 observation: deliver one execution event sequence to stream and snapshot 2026-11-24 15:30:18 +08:00
Codex f83d992c61 tool: require exact current contracts without negotiation 2026-11-24 14:23:48 +08:00
Codex 8bfe0c36ee analysis: publish one schema for every project 2026-11-24 14:16:56 +08:00
Codex 8bd33a4615 docs: define single current contracts before the first stable release 2026-11-24 14:11:26 +08:00
Codex 652ea76360 Use Apache-2.0 as the sole project license
ci/woodpecker/push/main Pipeline was successful
2026-11-23 22:58:10 +08:00
Codex 9149ee40a4 Prepare Marqdo CLI 3.0.0-rc.2 with structured control flow
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
2026-11-23 22:40:06 +08:00
Codex 51d4c6568d Record control-flow RC verification and the pending performance decision 2026-11-23 22:35:23 +08:00
Codex af1e07f3d7 Benchmark the verified archive on release staging branches
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
2026-11-23 22:19:57 +08:00
Codex 58fccae303 Verify both Analysis versions in the shipped RC archive
ci/woodpecker/push/main Pipeline was canceled
2026-11-23 22:15:28 +08:00
Codex e903575d91 Record SHA-bound control-flow verification and consumer compatibility 2026-11-23 19:56:45 +08:00
Codex b1314328e6 Cover short-circuiting and transfers in nested branch arms 2026-11-23 19:53:40 +08:00
Codex 1dc088b602 Verify control-flow invariants and document the development contract 2026-11-23 19:51:12 +08:00
Codex 71d29261a8 Expose loop transfers through versioned public observations 2026-11-23 19:47:24 +08:00
Codex 69c5dc8d20 Implement nearest-loop transfers and reachable binding analysis 2026-11-23 19:41:01 +08:00
Codex 095eef1370 Lower else-if chains to ordered branch arms 2026-11-23 19:36:29 +08:00
Codex c582451a5f Specify structured control flow for RFC-CTRL-0005 2026-11-23 19:32:42 +08:00
242 changed files with 8702 additions and 5483 deletions

No files matched your search

+42 -20
View File
@@ -61,16 +61,16 @@ jobs:
./target/debug/marqdo check examples/multi-module/index.mq.md --refs \ ./target/debug/marqdo check examples/multi-module/index.mq.md --refs \
--emit /tmp/marqdo-analysis.json --emit /tmp/marqdo-analysis.json
./target/debug/marqdo run examples/multi-module/index.mq.md \ ./target/debug/marqdo run examples/multi-module/index.mq.md \
--trace-file /tmp/marqdo-analysis-trace.json --observation-file /tmp/marqdo-observation.json
python3 tests/consumers/analysis_consumer.py /tmp/marqdo-analysis.json python3 tests/consumers/analysis_consumer.py /tmp/marqdo-analysis.json
python3 tests/consumers/trace_consumer.py \ python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/marqdo-analysis.json /tmp/marqdo-analysis-trace.json /tmp/marqdo-observation.json --analysis /tmp/marqdo-analysis.json
./target/debug/marqdo run examples/hello.mq.md \ ./target/debug/marqdo run examples/hello.mq.md \
--trace-file /tmp/marqdo-trace.json --observation-file /tmp/marqdo-hello-observation.json
python3 - <<'PY' python3 - <<'PY'
import json import json
json.load(open("/tmp/marqdo-trace.json")) json.load(open("/tmp/marqdo-hello-observation.json"))
print("trace parses") print("snapshot parses")
PY PY
./target/debug/marqdo run examples/packages-multi-version/index.mq.md ./target/debug/marqdo run examples/packages-multi-version/index.mq.md
./target/debug/marqdo run examples/kernel-mock/demo.mq.md \ ./target/debug/marqdo run examples/kernel-mock/demo.mq.md \
@@ -106,14 +106,36 @@ jobs:
run: | run: |
cargo build -p marqdo-cli cargo build -p marqdo-cli
./target/debug/marqdo check examples/multi-module/index.mq.md --refs \ ./target/debug/marqdo check examples/multi-module/index.mq.md --refs \
--emit /tmp/analysis-v2.json --emit /tmp/analysis-simple.json
./target/debug/marqdo run examples/multi-module/index.mq.md \ ./target/debug/marqdo run examples/multi-module/index.mq.md \
--trace-file /tmp/trace-v2.json --observation-file /tmp/observation.json
python3 tests/consumers/validate_protocols.py \ python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v2.json /tmp/trace-v2.json examples/tool-unknown-name/tool.json /tmp/analysis-simple.json /tmp/observation.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json python3 tests/consumers/analysis_consumer.py /tmp/analysis-simple.json
python3 tests/consumers/trace_consumer.py \ python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/analysis-v2.json /tmp/trace-v2.json /tmp/observation.json --analysis /tmp/analysis-simple.json
./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md \
--emit /tmp/analysis-control.json
./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md \
--output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-control.json /tmp/control-observation.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-control.json --require-transfers
python3 tests/consumers/observation_consumer.py --snapshot /tmp/control-observation.json --analysis /tmp/analysis-control.json
python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl \
--analysis /tmp/analysis-control.json --validate-schema
python3 - <<'PY'
import json, pathlib
events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()]
snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_bytes())
assert snapshot["events"] == events
PY
cp /tmp/analysis-control.json /tmp/analysis-stale.json
printf ' ' >> /tmp/analysis-stale.json
if python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl \
--analysis /tmp/analysis-stale.json; then
exit 1
fi
cross-platform: cross-platform:
name: runtime contract (${{ matrix.os }}) name: runtime contract (${{ matrix.os }})
@@ -145,7 +167,7 @@ jobs:
workspace-tests.log "Workspace tests on ${{ matrix.os }}" workspace-tests.log "Workspace tests on ${{ matrix.os }}"
fi fi
exit "$status" exit "$status"
- name: Portable CLI, analysis and trace smoke - name: Portable CLI, Analysis and Observation smoke
shell: bash shell: bash
run: | run: |
set -e set -e
@@ -153,9 +175,9 @@ jobs:
--refs --emit /tmp/marqdo-portable-analysis.json --refs --emit /tmp/marqdo-portable-analysis.json
python3 tests/consumers/analysis_consumer.py /tmp/marqdo-portable-analysis.json python3 tests/consumers/analysis_consumer.py /tmp/marqdo-portable-analysis.json
cargo run -q -p marqdo-cli -- run examples/multi-module/index.mq.md \ cargo run -q -p marqdo-cli -- run examples/multi-module/index.mq.md \
--trace-file /tmp/marqdo-portable-trace.json --observation-file /tmp/marqdo-portable-observation.json
python3 tests/consumers/trace_consumer.py \ python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/marqdo-portable-analysis.json /tmp/marqdo-portable-trace.json /tmp/marqdo-portable-observation.json --analysis /tmp/marqdo-portable-analysis.json
- name: Strict isolation is unavailable and must fail closed - name: Strict isolation is unavailable and must fail closed
shell: bash shell: bash
run: | run: |
@@ -171,16 +193,16 @@ jobs:
run: | run: |
set -euo pipefail set -euo pipefail
set +e set +e
json=$(cargo run -q -p marqdo-cli -- run examples/hello.mq.md --mode strict --json) json=$(cargo run -q -p marqdo-cli -- run examples/hello.mq.md --mode strict --output json)
code=$? code=$?
set -e set -e
test "$code" -eq 1 test "$code" -eq 1
JSON_DOC="$json" python3 - <<'PY' JSON_DOC="$json" python3 - <<'PY'
import json, os import json, os
document = json.loads(os.environ["JSON_DOC"]) document = json.loads(os.environ["JSON_DOC"])
assert document["success"] is False, document assert document["schema"] == "marqdo.observation", document
assert document["command"] == "run", document assert document["run"]["status"] == "rejected", document
assert document["code"] == "strict.probe_unavailable", document assert document["events"][-1]["payload"]["error"]["code"] == "strict.probe_unavailable", document
PY PY
frozen-extensions: frozen-extensions:
+37 -7
View File
@@ -5,6 +5,40 @@ when:
event: [push, pull_request] event: [push, pull_request]
steps: steps:
# Fast contract lane: build the two shipped binaries and exercise the public
# Analysis/Observation contracts through the real CLI plus independent Python
# consumers. Kept separate from the Rust lane so a protocol break surfaces in
# minutes instead of waiting for the cross-target toolchain packages.
contract:
image: rust:1.100-bookworm
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker
- |
set -eux
./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json
./target/debug/marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl --observation-file /tmp/observation.json > /tmp/observation.jsonl
python3 tests/consumers/analysis_consumer.py /tmp/analysis.json
python3 tests/consumers/observation_consumer.py --validate-schema /tmp/observation.jsonl
python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/analysis.json /tmp/observation.json
./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md --emit /tmp/control-analysis.json
./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md --output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl
python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-observation.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers
python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/control-analysis.json /tmp/control-observation.json
python3 tests/consumers/observation_consumer.py --validate-schema --analysis /tmp/control-analysis.json /tmp/control-events.jsonl
- python3 tools/ci/verify_observation_stream.py /tmp/control-events.jsonl /tmp/control-observation.json
- |
set -eu
cp /tmp/control-analysis.json /tmp/analysis-stale.json
printf ' ' >> /tmp/analysis-stale.json
if python3 tests/consumers/observation_consumer.py --analysis /tmp/analysis-stale.json /tmp/control-events.jsonl; then
echo "stale Analysis was accepted" >&2
exit 1
fi
echo "stale Analysis rejected"
test: test:
image: rust:1.100-bookworm image: rust:1.100-bookworm
commands: commands:
@@ -15,14 +49,10 @@ steps:
- apt-get install -y --no-install-recommends nodejs - apt-get install -y --no-install-recommends nodejs
- cargo fmt --all -- --check - cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings - cargo clippy --workspace --all-targets -- -D warnings
# The provider CLI tests resolve a real provider worker next to the CLI # Provider CLI tests resolve a real provider worker next to the CLI
# binary. Build it once so the test harness does not need a nested build. # binary. Build it once so the test harness does not need a nested build.
- cargo build --locked -p marqdo-provider-worker - cargo build --locked -p marqdo-provider-worker
- cargo test --workspace --locked - cargo test --workspace --locked
# Execution Events v1 black-box contract: a released-binary-shaped run
# validated by the independent Python consumer and the public schema.
- cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl
- python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
- 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 -m unittest discover -s tools/ci -p "test_*.py" - python3 -m unittest discover -s tools/ci -p "test_*.py"
@@ -41,10 +71,10 @@ steps:
build: build:
image: rust:1.100-bookworm image: rust:1.100-bookworm
depends_on: [test, minimum-rust] depends_on: [test, minimum-rust, contract]
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 build-essential - apt-get install -y --no-install-recommends ca-certificates git openssl python3 python3-jsonschema build-essential
# Release archives must ship both binaries: the provider worker is the # Release archives must ship both binaries: the provider worker is the
# 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
+12 -4
View File
@@ -2,15 +2,15 @@
# Shared-node measurements may support an explicitly approved RC WARN. # Shared-node measurements may support an explicitly approved RC WARN.
when: when:
event: [manual] event: [manual]
branch: [master] branch: [master, "release/*"]
steps: steps:
measure: measure:
image: rust:1.100-bookworm image: rust:1.100-bookworm
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git build-essential - apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
- cargo build --release --locked -p marqdo-cli - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- | - |
set -eu set -eu
baseline_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854 baseline_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854
@@ -21,6 +21,14 @@ steps:
trap 'git worktree remove --force "$perf_dir/beta"; rm -rf "$perf_dir"' EXIT trap 'git worktree remove --force "$perf_dir/beta"; rm -rf "$perf_dir"' EXIT
(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)"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
tar -xzf "$archive" -C "$perf_dir"
candidate="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu"
test "$(cat "$candidate/SOURCE_SHA")" = "$CI_COMMIT_SHA"
allowed="$(awk '/^Cpus_allowed_list:/ {print $2}' /proc/self/status)" allowed="$(awk '/^Cpus_allowed_list:/ {print $2}' /proc/self/status)"
cpu_list="${MARQDO_PERF_CPU_LIST:-$(printf '%s' "$allowed" | cut -d, -f1 | cut -d- -f1)}" cpu_list="${MARQDO_PERF_CPU_LIST:-$(printf '%s' "$allowed" | cut -d, -f1 | cut -d- -f1)}"
echo "G4_NODE host=$(uname -n) kernel=$(uname -r) arch=$(uname -m) allowed_cpus=$allowed pin=$cpu_list" echo "G4_NODE host=$(uname -n) kernel=$(uname -r) arch=$(uname -m) allowed_cpus=$allowed pin=$cpu_list"
@@ -29,7 +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 --warmups 5 --samples 20 \ python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --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'
+12 -1
View File
@@ -3,7 +3,7 @@
**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/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.
For next-phase work, the authoritative release policy for the current For next-phase work, the authoritative release policy for the current
`3.0.0-beta.1` 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). `docs/STABLE_RELEASE_IMPLEMENTATION.md`
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable (stable gates G-A/G-B/G-C) is historical roadmap input for the later stable
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md` release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
@@ -34,6 +34,17 @@ correctness and release evidence before expanding the surface.
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates. 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`.
## Pre-stable protocol changes
Read [ADR-0068](docs/adr/0068-single-current-public-contracts.md) and the
[single-contract convergence policy](docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md)
before changing a public boundary. Keep one current specification, producer and validator per
boundary. Replace retired paths in the same integration, reject unsupported
formats explicitly, and update independent consumers and release smoke tests.
Keep old formats in Git history. Preserve authority, attribution and resource
limits during refactors. Confirm cross-repository and release evidence before
closing a protocol replacement issue.
## Development workflow ## Development workflow
1. Identify the affected rule and cite RFC-LANG-0002 / `spec/mapping.md` (or, for architecture-only changes, the relevant `docs/DEVELOPMENT_BLUEPRINT.md` section). 1. Identify the affected rule and cite RFC-LANG-0002 / `spec/mapping.md` (or, for architecture-only changes, the relevant `docs/DEVELOPMENT_BLUEPRINT.md` section).
+135 -14
View File
@@ -1,22 +1,143 @@
# Changelog # Changelog
All notable changes to the Marqdo CLI workspace. Product version All notable changes to the Marqdo CLI workspace. Published prereleases:
`3.0.0-beta.1` was tagged on 2026-11-22 at source `3.0.0-beta.1` (2026-11-22, source
`2c7c4f31e7a388d3fcfa717a77067e696ed13854` `2c7c4f31e7a388d3fcfa717a77067e696ed13854`),
([release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1)); `3.0.0-rc.1` (source `f7a5a7b0163bf5229ed09adfffd892f9899e6667`) and
the next section collects post-beta `3.0.0-rc.2` (source `9149ee40a48fcda692c5c112f66c465487d13dfb`); the next
changes. Protocol versions (Analysis v2, Trace v2, Tool v1, Plugin ABI v1, section collects changes for the current `3.0.0-rc.3` candidate. Current
Foreign wire v1, Provider manifest v2, lock v4) and independent package protocol contracts are Analysis v3, Observation v1, CLI Tool revision 1,
versions (including the bundled stdlib `0.1.0`) are versioned separately and Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4; independent
do not follow the product version. Dates use ISO 8601. package versions (including the bundled stdlib `0.1.0`) are versioned
separately and do not follow the product version. Dates use ISO 8601.
Older sections are release records: a retired option or spec they name is
available at its tagged commit, not in the current tree.
## 3.0.0-rc.1 (candidate) ## 3.0.0-rc.3 (candidate)
- The Rust workspace, CLI version output and protocol producers report - The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.1`. The locked workspace requires Rust 1.89. `3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux
x86_64 on glibc 2.39.
- **Licensing:** the workspace is now Apache-2.0 only. `Cargo.toml` declares
`license = "Apache-2.0"` and the dual-licensed `LICENSE-MIT` file is removed;
the archive ships `LICENSE-APACHE` only. This is a repository-licensing
change, not a protocol or language change.
### Single current public contracts — issue #8 (breaking)
Executed policy: [ADR-0068](docs/adr/0068-single-current-public-contracts.md) and
[the protocol convergence policy](docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md).
This is a pre-stable replacement, not a compatibility release. Retired formats
are rejected; there is no legacy reader, alias, fallback, negotiation or
automatic migration.
- **Analysis has one writer for every project.** `check --emit` always emits
`marqdo.analysis` `schema_version: 3`, including projects without
`break`/`continue`. The content-driven v2/v3 selector is deleted, and the
retired `spec/analysis-v*.md` documents and schemas are removed from the
current tree. Consumers no longer need to branch on the project content.
- **Trace v2 and Execution Events v1 became one Observation contract.**
`run`/`call` emit one `marqdo.observation` `schema_version: 1` event sequence
per execution. `--output jsonl` streams those events, `--output json` and
`--observation-file PATH` publish an atomic snapshot of the same events from
the same execution. `run_id`, `seq`, frame identity, terminal semantics,
capture budgets and privacy rules are defined once in
[`spec/observation.md`](spec/observation.md). The retired `--json`,
`--trace-file`, `--event-stream` and `--trace` options are rejected, and the
in-process effect-trace document is gone: effects are `effect` observation
events.
- **CLI Tool requirements are single exact values.** `tool.json` declares
`requires.api_revision` (required) plus optional exact `analysis` and
`observation` integers. Version arrays and intersection negotiation are
removed. Retired manifests and records are rejected with a remove/reinstall
instruction and are never rewritten.
- **Plugin and resource-provider workers share one transport.** Framing,
bounded reads, deadlines, dead-worker quarantine and teardown live in
`marqdo-worker-ipc` ([`spec/worker-ipc.md`](spec/worker-ipc.md)); the invoke
vocabulary, grants, kind rights and error codes stay with each boundary.
- **Extension descriptors and lock keep their current identifiers.** There is
no version renumbering without a shape change: plugin `abi: ^1.0`, provider
`schema_version: 2`, kernel `wire_version: 1` and lock v4 stay current.
Retired provider/kernel/plugin revisions and lock v1–v3 are rejected with an
explicit regeneration/reinstall instruction; no migrator runs.
- **`spec/` now contains only current contracts.** Retired specifications are
available in Git history and tagged archives. ADRs covering retired public
contracts carry a Historical header. `docs/developers/analysis-trace.md` was
replaced by `analysis-observation.md`.
- **CI is a protocol consumer.** A fast `contract` lane builds both shipped
binaries and drives the real CLI through the independent Python consumers,
while the full `test` lane runs fmt/clippy/tests/docs/architecture gates.
`tools/ci/verify_observation_stream.py` (checked in, unit-tested) asserts
that one run's JSONL stream and JSON snapshot are the same event sequence.
### Review fixes after the first candidate build
- A rejected strict observation destination no longer emits a partial JSONL
stream: `--output jsonl` and `--observation-file` are refused before any
session opens.
- `check --emit` removes a previous Analysis artifact when the project cannot
be loaded, not only when it has compile errors.
- Filesystem resource requests report their concrete effect operation
(`fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`,
`fs.rename`) instead of a generic `resource.request`.
- The shared worker transport preserves the plugin ABI frame codes
`worker_frame_too_large` and `worker_encode_failed`.
- The event and snapshot schemas agree on the capture `level` enum.
- The G4 workload catalogue uses `run`/`call --output json` and pins the
current snapshot in its correctness digest; the previously retired `--json`
flag made every non-check workload fail correctness verification.
Migration for consumers:
1. Re-run `marqdo check --emit` and read `marqdo.analysis` without a version
branch; verify `project`, module ids and source digests.
2. Replace Trace/Event readers with an Observation reader; stream with
`--output jsonl` and/or read `--observation-file`. Verify `run_id`, `seq`,
source binding and the single terminal event.
3. Rewrite `tool.json` to the exact current requirements, rebuild the tool and
`marqdo tool remove` + reinstall. Old registrations are not migrated.
4. Rebuild/reinstall plugins, providers and kernels from their current
descriptors; re-run `marqdo lock` instead of reusing a retired lock.
### Verification
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D
warnings`, `cargo test --workspace --locked` pass on the candidate tree.
- Independent consumers (`tests/consumers/analysis_consumer.py`,
`observation_consumer.py`, `validate_protocols.py`) validate real CLI output;
`tests/consumers/observation_consumer.py` checks that stream and snapshot are
the same event sequence.
- `crates/cli/tests/architecture_boundaries.rs` forbids a second worker
framing implementation and pins the workspace layer list;
`docs_consistency` keeps one current overview and resolving links.
- Same-SHA Linux CI, the deterministic archive build, the from-archive smoke,
the cold-install container check and the frozen external conformance suite
(fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`) are recorded in the
per-gate evidence bound to the release SHA; see
[`docs/releasing.md`](docs/releasing.md) and [`docs/STATUS.md`](docs/STATUS.md).
- The RC strict-L1 disposable-VM lane and the G4 shared-node comparison
(maintainer-approved `WARN` for this named RC, with the environment and
limits recorded in the release notes) complete the RC gate set; the archive
sha256 for the tagged SHA is published with the release assets.
## 3.0.0-rc.2 (candidate)
- The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.2`. The locked workspace requires Rust 1.89.
- The candidate targets Linux x86_64 with glibc. See - The candidate targets Linux x86_64 with glibc. See
[release gates](docs/releasing.md) for the evidence required for publication. [release gates](docs/releasing.md) for the evidence required for publication.
### Structured control flow (RFC-CTRL-0005)
- Added ordered `else if` arms and nearest-loop `break` and `continue`.
Bare keyword carriers take the control meaning. Calls, bindings and
identifiers within expressions retain their existing syntax.
- Inferred signatures now use reachable reads and merge assignments on
reachable control exits. A parameter inferred only from unreachable
statements may disappear.
- Analysis v3 represents loop transfers. Projects without transfers still emit
v2. Trace v2 and Execution Events v1 report the two explicit control events.
### Core/extension boundary — RFC-EXT-0003 (issue #3) ### Core/extension boundary — RFC-EXT-0003 (issue #3)
Executed evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md). Executed evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -68,7 +189,7 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
metadata-only `@namespace.identifier` annotation layer is specified as metadata-only `@namespace.identifier` annotation layer is specified as
**Proposed** with target `3.1.x`. The current parser still rejects any other **Proposed** with target `3.1.x`. The current parser still rejects any other
leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code, leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code,
manifest loader, Analysis v3 or sidecar exists in this build. Contracts: manifest loader or heading annotations projection exists in this build. Contracts:
ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md). ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md).
- **Foreign F-B removal is deferred (H-02).** The permission-gated one-shot - **Foreign F-B removal is deferred (H-02).** The permission-gated one-shot
`foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled `foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled
@@ -98,8 +219,8 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
- New public contract - New public contract
[`spec/execution-events-v1.md`](spec/execution-events-v1.md) and [`spec/execution-events-v1.md`](spec/execution-events-v1.md) and
[`spec/schemas/execution-events-v1.schema.json`](spec/schemas/execution-events-v1.schema.json), [`spec/schemas/execution-events-v1.schema.json`](spec/schemas/execution-events-v1.schema.json),
with fixtures and an independent Python consumer. Analysis v2 and Trace v2 with fixtures and an independent Python consumer. Trace v2 retains its
schemas/versions are unchanged. public event envelope.
- Limitations: memory metadata events (OBS-06/P2), a bidirectional debug - Limitations: memory metadata events (OBS-06/P2), a bidirectional debug
protocol and SSE/HTTP remain out of scope; strict mode refuses event mode protocol and SSE/HTTP remain out of scope; strict mode refuses event mode
explicitly. explicitly.
+52 -40
View File
@@ -1,17 +1,17 @@
# Compatibility and support matrix # Compatibility and support matrix
Snapshot: product version **`3.0.0-beta.1`** (prerelease), branch `master`, Snapshot: candidate product version **`3.0.0-rc.3`** (prerelease). The last
tagged `v3.0.0-beta.1` at source SHA `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. This file records what was actually verified and published prerelease is `3.0.0-rc.2` at source SHA
separates it from what is only implemented. The supported release platform is `9149ee40a48fcda692c5c112f66c465487d13dfb`. This file records what was
**Linux x86_64 (glibc)**; everything else is experimental and not claimed for actually verified and separates it from what is only implemented. The
this beta. Executed status and same-SHA evidence are in supported release platform is **Linux x86_64 (glibc 2.39)**; everything else is
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under experimental and not claimed for this prerelease. Executed status and
[`docs/evidence/extension/`](docs/evidence/extension/README.md). SHA-bound evidence are in [`docs/STATUS.md`](docs/STATUS.md) and under
[`docs/evidence/`](docs/evidence/extension/README.md).
The `3.0.0-rc.1` candidate targets Linux x86_64 on glibc 2.39 and The `3.0.0-rc.3` candidate includes the post-beta protocol convergence below.
includes the post-beta changes below. See the See the [RC acceptance procedure](docs/releasing.md). The platform evidence
[RC acceptance procedure](docs/releasing.md). The platform evidence table table records the beta, rc.1/rc.2 and candidate verification.
records the beta and subsequent development verification.
## Language source syntax (breaking change) ## Language source syntax (breaking change)
@@ -51,7 +51,7 @@ Consequences for compatibility:
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003) ## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
These landed after the beta tag and **are included in the `3.0.0-rc.1` candidate**; they are These landed after the beta tag and **are included in the `3.0.0-rc.3` candidate**; they are
intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md). evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -62,24 +62,39 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid
| Release archive must ship the verified `stdlib/` | **Delivery requirement.** Archive contains `stdlib.json` + all modules and `RELEASE_INFO.json` carries its name/version/tree/alias digests/count/files. Removing or tampering with it fails closed; release builds do not fall back to the build-machine source path. | | Release archive must ship the verified `stdlib/` | **Delivery requirement.** Archive contains `stdlib.json` + all modules and `RELEASE_INFO.json` carries its name/version/tree/alias digests/count/files. Removing or tampering with it fails closed; release builds do not fall back to the build-machine source path. |
| Core resource kinds enforced on every registration path (H-04) | Provider name or declared kind equal to `stdio/file/tcp/tls/udp/tcp-listener` is rejected with `ext.manifest_invalid` (CLI) / `ResourceUnsupported` (host) before registration. No provider may shadow a core kind. | | Core resource kinds enforced on every registration path (H-04) | Provider name or declared kind equal to `stdio/file/tcp/tls/udp/tcp-listener` is rejected with `ext.manifest_invalid` (CLI) / `ResourceUnsupported` (host) before registration. No provider may shadow a core kind. |
| `resource_request` operation ownership (H-03) | New domain/business operations are forbidden in the core: ship a pure `.mq.md` package, ABI export or Provider. The exact reviewed allowlist is pinned by `architecture_boundaries.rs`; see `docs/architecture/resource-operations.md`. | | `resource_request` operation ownership (H-03) | New domain/business operations are forbidden in the core: ship a pure `.mq.md` package, ABI export or Provider. The exact reviewed allowlist is pinned by `architecture_boundaries.rs`; see `docs/architecture/resource-operations.md`. |
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`, Analysis v3 or sidecar exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. | | Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown` or heading annotations projection exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
| Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. | | Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. |
## Structured control flow (RFC-CTRL-0005, RC.2 and later)
The RC.2 and RC.3 candidates reserve `break` and `continue` only as complete
payloads. An existing standalone identifier read can be written as
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within
expressions retain their meaning. Two separate carriers containing `else` and
`if` still require two closing `end` statements.
Parameter inference ignores reads after a definite transfer. When upgrading
a caller that passed an argument inferred solely from unreachable code,
remove the argument or keep it through an explicit `params(...)` declaration.
The current Analysis contract is `schema_version: 3` for every project, so an
external tool that still reads Analysis v2 must be updated before it can
consume this candidate's `check --emit` output.
## Public protocol versions ## Public protocol versions
| Surface | Version | Compatibility rule | | Surface | Version | Compatibility rule |
|---|---|---| |---|---|---|
| Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. | | Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. |
| Language / CLI | `3.0.0-rc.1` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. | | Language / CLI | `3.0.0-rc.3` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. |
| `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). | | `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). |
| Analysis | v2 | Consumers reject unknown majors; incompatible field changes require v3. | | Analysis | v3 | One writer and one current major for every project, including projects without loop transfers. Consumers reject other majors; the retired v2 selector, schema and documents are gone (ADR-0068). |
| Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. | | Observation | v1 | One `run_id`/`seq` event sequence per execution, delivered as JSONL, JSON snapshot or file snapshot from the same run. Values are opt-in and bounded; consumers reject other identifiers (spec/observation.md). |
| Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). | | CLI Tool | revision 1 | `requires.api_revision` is one exact integer; `analysis`/`observation` are optional exact integers. Version arrays and intersection negotiation are rejected with a reinstall instruction. |
| CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. |
| Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. | | Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. |
| Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). | | Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). |
| Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). | | Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). |
| Analysis `calls[].state/target` | v2 (projection) | Now projected from the unique binding; official stdlib aliases appear as `function`. Schema/version unchanged; private binding table not serialized. | | Analysis `calls[].state/target` | v3 projection | Projected from the unique binding; official stdlib aliases appear as `function`. The private binding table is not serialized. |
| Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). | | Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). |
| Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. | | Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. |
@@ -103,9 +118,8 @@ portable/tested locally but the native platform lane has not run here;
| Resource Provider v2 CLI (`--provider`/`--allow-provider`, worker helper) | PASS (linux/x86_64; real C sensor + helper) | **FAIL-CLOSED** (`ext.platform_unsupported`) | **UNSUPPORTED** | | Resource Provider v2 CLI (`--provider`/`--allow-provider`, worker helper) | PASS (linux/x86_64; real C sensor + helper) | **FAIL-CLOSED** (`ext.platform_unsupported`) | **UNSUPPORTED** |
| Capability handler registry (`fs.read` handler, audit, unavailable) | PASS | UNVERIFIED | UNVERIFIED | | Capability handler registry (`fs.read` handler, audit, unavailable) | PASS | UNVERIFIED | UNVERIFIED |
| External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (`--release` binary sha256 `28e3776d…`, fixture repo `e4b7352c…`; see `docs/evidence/extension/6a7bb983.../manifest.json`) | UNVERIFIED | UNVERIFIED | | External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (`--release` binary sha256 `28e3776d…`, fixture repo `e4b7352c…`; see `docs/evidence/extension/6a7bb983.../manifest.json`) | UNVERIFIED | UNVERIFIED |
| Analysis v2 / Trace v2 + Python consumers | PASS | UNVERIFIED | UNVERIFIED | | Analysis v3 + Observation v1 + Python consumers | PASS (same-SHA CI contract lane and archive smoke; independent consumers) | UNVERIFIED | UNVERIFIED |
| Execution Events v1 (`--event-stream jsonl`, P0/P1) | PASS locally (14 CLI contract tests + 8 host + 4 runtime; independent Python schema consumer); post-beta, not in the tagged archive | UNVERIFIED | UNVERIFIED | | CLI Tool revision 1 + independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Tool Protocol v1 + 3 independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** | | Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** |
| Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) | | Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) |
| Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED | | Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED |
@@ -133,14 +147,15 @@ the Windows C ABI/provider paths remain fail-closed.
rlimits and wall-clock/output supervision; the child verifies `PID 1`, rlimits and wall-clock/output supervision; the child verifies `PID 1`,
`NoNewPrivs`, `CapEff=0`, a non-initial uid map and no non-loopback network. `NoNewPrivs`, `CapEff=0`, a non-initial uid map and no non-loopback network.
- Refused before launch: `--allow-read`, `--allow-write`, `--allow-foreign`, - Refused before launch: `--allow-read`, `--allow-write`, `--allow-foreign`,
`--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`, `--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`;
`--trace-file`. `--output jsonl` and `--observation-file` are refused because the supervisor
owns the output channel.
- Strict L2 (letting Worker/Foreign/native plugin run inside the sandbox) is - Strict L2 (letting Worker/Foreign/native plugin run inside the sandbox) is
not implemented and must not be inferred from L1 passing. not implemented and must not be inferred from L1 passing.
## Minimum environment ## Minimum environment
- Rust 1.82+ (verified with 1.100.0). - Rust 1.89+ (locked minimum; verified with 1.100.0).
- Linux/macOS: a C compiler for Native ABI fixtures; Python/Node only for - Linux/macOS: a C compiler for Native ABI fixtures; Python/Node only for
Foreign kernels; `git` for Git dependencies. Foreign kernels; `git` for Git dependencies.
- `strict` additionally requires Bubblewrap and a kernel/environment that - `strict` additionally requires Bubblewrap and a kernel/environment that
@@ -159,7 +174,7 @@ the Windows C ABI/provider paths remain fail-closed.
* The external conformance suite is a mandatory **additional** release gate * The external conformance suite is a mandatory **additional** release gate
(`docs/releasing.md` §7); it does not replace G3/G4/native lanes. (`docs/releasing.md` §7); it does not replace G3/G4/native lanes.
## Explicitly unsupported in this beta ## Explicitly unsupported in this prerelease
- Pre-RFC `.mq.md` source syntax (Strong-execute / Emph-return / ordered-list - Pre-RFC `.mq.md` source syntax (Strong-execute / Emph-return / ordered-list
branch / bullet-list loop / block-quote call / first code-span signature). branch / bullet-list loop / block-quote call / first code-span signature).
@@ -174,20 +189,17 @@ the Windows C ABI/provider paths remain fail-closed.
sessions, and general-purpose CAS. The three `sample-*` tools are test sessions, and general-purpose CAS. The three `sample-*` tools are test
fixtures for the generic Tool protocol, not product features. fixtures for the generic Tool protocol, not product features.
- Tagged Windows/macOS release archives: only the Linux x86_64 archive is - Tagged Windows/macOS release archives: only the Linux x86_64 archive is
produced for `3.0.0-beta.1`. macOS/Windows native artifacts are not claimed; produced for the 3.0 prerelease line. macOS/Windows native artifacts are not
the Windows lane is a Linux-hosted compile gate only. claimed; the Windows lane is a Linux-hosted compile gate only.
## Release decision ## Release decision
**`3.0.0-beta.1` prerelease — approved as a Linux x86_64 beta with explicitly **`3.0.0-rc.3` prerelease candidate — Linux x86_64 only.** The RC profile in
recorded gaps.** The beta profile in [`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3 is
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3.1 used, not the stable profile: Linux is the only supported platform,
was used, not the stable profile: Linux is the only supported platform, macOS/Windows are declared UNSUPPORTED for this scope, strict L1 requires
macOS/Windows are declared unsupported/experimental, G4 is a Beta-only `WARN` same-SHA disposable-VM evidence and G4 performance is recorded as a
on the fixed Woodpecker agent, and strict policy and frozen-binary conformance maintainer-approved shared-node `WARN` for this named RC. The aggregate decision
are recorded with same-SHA evidence in [`docs/STATUS.md`](docs/STATUS.md) and and per-gate evidence are bound to the candidate SHA in
[`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json) [`docs/STATUS.md`](docs/STATUS.md) and the release assets. A prerelease does not
(`BETA_RELEASE_CANDIDATE`). Release: imply stable `3.0.0` or LTS; the stable gate remains stricter and separate.
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. Beta status
does not imply stable `3.0.0` or LTS; the stable gate remains stricter and
separate.
Generated
+27 -16
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "adler2" name = "adler2"
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "marqdo-cli" name = "marqdo-cli"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"clap", "clap",
"hex", "hex",
@@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-expression" name = "marqdo-expression"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
@@ -449,7 +449,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-foreign" name = "marqdo-foreign"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"hex", "hex",
"libc", "libc",
@@ -465,7 +465,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-frontend" name = "marqdo-frontend"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-ir", "marqdo-ir",
@@ -480,7 +480,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-host" name = "marqdo-host"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"flate2", "flate2",
"getrandom 0.4.3", "getrandom 0.4.3",
@@ -491,6 +491,7 @@ dependencies = [
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-span", "marqdo-span",
"marqdo-value", "marqdo-value",
"marqdo-worker-ipc",
"rcgen", "rcgen",
"regex", "regex",
"rustls", "rustls",
@@ -504,7 +505,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-ir" name = "marqdo-ir"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-span", "marqdo-span",
@@ -514,7 +515,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-markdown" name = "marqdo-markdown"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"comrak", "comrak",
"marqdo-span", "marqdo-span",
@@ -525,7 +526,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-package" name = "marqdo-package"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"hex", "hex",
"semver", "semver",
@@ -539,12 +540,13 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-abi" name = "marqdo-plugin-abi"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"hex", "hex",
"libloading", "libloading",
"marqdo-span", "marqdo-span",
"marqdo-value", "marqdo-value",
"marqdo-worker-ipc",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
@@ -554,7 +556,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-sdk" name = "marqdo-plugin-sdk"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-plugin-abi", "marqdo-plugin-abi",
"serde", "serde",
@@ -563,19 +565,20 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-provider-worker" name = "marqdo-provider-worker"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"libloading", "libloading",
"marqdo-host", "marqdo-host",
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-value", "marqdo-value",
"marqdo-worker-ipc",
"serde_json", "serde_json",
"tempfile", "tempfile",
] ]
[[package]] [[package]]
name = "marqdo-runtime" name = "marqdo-runtime"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-frontend", "marqdo-frontend",
@@ -594,7 +597,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-sandbox" name = "marqdo-sandbox"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"libc", "libc",
"serde", "serde",
@@ -602,14 +605,14 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-span" name = "marqdo-span"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"serde", "serde",
] ]
[[package]] [[package]]
name = "marqdo-value" name = "marqdo-value"
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
@@ -618,6 +621,14 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "marqdo-worker-ipc"
version = "3.0.0-rc.3"
dependencies = [
"serde_json",
"thiserror",
]
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.8.3" version = "2.8.3"
+4 -2
View File
@@ -10,6 +10,7 @@ members = [
"crates/marqdo-foreign", "crates/marqdo-foreign",
"crates/marqdo-plugin-abi", "crates/marqdo-plugin-abi",
"crates/marqdo-provider-worker", "crates/marqdo-provider-worker",
"crates/marqdo-worker-ipc",
"crates/marqdo-plugin-sdk", "crates/marqdo-plugin-sdk",
"crates/marqdo-host", "crates/marqdo-host",
"crates/marqdo-runtime", "crates/marqdo-runtime",
@@ -19,10 +20,10 @@ members = [
] ]
[workspace.package] [workspace.package]
version = "3.0.0-rc.1" version = "3.0.0-rc.3"
edition = "2021" edition = "2021"
rust-version = "1.89" rust-version = "1.89"
license = "MIT OR Apache-2.0" license = "Apache-2.0"
repository = "https://github.com/cflmy/marqdo-cli" repository = "https://github.com/cflmy/marqdo-cli"
authors = ["Marqdo contributors"] authors = ["Marqdo contributors"]
@@ -35,6 +36,7 @@ marqdo-ir = { path = "crates/marqdo-ir" }
marqdo-frontend = { path = "crates/marqdo-frontend" } marqdo-frontend = { path = "crates/marqdo-frontend" }
marqdo-foreign = { path = "crates/marqdo-foreign" } 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-host = { path = "crates/marqdo-host" } marqdo-host = { path = "crates/marqdo-host" }
marqdo-runtime = { path = "crates/marqdo-runtime" } marqdo-runtime = { path = "crates/marqdo-runtime" }
marqdo-package = { path = "crates/marqdo-package" } marqdo-package = { path = "crates/marqdo-package" }
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Marqdo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21 -19
View File
@@ -10,7 +10,7 @@ The official implementation is a Rust workspace; Python/Node are optional
foreign kernels, never the compiler target. foreign kernels, never the compiler target.
This repository is the new, independent Marqdo toolchain, now at product This repository is the new, independent Marqdo toolchain, now at product
version **`3.0.0-rc.1`** in this checkout. It is **not** a compatibility rewrite of version **`3.0.0-rc.3`** in this checkout. It is **not** a compatibility rewrite of
`cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not `cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not
claimed to work here. See [docs/developers/](docs/developers/README.md) for the claimed to work here. See [docs/developers/](docs/developers/README.md) for the
third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta
@@ -31,7 +31,7 @@ release policy.
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1), > [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1),
> source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the > source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the
> C ABI plugin/provider paths are Linux-only in this beta. The language > C ABI plugin/provider paths are Linux-only in this beta. The language
> (RFC-LANG-0002), lock v4, Analysis v2, Trace v2, Tool v1, Plugin ABI v1 > (RFC-LANG-0002), lock v4, Analysis, Observation, CLI Tool, Plugin ABI v1
> (native + worker), pinned Foreign providers and Resource Provider v2 are > (native + worker), pinned Foreign providers and Resource Provider v2 are
> implemented and covered by tests. **`strict` OS isolation is Linux-only and > implemented and covered by tests. **`strict` OS isolation is Linux-only and
> probe-gated**; unsupported hosts must fail closed, and strict L2 > probe-gated**; unsupported hosts must fail closed, and strict L2
@@ -67,7 +67,7 @@ marqdo init demo
cd demo cd demo
marqdo check index.mq.md marqdo check index.mq.md
marqdo run index.mq.md # executes ## @exec main marqdo run index.mq.md # executes ## @exec main
marqdo run index.mq.md --event-stream jsonl # live Execution Events v1 NDJSON marqdo run index.mq.md --output jsonl # live Observation JSON Lines
marqdo inspect index.mq.md --ast marqdo inspect index.mq.md --ast
marqdo inspect index.mq.md --signature marqdo inspect index.mq.md --signature
marqdo call index.mq.md main marqdo call index.mq.md main
@@ -114,10 +114,11 @@ executes anything. The Markdown profile is unchanged by the semantic rewrite.
* **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`, * **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`,
`*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans `*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans
for expressions containing `*` or `**`. for expressions containing `*` or `**`.
* **Statements are explicit.** `if <Bool>`, `else`, `while <Bool>`, `end`, * **Statements are explicit.** An `if` may have multiple `else if` arms and
`return <expr>`, `params(n: Int)`, assignment, or an expression call. Each a final `else`. `while` repeats while its condition is true. `break` exits the
carrier holds exactly one statement; every `if`/`while` is closed by `end` nearest loop and `continue` rechecks its condition. Each carrier holds one
inside the same heading body. statement and every `if` or `while` closes with `end` in the same heading
body. See the [control-flow example](examples/control-flow.mq.md).
* **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the * **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the
document. `> print(1)` is prose; `> **print(1)**` contains a call. document. `> print(1)` is prose; `> **print(1)**` contains a call.
* **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is * **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is
@@ -214,7 +215,7 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
`lock`, strict `sync --locked` with atomic `.marqdo/env` materialization. `lock`, strict `sync --locked` with atomic `.marqdo/env` materialization.
`run`/`call`/`check` never fetch or rewrite the lock. `run`/`call`/`check` never fetch or rewrite the lock.
* **P4 security core** — capability-checked host operations, project-relative * **P4 security core** — capability-checked host operations, project-relative
FS globs with traversal rejection, budgets, effect trace, `pure`/`project` FS globs with traversal rejection, budgets, Observation effect events, `pure`/`project`
modes, and **Linux `strict` mode** using Bubblewrap namespaces, no-new-privs, modes, and **Linux `strict` mode** using Bubblewrap namespaces, no-new-privs,
capability dropping, rlimits, a wall-clock supervisor and child capability dropping, rlimits, a wall-clock supervisor and child
self-verification (ADR-0021). It is probe-gated and verified in a disposable self-verification (ADR-0021). It is probe-gated and verified in a disposable
@@ -231,11 +232,10 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
target-triple + sha256 artifact verification, native and isolated worker target-triple + sha256 artifact verification, native and isolated worker
transports, brokered `fs.read`, and explicitly trusted in-process calls transports, brokered `fs.read`, and explicitly trusted in-process calls
(`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox. (`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox.
* **Public protocols** — Analysis v2 and Trace v2 with JSON Schemas and * **Public protocols** — [Analysis](spec/analysis.md) projects static facts.
independent Python consumers; Tool Protocol v1 with arbitrary command names, [Observation](spec/observation.md) delivers the same run as live JSONL or
SemVer negotiation and whole-bundle digest verification; **Execution Events a JSON snapshot. [CLI Tool](spec/cli-tool.md) installs independently built
v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and commands with exact protocol requirements and verifies their entire bundle.
explicitly selected, bounded values (post-beta addition, ADR-0059).
Run everything: Run everything:
@@ -251,7 +251,7 @@ cargo clippy --workspace --all-targets -- -D warnings
* **Strict is Linux-only and L1-only.** `--mode strict` enables the * **Strict is Linux-only and L1-only.** `--mode strict` enables the
Bubblewrap supervisor only when its runtime probe passes; otherwise it exits Bubblewrap supervisor only when its runtime probe passes; otherwise it exits
1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels, 1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels,
external grants and trace files (exit 2). Worker plugins provide external grants and live/file observation destinations (exit 2). Worker plugins provide
crash/address-space isolation, not an OS sandbox, and are not allowed in crash/address-space isolation, not an OS sandbox, and are not allowed in
strict. strict.
* **Native plugins run in-process** and require an explicit unsafe trust flag. * **Native plugins run in-process** and require an explicit unsafe trust flag.
@@ -327,7 +327,7 @@ tests/ conformance/negative corpus (see tests/README.md)
* [`docs/developers/README.md`](docs/developers/README.md) — third-party and * [`docs/developers/README.md`](docs/developers/README.md) — third-party and
integrator entry point (libraries, tools, plugins, kernels, providers, integrator entry point (libraries, tools, plugins, kernels, providers,
Analysis/Trace consumers, compatibility). Analysis/Trace consumers, compatibility).
* [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md) * [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md) — beta-era integration handbook (historical; current contracts are `spec/`)
— end-to-end third-party integration handbook. — end-to-end third-party integration handbook.
* [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md) * [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md)
— historical stable-release roadmap input (its own header marks it Proposed — historical stable-release roadmap input (its own header marks it Proposed
@@ -355,15 +355,16 @@ tests/ conformance/negative corpus (see tests/README.md)
* [`docs/adr/`](docs/adr/) — accepted decisions (crate graph, inert executables, * [`docs/adr/`](docs/adr/) — accepted decisions (crate graph, inert executables,
`ref` ambiguity, strict refusal, AST normalization, CLI contract, BigInt/wire, `ref` ambiguity, strict refusal, AST normalization, CLI contract, BigInt/wire,
package identity, callable resolution, plugin export routing, capability package identity, callable resolution, plugin export routing, capability
broker, kernel providers, generic CLI tools, plugin-handle authority, public Analysis/Trace v1). broker, kernel providers, generic CLI tools, plugin-handle authority, public contract replacement).
* Specs: [`markdown-profile.md`](spec/markdown-profile.md), * Specs: [`markdown-profile.md`](spec/markdown-profile.md),
[`mapping.md`](spec/mapping.md), [`expression.ebnf`](spec/expression.ebnf), [`mapping.md`](spec/mapping.md), [`expression.ebnf`](spec/expression.ebnf),
[`evaluation.md`](spec/evaluation.md), [`references.md`](spec/references.md), [`evaluation.md`](spec/evaluation.md), [`references.md`](spec/references.md),
[`value-wire.md`](spec/value-wire.md), [`security.md`](spec/security.md), [`value-wire.md`](spec/value-wire.md), [`security.md`](spec/security.md),
[`package-format.md`](spec/package-format.md), [`package-format.md`](spec/package-format.md),
[`plugin-abi.md`](spec/plugin-abi.md), [`math.md`](spec/math.md), [`plugin-abi.md`](spec/plugin-abi.md), [`math.md`](spec/math.md),
[`foreign.md`](spec/foreign.md), [`tool-v1.md`](spec/tool-v1.md), [`foreign.md`](spec/foreign.md), [`cli-tool.md`](spec/cli-tool.md),
[`analysis-v2.md`](spec/analysis-v2.md), [`trace-v2.md`](spec/trace-v2.md); [`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md),
[`worker-ipc.md`](spec/worker-ipc.md);
JSON Schemas in [`spec/schemas/`](spec/schemas/). JSON Schemas in [`spec/schemas/`](spec/schemas/).
* [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS` * [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS`
workflow. workflow.
@@ -373,6 +374,7 @@ tests/ conformance/negative corpus (see tests/README.md)
```bash ```bash
marqdo run examples/hello.mq.md marqdo run examples/hello.mq.md
marqdo call examples/control-flow.mq.md main
marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5 marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5
marqdo run examples/multi-module/index.mq.md marqdo run examples/multi-module/index.mq.md
marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node
@@ -430,7 +432,7 @@ marqdo run kernel/demo.mq.md \
marqdo run provider/demo.mq.md \ marqdo run provider/demo.mq.md \
--provider provider/build/provider.json --allow-provider demo.sensor --provider provider/build/provider.json --allow-provider demo.sensor
# 5. Independent CLI Tool consuming only public Analysis v2 # 5. Independent CLI Tool consuming public Analysis
marqdo tool install tool/tool.json marqdo tool install tool/tool.json
marqdo inspect-ext tool/demo.mq.md marqdo inspect-ext tool/demo.mq.md
``` ```
+1 -3
View File
@@ -28,10 +28,8 @@ walkdir = { workspace = true }
hex = { workspace = true } hex = { workspace = true }
sha2 = { workspace = true } sha2 = { workspace = true }
semver = { workspace = true } semver = { workspace = true }
tempfile = { workspace = true }
[[bin]] [[bin]]
name = "marqdo" name = "marqdo"
path = "src/main.rs" path = "src/main.rs"
[dev-dependencies]
tempfile = { workspace = true }
+9 -8
View File
@@ -1,4 +1,4 @@
//! Public Analysis v2 projection (spec/analysis-v2.md). //! Public Analysis projection (spec/analysis.md).
//! //!
//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node //! This is deliberately not a serde dump of `marqdo-ir`: the schema and node
//! kinds are the public contract, while internal Rust types may change. The //! kinds are the public contract, while internal Rust types may change. The
@@ -17,7 +17,7 @@ use crate::loader::LoadedProject;
/// Schema name and version. /// Schema name and version.
pub const SCHEMA: &str = "marqdo.analysis"; pub const SCHEMA: &str = "marqdo.analysis";
pub const SCHEMA_VERSION: u32 = 2; pub const SCHEMA_VERSION: u32 = 3;
/// Build the deterministic public projection. /// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value { pub fn build(project: &LoadedProject) -> Value {
@@ -76,11 +76,9 @@ fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
.map_err(|error| format!("cannot encode analysis: {error}")) .map_err(|error| format!("cannot encode analysis: {error}"))
} }
/// SHA-256 of the exact emitted Analysis bytes (Trace binds to this digest). /// SHA-256 of the exact emitted Analysis bytes.
pub fn digest(project: &LoadedProject) -> String { pub fn digest(project: &LoadedProject) -> Result<String, String> {
encode(project) encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes)))
.map(|bytes| sha256_hex(&bytes))
.unwrap_or_else(|_| sha256_hex(b""))
} }
/// Atomically write the projection. An error must not leave a stale success /// Atomically write the projection. An error must not leave a stale success
@@ -240,7 +238,7 @@ fn function_json(function: &Function) -> Value {
/// Project an assignment place. Local targets keep the v1 string form; the new /// Project an assignment place. Local targets keep the v1 string form; the new
/// index target is an additive object so existing consumers that compare the /// index target is an additive object so existing consumers that compare the
/// local `target` string are unaffected (Analysis v2, ADR-0022). /// local `target` string are unaffected (Analysis v3, ADR-0022).
fn place_json(place: &PlaceTarget) -> Value { fn place_json(place: &PlaceTarget) -> Value {
match place { match place {
PlaceTarget::Local { name, .. } => Value::String(name.clone()), PlaceTarget::Local { name, .. } => Value::String(name.clone()),
@@ -293,6 +291,8 @@ fn stmt_json(stmt: &Stmt) -> Value {
"body": body.iter().map(stmt_json).collect::<Vec<_>>(), "body": body.iter().map(stmt_json).collect::<Vec<_>>(),
"span": span_json(*span), "span": span_json(*span),
}), }),
Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}),
Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}),
Stmt::Return { value, span } => json!({ Stmt::Return { value, span } => json!({
"kind": "return", "kind": "return",
"value": expr_json(value), "value": expr_json(value),
@@ -523,6 +523,7 @@ fn collect_calls(
expr_calls(project, module, function, condition, calls); expr_calls(project, module, function, condition, calls);
collect_calls(project, module, function, body, calls); collect_calls(project, module, function, body, calls);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+46 -59
View File
@@ -29,6 +29,7 @@ pub use tool::{fmt, plugin_inspect};
use crate::args; use crate::args;
use crate::extension_descriptors::{self, StaticPluginSet}; use crate::extension_descriptors::{self, StaticPluginSet};
use crate::loader::{FileDiagnostic, LoadedProject}; use crate::loader::{FileDiagnostic, LoadedProject};
use crate::observation::ObservationSession;
use crate::output; use crate::output;
use crate::project_prepare::{self, PrepareOptions, PreparedProgram}; use crate::project_prepare::{self, PrepareOptions, PreparedProgram};
@@ -217,25 +218,6 @@ fn resolve_link(
} }
} }
/// Re-execute this CLI inside the strict Linux supervisor.
/// Emit one CLI error through the requested channel.
///
/// `--json` consumers require exactly one JSON document; human mode keeps the
/// conventional `error:` line on stderr. This helper is shared with the run
/// assembly so every strict control-plane failure follows one contract.
pub(super) fn emit_error(json: bool, command_name: &str, code: &str, message: &str) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": message,
"code": code,
}));
} else {
eprintln!("error: {message}");
}
}
/// Machine-readable routing decision for one captured strict execution. /// Machine-readable routing decision for one captured strict execution.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum StrictRoute { enum StrictRoute {
@@ -247,17 +229,15 @@ enum StrictRoute {
/// Classify a captured strict execution. /// Classify a captured strict execution.
/// ///
/// A strict child in `--json` mode must produce exactly one JSON document on /// Machine output is forwarded only if the child emitted one complete
/// stdout. Anything else is a control-plane failure: forwarding bwrap text or /// current Observation snapshot whose terminal agrees with the exit status.
/// an empty stream would break the CLI protocol (the GitHub-hosted Linux CI fn classify_strict_outcome(outcome: &StrictOutcome, snapshot: bool) -> StrictRoute {
/// failure that motivated this contract).
fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
let exit_code = outcome.exit_code.unwrap_or(1); let exit_code = outcome.exit_code.unwrap_or(1);
if !json { if !snapshot {
return StrictRoute::Forward { exit_code }; return StrictRoute::Forward { exit_code };
} }
if !outcome.stdout.is_empty() if outcome.exit_code.is_some()
&& serde_json::from_slice::<serde_json::Value>(&outcome.stdout).is_ok() && crate::observation::is_complete_snapshot(&outcome.stdout, exit_code)
{ {
return StrictRoute::Forward { exit_code }; return StrictRoute::Forward { exit_code };
} }
@@ -277,33 +257,39 @@ fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
} }
StrictRoute::Failure { StrictRoute::Failure {
code: "strict.child_invalid", code: "strict.child_invalid",
message: "the strict child did not produce exactly one JSON document; refusing to forward partial output" message: "the strict child did not produce exactly one JSON observation snapshot"
.to_string(), .to_string(),
} }
} }
/// Route one captured strict execution to stdout/stderr or one error document. /// Route captured child bytes through the selected output contract.
fn route_strict_outcome(outcome: StrictOutcome, json: bool, command_name: &str) -> i32 { fn route_strict_outcome(outcome: StrictOutcome, observation: Option<&ObservationSession>) -> i32 {
use std::io::Write; use std::io::Write;
match classify_strict_outcome(&outcome, json) { match classify_strict_outcome(&outcome, observation.is_some()) {
StrictRoute::Forward { exit_code } => { StrictRoute::Forward { exit_code } => {
let _ = std::io::stdout().write_all(&outcome.stdout); let mut stdout = std::io::stdout().lock();
let _ = std::io::stdout().flush(); if let Err(error) = stdout
.write_all(&outcome.stdout)
.and_then(|()| stdout.flush())
{
return run::transport_failure(&error.to_string());
}
let _ = std::io::stderr().write_all(&outcome.stderr); let _ = std::io::stderr().write_all(&outcome.stderr);
let _ = std::io::stderr().flush();
exit_code exit_code
} }
StrictRoute::Failure { code, message } => { StrictRoute::Failure { code, message } => {
output::print_json(&json!({ eprintln!("error[{code}]: {message}");
"command": command_name, if let Some(observation) = observation {
"success": false, let result = if code == "strict.namespace_failure" {
"error": message, observation.rejected("strict", code, &message)
"code": code, } else {
})); observation.incomplete()
match outcome.exit_code { };
Some(code) if code != 0 => code, if let Err(error) = result {
_ => 1, return run::transport_failure(&error);
}
} }
outcome.exit_code.filter(|code| *code != 0).unwrap_or(1)
} }
} }
} }
@@ -312,22 +298,26 @@ fn launch_strict_process(
project_root: &Path, project_root: &Path,
document: Option<&Path>, document: Option<&Path>,
settings: &SandboxSettings, settings: &SandboxSettings,
json: bool, observation: Option<&ObservationSession>,
command_name: &str,
) -> i32 { ) -> i32 {
let program = match std::env::current_exe() { let program = match std::env::current_exe() {
Ok(path) => path, Ok(path) => path,
Err(error) => { Err(error) => {
let message = format!("cannot locate the marqdo executable: {error}"); let message = format!("cannot locate the marqdo executable: {error}");
emit_error(json, command_name, "strict.launch_failed", &message); return run::fail(observation, "strict", "strict.launch_failed", &message, 1);
return 1;
} }
}; };
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect(); let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let output_limit = settings let program_output_limit = settings
.max_output .max_output
.unwrap_or(1024 * 1024) .unwrap_or(marqdo_host::DEFAULT_OUTPUT_BYTES);
.min(64 * 1024 * 1024); let output_limit = if observation.is_some() {
// Allow framing and runtime observations within the existing
// supervisor capture ceiling. The child's program budget still applies.
64 * 1024 * 1024
} else {
program_output_limit.min(64 * 1024 * 1024)
};
let timeout = Duration::from_secs(settings.timeout.unwrap_or(30)); let timeout = Duration::from_secs(settings.timeout.unwrap_or(30));
let stdlib_dir = crate::stdlib::StdlibBundle::discover() let stdlib_dir = crate::stdlib::StdlibBundle::discover()
.ok() .ok()
@@ -344,11 +334,8 @@ fn launch_strict_process(
stdlib_dir: stdlib_dir.as_deref(), stdlib_dir: stdlib_dir.as_deref(),
}; };
match marqdo_sandbox::launch_strict_capture(&command) { match marqdo_sandbox::launch_strict_capture(&command) {
Ok(outcome) => route_strict_outcome(outcome, json, command_name), Ok(outcome) => route_strict_outcome(outcome, observation),
Err(error) => { Err(error) => run::fail(observation, "strict", error.code(), &error.to_string(), 1),
emit_error(json, command_name, error.code(), &error.to_string());
1
}
} }
} }
@@ -431,7 +418,8 @@ fn runtime_location_json(
if let Some(located) = project.locate(module_id, span) { if let Some(located) = project.locate(module_id, span) {
location["line"] = json!(located.line); location["line"] = json!(located.line);
location["column"] = json!(located.column); location["column"] = json!(located.column);
location["file"] = json!(located.file.path.display().to_string()); // Attribution for a shareable snapshot is the project-relative
// path; an absolute host path is environment data, not contract.
location["relative_path"] = json!(located.file.module_id.relative_path); location["relative_path"] = json!(located.file.module_id.relative_path);
} }
} }
@@ -457,7 +445,6 @@ fn runtime_error_json(error: &RuntimeError, project: &LoadedProject) -> serde_js
"span": location["span"], "span": location["span"],
"line": location["line"], "line": location["line"],
"column": location["column"], "column": location["column"],
"file": location["file"],
"relative_path": location["relative_path"], "relative_path": location["relative_path"],
"frames": frames, "frames": frames,
}) })
@@ -544,7 +531,7 @@ mod tests {
#[test] #[test]
fn strict_json_success_is_forwarded_once() { fn strict_json_success_is_forwarded_once() {
let route = classify_strict_outcome( let route = classify_strict_outcome(
&outcome(Some(0), None, br#"{"command":"run","success":true}"#, b""), &outcome(Some(0), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"ok"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.completed","payload":{"status":"ok"}}]}"#, b""),
true, true,
); );
assert_eq!(route, StrictRoute::Forward { exit_code: 0 }); assert_eq!(route, StrictRoute::Forward { exit_code: 0 });
@@ -553,7 +540,7 @@ mod tests {
#[test] #[test]
fn strict_json_program_error_is_forwarded_unchanged() { fn strict_json_program_error_is_forwarded_unchanged() {
let route = classify_strict_outcome( let route = classify_strict_outcome(
&outcome(Some(2), None, br#"{"command":"run","success":false}"#, b""), &outcome(Some(2), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"error"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.failed","payload":{"status":"error"}}]}"#, b""),
true, true,
); );
assert_eq!(route, StrictRoute::Forward { exit_code: 2 }); assert_eq!(route, StrictRoute::Forward { exit_code: 2 });
+9 -1
View File
@@ -11,7 +11,15 @@ pub fn check(
) -> i32 { ) -> i32 {
let prepared = match prepare_project(file, json, plugins) { let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(code) => return code, Err(code) => {
// A failed check never leaves a success artifact behind: a consumer
// must not be able to bind `run` to a previous Analysis after the
// project stopped loading or compiling.
if let Some(path) = emit {
let _ = std::fs::remove_file(path);
}
return code;
}
}; };
let mut project = prepared.loaded; let mut project = prepared.loaded;
if refs { if refs {
+97 -301
View File
@@ -4,46 +4,59 @@
//! runtime helpers, but keeps the run session out of the command table. //! runtime helpers, but keeps the run session out of the command table.
use super::*; use super::*;
use crate::execution_events::{EventStream, ObservationOptions}; use crate::observation::{ObservationOptions, ObservationSession, OutputFormat};
use crate::provider_manifest; use crate::provider_manifest;
use marqdo_sandbox::StrictChildState; use marqdo_sandbox::StrictChildState;
pub fn execute( pub fn execute(
file: Option<&Path>, file: Option<&Path>,
function: Option<&str>, function: Option<&str>,
named_args: &[(String, Value)], named_args: Result<Vec<(String, Value)>, String>,
settings: &SandboxSettings, settings: &SandboxSettings,
json: bool, observation: &ObservationOptions,
trace: bool,
observation: Option<&ObservationOptions>,
) -> i32 { ) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" }; if !observation.enabled() && observation.has_capture_overrides() {
// Open the dedicated protocol channel before any project work so prepare eprintln!(
// and authorization failures can still produce `run.rejected`. "error: capture options require --output json, --output jsonl or --observation-file"
let events = match observation { );
Some(options) => match EventStream::open(options) { return 2;
Ok(stream) => Some(stream), }
Err(error) => { // Strict runs project code under the isolation supervisor, which owns
eprintln!("error[observe.transport_failed]: {error}"); // stdout. A live JSONL stream or a file destination would bypass that
return 1; // supervisor, so reject the destination before any session is opened: an
} // unsupported destination must never produce a partial stream.
}, if settings.mode == "strict"
None => None, && (observation.output == OutputFormat::Jsonl || observation.file.is_some())
}; {
let stream = events.as_ref(); return fail(
let prepared = if stream.is_some() { None,
let options = PrepareOptions { "strict",
plugins: settings.plugins.clone(), "strict.unsupported_grant",
}; "strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
match project_prepare::prepare(file, &options) { 2,
Ok(prepared) => prepared, );
Err(error) => return fail_prepare(stream, json, command_name, "prepare", &error), }
// Open before preparation so option, compile and authorization failures
// can still publish a rejection on the requested observation destination.
let events = if observation.enabled() {
match ObservationSession::open(observation) {
Ok(events) => Some(events),
Err(error) => return transport_failure(&error),
} }
} else { } else {
match prepare_project(file, json, &settings.plugins) { None
Ok(prepared) => prepared, };
Err(code) => return code, let stream = events.as_ref();
} let named_args = match named_args {
Ok(args) => args,
Err(message) => return fail(stream, "options", "cli.invalid_argument", &message, 2),
};
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
let prepared = match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, "prepare", &error),
}; };
let extension_sources = prepared.loaded.extension_sources.clone(); let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded; let project = prepared.loaded;
@@ -64,16 +77,8 @@ pub fn execute(
return transport_failure(&error); return transport_failure(&error);
} }
} }
if json { eprint!("{}", output::render_text(&project.diagnostics));
output::print_json(&json!({ eprintln!("error: refusing to run a project with compile errors");
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
return 1; return 1;
} }
let warnings: Vec<FileDiagnostic> = project let warnings: Vec<FileDiagnostic> = project
@@ -82,21 +87,13 @@ pub fn execute(
.filter(|item| !item.diagnostic.is_error()) .filter(|item| !item.diagnostic.is_error())
.cloned() .cloned()
.collect(); .collect();
if !json && !warnings.is_empty() { if !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings)); eprint!("{}", output::render_text(&warnings));
} }
let mode = match settings.sandbox_mode() { let mode = match settings.sandbox_mode() {
Ok(mode) => mode, Ok(mode) => mode,
Err(error) => { Err(error) => {
return fail( return fail(stream, "authorization", "cli.invalid_mode", &error, 2);
stream,
json,
command_name,
"authorization",
"cli.invalid_mode",
&error,
2,
);
} }
}; };
// A project-declared extension is activation, not authorization, but it is // A project-declared extension is activation, not authorization, but it is
@@ -115,15 +112,7 @@ pub fn execute(
marqdo_package::MANIFEST_FILE, marqdo_package::MANIFEST_FILE,
settings.mode settings.mode
); );
return fail( return fail(stream, "authorization", code, &message, 2);
stream,
json,
command_name,
"authorization",
code,
&message,
2,
);
} }
let mut kernel_paths = settings.kernels.clone(); let mut kernel_paths = settings.kernels.clone();
kernel_paths.extend( kernel_paths.extend(
@@ -144,28 +133,8 @@ pub fn execute(
provider_paths.sort(); provider_paths.sort();
provider_paths.dedup(); provider_paths.dedup();
if mode == SandboxMode::Strict { if mode == SandboxMode::Strict {
if stream.is_some() {
return fail(
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
"--event-stream jsonl is not supported under --mode strict; strict refuses \
trace/event artifacts and never downgrades to project mode",
2,
);
}
if let Err(error) = settings.strict_preflight() { if let Err(error) = settings.strict_preflight() {
return fail( return fail(stream, "strict", "strict.unsupported_grant", &error, 2);
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
&error,
2,
);
} }
match marqdo_sandbox::inspect_strict_child() { match marqdo_sandbox::inspect_strict_child() {
// A verified supervisor child may run project code. // A verified supervisor child may run project code.
@@ -174,32 +143,16 @@ pub fn execute(
Ok(StrictChildState::NotChild) => { Ok(StrictChildState::NotChild) => {
let platform = PlatformCapabilities::detect(); let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) { if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail( return fail(stream, "strict", error.code(), &error.to_string(), 1);
stream,
json,
command_name,
"strict",
error.code(),
&error.to_string(),
1,
);
} }
return launch_strict_process(&project.root, file, settings, json, command_name); return launch_strict_process(&project.root, file, settings, stream);
} }
// A marker without a verified identity is never trusted, and the // A marker without a verified identity is never trusted, and the
// platform-neutral inspection keeps Linux-only symbols out of this // platform-neutral inspection keeps Linux-only symbols out of this
// module so macOS/Windows builds compile. // module so macOS/Windows builds compile.
Err(reason) => { Err(reason) => {
let message = format!("strict isolation verification failed: {reason}"); let message = format!("strict isolation verification failed: {reason}");
return fail( return fail(stream, "strict", "strict.identity_invalid", &message, 1);
stream,
json,
command_name,
"strict",
"strict.identity_invalid",
&message,
1,
);
} }
} }
} }
@@ -207,8 +160,6 @@ pub fn execute(
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) { if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail( return fail(
stream, stream,
json,
command_name,
"authorization", "authorization",
"sandbox.unavailable", "sandbox.unavailable",
&error.to_string(), &error.to_string(),
@@ -218,15 +169,7 @@ pub fn execute(
let capabilities = match settings.capabilities() { let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities, Ok(capabilities) => capabilities,
Err(error) => { Err(error) => {
return fail( return fail(stream, "authorization", "cli.invalid_grants", &error, 2);
stream,
json,
command_name,
"authorization",
"cli.invalid_grants",
&error,
2,
);
} }
}; };
let stdin = read_stdin(); let stdin = read_stdin();
@@ -234,18 +177,6 @@ pub fn execute(
if let Some(stream) = stream { if let Some(stream) = stream {
host = host.with_observation(stream.config(), Box::new(stream.host_sink())); host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
} }
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel { if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel; host.budget.fuel = fuel;
} }
@@ -260,15 +191,7 @@ pub fn execute(
} }
for kernel_path in &kernel_paths { for kernel_path in &kernel_paths {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) { if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
return fail( return fail(stream, "prepare", "ext.kernel_load_failed", &error, 2);
stream,
json,
command_name,
"prepare",
"ext.kernel_load_failed",
&error,
2,
);
} }
} }
// T6: verify every selected artifact/path/hash before starting a worker or // T6: verify every selected artifact/path/hash before starting a worker or
@@ -282,7 +205,7 @@ pub fn execute(
let providers = match provider_manifest::read_provider_manifests(&provider_paths) { let providers = match provider_manifest::read_provider_manifests(&provider_paths) {
Ok(providers) => providers, Ok(providers) => providers,
Err(error) => { Err(error) => {
return fail_prepare(stream, json, command_name, "prepare", &error); return fail_prepare(stream, "prepare", &error);
} }
}; };
// `--provider` alone never authorizes; the exact `--allow-provider NAME` // `--provider` alone never authorizes; the exact `--allow-provider NAME`
@@ -302,7 +225,7 @@ pub fn execute(
provider.name, provider.name provider.name, provider.name
), ),
); );
return fail_prepare(stream, json, command_name, "authorization", &error); return fail_prepare(stream, "authorization", &error);
} }
} }
// A grant that matches no selected provider is a deterministic option // A grant that matches no selected provider is a deterministic option
@@ -317,7 +240,7 @@ pub fn execute(
providers are never discovered automatically" providers are never discovered automatically"
), ),
); );
return fail_prepare(stream, json, command_name, "authorization", &error); return fail_prepare(stream, "authorization", &error);
} }
} }
for plugin in &static_plugins.plugins { for plugin in &static_plugins.plugins {
@@ -325,17 +248,16 @@ pub fn execute(
&plugin.base_dir, &plugin.base_dir,
&plugin.artifact_relative, &plugin.artifact_relative,
) { ) {
return fail_prepare(stream, json, command_name, "authorization", &error); return fail_prepare(stream, "authorization", &error);
} }
let artifact = plugin.artifact_path(); let artifact = plugin.artifact_path();
if let Err(error) = extension_descriptors::verify_sha256(&artifact, &plugin.artifact_sha256) if let Err(error) = extension_descriptors::verify_sha256(&artifact, &plugin.artifact_sha256)
{ {
return fail_prepare(stream, json, command_name, "authorization", &error); return fail_prepare(stream, "authorization", &error);
} }
} }
// A native plugin shares this process and can write fd 1 directly, so it // An in-process native plugin can write directly to the inherited fds.
// can pollute the JSONL channel. Fail closed rather than presenting // Require a controlled channel before publishing observed program bytes.
// untrusted raw bytes as program stdout (RFC-OBS-0001 §4.4/§9.2, T26).
if stream.is_some() if stream.is_some()
&& static_plugins && static_plugins
.plugins .plugins
@@ -344,12 +266,9 @@ pub fn execute(
{ {
return fail( return fail(
stream, stream,
json,
command_name,
"authorization", "authorization",
"ext.event_stream_unsupported_native_plugin", "ext.observation_unsupported_native_plugin",
"--event-stream jsonl cannot guarantee a clean channel with an in-process native \ "observation requires a controlled output channel; use a worker plugin or text output without a snapshot",
plugin; use a worker plugin or disable event mode",
2, 2,
); );
} }
@@ -362,8 +281,6 @@ pub fn execute(
) { ) {
return fail( return fail(
stream, stream,
json,
command_name,
"authorization", "authorization",
"ext.plugin_load_failed", "ext.plugin_load_failed",
&message, &message,
@@ -376,8 +293,6 @@ pub fn execute(
if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) { if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) {
return fail( return fail(
stream, stream,
json,
command_name,
"authorization", "authorization",
"ext.plugin_binding_mismatch", "ext.plugin_binding_mismatch",
&message, &message,
@@ -393,7 +308,7 @@ pub fn execute(
provider, provider,
&settings.allow_provider, &settings.allow_provider,
) { ) {
return fail_prepare(stream, json, command_name, "prepare", &error); return fail_prepare(stream, "prepare", &error);
} }
} }
let function_name = function.unwrap_or("main").to_string(); let function_name = function.unwrap_or("main").to_string();
@@ -411,15 +326,7 @@ pub fn execute(
project.entry_file().path.display() project.entry_file().path.display()
) )
}; };
return fail( return fail(stream, "compile", "sem.no_entry_function", &message, 1);
stream,
json,
command_name,
"compile",
"sem.no_entry_function",
&message,
1,
);
} }
let runtime_args: Vec<EvaluatedArg> = named_args let runtime_args: Vec<EvaluatedArg> = named_args
.iter() .iter()
@@ -435,7 +342,10 @@ pub fn execute(
}; };
if let Some(stream) = stream { if let Some(stream) = stream {
let entry = format!("{}::{}", project.entry, function_name); let entry = format!("{}::{}", project.entry, function_name);
let analysis_digest = format!("sha256:{}", crate::analysis::digest(&project)); let analysis_digest = match crate::analysis::digest(&project) {
Ok(digest) => digest,
Err(error) => return fail(Some(stream), "prepare", "cli.analysis_failed", &error, 1),
};
if let Err(error) = stream.started( if let Err(error) = stream.started(
&entry, &entry,
mode.as_str(), mode.as_str(),
@@ -445,7 +355,7 @@ pub fn execute(
return transport_failure(&error); return transport_failure(&error);
} }
} }
let mut result = run_with_limits( let result = run_with_limits(
&project.program, &project.program,
&mut host, &mut host,
&project.entry, &project.entry,
@@ -453,128 +363,45 @@ pub fn execute(
runtime_args, runtime_args,
memory_limits, memory_limits,
); );
// A dead event pipe is a run failure even if the program itself returned.
if result.is_ok() {
if let Some(message) = host.observation_failure() {
result = Err(RuntimeError::new(
marqdo_value::ErrorCategory::Observation,
None,
format!("observe.transport_failed: {message}"),
));
}
}
let trace_run_id = stream.map(EventStream::run_id);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(
&project,
&host,
&entry,
status,
path,
trace_run_id.as_deref(),
) {
if let Some(stream) = stream {
let _ = stream.failed_error("cli.trace_failed", &error);
} else {
emit_error(json, command_name, "cli.trace_failed", &error);
}
return 1;
}
}
if let Some(stream) = stream { if let Some(stream) = stream {
// The program's stdout/stderr were already emitted as chunk events at if let Some(error) = host.observation_failure() {
// their real host commit points; never replay them on this channel. return transport_failure(error);
match &result { }
Ok(outcome) => { let delivered = match &result {
if let Err(error) = stream.completed(&outcome.value) { Ok(outcome) => stream.completed(&outcome.value),
return transport_failure(&error); Err(error) => stream.failed(runtime_error_json(error, &project)),
} };
} if let Err(error) = delivered {
Err(error) => { return transport_failure(&error);
if let Err(write_error) = stream.failed(error) {
eprintln!("error[observe.transport_failed]: {write_error}");
}
eprint!("{}", render_runtime_error(error, &project));
return 1;
}
} }
return 0;
} }
let stdout = host.take_output(); if observation.output == OutputFormat::Text {
let stdout_text = String::from_utf8_lossy(&stdout).to_string(); use std::io::Write;
let stderr = host.take_error(); let _ = std::io::stderr().write_all(&host.take_error());
let stderr_text = String::from_utf8_lossy(&stderr).to_string(); let _ = std::io::stdout().write_all(&host.take_output());
let trace_entries = host.trace().to_vec(); if let (Some(_), Ok(outcome)) = (function, &result) {
match result { if outcome.value != Value::Unit {
Ok(outcome) => { println!("{}", outcome.value.display());
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
} }
0
} }
}
match result {
Ok(_) => 0,
Err(error) => { Err(error) => {
if json { eprint!("{}", render_runtime_error(&error, &project));
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
1 1
} }
} }
} }
fn transport_failure(error: &str) -> i32 { pub(super) fn transport_failure(error: &str) -> i32 {
eprintln!("error[observe.transport_failed]: {error}"); eprintln!("error[observe.transport_failed]: {error}");
1 1
} }
/// Emit one pre-execution rejection (or the legacy non-event error form). /// Report a failure before the interpreter starts.
fn fail( pub(super) fn fail(
stream: Option<&EventStream>, stream: Option<&ObservationSession>,
json: bool,
command_name: &str,
phase: &str, phase: &str,
code: &str, code: &str,
message: &str, message: &str,
@@ -585,47 +412,16 @@ fn fail(
return transport_failure(&error); return transport_failure(&error);
} }
} }
if json && stream.is_none() { eprintln!("error[{code}]: {message}");
emit_error(json, command_name, code, message);
} else {
eprintln!("error[{code}]: {message}");
}
exit exit
} }
/// Emit one prepare/authorization rejection using a `PrepareError`.
fn fail_prepare( fn fail_prepare(
stream: Option<&EventStream>, stream: Option<&ObservationSession>,
json: bool,
command_name: &str,
phase: &str, phase: &str,
error: &crate::extension_descriptors::PrepareError, error: &crate::extension_descriptors::PrepareError,
) -> i32 { ) -> i32 {
if let Some(stream) = stream { fail(stream, phase, &error.code, &error.message, error.exit_code)
if let Err(write_error) = stream.rejected(phase, &error.code, &error.message) {
return transport_failure(&write_error);
}
eprintln!("error[{}]: {}", error.code, error.message);
} else {
emit_prepare_error(json, command_name, error);
}
error.exit_code
}
fn emit_prepare_error(
json: bool,
command_name: &str,
error: &crate::extension_descriptors::PrepareError,
) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": {"code": error.code, "message": error.message},
}));
} else {
eprintln!("error[{}]: {}", error.code, error.message);
}
} }
/// Compare the Host's actual plugin exports with the static manifest set. /// Compare the Host's actual plugin exports with the static manifest set.
+3 -10
View File
@@ -49,12 +49,6 @@ pub struct SandboxSettings {
pub allow_provider: Vec<String>, pub allow_provider: Vec<String>,
/// Explicit trust decision for in-process native plugin loading. /// Explicit trust decision for in-process native plugin loading.
pub trust_native_plugin: bool, pub trust_native_plugin: bool,
/// Optional Trace v2 output path.
pub trace_file: Option<PathBuf>,
/// Trace event budget override (0 = unlimited).
pub trace_max_events: Option<usize>,
/// Trace approximate byte budget override (0 = unlimited).
pub trace_max_bytes: Option<usize>,
/// External foreign-kernel descriptor paths. /// External foreign-kernel descriptor paths.
pub kernels: Vec<PathBuf>, pub kernels: Vec<PathBuf>,
} }
@@ -72,7 +66,7 @@ impl SandboxSettings {
/// Reject strict-mode requests that this L1 isolation level does not /// Reject strict-mode requests that this L1 isolation level does not
/// support. Strict currently covers pure Marqdo and native Math only; /// support. Strict currently covers pure Marqdo and native Math only;
/// granting Foreign, ABI plugins, resource providers, tools or trace files /// granting Foreign, ABI plugins, resource providers or tools
/// would require extending the supervisor contract first. /// would require extending the supervisor contract first.
pub fn strict_preflight(&self) -> Result<(), String> { pub fn strict_preflight(&self) -> Result<(), String> {
let requested = self.allow_foreign let requested = self.allow_foreign
@@ -87,14 +81,13 @@ impl SandboxSettings {
|| !self.providers.is_empty() || !self.providers.is_empty()
|| !self.allow_provider.is_empty() || !self.allow_provider.is_empty()
|| self.trust_native_plugin || self.trust_native_plugin
|| !self.kernels.is_empty() || !self.kernels.is_empty();
|| self.trace_file.is_some();
if requested { if requested {
return Err( return Err(
"strict mode currently supports pure Marqdo and native Math only; \ "strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\ --allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\ --allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\
--trust-native-plugin/--kernel/--trace-file are rejected. \ --trust-native-plugin/--kernel are rejected. \
Use --mode project for those capabilities." Use --mode project for those capabilities."
.to_string(), .to_string(),
); );
+1
View File
@@ -648,6 +648,7 @@ fn collect_identifiers_stmts(stmts: &[Stmt], names: &mut std::collections::BTree
collect_identifiers_expr(condition, names); collect_identifiers_expr(condition, names);
collect_identifiers_stmts(body, names); collect_identifiers_stmts(body, names);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+35 -101
View File
@@ -7,16 +7,15 @@
mod analysis; mod analysis;
mod args; mod args;
mod commands; mod commands;
mod execution_events;
mod extension_descriptors; mod extension_descriptors;
mod extension_selection; mod extension_selection;
mod loader; mod loader;
mod observation;
mod output; mod output;
mod project_prepare; mod project_prepare;
mod provider_manifest; mod provider_manifest;
mod stdlib; mod stdlib;
mod tool; mod tool;
mod trace;
use std::ffi::OsString; use std::ffi::OsString;
use std::path::PathBuf; use std::path::PathBuf;
@@ -35,69 +34,44 @@ struct Cli {
command: Command, command: Command,
} }
/// Execution Events v1 options (RFC-OBS-0001). /// Output and capture options for run and call.
///
/// `--event-stream jsonl` makes the CLI stdout a dedicated NDJSON channel;
/// program stdout/stderr become events. It is mutually exclusive with
/// `--json` and is not accepted by static commands.
#[derive(Args, Clone)] #[derive(Args, Clone)]
struct ObserveArgs { struct ObserveArgs {
/// Stream Execution Events v1 as JSON Lines on stdout (only `jsonl`). /// Select terminal text, a JSON observation snapshot or live JSON Lines.
#[arg( #[arg(long, value_enum, default_value = "text")]
long = "event-stream", output: observation::OutputFormat,
value_name = "FORMAT", /// Atomically save a private observation snapshot of this run.
value_parser = [execution_events::FORMAT_JSONL], #[arg(long, value_name = "PATH")]
conflicts_with = "json" observation_file: Option<PathBuf>,
)]
event_stream: Option<String>,
/// Publish the value of one exactly named local variable (repeatable). /// Publish the value of one exactly named local variable (repeatable).
#[arg( #[arg(long = "observe-variable", value_name = "NAME")]
long = "observe-variable",
value_name = "NAME",
requires = "event_stream"
)]
observe_variable: Vec<String>, observe_variable: Vec<String>,
/// Publish the value of one exactly named parameter (repeatable). /// Publish the value of one exactly named parameter (repeatable).
#[arg( #[arg(long = "observe-parameter", value_name = "NAME")]
long = "observe-parameter",
value_name = "NAME",
requires = "event_stream"
)]
observe_parameter: Vec<String>, observe_parameter: Vec<String>,
/// Allow selected Text values to be published (second explicit consent). /// Allow selected Text values to be published (second explicit consent).
#[arg(long = "observe-text-values", requires = "event_stream")] #[arg(long = "observe-text-values")]
observe_text_values: bool, observe_text_values: bool,
/// Maximum encoded source bytes for one observed value (0 = unlimited). /// Maximum encoded source bytes for one observed value (0 = unlimited).
#[arg( #[arg(long = "observe-max-value-bytes", value_name = "BYTES")]
long = "observe-max-value-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
observe_max_value_bytes: Option<usize>, observe_max_value_bytes: Option<usize>,
/// Override the structural/value event budget (0 = unlimited). /// Override the structural/value event budget (0 = unlimited).
#[arg( #[arg(long = "observe-max-events", value_name = "COUNT")]
long = "observe-max-events",
value_name = "COUNT",
requires = "event_stream"
)]
observe_max_events: Option<u64>, observe_max_events: Option<u64>,
/// Override the approximate structural/value byte budget (0 = unlimited). /// Override the approximate structural/value byte budget (0 = unlimited).
#[arg( #[arg(long = "observe-max-bytes", value_name = "BYTES")]
long = "observe-max-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
observe_max_bytes: Option<u64>, observe_max_bytes: Option<u64>,
} }
impl ObserveArgs { impl ObserveArgs {
fn options(&self) -> Option<execution_events::ObservationOptions> { fn options(&self) -> observation::ObservationOptions {
self.event_stream.as_ref()?; let mut options = observation::ObservationOptions {
let mut options = execution_events::ObservationOptions { output: self.output,
file: self.observation_file.clone(),
variables: self.observe_variable.clone(), variables: self.observe_variable.clone(),
parameters: self.observe_parameter.clone(), parameters: self.observe_parameter.clone(),
allow_text_values: self.observe_text_values, allow_text_values: self.observe_text_values,
..execution_events::ObservationOptions::default() ..observation::ObservationOptions::default()
}; };
if let Some(bytes) = self.observe_max_value_bytes { if let Some(bytes) = self.observe_max_value_bytes {
options.max_value_bytes = bytes; options.max_value_bytes = bytes;
@@ -108,7 +82,7 @@ impl ObserveArgs {
if let Some(bytes) = self.observe_max_bytes { if let Some(bytes) = self.observe_max_bytes {
options.max_bytes = bytes; options.max_bytes = bytes;
} }
Some(options) options
} }
} }
@@ -220,15 +194,6 @@ struct SandboxArgs {
/// (repeatable; wildcards are not supported). /// (repeatable; wildcards are not supported).
#[arg(long = "allow-provider", value_name = "NAME")] #[arg(long = "allow-provider", value_name = "NAME")]
allow_provider: Vec<String>, allow_provider: Vec<String>,
/// Write a versioned Trace v2 file for this run.
#[arg(long = "trace-file", value_name = "PATH")]
trace_file: Option<PathBuf>,
/// Override the trace event budget (0 = unlimited).
#[arg(long = "trace-max-events")]
trace_max_events: Option<usize>,
/// Override the approximate trace byte budget (0 = unlimited).
#[arg(long = "trace-max-bytes")]
trace_max_bytes: Option<usize>,
/// Register an external foreign-kernel provider (repeatable). /// Register an external foreign-kernel provider (repeatable).
#[arg(long = "kernel", value_name = "PATH")] #[arg(long = "kernel", value_name = "PATH")]
kernel: Vec<PathBuf>, kernel: Vec<PathBuf>,
@@ -259,9 +224,6 @@ impl SandboxArgs {
providers: self.provider.clone(), providers: self.provider.clone(),
allow_provider: self.allow_provider.clone(), allow_provider: self.allow_provider.clone(),
trust_native_plugin: self.trust_native_plugin, trust_native_plugin: self.trust_native_plugin,
trace_file: self.trace_file.clone(),
trace_max_events: self.trace_max_events,
trace_max_bytes: self.trace_max_bytes,
kernels: self.kernel.clone(), kernels: self.kernel.clone(),
} }
} }
@@ -273,12 +235,6 @@ struct RunArgs {
file: Option<PathBuf>, file: Option<PathBuf>,
#[command(flatten)] #[command(flatten)]
sandbox: SandboxArgs, sandbox: SandboxArgs,
/// Machine readable JSON output; program stdout is embedded, never mixed.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)] #[command(flatten)]
observe: ObserveArgs, observe: ObserveArgs,
} }
@@ -294,12 +250,6 @@ struct CallArgs {
args: Vec<String>, args: Vec<String>,
#[command(flatten)] #[command(flatten)]
sandbox: SandboxArgs, sandbox: SandboxArgs,
/// Machine readable JSON output.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)] #[command(flatten)]
observe: ObserveArgs, observe: ObserveArgs,
} }
@@ -314,7 +264,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking. /// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")] #[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>, plugin: Vec<PathBuf>,
/// Write the public Analysis v2 projection (only on successful check). /// Write the current public Analysis JSON for the checked project.
#[arg(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
emit: Option<PathBuf>, emit: Option<PathBuf>,
/// Machine readable JSON output. /// Machine readable JSON output.
@@ -514,36 +464,20 @@ fn dispatch() -> i32 {
}; };
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin) commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
} }
Command::Run(args) => { Command::Run(args) => commands::execute(
let observation = args.observe.options(); args.file.as_deref(),
commands::execute( None,
args.file.as_deref(), Ok(Vec::new()),
None, &args.sandbox.settings(),
&[], &args.observe.options(),
&args.sandbox.settings(), ),
args.json, Command::Call(args) => commands::execute(
args.trace, Some(&args.file),
observation.as_ref(), Some(&args.function),
) commands::parse_named_args(&args.args),
} &args.sandbox.settings(),
Command::Call(args) => match commands::parse_named_args(&args.args) { &args.observe.options(),
Ok(named) => { ),
let observation = args.observe.options();
commands::execute(
Some(&args.file),
Some(&args.function),
&named,
&args.sandbox.settings(),
args.json,
args.trace,
observation.as_ref(),
)
}
Err(error) => {
eprintln!("error: {error}");
2
}
},
Command::Fmt(args) => commands::fmt(args.file.as_deref(), args.check), Command::Fmt(args) => commands::fmt(args.file.as_deref(), args.check),
Command::Plugin(args) => match args.command { Command::Plugin(args) => match args.command {
PluginCommand::Inspect(args) => commands::plugin_inspect(&args.target, args.json), PluginCommand::Inspect(args) => commands::plugin_inspect(&args.target, args.json),
@@ -1,15 +1,9 @@
//! Execution Events v1 JSONL writer and public envelope. //! Deliver the Host observation sequence to JSONL or atomic JSON snapshots.
//!
//! Normative contract: `spec/execution-events-v1.md`; decision record:
//! ADR-0059. The host owns the typed events; this module only assigns the
//! public envelope/sequence, encodes bytes as base64 and writes one flushed
//! line per event to the CLI protocol stdout.
//!
//! There is no HTTP, SSE, WebSocket, View or Agent branch here.
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::io::{self, Write}; use std::io::{self, Seek, Write};
use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -18,19 +12,27 @@ use marqdo_host::{
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, DEFAULT_MAX_VALUE_BYTES,
}; };
use marqdo_value::{RuntimeError, Value}; use marqdo_value::Value;
use serde_json::{json, Value as Json}; use serde_json::{json, Value as Json};
/// Public schema name. /// Public schema name.
pub const SCHEMA: &str = "marqdo.execution-events"; pub const SCHEMA: &str = "marqdo.observation";
/// Public schema major version. /// Public schema major version.
pub const SCHEMA_VERSION: u32 = 1; pub const SCHEMA_VERSION: u32 = 1;
/// The only accepted `--event-stream` format in v1. /// Delivery format on stdout.
pub const FORMAT_JSONL: &str = "jsonl"; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Text,
Json,
Jsonl,
}
/// CLI observation options. /// CLI observation options.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObservationOptions { pub struct ObservationOptions {
pub output: OutputFormat,
pub file: Option<PathBuf>,
/// Exact local-variable names selected with `--observe-variable`. /// Exact local-variable names selected with `--observe-variable`.
pub variables: Vec<String>, pub variables: Vec<String>,
/// Exact parameter names selected with `--observe-parameter`. /// Exact parameter names selected with `--observe-parameter`.
@@ -48,6 +50,8 @@ pub struct ObservationOptions {
impl Default for ObservationOptions { impl Default for ObservationOptions {
fn default() -> Self { fn default() -> Self {
Self { Self {
output: OutputFormat::Text,
file: None,
variables: Vec::new(), variables: Vec::new(),
parameters: Vec::new(), parameters: Vec::new(),
allow_text_values: false, allow_text_values: false,
@@ -59,6 +63,20 @@ impl Default for ObservationOptions {
} }
impl ObservationOptions { impl ObservationOptions {
pub fn enabled(&self) -> bool {
self.output != OutputFormat::Text || self.file.is_some()
}
pub fn has_capture_overrides(&self) -> bool {
let defaults = Self::default();
!self.variables.is_empty()
|| !self.parameters.is_empty()
|| self.allow_text_values
|| self.max_value_bytes != defaults.max_value_bytes
|| self.max_events != defaults.max_events
|| self.max_bytes != defaults.max_bytes
}
/// Typed host policy for this run. /// Typed host policy for this run.
pub fn config(&self) -> ObservationConfig { pub fn config(&self) -> ObservationConfig {
ObservationConfig { ObservationConfig {
@@ -73,15 +91,15 @@ impl ObservationOptions {
} }
} }
/// One run's JSONL writer, shared with the host sink. /// One run and event sequence, shared with the host observation sink.
#[derive(Clone)] #[derive(Clone)]
pub struct EventStream { pub struct ObservationSession {
inner: Rc<RefCell<JsonlWriter>>, inner: Rc<RefCell<EventWriter>>,
config: ObservationConfig, config: ObservationConfig,
} }
impl EventStream { impl ObservationSession {
/// Open the protocol channel and write `stream.opened` as `seq: 0`. /// Set up all destinations and publish the first event.
pub fn open(options: &ObservationOptions) -> Result<Self, String> { pub fn open(options: &ObservationOptions) -> Result<Self, String> {
let run_id = new_run_id(); let run_id = new_run_id();
let config = options.config(); let config = options.config();
@@ -90,10 +108,6 @@ impl EventStream {
"name": "marqdo", "name": "marqdo",
"version": env!("CARGO_PKG_VERSION"), "version": env!("CARGO_PKG_VERSION"),
}, },
"protocol": {
"name": SCHEMA,
"schema_version": SCHEMA_VERSION,
},
"observation": { "observation": {
"level": config.level(), "level": config.level(),
"values": config.values_enabled(), "values": config.values_enabled(),
@@ -107,10 +121,15 @@ impl EventStream {
"max_value_bytes": config.max_value_bytes, "max_value_bytes": config.max_value_bytes,
}, },
}); });
let mut writer = JsonlWriter { let mut writer = EventWriter {
out: Box::new(io::stdout()), output: options.output,
run_id: run_id.clone(), snapshot: Snapshot::open(options)?,
run_id,
seq: 0, seq: 0,
source: Json::Null,
truncated: Json::Null,
capture: opened["observation"].clone(),
failed: false,
}; };
writer.emit("stream.opened", opened)?; writer.emit("stream.opened", opened)?;
Ok(Self { Ok(Self {
@@ -119,11 +138,6 @@ impl EventStream {
}) })
} }
/// Opaque run identity shared with Trace v2 when both are requested.
pub fn run_id(&self) -> String {
self.inner.borrow().run_id.clone()
}
/// Typed policy (used to install the host sink). /// Typed policy (used to install the host sink).
pub fn config(&self) -> ObservationConfig { pub fn config(&self) -> ObservationConfig {
self.config.clone() self.config.clone()
@@ -163,40 +177,26 @@ impl EventStream {
) )
} }
/// Write the successful terminal event. /// Write the successful terminal event and its explicitly returned result.
pub fn completed(&self, value: &Value) -> Result<(), String> { pub fn completed(&self, value: &Value) -> Result<(), String> {
let transferable = !value.contains_memory()
&& !value.contains_resource()
&& !marqdo_host::contains_plugin_handle(value);
let wire = transferable.then(|| marqdo_value::to_wire(value));
self.emit( self.emit(
"run.completed", "run.completed",
json!({"status": "ok", "value": marqdo_value::to_wire(value)}), json!({"status": "ok", "value": wire, "value_type": value.type_name()}),
) )
} }
/// Write the failed terminal event. /// Write the failed terminal event.
pub fn failed(&self, error: &RuntimeError) -> Result<(), String> { pub fn failed(&self, error: Json) -> Result<(), String> {
self.emit( self.emit("run.failed", json!({"status": "error", "error": error}))
"run.failed",
json!({
"status": "error",
"error": {
"code": error.code(),
"message": error.message,
"module_id": error.module_id.as_deref(),
"span": error.span.map(span_json),
}
}),
)
} }
/// Write a failed terminal event for a CLI-level failure that still has a /// Deliver a snapshot without a terminal event when isolation interrupted a run.
/// stable code (for example `cli.trace_failed`). pub fn incomplete(&self) -> Result<(), String> {
pub fn failed_error(&self, code: &str, message: &str) -> Result<(), String> { self.inner.borrow_mut().finish_snapshot("incomplete")
self.emit(
"run.failed",
json!({
"status": "error",
"error": {"code": code, "message": message},
}),
)
} }
/// Write the pre-execution rejection terminal event. /// Write the pre-execution rejection terminal event.
@@ -220,7 +220,7 @@ impl EventStream {
/// `ObservationSink` adapter installed into `StdHost`. /// `ObservationSink` adapter installed into `StdHost`.
pub struct HostEventSink { pub struct HostEventSink {
stream: EventStream, stream: ObservationSession,
} }
impl ObservationSink for HostEventSink { impl ObservationSink for HostEventSink {
@@ -231,14 +231,105 @@ impl ObservationSink for HostEventSink {
} }
} }
struct JsonlWriter { struct Snapshot {
out: Box<dyn Write>, staging: tempfile::NamedTempFile,
run_id: String, path: Option<PathBuf>,
seq: u64,
} }
impl JsonlWriter { impl Snapshot {
fn open(options: &ObservationOptions) -> Result<Option<Self>, String> {
if options.output != OutputFormat::Json && options.file.is_none() {
return Ok(None);
}
let staging = if let Some(path) = &options.file {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create observation directory: {error}"))?;
tempfile::NamedTempFile::new_in(parent)
} else {
tempfile::NamedTempFile::new()
}
.map_err(|error| format!("cannot stage observation snapshot: {error}"))?;
let mut snapshot = Self {
staging,
path: options.file.clone(),
};
snapshot.write(b"{\"events\":[")?;
Ok(Some(snapshot))
}
fn write(&mut self, bytes: &[u8]) -> Result<(), String> {
self.staging
.write_all(bytes)
.map_err(|error| format!("cannot write observation snapshot: {error}"))
}
fn finish(mut self, metadata: Json, stdout: bool) -> Result<(), String> {
let suffix = serde_json::to_vec(&metadata)
.map_err(|error| format!("cannot encode observation metadata: {error}"))?;
self.write(b"],")?;
self.write(&suffix[1..])?;
self.write(b"\n")?;
if let Some(path) = &self.path {
self.staging
.as_file()
.sync_all()
.map_err(|error| format!("cannot sync observation snapshot: {error}"))?;
let mut file = self
.staging
.persist(path)
.map_err(|error| format!("cannot publish observation snapshot: {error}"))?;
if stdout {
write_snapshot_stdout(&mut file)?;
}
} else {
write_snapshot_stdout(self.staging.as_file_mut())?;
}
Ok(())
}
}
fn write_snapshot_stdout(file: &mut std::fs::File) -> Result<(), String> {
let mut out = io::stdout().lock();
file.rewind()
.and_then(|()| io::copy(file, &mut out))
.and_then(|_| out.flush())
.map_err(|error| format!("cannot write observation snapshot to stdout: {error}"))
}
struct EventWriter {
output: OutputFormat,
snapshot: Option<Snapshot>,
run_id: String,
seq: u64,
source: Json,
truncated: Json,
capture: Json,
failed: bool,
}
impl EventWriter {
fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> { fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> {
if self.failed {
return Err("observation transport already failed".into());
}
let result = self.deliver(kind, payload);
if result.is_err() {
self.failed = true;
self.snapshot.take();
}
result
}
fn deliver(&mut self, kind: &str, payload: Json) -> Result<(), String> {
match kind {
"run.started" => self.source = payload["source"].clone(),
"observation.truncated" => self.truncated = payload.clone(),
_ => {}
}
let event = json!({ let event = json!({
"schema": SCHEMA, "schema": SCHEMA,
"schema_version": SCHEMA_VERSION, "schema_version": SCHEMA_VERSION,
@@ -247,18 +338,78 @@ impl JsonlWriter {
"kind": kind, "kind": kind,
"payload": payload, "payload": payload,
}); });
let mut line = serde_json::to_vec(&event) let mut bytes = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode execution event: {error}"))?; .map_err(|error| format!("cannot encode observation event: {error}"))?;
line.push(b'\n'); if let Some(snapshot) = &mut self.snapshot {
// Flush each line: line-buffered batching would hide real-time output if self.seq != 0 {
// behind the run duration (RFC-OBS-0001 §5.2). snapshot.write(b",")?;
self.out }
.write_all(&line) snapshot.write(&bytes)?;
.and_then(|()| self.out.flush()) }
.map_err(|error| format!("cannot write execution event stream: {error}"))?; if matches!(kind, "run.completed" | "run.failed" | "run.rejected") {
self.finish_snapshot(payload["status"].as_str().expect("terminal status"))?;
}
if self.output == OutputFormat::Jsonl {
let mut out = io::stdout().lock();
bytes.push(b'\n');
out.write_all(&bytes)
.and_then(|()| out.flush())
.map_err(|error| format!("cannot write observation stream: {error}"))?;
}
self.seq += 1; self.seq += 1;
Ok(()) Ok(())
} }
fn finish_snapshot(&mut self, status: &str) -> Result<(), String> {
let Some(snapshot) = self.snapshot.take() else {
return Ok(());
};
let mut capture = self.capture.clone();
capture["truncated"] = self.truncated.clone();
snapshot.finish(
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": self.run_id, "status": status, "source": self.source},
"capture": capture,
}),
self.output == OutputFormat::Json,
)
}
}
/// The strict supervisor forwards only a complete current snapshot.
pub fn is_complete_snapshot(bytes: &[u8], exit_code: i32) -> bool {
let Ok(snapshot) = serde_json::from_slice::<Json>(bytes) else {
return false;
};
let Some(events) = snapshot["events"].as_array() else {
return false;
};
let Some(run_id) = snapshot["run"]["id"].as_str() else {
return false;
};
let Some(last) = events.last() else {
return false;
};
let status = match last["kind"].as_str() {
Some("run.completed") if exit_code == 0 => "ok",
Some("run.failed") if exit_code != 0 => "error",
Some("run.rejected") if exit_code != 0 => "rejected",
_ => return false,
};
snapshot["schema"] == SCHEMA
&& snapshot["schema_version"] == SCHEMA_VERSION
&& snapshot["run"]["status"] == status
&& snapshot["capture"].is_object()
&& last["payload"]["status"] == status
&& events[0]["kind"] == "stream.opened"
&& events.iter().enumerate().all(|(seq, event)| {
event["schema"] == SCHEMA
&& event["schema_version"] == SCHEMA_VERSION
&& event["run_id"] == run_id
&& event["seq"] == seq
})
} }
fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) { fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
@@ -351,7 +502,21 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
"span": span.map(span_json), "span": span.map(span_json),
}), }),
), ),
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => (
transfer.event_kind(),
json!({
"frame_id": frame_id.as_wire(),
"module_id": module_id,
"span": span_json(span),
}),
),
ObservationEvent::Effect { ObservationEvent::Effect {
frame_id,
operation, operation,
result_code, result_code,
module_id, module_id,
@@ -359,6 +524,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
} => ( } => (
"effect", "effect",
json!({ json!({
"frame_id": frame_id.map(FrameId::as_wire),
"operation": operation, "operation": operation,
"result_code": result_code, "result_code": result_code,
"module_id": module_id, "module_id": module_id,
+89 -126
View File
@@ -1,4 +1,4 @@
//! Generic external CLI tool protocol (spec/tool-v1.md). //! Generic external CLI tool protocol (spec/cli-tool.md).
//! //!
//! The core never knows a tool's name. It validates a user-supplied //! The core never knows a tool's name. It validates a user-supplied
//! `tool.json`, verifies protocol compatibility, copies the whole bundle into a //! `tool.json`, verifies protocol compatibility, copies the whole bundle into a
@@ -11,7 +11,7 @@ use std::ffi::OsString;
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use std::process::Command as ProcessCommand; use std::process::Command as ProcessCommand;
use semver::{Version, VersionReq}; use semver::Version;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@@ -21,19 +21,7 @@ const RECORD_VERSION: u32 = 2;
const MAX_BUNDLE_FILES: usize = 4096; const MAX_BUNDLE_FILES: usize = 4096;
const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024; const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024;
/// Protocols this core can provide to tools. const API_REVISION: u32 = 1;
#[derive(Debug, Clone, Copy)]
struct SupportedProtocols {
tool: u32,
analysis: &'static [u32],
trace: &'static [u32],
}
const SUPPORTED: SupportedProtocols = SupportedProtocols {
tool: PROTOCOL_VERSION,
analysis: &[2],
trace: &[2],
};
const BUILTIN_COMMANDS: &[&str] = &[ const BUILTIN_COMMANDS: &[&str] = &[
"init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync", "init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync",
@@ -41,6 +29,7 @@ const BUILTIN_COMMANDS: &[&str] = &[
]; ];
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolManifest { struct ToolManifest {
schema: String, schema: String,
schema_version: u32, schema_version: u32,
@@ -48,38 +37,29 @@ struct ToolManifest {
version: String, version: String,
command: String, command: String,
entrypoint: PathBuf, entrypoint: PathBuf,
#[serde(default)] requires: Requirements,
compatibility: Compatibility,
} }
#[derive(Debug, Clone, Default, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct Compatibility { #[serde(deny_unknown_fields)]
#[serde(default)] struct Requirements {
marqdo: Option<String>, api_revision: u32,
#[serde(default)] #[serde(
analysis: Option<Vec<u32>>, default,
#[serde(default)] skip_serializing_if = "Option::is_none",
trace: Option<Vec<u32>>, deserialize_with = "read_requirement"
)]
analysis: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "read_requirement"
)]
observation: Option<u32>,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize)] fn read_requirement<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<Option<u32>, D::Error> {
struct RecordedCompatibility { u32::deserialize(reader).map(Some)
#[serde(default, skip_serializing_if = "Option::is_none")]
marqdo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
analysis: Option<Vec<u32>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
trace: Option<Vec<u32>>,
}
impl RecordedCompatibility {
fn as_compatibility(&self) -> Compatibility {
Compatibility {
marqdo: self.marqdo.clone(),
analysis: self.analysis.clone(),
trace: self.trace.clone(),
}
}
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -90,6 +70,7 @@ struct BundleEntry {
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolRecord { struct ToolRecord {
record_version: u32, record_version: u32,
command: String, command: String,
@@ -100,8 +81,7 @@ struct ToolRecord {
bundle_sha256: String, bundle_sha256: String,
source: String, source: String,
schema_version: u32, schema_version: u32,
#[serde(default)] requires: Requirements,
compatibility: RecordedCompatibility,
} }
/// `marqdo tool install <manifest-or-directory>`. /// `marqdo tool install <manifest-or-directory>`.
@@ -201,11 +181,7 @@ fn install_inner(manifest_path: &Path) -> Result<ToolRecord, String> {
bundle_sha256: bundle_sha256.clone(), bundle_sha256: bundle_sha256.clone(),
source: manifest_file.display().to_string(), source: manifest_file.display().to_string(),
schema_version: manifest.schema_version, schema_version: manifest.schema_version,
compatibility: RecordedCompatibility { requires: manifest.requires.clone(),
marqdo: manifest.compatibility.marqdo.clone(),
analysis: manifest.compatibility.analysis.clone(),
trace: manifest.compatibility.trace.clone(),
},
}; };
let record_json = serde_json::to_string_pretty(&record) let record_json = serde_json::to_string_pretty(&record)
.map_err(|error| format!("cannot serialize record: {error}"))?; .map_err(|error| format!("cannot serialize record: {error}"))?;
@@ -226,7 +202,7 @@ impl ToolManifest {
let text = std::fs::read_to_string(path) let text = std::fs::read_to_string(path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?; .map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
let manifest: Self = let manifest: Self =
serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}"))?; serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}. Build the tool with current exact protocol requirements"))?;
Ok(manifest) Ok(manifest)
} }
} }
@@ -235,10 +211,10 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
if manifest.schema != SCHEMA { if manifest.schema != SCHEMA {
return Err(format!("unsupported tool schema `{}`", manifest.schema)); return Err(format!("unsupported tool schema `{}`", manifest.schema));
} }
if manifest.schema_version != SUPPORTED.tool { if manifest.schema_version != PROTOCOL_VERSION {
return Err(format!( return Err(format!(
"unsupported tool schema_version {} (expected {})", "unsupported tool schema_version {} (expected {})",
manifest.schema_version, SUPPORTED.tool manifest.schema_version, PROTOCOL_VERSION
)); ));
} }
if !is_valid_command(&manifest.command) { if !is_valid_command(&manifest.command) {
@@ -262,46 +238,31 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
manifest.version manifest.version
) )
})?; })?;
negotiate(&manifest.version, &manifest.compatibility) validate_requirements(&manifest.requires)
} }
fn negotiate(tool_version: &str, compatibility: &Compatibility) -> Result<(), String> { fn validate_requirements(requires: &Requirements) -> Result<(), String> {
Version::parse(tool_version) for (name, requested, current) in [
.map_err(|error| format!("tool version `{tool_version}` is not valid SemVer: {error}"))?; ("api_revision", Some(requires.api_revision), API_REVISION),
let core_version = Version::parse(env!("CARGO_PKG_VERSION")) (
.map_err(|error| format!("core version is not valid SemVer: {error}"))?; "analysis",
if let Some(range) = &compatibility.marqdo { requires.analysis,
let requirement = VersionReq::parse(range) crate::analysis::SCHEMA_VERSION,
.map_err(|error| format!("invalid marqdo compatibility range `{range}`: {error}"))?; ),
if !requirement.matches(&core_version) { (
return Err(format!( "observation",
"tool requires marqdo `{range}`, this core is {}", requires.observation,
env!("CARGO_PKG_VERSION") crate::observation::SCHEMA_VERSION,
)); ),
] {
if let Some(requested) = requested {
if requested != current {
return Err(format!(
"tool.protocol_incompatible: tool requires {name} {requested}, this core provides {current}"
));
}
} }
} }
negotiate_protocol(
"analysis",
compatibility.analysis.as_deref(),
SUPPORTED.analysis,
)?;
negotiate_protocol("trace", compatibility.trace.as_deref(), SUPPORTED.trace)?;
Ok(())
}
fn negotiate_protocol(
name: &str,
requested: Option<&[u32]>,
supported: &[u32],
) -> Result<(), String> {
let Some(requested) = requested else {
return Ok(());
};
if requested.is_empty() || !requested.iter().any(|version| supported.contains(version)) {
return Err(format!(
"tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}"
));
}
Ok(()) Ok(())
} }
@@ -475,7 +436,7 @@ pub fn list(json: bool) -> i32 {
"name": record.name, "name": record.name,
"version": record.version, "version": record.version,
"bundle_files": record.bundle.len(), "bundle_files": record.bundle.len(),
"compatibility": record.compatibility, "requires": record.requires,
}) })
}) })
.collect(); .collect();
@@ -560,8 +521,8 @@ pub fn dispatch(args: &[OsString]) -> i32 {
return 2; return 2;
}; };
let command = first.to_string_lossy(); let command = first.to_string_lossy();
if BUILTIN_COMMANDS.contains(&command.as_ref()) { if !is_valid_command(&command) || BUILTIN_COMMANDS.contains(&command.as_ref()) {
eprintln!("error: internal dispatch error for built-in command `{command}`"); eprintln!("error: invalid external command `{command}`");
return 2; return 2;
} }
let home = match tool_home() { let home = match tool_home() {
@@ -574,6 +535,10 @@ pub fn dispatch(args: &[OsString]) -> i32 {
let dir = home.join(command.as_ref()); let dir = home.join(command.as_ref());
let record = match load_record(&dir) { let record = match load_record(&dir) {
Ok(record) => record, Ok(record) => record,
Err(error) if dir.exists() => {
eprintln!("error: tool `{command}`: {error}");
return 1;
}
Err(_) => { Err(_) => {
eprintln!( eprintln!(
"error: unknown command `{command}`; install a tool with `marqdo tool install <tool.json>`" "error: unknown command `{command}`; install a tool with `marqdo tool install <tool.json>`"
@@ -585,14 +550,6 @@ pub fn dispatch(args: &[OsString]) -> i32 {
eprintln!("error: tool record does not match command `{command}`; reinstall it"); eprintln!("error: tool record does not match command `{command}`; reinstall it");
return 1; return 1;
} }
if let Err(error) = negotiate(&record.version, &record.compatibility.as_compatibility()) {
eprintln!("error: tool `{command}` is not compatible with this core: {error}");
return 1;
}
if record.record_version != RECORD_VERSION {
eprintln!("error: tool `{command}` uses an old record; reinstall it");
return 1;
}
let bundle = match collect_bundle(&dir, true) { let bundle = match collect_bundle(&dir, true) {
Ok(bundle) => bundle, Ok(bundle) => bundle,
Err(error) => { Err(error) => {
@@ -619,26 +576,16 @@ pub fn dispatch(args: &[OsString]) -> i32 {
}; };
let mut process = ProcessCommand::new(&entrypoint); let mut process = ProcessCommand::new(&entrypoint);
process.args(&args[1..]); process.args(&args[1..]);
if let Ok(bin) = std::env::current_exe() { match std::env::current_exe() {
process.env("MARQDO_BIN", bin); Ok(bin) => {
} process.env("MARQDO_BIN", bin);
process.env("MARQDO_TOOL_PROTOCOL", "1"); }
if record Err(error) => {
.compatibility eprintln!("error: cannot locate marqdo for tool `{command}`: {error}");
.analysis return 1;
.as_ref() }
.is_some_and(|versions| versions.contains(&2))
{
process.env("MARQDO_PROTOCOL_ANALYSIS", "2");
}
if record
.compatibility
.trace
.as_ref()
.is_some_and(|versions| versions.contains(&2))
{
process.env("MARQDO_PROTOCOL_TRACE", "2");
} }
process.env("MARQDO_API_REVISION", API_REVISION.to_string());
match process.status() { match process.status() {
Ok(status) => status.code().unwrap_or(1), Ok(status) => status.code().unwrap_or(1),
Err(error) => { Err(error) => {
@@ -682,7 +629,10 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
if entry.file_name().to_string_lossy().starts_with('.') { if entry.file_name().to_string_lossy().starts_with('.') {
continue; continue;
} }
if let Ok(record) = load_record(&entry.path()) { if entry.path().join("record.json").is_file() {
let record = load_record(&entry.path()).map_err(|error| {
format!("tool `{}`: {error}", entry.file_name().to_string_lossy())
})?;
records.insert(record.command.clone(), record); records.insert(record.command.clone(), record);
} }
} }
@@ -690,13 +640,26 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
} }
fn load_record(dir: &Path) -> Result<ToolRecord, String> { fn load_record(dir: &Path) -> Result<ToolRecord, String> {
let text = std::fs::read_to_string(dir.join("record.json")) let record_path = dir.join("record.json");
.map_err(|error| format!("tool record is missing: {error}"))?; let inspect = |path| {
let record: ToolRecord = std::fs::symlink_metadata(path)
serde_json::from_str(&text).map_err(|error| format!("invalid tool record: {error}"))?; .map_err(|error| format!("cannot inspect tool registration: {error}"))
if record.record_version != RECORD_VERSION { };
return Err("tool record is from an older protocol; reinstall it".to_string()); if !inspect(dir)?.is_dir() || !inspect(record_path.as_path())?.is_file() {
return Err("invalid tool registration path. Remove and reinstall the tool".to_string());
} }
let text = std::fs::read_to_string(record_path)
.map_err(|error| format!("tool record is missing: {error}"))?;
let record: ToolRecord = serde_json::from_str(&text).map_err(|error| {
format!("invalid or retired tool record: {error}. Remove and reinstall the tool")
})?;
if record.record_version != RECORD_VERSION || record.schema_version != PROTOCOL_VERSION {
return Err(
"tool record uses an unsupported format. Remove and reinstall the tool".to_string(),
);
}
validate_requirements(&record.requires)
.map_err(|error| format!("{error}. Remove and reinstall the tool"))?;
Ok(record) Ok(record)
} }
-144
View File
@@ -1,144 +0,0 @@
//! Public Trace v2 writer (spec/trace-v2.md).
//!
//! Events come from the interpreter (semantic) and the capability host
//! (effects). No argument values, secrets or handles are recorded.
use std::path::Path;
use marqdo_host::{Host, SemanticEvent, StdHost, TraceEntry};
use serde_json::{json, Value};
use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.trace";
pub const SCHEMA_VERSION: u32 = 2;
/// Write a trace atomically for one run.
pub fn write(
project: &LoadedProject,
host: &StdHost,
entry: &str,
status: &str,
path: &Path,
run_id: Option<&str>,
) -> Result<(), String> {
// A combined `--event-stream` run shares the CLI-generated opaque run id
// with Execution Events v1; Trace v2 keeps its schema and field types.
let run_id = run_id.map(str::to_string).unwrap_or_else(|| {
format!(
"{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
)
});
let analysis_digest = crate::analysis::digest(project);
let root_id = project.identity.root_id();
let state = host.trace_state();
let mut events: Vec<Value> = host
.semantic_events()
.iter()
.map(semantic_json)
.chain(host.trace().iter().map(effect_json))
.collect();
events.sort_by_key(|event| event.get("seq").and_then(Value::as_u64).unwrap_or(u64::MAX));
let mut truncation = state.truncation.clone();
let max_bytes = state.budget.max_bytes;
let bytes = loop {
let mut all = events.clone();
if let Some(truncation) = &truncation {
let seq = all
.last()
.and_then(|event| event.get("seq"))
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1;
all.push(json!({
"seq": seq,
"kind": "trace.truncated",
"module_id": null,
"span": null,
"detail": truncation.reason,
}));
}
let trace = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": run_id, "entry": entry, "status": status},
"source": {
"root_id": root_id,
"analysis_digest": format!("sha256:{analysis_digest}"),
},
"limits": {
"max_events": state.budget.max_events,
"max_bytes": state.budget.max_bytes,
},
"truncated": truncation,
"events": all,
});
let bytes = serde_json::to_vec_pretty(&trace)
.map_err(|error| format!("cannot encode trace: {error}"))?;
if max_bytes == 0 || bytes.len() <= max_bytes || events.is_empty() {
break bytes;
}
events.pop();
if truncation.is_none() {
truncation = Some(marqdo_host::TraceTruncation {
reason: "byte_budget".to_string(),
limit: max_bytes as u64,
written: events.len() as u64,
});
}
};
atomic_write(path, &bytes)
}
fn semantic_json(event: &SemanticEvent) -> Value {
json!({
"seq": event.seq,
"kind": event.kind,
"function_id": event.function_id,
"module_id": event.module_id,
"span": event.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": event.detail,
})
}
fn effect_json(entry: &TraceEntry) -> Value {
json!({
"seq": entry.seq,
"kind": "effect",
"module_id": entry.module,
"span": entry.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": entry.result,
"operation": entry.op,
"duration_micros": entry.duration_micros,
})
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?;
let temporary = parent.join(format!(
".{}.tmp-{}",
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "trace.json".to_string()),
std::process::id()
));
std::fs::write(&temporary, bytes)
.map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("cannot publish `{}`: {error}", path.display()));
}
Ok(())
}
@@ -1,5 +1,8 @@
//! Public Analysis/Trace v1 black-box contract (spec/analysis-v1.md, //! Public Analysis and Observation black-box contracts (spec/analysis.md,
//! spec/trace-v1.md). //! spec/observation.md).
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
@@ -96,7 +99,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
let analysis: serde_json::Value = serde_json::from_slice(&first_bytes).unwrap(); let analysis: serde_json::Value = serde_json::from_slice(&first_bytes).unwrap();
assert_eq!(analysis["schema"], "marqdo.analysis"); assert_eq!(analysis["schema"], "marqdo.analysis");
assert_eq!(analysis["schema_version"], 2); assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0]; let module = &analysis["modules"][0];
assert_eq!(module["id"], "root:default::index.mq.md"); assert_eq!(module["id"], "root:default::index.mq.md");
assert_eq!(module["package_instance_id"], "root:default"); assert_eq!(module["package_instance_id"], "root:default");
@@ -140,7 +143,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
} }
#[test] #[test]
fn analysis_v2_identity_is_location_independent() { fn analysis_identity_is_location_independent() {
let first = TempDir::new("analysis-identity-a"); let first = TempDir::new("analysis-identity-a");
let second = TempDir::new("analysis-identity-b"); let second = TempDir::new("analysis-identity-b");
let source = "## @exec main\n\n`x = 1`\n\n`return x`\n"; let source = "## @exec main\n\n`x = 1`\n\n`return x`\n";
@@ -182,7 +185,7 @@ fn analysis_v2_identity_is_location_independent() {
} }
#[test] #[test]
fn analysis_v2_projects_memory_place_targets_additively() { fn analysis_projects_memory_place_targets_additively() {
let dir = TempDir::new("analysis-place"); let dir = TempDir::new("analysis-place");
let source = let source =
"## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n"; "## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n";
@@ -211,7 +214,7 @@ fn analysis_v2_projects_memory_place_targets_additively() {
} }
#[test] #[test]
fn analysis_v2_projects_addressable_formula_and_code_resources() { fn analysis_projects_addressable_formula_and_code_resources() {
let dir = TempDir::new("analysis-resources"); let dir = TempDir::new("analysis-resources");
let source = r#"## @exec calc let source = r#"## @exec calc
@@ -271,7 +274,7 @@ print(1)
} }
#[test] #[test]
fn trace_v2_budget_truncates_long_loops_without_failing_the_run() { fn snapshot_budget_truncates_long_loops_without_failing_the_run() {
let dir = TempDir::new("trace-budget"); let dir = TempDir::new("trace-budget");
write( write(
dir.path(), dir.path(),
@@ -284,9 +287,9 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--trace-file", "--observation-file",
trace_path.to_str().unwrap(), trace_path.to_str().unwrap(),
"--trace-max-events", "--observe-max-events",
"20", "20",
], ],
); );
@@ -298,14 +301,18 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
); );
let trace: serde_json::Value = let trace: serde_json::Value =
serde_json::from_slice(&std::fs::read(&trace_path).unwrap()).unwrap(); serde_json::from_slice(&std::fs::read(&trace_path).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2); assert_eq!(trace["schema_version"], 1);
assert_eq!(trace["run"]["status"], "ok"); assert_eq!(trace["run"]["status"], "ok");
assert_eq!(trace["limits"]["max_events"], 20); assert_eq!(
assert_eq!(trace["truncated"]["reason"], "event_budget"); trace["events"][0]["payload"]["limits"]["max_observation_events"],
assert_eq!(trace["truncated"]["limit"], 20); 20
);
assert_eq!(trace["capture"]["truncated"]["reason"], "event_budget");
assert_eq!(trace["capture"]["truncated"]["limit"], 20);
let events = trace["events"].as_array().unwrap(); let events = trace["events"].as_array().unwrap();
assert!(events.len() <= 21, "events: {}", events.len()); assert_eq!(events.len(), 24);
assert_eq!(events.last().unwrap()["kind"], "trace.truncated"); assert_eq!(events[22]["kind"], "observation.truncated");
assert_eq!(events[23]["kind"], "run.completed");
let mut previous = None; let mut previous = None;
for event in events { for event in events {
let seq = event["seq"].as_u64().unwrap(); let seq = event["seq"].as_u64().unwrap();
@@ -331,7 +338,32 @@ fn failed_check_removes_stale_analysis() {
} }
#[test] #[test]
fn trace_records_calls_effects_and_status_without_secrets() { fn check_that_cannot_load_the_project_removes_stale_analysis() {
let dir = TempDir::new("analysis-load-error");
write(dir.path(), "index.mq.md", "## @exec main\n\n`return 1`\n");
let target = dir.path().join("analysis.json");
let first = cli(
dir.path(),
&["check", "index.mq.md", "--emit", target.to_str().unwrap()],
);
assert_eq!(first.status.code(), Some(0), "{first:?}");
assert!(target.exists());
// The load failure happens before the compile-error cleanup branch, so the
// remove must also cover the prepare path.
let failed = cli(
dir.path(),
&["check", "missing.mq.md", "--emit", target.to_str().unwrap()],
);
assert_ne!(failed.status.code(), Some(0), "{failed:?}");
assert!(
!target.exists(),
"a load failure must not leave the previous Analysis in place"
);
}
#[test]
fn snapshot_records_calls_effects_and_status_without_secrets() {
let dir = TempDir::new("trace"); let dir = TempDir::new("trace");
write(dir.path(), "index.mq.md", PROGRAM); write(dir.path(), "index.mq.md", PROGRAM);
let trace_path = dir.path().join("trace.json"); let trace_path = dir.path().join("trace.json");
@@ -340,7 +372,7 @@ fn trace_records_calls_effects_and_status_without_secrets() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--trace-file", "--observation-file",
trace_path.to_str().unwrap(), trace_path.to_str().unwrap(),
], ],
); );
@@ -356,15 +388,16 @@ fn trace_records_calls_effects_and_status_without_secrets() {
"values must not be recorded" "values must not be recorded"
); );
let trace: serde_json::Value = serde_json::from_str(&text).unwrap(); let trace: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(trace["schema"], "marqdo.trace"); assert_eq!(trace["schema"], "marqdo.observation");
assert_eq!(trace["schema_version"], 2); assert_eq!(trace["schema_version"], 1);
assert_eq!(trace["run"]["status"], "ok"); assert_eq!(trace["run"]["status"], "ok");
assert_eq!(trace["run"]["entry"], "root:default::index.mq.md::main"); assert_eq!(
trace["events"][1]["payload"]["entry"],
"root:default::index.mq.md::main"
);
let events = trace["events"].as_array().unwrap(); let events = trace["events"].as_array().unwrap();
assert!(events assert!(events.iter().any(|event| event["kind"] == "call.enter"
.iter() && event["payload"]["module_id"] == "root:default::index.mq.md"));
.any(|event| event["kind"] == "call.enter"
&& event["module_id"] == "root:default::index.mq.md"));
assert!(events.iter().any(|event| event["kind"] == "effect")); assert!(events.iter().any(|event| event["kind"] == "effect"));
assert!(events.iter().any(|event| event["kind"] == "call.exit")); assert!(events.iter().any(|event| event["kind"] == "call.exit"));
let mut previous = None; let mut previous = None;
@@ -384,12 +417,160 @@ fn trace_records_calls_effects_and_status_without_secrets() {
&[ &[
"run", "run",
"bad.mq.md", "bad.mq.md",
"--trace-file", "--observation-file",
error_trace.to_str().unwrap(), error_trace.to_str().unwrap(),
], ],
); );
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
let trace: serde_json::Value = let trace: serde_json::Value =
serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap(); serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap();
assert_eq!(trace["run"]["status"], "runtime.division_by_zero"); assert_eq!(trace["run"]["status"], "error");
assert_eq!(
trace["events"].as_array().unwrap().last().unwrap()["payload"]["error"]["code"],
"runtime.division_by_zero"
);
}
#[test]
fn multi_arm_branch_preserves_analysis_and_carrier_positions() {
let dir = TempDir::new("else-if");
let source = r#"## @exec 分类
`params(数值: Int)`
1. `if 数值 < 0`
`return -1`
2. **else if 数值 == 0**
`return 0`
> *else if 数值 == 1*
>
> `return 1`
`else`
`return 2`
`end`
"#;
write(dir.path(), "index.mq.md", source);
let output = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(output.status.success(), "{output:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 3);
assert_eq!(analysis["producer"]["markdown_profile"], "marqdo.md.v1");
let branch = &analysis["modules"][0]["functions"][0]["body"][0];
assert_eq!(branch["kind"], "branch");
let arms = branch["arms"].as_array().unwrap();
assert_eq!(arms.len(), 4);
for (arm, carrier) in arms.iter().zip([
"`if 数值 < 0`",
"**else if 数值 == 0**",
"*else if 数值 == 1*",
"`else`",
]) {
let start = source.find(carrier).unwrap();
let expected = serde_json::json!({"start": start, "end": start + carrier.len()});
assert_eq!(arm["span"], expected);
assert_eq!(arm["condition_span"], expected);
}
for (input, expected) in [("-3", "-1"), ("0", "0"), ("1", "1"), ("9", "2")] {
let output = cli(
dir.path(),
&[
"call",
"index.mq.md",
"分类",
"--arg",
&format!("数值={input}"),
"--output",
"json",
],
);
assert!(output.status.success(), "{output:?}");
let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(observation::terminal(&result)["value"]["decimal"], expected);
}
}
#[test]
fn an_imported_loop_transfer_uses_current_schema_and_keeps_the_else_if_call_edge() {
let dir = TempDir::new("imported-loop");
write(
dir.path(),
"gate.mq.md",
"## @exec enabled\n\n`while true`\n\n`break`\n\n`end`\n\n`return true`\n",
);
write(
dir.path(),
"index.mq.md",
r#"---
import:
gate: "./gate.mq.md"
---
## @exec main
`if false`
`return 0`
`else if gate.enabled()`
`return 1`
`end`
"#,
);
let result = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(result.status.success(), "{result:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 3);
let root = analysis["modules"]
.as_array()
.unwrap()
.iter()
.find(|module| module["relative_path"] == "index.mq.md")
.unwrap();
let calls = root["calls"].as_array().unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0]["state"], "function");
assert!(calls[0]["target"]
.as_str()
.unwrap()
.ends_with("::gate.mq.md::enabled"));
}
#[test]
fn invalid_loop_control_rejects_check_and_does_not_execute_the_function() {
let dir = TempDir::new("invalid-loop");
write(
dir.path(),
"index.mq.md",
"## @exec main\n\n`打印(\"unreachable output\")`\n\n`break`\n",
);
write(dir.path(), "stale.json", "previous output");
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "stale.json", "--json"],
);
assert_eq!(checked.status.code(), Some(1), "{checked:?}");
assert!(String::from_utf8_lossy(&checked.stdout).contains("sem.break_outside_loop"));
assert!(!String::from_utf8_lossy(&checked.stdout).contains("unreachable output"));
assert!(!dir.path().join("stale.json").exists());
let run = cli(dir.path(), &["run", "index.mq.md"]);
assert_eq!(run.status.code(), Some(1), "{run:?}");
assert!(run.stdout.is_empty());
} }
@@ -33,6 +33,7 @@ const WORKSPACE_CRATES: &[&str] = &[
"marqdo-foreign", "marqdo-foreign",
"marqdo-plugin-abi", "marqdo-plugin-abi",
"marqdo-provider-worker", "marqdo-provider-worker",
"marqdo-worker-ipc",
"marqdo-plugin-sdk", "marqdo-plugin-sdk",
"marqdo-host", "marqdo-host",
"marqdo-runtime", "marqdo-runtime",
@@ -140,6 +141,42 @@ fn stdlib_imports_resolve_inside_the_bundle() {
} }
} }
#[test]
fn shared_worker_transport_is_neutral_and_not_duplicated() {
let root = repo_root();
let transport = read(&root.join("crates/marqdo-worker-ipc/Cargo.toml"));
for forbidden in ["marqdo-host", "marqdo-plugin-abi", "marqdo-provider-worker"] {
assert!(
!transport.contains(forbidden),
"marqdo-worker-ipc must stay transport-only; it must not depend on `{forbidden}`"
);
}
for user in [
"crates/marqdo-host/Cargo.toml",
"crates/marqdo-plugin-abi/Cargo.toml",
"crates/marqdo-provider-worker/Cargo.toml",
] {
assert!(
read(&root.join(user)).contains("marqdo-worker-ipc = {"),
"{user} must use the one shared worker transport"
);
}
// The four-byte length prefix and its bounds live in exactly one crate.
for private in [
"crates/marqdo-host/src/plugin_worker.rs",
"crates/marqdo-host/src/provider_worker.rs",
"crates/marqdo-plugin-abi/src/worker.rs",
"crates/marqdo-provider-worker/src/main.rs",
] {
let text = read(&root.join(private));
let implementation = text.split("#[cfg(test)]").next().unwrap_or(&text);
assert!(
!implementation.contains("from_be_bytes") && !implementation.contains("to_be_bytes"),
"{private} reimplements worker framing instead of using marqdo-worker-ipc"
);
}
}
#[test] #[test]
fn host_keeps_the_documented_resource_endpoints() { fn host_keeps_the_documented_resource_endpoints() {
let resource = read(&repo_root().join("crates/marqdo-host/src/resource.rs")); let resource = read(&repo_root().join("crates/marqdo-host/src/resource.rs"));
+11 -7
View File
@@ -4,6 +4,8 @@
//! point is to prove that `check` and `run` share one static resolution and //! point is to prove that `check` and `run` share one static resolution and
//! that the runtime never guesses a plugin from a dotted string prefix. //! that the runtime never guesses a plugin from a dotted string prefix.
#![cfg(unix)] #![cfg(unix)]
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
@@ -187,11 +189,11 @@ fn renamed_import_alias_binds_the_module_function() {
); );
let check = cli(&["check", "index.mq.md"], dir.path()); let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check)); assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md", "--json"], dir.path()); let run = cli(&["run", "index.mq.md", "--output", "json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run)); assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap(); let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!( assert_eq!(
json["value"], observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "101"}) serde_json::json!({"type": "int", "decimal": "101"})
); );
} }
@@ -482,11 +484,14 @@ fn local_function_reference_is_a_dynamic_language_call() {
&dir.path().join("index.mq.md"), &dir.path().join("index.mq.md"),
"## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n", "## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n",
); );
let run = cli(&["call", "index.mq.md", "主", "--json"], dir.path()); let run = cli(
&["call", "index.mq.md", "主", "--output", "json"],
dir.path(),
);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run)); assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap(); let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!( assert_eq!(
json["value"], observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "16"}) serde_json::json!({"type": "int", "decimal": "16"})
); );
} }
@@ -526,11 +531,11 @@ fn explicit_import_aliases_bind_same_named_functions_independently() {
&dir.path().join("index.mq.md"), &dir.path().join("index.mq.md"),
"---\nimport:\n aa: \"./a.mq.md\"\n bb: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return aa.value() + bb.value()`\n", "---\nimport:\n aa: \"./a.mq.md\"\n bb: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return aa.value() + bb.value()`\n",
); );
let run = cli(&["run", "index.mq.md", "--json"], dir.path()); let run = cli(&["run", "index.mq.md", "--output", "json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run)); assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap(); let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!( assert_eq!(
json["value"], observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "30"}) serde_json::json!({"type": "int", "decimal": "30"})
); );
} }
@@ -632,7 +637,6 @@ fn check_emit_and_run_share_the_same_static_binding_source() {
plugin_dir.path().to_str().unwrap(), plugin_dir.path().to_str().unwrap(),
"--allow-plugin", "--allow-plugin",
"demo.solver", "demo.solver",
"--json",
], ],
dir.path(), dir.path(),
); );
+98
View File
@@ -202,3 +202,101 @@ fn has_hex_sha(text: &str) -> bool {
} }
false false
} }
/// CI is a consumer of the public protocols: its configuration must exercise
/// only the current contracts. A retired name in a pipeline is a latent
/// failure and implies a compatibility path was kept somewhere.
#[test]
fn ci_configuration_uses_only_current_protocols() {
let root = repo_root();
for relative in [
".woodpecker/main.yml",
".github/workflows/ci.yml",
"docs/ci.md",
] {
let text = read(&root.join(relative));
for retired in [
"--event-stream",
"--trace-file",
"execution-events",
"execution_events",
"analysis_v3_consumer",
"trace_consumer",
"analysis-v3",
] {
assert!(
!text.contains(retired),
"{relative} still references retired `{retired}`"
);
}
}
}
/// The current contract documents must describe the interface that exists.
/// A retired option or a path to a deleted spec in `spec/` or the current
/// developer guides is a release-record defect: consumers would implement a
/// contract the binary does not accept. Historical ADRs, evidence and
/// `docs/history/` keep their original text and are intentionally excluded.
#[test]
fn current_contract_documents_do_not_reference_retired_interfaces() {
let root = repo_root();
let mut files = vec![
"COMPATIBILITY.md".to_string(),
"README.md".to_string(),
"docs/ci.md".to_string(),
"docs/architecture/CURRENT.md".to_string(),
];
for directory in ["spec", "docs/developers", "examples"] {
let base = root.join(directory);
let mut stack = vec![base];
while let Some(path) = stack.pop() {
for entry in std::fs::read_dir(&path).expect("read contract docs") {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
} else if path.extension().and_then(|ext| ext.to_str()) == Some("md") {
files.push(
path.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string(),
);
}
}
}
}
let retired = [
"--trace-file",
"--event-stream",
"EffectTrace",
"crates/marqdo-host/src/trace.rs",
"spec/trace-v1.md",
"spec/trace-v2.md",
"spec/execution-events-v1.md",
"spec/analysis-v1.md",
"spec/analysis-v2.md",
"spec/tool-v1.md",
"worker_frame_invalid for an over-limit",
];
for relative in files {
let text = read(&root.join(&relative));
for (number, line) in text.lines().enumerate() {
for token in retired {
if !line.contains(token) {
continue;
}
// A sentence that explicitly marks the interface as retired or
// removed is documentation of the migration, not a claim that
// it is available.
let explained = line.contains("retired")
|| line.contains("removed")
|| line.contains("no longer");
assert!(
explained,
"{relative}:{} still documents retired `{token}`",
number + 1
);
}
}
}
}
+22 -10
View File
@@ -1,6 +1,9 @@
//! R6 integration examples that do not require an official external repo. //! R6 integration examples that do not require an official external repo.
#![cfg(unix)] #![cfg(unix)]
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path; use std::path::Path;
use std::process::{Command, Output}; use std::process::{Command, Output};
@@ -51,13 +54,13 @@ fn mqmd_stdlib_print_output_matches_builtin_print() {
#[test] #[test]
fn addressable_memory_example_runs_through_the_cli() { fn addressable_memory_example_runs_through_the_cli() {
let output = cli(&["run", "examples/memory-buffer.mq.md", "--json"]); let output = cli(&["run", "examples/memory-buffer.mq.md", "--output", "json"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output)); assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let report: serde_json::Value = let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON"); serde_json::from_slice(&output.stdout).expect("run --output json emits a snapshot");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
assert_eq!(report["value"]["type"], "int"); assert_eq!(observation::terminal(&report)["value"]["type"], "int");
assert_eq!(report["value"]["decimal"], "141"); assert_eq!(observation::terminal(&report)["value"]["decimal"], "141");
} }
#[test] #[test]
@@ -67,13 +70,17 @@ fn cli_memory_budget_override_fails_closed() {
"examples/memory-buffer.mq.md", "examples/memory-buffer.mq.md",
"--max-memory", "--max-memory",
"0", "0",
"--json", "--output",
"json",
]); ]);
assert_eq!(output.status.code(), Some(1), "{}", stderr(&output)); assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
let report: serde_json::Value = let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON"); serde_json::from_slice(&output.stdout).expect("run --output json emits a snapshot");
assert_eq!(report["success"], false); assert_eq!(report["run"]["status"], "error");
assert_eq!(report["error"]["code"], "resource.exhausted"); assert_eq!(
observation::terminal(&report)["error"]["code"],
"resource.exhausted"
);
} }
#[test] #[test]
@@ -133,7 +140,12 @@ fn unknown_tool_name_installs_and_dispatches() {
#[test] #[test]
fn public_schemas_are_valid_json_and_versioned() { fn public_schemas_are_valid_json_and_versioned() {
for name in ["analysis-v1", "trace-v1", "tool-v1", "execution-events-v1"] { for name in [
"analysis",
"observation-event",
"cli-tool",
"observation-file",
] {
let path = repo() let path = repo()
.join("spec/schemas") .join("spec/schemas")
.join(format!("{name}.schema.json")); .join(format!("{name}.schema.json"));
+56
View File
@@ -493,3 +493,59 @@ fn declared_kernel_extension_is_activated_from_the_manifest() {
let run = cli(&["run", "index.mq.md", "--allow-foreign"], project.path()); let run = cli(&["run", "index.mq.md", "--allow-foreign"], project.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run)); assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
} }
#[test]
fn retired_extension_descriptor_revisions_are_rejected_without_migration() {
// A kernel descriptor is only current at wire_version 1. There is no v2
// reader and no migration: the descriptor is rejected before locking.
let project = TempDir::new("retired-kernel");
std::fs::create_dir_all(project.path().join("kernel")).unwrap();
std::fs::write(
project.path().join("kernel/kernel.json"),
r#"{
"provider_id": "retired-provider",
"languages": ["retired-lang"],
"wire_version": 2,
"entrypoint": "./retired-lang",
"permissions_requested": [],
"digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}"#,
)
.unwrap();
write_project(
project.path(),
"extensions:\n kernels:\n - from: ./kernel/kernel.json\n",
);
std::fs::write(project.path().join("index.mq.md"), "## @exec main\n\nx\n").unwrap();
let rejected = lock(project.path());
assert!(!rejected.status.success(), "{}", stderr(&rejected));
assert!(
stderr(&rejected).contains("unsupported wire_version 2"),
"{}",
stderr(&rejected)
);
assert!(
!project.path().join("marqdo.lock").exists(),
"a rejected retired descriptor must not produce a lock"
);
// A plugin manifest whose ABI requirement targets a retired major is
// rejected by the single current manifest validator.
let Some(project) = plugin_project("retired-abi") else {
return;
};
let manifest_path = project.path().join("adapter/plugin.yaml");
let manifest = std::fs::read_to_string(&manifest_path).unwrap();
std::fs::write(
&manifest_path,
manifest.replace("abi: \"^1.0\"", "abi: \"^2.0\""),
)
.unwrap();
let rejected = lock(project.path());
assert!(!rejected.status.success(), "{}", stderr(&rejected));
assert!(
stderr(&rejected).contains("abi_requirement_unsupported"),
"{}",
stderr(&rejected)
);
}
+15 -3
View File
@@ -1,5 +1,8 @@
//! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint. //! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint.
#[path = "support/observation.rs"]
pub mod observation;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::net::TcpListener; use std::net::TcpListener;
use std::path::Path; use std::path::Path;
@@ -89,7 +92,14 @@ import:
); );
std::fs::write(dir.path().join("index.mq.md"), program).unwrap(); std::fs::write(dir.path().join("index.mq.md"), program).unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"]) .args([
"run",
"index.mq.md",
"--allow-net",
"127.0.0.1",
"--output",
"json",
])
.current_dir(dir.path()) .current_dir(dir.path())
.env( .env(
"MARQDO_STDLIB_DIR", "MARQDO_STDLIB_DIR",
@@ -110,8 +120,10 @@ import:
String::from_utf8_lossy(&output.stdout) String::from_utf8_lossy(&output.stdout)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true); assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["decimal"], "200"); assert_eq!(items[2]["decimal"], "200");
+104 -65
View File
@@ -9,6 +9,9 @@
//! Temporary directories live under the OS temp directory and are removed on //! Temporary directories live under the OS temp directory and are removed on
//! drop; the repository itself is never modified. //! drop; the repository itself is never modified.
#[path = "support/observation.rs"]
pub mod observation;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
@@ -253,16 +256,16 @@ fn run_json_embeds_program_stdout() {
"print.mq.md", "print.mq.md",
"## @exec main\n\n`打印(\"你好\")`\n\n`打印(42)`\n\n`return None`\n", "## @exec main\n\n`打印(\"你好\")`\n\n`打印(42)`\n\n`return None`\n",
); );
let output = cli(dir.path(), &["run", "print.mq.md", "--json"]); let output = cli(dir.path(), &["run", "print.mq.md", "--output", "json"]);
assert_exit(&output, 0, "run --json must succeed"); assert_exit(&output, 0, "run --output json must succeed");
// Exactly one JSON document on stdout: program output is embedded, never // Exactly one JSON document on stdout: program output is embedded, never
// interleaved with the machine-readable envelope. // interleaved with the machine-readable envelope.
let value = json_stdout(&output); let value = json_stdout(&output);
assert_eq!(value["command"], "run"); assert_eq!(value["schema"], "marqdo.observation");
assert_eq!(value["success"], true); assert_eq!(value["run"]["status"], "ok");
assert_eq!(value["stdout"], "你好\n42\n"); assert_eq!(observation::text(&value, "stdout.chunk"), "你好\n42\n");
assert_eq!(value["value"]["type"], "none"); assert_eq!(observation::terminal(&value)["value"]["type"], "none");
assert!(value["trace"].as_array().is_some()); assert!(value["events"].as_array().is_some());
assert!(stderr_text(&output).is_empty()); assert!(stderr_text(&output).is_empty());
// Text mode writes program output only to stdout, no JSON envelope. // Text mode writes program output only to stdout, no JSON envelope.
@@ -297,24 +300,33 @@ fn call_executes_examples_with_typed_arguments() {
"数学.阶乘", "数学.阶乘",
"--arg", "--arg",
"n=5", "n=5",
"--json", "--output",
"json",
], ],
); );
assert_exit(&output, 0, "call must execute factorial"); assert_exit(&output, 0, "call must execute factorial");
let value = json_stdout(&output); let value = json_stdout(&output);
assert_eq!(value["success"], true); assert_eq!(value["run"]["status"], "ok");
assert_eq!(value["value"]["type"], "int"); assert_eq!(observation::terminal(&value)["value"]["type"], "int");
assert_eq!(value["value"]["decimal"], "120"); assert_eq!(observation::terminal(&value)["value"]["decimal"], "120");
let math = examples.join("math.mq.md"); let math = examples.join("math.mq.md");
let output = cli( let output = cli(
&root, &root,
&["call", math.to_str().unwrap(), "计算圆面积", "--json"], &[
"call",
math.to_str().unwrap(),
"计算圆面积",
"--output",
"json",
],
); );
assert_exit(&output, 0, "call must execute the math example"); assert_exit(&output, 0, "call must execute the math example");
let value = json_stdout(&output); let value = json_stdout(&output);
assert_eq!(value["value"]["type"], "float"); assert_eq!(observation::terminal(&value)["value"]["type"], "float");
let area = value["value"]["value"].as_f64().expect("float value"); let area = observation::terminal(&value)["value"]["value"]
.as_f64()
.expect("float value");
assert!( assert!(
(area - std::f64::consts::PI * 16.0).abs() < 1e-12, (area - std::f64::consts::PI * 16.0).abs() < 1e-12,
"area={area}" "area={area}"
@@ -323,11 +335,17 @@ fn call_executes_examples_with_typed_arguments() {
let references = examples.join("references.mq.md"); let references = examples.join("references.mq.md");
let output = cli( let output = cli(
&root, &root,
&["call", references.to_str().unwrap(), "计算作用力", "--json"], &[
"call",
references.to_str().unwrap(),
"计算作用力",
"--output",
"json",
],
); );
assert_exit(&output, 0, "call must execute the references example"); assert_exit(&output, 0, "call must execute the references example");
let value = json_stdout(&output); let value = json_stdout(&output);
assert_eq!(value["value"]["decimal"], "6"); assert_eq!(observation::terminal(&value)["value"]["decimal"], "6");
let hello = examples.join("hello.mq.md"); let hello = examples.join("hello.mq.md");
let output = cli(&root, &["run", hello.to_str().unwrap()]); let output = cli(&root, &["run", hello.to_str().unwrap()]);
@@ -425,7 +443,8 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
assert!( assert!(
stderr.contains("namespace") stderr.contains("namespace")
|| stderr.contains("Resource temporarily unavailable") || stderr.contains("Resource temporarily unavailable")
|| stderr.contains("os error 11"), || stderr.contains("os error 11")
|| (stderr.contains("bwrap") && stderr.contains("Permission denied")),
"strict failure diagnostic does not identify the launch failure: {stderr}" "strict failure diagnostic does not identify the launch failure: {stderr}"
); );
assert!( assert!(
@@ -436,12 +455,19 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
let json = cli( let json = cli(
&root, &root,
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"], &[
"run",
hello.to_str().unwrap(),
"--mode",
"strict",
"--output",
"json",
],
); );
if json.status.success() { if json.status.success() {
let value = json_stdout(&json); let value = json_stdout(&json);
assert_eq!(value["success"], true); assert_eq!(value["run"]["status"], "ok");
assert_eq!(value["value"]["type"], "none"); assert_eq!(observation::terminal(&value)["value"]["type"], "none");
} else { } else {
assert_exit( assert_exit(
&json, &json,
@@ -449,8 +475,8 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
"strict launch failure keeps exit code 1 in JSON mode", "strict launch failure keeps exit code 1 in JSON mode",
); );
let value = json_stdout(&json); let value = json_stdout(&json);
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert!(value["error"] assert!(observation::terminal(&value)["error"]["message"]
.as_str() .as_str()
.expect("error string") .expect("error string")
.contains("strict")); .contains("strict"));
@@ -472,19 +498,26 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
let json = cli( let json = cli(
&root, &root,
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"], &[
"run",
hello.to_str().unwrap(),
"--mode",
"strict",
"--output",
"json",
],
); );
assert_exit(&json, 1, "strict refusal keeps exit code 1 in JSON mode"); assert_exit(&json, 1, "strict refusal keeps exit code 1 in JSON mode");
let value = json_stdout(&json); let value = json_stdout(&json);
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert!(value["error"] assert!(observation::terminal(&value)["error"]["message"]
.as_str() .as_str()
.expect("error string") .expect("error string")
.contains("strict mode")); .contains("strict mode"));
} }
/// A forged `MARQDO_STRICT_ACTIVE` marker must never be trusted and every /// A forged `MARQDO_STRICT_ACTIVE` marker must never be trusted and every
/// `--json` refusal must still contain exactly one JSON document. This runs on /// `--output json` refusal must still contain exactly one JSON document. This runs on
/// every platform; Linux rejects the marker during identity verification and /// every platform; Linux rejects the marker during identity verification and
/// non-Linux builds reject it as unsupported. /// non-Linux builds reject it as unsupported.
#[test] #[test]
@@ -494,15 +527,18 @@ fn forged_strict_marker_is_rejected_with_one_json_document() {
let hello = hello.to_str().unwrap(); let hello = hello.to_str().unwrap();
let json = cli_env( let json = cli_env(
&root, &root,
&["run", hello, "--mode", "strict", "--json"], &["run", hello, "--mode", "strict", "--output", "json"],
"MARQDO_STRICT_ACTIVE", "MARQDO_STRICT_ACTIVE",
"1", "1",
); );
assert_exit(&json, 1, "forged strict marker must fail closed"); assert_exit(&json, 1, "forged strict marker must fail closed");
let value = json_stdout(&json); let value = json_stdout(&json);
assert_eq!(value["command"], "run"); assert_eq!(value["schema"], "marqdo.observation");
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert_eq!(value["code"], "strict.identity_invalid"); assert_eq!(
observation::terminal(&value)["error"]["code"],
"strict.identity_invalid"
);
let human = cli_env( let human = cli_env(
&root, &root,
@@ -519,7 +555,7 @@ fn forged_strict_marker_is_rejected_with_one_json_document() {
assert!(stderr_text(&human).contains("strict isolation verification failed")); assert!(stderr_text(&human).contains("strict isolation verification failed"));
} }
/// CLI usage errors in `--json` mode keep the same one-document contract as /// CLI usage errors in `--output json` mode keep the same one-document contract as
/// successful and runtime-failure paths. /// successful and runtime-failure paths.
#[test] #[test]
fn json_mode_reports_cli_errors_as_one_document() { fn json_mode_reports_cli_errors_as_one_document() {
@@ -527,11 +563,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
let hello = root.join("examples").join("hello.mq.md"); let hello = root.join("examples").join("hello.mq.md");
let hello = hello.to_str().unwrap(); let hello = hello.to_str().unwrap();
let mode = cli(&root, &["run", hello, "--mode", "bogus", "--json"]); let mode = cli(
&root,
&["run", hello, "--mode", "bogus", "--output", "json"],
);
assert_exit(&mode, 2, "unknown mode"); assert_exit(&mode, 2, "unknown mode");
let value = json_stdout(&mode); let value = json_stdout(&mode);
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert_eq!(value["code"], "cli.invalid_mode"); assert_eq!(
observation::terminal(&value)["error"]["code"],
"cli.invalid_mode"
);
let grants = cli( let grants = cli(
&root, &root,
@@ -542,13 +584,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
"pure", "pure",
"--allow-read", "--allow-read",
"x", "x",
"--json", "--output",
"json",
], ],
); );
assert_exit(&grants, 2, "pure mode must reject grants"); assert_exit(&grants, 2, "pure mode must reject grants");
let value = json_stdout(&grants); let value = json_stdout(&grants);
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert_eq!(value["code"], "cli.invalid_grants"); assert_eq!(
observation::terminal(&value)["error"]["code"],
"cli.invalid_grants"
);
let strict = cli( let strict = cli(
&root, &root,
@@ -558,13 +604,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
"--mode", "--mode",
"strict", "strict",
"--allow-foreign", "--allow-foreign",
"--json", "--output",
"json",
], ],
); );
assert_exit(&strict, 2, "strict L1 must reject foreign grants"); assert_exit(&strict, 2, "strict L1 must reject foreign grants");
let value = json_stdout(&strict); let value = json_stdout(&strict);
assert_eq!(value["success"], false); assert_eq!(value["run"]["status"], "rejected");
assert_eq!(value["code"], "strict.unsupported_grant"); assert_eq!(
observation::terminal(&value)["error"]["code"],
"strict.unsupported_grant"
);
} }
#[test] #[test]
@@ -923,11 +973,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
"## @exec boom\n\n说明文字。\n\n`x = 1 / 0`\n\n`return x`\n", "## @exec boom\n\n说明文字。\n\n`x = 1 / 0`\n\n`return x`\n",
); );
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]); let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_exit(&output, 1, "division by zero is a runtime error"); assert_exit(&output, 1, "division by zero is a runtime error");
let value: serde_json::Value = let value: serde_json::Value =
serde_json::from_str(&stdout_text(&output)).expect("run --json emits JSON"); serde_json::from_str(&stdout_text(&output)).expect("run --output json emits JSON");
let error = &value["error"]; let error = &observation::terminal(&value)["error"];
assert_eq!(error["code"], "runtime.division_by_zero"); assert_eq!(error["code"], "runtime.division_by_zero");
assert!( assert!(
error["module_id"] error["module_id"]
@@ -939,22 +989,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
); );
assert_eq!(error["relative_path"], "physics.mq.md"); assert_eq!(error["relative_path"], "physics.mq.md");
assert!( assert!(
error["file"] error.get("file").is_none(),
.as_str() "a shareable snapshot must not embed an absolute host path: {error}"
.unwrap_or_default()
.ends_with("physics.mq.md"),
"{}",
error["file"]
); );
let line = error["line"].as_u64().unwrap_or(0); let line = error["line"].as_u64().unwrap_or(0);
assert!(line >= 5, "expected the failing statement line, got {line}"); assert!(line >= 5, "expected the failing statement line, got {line}");
assert!(
!error["file"]
.as_str()
.unwrap_or_default()
.ends_with("index.mq.md"),
"must not blame the entry file"
);
let human = cli(dir.path(), &["run", "index.mq.md"]); let human = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&human, 1, "human rendering also fails"); assert_exit(&human, 1, "human rendering also fails");
@@ -1171,22 +1210,22 @@ fn power_branch_loop_and_inert_code_end_to_end() {
"branch.mq.md", "branch.mq.md",
"## @exec main\n\n`n = 2`\n\n`if n ** 2 == 4`\n\n`print(\"乘方正确\")`\n\n`else`\n\n`if n ** 2 != 4`\n\n`print(\"乘方错误\")`\n\n`end`\n\n`end`\n", "## @exec main\n\n`n = 2`\n\n`if n ** 2 == 4`\n\n`print(\"乘方正确\")`\n\n`else`\n\n`if n ** 2 != 4`\n\n`print(\"乘方错误\")`\n\n`end`\n\n`end`\n",
); );
let branch = cli(dir.path(), &["run", "branch.mq.md", "--json"]); let branch = cli(dir.path(), &["run", "branch.mq.md", "--output", "json"]);
assert_exit(&branch, 0, "power branch run"); assert_exit(&branch, 0, "power branch run");
let value = json_stdout(&branch); let value = json_stdout(&branch);
assert_eq!(value["success"], true); assert_eq!(value["run"]["status"], "ok");
assert_eq!(value["stdout"], "乘方正确\n"); assert_eq!(observation::text(&value, "stdout.chunk"), "乘方正确\n");
assert_eq!(value["value"]["type"], "unit"); assert_eq!(observation::terminal(&value)["value"]["type"], "unit");
dir.write( dir.write(
"loop.mq.md", "loop.mq.md",
"## @exec main\n\n`n = 0`\n\n`limit = 100`\n\n`while n ** 2 < limit`\n\n`n = n + 1`\n\n`end`\n\n`return n`\n", "## @exec main\n\n`n = 0`\n\n`limit = 100`\n\n`while n ** 2 < limit`\n\n`n = n + 1`\n\n`end`\n\n`return n`\n",
); );
let looped = cli(dir.path(), &["run", "loop.mq.md", "--json"]); let looped = cli(dir.path(), &["run", "loop.mq.md", "--output", "json"]);
assert_exit(&looped, 0, "power loop run"); assert_exit(&looped, 0, "power loop run");
let value = json_stdout(&looped); let value = json_stdout(&looped);
assert_eq!(value["value"]["type"], "int"); assert_eq!(observation::terminal(&value)["value"]["type"], "int");
assert_eq!(value["value"]["decimal"], "10"); assert_eq!(observation::terminal(&value)["value"]["decimal"], "10");
// A code fence containing power syntax is an inert value: it produces no // A code fence containing power syntax is an inert value: it produces no
// diagnostics and never changes the returned value. // diagnostics and never changes the returned value.
@@ -1194,10 +1233,10 @@ fn power_branch_loop_and_inert_code_end_to_end() {
"inert.mq.md", "inert.mq.md",
"## @exec main\n\n```text\n**n = 2 ** 3**\n```\n\n`x = 1`\n\n`return x`\n\n### @knowledge 说明\n\n正文里的 `2 ** 3` 不执行。\n", "## @exec main\n\n```text\n**n = 2 ** 3**\n```\n\n`x = 1`\n\n`return x`\n\n### @knowledge 说明\n\n正文里的 `2 ** 3` 不执行。\n",
); );
let inert = cli(dir.path(), &["run", "inert.mq.md", "--json"]); let inert = cli(dir.path(), &["run", "inert.mq.md", "--output", "json"]);
assert_exit(&inert, 0, "inert code run"); assert_exit(&inert, 0, "inert code run");
let value = json_stdout(&inert); let value = json_stdout(&inert);
assert_eq!(value["value"]["decimal"], "1"); assert_eq!(observation::terminal(&value)["value"]["decimal"], "1");
} }
#[test] #[test]
@@ -1,9 +1,9 @@
//! Black-box Execution Events v1 contract tests (RFC-OBS-0001). //! Black-box Observation contract tests.
//! //!
//! These drive the real `marqdo` binary (`CARGO_BIN_EXE_marqdo`) and parse the //! These drive the real `marqdo` binary (`CARGO_BIN_EXE_marqdo`) and parse the
//! stdout line stream exactly like an external consumer. They cover the P0 //! stdout line stream exactly like an external consumer. They cover the P0
//! envelope/lifecycle/byte-fidelity contract and the P1 frame/value policy, //! envelope/lifecycle/byte-fidelity contract and the P1 frame/value policy,
//! plus trace coexistence, truncation, live delivery and a broken pipe. //! plus snapshot equivalence, truncation, live delivery and a broken pipe.
use std::fs; use std::fs;
use std::io::{BufRead, BufReader, Read}; use std::io::{BufRead, BufReader, Read};
@@ -124,7 +124,7 @@ fn assert_envelope(events: &[Value]) {
assert!(!events.is_empty()); assert!(!events.is_empty());
let first = &events[0]; let first = &events[0];
assert_eq!(first["kind"], "stream.opened"); assert_eq!(first["kind"], "stream.opened");
assert_eq!(first["schema"], "marqdo.execution-events"); assert_eq!(first["schema"], "marqdo.observation");
assert_eq!(first["schema_version"], 1); assert_eq!(first["schema_version"], 1);
assert_eq!(first["seq"], 0); assert_eq!(first["seq"], 0);
let run_id = first["run_id"].as_str().unwrap().to_string(); let run_id = first["run_id"].as_str().unwrap().to_string();
@@ -174,15 +174,16 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
eprintln!("python3 + jsonschema unavailable; schema consumer skipped"); eprintln!("python3 + jsonschema unavailable; schema consumer skipped");
return; return;
} }
let fixtures = repo_root().join("tests/consumers/fixtures/execution-events"); let fixtures = repo_root().join("tests/consumers/fixtures/observation");
let consumer = repo_root().join("tests/consumers/execution_events_consumer.py"); let consumer = repo_root().join("tests/consumers/observation_consumer.py");
for name in ["minimal.jsonl", "full.jsonl"] { for name in ["minimal.jsonl", "full.jsonl"] {
let path = fixtures.join("valid").join(name); let path = fixtures.join("valid").join(name);
let output = Command::new("python3") let output = Command::new("python3")
.arg(&consumer) .arg(&consumer)
.arg("--validate-schema")
.arg(&path) .arg(&path)
.output() .output()
.expect("run execution events consumer"); .expect("run observation consumer");
assert!( assert!(
output.status.success(), output.status.success(),
"valid fixture {name} rejected: {}", "valid fixture {name} rejected: {}",
@@ -193,9 +194,10 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
let path = entry.unwrap().path(); let path = entry.unwrap().path();
let output = Command::new("python3") let output = Command::new("python3")
.arg(&consumer) .arg(&consumer)
.arg("--validate-schema")
.arg(&path) .arg(&path)
.output() .output()
.expect("run execution events consumer"); .expect("run observation consumer");
assert!( assert!(
!output.status.success(), !output.status.success(),
"invalid fixture {} was accepted", "invalid fixture {} was accepted",
@@ -208,7 +210,7 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
fn structure_fixture_attributes_repeated_recursive_frames() { fn structure_fixture_attributes_repeated_recursive_frames() {
let dir = TempDir::new("structure"); let dir = TempDir::new("structure");
let source = fs::read_to_string( let source = fs::read_to_string(
repo_root().join("tests/consumers/fixtures/execution-events/structure.mq.md"), repo_root().join("tests/consumers/fixtures/observation/structure.mq.md"),
) )
.unwrap(); .unwrap();
dir.write("index.mq.md", &source); dir.write("index.mq.md", &source);
@@ -217,7 +219,7 @@ fn structure_fixture_attributes_repeated_recursive_frames() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-max-events", "--observe-max-events",
"1000", "1000",
@@ -287,7 +289,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--plugin", "--plugin",
plugin_dir.join("plugin.yaml").to_str().unwrap(), plugin_dir.join("plugin.yaml").to_str().unwrap(),
@@ -302,7 +304,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
assert_eq!(terminal["kind"], "run.rejected"); assert_eq!(terminal["kind"], "run.rejected");
assert_eq!( assert_eq!(
terminal["payload"]["error"]["code"], terminal["payload"]["error"]["code"],
"ext.event_stream_unsupported_native_plugin" "ext.observation_unsupported_native_plugin"
); );
assert!( assert!(
events_of(&events, "run.started").is_empty(), events_of(&events, "run.started").is_empty(),
@@ -311,8 +313,8 @@ fn native_plugin_is_fail_closed_in_event_mode() {
} }
#[test] #[test]
fn observed_values_never_enter_trace_v2() { fn selected_values_apply_equally_to_stream_and_private_snapshot() {
let dir = TempDir::new("trace-redaction"); let dir = TempDir::new("capture-consent");
dir.write( dir.write(
"index.mq.md", "index.mq.md",
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n", "## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
@@ -323,12 +325,12 @@ fn observed_values_never_enter_trace_v2() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-variable", "--observe-variable",
"secret_token", "secret_token",
"--observe-text-values", "--observe-text-values",
"--trace-file", "--observation-file",
trace_path.to_str().unwrap(), trace_path.to_str().unwrap(),
], ],
); );
@@ -337,24 +339,32 @@ fn observed_values_never_enter_trace_v2() {
String::from_utf8_lossy(&output.stdout).contains("DO_NOT_LEAK_SENTINEL_1"), String::from_utf8_lossy(&output.stdout).contains("DO_NOT_LEAK_SENTINEL_1"),
"the explicit event consent publishes the selected value in the stream" "the explicit event consent publishes the selected value in the stream"
); );
let trace = fs::read(&trace_path).unwrap(); let snapshot_bytes = fs::read(&trace_path).unwrap();
assert!( let snapshot: Value = serde_json::from_slice(&snapshot_bytes).unwrap();
!String::from_utf8_lossy(&trace).contains("DO_NOT_LEAK_SENTINEL_1"), assert_eq!(
"Trace v2 must not gain observed values" snapshot["events"],
serde_json::json!(parse_events(&output.stdout))
); );
let trace: Value = serde_json::from_slice(&trace).unwrap(); assert_eq!(
assert_eq!(trace["schema"], "marqdo.trace"); snapshot["capture"]["selected_variables"],
assert_eq!(trace["schema_version"], 2); serde_json::json!(["secret_token"])
);
assert!(String::from_utf8_lossy(&snapshot_bytes).contains("DO_NOT_LEAK_SENTINEL_1"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&trace_path).unwrap().permissions().mode() & 0o777,
0o600
);
}
} }
#[test] #[test]
fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() { fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() {
let dir = TempDir::new("basic"); let dir = TempDir::new("basic");
dir.write("index.mq.md", BASIC); dir.write("index.mq.md", BASIC);
let output = cli( let output = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
Some(0), Some(0),
@@ -382,27 +392,27 @@ fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() {
} }
#[test] #[test]
fn event_stream_rejects_mixed_json_and_static_commands() { fn retired_run_options_and_static_observation_are_rejected() {
let dir = TempDir::new("reject"); let dir = TempDir::new("reject");
dir.write("index.mq.md", BASIC); dir.write("index.mq.md", BASIC);
let mixed = cli( for args in [
dir.path(), vec!["--json"],
&["run", "index.mq.md", "--event-stream", "jsonl", "--json"], vec!["--event-stream", "jsonl"],
); vec!["--trace-file", "retired.json"],
assert_eq!(mixed.status.code(), Some(2)); vec!["--trace"],
assert!(mixed.stdout.is_empty(), "no mixed stdout"); vec!["--output", "jsonl", "--output", "json"],
assert!(String::from_utf8_lossy(&mixed.stderr).contains("--json")); vec!["--observe-variable", "n"],
] {
let mut command = vec!["run", "index.mq.md"];
command.extend(args);
let rejected = cli(dir.path(), &command);
assert_eq!(rejected.status.code(), Some(2));
assert!(rejected.stdout.is_empty(), "{command:?} must not execute");
}
assert!(!dir.path().join("retired.json").exists());
for command in ["check", "inspect"] { for command in ["check", "inspect"] {
let rejected = cli( let rejected = cli(dir.path(), &[command, "index.mq.md", "--output", "jsonl"]);
dir.path(), assert_eq!(rejected.status.code(), Some(2));
&[command, "index.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(
rejected.status.code(),
Some(2),
"{command} must reject the option"
);
assert!(rejected.stdout.is_empty(), "{command} must not execute"); assert!(rejected.stdout.is_empty(), "{command} must not execute");
} }
} }
@@ -411,10 +421,7 @@ fn event_stream_rejects_mixed_json_and_static_commands() {
fn prepare_and_runtime_failures_have_defined_terminals() { fn prepare_and_runtime_failures_have_defined_terminals() {
let dir = TempDir::new("failures"); let dir = TempDir::new("failures");
dir.write("broken.mq.md", "## @exec main\n\n`if true`\n\n`return 1`\n"); dir.write("broken.mq.md", "## @exec main\n\n`if true`\n\n`return 1`\n");
let rejected = cli( let rejected = cli(dir.path(), &["run", "broken.mq.md", "--output", "jsonl"]);
dir.path(),
&["run", "broken.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(rejected.status.code(), Some(1)); assert_eq!(rejected.status.code(), Some(1));
let events = parse_events(&rejected.stdout); let events = parse_events(&rejected.stdout);
assert_envelope(&events); assert_envelope(&events);
@@ -429,10 +436,7 @@ fn prepare_and_runtime_failures_have_defined_terminals() {
"runtime.mq.md", "runtime.mq.md",
"## @exec main\n\n`x = 1 / 0`\n\n`return x`\n", "## @exec main\n\n`x = 1 / 0`\n\n`return x`\n",
); );
let failed = cli( let failed = cli(dir.path(), &["run", "runtime.mq.md", "--output", "jsonl"]);
dir.path(),
&["run", "runtime.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(failed.status.code(), Some(1)); assert_eq!(failed.status.code(), Some(1));
let events = parse_events(&failed.stdout); let events = parse_events(&failed.stdout);
assert_envelope(&events); assert_envelope(&events);
@@ -455,10 +459,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n", "## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
); );
// Default: metadata only; no value, no sentinel anywhere. // Default: metadata only; no value, no sentinel anywhere.
let default = cli( let default = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(default.status.code(), Some(0)); assert_eq!(default.status.code(), Some(0));
assert!(!String::from_utf8_lossy(&default.stdout).contains("DO_NOT_LEAK_SENTINEL_1")); assert!(!String::from_utf8_lossy(&default.stdout).contains("DO_NOT_LEAK_SENTINEL_1"));
for event in events_of(&parse_events(&default.stdout), "variable.assigned") { for event in events_of(&parse_events(&default.stdout), "variable.assigned") {
@@ -471,7 +472,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-variable", "--observe-variable",
"visible_count", "visible_count",
@@ -498,7 +499,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-variable", "--observe-variable",
"secret_token", "secret_token",
@@ -519,7 +520,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-variable", "--observe-variable",
"secret_token", "secret_token",
@@ -554,10 +555,7 @@ fn binary_and_multibyte_output_is_byte_exact() {
"{}", "{}",
String::from_utf8_lossy(&normal.stderr) String::from_utf8_lossy(&normal.stderr)
); );
let streamed = cli( let streamed = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(streamed.status.code(), Some(0)); assert_eq!(streamed.status.code(), Some(0));
let events = parse_events(&streamed.stdout); let events = parse_events(&streamed.stdout);
let chunks = chunk_bytes(&events, "stdout.chunk"); let chunks = chunk_bytes(&events, "stdout.chunk");
@@ -570,37 +568,50 @@ fn binary_and_multibyte_output_is_byte_exact() {
} }
#[test] #[test]
fn trace_file_coexists_and_shares_the_run_identity() { fn stream_and_snapshot_share_every_event_from_one_run() {
let dir = TempDir::new("trace"); let dir = TempDir::new("destinations");
dir.write("index.mq.md", BASIC); dir.write("index.mq.md", BASIC);
let trace_path = dir.path().join("trace.json");
let output = cli( let output = cli(
dir.path(), dir.path(),
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--trace-file", "--observation-file",
trace_path.to_str().unwrap(), "run.json",
], ],
); );
assert_eq!(output.status.code(), Some(0)); assert!(output.status.success(), "{output:?}");
let events = parse_events(&output.stdout); let events = parse_events(&output.stdout);
assert_envelope(&events); assert_envelope(&events);
let trace: Value = serde_json::from_slice(&fs::read(&trace_path).unwrap()).unwrap(); let snapshot: Value =
assert_eq!(trace["schema"], "marqdo.trace"); serde_json::from_slice(&fs::read(dir.path().join("run.json")).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2); assert_eq!(snapshot["schema"], "marqdo.observation");
assert_eq!(trace["run"]["id"], events[0]["run_id"]); assert_eq!(snapshot["schema_version"], 1);
let started = events_of(&events, "run.started")[0]; assert_eq!(snapshot["run"]["id"], events[0]["run_id"]);
assert_eq!(snapshot["run"]["source"], events[1]["payload"]["source"]);
assert_eq!(snapshot["events"], serde_json::json!(events));
let second = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--output",
"json",
"--observation-file",
"run.json",
],
);
assert!(second.status.success(), "{second:?}");
assert_eq!( assert_eq!(
started["payload"]["source"]["analysis_digest"], second.stdout,
trace["source"]["analysis_digest"] fs::read(dir.path().join("run.json")).unwrap()
);
assert!(
events_of(&events, "run.completed").len() == 1,
"trace writing does not suppress the terminal event"
); );
let second: Value = serde_json::from_slice(&second.stdout).unwrap();
assert_ne!(second["run"]["id"], snapshot["run"]["id"]);
assert_eq!(second["run"]["status"], "ok");
} }
#[test] #[test]
@@ -612,7 +623,7 @@ fn structural_budget_truncates_without_losing_critical_events() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-max-events", "--observe-max-events",
"5", "5",
@@ -637,7 +648,7 @@ fn output_budget_still_fails_the_run_and_emits_no_chunk() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--max-output", "--max-output",
"3", "3",
@@ -663,7 +674,7 @@ fn live_chunks_arrive_while_the_program_is_still_running() {
.args([ .args([
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-max-events", "--observe-max-events",
"20", "20",
@@ -716,7 +727,7 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
.args([ .args([
"run", "run",
"index.mq.md", "index.mq.md",
"--event-stream", "--output",
"jsonl", "jsonl",
"--observe-max-events", "--observe-max-events",
"10", "10",
@@ -765,3 +776,148 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
"expected a transport diagnostic on stderr: {stderr}" "expected a transport diagnostic on stderr: {stderr}"
); );
} }
#[test]
fn loop_transfers_are_ordered_structural_events_with_source_spans() {
use sha2::{Digest, Sha256};
let dir = TempDir::new("loop-transfers");
let source = r#"## @exec main
`索引 = 0`
`while true`
`索引 = 索引 + 1`
`if 索引 == 1`
`continue`
`else if 索引 == 2`
`break`
`end`
`end`
`return 索引`
"#;
dir.write("index.mq.md", source);
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(checked.status.success(), "{checked:?}");
let analysis_bytes = fs::read(dir.path().join("analysis.json")).unwrap();
let analysis: Value = serde_json::from_slice(&analysis_bytes).unwrap();
assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0];
let branch = &module["functions"][0]["body"][1]["body"][1];
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--mode",
"pure",
"--output",
"jsonl",
"--observation-file",
"trace.json",
],
);
assert!(output.status.success(), "{output:?}");
let events = parse_events(&output.stdout);
assert_envelope(&events);
assert_eq!(events.last().unwrap()["kind"], "run.completed");
let trace: Value =
serde_json::from_slice(&fs::read(dir.path().join("trace.json")).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 1);
assert_eq!(
trace["run"]["source"]["analysis_digest"],
format!("sha256:{:x}", Sha256::digest(analysis_bytes))
);
let kinds = |events: &[Value]| {
events
.iter()
.filter_map(|event| match event["kind"].as_str() {
Some("loop.iteration") => Some("loop.iteration"),
Some("control.continue") => Some("control.continue"),
Some("control.break") => Some("control.break"),
Some("return") => Some("return"),
_ => None,
})
.collect::<Vec<_>>()
};
let expected = [
"loop.iteration",
"control.continue",
"loop.iteration",
"control.break",
"return",
];
assert_eq!(kinds(&events), expected);
let trace_events = trace["events"].as_array().unwrap();
assert_eq!(trace_events, &events);
let frame = &events_of(&events, "call.enter")[0]["payload"]["frame_id"];
for (index, keyword) in ["continue", "break"].iter().enumerate() {
let kind = format!("control.{keyword}");
let carrier = format!("`{keyword}`");
let start = source.find(&carrier).unwrap();
let span = serde_json::json!({"start": start, "end": start + carrier.len()});
let payload = &events_of(&events, &kind)[0]["payload"];
assert_eq!(payload["frame_id"], *frame);
assert_eq!(payload["module_id"], module["id"]);
assert_eq!(payload["span"], span);
assert_eq!(payload.as_object().unwrap().len(), 3);
let statement = &branch["arms"][index]["body"][0];
assert_eq!(statement["kind"], *keyword);
assert_eq!(statement["span"], span);
}
}
#[test]
fn strict_mode_rejects_live_and_file_destinations_before_opening_a_stream() {
let dir = TempDir::new("strict-destinations");
dir.write("index.mq.md", BASIC);
let snapshot = dir.path().join("snapshot.json");
let snapshot_arg = snapshot.to_str().unwrap().to_string();
for args in [
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"jsonl",
],
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"text",
"--observation-file",
snapshot_arg.as_str(),
],
] {
let output = cli(dir.path(), &args);
assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
assert!(
output.stdout.is_empty(),
"a rejected strict destination must not emit a partial stream: {}",
String::from_utf8_lossy(&output.stdout)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("strict.unsupported_grant"), "{stderr}");
assert!(
!snapshot.exists(),
"a rejected strict destination must not publish a snapshot file"
);
}
}
+47 -12
View File
@@ -1,5 +1,8 @@
//! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host. //! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host.
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
@@ -70,7 +73,14 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
); );
} }
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"]) .args([
"run",
path.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(repo_root()) .current_dir(repo_root())
.output() .output()
.expect("run marqdo"); .expect("run marqdo");
@@ -82,14 +92,15 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
); );
let report: serde_json::Value = let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("json report"); serde_json::from_slice(&output.stdout).expect("json report");
assert_eq!(report["success"], true, "{name}"); assert_eq!(report["run"]["status"], "ok", "{name}");
let golden = expected(name); let golden = expected(name);
assert_eq!( assert_eq!(
report["value"], golden["value"], observation::terminal(&report)["value"],
golden["value"],
"{criterion} fixture {name}" "{criterion} fixture {name}"
); );
assert_eq!( assert_eq!(
report["stdout"].as_str().unwrap_or_default(), observation::text(&report, "stdout.chunk"),
golden["stdout"].as_str().unwrap_or_default(), golden["stdout"].as_str().unwrap_or_default(),
"{criterion} fixture {name} stdout" "{criterion} fixture {name} stdout"
); );
@@ -100,7 +111,14 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
fn p2_stdlib_table_also_runs_in_pure_mode() { fn p2_stdlib_table_also_runs_in_pure_mode() {
let path = repo_root().join("stdlib").join("tests").join("table.mq.md"); let path = repo_root().join("stdlib").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(["run", path.to_str().unwrap(), "--mode", "pure", "--json"]) .args([
"run",
path.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(repo_root().join("stdlib")) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
@@ -112,8 +130,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let items = report["value"]["items"] let items = observation::terminal(&report)["value"]["items"]
.as_array() .as_array()
.expect("table test list"); .expect("table test list");
assert_eq!(items.len(), 9); assert_eq!(items.len(), 9);
@@ -133,14 +151,24 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
) )
.unwrap(); .unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", foreign.to_str().unwrap(), "--mode", "pure", "--json"]) .args([
"run",
foreign.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(dir.path()) .current_dir(dir.path())
.output() .output()
.expect("run foreign fixture"); .expect("run foreign fixture");
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false); assert_ne!(report["run"]["status"], "ok");
assert_eq!(report["error"]["code"], "permission.denied"); assert_eq!(
observation::terminal(&report)["error"]["code"],
"permission.denied"
);
let plugin = dir.path().join("plugin.mq.md"); let plugin = dir.path().join("plugin.mq.md");
std::fs::write( std::fs::write(
@@ -149,11 +177,18 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
) )
.unwrap(); .unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", plugin.to_str().unwrap(), "--mode", "pure", "--json"]) .args([
"run",
plugin.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(dir.path()) .current_dir(dir.path())
.output() .output()
.expect("run plugin fixture"); .expect("run plugin fixture");
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false); assert_ne!(report["run"]["status"], "ok");
} }
+2 -2
View File
@@ -52,7 +52,7 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
&[ &[
"run", "run",
"index.mq.md", "index.mq.md",
"--trace-file", "--observation-file",
trace.to_str().unwrap(), trace.to_str().unwrap(),
], ],
); );
@@ -69,7 +69,7 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
.as_array() .as_array()
.unwrap() .unwrap()
.iter() .iter()
.filter_map(|event| event["operation"].as_str()) .filter_map(|event| event["payload"]["operation"].as_str())
.collect(); .collect();
assert!( assert!(
operations.contains(&"resource.write"), operations.contains(&"resource.write"),
+32
View File
@@ -429,3 +429,35 @@ fn narration_removal_preserves_execution() {
); );
assert_eq!(values[0], marqdo_value::Value::int(120)); assert_eq!(values[0], marqdo_value::Value::int(120));
} }
#[test]
fn control_flow_ir_is_independent_of_lists_quotes_and_prose() {
let statements = [
"`i = 0`",
"`while true`",
"`i = i + 1`",
"`if i == 1`",
"`continue`",
"`else if i == 2`",
"`break`",
"`end`",
"`end`",
"`return i`",
];
let plain = format!("## @exec main\n\n{}\n", statements.join("\n\n"));
let adorned = statements
.iter()
.enumerate()
.map(|(index, statement)| match index % 3 {
0 => format!("1. {statement} Ordinary prose follows the carrier."),
1 => format!("> {statement}"),
_ => format!("- {statement}"),
})
.collect::<Vec<_>>()
.join("\n\n");
let decorated = format!("## @exec main\n\n{adorned}\n");
assert_eq!(
executable_projection(&plain),
executable_projection(&decorated)
);
}
+48 -29
View File
@@ -15,6 +15,8 @@
//! Other platforms must keep this file compiling but run no provider //! Other platforms must keep this file compiling but run no provider
//! assertions; the CLI itself fails closed with `ext.platform_unsupported`. //! assertions; the CLI itself fails closed with `ext.platform_unsupported`.
#![cfg(all(target_os = "linux", target_arch = "x86_64"))] #![cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[path = "support/observation.rs"]
pub mod observation;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -417,17 +419,14 @@ fn json_of(output: &Output) -> serde_json::Value {
} }
fn error_code(report: &serde_json::Value) -> String { fn error_code(report: &serde_json::Value) -> String {
report observation::terminal(report)["error"]["code"]
.get("error") .as_str()
.and_then(|error| error.get("code")) .expect("terminal error code")
.or_else(|| report.get("code"))
.and_then(|code| code.as_str())
.unwrap_or("<missing error code>")
.to_string() .to_string()
} }
fn map_field<'a>(report: &'a serde_json::Value, name: &str) -> &'a serde_json::Value { fn map_field<'a>(report: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
&report["value"]["entries"][name] &observation::terminal(report)["value"]["entries"][name]
} }
fn cc_available() -> bool { fn cc_available() -> bool {
@@ -469,7 +468,8 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
manifest.to_str().expect("utf-8 manifest path"), manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -480,7 +480,7 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
"run failed: {}", "run failed: {}",
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
assert!(report["success"].as_bool().unwrap_or(false)); assert_eq!(report["run"]["status"], "ok");
assert_eq!(map_field(&report, "count")["decimal"], "5"); assert_eq!(map_field(&report, "count")["decimal"], "5");
assert!(map_field(&report, "eof")["value"] assert!(map_field(&report, "eof")["value"]
.as_bool() .as_bool()
@@ -490,13 +490,14 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
.unwrap_or(false)); .unwrap_or(false));
// `hello` is in the Memory region the provider filled on the first byte. // `hello` is in the Memory region the provider filled on the first byte.
assert_eq!(map_field(&report, "data")["decimal"], "104"); assert_eq!(map_field(&report, "data")["decimal"], "104");
assert_eq!(report["stdout"], ""); assert_eq!(observation::text(&report, "stdout.chunk"), "");
// The Host recorded the real resource effect (not a synthetic success). // The Host recorded the real resource effect (not a synthetic success).
let trace = report["trace"].as_array().expect("trace array"); let trace = report["events"].as_array().expect("trace array");
assert!( assert!(
trace trace
.iter() .iter()
.any(|entry| entry["op"] == "resource.open" && entry["result"] == "ok"), .any(|entry| entry["payload"]["operation"] == "resource.open"
&& entry["payload"]["result_code"] == "ok"),
"missing resource.open trace: {trace:?}" "missing resource.open trace: {trace:?}"
); );
let marks = marker_text(&marker); let marks = marker_text(&marker);
@@ -534,13 +535,14 @@ fn prov_02_without_grant_is_permission_denied_and_never_starts_the_worker() {
"index.mq.md", "index.mq.md",
"--provider", "--provider",
manifest.to_str().expect("utf-8 manifest path"), manifest.to_str().expect("utf-8 manifest path"),
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
let report = json_of(&output); let report = json_of(&output);
assert!(!report["success"].as_bool().unwrap_or(true)); assert_eq!(report["run"]["status"], "rejected");
assert_eq!(error_code(&report), "permission.denied"); assert_eq!(error_code(&report), "permission.denied");
assert!( assert!(
!marker.exists(), !marker.exists(),
@@ -562,7 +564,8 @@ fn prov_03_grant_without_manifest_is_never_discovered() {
"index.mq.md", "index.mq.md",
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -603,7 +606,8 @@ fn prov_04_duplicate_kind_across_providers_is_rejected_before_spawn() {
"demo.one", "demo.one",
"--allow-provider", "--allow-provider",
"demo.two", "demo.two",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -636,7 +640,8 @@ fn prov_05_one_provider_serves_two_non_reserved_kinds() {
manifest.to_str().expect("utf-8 manifest path"), manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider", "--allow-provider",
"demo.multi", "demo.multi",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -647,7 +652,9 @@ fn prov_05_one_provider_serves_two_non_reserved_kinds() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report = json_of(&output); let report = json_of(&output);
let items = report["value"]["items"].as_array().expect("list result"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(items[0]["decimal"], "5"); assert_eq!(items[0]["decimal"], "5");
assert_eq!(items[1]["decimal"], "2"); assert_eq!(items[1]["decimal"], "2");
assert!(items[2]["value"].as_bool().unwrap_or(false)); assert!(items[2]["value"].as_bool().unwrap_or(false));
@@ -691,7 +698,8 @@ fn prov_06_reserved_core_kinds_are_rejected() {
manifest.to_str().expect("utf-8 manifest path"), manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider", "--allow-provider",
"demo.reserved", "demo.reserved",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -734,7 +742,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
digest_manifest.to_str().expect("utf-8 path"), digest_manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -772,7 +781,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
symlink_manifest.to_str().expect("utf-8 path"), symlink_manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -803,7 +813,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
traversal_manifest.to_str().expect("utf-8 path"), traversal_manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -838,7 +849,8 @@ fn prov_08_missing_current_target_is_no_matching_artifact() {
manifest.to_str().expect("utf-8 path"), manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -873,7 +885,8 @@ fn prov_09_v1_manifest_is_unsupported_without_migration() {
manifest.to_str().expect("utf-8 path"), manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -910,7 +923,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg, manifest_arg,
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -932,7 +946,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg, manifest_arg,
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -953,7 +968,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg, manifest_arg,
"--allow-provider", "--allow-provider",
"*", "*",
"--json", "--output",
"json",
], ],
&marker, &marker,
); );
@@ -992,7 +1008,8 @@ fn prov_13_missing_sibling_helper_is_worker_unavailable_without_path_fallback()
manifest.to_str().expect("utf-8 path"), manifest.to_str().expect("utf-8 path"),
"--allow-provider", "--allow-provider",
"demo.sensor", "demo.sensor",
"--json", "--output",
"json",
]) ])
.current_dir(fixture.path()) .current_dir(fixture.path())
.env("PATH", path) .env("PATH", path)
@@ -1007,7 +1024,9 @@ fn prov_13_missing_sibling_helper_is_worker_unavailable_without_path_fallback()
); );
let report = json_of(&output); let report = json_of(&output);
assert_eq!(error_code(&report), "ext.worker_unavailable"); assert_eq!(error_code(&report), "ext.worker_unavailable");
let message = report["error"]["message"].as_str().unwrap_or_default(); let message = observation::terminal(&report)["error"]["message"]
.as_str()
.unwrap_or_default();
assert!( assert!(
message.contains("marqdo-provider-worker") && message.contains("missing"), message.contains("marqdo-provider-worker") && message.contains("missing"),
"{message}" "{message}"
+69 -27
View File
@@ -1,5 +1,8 @@
//! End-to-end resource stream tests through the CLI. //! End-to-end resource stream tests through the CLI.
#[path = "support/observation.rs"]
pub mod observation;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio}; use std::process::{Command, Output, Stdio};
@@ -80,7 +83,14 @@ fn project_file_stream_reads_chunks_into_memory() {
write_file(&dir.path().join("index.mq.md"), READER); write_file(&dir.path().join("index.mq.md"), READER);
let output = cli( let output = cli(
dir.path(), dir.path(),
&["run", "index.mq.md", "--allow-read", "data.txt", "--json"], &[
"run",
"index.mq.md",
"--allow-read",
"data.txt",
"--output",
"json",
],
); );
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
@@ -89,8 +99,8 @@ fn project_file_stream_reads_chunks_into_memory() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let values: Vec<&serde_json::Value> = report["value"]["items"] let values: Vec<&serde_json::Value> = observation::terminal(&report)["value"]["items"]
.as_array() .as_array()
.expect("list result") .expect("list result")
.iter() .iter()
@@ -148,7 +158,8 @@ fn project_file_stream_writes_on_close_then_reads_back() {
"out.bin", "out.bin",
"--allow-read", "--allow-read",
"out.bin", "out.bin",
"--json", "--output",
"json",
], ],
); );
assert_eq!( assert_eq!(
@@ -158,8 +169,10 @@ fn project_file_stream_writes_on_close_then_reads_back() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let values = report["value"]["items"].as_array().expect("list result"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "3"); assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["value"], true); assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["decimal"], "3"); assert_eq!(values[2]["decimal"], "3");
@@ -224,7 +237,8 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() {
"data.txt", "data.txt",
"--allow-write", "--allow-write",
"out.bin", "out.bin",
"--json", "--output",
"json",
], ],
); );
assert_eq!( assert_eq!(
@@ -234,8 +248,10 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let values = report["value"]["items"].as_array().expect("list result"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "6"); assert_eq!(values[0]["decimal"], "6");
assert_eq!(values[1]["value"], true); assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], true); assert_eq!(values[2]["value"], true);
@@ -287,7 +303,14 @@ fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
write_file(&dir.path().join("index.mq.md"), &program); write_file(&dir.path().join("index.mq.md"), &program);
let output = cli( let output = cli(
dir.path(), dir.path(),
&["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"], &[
"run",
"index.mq.md",
"--allow-net",
"127.0.0.1",
"--output",
"json",
],
); );
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
@@ -296,8 +319,10 @@ fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let values = report["value"]["items"].as_array().expect("list"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(values[0]["decimal"], "4"); assert_eq!(values[0]["decimal"], "4");
assert_eq!(values[1]["decimal"], "4"); assert_eq!(values[1]["decimal"], "4");
for (index, expected) in ["112", "105", "110", "103"].into_iter().enumerate() { for (index, expected) in ["112", "105", "110", "103"].into_iter().enumerate() {
@@ -312,11 +337,14 @@ fn file_stream_requires_a_read_grant() {
let dir = TempDir::new("file-denied"); let dir = TempDir::new("file-denied");
write_file(&dir.path().join("data.txt"), "abcdef"); write_file(&dir.path().join("data.txt"), "abcdef");
write_file(&dir.path().join("index.mq.md"), READER); write_file(&dir.path().join("index.mq.md"), READER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]); let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], false); assert_ne!(report["run"]["status"], "ok");
assert_eq!(report["error"]["code"], "permission.denied"); assert_eq!(
observation::terminal(&report)["error"]["code"],
"permission.denied"
);
} }
const STDIN_READER: &str = r#"## @exec main const STDIN_READER: &str = r#"## @exec main
@@ -338,7 +366,11 @@ const STDIN_READER: &str = r#"## @exec main
fn piped_stdin_is_chunked_and_reaches_eof() { fn piped_stdin_is_chunked_and_reaches_eof() {
let dir = TempDir::new("stdin"); let dir = TempDir::new("stdin");
write_file(&dir.path().join("index.mq.md"), STDIN_READER); write_file(&dir.path().join("index.mq.md"), STDIN_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"abcd"); let output = cli_with_stdin(
dir.path(),
&["run", "index.mq.md", "--output", "json"],
b"abcd",
);
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
Some(0), Some(0),
@@ -346,8 +378,10 @@ fn piped_stdin_is_chunked_and_reaches_eof() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let values = report["value"]["items"].as_array().expect("list result"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "2"); assert_eq!(values[0]["decimal"], "2");
assert_eq!(values[1]["value"], false); assert_eq!(values[1]["value"], false);
assert_eq!(values[2]["decimal"], "2"); assert_eq!(values[2]["decimal"], "2");
@@ -393,7 +427,7 @@ const STDERR_WRITER: &str = r#"## @exec main
fn program_stderr_is_separate_from_stdout_and_diagnostics() { fn program_stderr_is_separate_from_stdout_and_diagnostics() {
let dir = TempDir::new("stderr"); let dir = TempDir::new("stderr");
write_file(&dir.path().join("index.mq.md"), STDERR_WRITER); write_file(&dir.path().join("index.mq.md"), STDERR_WRITER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]); let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
Some(0), Some(0),
@@ -401,10 +435,12 @@ fn program_stderr_is_separate_from_stdout_and_diagnostics() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
assert_eq!(report["stdout"], "out"); assert_eq!(observation::text(&report, "stdout.chunk"), "out");
assert_eq!(report["stderr"], "err"); assert_eq!(observation::text(&report, "stderr.chunk"), "err");
let values = report["value"]["items"].as_array().expect("list result"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "3"); assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["decimal"], "3"); assert_eq!(values[1]["decimal"], "3");
assert_eq!(values[2]["value"], true); assert_eq!(values[2]["value"], true);
@@ -433,7 +469,11 @@ import:
fn stdlib_console_reads_lines_and_reports_eof() { fn stdlib_console_reads_lines_and_reports_eof() {
let dir = TempDir::new("console"); let dir = TempDir::new("console");
write_file(&dir.path().join("index.mq.md"), CONSOLE_READER); write_file(&dir.path().join("index.mq.md"), CONSOLE_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"one\ntwo\n"); let output = cli_with_stdin(
dir.path(),
&["run", "index.mq.md", "--output", "json"],
b"one\ntwo\n",
);
assert_eq!( assert_eq!(
output.status.code(), output.status.code(),
Some(0), Some(0),
@@ -441,9 +481,11 @@ fn stdlib_console_reads_lines_and_reports_eof() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
assert_eq!(report["stdout"], "one|two\n"); assert_eq!(observation::text(&report, "stdout.chunk"), "one|two\n");
let values = report["value"]["items"].as_array().expect("list result"); let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["value"], true); assert_eq!(values[0]["value"], true);
assert_eq!(values[1]["value"], true); assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], false); assert_eq!(values[2]["value"], false);
+8 -3
View File
@@ -1,5 +1,8 @@
//! CM-A08/P5 stdlib HTTP framing module tests. //! CM-A08/P5 stdlib HTTP framing module tests.
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
@@ -15,7 +18,7 @@ fn repo_root() -> std::path::PathBuf {
#[test] #[test]
fn stdlib_http_parses_chunked_responses_and_builds_requests() { fn stdlib_http_parses_chunked_responses_and_builds_requests() {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/http.mq.md", "--json"]) .args(["run", "tests/http.mq.md", "--output", "json"])
.current_dir(repo_root().join("stdlib")) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
@@ -27,8 +30,10 @@ fn stdlib_http_parses_chunked_responses_and_builds_requests() {
String::from_utf8_lossy(&output.stderr) String::from_utf8_lossy(&output.stderr)
); );
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json"); let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["decimal"], "200"); assert_eq!(items[0]["decimal"], "200");
assert_eq!(items[1]["value"], "OK"); assert_eq!(items[1]["value"], "OK");
assert_eq!(items[2]["value"], "text/plain"); assert_eq!(items[2]["value"], "text/plain");
+86 -27
View File
@@ -5,6 +5,9 @@
//! user import path (`std:` + the verified bundle), not through a conformance //! user import path (`std:` + the verified bundle), not through a conformance
//! fixture or a Rust shortcut. //! fixture or a Rust shortcut.
#[path = "support/observation.rs"]
pub mod observation;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
@@ -130,7 +133,7 @@ fn run_product_test(file: &TestFile) -> serde_json::Value {
.args(["run"]) .args(["run"])
.arg(stdlib_dir().join("tests").join(&file.name)) .arg(stdlib_dir().join("tests").join(&file.name))
.args(file.args.iter()) .args(file.args.iter())
.args(["--json"]) .args(["--output", "json"])
.current_dir(stdlib_dir()) .current_dir(stdlib_dir())
.env("MARQDO_STDLIB_DIR", stdlib_dir()) .env("MARQDO_STDLIB_DIR", stdlib_dir())
.envs( .envs(
@@ -196,9 +199,10 @@ fn the_whole_bundled_library_runs_through_std_imports() {
for file in product_tests() { for file in product_tests() {
let _guard = lock_fs(&file.name); let _guard = lock_fs(&file.name);
let report = run_product_test(&file); let report = run_product_test(&file);
assert_eq!(report["success"], true, "{}", file.name); assert_eq!(report["run"]["status"], "ok", "{}", file.name);
assert_eq!( assert_eq!(
report["stdout"], file.stdout, observation::text(&report, "stdout.chunk"),
file.stdout,
"{} wrote unexpected stdout", "{} wrote unexpected stdout",
file.name file.name
); );
@@ -214,7 +218,9 @@ fn fs_test_exercises_the_file_operation_surface() {
.find(|file| file.name == "fs.mq.md") .find(|file| file.name == "fs.mq.md")
.expect("fs test"), .expect("fs test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "7"); assert_eq!(items[1]["decimal"], "7");
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -244,7 +250,9 @@ fn json_test_parses_and_formats_nested_values() {
.find(|file| file.name == "json.mq.md") .find(|file| file.name == "json.mq.md")
.expect("json test"), .expect("json test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "1"); assert_eq!(items[1]["decimal"], "1");
assert_eq!(items[2]["value"], "说\"好"); assert_eq!(items[2]["value"], "说\"好");
@@ -269,7 +277,9 @@ fn csv_test_parses_and_formats_quoted_rows() {
.find(|file| file.name == "csv.mq.md") .find(|file| file.name == "csv.mq.md")
.expect("csv test"), .expect("csv test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
let row = items[0]["items"].as_array().expect("row"); let row = items[0]["items"].as_array().expect("row");
assert_eq!(row.len(), 3); assert_eq!(row.len(), 3);
assert_eq!(row[0]["value"], "甲"); assert_eq!(row[0]["value"], "甲");
@@ -298,7 +308,9 @@ fn path_test_joins_and_normalizes_project_paths() {
.find(|file| file.name == "path.mq.md") .find(|file| file.name == "path.mq.md")
.expect("path test"), .expect("path test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], "a/b/c"); assert_eq!(items[0]["value"], "a/b/c");
assert_eq!(items[1]["value"], "c.txt"); assert_eq!(items[1]["value"], "c.txt");
assert_eq!(items[2]["value"], "a/b"); assert_eq!(items[2]["value"], "a/b");
@@ -318,7 +330,9 @@ fn regex_test_matches_anchors_classes_and_search() {
.find(|file| file.name == "regex.mq.md") .find(|file| file.name == "regex.mq.md")
.expect("regex test"), .expect("regex test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], false); assert_eq!(items[1]["value"], false);
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -347,7 +361,9 @@ fn datetime_test_formats_and_parses_utc_instants() {
.find(|file| file.name == "datetime.mq.md") .find(|file| file.name == "datetime.mq.md")
.expect("datetime test"), .expect("datetime test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z"); assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z");
assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z"); assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z");
assert_eq!(items[2]["decimal"], "0"); assert_eq!(items[2]["decimal"], "0");
@@ -365,7 +381,9 @@ fn clock_test_reports_project_mode_unix_millis() {
.find(|file| file.name == "clock.mq.md") .find(|file| file.name == "clock.mq.md")
.expect("clock test"), .expect("clock test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], "Int"); assert_eq!(items[1]["value"], "Int");
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -379,7 +397,9 @@ fn env_test_reads_only_granted_names() {
.find(|file| file.name == "env.mq.md") .find(|file| file.name == "env.mq.md")
.expect("env test"), .expect("env test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true); assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -396,7 +416,9 @@ fn process_test_runs_an_explicitly_granted_program() {
.find(|file| file.name == "process.mq.md") .find(|file| file.name == "process.mq.md")
.expect("process test"), .expect("process test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "0"); assert_eq!(items[1]["decimal"], "0");
let expected = Command::new(env!("CARGO_BIN_EXE_marqdo")) let expected = Command::new(env!("CARGO_BIN_EXE_marqdo"))
@@ -420,7 +442,9 @@ fn random_test_reads_bounded_entropy() {
.find(|file| file.name == "random.mq.md") .find(|file| file.name == "random.mq.md")
.expect("random test"), .expect("random test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "16"); assert_eq!(items[1]["decimal"], "16");
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -436,7 +460,9 @@ fn compress_test_round_trips_gzip_text() {
.find(|file| file.name == "compress.mq.md") .find(|file| file.name == "compress.mq.md")
.expect("compress test"), .expect("compress test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true); assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true); assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true); assert_eq!(items[2]["value"], true);
@@ -451,7 +477,9 @@ fn format_test_pins_value_semantics_and_handle_observation() {
.find(|file| file.name == "format.mq.md") .find(|file| file.name == "format.mq.md")
.expect("format test"), .expect("format test"),
); );
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["decimal"], "3"); assert_eq!(items[0]["decimal"], "3");
assert_eq!(items[1]["value"], "[\"文本\", 2, 1.5]"); assert_eq!(items[1]["value"], "[\"文本\", 2, 1.5]");
assert_eq!(items[2]["value"], "{a: 1}"); assert_eq!(items[2]["value"], "{a: 1}");
@@ -473,12 +501,30 @@ fn text_and_utf8_tests_agree_on_the_byte_encoding() {
.find(|file| file.name == "utf8.mq.md") .find(|file| file.name == "utf8.mq.md")
.expect("utf8 test"), .expect("utf8 test"),
); );
assert_eq!(text["value"]["items"][0]["decimal"], "2"); assert_eq!(
assert_eq!(text["value"]["items"][1]["decimal"], "195"); observation::terminal(&text)["value"]["items"][0]["decimal"],
assert_eq!(text["value"]["items"][2]["decimal"], "169"); "2"
assert_eq!(utf8["value"]["items"][0]["decimal"], "2"); );
assert_eq!(utf8["value"]["items"][1]["value"], "é"); assert_eq!(
assert_eq!(utf8["value"]["items"][2]["value"], false); observation::terminal(&text)["value"]["items"][1]["decimal"],
"195"
);
assert_eq!(
observation::terminal(&text)["value"]["items"][2]["decimal"],
"169"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][0]["decimal"],
"2"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][1]["value"],
"é"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][2]["value"],
false
);
} }
#[test] #[test]
@@ -489,8 +535,14 @@ fn stream_and_console_use_the_resource_endpoints() {
.find(|file| file.name == "stream.mq.md") .find(|file| file.name == "stream.mq.md")
.expect("stream test"), .expect("stream test"),
); );
assert_eq!(stream["value"]["items"][0]["value"], true); assert_eq!(
assert_eq!(stream["value"]["items"][1]["decimal"], "7"); observation::terminal(&stream)["value"]["items"][0]["value"],
true
);
assert_eq!(
observation::terminal(&stream)["value"]["items"][1]["decimal"],
"7"
);
let console = run_product_test( let console = run_product_test(
product_tests() product_tests()
@@ -498,14 +550,21 @@ fn stream_and_console_use_the_resource_endpoints() {
.find(|file| file.name == "console.mq.md") .find(|file| file.name == "console.mq.md")
.expect("console test"), .expect("console test"),
); );
assert_eq!(console["value"]["items"][0]["value"], true); assert_eq!(
assert_eq!(console["value"]["items"][1]["value"], "hello"); observation::terminal(&console)["value"]["items"][0]["value"],
true
);
assert_eq!(
observation::terminal(&console)["value"]["items"][1]["value"],
"hello"
);
assert!( assert!(
console["trace"] console["events"]
.as_array() .as_array()
.unwrap() .unwrap()
.iter() .iter()
.any(|event| event["op"] == "resource.read" || event["op"] == "resource.open"), .any(|event| event["payload"]["operation"] == "resource.read"
|| event["payload"]["operation"] == "resource.open"),
"console test did not go through a resource endpoint" "console test did not go through a resource endpoint"
); );
} }
+8 -3
View File
@@ -1,5 +1,8 @@
//! CM-A08 table stdlib module tests. //! CM-A08 table stdlib module tests.
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
@@ -14,7 +17,7 @@ fn repo_root() -> std::path::PathBuf {
fn run_table_self_test() -> serde_json::Value { fn run_table_self_test() -> serde_json::Value {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/table.mq.md", "--json"]) .args(["run", "tests/table.mq.md", "--output", "json"])
.current_dir(repo_root().join("stdlib")) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
@@ -35,8 +38,10 @@ fn rows(value: &serde_json::Value) -> &Vec<serde_json::Value> {
#[test] #[test]
fn stdlib_table_algorithms_rebuild_without_mutating_inputs() { fn stdlib_table_algorithms_rebuild_without_mutating_inputs() {
let report = run_table_self_test(); let report = run_table_self_test();
assert_eq!(report["success"], true); assert_eq!(report["run"]["status"], "ok");
let items = report["value"]["items"].as_array().expect("list"); let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items.len(), 9); assert_eq!(items.len(), 9);
assert_eq!(items[0]["header"], serde_json::json!(["分数"])); assert_eq!(items[0]["header"], serde_json::json!(["分数"]));
+58
View File
@@ -0,0 +1,58 @@
//! Helpers for black-box tests that inspect values or committed program bytes.
use serde_json::Value;
pub fn terminal(snapshot: &Value) -> &Value {
assert_eq!(snapshot["schema"], "marqdo.observation");
let event = snapshot["events"].as_array().unwrap().last().unwrap();
assert!(matches!(
event["kind"].as_str(),
Some("run.completed" | "run.failed" | "run.rejected")
));
&event["payload"]
}
pub fn text(snapshot: &Value, channel: &str) -> String {
let bytes = snapshot["events"]
.as_array()
.unwrap()
.iter()
.filter(|event| event["kind"] == channel)
.flat_map(|event| {
let payload = &event["payload"];
let bytes = base64_decode(payload["data_base64"].as_str().unwrap());
assert_eq!(payload["byte_count"], bytes.len());
bytes
})
.collect();
String::from_utf8(bytes).unwrap()
}
fn base64_decode(text: &str) -> Vec<u8> {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::new();
let bytes: Vec<u8> = text
.bytes()
.filter(|byte| *byte != b'=')
.map(|byte| {
ALPHABET
.iter()
.position(|item| *item == byte)
.unwrap_or_else(|| panic!("invalid base64 byte {byte}")) as u8
})
.collect();
for chunk in bytes.chunks(4) {
let mut triple = 0u32;
for (index, byte) in chunk.iter().enumerate() {
triple |= u32::from(*byte) << (18 - 6 * index);
}
out.push((triple >> 16) as u8);
if chunk.len() > 2 {
out.push((triple >> 8) as u8);
}
if chunk.len() > 3 {
out.push(triple as u8);
}
}
out
}
+83 -97
View File
@@ -1,4 +1,4 @@
//! External CLI Tool Protocol v1 black-box tests (spec/tool-v1.md). //! External CLI CLI Tool black-box tests (spec/cli-tool.md).
//! //!
//! The tool fixture is compiled with rustc from `tests/fixtures/tool_echo.rs` //! The tool fixture is compiled with rustc from `tests/fixtures/tool_echo.rs`
//! rather than a shell script, so these tests run on Windows and macOS too. //! rather than a shell script, so these tests run on Windows and macOS too.
@@ -8,6 +8,8 @@ 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 sha2::Digest;
static COUNTER: AtomicU32 = AtomicU32::new(0); static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf); struct TempDir(PathBuf);
@@ -95,7 +97,7 @@ fn write_tool(dir: &Path, command: &str, _script: &str) -> PathBuf {
std::fs::write( std::fs::write(
&manifest, &manifest,
format!( format!(
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0"}}}}"# r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","requires":{{"api_revision":1}}}}"#
), ),
) )
.unwrap(); .unwrap();
@@ -120,7 +122,7 @@ fn repo_root() -> PathBuf {
} }
/// Compile one of the checked-in independent consumer samples and package it /// Compile one of the checked-in independent consumer samples and package it
/// as a Tool Protocol v1 bundle. Sources live in `examples/tool-samples/` so /// as a CLI Tool bundle. Sources live in `examples/tool-samples/` so
/// they are reviewable software, not hidden test strings. /// they are reviewable software, not hidden test strings.
fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf { fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
let root = repo_root(); let root = repo_root();
@@ -137,20 +139,18 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
.status() .status()
.expect("run rustc for the sample tool"); .expect("run rustc for the sample tool");
assert!(status.success(), "rustc failed for {command}"); assert!(status.success(), "rustc failed for {command}");
let entrypoint = format!("bin/{command}{}", std::env::consts::EXE_SUFFIX);
let manifest = package.join("tool.json"); let manifest = package.join("tool.json");
std::fs::write( let template = root.join(format!("examples/tool-samples/{command}/tool.json"));
&manifest, let mut document: serde_json::Value =
format!( serde_json::from_slice(&std::fs::read(template).unwrap()).unwrap();
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0","analysis":[2],"trace":[2]}}}}"# document["entrypoint"] =
), serde_json::json!(format!("bin/{command}{}", std::env::consts::EXE_SUFFIX));
) std::fs::write(&manifest, document.to_string()).unwrap();
.unwrap();
manifest manifest
} }
#[test] #[test]
fn independent_sample_tools_consume_public_analysis_and_trace() { fn independent_sample_tools_consume_public_analysis_and_observation() {
let dir = TempDir::new("samples"); let dir = TempDir::new("samples");
let home = dir.path().join("home"); let home = dir.path().join("home");
let analysis = dir.path().join("analysis.json"); let analysis = dir.path().join("analysis.json");
@@ -170,7 +170,11 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
.expect("run check"); .expect("run check");
assert!(check.status.success(), "check failed: {}", stderr(&check)); assert!(check.status.success(), "check failed: {}", stderr(&check));
let run = Command::new(binary()) let run = Command::new(binary())
.args(["run", "examples/multi-module/index.mq.md", "--trace-file"]) .args([
"run",
"examples/multi-module/index.mq.md",
"--observation-file",
])
.arg(&trace) .arg(&trace)
.current_dir(&root) .current_dir(&root)
.output() .output()
@@ -200,22 +204,22 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
assert_eq!(view.status.code(), Some(0), "{}", stderr(&view)); assert_eq!(view.status.code(), Some(0), "{}", stderr(&view));
let text = stdout(&view); let text = stdout(&view);
assert!( assert!(
text.contains("sample-view schema=marqdo.analysis version=2"), text.contains("sample-view schema=marqdo.analysis version=3"),
"{text}" "{text}"
); );
assert!(text.contains("modules="), "{text}"); assert!(text.contains("modules="), "{text}");
let knowledge = cli( let knowledge = cli(
&home, &home,
&["sample-knowledge", "--trace", trace.to_str().unwrap()], &["sample-knowledge", "--analysis", analysis.to_str().unwrap()],
); );
assert_eq!(knowledge.status.code(), Some(0), "{}", stderr(&knowledge)); assert_eq!(knowledge.status.code(), Some(0), "{}", stderr(&knowledge));
let text = stdout(&knowledge); let text = stdout(&knowledge);
assert!( assert!(
text.contains("sample-knowledge schema=marqdo.trace version=2"), text.contains("sample-knowledge schema=marqdo.analysis version=3"),
"{text}" "{text}"
); );
assert!(text.contains("status=ok"), "{text}"); assert!(text.contains("reference_sets="), "{text}");
let proof = cli( let proof = cli(
&home, &home,
@@ -223,14 +227,20 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
"sample-proof", "sample-proof",
"--analysis", "--analysis",
analysis.to_str().unwrap(), analysis.to_str().unwrap(),
"--trace", "--observation",
trace.to_str().unwrap(), trace.to_str().unwrap(),
], ],
); );
assert_eq!(proof.status.code(), Some(0), "{}", stderr(&proof)); assert_eq!(proof.status.code(), Some(0), "{}", stderr(&proof));
let text = stdout(&proof); let text = stdout(&proof);
assert!(text.contains("sample-proof bound=true"), "{text}"); let digest = format!(
assert!(text.contains("digest=sha256:"), "{text}"); "sha256:{:x}",
sha2::Sha256::digest(std::fs::read(&analysis).unwrap())
);
assert!(
text.contains(&format!("sample-proof claimed_digest={digest}")),
"{text}"
);
for command in ["sample-view", "sample-knowledge", "sample-proof"] { for command in ["sample-view", "sample-knowledge", "sample-proof"] {
let removed = cli(&home, &["tool", "remove", command]); let removed = cli(&home, &["tool", "remove", command]);
@@ -245,7 +255,7 @@ fn install_dispatch_list_remove_without_core_knowledge_of_the_name() {
let manifest = write_tool( let manifest = write_tool(
dir.path(), dir.path(),
"benchmark", "benchmark",
"#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_TOOL_PROTOCOL\"\nexit 7\n", "#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_API_REVISION\"\nexit 7\n",
); );
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
@@ -301,7 +311,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
let incompatible = std::fs::read_to_string(&manifest) let incompatible = std::fs::read_to_string(&manifest)
.unwrap() .unwrap()
.replace(">=3.0.0-beta.1,<4.0.0", ">=99.0"); .replace("\"api_revision\":1", "\"api_revision\":99");
let incompatible_manifest = dir.path().join("incompatible.json"); let incompatible_manifest = dir.path().join("incompatible.json");
std::fs::write(&incompatible_manifest, incompatible).unwrap(); std::fs::write(&incompatible_manifest, incompatible).unwrap();
let output = cli( let output = cli(
@@ -309,7 +319,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
&["tool", "install", incompatible_manifest.to_str().unwrap()], &["tool", "install", incompatible_manifest.to_str().unwrap()],
); );
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("requires marqdo")); assert!(stderr(&output).contains("requires api_revision"));
} }
#[test] #[test]
@@ -355,47 +365,61 @@ fn tampered_binary_and_path_hijack_are_not_executed() {
} }
#[test] #[test]
fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() { fn tool_requires_exact_current_protocols_and_rejects_retired_registrations() {
use serde_json::json;
let dir = TempDir::new("protocols"); let dir = TempDir::new("protocols");
let home = dir.path().join("home"); let home = dir.path().join("home");
let manifest = write_tool( let manifest = write_tool(dir.path(), "proto", "");
dir.path(), let mut document: serde_json::Value =
"proto", serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
"#!/bin/sh\nprintf 'analysis=%s\\ntrace=%s\\n' \"$MARQDO_PROTOCOL_ANALYSIS\" \"$MARQDO_PROTOCOL_TRACE\"\n", for (requires, expected) in [
); (
let text = std::fs::read_to_string(&manifest).unwrap().replace( json!({"api_revision": 1, "analysis": [3]}),
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"", "invalid tool.json",
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",\"analysis\":[2],\"trace\":[2]", ),
); (
std::fs::write(&manifest, text).unwrap(); json!({"api_revision": 1, "analysis": null}),
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); "invalid tool.json",
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install)); ),
let output = cli(&home, &["proto"]); (
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output)); json!({"api_revision": 1, "analysis": 2}),
let text = stdout(&output); "tool.protocol_incompatible",
assert!(text.contains("analysis=2"), "{text}"); ),
assert!(text.contains("trace=2"), "{text}"); (
json!({"api_revision": 1, "observation": 99}),
for (compat, tag) in [ "tool.protocol_incompatible",
("\"analysis\":[99]", "analysis-disjoint"), ),
("\"analysis\":[]", "analysis-empty"),
("\"trace\":[9]", "trace-disjoint"),
] { ] {
let command = format!("bad-{tag}"); document["requires"] = requires;
let manifest = write_tool(dir.path(), &command, "#!/bin/sh\nexit 0\n"); std::fs::write(&manifest, document.to_string()).unwrap();
let text = std::fs::read_to_string(&manifest).unwrap().replace(
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"",
&format!("\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",{compat}"),
);
std::fs::write(&manifest, text).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]); let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1), "{tag}"); assert_eq!(output.status.code(), Some(1));
assert!( assert!(stderr(&output).contains(expected), "{}", stderr(&output));
stderr(&output).contains("protocol_incompatible"),
"{tag}: {}",
stderr(&output)
);
} }
document.as_object_mut().unwrap().remove("requires");
document["compatibility"] = json!({"analysis": [2, 3]});
std::fs::write(&manifest, document.to_string()).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("invalid tool.json"));
document.as_object_mut().unwrap().remove("compatibility");
document["requires"] = json!({"api_revision": 1, "analysis": 3, "observation": 1});
std::fs::write(&manifest, document.to_string()).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(cli(&home, &["proto"]).status.code(), Some(7));
let record = home.join("proto/record.json");
let mut installed: serde_json::Value =
serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
installed.as_object_mut().unwrap().remove("requires");
installed["compatibility"] = json!({"analysis": [2, 3]});
std::fs::write(&record, installed.to_string()).unwrap();
let output = cli(&home, &["proto"]);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("Remove and reinstall"));
assert!(cli(&home, &["tool", "remove", "proto"]).status.success());
} }
#[test] #[test]
@@ -449,41 +473,3 @@ fn a_root_record_json_in_the_source_package_is_rejected() {
assert_eq!(output.status.code(), Some(1)); assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("must not contain a root record.json")); assert!(stderr(&output).contains("must not contain a root record.json"));
} }
#[test]
fn prerelease_core_requires_an_explicit_prerelease_compatible_range() {
let dir = TempDir::new("prerelease-range");
let home = dir.path().join("home");
let core = env!("CARGO_PKG_VERSION");
for (range, compatible) in [
(">=3.0.0-beta.1,<4.0.0".to_string(), true),
(format!("={core}"), true),
(">=3.0.0,<4.0.0".to_string(), !core.contains('-')),
(">=0.1,<1".to_string(), false),
] {
let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n");
let text = std::fs::read_to_string(&manifest)
.unwrap()
.replace(">=3.0.0-beta.1,<4.0.0", &range);
std::fs::write(&manifest, text).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(
output.status.success(),
compatible,
"{range} on {core}: {}",
stderr(&output)
);
if compatible {
assert!(cli(&home, &["tool", "remove", "prerelease"])
.status
.success());
} else {
assert!(
stderr(&output).contains("requires marqdo"),
"{}",
stderr(&output)
);
}
}
}
+58 -4
View File
@@ -2,7 +2,7 @@
//! //!
//! One Markdown carrier holds exactly one payload. This module is the only //! One Markdown carrier holds exactly one payload. This module is the only
//! place that decides whether that payload is a control statement //! place that decides whether that payload is a control statement
//! (`if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an //! (`if`/`else if`/`else`/`while`/`break`/`continue`/`end`/`return`), a `params(...)` declaration, or an
//! ordinary assignment/expression. The frontend still owns pairing the control //! ordinary assignment/expression. The frontend still owns pairing the control
//! words into blocks; this module owns their lexical recognition and the //! words into blocks; this module owns their lexical recognition and the
//! expression grammar they embed. //! expression grammar they embed.
@@ -22,10 +22,16 @@ use marqdo_span::Span;
pub enum PayloadStatement { pub enum PayloadStatement {
/// `if <expr>` /// `if <expr>`
If(Expr), If(Expr),
/// `else if <expr>`
ElseIf(Expr),
/// `else` (no expression) /// `else` (no expression)
Else, Else,
/// `while <expr>` /// `while <expr>`
While(Expr), While(Expr),
/// Exit the closest enclosing loop.
Break,
/// Recheck the closest enclosing loop condition.
Continue,
/// `end` (no expression) /// `end` (no expression)
End, End,
/// `return <expr>` /// `return <expr>`
@@ -65,7 +71,12 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
let tokens = lexer::tokenize(trimmed)?; let tokens = lexer::tokenize(trimmed)?;
let first = tokens.first().expect("tokenize always returns EOF"); let first = tokens.first().expect("tokenize always returns EOF");
match first.kind { match &first.kind {
TokenKind::Ident(name) if matches!(tokens[1].kind, TokenKind::Eof) => match name.as_str() {
"break" => Ok(PayloadStatement::Break),
"continue" => Ok(PayloadStatement::Continue),
_ => parse_statement(trimmed).map(PayloadStatement::Ordinary),
},
TokenKind::If => { TokenKind::If => {
let expr = control_expression(trimmed, first.span, "if")?; let expr = control_expression(trimmed, first.span, "if")?;
Ok(PayloadStatement::If(expr)) Ok(PayloadStatement::If(expr))
@@ -79,6 +90,11 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
Ok(PayloadStatement::Return(expr)) Ok(PayloadStatement::Return(expr))
} }
TokenKind::Else => { TokenKind::Else => {
if matches!(tokens[1].kind, TokenKind::If) {
let keyword = Span::new(first.span.start, tokens[1].span.end);
let expr = control_expression(trimmed, keyword, "else if")?;
return Ok(PayloadStatement::ElseIf(expr));
}
require_only_keyword(&tokens, "else")?; require_only_keyword(&tokens, "else")?;
Ok(PayloadStatement::Else) Ok(PayloadStatement::Else)
} }
@@ -128,6 +144,7 @@ mod tests {
fn expr_of(source: &str) -> Expr { fn expr_of(source: &str) -> Expr {
match parse_payload_statement(source).expect("valid payload") { match parse_payload_statement(source).expect("valid payload") {
PayloadStatement::If(expr) PayloadStatement::If(expr)
| PayloadStatement::ElseIf(expr)
| PayloadStatement::While(expr) | PayloadStatement::While(expr)
| PayloadStatement::Return(expr) => expr, | PayloadStatement::Return(expr) => expr,
other => panic!("unexpected payload: {other:?}"), other => panic!("unexpected payload: {other:?}"),
@@ -136,7 +153,7 @@ mod tests {
#[test] #[test]
fn parses_control_statements_with_payload_relative_spans() { fn parses_control_statements_with_payload_relative_spans() {
for keyword in ["if", "while", "return"] { for keyword in ["if", "else if", "while", "return"] {
let source = format!("{keyword} x > 0"); let source = format!("{keyword} x > 0");
let expr = expr_of(&source); let expr = expr_of(&source);
assert_eq!(expr.span().start, keyword.len() + 1); assert_eq!(expr.span().start, keyword.len() + 1);
@@ -159,7 +176,16 @@ mod tests {
#[test] #[test]
fn keywords_require_whitespace_and_an_expression() { fn keywords_require_whitespace_and_an_expression() {
for source in ["if", "while", "return", "if(x)", "while(1)", "return(x)"] { for source in [
"if",
"else if",
"while",
"return",
"if(x)",
"else if(x)",
"while(1)",
"return(x)",
] {
assert!( assert!(
parse_payload_statement(source).is_err(), parse_payload_statement(source).is_err(),
"{source} must be rejected" "{source} must be rejected"
@@ -167,9 +193,37 @@ mod tests {
} }
} }
#[test]
fn loop_control_keywords_are_contextual() {
assert_eq!(
parse_payload_statement("break").unwrap(),
PayloadStatement::Break
);
assert_eq!(
parse_payload_statement("continue").unwrap(),
PayloadStatement::Continue
);
for source in [
"break(1)",
"continue = 1",
"(break)",
"break + continue",
"continue_work()",
] {
assert!(matches!(
parse_payload_statement(source).unwrap(),
PayloadStatement::Ordinary(_)
));
}
for source in ["break 2", "continue outer", "break if true"] {
assert!(parse_payload_statement(source).is_err(), "{source}");
}
}
#[test] #[test]
fn control_expressions_must_consume_the_payload() { fn control_expressions_must_consume_the_payload() {
assert!(parse_payload_statement("if x > 0:").is_err()); assert!(parse_payload_statement("if x > 0:").is_err());
assert!(parse_payload_statement("else if x > 0:").is_err());
assert!(parse_payload_statement("if x y").is_err()); assert!(parse_payload_statement("if x y").is_err());
} }
+5 -1
View File
@@ -213,7 +213,10 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
} }
} }
Stmt::Loop { body, .. } => collect_assigned(body, out), Stmt::Loop { body, .. } => collect_assigned(body, out),
Stmt::Eval { .. } | Stmt::Return { .. } => {} Stmt::Eval { .. }
| Stmt::Return { .. }
| Stmt::Break { .. }
| Stmt::Continue { .. } => {}
} }
} }
} }
@@ -257,6 +260,7 @@ impl<'a> Binder<'a> {
self.expr(condition); self.expr(condition);
self.stmts(body); self.stmts(body);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+151 -102
View File
@@ -3,16 +3,12 @@
//! Parameters come only from free reads of executable expressions. Prose, //! Parameters come only from free reads of executable expressions. Prose,
//! headings, inert code spans and natural language never introduce parameters. //! headings, inert code spans and natural language never introduce parameters.
//! //!
//! The analysis tracks, for every program point: //! Each reachable path tracks definite and possible assignments. Sequences
//! * `must` – variables definitely assigned on every path from entry; //! merge fallthrough, break and continue separately, so a transfer never
//! * `may` – variables assigned on at least one path; //! contributes bindings from the statements it skips. A return ends the path.
//! * `ambiguous` – variables that may have been assigned before the read on
//! some path but not on all paths, which makes the variable's identity
//! ambiguous (blueprint S-04) rather than silently inventing a parameter.
//! //!
//! Loop bodies get special treatment: their first iteration starts from the //! The first iteration starts from the pre-loop state. A first read before a
//! pre-loop state, so a read of an entry variable inside a loop is a parameter //! body assignment can therefore still be a parameter (the counter case).
//! candidate even though the body also assigns it (the classic counter case).
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -45,7 +41,6 @@ pub struct ParamCandidate {
struct State { struct State {
must: BTreeSet<String>, must: BTreeSet<String>,
may: BTreeSet<String>, may: BTreeSet<String>,
ambiguous: BTreeSet<String>,
} }
impl State { impl State {
@@ -53,18 +48,46 @@ impl State {
State { State {
must: self.must.intersection(&other.must).cloned().collect(), must: self.must.intersection(&other.must).cloned().collect(),
may: self.may.union(&other.may).cloned().collect(), may: self.may.union(&other.may).cloned().collect(),
ambiguous: self.ambiguous.union(&other.ambiguous).cloned().collect(),
} }
} }
} }
/// Join only reachable paths. An absent path contributes no assignments.
fn merge_paths(left: &mut Option<State>, right: Option<State>) {
if let Some(right) = right {
*left = Some(match left.take() {
Some(left) => left.join(&right),
None => right,
});
}
}
#[derive(Default)]
struct Flow {
next: Option<State>,
breaks: Option<State>,
continues: Option<State>,
}
impl Flow {
fn merge(&mut self, other: Self) {
merge_paths(&mut self.next, other.next);
self.merge_loop_transfers(other.breaks, other.continues);
}
fn merge_loop_transfers(&mut self, breaks: Option<State>, continues: Option<State>) {
merge_paths(&mut self.breaks, breaks);
merge_paths(&mut self.continues, continues);
}
}
struct Analyzer<'a> { struct Analyzer<'a> {
/// Names that are parameters/locals/builtins/imports and therefore never /// Names that are parameters/locals/builtins/imports and therefore never
/// reported as unknown; used for explicit signatures. /// reported as unknown; used for explicit signatures.
known: Option<&'a BTreeSet<String>>, known: Option<&'a BTreeSet<String>>,
reads: BTreeMap<String, Span>, reads: BTreeMap<String, Span>,
diagnostics: Vec<Diagnostic>, diagnostics: Vec<Diagnostic>,
ambiguous_reported: BTreeSet<String>, ambiguous_reads: BTreeMap<String, Span>,
unknown_reported: BTreeSet<String>, unknown_reported: BTreeSet<String>,
} }
@@ -74,7 +97,7 @@ impl<'a> Analyzer<'a> {
known, known,
reads: BTreeMap::new(), reads: BTreeMap::new(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
ambiguous_reported: BTreeSet::new(), ambiguous_reads: BTreeMap::new(),
unknown_reported: BTreeSet::new(), unknown_reported: BTreeSet::new(),
} }
} }
@@ -83,20 +106,8 @@ impl<'a> Analyzer<'a> {
if state.must.contains(name) { if state.must.contains(name) {
return; return;
} }
if state.ambiguous.contains(name) { if state.may.contains(name) {
if !self.ambiguous_reported.contains(name) { self.ambiguous_reads.entry(name.to_string()).or_insert(span);
self.ambiguous_reported.insert(name.to_string());
self.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNINITIALIZED,
Some(span),
format!("`{name}` may be read before it is assigned"),
)
.with_hint(
"assign it on every path before this read, or pass it in as a parameter",
),
);
}
return; return;
} }
if let Some(known) = self.known { if let Some(known) = self.known {
@@ -169,107 +180,104 @@ impl<'a> Analyzer<'a> {
} }
} }
fn assign(&self, name: &str, state: &mut State) { fn analyze_stmts(&mut self, stmts: &[Stmt], state: State) -> Flow {
state.must.insert(name.to_string()); let mut flow = Flow {
state.may.insert(name.to_string()); next: Some(state),
state.ambiguous.insert(name.to_string()); ..Flow::default()
} };
fn analyze_stmts(&mut self, stmts: &[Stmt], mut state: State) -> State {
for stmt in stmts { for stmt in stmts {
state = match stmt { let Some(mut state) = flow.next.take() else {
break;
};
flow.next = match stmt {
Stmt::Assign { target, value, .. } => { Stmt::Assign { target, value, .. } => {
match target { match target {
PlaceTarget::Local { name, .. } => { PlaceTarget::Local { name, .. } => {
// Preserve v1 order: the RHS is read before the
// local rebinding makes the name definitely
// assigned.
self.read_expr(value, &state); self.read_expr(value, &state);
self.assign(name, &mut state); state.must.insert(name.clone());
state.may.insert(name.clone());
} }
PlaceTarget::Index { base, index, .. } => { PlaceTarget::Index { base, index, .. } => {
// Runtime order for an index place is base, index, // Keep the runtime's evaluation order.
// RHS; reads in the place are free reads like any
// other.
self.read_expr(base, &state); self.read_expr(base, &state);
self.read_expr(index, &state); self.read_expr(index, &state);
self.read_expr(value, &state); self.read_expr(value, &state);
} }
} }
state Some(state)
} }
Stmt::Eval { expr, .. } => { Stmt::Eval { expr, .. } => {
self.read_expr(expr, &state); self.read_expr(expr, &state);
state Some(state)
} }
Stmt::Return { value, .. } => { Stmt::Return { value, .. } => {
self.read_expr(value, &state); self.read_expr(value, &state);
state None
}
Stmt::Break { .. } => {
merge_paths(&mut flow.breaks, Some(state));
None
}
Stmt::Continue { .. } => {
merge_paths(&mut flow.continues, Some(state));
None
}
Stmt::Branch { arms, .. } => {
let branch = self.analyze_branch(arms, state);
flow.merge_loop_transfers(branch.breaks, branch.continues);
branch.next
} }
Stmt::Branch { arms, .. } => self.analyze_branch(arms, state),
Stmt::Loop { Stmt::Loop {
condition, body, .. condition, body, ..
} => { } => self.analyze_loop(condition, body, state),
self.read_expr(condition, &state);
// First iteration starts from the pre-loop state: body
// assignments must not flag pre-loop reads as ambiguous.
let body_out = self.analyze_stmts(
body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
State {
must: state.must.clone(),
may: body_out
.may
.union(&state.may)
.cloned()
.collect::<BTreeSet<_>>(),
ambiguous: body_out
.ambiguous
.union(&state.ambiguous)
.cloned()
.collect::<BTreeSet<_>>(),
}
}
}; };
} }
state flow
} }
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> State { fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> Flow {
// Conditions are evaluated in order against the incoming state. let mut flow = Flow::default();
for arm in arms { for arm in arms {
// Only earlier false conditions lead to this arm. Conditions do
// not change the assignment state of the current frame.
self.read_expr(&arm.condition, &state); self.read_expr(&arm.condition, &state);
if arm.condition != Expr::Bool(false) {
flow.merge(self.analyze_stmts(&arm.body, state.clone()));
}
if arm.condition == Expr::Bool(true) {
return flow;
}
} }
// The branch may match no arm, so the incoming state joins every arm's merge_paths(&mut flow.next, Some(state));
// state; variables assigned only inside an arm stay "may assigned". flow
let mut joined: Option<State> = Some(State { }
must: state.must.clone(),
may: state.may.clone(), fn analyze_loop(&mut self, condition: &Expr, body: &[Stmt], state: State) -> Option<State> {
ambiguous: state.ambiguous.clone(), self.read_expr(condition, &state);
}); if *condition == Expr::Bool(false) {
for arm in arms { return Some(state);
let arm_out = self.analyze_stmts(
&arm.body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
joined = Some(match joined {
None => arm_out,
Some(previous) => previous.join(&arm_out),
});
} }
match joined {
Some(joined) => joined, let Flow {
None => state, mut next,
mut breaks,
continues,
} = self.analyze_stmts(body, state.clone());
merge_paths(&mut next, continues);
// A later break can inherit assignments from an earlier iteration.
// It can also occur on the first, so only "may" gains those bindings.
if let (Some(breaks), Some(backedge)) = (&mut breaks, &next) {
breaks.may.extend(backedge.may.iter().cloned());
} }
if *condition == Expr::Bool(true) {
return breaks;
}
// A false condition may be seen before any iteration or after a
// backedge. A break exits directly and a return never reaches here.
merge_paths(&mut next, Some(state));
merge_paths(&mut next, breaks);
next
} }
} }
@@ -294,7 +302,34 @@ pub fn infer(
names names
}); });
let mut analyzer = Analyzer::new(known.as_ref()); let mut analyzer = Analyzer::new(known.as_ref());
analyzer.analyze_stmts(stmts, State::default()); let initial = signature.map_or_else(State::default, |signature| {
let bound: BTreeSet<_> = signature
.params
.iter()
.map(|param| param.name.clone())
.collect();
State {
must: bound.clone(),
may: bound,
}
});
analyzer.analyze_stmts(stmts, initial);
for (name, span) in analyzer.ambiguous_reads {
// A reachable free read makes the name an entry parameter throughout
// an inferred function, including before or after a local rebinding.
if !analyzer.reads.contains_key(&name) {
analyzer.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNINITIALIZED,
Some(span),
format!("`{name}` may be read before it is assigned"),
)
.with_hint(
"assign it on every path before this read, or pass it in as a parameter",
),
);
}
}
let mut params: Vec<ParamCandidate> = analyzer let mut params: Vec<ParamCandidate> = analyzer
.reads .reads
.iter() .iter()
@@ -391,7 +426,14 @@ mod tests {
}, },
ret("n"), ret("n"),
]; ];
assert_eq!(params(&stmts), vec!["n".to_string()]); let inference = infer(&stmts, None, &BTreeSet::new());
assert_eq!(inference.params[0].name, "n");
assert_eq!(inference.params.len(), 1);
assert!(
inference.diagnostics.is_empty(),
"{:?}",
inference.diagnostics
);
} }
#[test] #[test]
@@ -399,7 +441,7 @@ mod tests {
let stmts = vec![ let stmts = vec![
Stmt::Branch { Stmt::Branch {
arms: vec![BranchArm { arms: vec![BranchArm {
condition: parse_expression("true").unwrap(), condition: parse_expression("flag").unwrap(),
condition_span: Span::new(0, 0), condition_span: Span::new(0, 0),
body: vec![assign("x", "1")], body: vec![assign("x", "1")],
span: Span::new(0, 0), span: Span::new(0, 0),
@@ -409,7 +451,14 @@ mod tests {
ret("x"), ret("x"),
]; ];
let inference = infer(&stmts, None, &BTreeSet::new()); let inference = infer(&stmts, None, &BTreeSet::new());
assert!(inference.params.is_empty()); assert_eq!(
inference
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>(),
["flag"]
);
assert!(inference assert!(inference
.diagnostics .diagnostics
.iter() .iter()
+128 -92
View File
@@ -8,7 +8,7 @@
use marqdo_expression::{ use marqdo_expression::{
parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind, parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind,
}; };
use marqdo_ir::{PlaceTarget, Stmt}; use marqdo_ir::{BranchArm, PlaceTarget, Stmt};
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode}; use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic}; use marqdo_value::{codes, Diagnostic};
@@ -100,10 +100,10 @@ struct Mapper {
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stop { enum ArmContext {
End, Outside,
Else, Conditional,
Eof, Default,
} }
struct RawPayload { struct RawPayload {
@@ -139,14 +139,12 @@ impl Mapper {
self.extract(block, &mut raw, true); self.extract(block, &mut raw, true);
} }
let mut position = 0; let mut position = 0;
let (stmts, stop) = self.sequence(&raw, &mut position, false, false); let stmts = self.sequence(&raw, &mut position, ArmContext::Outside, false);
if stop != Stop::Eof { if let Some(node) = raw.get(position) {
// `sequence` leaves `position` on the stray `end` payload, so the // The only delimiter that can stop the segment is a stray `end`.
// diagnostic points at the keyword instead of the previous
// statement. A control frame may never close across a heading.
self.error( self.error(
codes::SEM_UNMATCHED_END, codes::SEM_UNMATCHED_END,
raw.get(position).map(|node| node.span), Some(node.span),
"`end` has no open `if`/`while` in this heading segment", "`end` has no open `if`/`while` in this heading segment",
); );
} }
@@ -215,7 +213,11 @@ impl Mapper {
return; return;
} }
if let Some(mut payload) = self.parse_payload(&text, &segments) { if let Some(mut payload) = self.parse_payload(&text, &segments) {
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload { if let Payload::If(expr)
| Payload::ElseIf(expr)
| Payload::While(expr)
| Payload::Return(expr) = &mut payload
{
segments.rewrite_expr(expr); segments.rewrite_expr(expr);
} }
out.push(RawPayload { out.push(RawPayload {
@@ -243,102 +245,78 @@ impl Mapper {
} }
} }
/// Read a body up to its next delimiter without consuming that delimiter.
fn sequence( fn sequence(
&mut self, &mut self,
nodes: &[RawPayload], nodes: &[RawPayload],
position: &mut usize, position: &mut usize,
stop_on_else: bool, arm: ArmContext,
in_else_body: bool, in_loop: bool,
) -> (Vec<Stmt>, Stop) { ) -> Vec<Stmt> {
let mut out = Vec::new(); let mut out = Vec::new();
while *position < nodes.len() { while let Some(raw) = nodes.get(*position) {
let raw = &nodes[*position];
match &raw.payload { match &raw.payload {
Payload::Else => { Payload::Else | Payload::ElseIf(_) => {
if stop_on_else { if arm == ArmContext::Conditional {
return (out, Stop::Else); break;
} }
self.error( let (code, message) = match (&raw.payload, arm) {
if in_else_body { (Payload::Else, ArmContext::Default) => {
codes::SEM_DUPLICATE_ELSE (codes::SEM_DUPLICATE_ELSE, "`if` has more than one `else`")
} else {
codes::SEM_UNMATCHED_ELSE
},
Some(raw.span),
if in_else_body {
"`if` has more than one `else`"
} else {
"`else` has no open `if`"
},
);
*position += 1;
}
Payload::End => {
return (out, Stop::End);
}
Payload::If(condition) => {
self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (then_body, stop) = self.sequence(nodes, position, true, false);
let mut else_body = Vec::new();
let finish = match stop {
Stop::Else => {
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, true);
else_body = body;
stop
} }
other => other, (Payload::Else, _) => {
(codes::SEM_UNMATCHED_ELSE, "`else` has no open `if`")
}
(_, ArmContext::Default) => (
codes::SEM_ELSE_IF_AFTER_ELSE,
"`else if` cannot follow the final `else`",
),
(_, _) => (codes::SEM_UNMATCHED_ELSE_IF, "`else if` has no open `if`"),
}; };
if finish != Stop::End { self.error(code, Some(raw.span), message);
self.error( *position += 1;
codes::SEM_UNCLOSED_CONTROL, }
Some(span), Payload::End => break,
"`if` is not closed by `end`", Payload::If(_) => {
); self.executed = true;
} else { out.push(self.branch(nodes, position, in_loop));
*position += 1;
}
let mut arms = vec![marqdo_ir::BranchArm {
condition,
condition_span: span,
body: then_body,
span,
}];
if !else_body.is_empty() {
arms.push(marqdo_ir::BranchArm {
condition: Expr::Bool(true),
condition_span: span,
body: else_body,
span,
});
}
out.push(Stmt::Branch { arms, span });
} }
Payload::While(condition) => { Payload::While(condition) => {
self.executed = true; self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1; *position += 1;
let (body, stop) = self.sequence(nodes, position, false, false); let body = self.sequence(nodes, position, ArmContext::Outside, true);
if stop != Stop::End { self.close_block(nodes, position, raw.span, "while");
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`while` is not closed by `end`",
);
} else {
*position += 1;
}
out.push(Stmt::Loop { out.push(Stmt::Loop {
condition, condition: condition.clone(),
condition_span: span, condition_span: raw.span,
body, body,
span, span: raw.span,
}); });
} }
Payload::Break | Payload::Continue => {
self.executed = true;
let span = raw.span;
let (statement, code, keyword) = match raw.payload {
Payload::Break => {
(Stmt::Break { span }, codes::SEM_BREAK_OUTSIDE_LOOP, "break")
}
_ => (
Stmt::Continue { span },
codes::SEM_CONTINUE_OUTSIDE_LOOP,
"continue",
),
};
if in_loop {
out.push(statement);
} else {
self.error(
code,
Some(span),
format!("`{keyword}` requires an open loop in this heading segment"),
);
}
*position += 1;
}
Payload::Return(value) => { Payload::Return(value) => {
self.executed = true; self.executed = true;
out.push(Stmt::Return { out.push(Stmt::Return {
@@ -406,6 +384,64 @@ impl Mapper {
} }
} }
} }
(out, Stop::Eof) out
}
fn branch(&mut self, nodes: &[RawPayload], position: &mut usize, in_loop: bool) -> Stmt {
let span = nodes[*position].span;
let mut arms = Vec::new();
while let Some(raw) = nodes.get(*position) {
let condition = match &raw.payload {
Payload::If(condition) | Payload::ElseIf(condition) => condition,
_ => break,
};
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Conditional, in_loop);
arms.push(BranchArm {
condition: condition.clone(),
condition_span: raw.span,
body,
span: raw.span,
});
}
if let Some(raw) = nodes
.get(*position)
.filter(|raw| matches!(raw.payload, Payload::Else))
{
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Default, in_loop);
// An empty fallback is ordinary fallthrough.
if !body.is_empty() {
arms.push(BranchArm {
condition: Expr::Bool(true),
condition_span: raw.span,
body,
span: raw.span,
});
}
}
self.close_block(nodes, position, span, "if");
Stmt::Branch { arms, span }
}
fn close_block(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
opener: Span,
keyword: &str,
) {
if matches!(
nodes.get(*position).map(|raw| &raw.payload),
Some(Payload::End)
) {
*position += 1;
} else {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(opener),
format!("`{keyword}` is not closed by `end`"),
);
}
} }
} }
+1
View File
@@ -13,6 +13,7 @@ libloading = { workspace = true }
rustls = { workspace = true } rustls = { workspace = true }
rustls-native-certs = { workspace = true } rustls-native-certs = { workspace = true }
marqdo-plugin-abi = { workspace = true } marqdo-plugin-abi = { workspace = true }
marqdo-worker-ipc = { workspace = true }
flate2 = { workspace = true } flate2 = { workspace = true }
getrandom = { workspace = true } getrandom = { workspace = true }
regex = { workspace = true } regex = { workspace = true }
+41 -150
View File
@@ -7,7 +7,7 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket}; use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant}; use std::time::Duration;
use marqdo_plugin_abi::{ use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest, ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
@@ -31,11 +31,9 @@ use crate::provider_worker::WorkerResourceProvider;
use crate::resource::{ use crate::resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider, is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
}; };
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode}; use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
mod dispatch; mod dispatch;
mod effects;
mod providers; mod providers;
mod resource_ops; mod resource_ops;
mod resource_requests; mod resource_requests;
@@ -182,29 +180,10 @@ pub trait Host {
/// Take the buffered program output. /// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>; fn take_output(&mut self) -> Vec<u8>;
/// Recorded effects.
fn trace(&self) -> &[TraceEntry];
/// Record one semantic event (Trace v1). Default: ignored.
fn record_semantic(
&mut self,
_kind: &str,
_function_id: Option<&str>,
_module_id: Option<&str>,
_span: Option<Span>,
_detail: Option<&str>,
) {
}
/// Recorded semantic events. Default: empty.
fn semantic_events(&self) -> &[SemanticEvent] {
&[]
}
/// Whether the host has an installed observation sink. /// Whether the host has an installed observation sink.
/// ///
/// The default host is inert; the interpreter uses this to skip building /// The default host is inert; the interpreter uses this to skip building
/// any observation event when the run has no `--event-stream`. /// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool { fn observation_enabled(&self) -> bool {
false false
} }
@@ -252,8 +231,6 @@ pub struct StdHost {
pub budget: Budget, pub budget: Budget,
/// Filesystem view. /// Filesystem view.
pub fs: ProjectFs, pub fs: ProjectFs,
/// Effect trace.
pub trace: EffectTrace,
/// Maximum wall-clock time for one foreign kernel call. /// Maximum wall-clock time for one foreign kernel call.
pub foreign_timeout: Duration, pub foreign_timeout: Duration,
/// Maximum captured bytes per foreign stream. /// Maximum captured bytes per foreign stream.
@@ -280,9 +257,6 @@ pub struct StdHost {
resources: ResourceTable, resources: ResourceTable,
/// Registered in-process providers keyed by resource kind (ADR-0033). /// Registered in-process providers keyed by resource kind (ADR-0033).
resource_providers: BTreeMap<String, (String, SharedResourceProvider)>, resource_providers: BTreeMap<String, (String, SharedResourceProvider)>,
semantic_events: Vec<SemanticEvent>,
next_event_seq: u64,
trace_state: TraceState,
observation: Option<ObservationState>, observation: Option<ObservationState>,
observation_error: Option<String>, observation_error: Option<String>,
} }
@@ -331,7 +305,6 @@ impl StdHost {
capabilities, capabilities,
budget: Budget::default(), budget: Budget::default(),
fs: ProjectFs::new(project_root), fs: ProjectFs::new(project_root),
trace: EffectTrace::default(),
foreign_timeout: Duration::from_secs(10), foreign_timeout: Duration::from_secs(10),
foreign_output_limit: 1024 * 1024, foreign_output_limit: 1024 * 1024,
kernel_registry: marqdo_foreign::KernelRegistry::builtin(), kernel_registry: marqdo_foreign::KernelRegistry::builtin(),
@@ -346,9 +319,6 @@ impl StdHost {
stderr: Vec::new(), stderr: Vec::new(),
resources: ResourceTable::new(), resources: ResourceTable::new(),
resource_providers: BTreeMap::new(), resource_providers: BTreeMap::new(),
semantic_events: Vec::new(),
next_event_seq: 0,
trace_state: TraceState::default(),
observation: None, observation: None,
observation_error: None, observation_error: None,
} }
@@ -502,22 +472,6 @@ impl StdHost {
exports exports
} }
/// Recorded semantic events (Trace v1).
pub fn semantic_events(&self) -> &[SemanticEvent] {
&self.semantic_events
}
/// Trace capacity state for the writer.
pub fn trace_state(&self) -> &TraceState {
&self.trace_state
}
/// Override the trace event/byte budget.
pub fn with_trace_budget(mut self, budget: TraceBudget) -> Self {
self.trace_state.budget = budget;
self
}
/// Audited plugin capability decisions. /// Audited plugin capability decisions.
pub fn capability_audit(&self) -> Vec<CapabilityAudit> { pub fn capability_audit(&self) -> Vec<CapabilityAudit> {
self.broker_audit self.broker_audit
@@ -536,13 +490,6 @@ impl StdHost {
}) })
} }
/// Enable effect tracing.
pub fn with_trace(mut self) -> Self {
self.trace = EffectTrace::enabled();
self.trace_state.enabled = true;
self
}
/// Install the typed observation sink and policy (RFC-OBS-0001). /// Install the typed observation sink and policy (RFC-OBS-0001).
/// ///
/// Without this call the host has no observation state: it does not /// Without this call the host has no observation state: it does not
@@ -617,8 +564,13 @@ impl StdHost {
result_code: &str, result_code: &str,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) { ) {
let frame_id = self
.observation
.as_ref()
.and_then(ObservationState::parent_frame);
let result = self.emit_observation( let result = self.emit_observation(
ObservationEvent::Effect { ObservationEvent::Effect {
frame_id,
operation, operation,
result_code, result_code,
module_id: &ctx.module_id, module_id: &ctx.module_id,
@@ -777,26 +729,8 @@ impl Host for StdHost {
max_bytes: usize, max_bytes: usize,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> { ) -> Result<ResourceRead, RuntimeError> {
let started = Instant::now();
let kind = self.resources.kind(handle, ctx.span)?;
let read = self.resources.read(handle, max_bytes, ctx.span)?; let read = self.resources.read(handle, max_bytes, ctx.span)?;
self.record_semantic( self.observe_effect("resource.read", "ok", ctx);
"resource.read",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!(
"kind={kind} count={} eof={}",
read.bytes.len(),
read.eof
)),
);
self.record_resource_effect(
"resource.read",
ctx,
started,
&format!("kind={kind} count={}", read.bytes.len()),
);
Ok(read) Ok(read)
} }
@@ -806,7 +740,6 @@ impl Host for StdHost {
bytes: &[u8], bytes: &[u8],
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> { ) -> Result<usize, RuntimeError> {
let started = Instant::now();
let kind = self.resources.kind(handle, ctx.span)?; let kind = self.resources.kind(handle, ctx.span)?;
let stdio = self.resources.stdio_name(handle, ctx.span)?; let stdio = self.resources.stdio_name(handle, ctx.span)?;
let count = self.resources.write(handle, bytes, ctx.span)?; let count = self.resources.write(handle, bytes, ctx.span)?;
@@ -829,19 +762,7 @@ impl Host for StdHost {
self.emit_observation(event, true)?; self.emit_observation(event, true)?;
} }
} }
self.record_semantic( self.observe_effect("resource.write", "ok", ctx);
"resource.write",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={kind} count={count}")),
);
self.record_resource_effect(
"resource.write",
ctx,
started,
&format!("kind={kind} count={count}"),
);
Ok(count) Ok(count)
} }
@@ -850,29 +771,11 @@ impl Host for StdHost {
handle: ResourceHandle, handle: ResourceHandle,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<(), RuntimeError> { ) -> Result<(), RuntimeError> {
let started = Instant::now(); if let Some((relative, bytes)) = self.resources.pending_file_write(handle, ctx.span)? {
let pending = self.resources.pending_file_write(handle, ctx.span)?; self.fs.write_bytes(&relative, &bytes, ctx.span)?;
let count = match pending { }
Some((relative, bytes)) => {
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
bytes.len()
}
None => 0,
};
self.resources.close(handle, ctx.span)?; self.resources.close(handle, ctx.span)?;
self.record_semantic( self.observe_effect("resource.close", "ok", ctx);
"resource.close",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("flushed_bytes={count}")),
);
self.record_resource_effect(
"resource.close",
ctx,
started,
&format!("flushed_bytes={count}"),
);
Ok(()) Ok(())
} }
@@ -881,16 +784,8 @@ impl Host for StdHost {
handle: ResourceHandle, handle: ResourceHandle,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> { ) -> Result<Value, RuntimeError> {
let started = Instant::now();
let accepted = self.resources.accept(handle, ctx.span)?; let accepted = self.resources.accept(handle, ctx.span)?;
self.record_semantic( self.observe_effect("resource.accept", "ok", ctx);
"resource.accept",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=tcp-listener"),
);
self.record_resource_effect("resource.accept", ctx, started, "ok");
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::Resource(accepted)); map.insert("value".to_string(), Value::Resource(accepted));
@@ -990,6 +885,14 @@ impl Host for StdHost {
return Ok(()); return Ok(());
} }
match event { match event {
RuntimeObservation::Effect {
operation,
module_id,
span,
} => {
self.observe_effect(operation, "ok", &ExecutionContext::new(module_id, span));
Ok(())
}
RuntimeObservation::Return { RuntimeObservation::Return {
frame_id, frame_id,
value_type, value_type,
@@ -1047,6 +950,25 @@ impl Host for StdHost {
false, false,
) )
} }
RuntimeObservation::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => {
let Some(frame_id) = frame_id else {
return Ok(());
};
self.emit_observation(
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
},
false,
)
}
RuntimeObservation::VariableAssigned { RuntimeObservation::VariableAssigned {
frame_id, frame_id,
name, name,
@@ -1111,37 +1033,6 @@ impl Host for StdHost {
fn take_output(&mut self) -> Vec<u8> { fn take_output(&mut self) -> Vec<u8> {
std::mem::take(&mut self.output) std::mem::take(&mut self.output)
} }
fn trace(&self) -> &[TraceEntry] {
self.trace.entries()
}
fn record_semantic(
&mut self,
kind: &str,
function_id: Option<&str>,
module_id: Option<&str>,
span: Option<Span>,
detail: Option<&str>,
) {
let estimate = TraceState::estimate(kind, function_id, module_id, detail, None);
if !self.trace_state.accept(estimate) {
return;
}
let seq = self.next_seq();
self.semantic_events.push(SemanticEvent {
seq,
kind: kind.to_string(),
function_id: function_id.map(str::to_string),
module_id: module_id.map(str::to_string),
span,
detail: detail.map(str::to_string),
});
}
fn semantic_events(&self) -> &[SemanticEvent] {
&self.semantic_events
}
} }
fn map_plugin_error(error: PluginError) -> RuntimeError { fn map_plugin_error(error: PluginError) -> RuntimeError {
+5 -23
View File
@@ -1,7 +1,7 @@
//! `Host::invoke` dispatch table. //! `Host::invoke` dispatch table.
//! //!
//! Child module of `host`: it may call the parent's private capability, //! Child module of `host`: it may call the parent's private capability,
//! resource and trace helpers. `StdHost` remains the only host implementation. //! resource and observation helpers. `StdHost` remains the only host implementation.
use super::*; use super::*;
@@ -36,30 +36,12 @@ pub(crate) fn invoke(
), ),
)); ));
} }
let started = Instant::now();
let result = host.dispatch(op, args, ctx); let result = host.dispatch(op, args, ctx);
let summary = match &result { let result_code = match &result {
Ok(_) => "ok".to_string(), Ok(_) => "ok",
Err(error) => error.code().to_string(), Err(error) => error.code(),
}; };
let estimate = TraceState::estimate( host.observe_effect(op.name(), result_code, ctx);
"effect",
None,
Some(&ctx.module_id),
Some(&summary),
Some(op.name()),
);
if host.trace_state.accept(estimate) {
let seq = host.next_seq();
host.trace.record(
seq,
op.name(),
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary,
);
}
result result
} }
-44
View File
@@ -1,44 +0,0 @@
//! Trace/effect bookkeeping helpers for `StdHost`.
//!
//! Child module of `host`; it may use the parent's private trace state.
use super::*;
impl StdHost {
pub(crate) fn next_seq(&mut self) -> u64 {
let seq = self.next_event_seq;
self.next_event_seq += 1;
seq
}
pub(crate) fn record_resource_effect(
&mut self,
op: &str,
ctx: &ExecutionContext,
started: Instant,
summary: &str,
) {
let estimate = TraceState::estimate(
"effect",
None,
Some(&ctx.module_id),
Some(summary),
Some(op),
);
if !self.trace_state.accept(estimate) {
return;
}
let seq = self.next_seq();
self.trace.record(
seq,
op,
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary.to_string(),
);
// Executed regardless of Trace v2 being enabled: the two writers are
// independent observation outputs (RFC-OBS-0001 §4.6).
self.observe_effect(op, summary, ctx);
}
}
+8 -65
View File
@@ -38,7 +38,6 @@ impl StdHost {
rights: &[String], rights: &[String],
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> { ) -> Result<Value, RuntimeError> {
let started = Instant::now();
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect(); let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
if self.mode == SandboxMode::Strict { if self.mode == SandboxMode::Strict {
// stdio/stdout is the existing console channel already permitted by // stdio/stdout is the existing console channel already permitted by
@@ -89,14 +88,7 @@ impl StdHost {
"stdout" => self.resources.open_stdout(), "stdout" => self.resources.open_stdout(),
_ => unreachable!(), _ => unreachable!(),
}; };
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=stdio descriptor={descriptor}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
"file" => { "file" => {
@@ -105,28 +97,14 @@ impl StdHost {
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?; let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let bytes = self.fs.read_bytes(descriptor, ctx.span)?; let bytes = self.fs.read_bytes(descriptor, ctx.span)?;
let handle = self.resources.open_file(relative, bytes); let handle = self.resources.open_file(relative, bytes);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=read"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
return Ok(Value::Resource(handle)); return Ok(Value::Resource(handle));
} }
if requested == BTreeSet::from(["write"]) { if requested == BTreeSet::from(["write"]) {
self.capabilities.check_write(descriptor, ctx.span)?; self.capabilities.check_write(descriptor, ctx.span)?;
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?; let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let handle = self.resources.open_file_writer(relative); let handle = self.resources.open_file_writer(relative);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=write"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
return Ok(Value::Resource(handle)); return Ok(Value::Resource(handle));
} }
Err(RuntimeError::new( Err(RuntimeError::new(
@@ -184,14 +162,7 @@ impl StdHost {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5))); let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_tcp(stream); let handle = self.resources.open_tcp(stream);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
"tls" => { "tls" => {
@@ -284,14 +255,7 @@ impl StdHost {
})?; })?;
let stream = rustls::StreamOwned::new(connection, tcp); let stream = rustls::StreamOwned::new(connection, tcp);
let handle = self.resources.open_tls(stream); let handle = self.resources.open_tls(stream);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tls host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
"tcp-listener" => { "tcp-listener" => {
@@ -348,14 +312,7 @@ impl StdHost {
) )
})?; })?;
let handle = self.resources.open_tcp_listener(listener); let handle = self.resources.open_tcp_listener(listener);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp-listener host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
"udp" => { "udp" => {
@@ -416,14 +373,7 @@ impl StdHost {
let _ = socket.set_read_timeout(Some(Duration::from_secs(5))); let _ = socket.set_read_timeout(Some(Duration::from_secs(5)));
let _ = socket.set_write_timeout(Some(Duration::from_secs(5))); let _ = socket.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_udp(socket); let handle = self.resources.open_udp(socket);
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=udp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
other => { other => {
@@ -447,14 +397,7 @@ impl StdHost {
let handle = self let handle = self
.resources .resources
.open_provider(provider, other, descriptor, rights, ctx.span)?; .open_provider(provider, other, descriptor, rights, ctx.span)?;
self.record_semantic( self.observe_effect("resource.open", "ok", ctx);
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={other} provider={provider_name}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle)) Ok(Value::Resource(handle))
} }
} }
@@ -2,9 +2,9 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::time::{Instant, SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value}; use super::{ErrorCategory, ExecutionContext, RuntimeError, SandboxMode, StdHost, Value};
impl StdHost { impl StdHost {
pub(super) fn request_compatibility_operation( pub(super) fn request_compatibility_operation(
@@ -13,7 +13,6 @@ impl StdHost {
args: Vec<Value>, args: Vec<Value>,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> { ) -> Result<Value, RuntimeError> {
let started = Instant::now();
if self.mode != SandboxMode::Project { if self.mode != SandboxMode::Project {
return Err(RuntimeError::new( return Err(RuntimeError::new(
ErrorCategory::PermissionDenied, ErrorCategory::PermissionDenied,
@@ -72,14 +71,7 @@ impl StdHost {
self.capabilities.check_process(&program, ctx.span)?; self.capabilities.check_process(&program, ctx.span)?;
let result = let result =
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?; crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic( self.observe_effect("process.run", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
Ok(result) Ok(result)
} }
"regex.match" | "regex.captures" => { "regex.match" | "regex.captures" => {
@@ -116,14 +108,7 @@ impl StdHost {
)) ))
} }
}; };
self.record_semantic( self.observe_effect(operation, "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" { if operation == "regex.match" {
@@ -192,14 +177,7 @@ impl StdHost {
.into_iter() .into_iter()
.map(|byte| Value::int(byte as i64)) .map(|byte| Value::int(byte as i64))
.collect(); .collect();
self.record_semantic( self.observe_effect("compress.gzip", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values)); map.insert("value".to_string(), Value::List(values));
@@ -274,14 +252,7 @@ impl StdHost {
)) ))
} }
}; };
self.record_semantic( self.observe_effect("compress.gunzip", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text)); map.insert("value".to_string(), Value::text(text));
@@ -326,14 +297,7 @@ impl StdHost {
.into_iter() .into_iter()
.map(|byte| Value::int(byte as i64)) .map(|byte| Value::int(byte as i64))
.collect(); .collect();
self.record_semantic( self.observe_effect("random.bytes", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values)); map.insert("value".to_string(), Value::List(values));
@@ -385,14 +349,7 @@ impl StdHost {
); );
} }
} }
self.record_semantic( self.observe_effect("env.get", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
Ok(Value::Map(map)) Ok(Value::Map(map))
} }
"clock.now" => { "clock.now" => {
@@ -420,14 +377,7 @@ impl StdHost {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true)); map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis)); map.insert("value".to_string(), Value::int(millis));
self.record_semantic( self.observe_effect("clock.now", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
Ok(Value::Map(map)) Ok(Value::Map(map))
} }
"fs.read_at" => { "fs.read_at" => {
@@ -470,14 +420,7 @@ impl StdHost {
let result = self let result = self
.fs .fs
.request("read_at", &[path, offset, length], ctx.span)?; .request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic( self.observe_effect("fs.read_at", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
Ok(result) Ok(result)
} }
"fs.append" => { "fs.append" => {
@@ -507,14 +450,7 @@ impl StdHost {
}; };
self.capabilities.check_write(&path, ctx.span)?; self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?; let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic( self.observe_effect("fs.append", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
Ok(result) Ok(result)
} }
"fs.walk" => { "fs.walk" => {
@@ -537,14 +473,7 @@ impl StdHost {
}; };
self.capabilities.check_read(&path, ctx.span)?; self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?; let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic( self.observe_effect("fs.walk", "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
Ok(result) Ok(result)
} }
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => { "fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
@@ -587,19 +516,7 @@ impl StdHost {
_ => unreachable!(), _ => unreachable!(),
} }
let result = self.fs.request(name, &paths, ctx.span)?; let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic( self.observe_effect(&format!("fs.{name}"), "ok", ctx);
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect(
"resource.request",
ctx,
started,
&format!("fs.{name}"),
);
Ok(result) Ok(result)
} }
_ => { _ => {
+2 -4
View File
@@ -1,4 +1,4 @@
//! CapabilityHost: capability checks, resource budgets, effect tracing and the //! CapabilityHost: capability checks, resource budgets, observation and the
//! only bridge to math, foreign kernels, files and plugins. //! only bridge to math, foreign kernels, files and plugins.
//! //!
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks //! Blueprint §9 and §7.3: every side effect goes through this boundary, checks
@@ -17,7 +17,6 @@ mod process;
mod provider_c; mod provider_c;
mod provider_worker; mod provider_worker;
pub mod resource; pub mod resource;
pub mod trace;
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT}; pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
pub use capability::{ pub use capability::{
@@ -30,7 +29,7 @@ pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost}; pub use host::{arity, expect_text, Host, HostOp, 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, ObservationConfig, ObservationError, encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation, ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
@@ -39,4 +38,3 @@ pub use resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider, is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
CORE_RESOURCE_KINDS, CORE_RESOURCE_KINDS,
}; };
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
+43 -3
View File
@@ -4,7 +4,7 @@
//! interpreter and host emit at real commit points, the optional sink the CLI //! interpreter and host emit at real commit points, the optional sink the CLI
//! installs, the run-scoped frame identity and the bounded observation budget. //! installs, the run-scoped frame identity and the bounded observation budget.
//! It does **not** know JSONL, HTTP, SSE, View, agents or the public envelope; //! It does **not** know JSONL, HTTP, SSE, View, agents or the public envelope;
//! the CLI composes the public Execution Events v1 protocol from these events. //! the CLI composes the public Observation protocol from these events.
//! //!
//! Defaults are deliberately inert: no sink means no allocation and no //! Defaults are deliberately inert: no sink means no allocation and no
//! serialization. The facade never exposes `Frame.locals`, the whole //! serialization. The facade never exposes `Frame.locals`, the whole
@@ -193,8 +193,16 @@ pub enum ObservationEvent<'a> {
module_id: &'a str, module_id: &'a str,
span: Option<Span>, span: Option<Span>,
}, },
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: FrameId,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// The host completed a controlled effect attempt. /// The host completed a controlled effect attempt.
Effect { Effect {
frame_id: Option<FrameId>,
operation: &'a str, operation: &'a str,
result_code: &'a str, result_code: &'a str,
module_id: &'a str, module_id: &'a str,
@@ -230,12 +238,36 @@ 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`]. /// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
/// ///
/// Every variant carries an `Option<FrameId>`; observation of values and /// Value and control observations carry the owning call frame.
/// structural events only happens while a frame identity exists.
#[derive(Debug)] #[derive(Debug)]
pub enum RuntimeObservation<'a> { 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). /// A `return` statement committed (before the call exits).
Return { Return {
frame_id: Option<FrameId>, frame_id: Option<FrameId>,
@@ -257,6 +289,13 @@ pub enum RuntimeObservation<'a> {
module_id: &'a str, module_id: &'a str,
span: Option<Span>, 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. /// A local variable assignment committed.
VariableAssigned { VariableAssigned {
frame_id: Option<FrameId>, frame_id: Option<FrameId>,
@@ -498,6 +537,7 @@ pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
} }
ObservationEvent::BranchEval { module_id, .. } ObservationEvent::BranchEval { module_id, .. }
| ObservationEvent::LoopIteration { module_id, .. } | ObservationEvent::LoopIteration { module_id, .. }
| ObservationEvent::LoopTransfer { module_id, .. }
| ObservationEvent::Effect { module_id, .. } => { | ObservationEvent::Effect { module_id, .. } => {
add_text(module_id); add_text(module_id);
if let ObservationEvent::LoopIteration { decision, .. } = event { if let ObservationEvent::LoopIteration { decision, .. } = event {
+116 -99
View File
@@ -4,27 +4,30 @@
//! `__plugin-worker` command. It isolates crashes and keeps native code out of //! `__plugin-worker` command. It isolates crashes and keeps native code out of
//! the interpreter process. A plain process is **not** an OS sandbox; strict //! the interpreter process. A plain process is **not** an OS sandbox; strict
//! mode still refuses without a real isolation adapter. //! mode still refuses without a real isolation adapter.
//!
//! Framing, bounded reads, deadlines and teardown come from
//! [`marqdo_worker_ipc`]. The invoke/capability vocabulary, capability limit and
//! plugin error codes remain owned here: a shared transport never shares
//! capabilities.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::Path; use std::path::Path;
use std::process::{Child, ChildStdin, Command, Stdio}; use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, Receiver}; use std::time::{Duration, Instant};
use std::thread;
use std::time::Duration;
use marqdo_plugin_abi::worker::{ use marqdo_plugin_abi::worker::{
read_frame, write_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, WORKER_COMMAND, response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
WORKER_COMMAND,
}; };
use marqdo_plugin_abi::{ use marqdo_plugin_abi::{
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse, CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
}; };
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::json; use serde_json::json;
/// A native plugin running in an isolated worker process. /// A native plugin running in an isolated worker process.
pub struct WorkerPlugin { pub struct WorkerPlugin {
child: Child, connection: Connection,
stdin: ChildStdin,
frames: Receiver<Result<serde_json::Value, PluginError>>,
exports: BTreeMap<String, String>, exports: BTreeMap<String, String>,
dead: bool, dead: bool,
capability_handler: Option<CapabilityHandler>, capability_handler: Option<CapabilityHandler>,
@@ -36,7 +39,7 @@ const CALL_TIMEOUT: Duration = Duration::from_secs(10);
impl std::fmt::Debug for WorkerPlugin { impl std::fmt::Debug for WorkerPlugin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkerPlugin") f.debug_struct("WorkerPlugin")
.field("pid", &self.child.id()) .field("pid", &self.connection.id())
.field("exports", &self.exports.keys().collect::<Vec<_>>()) .field("exports", &self.exports.keys().collect::<Vec<_>>())
.finish() .finish()
} }
@@ -77,7 +80,7 @@ impl WorkerPlugin {
format!("cannot find the current executable: {error}"), format!("cannot find the current executable: {error}"),
) )
})?; })?;
let mut child = match Command::new(executable) let child: Child = match Command::new(executable)
.arg(WORKER_COMMAND) .arg(WORKER_COMMAND)
.arg(&manifest_path) .arg(&manifest_path)
.arg(base_dir) .arg(base_dir)
@@ -95,66 +98,33 @@ impl WorkerPlugin {
)); ));
} }
}; };
let Some(stdin) = child.stdin.take() else { let connection = match Connection::attach(child, MAX_FRAME_BYTES) {
let _ = child.kill(); Ok(connection) => connection,
return Err(PluginError::load( Err(error) => {
"worker_spawn_failed", let _ = std::fs::remove_file(&manifest_path);
"worker stdin unavailable", return Err(PluginError::load(
)); "worker_spawn_failed",
}; format!("cannot start plugin worker transport: {error}"),
let Some(mut stdout) = child.stdout.take() else { ));
let _ = child.kill(); }
let _ = std::fs::remove_file(&manifest_path);
return Err(PluginError::load(
"worker_spawn_failed",
"worker stdout unavailable",
));
}; };
let (sender, frames) = mpsc::channel(); let mut connection = connection;
thread::Builder::new() let ready = match connection.receive(Instant::now() + HANDSHAKE_TIMEOUT) {
.name("marqdo-plugin-worker-reader".to_string())
.spawn(move || loop {
match read_frame(&mut stdout) {
Ok(Some(frame)) => {
if sender.send(Ok(frame)).is_err() {
break;
}
}
Ok(None) => {
let _ = sender.send(Err(PluginError::invoke(
"plugin.crashed",
"plugin worker closed its output stream",
)));
break;
}
Err(error) => {
let _ = sender.send(Err(error));
break;
}
}
})
.map_err(|error| {
let _ = child.kill();
PluginError::load(
"worker_spawn_failed",
format!("cannot start worker reader: {error}"),
)
})?;
let ready = match frames.recv_timeout(HANDSHAKE_TIMEOUT) {
Ok(frame) => frame, Ok(frame) => frame,
Err(_) => { Err(TransportError::Timeout) => {
let _ = std::fs::remove_file(&manifest_path); let _ = std::fs::remove_file(&manifest_path);
let _ = child.kill();
return Err(PluginError::invoke( return Err(PluginError::invoke(
"plugin.timeout", "plugin.timeout",
"plugin worker handshake timed out", "plugin worker handshake timed out",
)); ));
} }
Err(error) => {
let _ = std::fs::remove_file(&manifest_path);
return Err(transport_error(error));
}
}; };
let _ = std::fs::remove_file(&manifest_path); let _ = std::fs::remove_file(&manifest_path);
let ready = ready?;
if ready.get("kind").and_then(serde_json::Value::as_str) != Some("ready") { if ready.get("kind").and_then(serde_json::Value::as_str) != Some("ready") {
let _ = child.kill();
return Err(PluginError::load( return Err(PluginError::load(
"worker_handshake_failed", "worker_handshake_failed",
"worker did not report ready", "worker did not report ready",
@@ -182,16 +152,13 @@ impl WorkerPlugin {
.collect(); .collect();
let actual: std::collections::BTreeSet<&str> = exports.keys().map(String::as_str).collect(); let actual: std::collections::BTreeSet<&str> = exports.keys().map(String::as_str).collect();
if declared != actual { if declared != actual {
let _ = child.kill();
return Err(PluginError::manifest( return Err(PluginError::manifest(
"worker_export_mismatch", "worker_export_mismatch",
"worker exports do not match the manifest", "worker exports do not match the manifest",
)); ));
} }
Ok(Self { Ok(Self {
child, connection,
stdin,
frames,
exports, exports,
dead: false, dead: false,
capability_handler, capability_handler,
@@ -208,36 +175,21 @@ impl WorkerPlugin {
} }
let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?) let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?)
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?; .map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
if let Err(error) = write_frame( let deadline = Instant::now() + CALL_TIMEOUT;
&mut self.stdin, if let Err(error) = self.connection.send(
&json!({"kind": "invoke", "request": request_value}), json!({"kind": "invoke", "request": request_value}),
deadline,
) { ) {
self.mark_dead(); self.mark_dead();
return Err(error); return Err(invocation_error(error));
} }
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
let mut capability_requests = 0usize; let mut capability_requests = 0usize;
loop { loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now()); let frame = match self.connection.receive(deadline) {
if remaining.is_zero() { Ok(frame) => frame,
self.mark_dead(); Err(error) => {
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
));
}
let frame = match self.frames.recv_timeout(remaining) {
Ok(Ok(frame)) => frame,
Ok(Err(error)) => {
self.mark_dead(); self.mark_dead();
return Err(error); return Err(invocation_error(error));
}
Err(_) => {
self.mark_dead();
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
));
} }
}; };
match frame.get("kind").and_then(serde_json::Value::as_str) { match frame.get("kind").and_then(serde_json::Value::as_str) {
@@ -252,13 +204,13 @@ impl WorkerPlugin {
), ),
)); ));
} }
if let Err(error) = self.handle_capability_request(&frame) { if let Err(error) = self.handle_capability_request(&frame, deadline) {
self.mark_dead(); self.mark_dead();
return Err(error); return Err(error);
} }
} }
Some("response") => { Some("response") => {
return marqdo_plugin_abi::worker::response_from_frame(&frame); return response_from_frame(&frame);
} }
Some("error") => { Some("error") => {
return Err(PluginError::invoke( return Err(PluginError::invoke(
@@ -283,7 +235,11 @@ impl WorkerPlugin {
} }
} }
fn handle_capability_request(&mut self, frame: &serde_json::Value) -> Result<(), PluginError> { fn handle_capability_request(
&mut self,
frame: &serde_json::Value,
deadline: Instant,
) -> Result<(), PluginError> {
let id = frame let id = frame
.get("id") .get("id")
.and_then(serde_json::Value::as_u64) .and_then(serde_json::Value::as_u64)
@@ -332,23 +288,84 @@ impl WorkerPlugin {
"message":error.message, "message":error.message,
}), }),
}; };
if let Err(error) = write_frame(&mut self.stdin, &reply) { self.connection
self.mark_dead(); .send(reply, deadline)
return Err(error); .map_err(invocation_error)
}
Ok(())
} }
fn mark_dead(&mut self) { fn mark_dead(&mut self) {
self.dead = true; self.dead = true;
let _ = self.child.kill(); self.connection.abort();
} }
} }
impl Drop for WorkerPlugin { impl Drop for WorkerPlugin {
fn drop(&mut self) { fn drop(&mut self) {
let _ = write_frame(&mut self.stdin, &json!({"kind": "shutdown"})); if !self.dead {
let _ = self.child.kill(); let _ = self.connection.send(
let _ = self.child.wait(); json!({"kind": "shutdown"}),
Instant::now() + Duration::from_millis(500),
);
}
self.connection.abort();
}
}
fn invocation_error(error: TransportError) -> PluginError {
match error {
TransportError::Timeout => PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
),
other => transport_error(other),
}
}
fn transport_error(error: TransportError) -> PluginError {
match error {
TransportError::Timeout => {
PluginError::invoke("plugin.timeout", "plugin worker exceeded its timeout")
}
TransportError::Closed => {
PluginError::invoke("plugin.crashed", "plugin worker closed its output stream")
}
TransportError::Frame(FrameError::Io(error)) => PluginError::invoke(
"plugin.crashed",
format!("worker frame I/O failed: {error}"),
),
// The shared transport classifies an over-limit or unencodable frame
// before anything is written. Keep the boundary-specific codes the
// plugin ABI has always reported instead of flattening them into
// `worker_frame_invalid`.
TransportError::Frame(FrameError::Encode(error)) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
TransportError::Frame(FrameError::Length(length)) => PluginError::wire(
"worker_frame_too_large",
format!("worker frame is {length} bytes"),
),
TransportError::Frame(other) => {
PluginError::wire("worker_frame_invalid", other.to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transport_errors_keep_the_boundary_specific_codes() {
let too_large = transport_error(TransportError::Frame(FrameError::Length(9 * 1024 * 1024)));
assert_eq!(too_large.code, "worker_frame_too_large");
let over_limit = transport_error(TransportError::Frame(FrameError::PartialPayload {
expected: 10,
actual: 3,
}));
assert_eq!(over_limit.code, "worker_frame_invalid");
let closed = transport_error(TransportError::Closed);
assert_eq!(closed.code, "plugin.crashed");
} }
} }
+43 -48
View File
@@ -1,29 +1,34 @@
//! Host-managed worker resource provider (ADR-0035). //! Host-managed worker resource provider (ADR-0035).
//! //!
//! This is a small, versioned framed-JSON transport for **trusted helper //! This is a bounded framed-JSON transport for **trusted helper processes**.
//! processes**. It is not a C ABI binding and not an OS sandbox: the helper //! It is not a C ABI binding and not an OS sandbox: the helper runs as the host
//! runs as the host user. Registration is a host embedding API; language code //! user. Registration is a host embedding API; language code only sees the
//! only sees the normal `resource.*` operations. //! normal `resource.*` operations.
//!
//! Framing, bounded reads, request deadlines and teardown come from
//! [`marqdo_worker_ipc`]. The `open`/`read`/`write`/`close` vocabulary, kind
//! rights and error categories stay owned by the resource boundary, so a
//! shared transport never widens provider authority.
use std::io::{BufReader, Read, Write};
use std::path::Path; use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use marqdo_span::Span; use marqdo_span::Span;
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, 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;
const WORKER_TIMEOUT: Duration = Duration::from_secs(30);
/// A `ResourceProvider` backed by a child process speaking framed JSON. /// A `ResourceProvider` backed by a child process speaking framed JSON.
pub(crate) struct WorkerResourceProvider { pub(crate) struct WorkerResourceProvider {
name: String, name: String,
kinds: Vec<String>, kinds: Vec<String>,
child: Child, connection: Connection,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
} }
impl WorkerResourceProvider { impl WorkerResourceProvider {
@@ -33,7 +38,7 @@ impl WorkerResourceProvider {
program: &Path, program: &Path,
args: &[String], args: &[String],
) -> Result<Self, RuntimeError> { ) -> Result<Self, RuntimeError> {
let mut child = Command::new(program) let child = Command::new(program)
.args(args) .args(args)
.stdin(Stdio::piped()) .stdin(Stdio::piped())
.stdout(Stdio::piped()) .stdout(Stdio::piped())
@@ -49,20 +54,12 @@ impl WorkerResourceProvider {
), ),
) )
})?; })?;
let stdin = child let connection = Connection::attach(child, MAX_FRAME_BYTES)
.stdin .map_err(|error| worker_error(&format!("cannot attach to worker: {error}")))?;
.take()
.ok_or_else(|| worker_error("missing stdin pipe"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| worker_error("missing stdout pipe"))?;
let mut provider = Self { let mut provider = Self {
name: name.to_string(), name: name.to_string(),
kinds: kinds.to_vec(), kinds: kinds.to_vec(),
child, connection,
stdin,
stdout: BufReader::new(stdout),
}; };
// Handshake: the helper must answer a ping before it is trusted. // Handshake: the helper must answer a ping before it is trusted.
provider.request(json!({"op": "ping"}))?; provider.request(json!({"op": "ping"}))?;
@@ -70,30 +67,11 @@ impl WorkerResourceProvider {
} }
fn request(&mut self, request: Json) -> Result<Json, RuntimeError> { fn request(&mut self, request: Json) -> Result<Json, RuntimeError> {
let bytes = serde_json::to_vec(&request) let deadline = Instant::now() + WORKER_TIMEOUT;
.map_err(|error| worker_error(&format!("cannot encode request: {error}")))?; self.connection
if bytes.len() > MAX_FRAME_BYTES { .send(request, deadline)
return Err(worker_error("request frame is too large")); .map_err(transport_error)?;
} let response = self.connection.receive(deadline).map_err(transport_error)?;
self.stdin
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| self.stdin.write_all(&bytes))
.and_then(|()| self.stdin.flush())
.map_err(|error| worker_error(&format!("cannot write request frame: {error}")))?;
let mut header = [0u8; 4];
self.stdout
.read_exact(&mut header)
.map_err(|error| worker_error(&format!("cannot read response header: {error}")))?;
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(worker_error("invalid response frame length"));
}
let mut payload = vec![0u8; length];
self.stdout
.read_exact(&mut payload)
.map_err(|error| worker_error(&format!("cannot read response frame: {error}")))?;
let response: Json = serde_json::from_slice(&payload)
.map_err(|error| worker_error(&format!("invalid response JSON: {error}")))?;
if response.get("ok").and_then(Json::as_bool) != Some(true) { if response.get("ok").and_then(Json::as_bool) != Some(true) {
let code = response let code = response
.get("code") .get("code")
@@ -192,9 +170,11 @@ impl ResourceProvider for WorkerResourceProvider {
impl Drop for WorkerResourceProvider { impl Drop for WorkerResourceProvider {
fn drop(&mut self) { fn drop(&mut self) {
let _ = self.request(json!({"op": "shutdown"})); let _ = self.connection.send(
let _ = self.child.kill(); json!({"op": "shutdown"}),
let _ = self.child.wait(); Instant::now() + Duration::from_millis(500),
);
self.connection.abort();
} }
} }
@@ -205,6 +185,21 @@ fn with_span(mut error: RuntimeError, span: Option<Span>) -> RuntimeError {
error error
} }
fn transport_error(error: TransportError) -> RuntimeError {
match error {
TransportError::Timeout => {
worker_error("worker resource provider did not answer before the deadline")
}
TransportError::Closed => worker_error("worker resource provider closed its transport"),
TransportError::Frame(FrameError::Io(error)) => {
worker_error(&format!("worker resource provider I/O failed: {error}"))
}
TransportError::Frame(other) => {
worker_error(&format!("worker resource provider frame error: {other}"))
}
}
}
fn worker_error(message: &str) -> RuntimeError { fn worker_error(message: &str) -> RuntimeError {
RuntimeError::new(ErrorCategory::HostError, None, message.to_string()) RuntimeError::new(ErrorCategory::HostError, None, message.to_string())
} }
-180
View File
@@ -1,180 +0,0 @@
//! Effect tracing.
use std::time::Duration;
use marqdo_span::Span;
use serde::{Deserialize, Serialize};
/// One recorded host effect.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceEntry {
/// Global event sequence within the run.
#[serde(default)]
pub seq: u64,
/// Operation name (`print`, `fs.read`, `foreign.call`, ...).
pub op: String,
/// Module that initiated it.
pub module: String,
/// Source span of the call site.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Wall-clock duration.
pub duration_micros: u64,
/// Result summary (`ok`, or a diagnostic code). Never contains secrets.
pub result: String,
}
/// Collected effects for one run.
#[derive(Debug, Clone, Default)]
pub struct EffectTrace {
entries: Vec<TraceEntry>,
/// Whether tracing is enabled.
pub enabled: bool,
}
impl EffectTrace {
/// Enable tracing.
pub fn enabled() -> Self {
Self {
entries: Vec::new(),
enabled: true,
}
}
/// Record an effect.
pub fn record(
&mut self,
seq: u64,
op: impl Into<String>,
module: impl Into<String>,
span: Option<Span>,
duration: Duration,
result: impl Into<String>,
) {
if !self.enabled {
return;
}
self.entries.push(TraceEntry {
seq,
op: op.into(),
module: module.into(),
span,
duration_micros: duration.as_micros() as u64,
result: result.into(),
});
}
/// Recorded entries.
pub fn entries(&self) -> &[TraceEntry] {
&self.entries
}
}
/// Default maximum number of trace events.
pub const DEFAULT_MAX_TRACE_EVENTS: usize = 100_000;
/// Default approximate maximum serialized trace bytes.
pub const DEFAULT_MAX_TRACE_BYTES: usize = 32 * 1024 * 1024;
/// Trace capacity budget. A zero value means unlimited.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceBudget {
/// Maximum events (including the terminal truncation marker).
pub max_events: usize,
/// Approximate maximum serialized bytes.
pub max_bytes: usize,
}
impl Default for TraceBudget {
fn default() -> Self {
Self {
max_events: DEFAULT_MAX_TRACE_EVENTS,
max_bytes: DEFAULT_MAX_TRACE_BYTES,
}
}
}
/// Why and where a trace stopped recording.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TraceTruncation {
/// `event_budget` or `byte_budget`.
pub reason: String,
/// The configured limit that was reached.
pub limit: u64,
/// Events written before truncation.
pub written: u64,
}
/// Mutable trace capacity state for one run.
#[derive(Debug, Clone, Default)]
pub struct TraceState {
/// Whether trace recording is enabled.
pub enabled: bool,
/// Configured budget.
pub budget: TraceBudget,
/// Events accepted so far.
pub written: usize,
/// Estimated accepted bytes.
pub bytes: usize,
/// Truncation marker, set once.
pub truncation: Option<TraceTruncation>,
}
impl TraceState {
/// Accept one event if it fits the budget.
pub fn accept(&mut self, estimate: usize) -> bool {
if !self.enabled || self.truncation.is_some() {
return false;
}
if self.budget.max_events > 0 && self.written >= self.budget.max_events {
self.truncation = Some(TraceTruncation {
reason: "event_budget".to_string(),
limit: self.budget.max_events as u64,
written: self.written as u64,
});
return false;
}
if self.budget.max_bytes > 0 && self.bytes + estimate > self.budget.max_bytes {
self.truncation = Some(TraceTruncation {
reason: "byte_budget".to_string(),
limit: self.budget.max_bytes as u64,
written: self.written as u64,
});
return false;
}
self.written += 1;
self.bytes += estimate;
true
}
/// Estimate one semantic/effect event envelope.
pub fn estimate(
kind: &str,
function_id: Option<&str>,
module_id: Option<&str>,
detail: Option<&str>,
operation: Option<&str>,
) -> usize {
96 + kind.len()
+ function_id.map(str::len).unwrap_or(0)
+ module_id.map(str::len).unwrap_or(0)
+ detail.map(str::len).unwrap_or(0)
+ operation.map(str::len).unwrap_or(0)
}
}
/// One semantic event emitted by the interpreter (Trace v2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticEvent {
/// Global event sequence within the run.
pub seq: u64,
/// Stable event kind (`call.enter`, `call.exit`, `branch.eval`, ...).
pub kind: String,
/// Canonical function id, when inside a call.
pub function_id: Option<String>,
/// Logical module owning `span`.
pub module_id: Option<String>,
/// Source span, when known.
pub span: Option<Span>,
/// Non-sensitive detail (`ok`, `true`, `int`, an error code).
pub detail: Option<String>,
}
+83
View File
@@ -58,6 +58,10 @@ enum Recorded {
state: ValueState, state: ValueState,
value: Option<serde_json::Value>, value: Option<serde_json::Value>,
}, },
LoopTransfer {
frame: FrameId,
kind: &'static str,
},
Effect { Effect {
operation: String, operation: String,
result_code: String, result_code: String,
@@ -110,6 +114,12 @@ impl From<ObservationEvent<'_>> for Recorded {
frame: frame_id, frame: frame_id,
decision: decision.to_string(), decision: decision.to_string(),
}, },
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Recorded::LoopTransfer {
frame: frame_id,
kind: transfer.event_kind(),
},
ObservationEvent::Effect { ObservationEvent::Effect {
operation, operation,
result_code, result_code,
@@ -452,3 +462,76 @@ fn value_encoding_is_selected_bounded_and_handle_safe() {
assert_eq!(state, ValueState::Unsupported); assert_eq!(state, ValueState::Unsupported);
assert!(value.is_none()); assert!(value.is_none());
} }
#[test]
fn filesystem_operations_report_the_concrete_effect_name() {
let dir = std::env::temp_dir().join(format!(
"marqdo-host-fs-effect-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("data.txt"), b"x").unwrap();
std::fs::create_dir_all(dir.join("sub")).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_read("**").allow_write("**"),
dir.clone(),
)
.with_observation(
ObservationConfig::default(),
Box::new(Recorder {
events: Rc::clone(&events),
fail: false,
}),
);
let ctx = context();
for (operation, args) in [
("fs.exists", vec![Value::Text("data.txt".to_string())]),
("fs.metadata", vec![Value::Text("data.txt".to_string())]),
("fs.list", vec![Value::Text("sub".to_string())]),
("fs.mkdir", vec![Value::Text("created".to_string())]),
("fs.remove", vec![Value::Text("created".to_string())]),
(
"fs.rename",
vec![
Value::Text("data.txt".to_string()),
Value::Text("moved.txt".to_string()),
],
),
] {
host.resource_request(operation, args, &ctx)
.unwrap_or_else(|error| panic!("{operation}: {error}"));
}
let operations: Vec<String> = events
.borrow()
.iter()
.filter_map(|event| match event {
Recorded::Effect {
operation,
result_code,
} => {
assert_eq!(result_code, "ok");
Some(operation.clone())
}
_ => None,
})
.collect();
assert_eq!(
operations,
[
"fs.exists",
"fs.metadata",
"fs.list",
"fs.mkdir",
"fs.remove",
"fs.rename",
],
"each filesystem request must report its concrete operation"
);
let _ = std::fs::remove_dir_all(&dir);
}
+1 -1
View File
@@ -3,7 +3,7 @@
//! The frontend resolves every statically visible call site exactly once and //! The frontend resolves every statically visible call site exactly once and
//! records the decision here. The runtime only dispatches by this table: it //! records the decision here. The runtime only dispatches by this table: it
//! never re-resolves a qualified name and never guesses a plugin from a string //! never re-resolves a qualified name and never guesses a plugin from a string
//! prefix. The table is internal IR (not part of Analysis/Trace v2 wire //! prefix. The table is internal IR (not part of the Analysis/Observation wire
//! contracts) and is deliberately skipped when a [`crate::Program`] is //! contracts) and is deliberately skipped when a [`crate::Program`] is
//! serialized. //! serialized.
//! //!
+17 -5
View File
@@ -285,11 +285,11 @@ pub enum Stmt {
/// Span of the whole statement. /// Span of the whole statement.
span: Span, span: Span,
}, },
/// `if`/`else` group: the first true arm wins. /// `if`/`else if`/`else` group: the first true arm wins.
Branch { Branch {
/// Arms in AST order. /// Arms in AST order.
arms: Vec<BranchArm>, arms: Vec<BranchArm>,
/// Span of the list node. /// Span of the opening `if` carrier.
span: Span, span: Span,
}, },
/// `while`/`end` group. /// `while`/`end` group.
@@ -303,6 +303,16 @@ pub enum Stmt {
/// Span of the whole `while` statement. /// Span of the whole `while` statement.
span: Span, span: Span,
}, },
/// Exit the nearest loop in the enclosing function.
Break {
/// Span of the carrier.
span: Span,
},
/// Resume at the nearest loop condition in the enclosing function.
Continue {
/// Span of the carrier.
span: Span,
},
/// Return from the enclosing function (`return` statement). /// Return from the enclosing function (`return` statement).
Return { Return {
/// Returned expression. /// Returned expression.
@@ -320,12 +330,14 @@ impl Stmt {
| Stmt::Eval { span, .. } | Stmt::Eval { span, .. }
| Stmt::Branch { span, .. } | Stmt::Branch { span, .. }
| Stmt::Loop { span, .. } | Stmt::Loop { span, .. }
| Stmt::Break { span }
| Stmt::Continue { span }
| Stmt::Return { span, .. } => *span, | Stmt::Return { span, .. } => *span,
} }
} }
} }
/// One arm of an `if`/`else` group. /// One arm of an `if`/`else if`/`else` group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BranchArm { pub struct BranchArm {
/// Boolean condition expression. /// Boolean condition expression.
@@ -334,7 +346,7 @@ pub struct BranchArm {
pub condition_span: Span, pub condition_span: Span,
/// Statements executed when the condition is true. /// Statements executed when the condition is true.
pub body: Vec<Stmt>, pub body: Vec<Stmt>,
/// Span of the whole list item. /// Span of the branch carrier.
pub span: Span, pub span: Span,
} }
@@ -479,7 +491,7 @@ pub struct Program {
pub external_callables: Vec<callable::CallableDescriptor>, pub external_callables: Vec<callable::CallableDescriptor>,
/// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054). /// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
/// ///
/// Internal IR: deliberately skipped on the wire so Analysis/Trace v2 /// Internal IR: deliberately skipped on the wire so Analysis v3/Observation v1
/// consumers are unaffected. A prepared program always carries a complete /// consumers are unaffected. A prepared program always carries a complete
/// table; the runtime never re-resolves names. /// table; the runtime never re-resolves names.
#[serde(skip)] #[serde(skip)]
+1
View File
@@ -11,6 +11,7 @@ authors.workspace = true
[dependencies] [dependencies]
marqdo-span = { workspace = true } 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 } serde_yaml = { workspace = true }
+29 -71
View File
@@ -30,84 +30,42 @@ pub const MAX_CAPABILITY_REQUEST_BYTES: usize = 64 * 1024;
/// Read one length-prefixed frame (4-byte big-endian length + JSON). /// Read one length-prefixed frame (4-byte big-endian length + JSON).
/// ///
/// `Ok(None)` means a clean EOF at a frame boundary. A partial header or /// `Ok(None)` means a clean EOF at a frame boundary. A partial header or
/// truncated payload is a protocol error, never EOF. /// truncated payload is a protocol error, never EOF. Framing itself is shared
/// with other persistent workers; the plugin vocabulary stays in this module.
pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Value>, PluginError> { pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Value>, PluginError> {
let mut length = [0_u8; 4]; marqdo_worker_ipc::read_frame(reader, MAX_FRAME_BYTES).map_err(frame_read_error)
let mut read = 0usize;
while read < length.len() {
match reader.read(&mut length[read..]) {
Ok(0) if read == 0 => return Ok(None),
Ok(0) => {
return Err(PluginError::wire(
"worker_frame_invalid",
"worker stream ended inside a frame header",
))
}
Ok(count) => read += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => {
return Err(PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
))
}
}
}
let length = u32::from_be_bytes(length) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(PluginError::wire(
"worker_frame_invalid",
format!("worker frame length {length} is invalid"),
));
}
let mut bytes = Vec::with_capacity(length.min(64 * 1024));
let read = reader
.take(length as u64)
.read_to_end(&mut bytes)
.map_err(|error| {
PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
)
})?;
if read != length {
return Err(PluginError::wire(
"worker_frame_invalid",
format!("worker frame declared {length} bytes but only {read} arrived"),
));
}
serde_json::from_slice(&bytes).map(Some).map_err(|error| {
PluginError::wire(
"worker_frame_invalid",
format!("worker frame is not valid JSON: {error}"),
)
})
} }
/// Write one length-prefixed frame. /// Write one length-prefixed frame.
pub fn write_frame<W: Write>(writer: &mut W, value: &Value) -> Result<(), PluginError> { pub fn write_frame<W: Write>(writer: &mut W, value: &Value) -> Result<(), PluginError> {
let bytes = serde_json::to_vec(value).map_err(|error| { marqdo_worker_ipc::write_frame(writer, value, MAX_FRAME_BYTES).map_err(frame_write_error)
PluginError::wire( }
"worker_encode_failed",
format!("cannot encode worker frame: {error}"), fn frame_read_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
) match error {
})?; marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
if bytes.len() > MAX_FRAME_BYTES { "plugin.crashed",
return Err(PluginError::wire( format!("worker frame read failed: {error}"),
),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
}
}
fn frame_write_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
match error {
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
"plugin.crashed",
format!("worker frame write failed: {error}"),
),
marqdo_worker_ipc::FrameError::Encode(error) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
marqdo_worker_ipc::FrameError::Length(length) => PluginError::wire(
"worker_frame_too_large", "worker_frame_too_large",
format!("worker frame is {} bytes", bytes.len()), format!("worker frame is {length} bytes"),
)); ),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
} }
writer
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| writer.write_all(&bytes))
.and_then(|()| writer.flush())
.map_err(|error| {
PluginError::invoke(
"plugin.crashed",
format!("worker frame write failed: {error}"),
)
})
} }
/// Run one worker until shutdown/EOF. Returns a process exit code. /// Run one worker until shutdown/EOF. Returns a process exit code.
+1
View File
@@ -12,6 +12,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
libloading = { workspace = true } libloading = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
marqdo-worker-ipc = { workspace = true }
[dev-dependencies] [dev-dependencies]
marqdo-host = { path = "../marqdo-host" } marqdo-host = { path = "../marqdo-host" }
+7 -33
View File
@@ -5,7 +5,6 @@
//! boundary, not a sandbox: the library runs with the worker's privileges. //! boundary, not a sandbox: the library runs with the worker's privileges.
use std::ffi::{c_char, CString}; use std::ffi::{c_char, CString};
use std::io::{Read, Write};
use std::path::PathBuf; use std::path::PathBuf;
use libloading::Library; use libloading::Library;
@@ -129,41 +128,16 @@ impl Provider {
} }
fn read_frame() -> Result<Option<Json>, String> { fn read_frame() -> Result<Option<Json>, String> {
let mut header = [0u8; 4]; let stdin = std::io::stdin();
let mut read = 0usize; let mut input = stdin.lock();
while read < header.len() { marqdo_worker_ipc::read_frame(&mut input, MAX_FRAME_BYTES).map_err(|error| error.to_string())
match std::io::stdin().read(&mut header[read..]) {
Ok(0) if read == 0 => return Ok(None),
Ok(0) => return Err("stdin ended inside a frame header".to_string()),
Ok(count) => read += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(format!("stdin read failed: {error}")),
}
}
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(format!("invalid frame length {length}"));
}
let mut payload = vec![0u8; length];
std::io::stdin()
.read_exact(&mut payload)
.map_err(|error| format!("stdin read failed: {error}"))?;
serde_json::from_slice(&payload)
.map(Some)
.map_err(|error| format!("invalid JSON frame: {error}"))
} }
fn write_frame(value: &Json) -> Result<(), String> { fn write_frame(value: &Json) -> Result<(), String> {
let bytes = serde_json::to_vec(value).map_err(|error| format!("encode failed: {error}"))?; let stdout = std::io::stdout();
if bytes.len() > MAX_FRAME_BYTES { let mut output = stdout.lock();
return Err("response frame is too large".to_string()); marqdo_worker_ipc::write_frame(&mut output, value, MAX_FRAME_BYTES)
} .map_err(|error| error.to_string())
let mut stdout = std::io::stdout();
stdout
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| stdout.write_all(&bytes))
.and_then(|()| stdout.flush())
.map_err(|error| format!("stdout write failed: {error}"))
} }
fn fail(message: &str) -> Json { fn fail(message: &str) -> Json {
+2 -12
View File
@@ -160,12 +160,7 @@ pub(crate) fn dispatch(
let handle = interpreter let handle = interpreter
.memory_mut() .memory_mut()
.create(initial_pages, max_pages, span)?; .create(initial_pages, max_pages, span)?;
interpreter.record_memory_event( interpreter.observe_memory_effect("memory.new", &module, span)?;
"memory.new",
&module,
span,
&format!("initial_pages={initial_pages} max_pages={max_pages}"),
);
Ok(Value::Memory(handle)) Ok(Value::Memory(handle))
} }
"memory.size" => { "memory.size" => {
@@ -191,12 +186,7 @@ pub(crate) fn dispatch(
}; };
let pages = page_count(take(&bound, "pages", builtin, span)?, span)?; let pages = page_count(take(&bound, "pages", builtin, span)?, span)?;
let old_pages = interpreter.memory_mut().grow(handle, pages, span)?; let old_pages = interpreter.memory_mut().grow(handle, pages, span)?;
interpreter.record_memory_event( interpreter.observe_memory_effect("memory.grow", &module, span)?;
"memory.grow",
&module,
span,
&format!("pages={pages} old_pages={old_pages}"),
);
Ok(pages_value(old_pages, span)?) Ok(pages_value(old_pages, span)?)
} }
"list.append" => { "list.append" => {
+53 -61
View File
@@ -4,7 +4,8 @@ use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry}; use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{ use marqdo_host::{
ExecutionContext, FrameId, Host, HostOp, ParameterSource, ResourceRead, RuntimeObservation, ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
RuntimeObservation,
}; };
use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt}; use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt};
use marqdo_span::Span; use marqdo_span::Span;
@@ -71,6 +72,8 @@ struct BoundArgs {
enum Flow { enum Flow {
Next, Next,
Return(Value), Return(Value),
Break(Span),
Continue(Span),
} }
/// Marqdo tree-walk interpreter. /// Marqdo tree-walk interpreter.
@@ -175,13 +178,6 @@ impl<'a> Interpreter<'a> {
if self.depth + 1 > 0 { if self.depth + 1 > 0 {
self.host.check_stack(self.depth + 1, call_span)?; self.host.check_stack(self.depth + 1, call_span)?;
} }
self.host.record_semantic(
"call.enter",
Some(&trace_id),
Some(&trace_module),
call_span,
None,
);
let bound = match self.bind_args(function, args, call_span) { let bound = match self.bind_args(function, args, call_span) {
Ok(bound) => bound, Ok(bound) => bound,
Err(mut error) => { Err(mut error) => {
@@ -225,20 +221,23 @@ impl<'a> Interpreter<'a> {
id: frame_id, id: frame_id,
}; };
self.depth += 1; self.depth += 1;
let result = self.exec_stmts(program, &function.body, &mut frame); let result = self
.exec_stmts(program, &function.body, &mut frame)
.and_then(|flow| match flow {
Flow::Next => Ok(None),
Flow::Return(value) => Ok(Some(value)),
Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
"loop control escaped its enclosing function",
)),
});
self.depth -= 1; self.depth -= 1;
let status = match &result { let status = match &result {
Ok(Flow::Next) => "ok", Ok(None) => "ok",
Ok(Flow::Return(_)) => "return", Ok(Some(_)) => "return",
Err(error) => error.code(), Err(error) => error.code(),
}; };
self.host.record_semantic(
"call.exit",
Some(&trace_id),
Some(&trace_module),
call_span,
Some(status),
);
let close = self let close = self
.host .host
.observation_end_frame(frame_id, status, &trace_module, call_span); .observation_end_frame(frame_id, status, &trace_module, call_span);
@@ -246,8 +245,7 @@ impl<'a> Interpreter<'a> {
close?; close?;
} }
match result { match result {
Ok(Flow::Next) => Ok(Value::Unit), Ok(value) => Ok(value.unwrap_or(Value::Unit)),
Ok(Flow::Return(value)) => Ok(value),
Err(mut error) => { Err(mut error) => {
error.attribute_module(function.id.module.canonical()); error.attribute_module(function.id.module.canonical());
error.push_frame( error.push_frame(
@@ -409,16 +407,27 @@ impl<'a> Interpreter<'a> {
Stmt::Eval { expr, .. } => { Stmt::Eval { expr, .. } => {
self.eval_expr(expr, frame)?; self.eval_expr(expr, frame)?;
} }
Stmt::Break { span } | Stmt::Continue { span } => {
let (flow, transfer) = if matches!(stmt, Stmt::Break { .. }) {
(Flow::Break(*span), LoopTransfer::Break)
} else {
(Flow::Continue(*span), LoopTransfer::Continue)
};
let module = frame.function.module.canonical();
if self.observe {
self.host
.observe_runtime(RuntimeObservation::LoopTransfer {
frame_id: frame.id,
transfer,
module_id: &module,
span: *span,
})?;
}
return Ok(flow);
}
Stmt::Return { value, span } => { Stmt::Return { value, span } => {
let value = self.eval_expr(value, frame)?; let value = self.eval_expr(value, frame)?;
let module = frame.function.module.canonical(); let module = frame.function.module.canonical();
self.host.record_semantic(
"return",
Some(&frame.function.to_string()),
Some(&module),
Some(*span),
Some(value.type_name()),
);
if self.observe { if self.observe {
self.host.observe_runtime(RuntimeObservation::Return { self.host.observe_runtime(RuntimeObservation::Return {
frame_id: frame.id, frame_id: frame.id,
@@ -443,13 +452,6 @@ impl<'a> Interpreter<'a> {
)); ));
}; };
let module = frame.function.module.canonical(); let module = frame.function.module.canonical();
self.host.record_semantic(
"branch.eval",
Some(&frame.function.to_string()),
Some(&module),
Some(arm.condition_span),
Some(if condition { "true" } else { "false" }),
);
if self.observe { if self.observe {
self.host.observe_runtime(RuntimeObservation::BranchEval { self.host.observe_runtime(RuntimeObservation::BranchEval {
frame_id: frame.id, frame_id: frame.id,
@@ -461,7 +463,7 @@ impl<'a> Interpreter<'a> {
if condition { if condition {
match self.exec_stmts(program, &arm.body, frame)? { match self.exec_stmts(program, &arm.body, frame)? {
Flow::Next => break, Flow::Next => break,
Flow::Return(value) => return Ok(Flow::Return(value)), flow => return Ok(flow),
} }
} }
} }
@@ -482,13 +484,6 @@ impl<'a> Interpreter<'a> {
)); ));
}; };
let module = frame.function.module.canonical(); let module = frame.function.module.canonical();
self.host.record_semantic(
"loop.iteration",
Some(&frame.function.to_string()),
Some(&module),
Some(*condition_span),
Some(if value { "continue" } else { "exit" }),
);
if self.observe { if self.observe {
self.host self.host
.observe_runtime(RuntimeObservation::LoopIteration { .observe_runtime(RuntimeObservation::LoopIteration {
@@ -502,8 +497,9 @@ impl<'a> Interpreter<'a> {
break; break;
} }
match self.exec_stmts(program, body, frame)? { match self.exec_stmts(program, body, frame)? {
Flow::Next => {} Flow::Next | Flow::Continue(_) => {}
Flow::Return(value) => return Ok(Flow::Return(value)), Flow::Break(_) => break,
flow @ Flow::Return(_) => return Ok(flow),
} }
}, },
} }
@@ -556,15 +552,7 @@ impl<'a> Interpreter<'a> {
)); ));
}; };
self.memory.write(handle, &offset, byte, span)?; self.memory.write(handle, &offset, byte, span)?;
let module = frame.function.module.canonical(); self.observe_memory_effect("memory.write", &frame.function.module, span)
self.host.record_semantic(
"memory.write",
Some(&frame.function.to_string()),
Some(&module),
span,
Some("byte"),
);
Ok(())
} }
fn eval_args( fn eval_args(
@@ -867,17 +855,21 @@ impl<'a> Interpreter<'a> {
&mut self.memory &mut self.memory
} }
/// Record a semantic event for a builtin that is not a host operation. /// Publish a committed local memory operation without its data or address.
pub(crate) fn record_memory_event( pub(crate) fn observe_memory_effect(
&mut self, &mut self,
kind: &str, operation: &str,
module: &ModuleId, module: &ModuleId,
span: Option<Span>, span: Option<Span>,
detail: &str, ) -> Result<(), RuntimeError> {
) { if self.observe {
let module = module.canonical(); self.host.observe_runtime(RuntimeObservation::Effect {
self.host operation,
.record_semantic(kind, None, Some(&module), span, Some(detail)); module_id: &module.canonical(),
span,
})?;
}
Ok(())
} }
/// Open a resource/stream through the host boundary. /// Open a resource/stream through the host boundary.
@@ -249,3 +249,46 @@ fn memory_budget_is_enforced_without_changing_the_region() {
.unwrap_err(); .unwrap_err();
assert_eq!(error.code(), "resource.exhausted"); assert_eq!(error.code(), "resource.exhausted");
} }
#[test]
fn continue_obeys_fuel_and_wall_clock_budgets() {
use std::time::{Duration, Instant};
let source = "## @exec main\n\n`while true`\n\n`continue`\n\n`end`\n";
let program = build(source);
let module = ModuleId::from("index.mq.md");
let mut fuel_host = host();
fuel_host.budget.fuel = 20;
let fuel = run(&program, &mut fuel_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(fuel.code(), "resource.exhausted");
assert!(fuel.message.contains("fuel exhausted"));
let mut deadline_host = host();
deadline_host.budget.fuel = u64::MAX;
deadline_host.budget.deadline = Some(Instant::now() + Duration::from_millis(25));
let timeout = run(&program, &mut deadline_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(timeout.code(), "resource.exhausted");
assert!(timeout.message.contains("wall-clock time limit"));
}
#[test]
fn malformed_ir_cannot_transfer_into_the_callers_loop() {
let source =
"## @exec child\n\n`return 1`\n\n## @exec main\n\n`while true`\n\n`child()`\n\n`end`\n";
let mut program = build(source);
let module = ModuleId::from("index.mq.md");
let child = program
.modules
.get_mut(&module)
.unwrap()
.functions
.iter_mut()
.find(|function| function.id.name == "child")
.unwrap();
let span = child.body[0].span();
child.body[0] = marqdo_ir::Stmt::Break { span };
let error = run(&program, &mut host(), &module, "main", Vec::new()).unwrap_err();
assert_eq!(error.category, marqdo_value::ErrorCategory::Internal);
assert_eq!(error.span, Some(span));
}
@@ -93,6 +93,18 @@ impl ObservationSink for Recorder {
source: None, source: None,
decision: decision.to_string(), decision: decision.to_string(),
}, },
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Seen {
kind: transfer.event_kind(),
frame: Some(frame_id.0),
name: String::new(),
value_type: String::new(),
state: None,
wire: None,
source: None,
decision: String::new(),
},
ObservationEvent::VariableAssigned { ObservationEvent::VariableAssigned {
frame_id, frame_id,
name, name,
+8
View File
@@ -31,6 +31,14 @@ pub mod codes {
pub const SEM_SYNTAX: &str = "sem.syntax"; pub const SEM_SYNTAX: &str = "sem.syntax";
/// `else` does not bind an open `if`. /// `else` does not bind an open `if`.
pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else"; pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else";
/// `else if` has no matching open `if`.
pub const SEM_UNMATCHED_ELSE_IF: &str = "sem.unmatched_else_if";
/// `else if` follows the final `else`.
pub const SEM_ELSE_IF_AFTER_ELSE: &str = "sem.else_if_after_else";
/// A `break` appears outside a loop in its heading segment.
pub const SEM_BREAK_OUTSIDE_LOOP: &str = "sem.break_outside_loop";
/// A `continue` appears outside a loop in its heading segment.
pub const SEM_CONTINUE_OUTSIDE_LOOP: &str = "sem.continue_outside_loop";
/// A second `else` appears for one `if`. /// A second `else` appears for one `if`.
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else"; pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
/// `end` closes no open frame. /// `end` closes no open frame.
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "marqdo-worker-ipc"
description = "Bounded framed JSON and child transport for Marqdo workers"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
[dependencies]
serde_json = { workspace = true }
thiserror = { workspace = true }
+370
View File
@@ -0,0 +1,370 @@
#![forbid(unsafe_code)]
//! Bounded length-prefixed JSON framing and child-process transport shared by
//! persistent Marqdo workers.
//!
//! The crate owns only what is genuinely common to a plugin worker and a
//! resource-provider worker: the four-byte big-endian length prefix, the
//! maximum frame size, clean-EOF versus truncated-frame classification, a
//! single reader and writer thread, request deadlines, and process teardown.
//! Each caller still owns its own frame vocabulary, size limit, authority,
//! capability bridge and error codes. Sharing this transport does not share
//! capabilities or trust.
//!
//! Foreign kernels and CLI Tools do not use this transport: a foreign kernel
//! is a one-shot stdin/stdout wire value, and a CLI Tool is an independent
//! executable owning its standard streams.
use std::io::{self, Read, Write};
use std::process::Child;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
use std::time::{Duration, Instant};
use serde_json::Value;
use thiserror::Error;
/// Read a bounded four-byte big-endian length and JSON value.
#[derive(Debug, Error)]
pub enum FrameError {
#[error("worker frame I/O failed: {0}")]
Io(#[from] io::Error),
#[error("worker stream ended inside a frame header")]
PartialHeader,
#[error("worker frame length {0} is invalid")]
Length(usize),
#[error("worker frame declared {expected} bytes but only {actual} arrived")]
PartialPayload { expected: usize, actual: usize },
#[error("worker frame is not valid JSON: {0}")]
InvalidJson(serde_json::Error),
#[error("cannot encode worker frame: {0}")]
Encode(serde_json::Error),
}
/// Read one bounded frame.
///
/// `Ok(None)` is a clean EOF at a frame boundary. A partial header, a
/// truncated payload, an invalid length or invalid JSON is a protocol error and
/// never EOF. `limit` is the caller's protocol frame budget, in bytes.
pub fn read_frame(reader: &mut impl Read, limit: usize) -> Result<Option<Value>, FrameError> {
let mut header = [0; 4];
let mut offset = 0;
while offset < header.len() {
match reader.read(&mut header[offset..]) {
Ok(0) if offset == 0 => return Ok(None),
Ok(0) => return Err(FrameError::PartialHeader),
Ok(count) => offset += count,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error.into()),
}
}
let expected = u32::from_be_bytes(header) as usize;
if expected == 0 || expected > limit {
return Err(FrameError::Length(expected));
}
let mut payload = Vec::with_capacity(expected.min(64 * 1024));
let actual = reader.take(expected as u64).read_to_end(&mut payload)?;
if actual != expected {
return Err(FrameError::PartialPayload { expected, actual });
}
serde_json::from_slice(&payload)
.map(Some)
.map_err(FrameError::InvalidJson)
}
/// Write and flush one frame under the peer's configured size limit.
pub fn write_frame(writer: &mut impl Write, value: &Value, limit: usize) -> Result<(), FrameError> {
let payload = serde_json::to_vec(value).map_err(FrameError::Encode)?;
if payload.len() > limit {
return Err(FrameError::Length(payload.len()));
}
let length = u32::try_from(payload.len()).map_err(|_| FrameError::Length(payload.len()))?;
writer.write_all(&length.to_be_bytes())?;
writer.write_all(&payload)?;
writer.flush()?;
Ok(())
}
/// Failure of one configured request/response exchange.
#[derive(Debug, Error)]
pub enum TransportError {
#[error("worker transport reached its deadline")]
Timeout,
#[error("worker transport closed")]
Closed,
#[error(transparent)]
Frame(#[from] FrameError),
}
type WriteRequest = (Value, SyncSender<Result<(), FrameError>>);
/// Owns one configured child and its two dedicated protocol pipes.
///
/// A connection is sequential: one caller drives one exchange at a time, and
/// the caller supplies the deadline for that exchange. Any transport error
/// kills and reaps the child, so a dead worker is never reused.
pub struct Connection {
child: Option<Child>,
writes: Option<SyncSender<WriteRequest>>,
reads: Option<Receiver<Result<Value, FrameError>>>,
}
impl Connection {
/// Attach to a child with piped stdin/stdout, closing the child on failure.
pub fn attach(child: Child, limit: usize) -> io::Result<Self> {
let mut connection = Self {
child: Some(child),
writes: None,
reads: None,
};
if let Err(error) = connection.attach_pipes(limit) {
connection.abort();
return Err(error);
}
Ok(connection)
}
fn attach_pipes(&mut self, limit: usize) -> io::Result<()> {
let instance = self.child.as_mut().expect("child present");
let mut stdin = instance
.stdin
.take()
.ok_or_else(|| io::Error::other("worker stdin unavailable"))?;
let mut stdout = instance
.stdout
.take()
.ok_or_else(|| io::Error::other("worker stdout unavailable"))?;
let (writes, pending) = mpsc::sync_channel::<WriteRequest>(1);
std::thread::Builder::new()
.name("marqdo-worker-writer".into())
.spawn(move || {
while let Ok((value, reply)) = pending.recv() {
if reply.send(write_frame(&mut stdin, &value, limit)).is_err() {
break;
}
}
})?;
self.writes = Some(writes);
let (received, reads) = mpsc::sync_channel(1);
std::thread::Builder::new()
.name("marqdo-worker-reader".into())
.spawn(move || loop {
match read_frame(&mut stdout, limit) {
Ok(Some(value)) => {
if received.send(Ok(value)).is_err() {
break;
}
}
Ok(None) => break,
Err(error) => {
let _ = received.send(Err(error));
break;
}
}
})?;
self.reads = Some(reads);
Ok(())
}
/// Process id of the attached child, if it is still owned here.
pub fn id(&self) -> Option<u32> {
self.child.as_ref().map(Child::id)
}
/// Send one frame and wait for the write to complete before the deadline.
pub fn send(&mut self, value: Value, deadline: Instant) -> Result<(), TransportError> {
let result = (|| {
let channel = self.writes.as_ref().ok_or(TransportError::Closed)?;
let (response, result) = mpsc::sync_channel(1);
let mut pending = Some((value, response));
loop {
match channel.try_send(pending.take().expect("pending frame")) {
Ok(()) => break,
Err(TrySendError::Full(returned)) => {
pending = Some(returned);
if Instant::now() >= deadline {
return Err(TransportError::Timeout);
}
std::thread::sleep(Duration::from_millis(1));
}
Err(TrySendError::Disconnected(_)) => return Err(TransportError::Closed),
}
}
wait(&result, deadline)?.map_err(Into::into)
})();
if result.is_err() {
self.abort();
}
result
}
/// Receive one frame before the deadline.
pub fn receive(&mut self, deadline: Instant) -> Result<Value, TransportError> {
let result = self
.reads
.as_ref()
.ok_or(TransportError::Closed)
.and_then(|channel| wait(channel, deadline))
.and_then(|frame| frame.map_err(Into::into));
if result.is_err() {
self.abort();
}
result
}
/// Make this peer unusable and reap the process.
pub fn abort(&mut self) {
self.writes.take();
self.reads.take();
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
impl Drop for Connection {
fn drop(&mut self) {
self.abort();
}
}
fn wait<T>(channel: &Receiver<T>, deadline: Instant) -> Result<T, TransportError> {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(TransportError::Timeout);
}
channel
.recv_timeout(remaining)
.map_err(|error| match error {
RecvTimeoutError::Timeout => TransportError::Timeout,
RecvTimeoutError::Disconnected => TransportError::Closed,
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn framing_distinguishes_boundary_eof_from_a_partial_record() {
let mut bytes = Vec::new();
write_frame(&mut bytes, &json!({"ok": true}), 64).unwrap();
let mut input = bytes.as_slice();
assert_eq!(
read_frame(&mut input, 64).unwrap(),
Some(json!({"ok": true}))
);
assert_eq!(read_frame(&mut input, 64).unwrap(), None);
assert!(matches!(
read_frame(&mut &bytes[..3], 64),
Err(FrameError::PartialHeader)
));
assert!(matches!(
read_frame(&mut &bytes[..6], 64),
Err(FrameError::PartialPayload { .. })
));
assert!(matches!(
read_frame(&mut &[0; 4][..], 64),
Err(FrameError::Length(0))
));
assert!(matches!(
read_frame(&mut &bytes[..4], 4),
Err(FrameError::Length(_))
));
}
#[test]
fn writing_past_the_peer_limit_is_a_frame_error() {
let mut bytes = Vec::new();
let error = write_frame(&mut bytes, &json!({"payload": "long"}), 4).unwrap_err();
assert!(matches!(error, FrameError::Length(_)));
assert!(bytes.is_empty());
}
#[cfg(unix)]
mod child {
use super::*;
use std::process::{Command, Stdio};
fn connection(script: &str) -> Connection {
let child = Command::new("python3")
.arg("-c")
.arg(script)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("python3 is required for worker transport tests");
Connection::attach(child, 1024).expect("attach child")
}
const ECHO: &str = r#"
import sys, json, struct
def read_frame():
header = sys.stdin.buffer.read(4)
if len(header) < 4:
return None
return json.loads(sys.stdin.buffer.read(struct.unpack(">I", header)[0]))
def write_frame(value):
payload = json.dumps(value).encode()
sys.stdout.buffer.write(struct.pack(">I", len(payload)) + payload)
sys.stdout.buffer.flush()
while True:
frame = read_frame()
if frame is None:
break
write_frame({"echo": frame})
"#;
#[test]
fn connection_round_trips_frames_from_one_child() {
let mut connection = connection(ECHO);
let deadline = Instant::now() + Duration::from_secs(10);
connection.send(json!({"n": 1}), deadline).unwrap();
assert_eq!(
connection.receive(deadline).unwrap(),
json!({"echo": {"n": 1}})
);
connection.send(json!({"n": 2}), deadline).unwrap();
assert_eq!(
connection.receive(deadline).unwrap(),
json!({"echo": {"n": 2}})
);
}
#[test]
fn a_silent_child_hits_the_request_deadline_and_is_reaped() {
let mut connection = connection("import time; time.sleep(30)");
let deadline = Instant::now() + Duration::from_millis(200);
assert!(matches!(
connection.receive(deadline),
Err(TransportError::Timeout)
));
assert!(connection.id().is_none());
assert!(matches!(
connection.receive(Instant::now() + Duration::from_secs(1)),
Err(TransportError::Closed)
));
}
#[test]
fn clean_eof_is_closed_and_a_truncated_frame_is_a_frame_error() {
let mut silent = connection("pass");
assert!(matches!(
silent.receive(Instant::now() + Duration::from_secs(10)),
Err(TransportError::Closed)
));
let mut truncated = connection(
"import sys, struct; sys.stdout.buffer.write(struct.pack('>I', 10) + b'{}'); sys.stdout.buffer.flush()",
);
assert!(matches!(
truncated.receive(Instant::now() + Duration::from_secs(10)),
Err(TransportError::Frame(FrameError::PartialPayload { .. }))
));
}
}
}
@@ -1,5 +1,14 @@
# Marqdo 3.x 第三方开发者接入手册 # Marqdo 3.x 第三方开发者接入手册
> **历史文档(beta 时代记录)。** 本文于 `3.0.0-beta.1` 上验证并随其发布。
> beta 时代的 Analysis v2、Trace v2、Tool Protocol v1 与
> `run/call --trace-file` 等接口已被 [ADR-0068](adr/0068-single-current-public-contracts.md)
> 原地替换:当前契约是 Analysis v3、Observation v1、CLI Tool revision 1。
> 请以 `spec/`([analysis](spec/analysis.md)、[observation](spec/observation.md)、
> [cli-tool](spec/cli-tool.md))和
> [`developers/README.md`](developers/README.md) 为当前入口;本文仅作 beta
> 接洽流程与迁移背景保留,其中出现的旧命令/旧协议名不代表当前 CLI 可用。
>
> 状态:**随 `3.0.0-beta.1` 发布**(Linux x86_64 beta)。产品版本为 `3.0.0-beta.1`;协议版本独立:Analysis v2、Trace v2、Tool v1、Plugin ABI v1、Foreign wire v1、Provider manifest v2、Lock v4、Markdown profile `marqdo.md.v1`。官方 stdlib 包版本 `0.1.0`、插件/工具/示例包版本也都是独立版本轴,不随产品版本变化。 > 状态:**随 `3.0.0-beta.1` 发布**(Linux x86_64 beta)。产品版本为 `3.0.0-beta.1`;协议版本独立:Analysis v2、Trace v2、Tool v1、Plugin ABI v1、Foreign wire v1、Provider manifest v2、Lock v4、Markdown profile `marqdo.md.v1`。官方 stdlib 包版本 `0.1.0`、插件/工具/示例包版本也都是独立版本轴,不随产品版本变化。
> >
> 本文是入门与工程接洽流程;与已发布二进制冲突时,以该版本 `--help`、`--version`、`spec/` 和 release notes 为准。本文所有命令片段都已在 `3.0.0-beta.1` 二进制上验证;未验证的可能平台行为会明确标注为 UNVERIFIED/UNSUPPORTED,绝不默认为支持。 > 本文是入门与工程接洽流程;与已发布二进制冲突时,以该版本 `--help`、`--version`、`spec/` 和 release notes 为准。本文所有命令片段都已在 `3.0.0-beta.1` 二进制上验证;未验证的可能平台行为会明确标注为 UNVERIFIED/UNSUPPORTED,绝不默认为支持。
+155 -13
View File
@@ -1,12 +1,11 @@
# Marqdo Implementation Status # Marqdo Implementation Status
Snapshot: **2026-11-22**, product version **`3.0.0-beta.1`** (prerelease, tag Snapshot: **2026-11-24**, product version **`3.0.0-rc.3`** (prerelease
`v3.0.0-beta.1`). Released platform: **Linux x86_64 (glibc)**. Tagged source candidate). Last published prerelease: `3.0.0-rc.2` at source SHA
SHA: **`2c7c4f31e7a388d3fcfa717a77067e696ed13854`**; release: **`9149ee40a48fcda692c5c112f66c465487d13dfb`**; last published beta
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. The `3.0.0-beta.1` at **`2c7c4f31e7a388d3fcfa717a77067e696ed13854`**. The released
same-SHA evidence aggregate is platform is **Linux x86_64 (glibc 2.39)**. The RC gate aggregate for this
[`evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json) candidate is bound to the candidate SHA; its binary hashes are in the archive's
(decision `BETA_RELEASE_CANDIDATE`); binary hashes are in the archive's
`RELEASE_INFO.json`. Do not copy a SHA from a plan. `RELEASE_INFO.json`. Do not copy a SHA from a plan.
Current architecture overview: Current architecture overview:
@@ -26,12 +25,138 @@ as current status.
## RC candidate ## RC candidate
The workspace reports `3.0.0-rc.1` and declares Rust 1.89 as its locked The workspace reports `3.0.0-rc.3` and declares Rust 1.89 as its locked
minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The
[release procedure](releasing.md) requires a green manifest bound to the [release procedure](releasing.md) requires a green manifest bound to the
candidate SHA before publication. The release record below refers to the candidate SHA before publication. The release record below refers to the
published beta. published beta.
## Current protocol integration
[ADR-0068](adr/0068-single-current-public-contracts.md) and the
[single-contract policy](architecture/PROTOCOL_CONVERGENCE_POLICY.md) govern
every public boundary. Current developer inputs are
[Analysis](../spec/analysis.md), [Observation](../spec/observation.md) and the
[CLI Tool](../spec/cli-tool.md); the shared persistent-worker transport is
[worker-ipc](../spec/worker-ipc.md).
Issue [#8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) converged the
pre-stable contracts in one breaking integration, with no compatibility layer:
- Analysis has one writer and one current `schema_version` for every project,
including projects without loop transfers. The content-driven v2/v3 selector
and the retired `spec/analysis-v*.md` documents are gone.
- Trace and Execution Events became one Observation event definition. One
execution emits one `run_id`/`seq` sequence; `--output jsonl` and
`--observation-file` deliver those same events, never a second execution or a
second numbering. The retired `--json`/`--trace-file`/`--event-stream`
options are rejected.
- CLI Tool requirements are single exact integers (`api_revision`, optional
`analysis`, optional `observation`). Version arrays and intersection
negotiation are removed; retired registrations are rejected with a reinstall
instruction.
- Plugin and resource-provider workers share one bounded framed transport
([worker-ipc](../spec/worker-ipc.md)) while each boundary keeps its own
vocabulary, limits, capabilities and error codes.
- Extension descriptors (plugin/provider/kernel) and lock v4 keep their current
format identifiers. Retired lock versions are rejected with an explicit
`marqdo lock` regeneration instruction; there is no migrator. Renumbering an
unchanged format was explicitly rejected.
The `spec/` tree contains only current contracts; retired specifications are in
Git history and tagged archives. The earlier release records below describe
their tagged binaries and are not current protocol claims.
## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate)
The current tree replaces the retired protocols in place, with no compatibility
path. Policy: [ADR-0068](adr/0068-single-current-public-contracts.md) and
[the convergence policy](architecture/PROTOCOL_CONVERGENCE_POLICY.md). This
section records commands executed on the candidate tree; it is local Linux
evidence, not a same-SHA CI or archive gate.
Executed 2026-11-24 on the reviewed candidate tree, Linux x86_64
(workspace `3.0.0-rc.3`, Rust 1.100.0):
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS: 607 passed, 0 failed, 2 ignored
cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed
cargo test -p marqdo-cli --test docs_consistency PASS: 7 passed
cargo test -p marqdo-cli --test observation PASS: 16 passed
cargo test -p marqdo-cli --test analysis_observation PASS: 23 passed
cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed
cargo test -p marqdo-cli --test extension_selection PASS: 14 passed
cargo test -p marqdo-worker-ipc PASS: 5 passed
python3 -m unittest discover -s tools/ci -p "test_*.py" PASS: 41 tests
```
Black-box consumer run against the real `target/debug/marqdo`:
```text
check examples/multi-module/index.mq.md --refs --emit analysis.json schema marqdo.analysis/3
run examples/multi-module/index.mq.md --observation-file snap.json schema marqdo.observation/1
validate_protocols.py analysis.json snap.json tool.json PASS (7 modules, 333 events)
analysis_consumer.py analysis.json PASS (32 functions)
observation_consumer.py --snapshot snap.json --analysis analysis.json PASS
check tests/conformance/semantics/85-nested-loop-control.mq.md PASS
run ... --output jsonl --observation-file snapshot 66 events
observation_consumer.py stream.jsonl --validate-schema PASS (3 transfers)
snapshot["events"] == stream lines PASS
observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected
marqdo --version marqdo 3.0.0-rc.3
```
Same-SHA CI on the first (pre-review) candidate build, Linux x86_64
([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit
`5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full
Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows
cross-target compile check), `minimum-rust` and `build` all PASS. The build lane
produced `marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz`
(sha256 `d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37`),
passed the from-archive smoke, and passed the frozen external conformance suite
7/7 with fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`
(callable registry, plugin worker, foreign kernel, provider CLI, pinned package,
tool Analysis consumer, negative security).
The detailed local log and that CI addendum are in
[`evidence/2026-11-24-rc.3-protocol-convergence-local.md`](evidence/2026-11-24-rc.3-protocol-convergence-local.md);
they describe the protocol convergence itself. The reviewed candidate's own
same-SHA CI, archive and gate evidence are recorded in the release evidence
bound to the released SHA.
### 0.9.1 Review closure on the candidate tree
A code review of the first candidate build found and closed these defects
(regression test for each):
- A strict run no longer emits a partial JSONL stream for a destination it
refuses; live and file destinations are rejected before any session opens.
- `check --emit` removes a previous Analysis artifact when the project cannot
be loaded, not only when it has compile errors.
- Filesystem resource requests report their concrete effect operation
(`fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`,
`fs.rename`).
- The shared worker transport preserves `worker_frame_too_large` and
`worker_encode_failed` for the plugin boundary.
- Observation error locations no longer embed an absolute host path, and
pre-start option errors use the documented `options` phase.
- The event and snapshot schemas agree on the capture `level` enum.
- The G4 workload catalogue measures `run`/`call` through `--output json`; the
retired `--json` flag had made every non-check workload fail correctness.
- `spec/` and the current developer guides were brought back in line with the
binary, and a docs-consistency gate now fails when a retired interface or a
deleted spec path returns.
Release status: this section records local Linux evidence and the same-SHA CI
for the candidate. Publication additionally requires the RC profile gates in
[`releasing.md`](releasing.md) — same-SHA disposable-VM strict L1, clean
install, frozen extensions, version compatibility and G4 performance (the
maintainer-approved shared-node `WARN` for this named RC). Those results are
recorded in the evidence bound to the released SHA and in the release assets;
an unavailable strict host is fail-closed, never a downgrade.
## 0. Beta release record — `3.0.0-beta.1` ## 0. Beta release record — `3.0.0-beta.1`
### 0.1 Product, version axes and scope ### 0.1 Product, version axes and scope
@@ -39,9 +164,10 @@ published beta.
- Workspace/crate version, `marqdo --version` and Analysis `producer.version` - Workspace/crate version, `marqdo --version` and Analysis `producer.version`
are `3.0.0-beta.1`; `Cargo.lock` is committed and release builds use are `3.0.0-beta.1`; `Cargo.lock` is committed and release builds use
`--locked`. `--locked`.
- Independent axes are unchanged: Analysis v2, Trace v2, Tool v1, Plugin ABI - At the tagged beta, the axes were Analysis v2, Trace v2, Tool v1, Plugin ABI
v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile
`marqdo.md.v1`; bundled stdlib stays package version `0.1.0`. `marqdo.md.v1`; bundled stdlib stayed package version `0.1.0`. Those are
historical identifiers, not current claims.
- `project.marqdo` is enforced; prerelease SemVer rules are covered by tests - `project.marqdo` is enforced; prerelease SemVer rules are covered by tests
(`>=3.0.0,<4.0.0` does not silently accept a beta core). (`>=3.0.0,<4.0.0` does not silently accept a beta core).
- Only the Linux x86_64 archive is claimed. macOS/Windows are - Only the Linux x86_64 archive is claimed. macOS/Windows are
@@ -102,12 +228,12 @@ exports reconcile exactly with the static manifest. The independent
frozen-binary suite is the beta gate above; the older `6a7bb98` manifest is frozen-binary suite is the beta gate above; the older `6a7bb98` manifest is
historical and superseded by the release-SHA manifest. historical and superseded by the release-SHA manifest.
## 0.5 Post-beta addition — Execution Events v1 (unreleased) ## 0.5 Historical: post-beta Execution Events v1 (superseded by Observation)
This section records work **after** the `v3.0.0-beta.1` tag. It is not part of This section records work **after** the `v3.0.0-beta.1` tag. It is not part of
the tagged beta archive and no new release tag has been created. The design the tagged beta archive and no new release tag has been created. The design
input is RFC-OBS-0001 (issue `#1`), the frozen decision is ADR-0059 and the input is RFC-OBS-0001 (issue `#1`), the frozen decision is ADR-0059 and the
normative contract is [`spec/execution-events-v1.md`](../spec/execution-events-v1.md). normative contract is [the beta-era event contract](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/execution-events-v1.md).
Executed evidence for this section is Executed evidence for this section is
[`evidence/2026-11-22-execution-events-v1.md`](evidence/2026-11-22-execution-events-v1.md). [`evidence/2026-11-22-execution-events-v1.md`](evidence/2026-11-22-execution-events-v1.md).
@@ -264,6 +390,22 @@ digests. The external lane ran from a temporary fixture checkout with Cargo
absent from PATH. Archive SHA-256 is absent from PATH. Archive SHA-256 is
`8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`. `8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`.
## 0.8 Historical: structured control flow — RFC-CTRL-0005 (RC.2 snapshot)
[ADR-0067](adr/0067-structured-control-flow.md) covers the phase A implementation.
An `else if` carrier adds a condition arm to the existing branch IR.
`break` and `continue` transfer to the nearest loop in the same heading
execution segment. Binding inference joins only reachable control exits.
The [runnable example](../examples/control-flow.mq.md) uses ordinary Markdown
list containers.
[the shipped rc.2 Analysis contract](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/analysis-v3.md) represents the loop transfer statements.
Other documents continue to emit v2. Trace v2 and Execution Events v1 expose
the new control events. The published beta evidence applies to its original
SHA. The maintainer selected phase A for RC.2. List iteration
is a follow-up design. The [pre-candidate local verification record](evidence/2026-11-23-rfc-ctrl-0005.md)
identifies the tested commit, commands, archive digest and consumer results.
## 1. Historical: pre-beta remote baseline and evidence ## 1. Historical: pre-beta remote baseline and evidence
> **Historical record.** Everything in §1 onward was executed before the > **Historical record.** Everything in §1 onward was executed before the
@@ -656,7 +798,7 @@ Consumer evidence:
```bash ```bash
./target/debug/marqdo check examples/multi-module/index.mq.md --refs --emit /tmp/a.json ./target/debug/marqdo check examples/multi-module/index.mq.md --refs --emit /tmp/a.json
./target/debug/marqdo run examples/multi-module/index.mq.md --trace-file /tmp/t.json ./target/debug/marqdo run examples/multi-module/index.mq.md --observation-file /tmp/observation.json
python3 tests/consumers/analysis_consumer.py /tmp/a.json python3 tests/consumers/analysis_consumer.py /tmp/a.json
python3 tests/consumers/trace_consumer.py /tmp/a.json /tmp/t.json python3 tests/consumers/trace_consumer.py /tmp/a.json /tmp/t.json
``` ```
+3
View File
@@ -1,5 +1,8 @@
# ADR-0006: CLI output, exit-code and JSON contract # ADR-0006: CLI output, exit-code and JSON contract
> Historical public protocol sections. Current Analysis, runtime output and
> Tool contracts are specified by [ADR-0068](0068-single-current-public-contracts.md).
Status: **Accepted** Status: **Accepted**
Date: 2026-11-20 Date: 2026-11-20
@@ -1,5 +1,8 @@
# ADR-0013: Generic external CLI Tool Protocol v1 # ADR-0013: Generic external CLI Tool Protocol v1
> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes
> the public contracts described in this record.
Status: **Accepted** Status: **Accepted**
Date: 2026-11-20 Date: 2026-11-20
@@ -1,5 +1,8 @@
# ADR-0015: Public Analysis v1 and Trace v1 # ADR-0015: Public Analysis v1 and Trace v1
> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes
> the public contracts described in this record.
Status: **Accepted** Status: **Accepted**
Date: 2026-11-20 Date: 2026-11-20
@@ -1,11 +1,15 @@
# ADR-0059: Runtime observability and Execution Events v1 # ADR-0059: Runtime observability and Execution Events v1
> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes
> the public contracts described in this record.
- **Status:** Accepted - **Status:** Accepted
- **Date:** 2026-11-22 - **Date:** 2026-11-22
- **Decision owners:** CLI, runtime and host maintainers - **Decision owners:** CLI, runtime and host maintainers
- **Inputs:** [RFC-OBS-0001](../architecture/RFC-OBS-0001-runtime-observability.md) - **Inputs:** RFC-OBS-0001 (issue `#1` of `cflmy/marqdo-cli`), Trace v2,
(issue `#1` of `cflmy/marqdo-cli`), [Trace v2](../../spec/trace-v2.md), Analysis v2 and Tool Protocol v1. Those documents were retired in place by
[Analysis v2](../../spec/analysis-v2.md), [Tool Protocol v1](../../spec/tool-v1.md) [ADR-0068](0068-single-current-public-contracts.md) and are available at
their tagged commits, not in the current `spec/` tree.
## Context ## Context
+45
View File
@@ -0,0 +1,45 @@
# ADR-0067 — Multi-arm branches and nearest-loop control
> Historical public protocol sections. Current Analysis, runtime output and
> Tool contracts are specified by [ADR-0068](0068-single-current-public-contracts.md).
Status: Accepted for development. Release inclusion requires a maintainer
decision and the applicable same-SHA release gates.
Implements stage A of [RFC-CTRL-0005](https://git.cflmy.cn/cflmy/marqdo-cli/issues/7)
as an amendment to [RFC-LANG-0002](../architecture/RFC-LANG-0002-unified-semantics.md)
and the existing [mapping](../../spec/mapping.md) and
[grammar](../../spec/expression.ebnf). Follow the frontend → IR → interpreter
boundary in the [development blueprint](../DEVELOPMENT_BLUEPRINT.md#7-rust-独立解释器ir值系统与执行内核).
## Language and execution
An `else if` carrier adds an arm to the existing Branch IR. Condition
evaluation is ordered and short-circuited. A separate `else` carrier followed
by `if` keeps its nested meaning. The frontend owns pairing, heading
boundaries, and diagnostics. The Markdown profile and carrier mapping stay
the same.
A complete `break` or `continue` payload is contextual loop control. Existing
names in functions, parameters, fields, calls and expressions stay valid.
The ambiguous case is a standalone identifier read, which can be written
with parentheses. The runtime propagates a structured result to the nearest
loop, with the usual statement and iteration budgets. The loop consumes that
result within the current function. Static binding analysis only merges
reachable exits and keeps the function's initial loop-entry binding rules.
## Public projections
Branch arms fit Analysis v2. A project containing a loop transfer requires
Analysis v3, which preserves the envelope and adds the statement kinds
`break` and `continue`. The writer selects the required version from the
project. A v2 reader can keep reading existing output and rejects v3 at the
envelope. Trace v2 adds `control.break` and `control.continue` to its open
event vocabulary. Execution Events v1 adds the corresponding events, carrying
only the existing frame/module/span fields. The Trace digest binds to the
automatically selected Analysis document. Markdown, ABI and Host operation
versions are independent of this change.
Stage B List iteration requires a separate decision on snapshot and binding
semantics. Release approval and ecosystem adoption are tracked outside this
implementation.
@@ -0,0 +1,55 @@
# ADR-0068 — One current contract per public boundary
Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-24).
## Context
Issue [#8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) identified two
independent Analysis version selectors. A tool could install successfully
even when it could not read the output for a given project. The runtime
also projected the same execution into independently defined Trace and
Execution Events protocols. The compilation pipeline described in
DEVELOPMENT_BLUEPRINT §7 remains the source of language facts.
## Decision
Before the first stable release, replace a broken public contract in place.
For each boundary, keep one current format identifier, one producer and one
validation path. Reject mismatches explicitly. Update the CLI, schemas,
consumers, fixtures and CI in the same integration. Use Git history and
release tags to retrieve retired specifications. A future stable release
requires its own compatibility policy.
- Analysis is always `marqdo.analysis` revision 3, including projects without
loop transfers. The Markdown AST and IR remain internal authorities.
- Runtime observations use `marqdo.observation` revision 1. One run emits
one sequence. JSONL stdout and JSON snapshots deliver those same events.
`run` and `call` use `--output text|json|jsonl` and
`--observation-file PATH`. Capture selections and budgets apply to all
observation destinations.
- Tool manifests use `marqdo.cli-tool` with its existing revision 1, a required
`requires.api_revision: 1` and optional exact Analysis and Observation
requirements. Reinstall tools registered under earlier formats. The
existing Tool subcommands and external dispatch suffice for this workflow.
Required fields and strict validation reject retired input at the existing
format identifier. This change introduces no new numeric protocol versions.
- Keep the three current extension descriptors. Callable exports, resource
rights and foreign interpreter selection have independent validation and
lifecycles. Share value encoding and equivalent process transport
primitives. Keep Lock v4 because its graph and artifact identities still
describe the selected extensions without a format change.
## Security and verification
Static analysis stays non-executing. Observation binds to the exact Analysis
artifact and defaults to structural capture. Selected values, Text consent,
handles, buffering, output bytes and failure/truncation must follow the
current observation contract. Preserve native trust, process timeouts,
worker quarantine, capability grants, artifact integrity and fail-closed
strict behavior.
Exercise real CLI output with an independent consumer, including old-input
rejection, two simultaneous destinations from a single invocation, source
digest mismatches, allowlisted capture, and consumer installation. Validate
independent View and Lint against the final CLI, then validate the shipped
archive and its SHA-bound release evidence before tagging an RC.
+2 -1
View File
@@ -64,4 +64,5 @@ Files: `0001`–`0050`, plus:
* [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful * [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful
operations and child resources; operations and child resources;
* [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded * [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded
communication and cancellation. communication and cancellation;
* [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers.
+57 -17
View File
@@ -27,14 +27,6 @@ replace `spec/` or a recorded test log.
> [`spec/extension-selection.md`](../../spec/extension-selection.md), > [`spec/extension-selection.md`](../../spec/extension-selection.md),
> [`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md). > [`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md).
> >
> **Post-baseline observability (ADR-0059, RFC-OBS-0001).** After the tagged
> baseline the tree adds Execution Events v1: a typed host observation facade,
> real-commit stdout/stderr chunks, run-unique call frames and explicitly
> selected bounded values over `run/call --event-stream jsonl`. Analysis v2 and
> Trace v2 are unchanged. This is locally tested on the post-baseline tree
> ([`../STATUS.md`](../STATUS.md) §0.5) and is not part of the tagged beta
> archive or its same-SHA evidence.
>
> **Post-baseline core/extension boundary (RFC-EXT-0003, ADR-0060–0063).** The > **Post-baseline core/extension boundary (RFC-EXT-0003, ADR-0060–0063).** The
> core call surface no longer owns the domain math kernel (`math.*` removed; > core call surface no longer owns the domain math kernel (`math.*` removed;
> `crates/marqdo-math` deleted; ADR-0061), sibling heading mode inheritance is > `crates/marqdo-math` deleted; ADR-0061), sibling heading mode inheritance is
@@ -55,6 +47,41 @@ replace `spec/` or a recorded test log.
> [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed. > [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed.
> See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased). > See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased).
> **Structured control flow (RFC-CTRL-0005).**
> [ADR-0067](../adr/0067-structured-control-flow.md) extends the payload parser
> and branch mapper, adds nearest-loop execution transfers and makes binding
> inference path-sensitive. Analysis projects the same branch and loop
> structure for every module. The interpreter reports transfers through Host
> observation.
## Public boundaries and pre-stable changes
[ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy
for replacing public interfaces before the first stable release.
| Boundary | Owner | Current contract |
|---|---|---|
| Static facts | CLI Analysis projection of the prepared project | [Analysis](../../spec/analysis.md) |
| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) |
| Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) |
| Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) |
| Persistent worker plumbing | Plugin and provider workers share one bounded framed transport; each keeps its vocabulary, limits and authority | [Shared worker transport](../../spec/worker-ipc.md) |
| Values and package identities | Value Wire and project lock | [Value Wire](../../spec/value-wire.md), [Extension selection and lock](../../spec/extension-selection.md) |
`check --emit analysis.json` projects static facts from the prepared project.
`run` and `call` execute the same prepared program through the CapabilityHost.
`--output jsonl` provides live events and `--observation-file run.json` saves
the same event sequence from that invocation. Consumers verify the exact
Analysis bytes before marking execution spans in source.
When replacing a contract, update its producer, specification, schema, real
consumers, fixtures and CI in one integration. Every required field and format
identifier should correspond to a check at the boundary. Reject obsolete
inputs with a corrective action. Keep historical formats in Git. Review
grants, budgets, file integrity, source attribution and privacy independently
of the transport change. Check the [implementation status](../STATUS.md)
for executed evidence and release gates.
## 1. Four state dimensions ## 1. Four state dimensions
A claim is stated in exactly one of these dimensions. "Exists in the tree" is not A claim is stated in exactly one of these dimensions. "Exists in the tree" is not
@@ -63,7 +90,7 @@ platform".
| Dimension | Current state | Source | | Dimension | Current state | Source |
|---|---|---| |---|---|---|
| Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; post-baseline Execution Events v1 (ADR-0059), core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` | | Implemented | Rust workspace: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool, Analysis and Observation, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` |
| Tested locally | `cargo test --workspace --locked`, `cargo fmt --all -- --check`, `clippy -D warnings`, release archive smoke and an independent `ubuntu:24.04` cold-install run on the RFC-EXT-0003 tree (Linux x86_64); exact counts and logs are in `docs/STATUS.md` §0.6 and the RFC-EXT-0003 evidence file. Historical baselines stay in earlier sections. | `docs/STATUS.md` §0.6, `docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md` | | Tested locally | `cargo test --workspace --locked`, `cargo fmt --all -- --check`, `clippy -D warnings`, release archive smoke and an independent `ubuntu:24.04` cold-install run on the RFC-EXT-0003 tree (Linux x86_64); exact counts and logs are in `docs/STATUS.md` §0.6 and the RFC-EXT-0003 evidence file. Historical baselines stay in earlier sections. | `docs/STATUS.md` §0.6, `docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md` |
| Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` | | Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` |
| Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 | | Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 |
@@ -85,7 +112,7 @@ execution: Value / MemoryStore / evaluator / budgets
(computes; does not own stdout or file handles) (computes; does not own stdout or file handles)
| |
controlled platform API: open/read/write/close + non-streaming requests controlled platform API: open/read/write/close + non-streaming requests
capability / budget / audit / trace capability / budget / audit / observation
stdio / file / tcp / OS adapters stdio / file / tcp / OS adapters
explicitly registered providers (in-process / worker / C ABI) explicitly registered providers (in-process / worker / C ABI)
| |
@@ -116,8 +143,8 @@ Layer rules:
5. Callable Plugin and Resource Provider share one registry/authorization/audit 5. Callable Plugin and Resource Provider share one registry/authorization/audit
mechanism, but keep different capability types. mechanism, but keep different capability types.
6. CLI policy/commands are `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; 6. CLI policy/commands are `commands/{sandbox,run,check,inspect,init,package,tool}.rs`;
host open-path/providers/effects/dispatch are host open-path/providers/dispatch are
`host/{resource_ops,providers,effects,dispatch}.rs`; process execution is `host/{resource_ops,providers,dispatch}.rs`; process execution is
`process.rs`. These are child modules, not new crates or a second backend. `process.rs`. These are child modules, not new crates or a second backend.
## 3. Dependency direction and public contracts ## 3. Dependency direction and public contracts
@@ -128,9 +155,17 @@ Current Rust dependency edges (documented, not proposed):
marqdo-cli -> marqdo-runtime -> marqdo-host marqdo-cli -> marqdo-runtime -> marqdo-host
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ... marqdo-cli -> 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-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc
marqdo-plugin-abi -> marqdo-worker-ipc
marqdo-provider-worker -> marqdo-worker-ipc
``` ```
`marqdo-worker-ipc` depends only on `serde_json` and `thiserror`: it is the one
copy of bounded worker framing, deadlines and process teardown
([spec/worker-ipc.md](../../spec/worker-ipc.md)). It must never depend on the
host, the plugin ABI, or a worker binary; sharing plumbing must not share
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` is the current direction. Do not add a second
execution backend or a `marqdo-stdlib` crate by implication. A future embedded execution backend or a `marqdo-stdlib` crate by implication. A future embedded
runtime or a second backend needs the thin `ExecutionPort` contract described in the runtime or a second backend needs the thin `ExecutionPort` contract described in the
@@ -139,7 +174,7 @@ review RFC, not a new crate per provider.
| Public contract | API (`.mq.md`) | State | Tests | | Public contract | API (`.mq.md`) | State | Tests |
|---|---|---|---| |---|---|---|---|
| stdio stdin | `resource.open("stdio","stdin",["read"])`, `resource.read`, `resource.close`; one run-scoped cursor | implemented, read-only | `resource_streams`, `p2_closure`, `tests/conformance` | | stdio stdin | `resource.open("stdio","stdin",["read"])`, `resource.read`, `resource.close`; one run-scoped cursor | implemented, read-only | `resource_streams`, `p2_closure`, `tests/conformance` |
| Execution Events v1 | `run/call --event-stream jsonl`; `--observe-variable`, `--observe-parameter`, `--observe-text-values` | implemented P0/P1 (post-beta); P2 memory metadata deferred; strict refuses the option | `execution_events` CLI, `observation` host/runtime, `execution_events_consumer.py` | | Observation | `run/call --output jsonl`, `--output json` or `--observation-file PATH` | one event sequence and capture policy | `observation`, `analysis_observation`, `observation_consumer.py` |
| stdio stdout | `resource.open("stdio","stdout",["write"])`, `resource.write`, `resource.close`; separate output budget | implemented | `stdlib_bundle`, `print_routing`, `resource_streams` | | stdio stdout | `resource.open("stdio","stdout",["write"])`, `resource.write`, `resource.close`; separate output budget | implemented | `stdlib_bundle`, `print_routing`, `resource_streams` |
| stdio stderr | `resource.open("stdio","stderr",["write"])`; separate from stdout and CLI diagnostics | implemented | `resource_streams`, `stdlib_product` | | stdio stderr | `resource.open("stdio","stderr",["write"])`; separate from stdout and CLI diagnostics | implemented | `resource_streams`, `stdlib_product` |
| project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` | | project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` |
@@ -148,7 +183,7 @@ review RFC, not a new crate per provider.
| `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` | | `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` |
| core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` | | core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
| `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` | | `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
| Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); third-party heading annotations are **Proposed** metadata only, Analysis v2 unchanged (H-05/H-07) | core mode: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` | | Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); third-party heading annotations are **Proposed** metadata only, Analysis v3 unchanged (H-05/H-07) | core mode: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` |
| Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` | | Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` |
| `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` | | `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` |
| `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` | | `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` |
@@ -164,7 +199,7 @@ review RFC, not a new crate per provider.
| `std:net/http` | byte-exact HTTP/1.1 parse/build; chunk sizes are byte counts; text wrapper compatible | implemented (pure `.mq.md`) | `stdlib_http` | | `std:net/http` | byte-exact HTTP/1.1 parse/build; chunk sizes are byte counts; text wrapper compatible | implemented (pure `.mq.md`) | `stdlib_http` |
| HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` | | HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` |
| print / official stdlib aliases | `打印`/`print` are verified `stdlib.json` public aliases bound to `io.mq.md::写值`; ordinary Marqdo calls, no `print_override`, no runtime branch, no `HostOp::Print` | implemented (ADR-0058) | `stdlib_alias_routing`, `print_routing`, `stdlib_product` | | print / official stdlib aliases | `打印`/`print` are verified `stdlib.json` public aliases bound to `io.mq.md::写值`; ordinary Marqdo calls, no `print_override`, no runtime branch, no `HostOp::Print` | implemented (ADR-0058) | `stdlib_alias_routing`, `print_routing`, `stdlib_product` |
| callable resolution | one registry + one `bind_program_calls` pass; `check`/`run`/`inspect`/Analysis share `CallSiteKey` bindings; plugin exports reconcile exactly with static manifests; no runtime name fallback | implemented (ADR-0054) | `callable_resolution`, `plugin_worker`, `analysis_trace` | | callable resolution | one registry + one `bind_program_calls` pass; `check`/`run`/`inspect`/Analysis share `CallSiteKey` bindings; plugin exports reconcile exactly with static manifests; no runtime name fallback | implemented (ADR-0054) | `callable_resolution`, `plugin_worker`, `analysis_observation` |
| resource provider v2 CLI | `--provider`/`--allow-provider` select and authorize a `provider.json` schema-2 `c-abi-1` worker artifact; manifest/artifact/grants/duplicate kinds verified before spawn; sibling helper only | implemented linux/x86_64; other platforms fail closed (ADR-0055) | `provider_cli` | | resource provider v2 CLI | `--provider`/`--allow-provider` select and authorize a `provider.json` schema-2 `c-abi-1` worker artifact; manifest/artifact/grants/duplicate kinds verified before spawn; sibling helper only | implemented linux/x86_64; other platforms fail closed (ADR-0055) | `provider_cli` |
| capability handlers | trusted handler registry executes granted capabilities under budget/audit; missing handler is `capability.unavailable`; `fs.read` is the first real handler | implemented (ADR-0057) | `capability_handlers` | | capability handlers | trusted handler registry executes granted capabilities under budget/audit; missing handler is `capability.unavailable`; `fs.read` is the first real handler | implemented (ADR-0057) | `capability_handlers` |
| strict mode | only the pure/Math execution path and the built-in stdout console channel; project/foreign/plugin/tool/trace/file/network grants are rejected | implemented L1; L2 not implemented | `tests/security`, `resource_streams`, `stdlib_product` | | strict mode | only the pure/Math execution path and the built-in stdout console channel; project/foreign/plugin/tool/trace/file/network grants are rejected | implemented L1; L2 not implemented | `tests/security`, `resource_streams`, `stdlib_product` |
@@ -194,7 +229,7 @@ that a phase is complete.
| 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 |
| P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,effects,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design | | P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design |
| P2 | HTTP/1.1 framing is byte-exact; HTTP/2, trailers and transfer decoding remain open | open | | P2 | HTTP/1.1 framing is byte-exact; HTTP/2, trailers and transfer decoding remain open | open |
| P2 | DNS, UDP, TCP listener and TLS client endpoints are implemented; no TLS server/mTLS or custom-CA CLI | open | | P2 | DNS, UDP, TCP listener and TLS client endpoints are implemented; no TLS server/mTLS or custom-CA CLI | open |
| P2 | `std:path`, pure+host regex, `std:datetime`, `std:clock`, `std:env`, `std:process`, `std:random` and gzip compression are implemented; no streaming/zstd/brotli | open | | P2 | `std:path`, pure+host regex, `std:datetime`, `std:clock`, `std:env`, `std:process`, `std:random` and gzip compression are implemented; no streaming/zstd/brotli | open |
@@ -223,10 +258,15 @@ that a phase is complete.
5. When behavior or status changes, update code + tests + `docs/STATUS.md` + 5. When behavior or status changes, update code + tests + `docs/STATUS.md` +
this file + an evidence file in the same change. A fixture/demo is not a this file + an evidence file in the same change. A fixture/demo is not a
published stdlib API. published stdlib API.
6. A public-boundary change must follow
[`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md): one
current contract, replace in place, reject retired inputs, no compatibility
path or version negotiation, and no version bump without a shape change.
## 7. References ## 7. 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.
- [Implementation status](../STATUS.md) — executed state and blockers. - [Implementation status](../STATUS.md) — executed state and blockers.
- [Language/frontmatter blueprint](../DEVELOPMENT_BLUEPRINT.md) — design baseline; not current status. - [Language/frontmatter blueprint](../DEVELOPMENT_BLUEPRINT.md) — design baseline; not current status.
- [3.0 prerelease plan](../MARQDO_3_0_PRERELEASE_PLAN.md) — current release policy and beta gates. - [3.0 prerelease plan](../MARQDO_3_0_PRERELEASE_PLAN.md) — current release policy and beta gates.
@@ -0,0 +1,202 @@
# Protocol convergence policy (pre-stable)
Status: **current contributor policy**. Owner: architecture review. Authority:
[ADR-0068](../adr/0068-single-current-public-contracts.md), adopted for
[issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) before the first
stable release. This page is the checklist that prevents the same failure from
returning; it does not replace `spec/` or an ADR.
## 1. The failure this policy prevents
Before issue #8 the tree kept several competing models of the same fact:
- Analysis chose `schema_version` 2 or 3 from the **content** of the project
(presence of `break`/`continue`), and a Tool declared an **array** of
Analysis versions and installed when the arrays intersected. Installation
succeeded while the actual output stayed unreadable for that project.
- Trace and Execution Events each defined a public representation of the same
execution, with separate writers, budgets and privacy rules.
- `spec/` still carried superseded Analysis/Trace/Events documents beside the
current ones, so a reader could not tell which contract the binary emitted.
The root cause was not "too many JSON files". It was **maintaining a replaced
architecture as a second live path** after the architecture had changed. The
cure is one current contract per real boundary, replaced in place, with
retired inputs rejected explicitly.
## 2. Current boundary map
Every row has exactly one current contract. A change must keep it that way.
| Real boundary | Current contract | Single producer / validator | Retired, kept in Git only |
|---|---|---|---|
| Markdown syntax | [`markdown-profile.md`](../../spec/markdown-profile.md) `marqdo.md.v1` | `marqdo-markdown` (frozen Comrak options) | older profiles |
| Language mapping | [`mapping.md`](../../spec/mapping.md), [`expression.ebnf`](../../spec/expression.ebnf) | `marqdo-frontend` + `marqdo-expression` | pre-RFC-LANG-0002 mapping |
| Static facts | [`analysis.md`](../../spec/analysis.md) + `analysis.schema.json` | `crates/cli/src/analysis.rs` | Analysis v1/v2/v3 split |
| Runtime facts | [`observation.md`](../../spec/observation.md) + two schemas (event, snapshot) | Host observation sink, CLI assigns `run_id`/`seq` | Trace v1/v2, Execution Events v1 |
| Installed commands | [`cli-tool.md`](../../spec/cli-tool.md) + `cli-tool.schema.json` | `crates/cli/src/tool.rs` | Tool v1 arrays/negotiation |
| C ABI | [`plugin-abi.md`](../../spec/plugin-abi.md) + C header | `marqdo-plugin-abi`, SDK | obsolete ABI major |
| Foreign kernels | [`foreign.md`](../../spec/foreign.md) wire v1 | `marqdo-foreign` (one-shot) | retired wire/versions |
| Resource providers | [`resource-provider-v2.md`](../../spec/resource-provider-v2.md) manifest v2 | CLI manifest validation + Host worker | retired manifests |
| Worker plumbing | [`worker-ipc.md`](../../spec/worker-ipc.md) (internal, no version) | `marqdo-worker-ipc` | private framing copies |
| Extension selection + lock | [`extension-selection.md`](../../spec/extension-selection.md), lock v4 | `marqdo-package` + CLI | lock v1–v3 readers/migrators |
| Values | [`value-wire.md`](../../spec/value-wire.md) | `marqdo-value::wire` | alternate encoders |
A boundary may have **two root objects** of one contract (currently Observation
event and snapshot). Two root objects are not two protocols: they share one
event definition and one schema authority.
## 3. Rules
### 3.1 One current contract per boundary
- One current format identifier, one producer, one validation path.
- No selection of a schema from project content, feature detection or runtime
state.
- No multi-version arrays, version ranges, "highest shared version", capability
probing or intersection negotiation.
- No simultaneous emission of an old and a new format, and no compatibility
adapter between two writers.
### 3.2 Replace in place, in one integration
- Change the producer, specification, JSON Schema, independent consumers,
fixtures and CI in the same change series. The intermediate commits on a
branch may be incomplete; a merged state may not contain two live paths.
- Delete the replaced implementation, spec and fixtures in that integration.
Git history and tagged archives are the archaeology; `spec/` is not.
- Keep the existing format identifier when the contract **shape** does not
change. Do not renumber formats for appearance, symmetry or "freshness"
(**no version bump without a shape change**). Conversely, when the shape
changes, an in-place replacement at the existing identifier is allowed
pre-stable and preferred over adding a parallel version.
### 3.3 Reject, never migrate silently
- Unsupported formats, versions, fields and command options fail with a
corrective action (for example "run `marqdo lock` to regenerate", "remove and
reinstall the tool").
- No automatic upgrade of an old lock, tool record, manifest or machine output;
no field guessing; no fallback to a legacy reader; no "temporarily accept
both".
- Keep historical formats retrievable from Git and release tags, but do not let
the current binary read them.
### 3.4 Never trade a safety invariant for convergence
Removing a compatibility path must not remove integrity, authorization, type
checks, worker timeouts, size limits, secret handling or OS-isolation gates.
Convergence is about the fact model, not about relaxing it. When deleting code
that looks like "legacy compatibility", confirm first that it is not one of:
- Analysis/Observation digest binding and source attribution;
- tool bundle hashing, entrypoint/path/symlink checks, command-conflict checks;
- plugin/provider artifact target/path/sha256 verification and native trust;
- capability grants, declared-vs-installed handler checks, budgets;
- strict mode fail-closed behavior and worker quarantine;
- Value Wire type fidelity and non-transferable handle rules.
### 3.5 Preserve privacy when merging fact models
A unified model must keep the strictest privacy default of the models it
replaces. Today value observation is off by default; selected names must be
declared; Text needs separate consent; Memory/Handle are never serialized.
Merging Trace into Observation never blesses Trace-era value exposure.
## 4. Mandatory change procedure
For any change to a public boundary, in order:
1. **ADR.** Record the single target design, the boundary, the identifier
decision (keep or replace) and what is deleted. If an ADR is superseded, mark
its header Historical so no reader treats it as current.
2. **Specification in place.** Update the one current `spec/*.md` (never add a
parallel "v-next" current spec). Update the JSON Schema if one exists.
`spec/` must describe only what the current tree emits.
3. **One producer, one validator.** Delete the alternate selection logic, the
second writer, the legacy reader and their dead error paths in the same
series. `grep` is evidence: no `legacy`, `compat`, `schema_v2_or_v3`,
`shared_version`, version arrays or fallback branches may remain runnable.
4. **Fixtures and consumers.** Replace goldens with ones produced by the **real
CLI**, update the independent consumer(s), and add negative fixtures for the
retired input. Never weaken or delete a security/semantic negative test to
go green.
5. **CLI and docs.** Update `--help`, README, developer guides, examples and
release/smoke scripts. No alias for a retired option.
6. **Enforcement gate.** Add or keep a source-level check that the duplicate
cannot quietly return (see `architecture_boundaries` tests; for example the
shared worker transport test forbids reimplementing framing).
7. **Evidence.** Record the executed commands in `docs/STATUS.md` and an
evidence file with the exact SHA. A design document is not evidence.
## 5. Anti-patterns — do not do these
| Tempting move | Why it is rejected | Do instead |
|---|---|---|
| Keep v2 output for "simple" projects | Content-driven schema selection is the original bug | One writer, one identifier |
| Accept `analysis: [2,3]` and pick the intersection | Installs succeed when output is unreadable | One exact requirement, reject mismatch |
| Add `--legacy`, `compat`, `map_v1` or per-file switch | Reintroduces a second live architecture | Replace the current path; delete the old one |
| Keep the old writer behind a new "Unified" trait | Cosmetic abstraction over two fact models | One producer feeding all destinations |
| Rename `analysis-v3.md` to `analysis.md` only | Docs claim what code does not do | Update code, schema, fixtures, consumers together |
| Accept old lock/tool/extension silently | Hides a broken upgrade and loses integrity | Fail with an explicit regenerate/reinstall message |
| Delete security tests to make CI green | Convergence must not lower the bar | Keep/strengthen negatives |
| Renumber an unchanged format "to be safe" | Creates migration cost without a shape change | Keep the existing identifier |
| Add a second observation writer per destination | Two sources of truth for one execution | One event sequence, many destinations |
| Share worker capabilities with shared framing | Transport sharing is not authority sharing | Share framing only; keep grants per boundary |
## 6. Review checklist
A reviewer must be able to answer "yes" to all of these before approving a
protocol-boundary change:
- [ ] Does this boundary still have exactly one current contract and one
producer/validator?
- [ ] Did the replaced spec/implementation/fixtures get deleted in this
integration (not scheduled "later")?
- [ ] Are retired inputs rejected with a corrective action, with no migrator,
alias, fallback or field guessing?
- [ ] Is the format identifier unchanged unless the contract shape changed?
- [ ] Do independent consumers and real-CLI fixtures validate the new artifact,
including at least one negative case?
- [ ] Are digest binding, attribution, grants, budgets, timeouts, size limits,
secret handling and strict-mode fail-closed behavior intact and tested?
- [ ] Does the privacy default stay structural, with explicit value/Text
consent?
- [ ] Are `--help`, README, developer docs, examples and release smoke updated
to the current contract only?
- [ ] Is there a source-level gate preventing the duplicate path from returning?
- [ ] Is the executed evidence recorded against a SHA (not a plan or a claim)?
## 7. Definition of Done for a convergence change
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D
warnings`, `cargo test --workspace --locked` pass.
- `cargo test -p marqdo-cli --test architecture_boundaries --test
docs_consistency` pass.
- Independent consumers validate real CLI output; schema files parse; retired
options and formats are proven rejected.
- `spec/` contains no superseded current-contract document; retired ADRs carry a
Historical header; `docs/STATUS.md` names the executed evidence.
- The release archive smoke test is updated before an RC is tagged, and the RC
evidence is bound to the archive's SHA.
## 8. Stable-release boundary
Everything above applies **before the first stable release**. After the first
stable release a separate compatibility policy must define which contracts are
stabilized, the deprecation window and the upgrade rules. Do not import
post-stable compatibility obligations into the pre-stable tree, and do not
assume this policy authorizes breaking stable contracts later.
## 9. Where the policy is enforced
| Enforcement | Artifact |
|---|---|
| Absolute language/architecture rules | [`AGENTS.md`](../../AGENTS.md) |
| Public-contract decision | [ADR-0068](../adr/0068-single-current-public-contracts.md) |
| Architecture overview and boundary table | [`architecture/CURRENT.md`](CURRENT.md) |
| Normative contracts | `spec/*.md` + `spec/schemas/*.json` |
| Source-level boundary gates | `crates/cli/tests/architecture_boundaries.rs` |
| Docs/link/status gates | `crates/cli/tests/docs_consistency.rs` |
| Independent consumers | `tests/consumers/*.py` |
| Release evidence | [`STATUS.md`](../STATUS.md), `docs/evidence/`, `docs/releasing.md` |
+4 -1
View File
@@ -5,6 +5,9 @@ Status: **index**. The single current architecture overview is
input and evidence. It is not a second running-status page. input and evidence. It is not a second running-status page.
- Current architecture and four state dimensions: [`CURRENT.md`](CURRENT.md). - Current architecture and four state dimensions: [`CURRENT.md`](CURRENT.md).
- Public-contract convergence rules and review checklist:
[`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md)
([ADR-0068](../adr/0068-single-current-public-contracts.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
@@ -21,7 +24,7 @@ input and evidence. It is not a second running-status page.
|---|---|---| |---|---|---|
| [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. |
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Adopted and implemented (P0/P1)** | Typed host observation, Execution Events v1 NDJSON, frame identity, selected bounded values; P2 memory metadata remains deferred. | | [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. |
| RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. | | RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. |
@@ -526,8 +526,11 @@ import:
| 关键字 | 语法 | 含义 | 是否新增计算原语 | | 关键字 | 语法 | 含义 | 是否新增计算原语 |
|---|---|---|---| |---|---|---|---|
| `if` | `if <Bool expression>` | 开始条件分支 | 否,映射已有 `Branch` | | `if` | `if <Bool expression>` | 开始条件分支 | 否,映射已有 `Branch` |
| `else if` | `else if <Bool expression>` | 添加同一分支组的条件臂 | 否,复用 `Branch` |
| `else` | `else` | 切换至当前 if 的否则分支 | 否 | | `else` | `else` | 切换至当前 if 的否则分支 | 否 |
| `while` | `while <Bool expression>` | 开始循环 | 否,映射已有 `Loop` | | `while` | `while <Bool expression>` | 开始循环 | 否,映射已有 `Loop` |
| `break` | `break` | 退出最近一层循环 | 否,结构化控制转移 |
| `continue` | `continue` | 重新检查最近一层循环的条件 | 否,结构化控制转移 |
| `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 | | `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 |
| `return` | `return <expression>` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` | | `return` | `return <expression>` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` |
| `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 | | `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 |
@@ -604,7 +607,7 @@ import:
`return x` `return x`
```` ````
规范语义:条件计算一次,必须是 Bool;为真执行 `if` 和 `else` 之间的载荷,否则执行 `else` 和 `end` 之间的载荷。**不能两个分支都执行。** `else` 可以省略;但 `end` 不能省略。 各条件必须返回 Bool,每个条件在轮到该臂时求值一次。执行第一个为真的臂,或在所有条件为假时执行末尾的 `else`。没有匹配臂也没有 `else` 时直接继续。每组需要一个 `end`。
**将它排成有序列表也完全合法**: **将它排成有序列表也完全合法**:
@@ -675,7 +678,9 @@ import:
匹配规则:每个 `else` 只作用于**栈顶尚未结束的 `if`**;每个 `end` 关闭最近的 `if` 或 `while`。这是一套确定的编译期配对规则,不靠缩进/列表种类/解释器猜测。 匹配规则:每个 `else` 只作用于**栈顶尚未结束的 `if`**;每个 `end` 关闭最近的 `if` 或 `while`。这是一套确定的编译期配对规则,不靠缩进/列表种类/解释器猜测。
**不支持 `else if` 专用写法(本期)**:若需要多路判断,可在 `else` 内另写一个嵌套 `if ... end`,按上述栈规则执行。若未来证明有显著可读性需求,再独立讨论 `elif`,不能开发者自行在 Parser 中宽容接受。 多臂条件采用同一载荷内的 `else if <expr>`,允许零至多个条件臂和一个末尾
`else`。整组由一个 `end` 闭合,各条件从左到右按需求值。两个独立载荷
`else` 与 `if` 仍表示嵌套分支。详见 [RFC-CTRL-0005 的采纳记录](../adr/0067-structured-control-flow.md)。
## 4.5 `while` / `end`:不依赖 bullet List 的循环 ## 4.5 `while` / `end`:不依赖 bullet List 的循环
@@ -720,9 +725,10 @@ import:
严格规则: 严格规则:
- 每一个 `if` 恰有一个匹配的 `end`;`else` 可选且最多一个。 - 每一个 `if` 恰有一个匹配的 `end`。可有多个 `else if` 和一个末尾 `else`。
- 每一个 `while` 恰有一个匹配的 `end`。 - 每一个 `while` 恰有一个匹配的 `end`。
- `else` 不能独立出现;不能对应 `while`;一个 `if` 不能有两个 `else`。 - `else if` 和 `else` 只能配对栈顶的 `if`。
- 独占载荷的 `break` 结束同一标题执行段中的最近循环,`continue` 跳至该循环的下一次条件检查。
- `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。 - `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。
- 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。 - 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。
- `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。 - `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。
@@ -755,7 +761,7 @@ V2 推荐显式声明:
| `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) | | `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) |
| `end if` | 语法错误 | `end` | | `end if` | 语法错误 | `end` |
| `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` | | `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` |
| `break`、`continue`、`try` | 未纳入首版语法 | 首版不承诺 | | `try` | 不属于当前语法 | — |
| `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API | | `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API |
| `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 | | `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 |
| 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` | | 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` |
@@ -784,7 +790,10 @@ V2 推荐显式声明:
```ebnf ```ebnf
(* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *) (* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *)
carrier_statement = "if", required_space, expr, EOF carrier_statement = "if", required_space, expr, EOF
| "else", whitespace, "if", whitespace, Expr, EOF
| "else", EOF | "else", EOF
| "break", EOF
| "continue", EOF
| "while", required_space, expr, EOF | "while", required_space, expr, EOF
| "end", EOF | "end", EOF
| "return", required_space, expr, EOF | "return", required_space, expr, EOF
@@ -799,7 +808,7 @@ carrier_statement = "if", required_space, expr, EOF
**词法必须考虑完整单词边界**:`ifdef()`、`returning()` 不是 `if`、`return` 控制语句;反之,单独的 `if`、`else` 等当作标识符使用应明确报保留字错误。为了避免自相矛盾,Tokeniser 和 Parser 均应对关键字使用同一套保留字定义。 **词法必须考虑完整单词边界**:`ifdef()`、`returning()` 不是 `if`、`return` 控制语句;反之,单独的 `if`、`else` 等当作标识符使用应明确报保留字错误。为了避免自相矛盾,Tokeniser 和 Parser 均应对关键字使用同一套保留字定义。
- `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。 - `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。
- `else`、`end` 后不允许额外词元,`end if`、`else x` 均硬错误。 - `else if` 后必须有条件;独立的 `else` 和 `end` 后无额外词元。
- `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。 - `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。
- `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。 - `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。
- 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。 - 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。
@@ -817,14 +826,23 @@ TokenStream = [StatementToken(payload, span, carrier_kind, owner_unit), ...]
```text ```text
open_if(condition): open_if(condition):
push IfFrame(cond, then=[], else=None) push IfFrame(arms=[(condition, [])], has_else=false)
on_statement(stmt): on_statement(stmt):
append stmt to the current innermost active body append stmt to the current innermost active body
on_else_if(condition):
require stack.top == IfFrame and not frame.has_else
append and activate a new conditional arm
on_else: on_else:
require stack.top == IfFrame and frame.else is None require stack.top == IfFrame and not frame.has_else
switch frame active branch from then to else append and activate the final arm
set frame.has_else
on_break_or_continue:
require an open WhileFrame in the current segment
append the transfer to the current innermost active body
open_while(condition): open_while(condition):
push WhileFrame(cond, body=[]) push WhileFrame(cond, body=[])
@@ -842,10 +860,10 @@ at_segment_end:
该算法可以保证: 该算法可以保证:
- `else` 配对最近尚未结束、且位于栈顶的 `if`;不得跳过未关闭的 `while` 寻找更外层 `if`。 - `else if` 和 `else` 配对栈顶的 `if`,且只能出现在末尾 `else` 之前;不得跳过未关闭的 `while` 寻找更外层 `if`。
- `end` 只关闭栈顶最近的一层 if/while,没有匹配结构时报错。 - `end` 只关闭栈顶最近的一层 if/while,没有匹配结构时报错。
- `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。 - `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。
- `else` 不会成为单独一条 Runtime 指令;它只是 IR `Branch` 的分支边界。 - `else if` 和 `else` 是 `Branch` 的臂边界。解释器将 `break` 和 `continue` 传递到最近的循环。
- 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。 - 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。
**一个实现注意点**:现有 `Branch` IR 的每个 arm 带 `condition`,没有专用可选 else;首版可以将兜底 else 降为最后一个 `true` arm,并明确保持既有“从左到右找第一匹配”的短路求值。如果未来 IR 引入更明确的 `else_body`,必须同步更改 IR schema、Trace 规范和**全部下游消费者及测试**;不能在本轮暗改行为。 **一个实现注意点**:现有 `Branch` IR 的每个 arm 带 `condition`,没有专用可选 else;首版可以将兜底 else 降为最后一个 `true` arm,并明确保持既有“从左到右找第一匹配”的短路求值。如果未来 IR 引入更明确的 `else_body`,必须同步更改 IR schema、Trace 规范和**全部下游消费者及测试**;不能在本轮暗改行为。
@@ -969,6 +987,10 @@ R(IR, imports) = ExecutableProgram or Diagnostics
| `## @exec` | 缺少标题名称 | `sem.empty_unit_name` | | `## @exec` | 缺少标题名称 | `sem.empty_unit_name` |
| `**if x >**` | 语法错误,不降级文档 | `sem.syntax` | | `**if x >**` | 语法错误,不降级文档 | `sem.syntax` |
| `**else**`(无 if) | 无匹配分支 | `sem.unmatched_else` | | `**else**`(无 if) | 无匹配分支 | `sem.unmatched_else` |
| `**else if true**`(无 if) | 无匹配分支 | `sem.unmatched_else_if` |
| `**else if true**`(位于末尾 else 后) | 条件臂位置非法 | `sem.else_if_after_else` |
| `**break**`(循环外) | 无匹配循环 | `sem.break_outside_loop` |
| `**continue**`(循环外) | 无匹配循环 | `sem.continue_outside_loop` |
| `**else**`(重复 else) | 重复,否则分支只允许一个 | `sem.duplicate_else` | | `**else**`(重复 else) | 重复,否则分支只允许一个 | `sem.duplicate_else` |
| `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` | | `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` |
| `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` | | `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` |
@@ -1,9 +1,9 @@
# RFC-OBS-0001: Runtime observability and real-time execution events # RFC-OBS-0001: Runtime observability and real-time execution events
> **Status:** Accepted and implemented at the level recorded in > **Status:** Historical design input. [ADR-0068](../adr/0068-single-current-public-contracts.md)
> [`docs/STATUS.md`](../STATUS.md); this file is the frozen design input. > replaced Execution Events v1 and Trace v2 with the single current
> The normative protocol contract is > [Observation contract](../../spec/observation.md); the retired spec named
> [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md). > below exists only in Git history and in tagged archives.
> >
> **Source:** issue `#1` of `cflmy/marqdo-cli`, filed 2026-11-22 against > **Source:** issue `#1` of `cflmy/marqdo-cli`, filed 2026-11-22 against
> `master@eeea01d672c07b6be7d6444031d1619309dc88ab`. It is reproduced here so > `master@eeea01d672c07b6be7d6444031d1619309dc88ab`. It is reproduced here so
+36 -17
View File
@@ -11,43 +11,62 @@
[development-credentials.md](development-credentials.md). Do not put tokens in [development-credentials.md](development-credentials.md). Do not put tokens in
pipeline files or commit messages. pipeline files or commit messages.
The default Docker pipeline runs on push and pull request: The default Docker pipeline runs on push and pull request. A fast `contract`
lane exercises the public Analysis/Observation contracts through the real CLI
and the independent Python consumers; the full `test` lane runs the Rust gates
and the Windows cross-target compile check; `build` packages the archive, runs
the from-archive smoke and the frozen external conformance suite.
```text ```text
test: contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
rustup component add clippy rustfmt cargo build --locked -p marqdo-cli -p marqdo-provider-worker
apt install curl/ca-certificates/python3/python3-jsonschema + Node.js 22 real CLI check/run over the Observation fixtures
analysis_consumer / observation_consumer / validate_protocols
stream==snapshot assertion (tools/ci/verify_observation_stream.py)
stale-Analysis rejection
test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries):
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
cargo run --locked -p marqdo-cli -- run \ docs_consistency / architecture_boundaries / stdlib_product
tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl \
> /tmp/execution-events.jsonl
python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
cargo test -p marqdo-cli --test docs_consistency
cargo test -p marqdo-cli --test architecture_boundaries
cargo test -p marqdo-cli --test stdlib_product
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
build (depends on test): minimum-rust (rust:1.89-bookworm):
cargo check --locked --workspace --all-targets
build (depends on test, minimum-rust, contract):
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
package + cold-install smoke (which now validates live Execution Events v1) package the deterministic archive for $CI_COMMIT_SHA
from-archive smoke (tools/release/smoke.py)
frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7)
``` ```
A separate manual workflow, [`.woodpecker/performance.yml`](../.woodpecker/performance.yml),
builds the beta baseline and the candidate archive on the shared Woodpecker
agent and records the nine G4 comparisons. Its reports stay `SMOKE`; only the
maintainer-approved RC `WARN` exception can use them (see
[`releasing.md`](releasing.md) and [`performance.md`](performance.md)).
The pipeline is a protocol consumer itself: it must exercise only the current
Analysis and Observation contracts. `docs_consistency::ci_configuration_uses_only_current_protocols`
fails if a retired option or consumer name returns, and
`current_contract_documents_do_not_reference_retired_interfaces` extends the
same rule to `spec/` and the current developer guides.
Node.js 22 is required because the optional foreign-kernel tests use ES-module Node.js 22 is required because the optional foreign-kernel tests use ES-module
syntax; Debian bookworm's Node 18 fails those tests. syntax; Debian bookworm's Node 18 fails those tests.
> **Language contract note.** `cargo test --workspace` includes conformance > **Language contract note.** `cargo test --workspace` includes conformance
> fixtures that execute `.mq.md` source under > fixtures that execute `.mq.md` source under
> [RFC-LANG-0002](architecture/RFC-LANG-0002-unified-semantics.md). The > [RFC-LANG-0002](architecture/RFC-LANG-0002-unified-semantics.md). A red
> implementation, stdlib digest and corpus are green at `ffd1cc9`; a red
> executable-source suite is a real regression, not an expected migration > executable-source suite is a real regression, not an expected migration
> state. Do not "fix" it by restoring the old mapper or regenerating goldens; > state. Do not "fix" it by restoring the old mapper or regenerating goldens;
> see [`STATUS.md`](STATUS.md). The pipeline definition itself > see [`STATUS.md`](STATUS.md). The lanes above are the current definition; it
> (fmt/clippy/test/build, security lane, platform gaps) is unchanged. > changes only with this document.
## What this pipeline does not cover ## What this pipeline does not cover
+10 -9
View File
@@ -18,12 +18,13 @@ their date.
```text ```text
marqdo-cli/ marqdo-cli/
├── Cargo.toml workspace (15 crates, resolver 2) ├── Cargo.toml workspace (16 crates, resolver 2)
├── AGENTS.md operator rules for contributors/agents ├── AGENTS.md operator rules for contributors/agents
├── README.md user-facing quickstart and limits ├── README.md user-facing quickstart and limits
├── docs/ ├── docs/
│ ├── DEVELOPMENT_BLUEPRINT.md architecture baseline (language-mapping sections historical) │ ├── DEVELOPMENT_BLUEPRINT.md architecture baseline (language-mapping sections historical)
│ ├── architecture/RFC-LANG-0002-unified-semantics.md current language authority │ ├── architecture/RFC-LANG-0002-unified-semantics.md current language authority
│ ├── architecture/PROTOCOL_CONVERGENCE_POLICY.md one-current-contract rules + review checklist
│ ├── STABLE_RELEASE_IMPLEMENTATION.md authoritative next-phase/release plan │ ├── STABLE_RELEASE_IMPLEMENTATION.md authoritative next-phase/release plan
│ ├── STATUS.md current evidence, work packages, blockers │ ├── STATUS.md current evidence, work packages, blockers
│ ├── migration/ syntax-migration rules + file inventory │ ├── migration/ syntax-migration rules + file inventory
@@ -45,12 +46,13 @@ marqdo-cli/
│ ├── security.md modes, capabilities, budgets, trust │ ├── security.md modes, capabilities, budgets, trust
│ ├── package-format.md marqdo.yaml / marqdo.lock / init │ ├── package-format.md marqdo.yaml / marqdo.lock / init
│ ├── plugin-abi.md C ABI v1, SDK, host lifecycle │ ├── plugin-abi.md C ABI v1, SDK, host lifecycle
│ ├── worker-ipc.md shared persistent-worker framing/transport
│ ├── math.md removed core math outlook + migration (ADR-0061) │ ├── math.md removed core math outlook + migration (ADR-0061)
│ ├── foreign.md Python/Node kernel protocol │ ├── foreign.md Python/Node kernel protocol
│ ├── tool-v1.md generic external Tool Protocol v1 │ ├── cli-tool.md external command registration and dispatch
│ ├── analysis-v2.md public Analysis v2 projection (v1 historical) │ ├── analysis.md current static projection
│ ├── trace-v2.md public Trace v2 projection (v1 historical) │ ├── observation.md live events and snapshots
│ └── trace-v1.md public Trace v1 event stream │ └── cli-tool.md external command registration and dispatch
├── crates/ ├── crates/
│ ├── marqdo-span/ Span, LineCol, LineIndex (leaf) │ ├── marqdo-span/ Span, LineCol, LineIndex (leaf)
│ ├── marqdo-value/ Value, diagnostics, errors, wire encoding │ ├── marqdo-value/ Value, diagnostics, errors, wire encoding
@@ -207,7 +209,7 @@ counts, harness responsibilities and known observations.
## 5. Coding conventions ## 5. Coding conventions
* Rust edition 2021, `rust-version = 1.82`, workspace version `3.0.0-beta.1`. * Rust edition 2021, `rust-version = 1.89`, workspace version `3.0.0-rc.3`.
* `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses * `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses
`#![forbid(unsafe_code)]`); the ABI/loader crates contain the only `#![forbid(unsafe_code)]`); the ABI/loader crates contain the only
`unsafe` code and every block has a SAFETY comment explaining the contract. `unsafe` code and every block has a SAFETY comment explaining the contract.
@@ -309,9 +311,8 @@ capability flags shown above). See [`STATUS.md`](STATUS.md).
`docs/NEXT_RELEASE_CI_CONVERGENCE.md` are **Historical/Superseded** planning `docs/NEXT_RELEASE_CI_CONVERGENCE.md` are **Historical/Superseded** planning
input (their banners link the RFC); `docs/STABLE_RELEASE_IMPLEMENTATION.md` is input (their banners link the RFC); `docs/STABLE_RELEASE_IMPLEMENTATION.md` is
the authoritative next-phase/release plan. None describes implemented the authoritative next-phase/release plan. None describes implemented
behavior. `spec/tool-v1.md` is a candidate protocol until an ADR and behavior. Use the current contracts and [ADR-0068](adr/0068-single-current-public-contracts.md)
implementation tests land. Never cite a proposed or historical document as when replacing a public interface.
evidence that a feature exists.
* Changes to language semantics, AST mapping, wire format, plugin ABI, * Changes to language semantics, AST mapping, wire format, plugin ABI,
package/lock format, authorization defaults or public CLI behavior require an package/lock format, authorization defaults or public CLI behavior require an
**Accepted ADR** (or superseding one) plus spec updates and tests. Use the **Accepted ADR** (or superseding one) plus spec updates and tests. Use the
+13 -10
View File
@@ -6,17 +6,18 @@ Rust structures, `marqdo-ir` internals, `inspect --ir`, relative paths into the
core checkout, or host memory layout. Adding a new domain function must not core checkout, or host memory layout. Adding a new domain function must not
require a core commit. require a core commit.
Product version for these docs: **`3.0.0-rc.1`** (Linux x86_64 candidate). Product version for these docs: **`3.0.0-rc.3`** (Linux x86_64 candidate).
Protocol versions are independent: Analysis v2, Trace v2, Execution Events v1, Current protocol contracts: Analysis, Observation, CLI Tool, Plugin ABI v1,
Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4, Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
markdown profile `marqdo.md.v1`. `marqdo.md.v1`. Product, protocol and package versions are independent; see
[compatibility.md](compatibility.md).
## Pick your entry point ## Pick your entry point
| Goal | Use | Deliverable | | Goal | Use | Deliverable |
|---|---|---| |---|---|---|
| AI/math/data/quantum/SKILL libraries, pure algorithms | `.mq.md` package | `index.mq.md`, `marqdo.yaml`, README, tests | | AI/math/data/quantum/SKILL libraries, pure algorithms | `.mq.md` package | `index.mq.md`, `marqdo.yaml`, README, tests |
| Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool Protocol v1 | standalone executable + `tool.json` + Analysis/Trace consumer | | Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool protocol | standalone executable + `tool.json` + Analysis/Observation consumer |
| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, SDK/header | | High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, SDK/header |
| New foreign language backend (R/Python/Julia/…) | Foreign Kernel | `kernel.json`, executable provider, pinned environment | | New foreign language backend (R/Python/Julia/…) | Foreign Kernel | `kernel.json`, executable provider, pinned environment |
| Hardware/device/external-stream resources | Resource Provider v2 | `provider.json`, C ABI library, worker helper | | Hardware/device/external-stream resources | Resource Provider v2 | `provider.json`, C ABI library, worker helper |
@@ -28,19 +29,21 @@ markdown profile `marqdo.md.v1`.
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
it through a pinned Git dependency. it through a pinned Git dependency.
3. [tools.md](tools.md) — build an external Tool that consumes Analysis v2 and 3. [tools.md](tools.md) — build an external Tool that consumes the current
Trace v2. Analysis and Observation contracts.
4. [extensions.md](extensions.md) — plugins, foreign kernels, resource 4. [extensions.md](extensions.md) — plugins, foreign kernels, resource
providers, extension selection and lock v4. providers, extension selection and lock v4.
5. [analysis-trace.md](analysis-trace.md) — the public static/dynamic data 5. [analysis-observation.md](analysis-observation.md) — the public static/dynamic data
contracts, Execution Events v1 and digest binding. contracts and digest binding.
6. [compatibility.md](compatibility.md) — version axes, platform matrix and the 6. [compatibility.md](compatibility.md) — version axes, platform matrix and the
prerelease policy. prerelease policy.
7. [release-limits.md](release-limits.md) — the honest beta limitations (this 7. [release-limits.md](release-limits.md) — the honest beta limitations (this
file ships in the archive as `KNOWN_LIMITATIONS.md`). file ships in the archive as `KNOWN_LIMITATIONS.md`).
The full worked handbook is The full worked handbook is
[`../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md). [`../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md)
(beta-era integration handbook, kept as a historical record; the current
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.
+44
View File
@@ -0,0 +1,44 @@
# Analysis and Observation
Run the same public CLI that users install.
```sh
marqdo check index.mq.md --emit ./analysis.json
marqdo call index.mq.md main --output jsonl --observation-file ./run.json
```
A tool can use [Analysis](../../spec/analysis.md) to locate functions, imports,
references, resources and calls. Validate its identifier before walking the
module and statement arrays. Use the original UTF-8 bytes for offsets and
digest checks. The format is the same for a simple document and one using
structured loop transfers.
[Observation](../../spec/observation.md) carries frames, control flow, committed
output and the final result. Consume JSONL for live updates, or use
`--output json` for one JSON snapshot on stdout. The snapshot's `events`
array has the same objects as the live stream. The first event opens the run
and the terminal event gives its outcome. Treat a stream that ends before a
terminal as incomplete. Base64 decode each stdout and stderr chunk and verify
its byte count. Read the typed return from `run.completed.payload.value`.
Before highlighting source locations, compare the `run.started` root and
SHA-256 of the exact Analysis artifact, then check the source file digest.
A different report or edited source requires a fresh check and run.
The repository's independent consumer implements both delivery modes.
```sh
python3 tests/consumers/observation_consumer.py ./run.json --snapshot \
--analysis ./analysis.json --source-root .
```
Value capture uses exact names and explicit Text consent. Use
`--observe-variable NAME` and `--observe-parameter NAME` only for the
values the feature needs. Request `--observe-text-values` when the caller
has opted into this disclosure. Program output and explicit returned values
can themselves contain sensitive data.
Update integrations that previously used the retired run/call JSON,
Trace, Execution Events or retired run/call options. Use the commands above,
remove the old
reader, and rebuild and reinstall the Tool with the
[current manifest](../../spec/cli-tool.md).
-115
View File
@@ -1,115 +0,0 @@
# Analysis v2 and Trace v2 consumers
Both are public, versioned JSON artifacts. A consumer must read them as files,
never link Marqdo's Rust internals or depend on `inspect --ir`.
## Analysis v2 (static)
```bash
marqdo check index.mq.md --emit ./analysis.json
```
- Write atomically; only publish after `check` exits 0. `--refs` is an
independent Markdown-link check and can make `check` fail; on failure the emit
target is removed. Do not generate a consumer artifact with
`check --refs --emit` without checking the exit code.
- `schema: "marqdo.analysis"`, `schema_version: 2`.
- Top level: `producer` (`name`, `version` = product version,
`markdown_profile`), `project`, `modules`, `diagnostics`.
- `project`: `root_id` (`root:<name>@<version>` for manifest projects),
`identity_kind`, `lock_digest` (`""` without a lock), `stdlib`
(`version`, `digest`, `instance_id`; may be null).
- `modules[]`: `id`, `package_instance_id`, `relative_path`, `source_digest`,
`units`, `functions`, `imports`, `references`, `calls`, `resources`.
Diagnostics are top-level, not per-module.
- Byte offsets are UTF-8 source offsets. Stable index keys are logical package
instance ids, never absolute paths.
- `check` does not load plugin libraries, start kernels/providers or execute the
program.
- Schemas: `spec/schemas/analysis-v2.schema.json`; contract:
`spec/analysis-v2.md`; consumers: `tests/consumers/analysis_consumer.py`,
`tests/consumers/validate_protocols.py`.
View must render the **original Markdown** and use Analysis only to correlate
source offsets/heading units/callable mapping. Knowledge must use heading
anchors, links, resources, package identity and source digests; it must not
assume a `@knowledge` unit has runtime effects. Prove must map only the public
proveable subset and distinguish `proved / disproved / unknown / unsupported`;
a proof certificate needs matching source digest, semantics and contract
identity.
## Trace v2 (dynamic)
```bash
marqdo run index.mq.md --trace-file ./trace.json
```
- `schema: "marqdo.trace"`, `schema_version: 2`.
- `source.analysis_digest` must equal SHA-256 of the **Analysis JSON bytes** for
the same project/projection configuration. A mismatch means the trace is
stale; do not bind it to the new source. `run --trace-file` does not emit
Analysis itself.
- Event kinds: `call.enter`, `call.exit`, `branch.eval`, `loop.iteration`,
`return`, `effect`, and possibly `trace.truncated`. Sourced events carry a
module id and a UTF-8 span.
- Defaults are 100,000 events / 32 MiB; `--trace-max-events` and
`--trace-max-bytes` adjust them (`0` = unlimited). A consumer must tolerate
truncation and must not assume the trace is complete.
- Trace records no argument values, secrets or file contents.
- Contract: `spec/trace-v2.md`; schema:
`spec/schemas/trace-v2.schema.json`; consumer:
`tests/consumers/trace_consumer.py`.
## Execution Events v1 (live)
```bash
marqdo run index.mq.md --event-stream jsonl
marqdo call index.mq.md main --arg n=5 --event-stream jsonl
marqdo run index.mq.md --event-stream jsonl --trace-file ./trace.json
```
- `schema: "marqdo.execution-events"`, `schema_version: 1`. This is a separate
protocol from Analysis/Trace and has its own version axis.
- While active, the CLI stdout is a **pure NDJSON channel**: one JSON object per
line, `seq` starts at 0 and is strictly increasing. Program stdout/stderr are
only `stdout.chunk`/`stderr.chunk` events with `encoding: "base64"`,
`data_base64` and a matching `byte_count`. Concatenated decoded bytes equal a
normal run's output; invalid UTF-8/NUL/binary bytes are preserved.
- `stream.opened` is always seq 0. A run then has at most one `run.started` and
exactly one terminal event (`run.completed`, `run.failed`, `run.rejected`) on
a complete stream. An EOF without a terminal event is `incomplete`
(SIGKILL/crash/broken pipe); never synthesize success.
- `run.started.source` contains `root_id` and the `sha256:` digest of the exact
Analysis v2 bytes. `--trace-file` may be combined; both writers share one
opaque run id, and Trace v2 remains atomic and value-free.
- Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`),
`return`, `branch.eval`, `loop.iteration`, `effect`. Frames identify call
instances, not functions; a failed argument binding creates no frame.
- Values are off by default (`value_state: not_requested`).
`--observe-variable NAME` and `--observe-parameter NAME` are exact-name
selections. `Int`/`Float`/`Bool` are bounded by
`--observe-max-value-bytes` (default 256); selected `Text` is `redacted` until
`--observe-text-values` is also passed. Containers, `Memory`, resources and
plugin handles are `unsupported`; handles are never serialized.
- Structural/value events have a separate budget
(`--observe-max-events`, `--observe-max-bytes`; defaults 100 000 / 16 MiB).
Exhaustion emits one `observation.truncated` and still delivers stdout/stderr
and the terminal event. A broken output pipe fails the run with
`observe.transport_failed`; it never keeps executing side effects silently.
- `--event-stream` is mutually exclusive with `--json`, rejected by
`check`/`inspect`/`fmt`/`tool`, and currently rejected by `--mode strict`
(fail-closed, no downgrade). It is not a capability grant.
- Contract: [`../../spec/execution-events-v1.md`](../../spec/execution-events-v1.md);
schema: `spec/schemas/execution-events-v1.schema.json`; consumer:
`tests/consumers/execution_events_consumer.py`; fixtures and Rust gate:
`tests/consumers/fixtures/execution-events/` and
`crates/cli/tests/execution_events.rs`.
## Consumer rules
1. Reject unknown schema majors; there is no silent "use latest" fallback.
2. Verify `source.analysis_digest` against the actual Analysis file bytes.
3. Verify `source.root_id`/package identity; do not key on absolute paths.
4. Be deterministic and offline; never execute `.mq.md` yourself, never invent
host effects, and never inherit Marqdo grants.
5. Report an unsupported/stale artifact explicitly; do not silently downgrade.
+11 -12
View File
@@ -6,13 +6,12 @@ This page summarizes the public support policy. The authoritative matrix is
## Version axes (do not conflate) ## Version axes (do not conflate)
| Axis | `3.0.0-rc.1` value | Change rule | | Axis | `3.0.0-rc.3` value | Change rule |
|---|---|---| |---|---|---|
| Product / CLI | `3.0.0-rc.1` | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. | | Product / CLI | `3.0.0-rc.3` (candidate) | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. |
| Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. | | Analysis | v3 | One writer and one current major for every project. New major for incompatible changes; consumers reject unknown majors. |
| Trace | v2 | New major for incompatible changes; binds to exact Analysis bytes. | | Observation | v1 | One `run_id`/`seq` event sequence per execution; JSONL, JSON snapshot and file snapshot come from the same run. New major for incompatible required-field/ordering/redaction changes. |
| Execution Events | v1 | One-line NDJSON stream; new major for incompatible required-field/ordering/redaction changes. Consumers reject unknown majors. | | CLI Tool | revision 1 | Exact `requires.api_revision` plus optional exact `analysis`/`observation` integers; no version arrays or negotiation. |
| CLI Tool | v1 | Frozen manifest/negotiation/bundle contract for v1. |
| Plugin ABI | v1 (`1.0`) | Frozen C layout and version negotiation. | | Plugin ABI | v1 (`1.0`) | Frozen C layout and version negotiation. |
| Foreign wire | v1 | One-shot request envelope. | | Foreign wire | v1 | One-shot request envelope. |
| Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`. | | Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`. |
@@ -21,8 +20,8 @@ This page summarizes the public support policy. The authoritative matrix is
| Bundled stdlib | `0.1.0` | Independent package version; not the product version. | | Bundled stdlib | `0.1.0` | Independent package version; not the product version. |
| Plugin/tool/example packages | their own | Independent SemVer. | | Plugin/tool/example packages | their own | Independent SemVer. |
`project.marqdo` and a tool's `compatibility.marqdo` are **enforced product `project.marqdo` is an **enforced product range**; a tool declares its exact
ranges**. Prerelease cores require a prerelease range such as current protocol requirements in `requires`. Prerelease cores require a prerelease range such as
`>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match the RC. `>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match the RC.
## Candidate platform scope ## Candidate platform scope
@@ -36,13 +35,13 @@ ranges**. Prerelease cores require a prerelease range such as
Strict is Linux-only and probe-gated. Plugin/provider worker transports are not Strict is Linux-only and probe-gated. Plugin/provider worker transports are not
OS sandboxes. `pure`/`project` are execution modes, not security boundaries. OS sandboxes. `pure`/`project` are execution modes, not security boundaries.
Execution Events v1 is a live observation protocol: it is not a capability Observation v1 is a live observation protocol: it is not a capability grant,
grant, values are off by default, and `--mode strict` currently refuses values are off by default, and `--mode strict` refuses `--output jsonl` and
`--event-stream` explicitly (no downgrade). `--observation-file` explicitly (no downgrade).
## Language compatibility ## Language compatibility
`3.0.0-rc.1` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source `3.0.0-rc.3` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source
(Strong-execute / Emph-return / ordered-list branch / bullet-list loop / (Strong-execute / Emph-return / ordered-list branch / bullet-list loop /
block-quote call / first code-span signature) is **not executable**; there is no block-quote call / first code-span signature) is **not executable**; there is no
`--legacy`, syntax switch or downgrade path. Migration is a rewrite task `--legacy`, syntax switch or downgrade path. Migration is a rewrite task
+18 -12
View File
@@ -1,15 +1,15 @@
# Quickstart: install and run # Quickstart: install and run
Product: `3.0.0-rc.1` (Linux x86_64 candidate). Install a **release archive**, not Product: `3.0.0-rc.3` (Linux x86_64 candidate). Install a **release archive**, not
a source checkout, when you only consume Marqdo. a source checkout, when you only consume Marqdo.
## 1. Install the archive ## 1. Install the archive
```bash ```bash
sha256sum -c marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu.tar.gz.sha256 sha256sum -c marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz.sha256
tar -xzf marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu.tar.gz tar -xzf marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz
cd marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu cd marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu
./marqdo --version # marqdo 3.0.0-rc.1 ./marqdo --version # marqdo 3.0.0-rc.3
./marqdo --help ./marqdo --help
``` ```
@@ -48,7 +48,7 @@ marqdo call index.mq.md main
``` ```
`run` executes the entry function (`main` by default) and prints program output; `run` executes the entry function (`main` by default) and prints program output;
`call` prints the returned value. Use `--json` for machine-readable `call` prints the returned value. Use `--output json` for machine-readable
results (`{"command":"run","success":true,...}`), including embedded program results (`{"command":"run","success":true,...}`), including embedded program
stdout and diagnostics. stdout and diagnostics.
@@ -58,9 +58,15 @@ stdout and diagnostics.
documentation. Unmarked headings inherit the nearest ancestor mode. documentation. Unmarked headings inherit the nearest ancestor mode.
- `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of - `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of
one statement each. one statement each.
- Control flow uses keywords: `if`/`else`/`while`/`end`, plus `params(...)` and - A branch has an `if`, any number of `else if` arms and an optional
`return`. final `else`, followed by one `end`. Each condition is evaluated in order.
- Lists, block quotes and paragraphs are presentation only. - A `while` loop ends at `end`. Inside its body, `break` exits the nearest
loop and `continue` skips to its next condition check. `return` exits
the function. See the [runnable example](../../examples/control-flow.mq.md).
- Lists, block quotes and paragraphs organize the source view. For review or
linting, put each branch head at the start of an ordered list item and
place the loop head at the start of a bullet item. Nest the body visually
and close each group with its own `end` carrier.
- The normative contract is - The normative contract is
[`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md), [`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md),
[`../../spec/mapping.md`](../../spec/mapping.md) and [`../../spec/mapping.md`](../../spec/mapping.md) and
@@ -70,8 +76,8 @@ stdout and diagnostics.
```bash ```bash
marqdo check index.mq.md --json marqdo check index.mq.md --json
marqdo run index.mq.md --json marqdo run index.mq.md --output json
marqdo call index.mq.md main --json marqdo call index.mq.md main --output json
``` ```
## 5. Where next ## 5. Where next
@@ -79,6 +85,6 @@ marqdo call index.mq.md main --json
- Publish/consume a pure library: [libraries.md](libraries.md). - Publish/consume a pure library: [libraries.md](libraries.md).
- Build an external tool: [tools.md](tools.md). - Build an external tool: [tools.md](tools.md).
- Plugins, kernels, providers: [extensions.md](extensions.md). - Plugins, kernels, providers: [extensions.md](extensions.md).
- Analysis/Trace consumers: [analysis-trace.md](analysis-trace.md). - Analysis/Trace consumers: [analysis-observation.md](analysis-observation.md).
- Version axes and platform support: [compatibility.md](compatibility.md). - Version axes and platform support: [compatibility.md](compatibility.md).
- Beta limitations: [release-limits.md](release-limits.md). - Beta limitations: [release-limits.md](release-limits.md).
+12 -12
View File
@@ -1,4 +1,4 @@
# Marqdo 3.0.0-rc.1 — known limitations # Marqdo 3.0.0-rc.3 — known limitations
This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of
the release record: it defines the platform and feature scope for the release candidate. the release record: it defines the platform and feature scope for the release candidate.
@@ -49,18 +49,18 @@ Even when available:
wire-incompatible kernels. wire-incompatible kernels.
* **CLI tools**: a tool is an ordinary user-authorized executable and does * **CLI tools**: a tool is an ordinary user-authorized executable and does
**not** inherit `pure`/`project`/`strict` guarantees from the documents it **not** inherit `pure`/`project`/`strict` guarantees from the documents it
reads. `MARQDO_BIN`, `MARQDO_TOOL_PROTOCOL`, `MARQDO_PROTOCOL_ANALYSIS` and reads. `MARQDO_BIN` and `MARQDO_API_REVISION` are the only helpers the CLI
`MARQDO_PROTOCOL_TRACE` are the only helpers the CLI injects. injects; version negotiation was removed.
* **Extension selection** (`marqdo.yaml.extensions`, lock v4) is never * **Extension selection** (`marqdo.yaml.extensions`, lock v4) is never
authorization. `--allow-plugin`, `--allow-provider` and `--allow-foreign` authorization. `--allow-plugin`, `--allow-provider` and `--allow-foreign`
are still required. are still required.
## Compatibility and versioning ## Compatibility and versioning
* `3.0.0-rc.1` is a **prerelease**. The changelog lists changes from the beta. * `3.0.0-rc.3` is a **prerelease**. The changelog lists changes from the beta.
* The product version is independent of protocol versions: Analysis v2, Trace * The product version is independent of protocol versions: Analysis,
v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2
manifest v2 and lock v4 keep their own major numbers. and lock v4 keep their own identifiers.
* The official bundled stdlib keeps its independent package version `0.1.0`. * The official bundled stdlib keeps its independent package version `0.1.0`.
A plugin `.mq.md` package version such as `0.1.0` is also independent. A plugin `.mq.md` package version such as `0.1.0` is also independent.
* `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer * `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer
@@ -77,19 +77,19 @@ Archives are accompanied by SHA256 checksums and `RELEASE_INFO.json`
integrity only; they are **not** a publisher signature. A digest obtained from integrity only; they are **not** a publisher signature. A digest obtained from
an untrusted Git URL does not make the code trustworthy. an untrusted Git URL does not make the code trustworthy.
## Execution Events v1 ## Observation
* Implemented: live stdout/stderr chunks, lifecycle/terminal events, call * Implemented: live stdout/stderr chunks, lifecycle/terminal events, call
instance ids, branch/loop/effect events, explicit bounded value observation. instance ids, branch/loop/effect events, explicit bounded value observation.
* Not implemented: memory region/budget metadata (OBS-06/P2), raw memory * Not implemented: memory region/budget metadata (OBS-06/P2), raw memory
content, breakpoints/stepping/time travel, and a bidirectional debug content, breakpoints/stepping/time travel, and a bidirectional debug
protocol. Do not infer a debugger from this protocol. protocol. Do not infer a debugger from this protocol.
* `--mode strict` currently rejects `--event-stream` explicitly; there is no * `--mode strict` rejects `--output jsonl` and `--observation-file` before
silent fallback to `project`. launch; there is no silent fallback to `project`.
* The live lane is tested on Linux x86_64; macOS/Windows are unverified for * The live lane is tested on Linux x86_64; macOS/Windows are unverified for
this option for this candidate. this option for this candidate.
* In-process native plugins are rejected in event mode * In-process native plugins are rejected with an active machine destination
(`ext.event_stream_unsupported_native_plugin`) because they share the process (`ext.observation_unsupported_native_plugin`) because they share the process
and can write the protocol fd directly; worker plugins remain usable. and can write the protocol fd directly; worker plugins remain usable.
* Observation lowers confidentiality when values are explicitly enabled. Text * Observation lowers confidentiality when values are explicitly enabled. Text
needs a second opt-in; View/agents must not enable these flags by default. needs a second opt-in; View/agents must not enable these flags by default.
+55 -43
View File
@@ -1,12 +1,12 @@
# External tools: CLI Tool Protocol v1 # External tools: current CLI Tool protocol
The core does not contain `view`, `knowledge`, `prove`, `lint` or any other The core does not contain `view`, `knowledge`, `prove`, `lint` or any other
product command. A tool is a **separate executable** registered by the user; the product command. A tool is a **separate executable** registered by the user; the
CLI only dispatches unknown top-level commands to registered tools and never CLI only dispatches unknown top-level commands to registered tools and never
scans `PATH` for a guessed name. scans `PATH` for a guessed name.
Normative contract: [`../../spec/tool-v1.md`](../../spec/tool-v1.md) Normative contract: [`../../spec/cli-tool.md`](../../spec/cli-tool.md) and
(implemented and frozen for protocol v1). [`../../spec/schemas/cli-tool.schema.json`](../../spec/schemas/cli-tool.schema.json).
## 1. Package layout ## 1. Package layout
@@ -20,7 +20,7 @@ marqdo-view/
examples/ examples/
``` ```
`tool.json` for the `3.0.0-rc.1` candidate: `tool.json` for the `3.0.0-rc.3` candidate:
```json ```json
{ {
@@ -30,21 +30,19 @@ marqdo-view/
"version": "0.1.0", "version": "0.1.0",
"command": "view", "command": "view",
"entrypoint": "bin/marqdo-view", "entrypoint": "bin/marqdo-view",
"compatibility": { "requires": {"api_revision": 1, "analysis": 3, "observation": 1}
"marqdo": ">=3.0.0-beta.1,<4.0.0",
"analysis": [2],
"trace": [2]
}
} }
``` ```
- `version` is the **tool's** SemVer. - `version` is the **tool's** SemVer. It identifies the artifact; it does not
- `compatibility.marqdo` is the **core product** range. A stable-only promise compatibility with retired core protocols.
`>=3.0.0,<4.0.0` does not match a beta core; opt in explicitly. The CLI - `requires.api_revision` is required and must equal the current core revision.
rejects a mismatched range at install and dispatch time with a - `requires.analysis` and `requires.observation` are optional. Declare one only
`requires marqdo …` diagnostic. when the tool consumes that contract, and declare it as a **single exact
- `analysis`/`trace` are declared only if the tool consumes them; the current integer**; arrays, ranges and "highest shared version" negotiation do not
core provides Analysis v2 and Trace v2. exist.
- A mismatched requirement fails install and dispatch with
`tool.protocol_incompatible`; there is no negotiation and no fallback.
- `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in - `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in
command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`, command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`,
`remove`, `lock`, `sync`, `tool`, `help`). `remove`, `lock`, `sync`, `tool`, `help`).
@@ -71,11 +69,13 @@ The tool receives:
| Variable | Meaning | | Variable | Meaning |
|---|---| |---|---|
| `MARQDO_BIN` | absolute path of the running `marqdo` executable | | `MARQDO_BIN` | absolute path of the running `marqdo` executable |
| `MARQDO_TOOL_PROTOCOL` | `1` | | `MARQDO_API_REVISION` | the single current tool API revision (`1`) |
| `MARQDO_PROTOCOL_ANALYSIS` | `2` when Analysis v2 was negotiated |
| `MARQDO_PROTOCOL_TRACE` | `2` when Trace v2 was negotiated |
Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`. Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`.
The retired `MARQDO_TOOL_PROTOCOL`, `MARQDO_PROTOCOL_ANALYSIS` and
`MARQDO_PROTOCOL_TRACE` variables are not exported: version selection is not
negotiated. A registration written by a retired manifest/record format is
rejected with a "remove and reinstall" diagnostic and is never rewritten.
## 3. Consume the public protocols ## 3. Consume the public protocols
@@ -85,28 +85,37 @@ Static input (View/Knowledge/Proof):
"$MARQDO_BIN" check index.mq.md --refs --emit ./analysis.json "$MARQDO_BIN" check index.mq.md --refs --emit ./analysis.json
``` ```
Dynamic input: Dynamic input uses the single Observation contract. The same run can deliver
the event stream on stdout and an atomic JSON snapshot in one invocation:
```bash ```bash
"$MARQDO_BIN" run index.mq.md --trace-file ./trace.json # live JSONL events
"$MARQDO_BIN" run index.mq.md --output jsonl
"$MARQDO_BIN" call index.mq.md main --arg n=5 --output jsonl
# one JSON snapshot, from the same execution
"$MARQDO_BIN" run index.mq.md --output json --observation-file ./observation.json
# both destinations, still one execution
"$MARQDO_BIN" call index.mq.md main --arg n=5 --output jsonl \
--observation-file ./observation.json
``` ```
Live dynamic input (Execution Events v1): Consume the stdout line stream as NDJSON; do not pass another `--output` in the
same invocation. Every event carries `schema: "marqdo.observation"` and
`schema_version: 1`; read `stream.opened` for the capture policy and reject any
other format identifier. The JSON snapshot wraps the same events, so a consumer
must not treat it as a second protocol or renumber them. A tool server may
convert the stream to its own SSE/websocket transport; the CLI never implements
HTTP/SSE. Live and file destinations are rejected under `--mode strict` in the
current tree; the tool must surface that refusal instead of pretending
real-time support. The retired `--json`, `--trace-file` and `--event-stream`
options are rejected, not aliased.
```bash See [analysis-observation.md](analysis-observation.md) for fields and digest rules. A
"$MARQDO_BIN" run index.mq.md --event-stream jsonl consumer must verify the exact Analysis bytes (SHA-256) and each module source
"$MARQDO_BIN" call index.mq.md main --arg n=5 --event-stream jsonl digest before attributing a span. Do not depend on `inspect --ir`: that JSON is
``` not a frozen cross-repository protocol.
Consume the stdout line stream as NDJSON; do not pass `--json` in the same
invocation. Negotiate by reading `stream.opened` (`marqdo.execution-events`,
`schema_version: 1`) and reject unknown majors. A tool server may convert the
stream to its own SSE/websocket transport; the CLI never implements HTTP/SSE.
This option is unavailable under `--mode strict` in the current tree and the
tool must surface that refusal instead of pretending real-time support.
See [analysis-trace.md](analysis-trace.md) for fields and digest rules. Do not
depend on `inspect --ir`: that JSON is not a frozen cross-repository protocol.
The `view` tool renders the **original Markdown**, not the Analysis JSON; the The `view` tool renders the **original Markdown**, not the Analysis JSON; the
Analysis is an index, not a replacement for the source text. Analysis is an index, not a replacement for the source text.
@@ -121,13 +130,16 @@ Checksums verify bundle integrity only; they are not publisher authentication.
- Test against a **frozen** `marqdo` binary: hash it before/after the suite and - Test against a **frozen** `marqdo` binary: hash it before/after the suite and
fail if it changes. fail if it changes.
- Cover the negative paths: unknown schema major, incompatible `marqdo` range, - Cover the negative paths: unknown schema/schema_version, incompatible
reserved command, traversal/symlink entrypoint, tampered bundle file, missing `api_revision`/`analysis`/`observation` requirement, array requirements,
entrypoint, tool crash/exit-status propagation. retired record format, reserved command, traversal/symlink entrypoint,
- Match a real Analysis v2/Trace v2 schema (`spec/schemas/`) and check tampered bundle file, missing entrypoint, tool crash/exit-status propagation.
`source.analysis_digest`. - Validate against the current Analysis and Observation schemas
- Include README, minimal example, supported CLI product range, protocol (`spec/schemas/`) and check `source.analysis_digest` plus the module source
versions, platform matrix, reproducible artifact hashes and limitations. digest before using event spans.
- Include README, minimal example, supported CLI product range, the exact
protocol requirements, platform matrix, reproducible artifact hashes and
limitations.
- The archive ships `examples/tool-samples/{sample-view,sample-knowledge,sample-proof}` - The archive ships `examples/tool-samples/{sample-view,sample-knowledge,sample-proof}`
as independent source examples and `examples/tool-unknown-name/` as a as independent source examples and `examples/tool-unknown-name/` as a
runnable dispatch fixture. runnable dispatch fixture.
@@ -6,8 +6,9 @@
- **Source SHA:** `1d3dca7c1832eb9468e96384d9805a3812a303e4` (post-beta tree; - **Source SHA:** `1d3dca7c1832eb9468e96384d9805a3812a303e4` (post-beta tree;
the tagged beta is `2c7c4f31e7a388d3fcfa717a77067e696ed13854` and does **not** the tagged beta is `2c7c4f31e7a388d3fcfa717a77067e696ed13854` and does **not**
contain this feature). contain this feature).
- **Normative contract:** [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md), - **Normative contract at that time:** `spec/execution-events-v1.md` (retired
schema `spec/schemas/execution-events-v1.schema.json`, decision by [ADR-0068](../adr/0068-single-current-public-contracts.md); the current
contract is [`spec/observation.md`](../../spec/observation.md)), decision
[ADR-0059](../adr/0059-runtime-observability-and-execution-events.md). [ADR-0059](../adr/0059-runtime-observability-and-execution-events.md).
This file records commands actually executed on Linux x86_64 with Rust This file records commands actually executed on Linux x86_64 with Rust
@@ -0,0 +1,63 @@
# Linux RC1 assessment for RFC-CTRL-0005
Candidate `af1e07f3d772a7f641c37ef9c2d435783f93141d` was tested on
`release/3.0.0-rc.1-control-flow`. This is a separate verification branch
from the existing `release/3.0.0-rc.1` freeze at `f7a5a7b`.
[Woodpecker #56](https://ci.cflmy.cn/repos/1/pipeline/56) passed all steps,
including format, Clippy, workspace tests, Windows cross-compilation, the
Rust 1.89 locked check, release build, protocol smoke, and independent extension
conformance. Windows and macOS are outside this Linux candidate's scope.
## Archive
The locally rebuilt archive passes its checksum, smoke tests and installed-only
cold check in Ubuntu 24.04 with glibc 2.39. Its seven frozen extension contract
groups and six reference applications passed. Its executable digests match
the two digests stamped by Woodpecker #56.
| File | SHA-256 |
|---|---|
| Linux archive | `7d04070dfea78c71a4223b85156ec18b18476410d3a28db4b4fe24ab2dd7f5cf` |
| `marqdo` | `adaea5d34f914878b3ee67f8ea852741a6021d07e42e4e0d7e10510ee4559c8a` |
| `marqdo-provider-worker` | `71f145e75d0f69b7a292d7a48da0bf1f850d6f57efb417f59877c8acdeb195d3` |
The archive declares Analysis v2 and v3. Its smoke test exercises both majors
against independent readers and checks the Trace v2 digest. The old Lint
consumer limitation is recorded in the
[control-flow development verification](2026-11-23-rfc-ctrl-0005.md).
## Strict L1
The strict security lane passed for this SHA in a disposable Ubuntu 26.04 VM
as uid 1000, with Bubblewrap 0.11.1 and kernel 7.0.0-43-generic. The base image
digest was verified against Canonical's dated release checksum. The same guest
also verified the archive checksum and ran the installed example in strict
mode, returning 5 with the CLI digest shown above.
## Performance
Each paired run compared the beta tag with the extracted candidate archive.
All nine workload results were correctness-verified on Woodpecker agent 1,
pinned to logical CPU 0, kernel 7.0.0-31-generic, on an Intel i7-12700H with the
`powersave` governor. Each run used five warmups and twenty samples per
workload. All three candidate executable digests match the archive above.
The complete beta and candidate reports are retained in the linked logs.
| Paired run | HTTP parser p50 change | HTTP parser beta and candidate p95 |
|---|---:|---:|
| [#57](https://ci.cflmy.cn/repos/1/pipeline/57) | +21.58% | 5.5765 / 5.6545 ms |
| [#58](https://ci.cflmy.cn/repos/1/pipeline/58) | +0.05% | 5.7052 / 5.6888 ms |
| [#59](https://ci.cflmy.cn/repos/1/pipeline/59) | +0.15% | 5.7086 / 5.6371 ms |
The first pair crossed the 15% p50 threshold. Its beta p50 was 4.5126 ms,
compared with 5.5761 and 5.5602 ms in the next two pairs. The candidate p50
stayed within 5.4865–5.5789 ms across the three. The p95 and CPU samples
overlapped. The threshold breach was not reproduced and is recorded with the
shared-node variability. The largest RSS increase was 1.16%. No other
comparison crossed the investigation thresholds.
The three reports are shared-node SMOKE. The aggregate RC gate records
`DO_NOT_RELEASE` until the maintainer explicitly accepts the named shared-node
WARN or the dedicated-node performance gate passes. The candidate SHA remains
frozen while that decision is pending.
+58
View File
@@ -0,0 +1,58 @@
# RFC-CTRL-0005 development verification
The stage A implementation and tests were verified at
`b1314328e6128cf1066cedaee06a8aa84cf1a405` against the
[issue baseline](https://git.cflmy.cn/cflmy/marqdo-cli/issues/7)
`f7a5a7b0163bf5229ed09adfffd892f9899e6667`.
## Linux results
The local run used Rust 1.98.1 on Linux x86_64 and the locked dependency
graph. A clean checkout under a path that Bubblewrap could mount was used
for workspace testing and packaging.
| Check | Result |
|---|---|
| Baseline workspace tests | 587 passed, 2 ignored |
| Workspace format and Clippy with warnings denied | Passed |
| Workspace tests | 595 passed, 2 ignored |
| CLI tests | 220 passed |
| Python CI tooling tests | 32 passed |
| Release archive smoke | Passed, including strict execution |
| Frozen extension lane with fixtures at `cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec` | 7 contract groups and 6 reference applications passed |
| Archive-only control-flow example | Returned 5 in pure, project and strict modes |
| Archive-only independent protocol consumers | Analysis v2/v3, Trace v2 digest verification and Execution Events v1 passed. The legacy Analysis consumer rejected v3. |
The archive was built by `tools/release/package.py` and verified by
`tools/release/smoke.py` and `tools/ci/run_frozen_extensions.sh`.
Archive SHA-256 is
`00c486642c524ea699e3c83f151875b1048e9b4affc89565c79a3d29af4af9b7`.
The Rust commands were `cargo fmt --all -- --check`,
`cargo clippy --workspace --all-targets --locked --offline -- -D warnings`,
`cargo test --workspace --locked --offline --no-fail-fast -- --test-threads=1`
and `cargo test -p marqdo-cli --locked --offline -- --test-threads=1`.
GitHub and Woodpecker both contain independent schema and consumer checks.
## Coverage and consumer compatibility
- Semantic fixtures 80–88 cover ordered arms, short-circuiting, fallthrough,
empty arms, nested loops and branch bodies, contextual identifiers and
inert prose. Fixture 34 still exercises separately carried nested branches.
- The negative corpus covers unmatched and out-of-order arms, malformed
transfers, missing closure, function and heading bounds, and possibly
uninitialized reads on loop exit. Runtime tests cover non-boolean
conditions, fuel, deadlines and transfer containment at function boundaries.
- CLI tests compare Analysis, Trace and Execution Events source spans in UTF-8,
bind Trace to the emitted Analysis digest, verify the call graph and prove
that invalid input stops before execution. A property test compares
span-independent IR across Markdown list, quote and paragraph containers.
- The separately built `marqdo-lint 0.1.0` binary at repository commit
`58cea75` read the existing `hello.mq.md` Analysis v2 output. Its current
alignment logic reports `analysis_incomplete` for native `else if`,
and it rejects Analysis v3 because it supports only v2. Adoption of the
new nodes requires an update in the Lint repository.
These results record local implementation and archive verification.
Release inclusion and platform evidence remain subject to the maintainer's
release process.
@@ -0,0 +1,95 @@
# RC.3 protocol-convergence gate — local Linux evidence
Date: 2026-11-24. Product: `3.0.0-rc.3` (candidate). Source SHA:
`291e521cec2be20ae03832d104cc37284122cdd0` (the release-preparation commit).
Platform: Linux x86_64, glibc 2.39, Rust 1.93.1. Profile: **local gate only**.
This records commands actually executed for
[issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) /
[ADR-0068](../adr/0068-single-current-public-contracts.md). It is **not** a
same-SHA CI or clean-install release claim: [`releasing.md`](../releasing.md)
still requires the remote pipeline and archive/clean-install evidence bound to
the tagged SHA before publication. Do not tag or publish from this file alone.
## Gate results
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS: 601 passed, 0 failed, 2 ignored
cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed
cargo test -p marqdo-cli --test docs_consistency PASS: 5 passed
cargo test -p marqdo-cli --test observation PASS: 15 passed
cargo test -p marqdo-cli --test analysis_observation PASS: 10 passed
cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed
cargo test -p marqdo-cli --test extension_selection PASS: 14 passed
cargo test -p marqdo-worker-ipc PASS: 5 passed
```
Independent consumers against the real debug binary (not fixtures):
```text
validate_protocols.py analysis.json snapshot.json tool.json PASS (7 modules, 333 events)
analysis_consumer.py analysis.json PASS (32 functions)
observation_consumer.py --snapshot ... --analysis ... PASS
control-flow fixture: 66 events, 3 transfers
stream JSONL == snapshot events PASS
source digest mismatch (stale Analysis) rejected
marqdo --version marqdo 3.0.0-rc.3
```
## Release archive
Built with `python3 tools/release/package.py --source-sha
291e521cec2be20ae03832d104cc37284122cdd0 --version 3.0.0-rc.3` after
`cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker`.
```text
archive marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz
archive sha256 8a663dee0006742d6b1364380a62e54915a0ead56fa91a1dd3c1f64a2c16fc8b
archive size 5003180 bytes
source SHA 291e521cec2be20ae03832d104cc37284122cdd0
```
`python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz`
PASSED from the extracted archive only, including stdlib digest verification,
Analysis/Observation consumers, Tool install/dispatch, plugin and provider
worker paths, foreign kernel, strict fail-closed refusal on this host, and the
"bundled stdlib missing -> fail-closed" case.
## What is still required before publishing
1. Push `architecture/issue-8-protocols`, run the same-SHA CI pipeline
(`fmt`/`clippy`/workspace tests plus the schema/consumer and
frozen-extension jobs), and record the evidence aggregate.
2. Run the clean-install container gate against the archive bytes.
3. Tag `v3.0.0-rc.3` at the evidenced SHA and publish the archive, checksum and
release notes. Local evidence cannot be promoted to a remote claim.
## CI addendum — same-SHA Linux pipeline
After this local log, the branch was pushed and ran the same-SHA Woodpecker
pipeline on commit `5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`:
[pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70).
```text
contract lane (real CLI + independent consumers) PASS
test lane (fmt/clippy/tests/docs/arch/stdlib) PASS
Windows cross-target compile gate PASS
minimum-rust (1.89) PASS
build lane PASS
archive sha256 d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37
archive source 5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef
from-archive smoke PASS (stdlib digest, consumers, tools, workers, strict refusal)
frozen extensions 7/7 PASS at fixture SHA 015ff8ac15417b7ebbdb31ce2be2dab5362a1eba
```
The frozen extension fixture repository was updated in the same integration
(commit `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`): its tool manifest uses exact
current requirements, its consumers read the current Analysis/Observation
contracts through `--output json` / `--output jsonl` / `--observation-file`,
and no `--json`/`--trace-file`/`--event-stream` path remains.
This satisfies the Linux CI and cross-repository evidence for the protocol
replacement. It does **not** satisfy the RC strict-VM or G4 performance gates,
so `v3.0.0-rc.3` must not be tagged on this evidence alone.
+7 -4
View File
@@ -57,7 +57,7 @@ requires re-running every gate. On that SHA:
environment and limits; the 9 correctness workloads must still pass. Never environment and limits; the 9 correctness workloads must still pass. Never
report TCG/QEMU or development-container timings as G4. report TCG/QEMU or development-container timings as G4.
8. `README`, `CHANGELOG`, `COMPATIBILITY`, `docs/STATUS`, this file, 8. `README`, `CHANGELOG`, `COMPATIBILITY`, `docs/STATUS`, this file,
`spec/tool-v1.md`, `spec/plugin-abi.md` and the developer docs are on the `spec/cli-tool.md`, `spec/plugin-abi.md` and the developer docs are on the
same fact baseline. No "implemented but says Proposed", no "released but same fact baseline. No "implemented but says Proposed", no "released but
says DO NOT RELEASE", no product/protocol/package version confusion. says DO NOT RELEASE", no product/protocol/package version confusion.
9. Every shipped binary was actually built and smoke-tested on its claimed 9. Every shipped binary was actually built and smoke-tested on its claimed
@@ -120,7 +120,7 @@ python3 tools/release/package.py --version "$version" --source-sha "$sha"
Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory, Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory,
the **complete verified `stdlib/` bundle** (`stdlib.json`, every `.mq.md` module the **complete verified `stdlib/` bundle** (`stdlib.json`, every `.mq.md` module
and self-test), `LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`, and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
`RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`, `RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`,
`docs/developers/`, `examples/` (with host-built plugin/provider/math-backend `docs/developers/`, `examples/` (with host-built plugin/provider/math-backend
artifacts so the examples run without a compiler) and `tests/consumers/`. artifacts so the examples run without a compiler) and `tests/consumers/`.
@@ -128,7 +128,10 @@ 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`. `package.py` recomputes both digests `aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
with the same canonical algorithm as the runtime and refuses to package a mismatch with the same canonical algorithm as the runtime and refuses to package a mismatch
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04). The bundled stdlib is a with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04).
The `protocols.analysis` field identifies the default Analysis major.
`protocols.analysis_versions` lists all majors the archive can emit.
The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a
runtime requirement, not a build-machine side effect: a release binary must never runtime requirement, not a build-machine side effect: a release binary must never
fall back to the compile-time source path. fall back to the compile-time source path.
@@ -147,7 +150,7 @@ python3 tools/release/smoke.py \
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib
digests against `stdlib/stdlib.json` and the staged tree, offline digests against `stdlib/stdlib.json` and the staged tree, offline
`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2 and Trace v2 `--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis and Observation
consumers, Tool install/dispatch, native + worker plugin transports, a foreign consumers, Tool install/dispatch, native + worker plugin transports, a foreign
kernel, Resource Provider v2 through the shipped worker (positive, kernel, Resource Provider v2 through the shipped worker (positive,
unauthorized and missing-helper fail-closed), the pure math package and optional unauthorized and missing-helper fail-closed), the pure math package and optional
+35
View File
@@ -0,0 +1,35 @@
# @knowledge 筛选读数
跳过无效读数,遇到停止标记时结束扫描,返回已接收读数的总和。
## @exec main
`读数 = [2, -1, 3, 0, 9]`
`位置 = 0`
`合计 = 0`
- `while 位置 < 长度(读数)`:逐项读取。
`当前 = 读数[位置]`
`位置 = 位置 + 1`
1. `if 当前 < 0`:跳过无效读数。
`continue`
2. `else if 当前 == 0`:遇到停止标记。
`break`
3. `else`:累计有效读数。
`合计 = 合计 + 当前`
`end`
`end`
`return 合计`
@@ -1,4 +1,4 @@
//! Independent Tool Protocol v1 consumer: reads a small part of Trace v2. //! Independent Tool Protocol v1 consumer: reads a small part of Analysis.
use std::fs; use std::fs;
@@ -27,11 +27,11 @@ fn main() {
let args: Vec<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let path = args let path = args
.iter() .iter()
.position(|arg| arg == "--trace") .position(|arg| arg == "--analysis")
.and_then(|index| args.get(index + 1)) .and_then(|index| args.get(index + 1))
.or_else(|| args.first()) .or_else(|| args.first())
.unwrap_or_else(|| { .unwrap_or_else(|| {
eprintln!("usage: sample-knowledge --trace <trace-v2.json>"); eprintln!("usage: sample-knowledge --analysis <analysis.json>");
std::process::exit(2); std::process::exit(2);
}); });
let json = fs::read_to_string(path).unwrap_or_else(|error| { let json = fs::read_to_string(path).unwrap_or_else(|error| {
@@ -39,16 +39,15 @@ fn main() {
std::process::exit(1); std::process::exit(1);
}); });
let schema = string_field(&json, "schema").unwrap_or_default(); let schema = string_field(&json, "schema").unwrap_or_default();
if schema != "marqdo.trace" { if schema != "marqdo.analysis" {
eprintln!("sample-knowledge: expected marqdo.trace, got {schema:?}"); eprintln!("sample-knowledge: expected marqdo.analysis, got {schema:?}");
std::process::exit(1); std::process::exit(1);
} }
let version = number_field(&json, "schema_version").unwrap_or_default(); let version = number_field(&json, "schema_version").unwrap_or_default();
if version != 2 { if version != 3 {
eprintln!("sample-knowledge: unsupported Trace version {version}"); eprintln!("sample-knowledge: unsupported Analysis version {version}");
std::process::exit(1); std::process::exit(1);
} }
let status = string_field(&json, "status").unwrap_or_default(); let references = json.matches("\"references\"").count();
let events = json.matches("\"seq\"").count(); println!("sample-knowledge schema={schema} version={version} reference_sets={references}");
println!("sample-knowledge schema={schema} version={version} events={events} status={status}");
} }
@@ -5,9 +5,8 @@
"version": "0.1.0", "version": "0.1.0",
"command": "sample-knowledge", "command": "sample-knowledge",
"entrypoint": "bin/sample-knowledge", "entrypoint": "bin/sample-knowledge",
"compatibility": { "requires": {
"marqdo": ">=3.0.0-beta.1,<4.0.0", "api_revision": 1,
"analysis": [2], "analysis": 3
"trace": [2]
} }
} }
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff. Show more