Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ab4aaa861 | ||
|
|
2585915e16 | ||
|
|
e2162add22 | ||
|
|
9b4f0a0822 | ||
|
|
4bbefc9244 | ||
|
|
452e9a32bd | ||
|
|
63f62d5728 | ||
|
|
4a4ca63b45 | ||
|
|
b1fc211916 | ||
|
|
8473ac9827 | ||
|
|
e0645f376b | ||
|
|
7064c5f22c | ||
|
|
31ccfe15f8 | ||
|
|
1543d33c8a | ||
|
|
8737e093d6 | ||
|
|
0b7f238fd8 | ||
|
|
93e125e921 | ||
|
|
6d4209bf32 | ||
|
|
99789616a4 | ||
|
|
1b214d48da | ||
|
|
d8212aaa01 | ||
|
|
629fb9834d | ||
|
|
88d7cd3414 | ||
|
|
e6066e6ba9 | ||
|
|
1e2a045cc7 | ||
|
|
f211568c42 | ||
|
|
765c8350b0 | ||
|
|
847cf9fe33 | ||
|
|
d11b261aca | ||
|
|
682eae82b6 | ||
|
|
44a118003f | ||
|
|
238e4065c1 | ||
|
|
72d49ab2a1 |
No files matched your search
@@ -39,6 +39,10 @@ jobs:
|
|||||||
run: cargo test -p marqdo-cli --test docs_consistency
|
run: cargo test -p marqdo-cli --test docs_consistency
|
||||||
- name: Architecture boundaries
|
- name: Architecture boundaries
|
||||||
run: cargo test -p marqdo-cli --test architecture_boundaries
|
run: cargo test -p marqdo-cli --test architecture_boundaries
|
||||||
|
- name: Dependency-direction gate (Engine / Host Contract / Native Host)
|
||||||
|
run: python3 tools/ci/check_dependency_boundaries.py
|
||||||
|
- name: Engine independence and CLI differential execution
|
||||||
|
run: python3 tools/ci/check_engine_boundary.py
|
||||||
- name: CI evidence tool tests
|
- name: CI evidence tool tests
|
||||||
run: python3 -m unittest discover -s tools/ci -p "test_*.py"
|
run: python3 -m unittest discover -s tools/ci -p "test_*.py"
|
||||||
- name: Whole stdlib product tests
|
- name: Whole stdlib product tests
|
||||||
|
|||||||
@@ -37,3 +37,12 @@ __pycache__/
|
|||||||
*.pyc
|
*.pyc
|
||||||
.perf-out-*
|
.perf-out-*
|
||||||
.perf-err-*
|
.perf-err-*
|
||||||
|
|
||||||
|
# Independent consumer/fixture build outputs and the local scratch dir
|
||||||
|
/tests/embedding/target/
|
||||||
|
/tests/sdk-plugin/target/
|
||||||
|
/.tmp/
|
||||||
|
|
||||||
|
# Accidental curl/test capture files
|
||||||
|
/out
|
||||||
|
/log.txt
|
||||||
+5
-18
@@ -15,6 +15,7 @@ steps:
|
|||||||
- apt-get update
|
- apt-get update
|
||||||
- apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema
|
- apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema
|
||||||
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker
|
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker
|
||||||
|
- python3 tools/ci/check_dependency_boundaries.py
|
||||||
- |
|
- |
|
||||||
set -eux
|
set -eux
|
||||||
./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json
|
./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json
|
||||||
@@ -28,24 +29,8 @@ steps:
|
|||||||
python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers
|
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 --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 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
|
- python3 tools/ci/assert_stale_analysis.py /tmp/control-analysis.json /tmp/control-events.jsonl
|
||||||
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_text())
|
|
||||||
assert snapshot["events"] == events, "stream and snapshot must be one event sequence"
|
|
||||||
print("stream and snapshot share one event sequence")
|
|
||||||
PY
|
|
||||||
- |
|
|
||||||
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
|
||||||
@@ -63,6 +48,8 @@ steps:
|
|||||||
- cargo test --workspace --locked
|
- cargo test --workspace --locked
|
||||||
- cargo test -p marqdo-cli --test docs_consistency
|
- cargo test -p marqdo-cli --test docs_consistency
|
||||||
- cargo test -p marqdo-cli --test architecture_boundaries
|
- cargo test -p marqdo-cli --test architecture_boundaries
|
||||||
|
- python3 tools/ci/check_dependency_boundaries.py
|
||||||
|
- python3 tools/ci/check_engine_boundary.py
|
||||||
- python3 -m unittest discover -s tools/ci -p "test_*.py"
|
- python3 -m unittest discover -s tools/ci -p "test_*.py"
|
||||||
- cargo test -p marqdo-cli --test stdlib_product
|
- cargo test -p marqdo-cli --test stdlib_product
|
||||||
# Windows compile gate: runtime lanes are native on GitHub; this catches
|
# Windows compile gate: runtime lanes are native on GitHub; this catches
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
# Marqdo CLI — Agent / Contributor Operating Rules
|
# Marqdo CLI — Agent / Contributor Operating Rules
|
||||||
|
|
||||||
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative.
|
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/architecture/CURRENT.md` (the single current architecture overview, including the Engine / Host Contract / Native Host map), [ADR-0071](docs/adr/0071-engine-host-contract-boundary.md) (boundary rules and keep-in-workspace decision), `docs/STATUS.md` (what is actually implemented), the relevant `spec/` files, `docs/adr/` for decisions at their date, the developer entry point `docs/developers/README.md`, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation, legacy Marqdo syntax, historical planning document or old architecture gate is authoritative.
|
||||||
|
|
||||||
For next-phase work, the authoritative release policy for the current
|
For next-phase work, the authoritative release policy for the current
|
||||||
`3.0.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). The current architecture and
|
||||||
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable
|
dependency direction are owned by `docs/architecture/CURRENT.md` and
|
||||||
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
|
[ADR-0071](docs/adr/0071-engine-host-contract-boundary.md). The historical plans
|
||||||
(historical stabilization spec, baseline `0adebe4`), `docs/NEXT_PHASE_IMPLEMENTATION.md`
|
(`DEVELOPMENT_BLUEPRINT.md`, `NEXT_PHASE_IMPLEMENTATION.md`,
|
||||||
(M0.6 plan), `docs/EXTENSIBILITY_AUDIT.md` (E01–E16), `COMPATIBILITY.md` and
|
`STABLE_RELEASE_IMPLEMENTATION.md`, `CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`,
|
||||||
`docs/security-gate.md`. Older plans are historical input; the 3.0 prerelease plan is authoritative for
|
`EXTENSIBILITY_AUDIT.md`, `NEXT_RELEASE_CI_CONVERGENCE.md`) are archived design
|
||||||
current release decisions, and the stable-release spec applies only when the
|
history: read them with that status, do not use them as current requirements, and
|
||||||
project moves from beta to stable.
|
do not create a second running-status page. `COMPATIBILITY.md` and
|
||||||
None describes implemented behavior; re-check against HEAD and tests. `strict`
|
`docs/security-gate.md` remain current inputs. None describes implemented
|
||||||
remains fail-closed until G-C passes.
|
behavior; re-check against HEAD and tests. `strict` remains fail-closed until
|
||||||
|
G-C passes.
|
||||||
|
|
||||||
The stable-release spec also governs scope: do not add a top-level CLI command,
|
The stable-release spec also governs scope: do not add a top-level CLI command,
|
||||||
Knowledge/Proof/View special-casing, a second interpreter or a new package
|
Knowledge/Proof/View special-casing, a second interpreter or a new package
|
||||||
@@ -33,6 +34,8 @@ correctness and release evidence before expanding the surface.
|
|||||||
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
|
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
|
||||||
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
|
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
|
||||||
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
|
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
|
||||||
|
12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the standalone public SDK repository `cflmy/marqdo-plugin-sdk` consumes one pinned CLI contract revision and the CLI must not depend on it (ADR-0072). CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071/ADR-0072.
|
||||||
|
13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires a separate accepted ADR with ownership/release evidence; "keep in workspace" is a valid recorded decision. The only split approved so far is the independent public SDK (ADR-0072); the SDK is pinned to a CLI contract `rev` and must not return as a workspace member or copied source. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path.
|
||||||
|
|
||||||
## Pre-stable protocol changes
|
## Pre-stable protocol changes
|
||||||
|
|
||||||
@@ -51,7 +54,7 @@ closing a protocol replacement issue.
|
|||||||
2. Update the normative spec **in place** first; there is never a second active syntax spec.
|
2. Update the normative spec **in place** first; there is never a second active syntax spec.
|
||||||
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
|
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
|
||||||
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
|
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
|
||||||
5. Run formatting, clippy, unit tests, golden tests and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`).
|
5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`).
|
||||||
6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly.
|
6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly.
|
||||||
|
|
||||||
## Unresolved design topics
|
## Unresolved design topics
|
||||||
|
|||||||
+102
-16
@@ -1,20 +1,74 @@
|
|||||||
# 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`) and
|
||||||
changes. Current protocol contracts are Analysis, Observation, CLI Tool,
|
`3.0.0-rc.3` (2026-11-24, source `1e2a045cc78bf40972181abb44e7117c56cf4401`); the section below is the current
|
||||||
|
release record. Current
|
||||||
|
protocol contracts are Analysis v3, Observation v1, CLI Tool revision 1,
|
||||||
Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4; independent
|
Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4; independent
|
||||||
package versions (including the bundled stdlib `0.1.0`) are versioned
|
package versions (including the bundled stdlib `0.1.0`) are versioned
|
||||||
separately and do not follow the product version. Dates use ISO 8601.
|
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.3 (candidate)
|
## 3.0.0-rc.4 (2026-11-25)
|
||||||
|
|
||||||
|
- The Rust workspace, CLI version output and protocol producers report
|
||||||
|
`3.0.0-rc.4`; the supported platform remains Linux x86_64 on glibc 2.39 and
|
||||||
|
the locked Rust minimum remains 1.89. Released as tag `v3.0.0-rc.4` at
|
||||||
|
`452e9a32bd9e40dba427d4180691c58bab74449e`.
|
||||||
|
|
||||||
|
### Closed public Analysis boundary — issue #10 (breaking in place)
|
||||||
|
|
||||||
|
Executed policy: [ADR-0069](docs/adr/0069-public-analysis-boundary.md), replacing
|
||||||
|
`marqdo.analysis` revision 3 in place under ADR-0068. There is no old reader,
|
||||||
|
version negotiation or fallback; a same-revision artifact that lacks a current
|
||||||
|
required field is rejected and must be regenerated.
|
||||||
|
|
||||||
|
- **Document facts are public.** `modules[].source` carries the exact UTF-8
|
||||||
|
source already read by the loader and `modules[].document` is the canonical
|
||||||
|
Markdown AST in the public shape shared with `inspect --ast`. Consumers no
|
||||||
|
longer parse Markdown a second time or read package-cache paths.
|
||||||
|
- **Heading scope is one index.** Units expose the structured `path`, parent,
|
||||||
|
effective mode, mode origin and source unit, the heading span and the complete
|
||||||
|
section span. The root covers the whole source including a BOM. Exec H2
|
||||||
|
function ownership stays explicit.
|
||||||
|
- **Entry and snapshot identity are explicit.** `project.entry_module_id`,
|
||||||
|
captured `manifest_digest`/`lock_digest`, stdlib identity and the static
|
||||||
|
extension identities used by preparation are part of the artifact. The
|
||||||
|
post-preparation lock re-read and its silent empty digest on IO failure are
|
||||||
|
gone.
|
||||||
|
- **One document-link resolver.** Analysis `references`, `check --refs` and
|
||||||
|
`inspect --refs` share one pure resolver and explicit catalogs. It reports
|
||||||
|
`resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, `outside_scope`
|
||||||
|
or `invalid`; ordinary Analysis never opens a link target and a same-document
|
||||||
|
anchor names the real source module. The duplicate `commands.rs` resolver is
|
||||||
|
deleted.
|
||||||
|
- **Calls stay bound once.** Static call records keep the single prepared
|
||||||
|
binding table and now expose target kind, exact function/builtin/plugin target
|
||||||
|
and a reason for unresolved calls. Plugin targets carry only their verified
|
||||||
|
static owner; no plugin function is fabricated.
|
||||||
|
- **Output is private and atomic.** `--emit` writes owner-only exclusive bytes
|
||||||
|
through a temporary file and rename, and refuses to overwrite a loaded source,
|
||||||
|
manifest, lock file, directory, symlink or hard link to an input.
|
||||||
|
- **Independent consumers are the gate.** The Python Analysis consumer performs
|
||||||
|
semantic validation in addition to JSON Schema; mutation fixtures reject
|
||||||
|
missing current fields, tampered source/digests/spans, cycles, wrong owners
|
||||||
|
and invalid reference/nullability combinations. View-, lint- and
|
||||||
|
knowledge-like fixtures drive the real installed CLI.
|
||||||
|
|
||||||
|
## 3.0.0-rc.3 (2026-11-24)
|
||||||
|
|
||||||
- The Rust workspace, CLI version output and protocol producers report
|
- The Rust workspace, CLI version output and protocol producers report
|
||||||
`3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux
|
`3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux
|
||||||
x86_64 on glibc 2.39.
|
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)
|
### Single current public contracts — issue #8 (breaking)
|
||||||
|
|
||||||
@@ -36,7 +90,9 @@ automatic migration.
|
|||||||
the same execution. `run_id`, `seq`, frame identity, terminal semantics,
|
the same execution. `run_id`, `seq`, frame identity, terminal semantics,
|
||||||
capture budgets and privacy rules are defined once in
|
capture budgets and privacy rules are defined once in
|
||||||
[`spec/observation.md`](spec/observation.md). The retired `--json`,
|
[`spec/observation.md`](spec/observation.md). The retired `--json`,
|
||||||
`--trace-file` and `--event-stream` options are rejected.
|
`--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
|
- **CLI Tool requirements are single exact values.** `tool.json` declares
|
||||||
`requires.api_revision` (required) plus optional exact `analysis` and
|
`requires.api_revision` (required) plus optional exact `analysis` and
|
||||||
`observation` integers. Version arrays and intersection negotiation are
|
`observation` integers. Version arrays and intersection negotiation are
|
||||||
@@ -53,7 +109,30 @@ automatic migration.
|
|||||||
explicit regeneration/reinstall instruction; no migrator runs.
|
explicit regeneration/reinstall instruction; no migrator runs.
|
||||||
- **`spec/` now contains only current contracts.** Retired specifications are
|
- **`spec/` now contains only current contracts.** Retired specifications are
|
||||||
available in Git history and tagged archives. ADRs covering retired public
|
available in Git history and tagged archives. ADRs covering retired public
|
||||||
contracts carry a Historical header.
|
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:
|
Migration for consumers:
|
||||||
|
|
||||||
@@ -78,13 +157,20 @@ Migration for consumers:
|
|||||||
- `crates/cli/tests/architecture_boundaries.rs` forbids a second worker
|
- `crates/cli/tests/architecture_boundaries.rs` forbids a second worker
|
||||||
framing implementation and pins the workspace layer list;
|
framing implementation and pins the workspace layer list;
|
||||||
`docs_consistency` keeps one current overview and resolving links.
|
`docs_consistency` keeps one current overview and resolving links.
|
||||||
- Same-SHA Linux CI [pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70)
|
- Same-SHA Linux CI ([pipeline #80](https://ci.cflmy.cn/repos/1/pipeline/80)),
|
||||||
passed all lanes, produced archive sha256
|
the archive build, the from-archive smoke, the cold-install container check
|
||||||
`d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37`, passed
|
and the frozen external conformance suite (fixtures at
|
||||||
the from-archive smoke and the frozen external conformance suite 7/7 with
|
`015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`, 7/7) are recorded in the
|
||||||
fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`.
|
per-gate manifest
|
||||||
- Publication still requires the RC strict-VM and G4 performance evidence
|
[`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
|
||||||
described in [`docs/releasing.md`](docs/releasing.md).
|
(`RC_RELEASE_CANDIDATE`).
|
||||||
|
- The RC strict-L1 disposable-VM lane passed on the tagged SHA and the
|
||||||
|
published archive was re-verified in that guest; see
|
||||||
|
[`docs/evidence/2026-11-24-rc.3-release.md`](docs/evidence/2026-11-24-rc.3-release.md).
|
||||||
|
G4 is a maintainer-approved shared-node `WARN` for this named RC (three
|
||||||
|
paired runs, no p50 threshold breach), with the environment and limits in the
|
||||||
|
release notes. Release:
|
||||||
|
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3.
|
||||||
|
|
||||||
## 3.0.0-rc.2 (candidate)
|
## 3.0.0-rc.2 (candidate)
|
||||||
|
|
||||||
|
|||||||
+47
-44
@@ -1,17 +1,22 @@
|
|||||||
# Compatibility and support matrix
|
# Compatibility and support matrix
|
||||||
|
|
||||||
Snapshot: product version **`3.0.0-beta.1`** (prerelease), branch `master`,
|
Snapshot: product version **`3.0.0-rc.4`** (prerelease, released 2026-11-25).
|
||||||
tagged `v3.0.0-beta.1` at source SHA `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. This file records what was actually verified and
|
Tag `v3.0.0-rc.4` at source SHA
|
||||||
separates it from what is only implemented. The supported release platform is
|
`452e9a32bd9e40dba427d4180691c58bab74449e`; release
|
||||||
**Linux x86_64 (glibc)**; everything else is experimental and not claimed for
|
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4. The previous
|
||||||
this beta. Executed status and same-SHA evidence are in
|
release is `3.0.0-rc.3` at source SHA
|
||||||
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under
|
`1e2a045cc78bf40972181abb44e7117c56cf4401`; its evidence remains under
|
||||||
[`docs/evidence/extension/`](docs/evidence/extension/README.md).
|
[`docs/evidence/`](docs/evidence/2026-11-24-rc.3-release.md). This file records
|
||||||
|
what was actually verified and separates it from what is only implemented. The
|
||||||
|
supported release platform is **Linux x86_64 (glibc 2.39)**; everything else is
|
||||||
|
experimental and not claimed for this prerelease. Executed status and SHA-bound
|
||||||
|
evidence are in [`docs/STATUS.md`](docs/STATUS.md) and
|
||||||
|
[`docs/evidence/`](docs/evidence/).
|
||||||
|
|
||||||
The `3.0.0-rc.3` candidate targets Linux x86_64 on glibc 2.39 and
|
The `3.0.0-rc.4` release includes the post-beta protocol convergence and the
|
||||||
includes the post-beta changes below. See the
|
closed public Analysis boundary below. See the
|
||||||
[RC acceptance procedure](docs/releasing.md). The platform evidence table
|
[RC acceptance procedure](docs/releasing.md). The platform evidence table
|
||||||
records the beta and subsequent development verification.
|
records the beta, rc.1/rc.2/rc.3 and rc.4 candidate verification.
|
||||||
|
|
||||||
## Language source syntax (breaking change)
|
## Language source syntax (breaking change)
|
||||||
|
|
||||||
@@ -51,7 +56,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.3` candidate**; they are
|
These landed after the beta tag and **are included in the `3.0.0-rc.4` 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).
|
||||||
|
|
||||||
@@ -65,9 +70,9 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid
|
|||||||
| 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`. |
|
| 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)
|
## Structured control flow (RFC-CTRL-0005, RC.2 and later)
|
||||||
|
|
||||||
The RC.2 candidate reserves `break` and `continue` only as complete
|
The RC.2 and RC.3 candidates reserve `break` and `continue` only as complete
|
||||||
payloads. An existing standalone identifier read can be written as
|
payloads. An existing standalone identifier read can be written as
|
||||||
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within
|
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within
|
||||||
expressions retain their meaning. Two separate carriers containing `else` and
|
expressions retain their meaning. Two separate carriers containing `else` and
|
||||||
@@ -77,25 +82,24 @@ Parameter inference ignores reads after a definite transfer. When upgrading
|
|||||||
a caller that passed an argument inferred solely from unreachable code,
|
a caller that passed an argument inferred solely from unreachable code,
|
||||||
remove the argument or keep it through an explicit `params(...)` declaration.
|
remove the argument or keep it through an explicit `params(...)` declaration.
|
||||||
|
|
||||||
`marqdo-lint 0.1.0` reads legacy Analysis v2 documents. Its control layout
|
The current Analysis contract is `schema_version: 3` for every project, so an
|
||||||
alignment for `else if` and its Analysis v3 support require an update in
|
external tool that still reads Analysis v2 must be updated before it can
|
||||||
that tool.
|
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.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. |
|
| Language / CLI | `3.0.0-rc.4` (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/v3 | Projects with loop transfers emit v3. Other projects emit v2. Consumers reject unknown majors. |
|
| 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. |
|
||||||
|
|
||||||
@@ -118,10 +122,9 @@ portable/tested locally but the native platform lane has not run here;
|
|||||||
| Official stdlib public aliases (print de-magic; byte-identical output) | PASS | UNVERIFIED | UNVERIFIED |
|
| Official stdlib public aliases (print de-magic; byte-identical output) | PASS | UNVERIFIED | UNVERIFIED |
|
||||||
| 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 (7/7 categories against the published archive, fixture repo `015ff8ac…`; see the rc.3 evidence bundle) | 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 |
|
||||||
@@ -149,14 +152,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
|
||||||
@@ -175,7 +179,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).
|
||||||
@@ -190,20 +194,19 @@ 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.4` prerelease — released as a Linux x86_64 RC.** 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 was
|
||||||
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3.1
|
used: Linux is the only supported platform, macOS/Windows are UNSUPPORTED for
|
||||||
was used, not the stable profile: Linux is the only supported platform,
|
this scope, strict L1 has same-SHA disposable-VM evidence, and G4 performance is
|
||||||
macOS/Windows are declared unsupported/experimental, G4 is a Beta-only `WARN`
|
a maintainer-approved shared-node `WARN` for this named RC only. The aggregate
|
||||||
on the fixed Woodpecker agent, and strict policy and frozen-binary conformance
|
decision and per-gate evidence are in
|
||||||
are recorded with same-SHA evidence in [`docs/STATUS.md`](docs/STATUS.md) and
|
[`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
|
||||||
[`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
(`RC_RELEASE_CANDIDATE`) and the release assets; see
|
||||||
(`BETA_RELEASE_CANDIDATE`). Release:
|
[`docs/evidence/2026-11-24-rc.3-release.md`](docs/evidence/2026-11-24-rc.3-release.md).
|
||||||
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. Beta status
|
A prerelease does not imply stable `3.0.0` or LTS; the stable gate remains
|
||||||
does not imply stable `3.0.0` or LTS; the stable gate remains stricter and
|
stricter and separate.
|
||||||
separate.
|
|
||||||
Generated
+30
-30
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-cli"
|
name = "marqdo-cli"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap",
|
"clap",
|
||||||
"hex",
|
"hex",
|
||||||
@@ -420,6 +420,7 @@ dependencies = [
|
|||||||
"marqdo-foreign",
|
"marqdo-foreign",
|
||||||
"marqdo-frontend",
|
"marqdo-frontend",
|
||||||
"marqdo-host",
|
"marqdo-host",
|
||||||
|
"marqdo-host-contract",
|
||||||
"marqdo-ir",
|
"marqdo-ir",
|
||||||
"marqdo-markdown",
|
"marqdo-markdown",
|
||||||
"marqdo-package",
|
"marqdo-package",
|
||||||
@@ -438,7 +439,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-expression"
|
name = "marqdo-expression"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
"num-bigint",
|
"num-bigint",
|
||||||
@@ -449,7 +450,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-foreign"
|
name = "marqdo-foreign"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"hex",
|
"hex",
|
||||||
"libc",
|
"libc",
|
||||||
@@ -465,7 +466,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-frontend"
|
name = "marqdo-frontend"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo-expression",
|
"marqdo-expression",
|
||||||
"marqdo-ir",
|
"marqdo-ir",
|
||||||
@@ -480,13 +481,15 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-host"
|
name = "marqdo-host"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"flate2",
|
"flate2",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"glob",
|
"glob",
|
||||||
|
"hex",
|
||||||
"libloading",
|
"libloading",
|
||||||
"marqdo-foreign",
|
"marqdo-foreign",
|
||||||
|
"marqdo-host-contract",
|
||||||
"marqdo-plugin-abi",
|
"marqdo-plugin-abi",
|
||||||
"marqdo-sandbox",
|
"marqdo-sandbox",
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
@@ -499,13 +502,23 @@ dependencies = [
|
|||||||
"rustls-pemfile",
|
"rustls-pemfile",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"serde_yaml",
|
||||||
|
"sha2",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "marqdo-host-contract"
|
||||||
|
version = "3.0.0-rc.4"
|
||||||
|
dependencies = [
|
||||||
|
"marqdo-span",
|
||||||
|
"marqdo-value",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-ir"
|
name = "marqdo-ir"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo-expression",
|
"marqdo-expression",
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
@@ -515,7 +528,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-markdown"
|
name = "marqdo-markdown"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"comrak",
|
"comrak",
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
@@ -526,7 +539,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-package"
|
name = "marqdo-package"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"hex",
|
"hex",
|
||||||
"semver",
|
"semver",
|
||||||
@@ -540,35 +553,21 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-plugin-abi"
|
name = "marqdo-plugin-abi"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"hex",
|
|
||||||
"libloading",
|
|
||||||
"marqdo-span",
|
|
||||||
"marqdo-value",
|
"marqdo-value",
|
||||||
"marqdo-worker-ipc",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
|
||||||
"sha2",
|
|
||||||
"thiserror",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "marqdo-plugin-sdk"
|
|
||||||
version = "3.0.0-rc.3"
|
|
||||||
dependencies = [
|
|
||||||
"marqdo-plugin-abi",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-provider-worker"
|
name = "marqdo-provider-worker"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libloading",
|
"libloading",
|
||||||
"marqdo-host",
|
"marqdo-host",
|
||||||
|
"marqdo-host-contract",
|
||||||
"marqdo-sandbox",
|
"marqdo-sandbox",
|
||||||
"marqdo-value",
|
"marqdo-value",
|
||||||
"marqdo-worker-ipc",
|
"marqdo-worker-ipc",
|
||||||
@@ -578,11 +577,12 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-runtime"
|
name = "marqdo-runtime"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo-expression",
|
"marqdo-expression",
|
||||||
"marqdo-frontend",
|
"marqdo-frontend",
|
||||||
"marqdo-host",
|
"marqdo-host",
|
||||||
|
"marqdo-host-contract",
|
||||||
"marqdo-ir",
|
"marqdo-ir",
|
||||||
"marqdo-sandbox",
|
"marqdo-sandbox",
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
@@ -597,7 +597,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-sandbox"
|
name = "marqdo-sandbox"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -605,14 +605,14 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-span"
|
name = "marqdo-span"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-value"
|
name = "marqdo-value"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo-span",
|
"marqdo-span",
|
||||||
"num-bigint",
|
"num-bigint",
|
||||||
@@ -623,7 +623,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-worker-ipc"
|
name = "marqdo-worker-ipc"
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
|||||||
+3
-2
@@ -11,8 +11,8 @@ members = [
|
|||||||
"crates/marqdo-plugin-abi",
|
"crates/marqdo-plugin-abi",
|
||||||
"crates/marqdo-provider-worker",
|
"crates/marqdo-provider-worker",
|
||||||
"crates/marqdo-worker-ipc",
|
"crates/marqdo-worker-ipc",
|
||||||
"crates/marqdo-plugin-sdk",
|
|
||||||
"crates/marqdo-host",
|
"crates/marqdo-host",
|
||||||
|
"crates/marqdo-host-contract",
|
||||||
"crates/marqdo-runtime",
|
"crates/marqdo-runtime",
|
||||||
"crates/marqdo-package",
|
"crates/marqdo-package",
|
||||||
"crates/marqdo-sandbox",
|
"crates/marqdo-sandbox",
|
||||||
@@ -20,7 +20,7 @@ members = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "3.0.0-rc.3"
|
version = "3.0.0-rc.4"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.89"
|
rust-version = "1.89"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -38,6 +38,7 @@ marqdo-foreign = { path = "crates/marqdo-foreign" }
|
|||||||
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
|
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
|
||||||
marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" }
|
marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" }
|
||||||
marqdo-host = { path = "crates/marqdo-host" }
|
marqdo-host = { path = "crates/marqdo-host" }
|
||||||
|
marqdo-host-contract = { path = "crates/marqdo-host-contract" }
|
||||||
marqdo-runtime = { path = "crates/marqdo-runtime" }
|
marqdo-runtime = { path = "crates/marqdo-runtime" }
|
||||||
marqdo-package = { path = "crates/marqdo-package" }
|
marqdo-package = { path = "crates/marqdo-package" }
|
||||||
marqdo-sandbox = { path = "crates/marqdo-sandbox" }
|
marqdo-sandbox = { path = "crates/marqdo-sandbox" }
|
||||||
|
|||||||
@@ -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.3`** in this checkout. It is **not** a compatibility rewrite of
|
version **`3.0.0-rc.4`** 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
|
||||||
@@ -27,7 +27,10 @@ release policy.
|
|||||||
> [`docs/STATUS.md`](docs/STATUS.md) and
|
> [`docs/STATUS.md`](docs/STATUS.md) and
|
||||||
> [`docs/migration/README.md`](docs/migration/README.md).
|
> [`docs/migration/README.md`](docs/migration/README.md).
|
||||||
|
|
||||||
> **Published baseline: `3.0.0-beta.1` prerelease** —
|
> **Current release: `3.0.0-rc.4` prerelease** —
|
||||||
|
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4),
|
||||||
|
> source `452e9a32bd9e40dba427d4180691c58bab74449e`, Linux x86_64. The previous
|
||||||
|
> published baseline was `3.0.0-beta.1` —
|
||||||
> [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
|
||||||
@@ -46,8 +49,9 @@ release policy.
|
|||||||
CI: the source of truth is the Gitea remote
|
CI: the source of truth is the Gitea remote
|
||||||
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
|
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
|
||||||
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
|
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
|
||||||
runs fmt, clippy, workspace tests with `--locked`, the Windows cross-target
|
runs fmt, clippy, workspace tests with `--locked`, the dependency-direction and
|
||||||
compile gate and a release build of both binaries. The strict OS-isolation lane
|
engine-independence gates, the Windows
|
||||||
|
cross-target compile gate and a release build of both binaries. The strict OS-isolation lane
|
||||||
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
|
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
|
||||||
mirror is not used as the authoritative lane for this beta.
|
mirror is not used as the authoritative lane for this beta.
|
||||||
|
|
||||||
@@ -215,7 +219,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
|
||||||
@@ -251,7 +255,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.
|
||||||
@@ -291,17 +295,18 @@ crates/marqdo-ir module/unit/function/statement IR, builtin table
|
|||||||
crates/marqdo-frontend heading scopes, mapping, inference, static calls
|
crates/marqdo-frontend heading scopes, mapping, inference, static calls
|
||||||
crates/marqdo-foreign Python/Node one-shot kernel supervisor
|
crates/marqdo-foreign Python/Node one-shot kernel supervisor
|
||||||
crates/marqdo-sandbox mode parsing + platform isolation detection
|
crates/marqdo-sandbox mode parsing + platform isolation detection
|
||||||
crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader
|
crates/marqdo-host-contract neutral Host trait, HostOp, context and runtime facts
|
||||||
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro
|
crates/marqdo-plugin-abi public C ABI v1 contract: layout, wire envelope, errors
|
||||||
crates/marqdo-host CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
|
(the Rust SDK lives in cflmy/marqdo-plugin-sdk)
|
||||||
crates/marqdo-runtime tree-walk interpreter
|
crates/marqdo-host Native Host: capability, resources, OS, plugin loader/worker
|
||||||
|
crates/marqdo-runtime tree-walk interpreter (depends only on the neutral contract)
|
||||||
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
|
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
|
||||||
crates/cli CLI composition root (binary `marqdo`)
|
crates/cli CLI composition root (binary `marqdo`)
|
||||||
include/ frozen plugin C ABI header
|
include/ frozen plugin C ABI header
|
||||||
spec/ normative language/format/ABI specs
|
spec/ normative language/format/ABI specs
|
||||||
docs/ blueprint, ADRs, status, contributor guide
|
docs/ blueprint, ADRs, status, contributor guide
|
||||||
examples/ runnable documents + multi-module + plugin demo
|
examples/ runnable documents + multi-module + plugin demo
|
||||||
tests/ conformance/negative corpus (see tests/README.md)
|
tests/ conformance/negative corpus, embedding consumer and SDK fixture
|
||||||
```
|
```
|
||||||
|
|
||||||
## Documentation index
|
## Documentation index
|
||||||
@@ -327,7 +332,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
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ marqdo-frontend = { workspace = true }
|
|||||||
marqdo-foreign = { workspace = true }
|
marqdo-foreign = { workspace = true }
|
||||||
marqdo-plugin-abi = { workspace = true }
|
marqdo-plugin-abi = { workspace = true }
|
||||||
marqdo-host = { workspace = true }
|
marqdo-host = { workspace = true }
|
||||||
|
marqdo-host-contract = { workspace = true }
|
||||||
marqdo-runtime = { workspace = true }
|
marqdo-runtime = { workspace = true }
|
||||||
marqdo-package = { workspace = true }
|
marqdo-package = { workspace = true }
|
||||||
marqdo-sandbox = { workspace = true }
|
marqdo-sandbox = { workspace = true }
|
||||||
|
|||||||
@@ -1,653 +0,0 @@
|
|||||||
//! Public Analysis projection (spec/analysis.md).
|
|
||||||
//!
|
|
||||||
//! 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
|
|
||||||
//! exporter is read-only and never executes a document, loads a plugin or
|
|
||||||
//! starts a foreign kernel.
|
|
||||||
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use marqdo_expression::{BinaryOp, Expr, UnaryOp};
|
|
||||||
use marqdo_ir::{Function, Module, ModuleId, PlaceTarget, Resource, SignatureKind, Stmt, UnitKind};
|
|
||||||
use marqdo_span::Span;
|
|
||||||
use serde_json::{json, Value};
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
use crate::loader::LoadedProject;
|
|
||||||
|
|
||||||
/// Schema name and version.
|
|
||||||
pub const SCHEMA: &str = "marqdo.analysis";
|
|
||||||
pub const SCHEMA_VERSION: u32 = 3;
|
|
||||||
|
|
||||||
/// Build the deterministic public projection.
|
|
||||||
pub fn build(project: &LoadedProject) -> Value {
|
|
||||||
let mut modules = Vec::new();
|
|
||||||
for (module_id, file) in &project.files {
|
|
||||||
let module = &file.analysis.module;
|
|
||||||
modules.push(json!({
|
|
||||||
"id": module_id.to_string(),
|
|
||||||
"package_instance_id": module_id.instance,
|
|
||||||
"relative_path": module_id.relative_path,
|
|
||||||
"source_digest": sha256_hex(file.source.as_bytes()),
|
|
||||||
"units": units_json(module),
|
|
||||||
"functions": module.functions.iter().map(function_json).collect::<Vec<_>>(),
|
|
||||||
"imports": module.imports.iter().map(|import| json!({
|
|
||||||
"alias": import.alias,
|
|
||||||
"target": import.target,
|
|
||||||
"span": import.span,
|
|
||||||
"resolved": project.program.resolve_import(module_id, &import.alias).map(ToString::to_string),
|
|
||||||
})).collect::<Vec<_>>(),
|
|
||||||
"references": reference_edges(project, module_id),
|
|
||||||
"calls": module.functions.iter().flat_map(|function| calls_json(project, module, function)).collect::<Vec<_>>(),
|
|
||||||
"resources": resources_json(module_id, module),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
modules.sort_by(|a, b| {
|
|
||||||
a.get("id")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.cmp(&b.get("id").and_then(Value::as_str))
|
|
||||||
});
|
|
||||||
json!({
|
|
||||||
"schema": SCHEMA,
|
|
||||||
"schema_version": SCHEMA_VERSION,
|
|
||||||
"producer": {
|
|
||||||
"name": "marqdo",
|
|
||||||
"version": env!("CARGO_PKG_VERSION"),
|
|
||||||
"markdown_profile": "marqdo.md.v1",
|
|
||||||
},
|
|
||||||
"project": {
|
|
||||||
"root_id": project.identity.root_id(),
|
|
||||||
"identity_kind": project.identity.kind(),
|
|
||||||
"lock_digest": lock_digest(project),
|
|
||||||
"stdlib": project.stdlib.as_ref().map(|stdlib| json!({
|
|
||||||
"version": stdlib.version,
|
|
||||||
"digest": stdlib.digest,
|
|
||||||
"instance_id": stdlib.instance_id,
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
"modules": modules,
|
|
||||||
"diagnostics": diagnostics_json(project),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encode exactly the bytes written by `check --emit`.
|
|
||||||
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
|
|
||||||
serde_json::to_vec_pretty(&build(project))
|
|
||||||
.map_err(|error| format!("cannot encode analysis: {error}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// SHA-256 of the exact emitted Analysis bytes.
|
|
||||||
pub fn digest(project: &LoadedProject) -> Result<String, String> {
|
|
||||||
encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Atomically write the projection. An error must not leave a stale success
|
|
||||||
/// artifact behind.
|
|
||||||
pub fn write(project: &LoadedProject, path: &Path) -> Result<(), String> {
|
|
||||||
let bytes = encode(project)?;
|
|
||||||
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(|| "analysis.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(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lock_digest(project: &LoadedProject) -> Value {
|
|
||||||
let path = project.root.join(marqdo_package::LOCK_FILE);
|
|
||||||
match std::fs::read(path) {
|
|
||||||
Ok(bytes) => Value::String(format!("sha256:{}", sha256_hex(&bytes))),
|
|
||||||
Err(_) => Value::String(String::new()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resources_json(module_id: &ModuleId, module: &Module) -> Vec<Value> {
|
|
||||||
let mut formula_index = 0usize;
|
|
||||||
let mut code_index = 0usize;
|
|
||||||
module
|
|
||||||
.resources
|
|
||||||
.iter()
|
|
||||||
.map(|resource| match resource {
|
|
||||||
Resource::Formula {
|
|
||||||
unit,
|
|
||||||
latex,
|
|
||||||
display,
|
|
||||||
span,
|
|
||||||
} => {
|
|
||||||
formula_index += 1;
|
|
||||||
json!({
|
|
||||||
"id": format!("{module_id}#resource:formula-{formula_index}"),
|
|
||||||
"module_id": module_id.to_string(),
|
|
||||||
"unit_id": unit.to_string(),
|
|
||||||
"kind": "formula",
|
|
||||||
"span": span_json(*span),
|
|
||||||
"content_digest": sha256_hex(latex.as_bytes()),
|
|
||||||
"language": null,
|
|
||||||
"display": display,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Resource::Code {
|
|
||||||
unit,
|
|
||||||
language,
|
|
||||||
source: _,
|
|
||||||
content_hash,
|
|
||||||
span,
|
|
||||||
} => {
|
|
||||||
code_index += 1;
|
|
||||||
json!({
|
|
||||||
"id": format!("{module_id}#resource:code-{code_index}"),
|
|
||||||
"module_id": module_id.to_string(),
|
|
||||||
"unit_id": unit.to_string(),
|
|
||||||
"kind": "code",
|
|
||||||
"span": span_json(*span),
|
|
||||||
"content_digest": content_hash,
|
|
||||||
"language": language,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn diagnostics_json(project: &LoadedProject) -> Vec<Value> {
|
|
||||||
project
|
|
||||||
.diagnostics
|
|
||||||
.iter()
|
|
||||||
.map(|item| {
|
|
||||||
let (line, column) = item
|
|
||||||
.line_col()
|
|
||||||
.map(|(line, column)| (Value::from(line), Value::from(column)))
|
|
||||||
.unwrap_or((Value::Null, Value::Null));
|
|
||||||
json!({
|
|
||||||
"module": item.module_id.to_string(),
|
|
||||||
"relative_path": item.module_id.relative_path,
|
|
||||||
"span": item.diagnostic.span.map(span_json),
|
|
||||||
"line": line,
|
|
||||||
"column": column,
|
|
||||||
"severity": if item.diagnostic.is_error() { "error" } else { "warning" },
|
|
||||||
"code": item.diagnostic.code,
|
|
||||||
"message": item.diagnostic.message,
|
|
||||||
"hints": item.diagnostic.hints,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn units_json(module: &Module) -> Vec<Value> {
|
|
||||||
module
|
|
||||||
.units
|
|
||||||
.iter()
|
|
||||||
.map(|unit| {
|
|
||||||
let kind = match unit.kind {
|
|
||||||
UnitKind::Root => "root",
|
|
||||||
UnitKind::Namespace => "namespace",
|
|
||||||
UnitKind::Function => "function",
|
|
||||||
UnitKind::Knowledge => "knowledge",
|
|
||||||
UnitKind::Section => "section",
|
|
||||||
};
|
|
||||||
json!({
|
|
||||||
"id": unit.id.to_string(),
|
|
||||||
"kind": kind,
|
|
||||||
"name": unit.name,
|
|
||||||
"level": unit.level,
|
|
||||||
"span": span_json(unit.span),
|
|
||||||
"function": unit.function.as_ref().map(ToString::to_string),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn function_json(function: &Function) -> Value {
|
|
||||||
json!({
|
|
||||||
"id": function.id.to_string(),
|
|
||||||
"unit_id": function.unit.to_string(),
|
|
||||||
"local_name": function.local_name,
|
|
||||||
"namespace": function.namespace,
|
|
||||||
"span": span_json(function.span),
|
|
||||||
"heading_span": span_json(function.heading_span),
|
|
||||||
"signature": {
|
|
||||||
"kind": match function.signature {
|
|
||||||
SignatureKind::Explicit => "explicit",
|
|
||||||
SignatureKind::Inferred => "inferred",
|
|
||||||
},
|
|
||||||
"params": function.params.iter().map(|param| json!({
|
|
||||||
"name": param.name,
|
|
||||||
"required": param.default.is_none(),
|
|
||||||
"type": param.type_annotation,
|
|
||||||
"default": param.default.as_ref().map(expr_json),
|
|
||||||
"span": span_json(param.span),
|
|
||||||
})).collect::<Vec<_>>(),
|
|
||||||
},
|
|
||||||
"effects": ["unknown"],
|
|
||||||
"body": function.body.iter().map(stmt_json).collect::<Vec<_>>(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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
|
|
||||||
/// local `target` string are unaffected (Analysis v2, ADR-0022).
|
|
||||||
fn place_json(place: &PlaceTarget) -> Value {
|
|
||||||
match place {
|
|
||||||
PlaceTarget::Local { name, .. } => Value::String(name.clone()),
|
|
||||||
PlaceTarget::Index { base, index, span } => json!({
|
|
||||||
"kind": "index",
|
|
||||||
"base": expr_json(base),
|
|
||||||
"index": expr_json(index),
|
|
||||||
"span": span_json(*span),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stmt_json(stmt: &Stmt) -> Value {
|
|
||||||
match stmt {
|
|
||||||
Stmt::Assign {
|
|
||||||
target,
|
|
||||||
value,
|
|
||||||
span,
|
|
||||||
..
|
|
||||||
} => json!({
|
|
||||||
"kind": "assign",
|
|
||||||
"target": place_json(target),
|
|
||||||
"value": expr_json(value),
|
|
||||||
"span": span_json(*span),
|
|
||||||
}),
|
|
||||||
Stmt::Eval { expr, span } => json!({
|
|
||||||
"kind": "expression",
|
|
||||||
"value": expr_json(expr),
|
|
||||||
"span": span_json(*span),
|
|
||||||
}),
|
|
||||||
Stmt::Branch { arms, span } => json!({
|
|
||||||
"kind": "branch",
|
|
||||||
"arms": arms.iter().map(|arm| json!({
|
|
||||||
"condition": expr_json(&arm.condition),
|
|
||||||
"condition_span": span_json(arm.condition_span),
|
|
||||||
"body": arm.body.iter().map(stmt_json).collect::<Vec<_>>(),
|
|
||||||
"span": span_json(arm.span),
|
|
||||||
})).collect::<Vec<_>>(),
|
|
||||||
"span": span_json(*span),
|
|
||||||
}),
|
|
||||||
Stmt::Loop {
|
|
||||||
condition,
|
|
||||||
condition_span,
|
|
||||||
body,
|
|
||||||
span,
|
|
||||||
} => json!({
|
|
||||||
"kind": "loop",
|
|
||||||
"condition": expr_json(condition),
|
|
||||||
"condition_span": span_json(*condition_span),
|
|
||||||
"body": body.iter().map(stmt_json).collect::<Vec<_>>(),
|
|
||||||
"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!({
|
|
||||||
"kind": "return",
|
|
||||||
"value": expr_json(value),
|
|
||||||
"span": span_json(*span),
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expr_json(expr: &Expr) -> Value {
|
|
||||||
let span = span_json(expr.span());
|
|
||||||
match expr {
|
|
||||||
Expr::Int(value) => {
|
|
||||||
json!({"kind":"literal","type":"int","value":value.to_string(),"span":span})
|
|
||||||
}
|
|
||||||
Expr::Float(value) => json!({"kind":"literal","type":"float","value":value,"span":span}),
|
|
||||||
Expr::Text(value) => json!({"kind":"literal","type":"text","value":value,"span":span}),
|
|
||||||
Expr::Bool(value) => json!({"kind":"literal","type":"bool","value":value,"span":span}),
|
|
||||||
Expr::None => json!({"kind":"literal","type":"none","span":span}),
|
|
||||||
Expr::Ident(ident) => {
|
|
||||||
json!({"kind":"variable","name":ident.name,"span":span_json(ident.span)})
|
|
||||||
}
|
|
||||||
Expr::List(items) => {
|
|
||||||
json!({"kind":"list","items":items.iter().map(expr_json).collect::<Vec<_>>(),"span":span})
|
|
||||||
}
|
|
||||||
Expr::Record(entries) => json!({
|
|
||||||
"kind":"record",
|
|
||||||
"entries": entries.iter().map(|entry| json!({
|
|
||||||
"key": entry.key,
|
|
||||||
"key_span": span_json(entry.key_span),
|
|
||||||
"value": expr_json(&entry.value),
|
|
||||||
})).collect::<Vec<_>>(),
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
Expr::Unary { op, operand, .. } => json!({
|
|
||||||
"kind":"unary",
|
|
||||||
"op": unary_name(*op),
|
|
||||||
"operand": expr_json(operand),
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
Expr::Binary {
|
|
||||||
op, left, right, ..
|
|
||||||
} => json!({
|
|
||||||
"kind":"binary",
|
|
||||||
"op": binary_name(*op),
|
|
||||||
"left": expr_json(left),
|
|
||||||
"right": expr_json(right),
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
Expr::Member { base, name, .. } => json!({
|
|
||||||
"kind":"member",
|
|
||||||
"base": expr_json(base),
|
|
||||||
"field": name,
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
Expr::Index { base, index, .. } => json!({
|
|
||||||
"kind":"index",
|
|
||||||
"base": expr_json(base),
|
|
||||||
"index": expr_json(index),
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
Expr::Call { callee, args, .. } => json!({
|
|
||||||
"kind":"call",
|
|
||||||
"callee": expr_json(callee),
|
|
||||||
"args": args.iter().map(arg_json).collect::<Vec<_>>(),
|
|
||||||
"span":span
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn arg_json(arg: &marqdo_expression::Arg) -> Value {
|
|
||||||
json!({
|
|
||||||
"name": arg.name,
|
|
||||||
"value": expr_json(&arg.value),
|
|
||||||
"span": span_json(arg.span),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reference_edges(project: &LoadedProject, module_id: &marqdo_ir::ModuleId) -> Vec<Value> {
|
|
||||||
let Some(file) = project.files.get(module_id) else {
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
let parent = file.path.parent().unwrap_or_else(|| Path::new("."));
|
|
||||||
let mut edges = Vec::new();
|
|
||||||
file.analysis.document.root.walk(&mut |node| {
|
|
||||||
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
edges.push(resolve_reference(
|
|
||||||
project,
|
|
||||||
module_id,
|
|
||||||
&file.analysis.units,
|
|
||||||
parent,
|
|
||||||
url,
|
|
||||||
node.span,
|
|
||||||
));
|
|
||||||
});
|
|
||||||
edges.sort_by_key(|edge| {
|
|
||||||
edge.get("span")
|
|
||||||
.and_then(|span| span.get("start"))
|
|
||||||
.and_then(Value::as_u64)
|
|
||||||
.unwrap_or(0)
|
|
||||||
});
|
|
||||||
edges
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_reference(
|
|
||||||
project: &LoadedProject,
|
|
||||||
source_module: &marqdo_ir::ModuleId,
|
|
||||||
units: &marqdo_frontend::UnitIndex,
|
|
||||||
parent: &Path,
|
|
||||||
url: &str,
|
|
||||||
span: Span,
|
|
||||||
) -> Value {
|
|
||||||
if let Some(fragment) = url.strip_prefix('#') {
|
|
||||||
let unit = units.anchors.get(fragment).or_else(|| {
|
|
||||||
units
|
|
||||||
.units
|
|
||||||
.iter()
|
|
||||||
.find(|unit| unit.name == fragment)
|
|
||||||
.map(|unit| &unit.id)
|
|
||||||
});
|
|
||||||
return json!({
|
|
||||||
"source": source_module.to_string(),
|
|
||||||
"url": url,
|
|
||||||
"span": span_json(span),
|
|
||||||
"state": if unit.is_some() { "resolved" } else { "unresolved" },
|
|
||||||
"target_module": source_module.to_string(),
|
|
||||||
"target_unit": unit.map(ToString::to_string),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if url.starts_with("http://") || url.starts_with("https://") {
|
|
||||||
return json!({
|
|
||||||
"source": source_module.to_string(),
|
|
||||||
"url": url,
|
|
||||||
"span": span_json(span),
|
|
||||||
"state": "external",
|
|
||||||
"target_module": null,
|
|
||||||
"target_unit": null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let (path_part, fragment) = match url.split_once('#') {
|
|
||||||
Some((path, fragment)) => (path, Some(fragment)),
|
|
||||||
None => (url, None),
|
|
||||||
};
|
|
||||||
let candidate = parent.join(path_part);
|
|
||||||
let Some(target_module) = project.module_id_for_path(&candidate) else {
|
|
||||||
return json!({
|
|
||||||
"source": source_module.to_string(),
|
|
||||||
"url": url,
|
|
||||||
"span": span_json(span),
|
|
||||||
"state": "unresolved",
|
|
||||||
"target_module": null,
|
|
||||||
"target_unit": null,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
let target_units = project
|
|
||||||
.files
|
|
||||||
.get(&target_module)
|
|
||||||
.map(|file| &file.analysis.units);
|
|
||||||
let resolved = match (fragment, target_units) {
|
|
||||||
(None, _) => Some(None),
|
|
||||||
(Some(fragment), Some(units)) => units
|
|
||||||
.anchors
|
|
||||||
.get(fragment)
|
|
||||||
.or_else(|| {
|
|
||||||
units
|
|
||||||
.units
|
|
||||||
.iter()
|
|
||||||
.find(|unit| unit.name == fragment)
|
|
||||||
.map(|unit| &unit.id)
|
|
||||||
})
|
|
||||||
.map(|unit| Some(unit.to_string())),
|
|
||||||
(Some(_), None) => None,
|
|
||||||
};
|
|
||||||
let (state, target_unit) = match resolved {
|
|
||||||
Some(unit) => ("resolved", unit),
|
|
||||||
None => ("unresolved", None),
|
|
||||||
};
|
|
||||||
json!({
|
|
||||||
"source": source_module.to_string(),
|
|
||||||
"url": url,
|
|
||||||
"span": span_json(span),
|
|
||||||
"state": state,
|
|
||||||
"target_module": target_module.to_string(),
|
|
||||||
"target_unit": target_unit,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn calls_json(project: &LoadedProject, module: &Module, function: &Function) -> Vec<Value> {
|
|
||||||
let mut calls = Vec::new();
|
|
||||||
collect_calls(project, module, function, &function.body, &mut calls);
|
|
||||||
calls.sort_by_key(|call| {
|
|
||||||
call.get("span")
|
|
||||||
.and_then(|span| span.get("start"))
|
|
||||||
.and_then(Value::as_u64)
|
|
||||||
.unwrap_or(0)
|
|
||||||
});
|
|
||||||
calls
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_calls(
|
|
||||||
project: &LoadedProject,
|
|
||||||
module: &Module,
|
|
||||||
function: &Function,
|
|
||||||
body: &[Stmt],
|
|
||||||
calls: &mut Vec<Value>,
|
|
||||||
) {
|
|
||||||
for stmt in body {
|
|
||||||
match stmt {
|
|
||||||
Stmt::Assign { target, value, .. } => {
|
|
||||||
if let PlaceTarget::Index { base, index, .. } = target {
|
|
||||||
expr_calls(project, module, function, base, calls);
|
|
||||||
expr_calls(project, module, function, index, calls);
|
|
||||||
}
|
|
||||||
expr_calls(project, module, function, value, calls);
|
|
||||||
}
|
|
||||||
Stmt::Eval { expr: value, .. } => expr_calls(project, module, function, value, calls),
|
|
||||||
Stmt::Return { value, .. } => expr_calls(project, module, function, value, calls),
|
|
||||||
Stmt::Branch { arms, .. } => {
|
|
||||||
for arm in arms {
|
|
||||||
expr_calls(project, module, function, &arm.condition, calls);
|
|
||||||
collect_calls(project, module, function, &arm.body, calls);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Stmt::Loop {
|
|
||||||
condition, body, ..
|
|
||||||
} => {
|
|
||||||
expr_calls(project, module, function, condition, calls);
|
|
||||||
collect_calls(project, module, function, body, calls);
|
|
||||||
}
|
|
||||||
Stmt::Break { .. } | Stmt::Continue { .. } => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expr_calls(
|
|
||||||
project: &LoadedProject,
|
|
||||||
module: &Module,
|
|
||||||
function: &Function,
|
|
||||||
expr: &Expr,
|
|
||||||
calls: &mut Vec<Value>,
|
|
||||||
) {
|
|
||||||
match expr {
|
|
||||||
Expr::Call { callee, args, span } => {
|
|
||||||
let (state, target) = resolve_callee(project, module, function, *span);
|
|
||||||
calls.push(json!({
|
|
||||||
"function": function.id.to_string(),
|
|
||||||
"span": span_json(*span),
|
|
||||||
"callee": callee_json(callee),
|
|
||||||
"state": state,
|
|
||||||
"target": target,
|
|
||||||
}));
|
|
||||||
for arg in args {
|
|
||||||
expr_calls(project, module, function, &arg.value, calls);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Expr::Unary { operand, .. } => expr_calls(project, module, function, operand, calls),
|
|
||||||
Expr::Binary { left, right, .. } => {
|
|
||||||
expr_calls(project, module, function, left, calls);
|
|
||||||
expr_calls(project, module, function, right, calls);
|
|
||||||
}
|
|
||||||
Expr::List(items) => {
|
|
||||||
for item in items {
|
|
||||||
expr_calls(project, module, function, item, calls);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Expr::Record(entries) => {
|
|
||||||
for entry in entries {
|
|
||||||
expr_calls(project, module, function, &entry.value, calls);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Expr::Member { base, .. } => expr_calls(project, module, function, base, calls),
|
|
||||||
Expr::Index { base, index, .. } => {
|
|
||||||
expr_calls(project, module, function, base, calls);
|
|
||||||
expr_calls(project, module, function, index, calls);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Project the authoritative call binding into the Analysis `state`/`target`
|
|
||||||
/// fields.
|
|
||||||
///
|
|
||||||
/// Analysis is a read-only projection of the same prepared binding the runtime
|
|
||||||
/// consumes (RFC-EXT-0001 §4/§9): there is no second name-resolution algorithm
|
|
||||||
/// here. `state` keeps its v1 vocabulary (`function`, `builtin`, `plugin`,
|
|
||||||
/// `unresolved`); official stdlib aliases such as `打印` therefore appear as
|
|
||||||
/// `function` targets because that is the implementation that actually runs.
|
|
||||||
fn resolve_callee(
|
|
||||||
project: &LoadedProject,
|
|
||||||
_module: &Module,
|
|
||||||
function: &Function,
|
|
||||||
span: Span,
|
|
||||||
) -> (&'static str, Value) {
|
|
||||||
let key = marqdo_ir::call_binding::CallSiteKey::new(function.id.clone(), span);
|
|
||||||
match project.program.call_bindings.get(&key) {
|
|
||||||
Some(marqdo_ir::call_binding::BoundTarget::Builtin { canonical_name }) => {
|
|
||||||
("builtin", json!(canonical_name))
|
|
||||||
}
|
|
||||||
Some(marqdo_ir::call_binding::BoundTarget::Marqdo { function }) => {
|
|
||||||
("function", json!(function.to_string()))
|
|
||||||
}
|
|
||||||
Some(marqdo_ir::call_binding::BoundTarget::AbiPlugin { export, .. }) => {
|
|
||||||
("plugin", json!(export))
|
|
||||||
}
|
|
||||||
Some(marqdo_ir::call_binding::BoundTarget::DynamicValue) | None => {
|
|
||||||
("unresolved", Value::Null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn callee_json(callee: &Expr) -> Value {
|
|
||||||
match callee {
|
|
||||||
Expr::Ident(ident) => json!({"kind":"ident","name":ident.name}),
|
|
||||||
Expr::Member { base, name, .. } => {
|
|
||||||
json!({"kind":"member","base":callee_json(base),"field":name})
|
|
||||||
}
|
|
||||||
other => json!({"kind":"expression","span":span_json(other.span())}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn span_json(span: Span) -> Value {
|
|
||||||
json!({"start": span.start, "end": span.end})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unary_name(op: UnaryOp) -> &'static str {
|
|
||||||
match op {
|
|
||||||
UnaryOp::Not => "not",
|
|
||||||
UnaryOp::Neg => "neg",
|
|
||||||
UnaryOp::Pos => "pos",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn binary_name(op: BinaryOp) -> &'static str {
|
|
||||||
match op {
|
|
||||||
BinaryOp::Or => "or",
|
|
||||||
BinaryOp::And => "and",
|
|
||||||
BinaryOp::Eq => "eq",
|
|
||||||
BinaryOp::Ne => "ne",
|
|
||||||
BinaryOp::Lt => "lt",
|
|
||||||
BinaryOp::Le => "le",
|
|
||||||
BinaryOp::Gt => "gt",
|
|
||||||
BinaryOp::Ge => "ge",
|
|
||||||
BinaryOp::Add => "add",
|
|
||||||
BinaryOp::Sub => "sub",
|
|
||||||
BinaryOp::Mul => "mul",
|
|
||||||
BinaryOp::Div => "div",
|
|
||||||
BinaryOp::FloorDiv => "floor_div",
|
|
||||||
BinaryOp::Mod => "mod",
|
|
||||||
BinaryOp::Pow => "pow",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sha256_hex(bytes: &[u8]) -> String {
|
|
||||||
let mut hasher = Sha256::new();
|
|
||||||
hasher.update(bytes);
|
|
||||||
hex::encode(hasher.finalize())
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//! Explicit projector from the canonical Markdown AST to the public document
|
||||||
|
//! shape (spec/markdown-profile.md §5, spec/analysis.md §3.1).
|
||||||
|
//!
|
||||||
|
//! The same projector is used by Analysis and `inspect --ast`; there is no
|
||||||
|
//! second tree and no serde dump of an internal Rust enum.
|
||||||
|
|
||||||
|
use marqdo_markdown::{MdKind, MdNode};
|
||||||
|
use marqdo_span::Span;
|
||||||
|
use serde_json::{json, Map, Value};
|
||||||
|
|
||||||
|
/// Project one document root. The root span is normalised to the whole source
|
||||||
|
/// (including a tolerated BOM); child spans keep their parser coordinates.
|
||||||
|
pub fn document_json(root: &MdNode, source_len: usize) -> Value {
|
||||||
|
node_json(root, Some(Span::new(0, source_len)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node_json(node: &MdNode, span_override: Option<Span>) -> Value {
|
||||||
|
let span = span_override.unwrap_or(node.span);
|
||||||
|
let mut object = Map::new();
|
||||||
|
object.insert("kind".to_string(), json!(node.kind.tag()));
|
||||||
|
object.insert(
|
||||||
|
"span".to_string(),
|
||||||
|
json!({"start": span.start, "end": span.end}),
|
||||||
|
);
|
||||||
|
let children: Vec<Value> = node
|
||||||
|
.children
|
||||||
|
.iter()
|
||||||
|
.map(|child| node_json(child, None))
|
||||||
|
.collect();
|
||||||
|
object.insert("children".to_string(), Value::Array(children));
|
||||||
|
match &node.kind {
|
||||||
|
MdKind::Document
|
||||||
|
| MdKind::BlockQuote
|
||||||
|
| MdKind::Paragraph
|
||||||
|
| MdKind::Strong
|
||||||
|
| MdKind::Emph
|
||||||
|
| MdKind::Strikethrough
|
||||||
|
| MdKind::TableCell
|
||||||
|
| MdKind::ThematicBreak
|
||||||
|
| MdKind::SoftBreak
|
||||||
|
| MdKind::LineBreak => {}
|
||||||
|
MdKind::FrontMatter => {
|
||||||
|
object.insert(
|
||||||
|
"literal".to_string(),
|
||||||
|
Value::String(node.literal.clone().unwrap_or_default()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MdKind::Text | MdKind::MathBlock | MdKind::HtmlBlock | MdKind::HtmlInline => {
|
||||||
|
object.insert(
|
||||||
|
"literal".to_string(),
|
||||||
|
Value::String(node.literal.clone().unwrap_or_default()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MdKind::Code { ticks } => {
|
||||||
|
object.insert("ticks".to_string(), json!(ticks));
|
||||||
|
object.insert(
|
||||||
|
"literal".to_string(),
|
||||||
|
Value::String(node.literal.clone().unwrap_or_default()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MdKind::CodeBlock { fenced, info } => {
|
||||||
|
object.insert("fenced".to_string(), json!(fenced));
|
||||||
|
object.insert("info".to_string(), json!(info));
|
||||||
|
object.insert(
|
||||||
|
"literal".to_string(),
|
||||||
|
Value::String(node.literal.clone().unwrap_or_default()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MdKind::Math { display } => {
|
||||||
|
object.insert("display".to_string(), json!(display));
|
||||||
|
object.insert(
|
||||||
|
"literal".to_string(),
|
||||||
|
Value::String(node.literal.clone().unwrap_or_default()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MdKind::Heading { level, setext } => {
|
||||||
|
object.insert("level".to_string(), json!(level));
|
||||||
|
object.insert("setext".to_string(), json!(setext));
|
||||||
|
}
|
||||||
|
MdKind::List {
|
||||||
|
ordered,
|
||||||
|
start,
|
||||||
|
tight,
|
||||||
|
} => {
|
||||||
|
object.insert("ordered".to_string(), json!(ordered));
|
||||||
|
object.insert("start".to_string(), json!(start));
|
||||||
|
object.insert("tight".to_string(), json!(tight));
|
||||||
|
}
|
||||||
|
MdKind::Item { task } => {
|
||||||
|
object.insert("task".to_string(), json!(task));
|
||||||
|
}
|
||||||
|
MdKind::Link { url, title } | MdKind::Image { url, title } => {
|
||||||
|
object.insert("url".to_string(), json!(url));
|
||||||
|
object.insert("title".to_string(), json!(title));
|
||||||
|
}
|
||||||
|
MdKind::Table { alignments } => {
|
||||||
|
object.insert("alignments".to_string(), json!(alignments));
|
||||||
|
}
|
||||||
|
MdKind::TableRow { header } => {
|
||||||
|
object.insert("header".to_string(), json!(header));
|
||||||
|
}
|
||||||
|
MdKind::FootnoteDefinition { .. } | MdKind::FootnoteReference { .. } => {
|
||||||
|
// The frozen profile disables footnotes; the semantic validator
|
||||||
|
// rejects them if a future parser change ever emits one.
|
||||||
|
object.insert("tag".to_string(), json!(node.kind.tag()));
|
||||||
|
}
|
||||||
|
MdKind::Other { tag } => {
|
||||||
|
object.insert("tag".to_string(), json!(tag));
|
||||||
|
if let Some(literal) = &node.literal {
|
||||||
|
object.insert("literal".to_string(), Value::String(literal.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Object(object)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,340 @@
|
|||||||
|
//! Typed public Analysis DTO (spec/analysis.md).
|
||||||
|
//!
|
||||||
|
//! These types are the boundary model, not a dump of internal IR: every field
|
||||||
|
//! is projected explicitly from the prepared program. The canonical encoder
|
||||||
|
//! serializes this model once; the file writer and the Observation digest use
|
||||||
|
//! the same bytes.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
/// Half-open UTF-8 byte span in the owning module's `source`.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct SpanJson {
|
||||||
|
/// Inclusive byte offset.
|
||||||
|
pub start: usize,
|
||||||
|
/// Exclusive byte offset.
|
||||||
|
pub end: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<marqdo_span::Span> for SpanJson {
|
||||||
|
fn from(span: marqdo_span::Span) -> Self {
|
||||||
|
Self {
|
||||||
|
start: span.start,
|
||||||
|
end: span.end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Root Analysis document.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Analysis {
|
||||||
|
/// `marqdo.analysis`.
|
||||||
|
pub schema: &'static str,
|
||||||
|
/// Current revision.
|
||||||
|
pub schema_version: u32,
|
||||||
|
/// Producer identity.
|
||||||
|
pub producer: Producer,
|
||||||
|
/// Project snapshot and entry context.
|
||||||
|
pub project: Project,
|
||||||
|
/// Loaded modules, sorted by id.
|
||||||
|
pub modules: Vec<ModuleAnalysis>,
|
||||||
|
/// Deterministic diagnostics.
|
||||||
|
pub diagnostics: Vec<DiagnosticRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Producer identity.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Producer {
|
||||||
|
/// Always `marqdo`.
|
||||||
|
pub name: &'static str,
|
||||||
|
/// Product version.
|
||||||
|
pub version: &'static str,
|
||||||
|
/// Markdown profile id.
|
||||||
|
pub markdown_profile: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Project snapshot identity.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Project {
|
||||||
|
/// Logical root id.
|
||||||
|
pub root_id: String,
|
||||||
|
/// `manifest` or `workspace_snapshot`.
|
||||||
|
pub identity_kind: &'static str,
|
||||||
|
/// Module loaded from the CLI entry.
|
||||||
|
pub entry_module_id: String,
|
||||||
|
/// Captured lock digest, empty when no lock exists.
|
||||||
|
pub lock_digest: String,
|
||||||
|
/// Captured manifest digest, empty when no manifest exists.
|
||||||
|
pub manifest_digest: String,
|
||||||
|
/// Verified stdlib identity, if any.
|
||||||
|
pub stdlib: Option<Stdlib>,
|
||||||
|
/// Static extension identities that participated in preparation.
|
||||||
|
pub extensions: Vec<Extension>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verified bundled stdlib identity.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Stdlib {
|
||||||
|
/// Declared version.
|
||||||
|
pub version: String,
|
||||||
|
/// Verified content digest.
|
||||||
|
pub digest: String,
|
||||||
|
/// Package instance id.
|
||||||
|
pub instance_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One static extension identity.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Extension {
|
||||||
|
/// `plugin`, `kernel` or `provider`.
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// Declared package/provider name.
|
||||||
|
pub name: String,
|
||||||
|
/// Declared version.
|
||||||
|
pub version: String,
|
||||||
|
/// Logical owner package instance.
|
||||||
|
pub logical_owner: String,
|
||||||
|
/// Declared activation source, or `--plugin`.
|
||||||
|
pub source: String,
|
||||||
|
/// Manifest digest (`sha256:<hex>`).
|
||||||
|
pub manifest_digest: String,
|
||||||
|
/// Selected artifact digest (`sha256:<hex>`).
|
||||||
|
pub artifact_digest: String,
|
||||||
|
/// Selected host target triple.
|
||||||
|
pub selected_target: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One loaded module.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ModuleAnalysis {
|
||||||
|
/// Canonical module id.
|
||||||
|
pub id: String,
|
||||||
|
/// Package instance.
|
||||||
|
pub package_instance_id: String,
|
||||||
|
/// Package-relative path with `/` separators.
|
||||||
|
pub relative_path: String,
|
||||||
|
/// SHA-256 of the exact source bytes.
|
||||||
|
pub source_digest: String,
|
||||||
|
/// Exact UTF-8 source text.
|
||||||
|
pub source: String,
|
||||||
|
/// Public Markdown AST.
|
||||||
|
pub document: Value,
|
||||||
|
/// Heading units in document order.
|
||||||
|
pub units: Vec<UnitRecord>,
|
||||||
|
/// Anchor map sorted by anchor.
|
||||||
|
pub anchors: Vec<AnchorRecord>,
|
||||||
|
/// Exec H2 functions in document order.
|
||||||
|
pub functions: Vec<FunctionRecord>,
|
||||||
|
/// Explicit imports in document order.
|
||||||
|
pub imports: Vec<ImportRecord>,
|
||||||
|
/// Markdown references in source order.
|
||||||
|
pub references: Vec<ReferenceRecord>,
|
||||||
|
/// Static call bindings in source order.
|
||||||
|
pub calls: Vec<CallRecord>,
|
||||||
|
/// Inert resources in document order.
|
||||||
|
pub resources: Vec<ResourceRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One addressable heading range.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct UnitRecord {
|
||||||
|
/// Canonical unit id.
|
||||||
|
pub id: String,
|
||||||
|
/// Structured canonical path.
|
||||||
|
pub path: Vec<String>,
|
||||||
|
/// Parent unit id, root `null`.
|
||||||
|
pub parent_id: Option<String>,
|
||||||
|
/// `root`, `namespace`, `function`, `knowledge` or `section`.
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// Normalised heading name.
|
||||||
|
pub name: String,
|
||||||
|
/// Heading level, root 0.
|
||||||
|
pub level: u8,
|
||||||
|
/// Effective mode.
|
||||||
|
pub mode: &'static str,
|
||||||
|
/// `default`, `explicit` or `inherited`.
|
||||||
|
pub mode_origin: &'static str,
|
||||||
|
/// Unit that provided the effective mode.
|
||||||
|
pub mode_source_unit_id: String,
|
||||||
|
/// Original heading span, root `null`.
|
||||||
|
pub heading_span: Option<SpanJson>,
|
||||||
|
/// Complete section range.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Owning function id.
|
||||||
|
pub function: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One anchor entry.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct AnchorRecord {
|
||||||
|
/// GitHub-style anchor.
|
||||||
|
pub anchor: String,
|
||||||
|
/// Addressable unit.
|
||||||
|
pub unit_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One Exec H2 function.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct FunctionRecord {
|
||||||
|
/// Canonical function id.
|
||||||
|
pub id: String,
|
||||||
|
/// Addressable unit.
|
||||||
|
pub unit_id: String,
|
||||||
|
/// Local function name.
|
||||||
|
pub local_name: String,
|
||||||
|
/// Enclosing namespace.
|
||||||
|
pub namespace: Option<String>,
|
||||||
|
/// Declaration span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Heading span.
|
||||||
|
pub heading_span: SpanJson,
|
||||||
|
/// Signature.
|
||||||
|
pub signature: SignatureRecord,
|
||||||
|
/// Conservative effects.
|
||||||
|
pub effects: Vec<&'static str>,
|
||||||
|
/// Statements.
|
||||||
|
pub body: Vec<Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Function signature.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct SignatureRecord {
|
||||||
|
/// `explicit` or `inferred`.
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// Parameters.
|
||||||
|
pub params: Vec<ParamRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One function parameter.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ParamRecord {
|
||||||
|
/// Parameter name.
|
||||||
|
pub name: String,
|
||||||
|
/// Whether no default value exists.
|
||||||
|
pub required: bool,
|
||||||
|
/// Declared type annotation.
|
||||||
|
pub r#type: Option<String>,
|
||||||
|
/// Default expression.
|
||||||
|
pub default: Option<Value>,
|
||||||
|
/// Declaration span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One explicit import.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ImportRecord {
|
||||||
|
/// Local alias.
|
||||||
|
pub alias: String,
|
||||||
|
/// Declared target.
|
||||||
|
pub target: String,
|
||||||
|
/// Declaration span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Resolved module id.
|
||||||
|
pub resolved: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One resolved document reference.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ReferenceRecord {
|
||||||
|
/// Source module.
|
||||||
|
pub source: String,
|
||||||
|
/// Innermost owning unit.
|
||||||
|
pub source_unit: String,
|
||||||
|
/// Raw URL.
|
||||||
|
pub url: String,
|
||||||
|
/// Link span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Resolver state.
|
||||||
|
pub state: &'static str,
|
||||||
|
/// `module`, `file` or `null`.
|
||||||
|
pub target_kind: Option<&'static str>,
|
||||||
|
/// Resolved module.
|
||||||
|
pub target_module: Option<String>,
|
||||||
|
/// Resolved unit.
|
||||||
|
pub target_unit: Option<String>,
|
||||||
|
/// Logical candidate package instance.
|
||||||
|
pub candidate_package_instance_id: Option<String>,
|
||||||
|
/// Normalised package-relative candidate.
|
||||||
|
pub candidate_path: Option<String>,
|
||||||
|
/// Decoded fragment.
|
||||||
|
pub fragment: Option<String>,
|
||||||
|
/// Ambiguous exact candidates.
|
||||||
|
pub candidates: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One static call record.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CallRecord {
|
||||||
|
/// Caller function id.
|
||||||
|
pub function: String,
|
||||||
|
/// Call expression span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Callee shape.
|
||||||
|
pub callee: Value,
|
||||||
|
/// Function, builtin, plugin or unresolved.
|
||||||
|
pub state: &'static str,
|
||||||
|
/// Bound target value.
|
||||||
|
pub target: Option<String>,
|
||||||
|
/// `function`, `builtin`, `plugin` or `null`.
|
||||||
|
pub target_kind: Option<&'static str>,
|
||||||
|
/// Static plugin owner, if any.
|
||||||
|
pub target_owner: Option<TargetOwner>,
|
||||||
|
/// `dynamic`, `unbound` or `null`.
|
||||||
|
pub reason: Option<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Static plugin owner of a bound export.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct TargetOwner {
|
||||||
|
/// Always `plugin`.
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// Plugin package.
|
||||||
|
pub package: String,
|
||||||
|
/// Verified artifact digest.
|
||||||
|
pub digest: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One inert resource.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ResourceRecord {
|
||||||
|
/// Module-local ordinal id.
|
||||||
|
pub id: String,
|
||||||
|
/// Owning module.
|
||||||
|
pub module_id: String,
|
||||||
|
/// Innermost owning unit.
|
||||||
|
pub unit_id: String,
|
||||||
|
/// `formula` or `code`.
|
||||||
|
pub kind: &'static str,
|
||||||
|
/// AST node span.
|
||||||
|
pub span: SpanJson,
|
||||||
|
/// Payload digest.
|
||||||
|
pub content_digest: String,
|
||||||
|
/// Code fence language.
|
||||||
|
pub language: Option<String>,
|
||||||
|
/// Formula display mode (`null` for code).
|
||||||
|
pub display: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One diagnostic.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct DiagnosticRecord {
|
||||||
|
/// Owning module.
|
||||||
|
pub module: String,
|
||||||
|
/// Package-relative path.
|
||||||
|
pub relative_path: String,
|
||||||
|
/// Primary span.
|
||||||
|
pub span: Option<SpanJson>,
|
||||||
|
/// 1-based line.
|
||||||
|
pub line: Option<usize>,
|
||||||
|
/// 1-based column.
|
||||||
|
pub column: Option<usize>,
|
||||||
|
/// `error` or `warning`.
|
||||||
|
pub severity: &'static str,
|
||||||
|
/// Stable code.
|
||||||
|
pub code: String,
|
||||||
|
/// Message.
|
||||||
|
pub message: String,
|
||||||
|
/// Hints.
|
||||||
|
pub hints: Vec<String>,
|
||||||
|
}
|
||||||
+6
-125
@@ -3,7 +3,8 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use marqdo_host::{Host, StdHost};
|
use marqdo_host::StdHost;
|
||||||
|
use marqdo_host_contract::Host;
|
||||||
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
|
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
|
||||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome};
|
use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome};
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
@@ -64,38 +65,6 @@ pub(super) fn prepare_project(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `marqdo check`.
|
|
||||||
fn validate_refs(project: &LoadedProject) -> Vec<FileDiagnostic> {
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
for file in project.files.values() {
|
|
||||||
let parent = file.path.parent().unwrap_or_else(|| Path::new("."));
|
|
||||||
let mut unresolved: Vec<marqdo_span::Span> = Vec::new();
|
|
||||||
file.analysis.document.root.walk(&mut |node| {
|
|
||||||
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let (resolved, _, _) = resolve_link(project, &file.analysis.units, parent, url);
|
|
||||||
if !resolved {
|
|
||||||
unresolved.push(node.span);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
for span in unresolved {
|
|
||||||
diagnostics.push(FileDiagnostic {
|
|
||||||
module_id: file.module_id.clone(),
|
|
||||||
path: file.path.clone(),
|
|
||||||
source: file.source.clone(),
|
|
||||||
diagnostic: marqdo_value::Diagnostic::error(
|
|
||||||
marqdo_value::codes::REF_UNRESOLVED,
|
|
||||||
Some(span),
|
|
||||||
"reference target could not be resolved",
|
|
||||||
)
|
|
||||||
.with_hint("fix the link target or add the missing heading/file"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
diagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
fn summary_json(project: &LoadedProject) -> serde_json::Value {
|
fn summary_json(project: &LoadedProject) -> serde_json::Value {
|
||||||
let entry = project.entry_file();
|
let entry = project.entry_file();
|
||||||
json!({
|
json!({
|
||||||
@@ -130,94 +99,6 @@ fn signatures_json(module: &marqdo_ir::Module) -> serde_json::Value {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refs_json(project: &LoadedProject) -> serde_json::Value {
|
|
||||||
let entry = project.entry_file();
|
|
||||||
let parent = entry.path.parent().unwrap_or_else(|| Path::new("."));
|
|
||||||
let mut edges = Vec::new();
|
|
||||||
entry.analysis.document.root.walk(&mut |node| {
|
|
||||||
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let (resolved, target_module, target_unit) =
|
|
||||||
resolve_link(project, &entry.analysis.units, parent, url);
|
|
||||||
edges.push(json!({
|
|
||||||
"source": entry.module_id.to_string(),
|
|
||||||
"url": url,
|
|
||||||
"span": node.span,
|
|
||||||
"resolved": resolved,
|
|
||||||
"target_module": target_module,
|
|
||||||
"target_unit": target_unit,
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
serde_json::Value::Array(edges)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_link(
|
|
||||||
project: &LoadedProject,
|
|
||||||
units: &marqdo_frontend::UnitIndex,
|
|
||||||
parent: &Path,
|
|
||||||
url: &str,
|
|
||||||
) -> (bool, Option<String>, Option<String>) {
|
|
||||||
if let Some(fragment) = url.strip_prefix('#') {
|
|
||||||
let unit = units.anchors.get(fragment).or_else(|| {
|
|
||||||
units
|
|
||||||
.units
|
|
||||||
.iter()
|
|
||||||
.find(|unit| unit.name == fragment)
|
|
||||||
.map(|unit| &unit.id)
|
|
||||||
});
|
|
||||||
return match unit {
|
|
||||||
Some(unit) => (
|
|
||||||
true,
|
|
||||||
Some(project.entry.to_string()),
|
|
||||||
Some(unit.to_string()),
|
|
||||||
),
|
|
||||||
None => (false, None, None),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if url.starts_with("http://") || url.starts_with("https://") {
|
|
||||||
return (true, None, None);
|
|
||||||
}
|
|
||||||
let (path_part, fragment) = match url.split_once('#') {
|
|
||||||
Some((path, fragment)) => (path, Some(fragment)),
|
|
||||||
None => (url, None),
|
|
||||||
};
|
|
||||||
let candidate = parent.join(path_part);
|
|
||||||
let Ok(candidate) = candidate.canonicalize() else {
|
|
||||||
return (false, None, None);
|
|
||||||
};
|
|
||||||
let Some(module_id) = project.module_id_for_path(&candidate) else {
|
|
||||||
return (false, None, None);
|
|
||||||
};
|
|
||||||
let analyzed;
|
|
||||||
let target_units = match project.files.get(&module_id) {
|
|
||||||
Some(target_file) => &target_file.analysis.units,
|
|
||||||
None => {
|
|
||||||
// Links may reference documents that are not imported. Analyse the
|
|
||||||
// target statically for reference checking; nothing executes.
|
|
||||||
let Ok(source) = std::fs::read_to_string(&candidate) else {
|
|
||||||
return (false, None, None);
|
|
||||||
};
|
|
||||||
analyzed = marqdo_frontend::analyze_source(&module_id.to_string(), &source);
|
|
||||||
&analyzed.units
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let Some(fragment) = fragment else {
|
|
||||||
return (true, Some(module_id.to_string()), None);
|
|
||||||
};
|
|
||||||
let resolved = target_units.anchors.get(fragment).or_else(|| {
|
|
||||||
target_units
|
|
||||||
.units
|
|
||||||
.iter()
|
|
||||||
.find(|unit| unit.name == fragment)
|
|
||||||
.map(|unit| &unit.id)
|
|
||||||
});
|
|
||||||
match resolved {
|
|
||||||
Some(unit) => (true, Some(module_id.to_string()), Some(unit.to_string())),
|
|
||||||
None => (false, Some(module_id.to_string()), None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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 {
|
||||||
@@ -390,12 +271,12 @@ fn load_plugin_into_host(
|
|||||||
.parent()
|
.parent()
|
||||||
.map(|parent| parent.to_path_buf())
|
.map(|parent| parent.to_path_buf())
|
||||||
.unwrap_or_else(|| PathBuf::from("."));
|
.unwrap_or_else(|| PathBuf::from("."));
|
||||||
let manifest = marqdo_plugin_abi::PluginManifest::load(&manifest_path)
|
let manifest = marqdo_host::plugin::PluginManifest::load(&manifest_path)
|
||||||
.map_err(|error| format!("{}: {}", error.code, error.message))?;
|
.map_err(|error| format!("{}: {}", error.code, error.message))?;
|
||||||
manifest
|
manifest
|
||||||
.validate()
|
.validate()
|
||||||
.map_err(|error| format!("{}: {}", error.code, error.message))?;
|
.map_err(|error| format!("{}: {}", error.code, error.message))?;
|
||||||
if manifest.plugin.kind == marqdo_plugin_abi::PluginKind::Native && !trusted {
|
if manifest.plugin.kind == marqdo_host::plugin::PluginKind::Native && !trusted {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation",
|
"loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation",
|
||||||
manifest.plugin.name
|
manifest.plugin.name
|
||||||
@@ -418,7 +299,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -444,7 +326,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,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,22 +11,50 @@ 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 bind `run` to a previous Analysis after the project
|
||||||
|
// stopped loading. The input document is never the cleanup target.
|
||||||
|
if let Some(path) = emit {
|
||||||
|
if let Err(error) = crate::analysis::discard_without_prepare(file, path) {
|
||||||
|
eprintln!("error: {error}");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let mut project = prepared.loaded;
|
let mut prepared = prepared;
|
||||||
if refs {
|
if refs {
|
||||||
let ref_diagnostics = validate_refs(&project);
|
let report = crate::document_refs::references_for_project(
|
||||||
project.diagnostics.extend(ref_diagnostics);
|
&prepared.loaded,
|
||||||
|
crate::document_refs::ReferenceMode::VerifyLocal,
|
||||||
|
);
|
||||||
|
for issue in report.issues {
|
||||||
|
let Some(file) = prepared.loaded.files.get(&issue.module) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
prepared.loaded.diagnostics.push(FileDiagnostic {
|
||||||
|
module_id: issue.module,
|
||||||
|
path: file.path.clone(),
|
||||||
|
source: file.source.clone(),
|
||||||
|
diagnostic: issue.diagnostic,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let errors = output::error_count(&project.diagnostics);
|
let errors = output::error_count(&prepared.loaded.diagnostics);
|
||||||
if let Some(path) = emit {
|
if let Some(path) = emit {
|
||||||
if errors > 0 {
|
if errors > 0 {
|
||||||
let _ = std::fs::remove_file(path);
|
if let Err(error) = crate::analysis::discard(&prepared, path) {
|
||||||
} else if let Err(error) = crate::analysis::write(&project, path) {
|
eprintln!("error: {error}");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
} else if let Err(error) = crate::analysis::write(&prepared, path) {
|
||||||
eprintln!("error: {error}");
|
eprintln!("error: {error}");
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let project = &prepared.loaded;
|
||||||
if json {
|
if json {
|
||||||
output::print_json(&json!({
|
output::print_json(&json!({
|
||||||
"command": "check",
|
"command": "check",
|
||||||
|
|||||||
@@ -46,13 +46,20 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
|
|||||||
if flags.ast {
|
if flags.ast {
|
||||||
object.insert(
|
object.insert(
|
||||||
"ast".into(),
|
"ast".into(),
|
||||||
serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(),
|
crate::analysis::document_projection(
|
||||||
|
&entry.analysis.document.root,
|
||||||
|
entry.source.len(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.units {
|
if flags.units {
|
||||||
object.insert(
|
object.insert(
|
||||||
"units".into(),
|
"units".into(),
|
||||||
serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(),
|
serde_json::to_value(crate::analysis::units_projection(
|
||||||
|
&entry.analysis.units,
|
||||||
|
entry.source.len(),
|
||||||
|
))
|
||||||
|
.unwrap_or_default(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.signature {
|
if flags.signature {
|
||||||
@@ -65,7 +72,9 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.refs {
|
if flags.refs {
|
||||||
object.insert("refs".into(), json!(refs_json(project)));
|
let (references, issues) = refs_json(&prepared, &entry.module_id);
|
||||||
|
object.insert("refs".into(), references);
|
||||||
|
object.insert("reference_issues".into(), issues);
|
||||||
}
|
}
|
||||||
if flags.platform {
|
if flags.platform {
|
||||||
object.insert(
|
object.insert(
|
||||||
@@ -106,13 +115,21 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
|
|||||||
if flags.ast {
|
if flags.ast {
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default()
|
serde_json::to_string_pretty(&crate::analysis::document_projection(
|
||||||
|
&entry.analysis.document.root,
|
||||||
|
entry.source.len()
|
||||||
|
))
|
||||||
|
.unwrap_or_default()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.units {
|
if flags.units {
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default()
|
serde_json::to_string_pretty(&crate::analysis::units_projection(
|
||||||
|
&entry.analysis.units,
|
||||||
|
entry.source.len()
|
||||||
|
))
|
||||||
|
.unwrap_or_default()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.signature {
|
if flags.signature {
|
||||||
@@ -128,9 +145,14 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.refs {
|
if flags.refs {
|
||||||
|
let (references, issues) = refs_json(&prepared, &entry.module_id);
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
serde_json::to_string_pretty(&refs_json(project)).unwrap_or_default()
|
serde_json::to_string_pretty(&json!({
|
||||||
|
"refs": references,
|
||||||
|
"reference_issues": issues,
|
||||||
|
}))
|
||||||
|
.unwrap_or_default()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if flags.platform {
|
if flags.platform {
|
||||||
@@ -149,6 +171,41 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
|
|||||||
0
|
0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolve the entry module's links through the one document resolver and the
|
||||||
|
/// explicit `--refs` catalog. `inspect` never executes a target.
|
||||||
|
fn refs_json(
|
||||||
|
prepared: &crate::project_prepare::PreparedProgram,
|
||||||
|
entry: &marqdo_ir::ModuleId,
|
||||||
|
) -> (serde_json::Value, serde_json::Value) {
|
||||||
|
let report = crate::document_refs::references_for_project(
|
||||||
|
&prepared.loaded,
|
||||||
|
crate::document_refs::ReferenceMode::VerifyLocal,
|
||||||
|
);
|
||||||
|
let references: Vec<crate::analysis::ReferenceRecord> = report
|
||||||
|
.by_module
|
||||||
|
.get(entry)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(crate::analysis::reference_projection)
|
||||||
|
.collect();
|
||||||
|
let references = serde_json::to_value(references).unwrap_or_default();
|
||||||
|
let issues = report
|
||||||
|
.issues
|
||||||
|
.iter()
|
||||||
|
.filter(|issue| &issue.module == entry)
|
||||||
|
.map(|issue| {
|
||||||
|
json!({
|
||||||
|
"code": issue.diagnostic.code,
|
||||||
|
"severity": if issue.diagnostic.is_error() { "error" } else { "warning" },
|
||||||
|
"span": issue.diagnostic.span.map(|span| json!({"start": span.start, "end": span.end})),
|
||||||
|
"message": issue.diagnostic.message,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
(references, serde_json::Value::Array(issues))
|
||||||
|
}
|
||||||
|
|
||||||
/// Static extension identity projection for `inspect --extensions`.
|
/// Static extension identity projection for `inspect --extensions`.
|
||||||
///
|
///
|
||||||
/// Reports declared sources, lock identity, static plugin descriptors and
|
/// Reports declared sources, lock identity, static plugin descriptors and
|
||||||
|
|||||||
@@ -21,16 +21,25 @@ pub fn execute(
|
|||||||
);
|
);
|
||||||
return 2;
|
return 2;
|
||||||
}
|
}
|
||||||
|
// Strict runs project code under the isolation supervisor, which owns
|
||||||
|
// stdout. A live JSONL stream or a file destination would bypass that
|
||||||
|
// supervisor, so reject the destination before any session is opened: an
|
||||||
|
// unsupported destination must never produce a partial stream.
|
||||||
|
if settings.mode == "strict"
|
||||||
|
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some())
|
||||||
|
{
|
||||||
|
return fail(
|
||||||
|
None,
|
||||||
|
"strict",
|
||||||
|
"strict.unsupported_grant",
|
||||||
|
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
}
|
||||||
// Open before preparation so option, compile and authorization failures
|
// Open before preparation so option, compile and authorization failures
|
||||||
// can still publish a rejection on the requested observation destination.
|
// can still publish a rejection on the requested observation destination.
|
||||||
let strict_destination_rejected = settings.mode == "strict"
|
let events = if observation.enabled() {
|
||||||
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some());
|
match ObservationSession::open(observation) {
|
||||||
let mut destinations = observation.clone();
|
|
||||||
if strict_destination_rejected {
|
|
||||||
destinations.file = None;
|
|
||||||
}
|
|
||||||
let events = if destinations.enabled() {
|
|
||||||
match ObservationSession::open(&destinations) {
|
|
||||||
Ok(events) => Some(events),
|
Ok(events) => Some(events),
|
||||||
Err(error) => return transport_failure(&error),
|
Err(error) => return transport_failure(&error),
|
||||||
}
|
}
|
||||||
@@ -38,18 +47,9 @@ pub fn execute(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
let stream = events.as_ref();
|
let stream = events.as_ref();
|
||||||
if strict_destination_rejected {
|
|
||||||
return fail(
|
|
||||||
stream,
|
|
||||||
"strict",
|
|
||||||
"strict.unsupported_grant",
|
|
||||||
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
|
|
||||||
2,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let named_args = match named_args {
|
let named_args = match named_args {
|
||||||
Ok(args) => args,
|
Ok(args) => args,
|
||||||
Err(message) => return fail(stream, "prepare", "cli.invalid_argument", &message, 2),
|
Err(message) => return fail(stream, "options", "cli.invalid_argument", &message, 2),
|
||||||
};
|
};
|
||||||
let options = PrepareOptions {
|
let options = PrepareOptions {
|
||||||
plugins: settings.plugins.clone(),
|
plugins: settings.plugins.clone(),
|
||||||
@@ -58,12 +58,10 @@ pub fn execute(
|
|||||||
Ok(prepared) => prepared,
|
Ok(prepared) => prepared,
|
||||||
Err(error) => return fail_prepare(stream, "prepare", &error),
|
Err(error) => return fail_prepare(stream, "prepare", &error),
|
||||||
};
|
};
|
||||||
let extension_sources = prepared.loaded.extension_sources.clone();
|
if prepared.loaded.has_errors() {
|
||||||
let project = prepared.loaded;
|
|
||||||
let static_plugins = prepared.plugins;
|
|
||||||
if project.has_errors() {
|
|
||||||
if let Some(stream) = stream {
|
if let Some(stream) = stream {
|
||||||
let code = project
|
let code = prepared
|
||||||
|
.loaded
|
||||||
.diagnostics
|
.diagnostics
|
||||||
.iter()
|
.iter()
|
||||||
.find(|item| item.diagnostic.is_error())
|
.find(|item| item.diagnostic.is_error())
|
||||||
@@ -77,10 +75,24 @@ pub fn execute(
|
|||||||
return transport_failure(&error);
|
return transport_failure(&error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eprint!("{}", output::render_text(&project.diagnostics));
|
eprint!("{}", output::render_text(&prepared.loaded.diagnostics));
|
||||||
eprintln!("error: refusing to run a project with compile errors");
|
eprintln!("error: refusing to run a project with compile errors");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
// Bind the Observation snapshot to the exact bytes of the ordinary
|
||||||
|
// Analysis for these static options. Build it before moving the prepared
|
||||||
|
// program apart, but only when an observation destination is requested.
|
||||||
|
let analysis_digest = if stream.is_some() {
|
||||||
|
match crate::analysis::digest(&prepared) {
|
||||||
|
Ok(digest) => Some(digest),
|
||||||
|
Err(error) => return fail(stream, "prepare", "cli.analysis_failed", &error, 1),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let extension_sources = prepared.loaded.extension_sources.clone();
|
||||||
|
let project = prepared.loaded;
|
||||||
|
let static_plugins = prepared.plugins;
|
||||||
let warnings: Vec<FileDiagnostic> = project
|
let warnings: Vec<FileDiagnostic> = project
|
||||||
.diagnostics
|
.diagnostics
|
||||||
.iter()
|
.iter()
|
||||||
@@ -262,7 +274,7 @@ pub fn execute(
|
|||||||
&& static_plugins
|
&& static_plugins
|
||||||
.plugins
|
.plugins
|
||||||
.iter()
|
.iter()
|
||||||
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native)
|
.any(|plugin| plugin.kind == marqdo_host::plugin::PluginKind::Native)
|
||||||
{
|
{
|
||||||
return fail(
|
return fail(
|
||||||
stream,
|
stream,
|
||||||
@@ -342,15 +354,12 @@ 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 = match crate::analysis::digest(&project) {
|
let analysis_digest = analysis_digest.as_deref().unwrap_or_default();
|
||||||
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(),
|
||||||
&project.identity.root_id(),
|
&project.identity.root_id(),
|
||||||
&analysis_digest,
|
analysis_digest,
|
||||||
) {
|
) {
|
||||||
return transport_failure(&error);
|
return transport_failure(&error);
|
||||||
}
|
}
|
||||||
@@ -549,9 +558,9 @@ mod tests {
|
|||||||
base_dir: PathBuf::from("/fixtures/demo"),
|
base_dir: PathBuf::from("/fixtures/demo"),
|
||||||
package: "demo.ext".into(),
|
package: "demo.ext".into(),
|
||||||
version: "0.1.0".into(),
|
version: "0.1.0".into(),
|
||||||
kind: marqdo_plugin_abi::PluginKind::Worker,
|
kind: marqdo_host::plugin::PluginKind::Worker,
|
||||||
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
|
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
|
||||||
artifact_target: marqdo_plugin_abi::HostTarget::current()
|
artifact_target: marqdo_host::plugin::HostTarget::current()
|
||||||
.triple()
|
.triple()
|
||||||
.to_string(),
|
.to_string(),
|
||||||
artifact_sha256: "a".repeat(64),
|
artifact_sha256: "a".repeat(64),
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
|
|||||||
.parent()
|
.parent()
|
||||||
.map(|parent| parent.to_path_buf())
|
.map(|parent| parent.to_path_buf())
|
||||||
.unwrap_or_else(|| PathBuf::from("."));
|
.unwrap_or_else(|| PathBuf::from("."));
|
||||||
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
|
let manifest = match marqdo_host::plugin::PluginManifest::load(&manifest_path) {
|
||||||
Ok(manifest) => manifest,
|
Ok(manifest) => manifest,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
report_plugin_error(&error, json);
|
report_plugin_error(&error, json);
|
||||||
@@ -55,7 +55,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
|
|||||||
report_plugin_error(&error, json);
|
report_plugin_error(&error, json);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
let host_target = marqdo_plugin_abi::HostTarget::current();
|
let host_target = marqdo_host::plugin::HostTarget::current();
|
||||||
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
|
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
|
||||||
Ok((path, artifact)) => {
|
Ok((path, artifact)) => {
|
||||||
let abi = match manifest.abi_requirement() {
|
let abi = match manifest.abi_requirement() {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -10,9 +10,9 @@
|
|||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::path::{Component, Path, PathBuf};
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
|
||||||
|
use marqdo_host::plugin::{HostTarget, PluginKind, PluginManifest};
|
||||||
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
|
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
|
||||||
use marqdo_ir::SignatureKind;
|
use marqdo_ir::SignatureKind;
|
||||||
use marqdo_plugin_abi::{HostTarget, PluginKind, PluginManifest};
|
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
|||||||
@@ -81,12 +81,12 @@ fn plugin_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let manifest = marqdo_plugin_abi::PluginManifest::load(&extension.path)
|
let manifest = marqdo_host::plugin::PluginManifest::load(&extension.path)
|
||||||
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
|
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
|
||||||
manifest
|
manifest
|
||||||
.validate()
|
.validate()
|
||||||
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
|
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
|
||||||
let host = marqdo_plugin_abi::HostTarget::current();
|
let host = marqdo_host::plugin::HostTarget::current();
|
||||||
let artifact = manifest
|
let artifact = manifest
|
||||||
.resolve_artifact(&host)
|
.resolve_artifact(&host)
|
||||||
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
|
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
|
||||||
@@ -161,7 +161,7 @@ fn provider_identity(extension: &ResolvedExtension) -> Result<LockedExtension, P
|
|||||||
format!("`{}` has no version", extension.path.display()),
|
format!("`{}` has no version", extension.path.display()),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let target = marqdo_plugin_abi::HostTarget::current()
|
let target = marqdo_host::plugin::HostTarget::current()
|
||||||
.triple()
|
.triple()
|
||||||
.to_string();
|
.to_string();
|
||||||
let artifacts = manifest
|
let artifacts = manifest
|
||||||
@@ -293,7 +293,7 @@ fn kernel_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
|
|||||||
version: format!("wire:{wire_version}"),
|
version: format!("wire:{wire_version}"),
|
||||||
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
|
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
|
||||||
artifact_digest: digest.to_ascii_lowercase(),
|
artifact_digest: digest.to_ascii_lowercase(),
|
||||||
selected_target: marqdo_plugin_abi::HostTarget::current()
|
selected_target: marqdo_host::plugin::HostTarget::current()
|
||||||
.triple()
|
.triple()
|
||||||
.to_string(),
|
.to_string(),
|
||||||
source: extension.from.clone(),
|
source: extension.from.clone(),
|
||||||
|
|||||||
+81
-31
@@ -119,6 +119,14 @@ fn source_digest(source: &str) -> String {
|
|||||||
hex::encode(hasher.finalize())
|
hex::encode(hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `sha256:<hex>` of exact bytes, the wire form used by Analysis snapshots.
|
||||||
|
fn bytes_digest(bytes: &[u8]) -> String {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(bytes);
|
||||||
|
format!("sha256:{}", hex::encode(hasher.finalize()))
|
||||||
|
}
|
||||||
|
|
||||||
/// A resolved source location inside a loaded file.
|
/// A resolved source location inside a loaded file.
|
||||||
pub struct LocatedSource<'a> {
|
pub struct LocatedSource<'a> {
|
||||||
/// The owning file.
|
/// The owning file.
|
||||||
@@ -167,6 +175,13 @@ pub struct LoadedProject {
|
|||||||
pub manifest: Option<Manifest>,
|
pub manifest: Option<Manifest>,
|
||||||
/// Verified lock file, when present (lock v4).
|
/// Verified lock file, when present (lock v4).
|
||||||
pub lock: Option<LockFile>,
|
pub lock: Option<LockFile>,
|
||||||
|
/// SHA-256 of the exact `marqdo.lock` bytes captured while loading, or an
|
||||||
|
/// empty string when the project has no lock. Analysis must never re-read
|
||||||
|
/// the file: a later edit cannot change the snapshot the program used.
|
||||||
|
pub lock_digest: String,
|
||||||
|
/// SHA-256 of the exact `marqdo.yaml` bytes captured while loading, or an
|
||||||
|
/// empty string when there is no manifest.
|
||||||
|
pub manifest_digest: String,
|
||||||
/// Resolved `marqdo.yaml.extensions` activation sources (static paths only).
|
/// Resolved `marqdo.yaml.extensions` activation sources (static paths only).
|
||||||
pub extension_sources: Vec<marqdo_package::ResolvedExtension>,
|
pub extension_sources: Vec<marqdo_package::ResolvedExtension>,
|
||||||
}
|
}
|
||||||
@@ -201,29 +216,6 @@ impl LoadedProject {
|
|||||||
column: position.column,
|
column: position.column,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve a physical path to its loaded or statically addressable module.
|
|
||||||
pub fn module_id_for_path(&self, path: &Path) -> Option<ModuleId> {
|
|
||||||
let canonical = path.canonicalize().ok()?;
|
|
||||||
let mut best: Option<(&String, &PathBuf)> = None;
|
|
||||||
for (instance, root) in &self.packages {
|
|
||||||
if canonical.starts_with(root)
|
|
||||||
&& best
|
|
||||||
.as_ref()
|
|
||||||
.map(|(_, current)| root.components().count() > current.components().count())
|
|
||||||
.unwrap_or(true)
|
|
||||||
{
|
|
||||||
best = Some((instance, root));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let (instance, root) = best?;
|
|
||||||
let relative = canonical.strip_prefix(root).ok()?;
|
|
||||||
let mut parts = Vec::new();
|
|
||||||
for component in relative.components() {
|
|
||||||
parts.push(component.as_os_str().to_string_lossy().to_string());
|
|
||||||
}
|
|
||||||
Some(ModuleId::new(instance.clone(), parts.join("/")))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Loader {
|
struct Loader {
|
||||||
@@ -251,19 +243,32 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
|
|||||||
.map(|parent| parent.to_path_buf())
|
.map(|parent| parent.to_path_buf())
|
||||||
.unwrap_or_else(|| PathBuf::from(".")),
|
.unwrap_or_else(|| PathBuf::from(".")),
|
||||||
};
|
};
|
||||||
let manifest = if root.join(MANIFEST_FILE).is_file() {
|
// Read each snapshot input exactly once. The digest recorded in Analysis
|
||||||
Some(Manifest::load(&root.join(MANIFEST_FILE))?)
|
// is computed from these bytes, not from a second read after preparation.
|
||||||
|
let manifest_path = root.join(MANIFEST_FILE);
|
||||||
|
let (manifest, manifest_digest) = if manifest_path.is_file() {
|
||||||
|
let bytes = std::fs::read(&manifest_path)
|
||||||
|
.map_err(|error| format!("cannot read {MANIFEST_FILE}: {error}"))?;
|
||||||
|
let yaml = String::from_utf8(bytes.clone())
|
||||||
|
.map_err(|error| format!("{MANIFEST_FILE} is not valid UTF-8: {error}"))?;
|
||||||
|
let manifest =
|
||||||
|
Manifest::from_yaml(&yaml).map_err(|error| format!("{MANIFEST_FILE}: {error}"))?;
|
||||||
|
(Some(manifest), bytes_digest(&bytes))
|
||||||
} else {
|
} else {
|
||||||
None
|
(None, String::new())
|
||||||
};
|
};
|
||||||
let lock = if root.join(LOCK_FILE).is_file() {
|
let lock_path = root.join(LOCK_FILE);
|
||||||
let lock = LockFile::load(&root.join(LOCK_FILE))
|
let (lock, lock_digest) = if lock_path.is_file() {
|
||||||
.map_err(|error| format!("{LOCK_FILE}: {error}"))?;
|
let bytes = std::fs::read(&lock_path)
|
||||||
|
.map_err(|error| format!("cannot read {LOCK_FILE}: {error}"))?;
|
||||||
|
let yaml = String::from_utf8(bytes.clone())
|
||||||
|
.map_err(|error| format!("{LOCK_FILE} is not valid UTF-8: {error}"))?;
|
||||||
|
let lock = LockFile::from_yaml(&yaml).map_err(|error| format!("{LOCK_FILE}: {error}"))?;
|
||||||
if let Some(manifest) = &manifest {
|
if let Some(manifest) = &manifest {
|
||||||
lock.validate_root(manifest)
|
lock.validate_root(manifest)
|
||||||
.map_err(|error| format!("{LOCK_FILE}: {error}"))?;
|
.map_err(|error| format!("{LOCK_FILE}: {error}"))?;
|
||||||
}
|
}
|
||||||
Some(lock)
|
(Some(lock), bytes_digest(&bytes))
|
||||||
} else {
|
} else {
|
||||||
if manifest
|
if manifest
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -275,7 +280,7 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
|
|||||||
.to_string(),
|
.to_string(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
None
|
(None, String::new())
|
||||||
};
|
};
|
||||||
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone());
|
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone());
|
||||||
let entry_module = resolver.resolve_entry(&entry)?;
|
let entry_module = resolver.resolve_entry(&entry)?;
|
||||||
@@ -326,6 +331,8 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
|
|||||||
official_aliases,
|
official_aliases,
|
||||||
manifest,
|
manifest,
|
||||||
lock,
|
lock,
|
||||||
|
lock_digest,
|
||||||
|
manifest_digest,
|
||||||
extension_sources,
|
extension_sources,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -683,3 +690,46 @@ fn collect_identifiers_expr(expr: &Expr, names: &mut std::collections::BTreeSet<
|
|||||||
Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {}
|
Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
fn temp_project(files: &[(&str, &str)]) -> PathBuf {
|
||||||
|
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let root =
|
||||||
|
std::env::temp_dir().join(format!("marqdo-loader-test-{}-{id}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
for (name, source) in files {
|
||||||
|
std::fs::write(root.join(name), source).unwrap();
|
||||||
|
}
|
||||||
|
root
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn project_snapshot_digests_are_captured_once() {
|
||||||
|
let root = temp_project(&[
|
||||||
|
("marqdo.yaml", "project:\n name: snap\n version: 0.1.0\n"),
|
||||||
|
("index.mq.md", "## @exec main\n\n`return 1`\n"),
|
||||||
|
]);
|
||||||
|
let entry = root.join("index.mq.md");
|
||||||
|
let project = load(&entry).expect("load project");
|
||||||
|
let manifest_bytes = std::fs::read(root.join("marqdo.yaml")).unwrap();
|
||||||
|
assert_eq!(project.manifest_digest, bytes_digest(&manifest_bytes));
|
||||||
|
assert!(project.lock_digest.is_empty());
|
||||||
|
|
||||||
|
// The snapshot is what the program used; editing the manifest after
|
||||||
|
// loading cannot change the recorded digest.
|
||||||
|
std::fs::write(
|
||||||
|
root.join("marqdo.yaml"),
|
||||||
|
"project:\n name: snap\n version: 0.2.0\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(project.manifest_digest, bytes_digest(&manifest_bytes));
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
mod analysis;
|
mod analysis;
|
||||||
mod args;
|
mod args;
|
||||||
mod commands;
|
mod commands;
|
||||||
|
mod document_refs;
|
||||||
mod extension_descriptors;
|
mod extension_descriptors;
|
||||||
mod extension_selection;
|
mod extension_selection;
|
||||||
mod loader;
|
mod loader;
|
||||||
@@ -499,7 +500,7 @@ fn dispatch() -> i32 {
|
|||||||
},
|
},
|
||||||
Command::External(args) => tool::dispatch(&args),
|
Command::External(args) => tool::dispatch(&args),
|
||||||
Command::PluginWorker(args) => {
|
Command::PluginWorker(args) => {
|
||||||
marqdo_plugin_abi::worker::serve(&args.manifest, &args.base_dir)
|
marqdo_host::plugin::worker::serve(&args.manifest, &args.base_dir)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ use std::rc::Rc;
|
|||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use marqdo_host::{
|
use marqdo_host::{
|
||||||
FrameId, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
|
ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ValueState,
|
||||||
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES,
|
||||||
DEFAULT_MAX_VALUE_BYTES,
|
|
||||||
};
|
};
|
||||||
|
use marqdo_host_contract::{FrameId, ParameterSource};
|
||||||
use marqdo_value::Value;
|
use marqdo_value::Value;
|
||||||
use serde_json::{json, Value as Json};
|
use serde_json::{json, Value as Json};
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,8 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use marqdo_host::plugin::{HostTarget, TargetTriple};
|
||||||
use marqdo_host::StdHost;
|
use marqdo_host::StdHost;
|
||||||
use marqdo_plugin_abi::{HostTarget, TargetTriple};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
@@ -577,7 +577,7 @@ fn is_lowercase_sha256(value: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn is_known_capability(name: &str) -> bool {
|
fn is_known_capability(name: &str) -> bool {
|
||||||
marqdo_plugin_abi::KNOWN_CAPABILITIES.contains(&name)
|
marqdo_host::plugin::KNOWN_CAPABILITIES.contains(&name)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A dotted vendor capability proposal (validation only, never a grant).
|
/// A dotted vendor capability proposal (validation only, never a grant).
|
||||||
|
|||||||
@@ -0,0 +1,591 @@
|
|||||||
|
//! Public Analysis boundary tests (issue #10, ADR-0069).
|
||||||
|
//!
|
||||||
|
//! These drive the real CLI binary: exact source/AST/scope projection, explicit
|
||||||
|
//! reference states, output safety, Observation digest binding, independent
|
||||||
|
//! consumers and schema/semantic mutation rejection.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Output};
|
||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
struct TempDir(PathBuf);
|
||||||
|
|
||||||
|
impl TempDir {
|
||||||
|
fn new(tag: &str) -> Self {
|
||||||
|
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"marqdo-analysis-boundary-{}-{id}-{tag}",
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&path);
|
||||||
|
std::fs::create_dir_all(&path).unwrap();
|
||||||
|
Self(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self) -> &Path {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, name: &str, source: &str) -> PathBuf {
|
||||||
|
let path = self.0.join(name);
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
std::fs::create_dir_all(parent).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(&path, source).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(&self, name: &str) -> String {
|
||||||
|
std::fs::read_to_string(self.0.join(name)).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TempDir {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn binary() -> &'static str {
|
||||||
|
env!("CARGO_BIN_EXE_marqdo")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cli(dir: &Path, args: &[&str]) -> Output {
|
||||||
|
Command::new(binary())
|
||||||
|
.args(args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(dir: &Path, entry: &str, output: &str, extra: &[&str]) -> Output {
|
||||||
|
let mut args = vec!["check", entry, "--emit", output];
|
||||||
|
args.extend_from_slice(extra);
|
||||||
|
cli(dir, &args)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn analysis(dir: &Path, name: &str) -> serde_json::Value {
|
||||||
|
serde_json::from_slice(&std::fs::read(dir.join(name)).unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn digest(bytes: &[u8]) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(bytes);
|
||||||
|
hex::encode(hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repo_root() -> PathBuf {
|
||||||
|
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.to_path_buf()
|
||||||
|
}
|
||||||
|
|
||||||
|
const DOCUMENT: &str = "\u{feff}# @knowledge 数学\r\n\r\n## @exec 计算\r\n\r\n`params(n: Int)`\r\n\r\n`return n + 1`\r\n\r\n### 细节\r\n\r\n正文\r\n";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn analysis_projects_exact_source_document_and_complete_scopes() {
|
||||||
|
let dir = TempDir::new("scope");
|
||||||
|
dir.write("index.mq.md", DOCUMENT);
|
||||||
|
let output = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
let value = analysis(dir.path(), "analysis.json");
|
||||||
|
let module = &value["modules"][0];
|
||||||
|
assert_eq!(module["source"], DOCUMENT);
|
||||||
|
assert_eq!(module["source_digest"], digest(DOCUMENT.as_bytes()));
|
||||||
|
assert_eq!(value["project"]["entry_module_id"], module["id"]);
|
||||||
|
|
||||||
|
let document = &module["document"];
|
||||||
|
assert_eq!(document["kind"], "document");
|
||||||
|
assert_eq!(document["span"]["start"], 0);
|
||||||
|
assert_eq!(
|
||||||
|
document["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
let heading = document["children"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|node| node["kind"] == "heading" && node["level"] == 1)
|
||||||
|
.expect("level-1 heading");
|
||||||
|
assert!(heading["children"].is_array());
|
||||||
|
assert!(heading["children"].as_array().unwrap().iter().any(|node| {
|
||||||
|
node["kind"] == "text"
|
||||||
|
&& node["literal"]
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|literal| literal.contains("数学"))
|
||||||
|
}));
|
||||||
|
|
||||||
|
let units = module["units"].as_array().unwrap();
|
||||||
|
let by_name = |name: &str| {
|
||||||
|
units
|
||||||
|
.iter()
|
||||||
|
.find(|unit| unit["name"] == name)
|
||||||
|
.unwrap_or_else(|| panic!("missing unit {name}"))
|
||||||
|
};
|
||||||
|
let root = &units[0];
|
||||||
|
assert_eq!(root["kind"], "root");
|
||||||
|
assert_eq!(root["parent_id"], serde_json::Value::Null);
|
||||||
|
assert_eq!(root["heading_span"], serde_json::Value::Null);
|
||||||
|
assert_eq!(root["span"]["start"], 0);
|
||||||
|
assert_eq!(
|
||||||
|
root["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
let namespace = by_name("数学");
|
||||||
|
assert_eq!(namespace["kind"], "namespace");
|
||||||
|
assert_eq!(namespace["parent_id"], root["id"]);
|
||||||
|
assert_eq!(namespace["mode"], "knowledge");
|
||||||
|
assert_eq!(namespace["mode_origin"], "explicit");
|
||||||
|
assert_eq!(namespace["mode_source_unit_id"], namespace["id"]);
|
||||||
|
|
||||||
|
let function = by_name("计算");
|
||||||
|
assert_eq!(function["kind"], "function");
|
||||||
|
assert_eq!(function["parent_id"], namespace["id"]);
|
||||||
|
assert_eq!(function["mode"], "exec");
|
||||||
|
assert_eq!(function["mode_origin"], "explicit");
|
||||||
|
assert!(function["function"].is_string());
|
||||||
|
assert_ne!(function["span"], function["heading_span"]);
|
||||||
|
|
||||||
|
let section = by_name("细节");
|
||||||
|
assert_eq!(section["kind"], "section");
|
||||||
|
assert_eq!(section["parent_id"], function["id"]);
|
||||||
|
assert_eq!(section["mode"], "exec");
|
||||||
|
assert_eq!(section["mode_origin"], "inherited");
|
||||||
|
assert_eq!(section["mode_source_unit_id"], function["id"]);
|
||||||
|
// The complete function range includes the H3 child and runs to EOF.
|
||||||
|
assert_eq!(
|
||||||
|
function["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
section["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
let heading_start = DOCUMENT.find("## @exec 计算").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
function["heading_span"]["start"].as_u64().unwrap() as usize,
|
||||||
|
heading_start
|
||||||
|
);
|
||||||
|
|
||||||
|
let anchors = module["anchors"].as_array().unwrap();
|
||||||
|
assert!(anchors.iter().any(|anchor| anchor["anchor"] == "计算"));
|
||||||
|
let signature = &module["functions"][0]["signature"];
|
||||||
|
assert_eq!(signature["kind"], "explicit");
|
||||||
|
assert_eq!(signature["params"][0]["name"], "n");
|
||||||
|
assert_eq!(signature["params"][0]["type"], "Int");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reference_states_are_distinct_and_explicit_refs_do_not_change_the_program() {
|
||||||
|
let dir = TempDir::new("references");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n[本地](./other.mq.md#公式) [外链](https://example.com) [本文](#main)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
dir.write("other.mq.md", "## @knowledge 公式\n\n正文\n");
|
||||||
|
let ordinary = emit(dir.path(), "index.mq.md", "ordinary.json", &[]);
|
||||||
|
assert!(
|
||||||
|
ordinary.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&ordinary.stderr)
|
||||||
|
);
|
||||||
|
let value = analysis(dir.path(), "ordinary.json");
|
||||||
|
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
let references = value["modules"][0]["references"].as_array().unwrap();
|
||||||
|
let state = |url: &str| {
|
||||||
|
references
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == url)
|
||||||
|
.unwrap_or_else(|| panic!("missing reference {url}"))["state"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
};
|
||||||
|
assert_eq!(state("./other.mq.md#公式"), "not_loaded");
|
||||||
|
assert_eq!(state("https://example.com"), "external");
|
||||||
|
assert_eq!(state("#main"), "resolved");
|
||||||
|
// The ordinary artifact still describes only the loaded program.
|
||||||
|
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
|
||||||
|
// Explicit refs verify the direct target and keep the same ordinary bytes'
|
||||||
|
// module set. The emitted Analysis still uses the loaded catalog.
|
||||||
|
let verified = emit(dir.path(), "index.mq.md", "verified.json", &["--refs"]);
|
||||||
|
assert!(
|
||||||
|
verified.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&verified.stderr)
|
||||||
|
);
|
||||||
|
let verified_value = analysis(dir.path(), "verified.json");
|
||||||
|
assert_eq!(verified_value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
let verified_refs = verified_value["modules"][0]["references"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
verified_refs
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == "./other.mq.md#公式")
|
||||||
|
.unwrap()["state"],
|
||||||
|
"not_loaded",
|
||||||
|
"the emitted artifact must keep the loaded catalog"
|
||||||
|
);
|
||||||
|
let inspected = cli(dir.path(), &["inspect", "index.mq.md", "--refs", "--json"]);
|
||||||
|
assert!(inspected.status.success());
|
||||||
|
let inspected: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
|
||||||
|
let resolved = inspected["refs"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == "./other.mq.md#公式")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resolved["state"], "resolved");
|
||||||
|
assert_eq!(resolved["target_kind"], "module");
|
||||||
|
assert!(resolved["target_module"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::other.mq.md"));
|
||||||
|
|
||||||
|
// A broken explicitly verified target is an error and publishes no artifact.
|
||||||
|
dir.write(
|
||||||
|
"broken.mq.md",
|
||||||
|
"## @exec main\n\n[坏](./other.mq.md#不存在)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
let broken = emit(dir.path(), "broken.mq.md", "broken.json", &["--refs"]);
|
||||||
|
assert_eq!(broken.status.code(), Some(1), "{broken:?}");
|
||||||
|
assert!(!dir.path().join("broken.json").exists());
|
||||||
|
assert!(String::from_utf8_lossy(&broken.stderr).contains("ref.unresolved"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emit_refuses_inputs_symlinks_hardlinks_and_directories() {
|
||||||
|
let dir = TempDir::new("emit-safety");
|
||||||
|
let source = "## @exec main\n\n`return 1`\n";
|
||||||
|
let entry = dir.write("index.mq.md", source);
|
||||||
|
|
||||||
|
let self_emit = emit(dir.path(), "index.mq.md", "index.mq.md", &[]);
|
||||||
|
assert_eq!(self_emit.status.code(), Some(2), "{self_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
std::os::unix::fs::symlink(&entry, dir.path().join("link.json")).unwrap();
|
||||||
|
let symlink_emit = emit(dir.path(), "index.mq.md", "link.json", &[]);
|
||||||
|
assert_eq!(symlink_emit.status.code(), Some(2), "{symlink_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
|
||||||
|
std::fs::hard_link(&entry, dir.path().join("hard.json")).unwrap();
|
||||||
|
let hard_emit = emit(dir.path(), "index.mq.md", "hard.json", &[]);
|
||||||
|
assert_eq!(hard_emit.status.code(), Some(2), "{hard_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::fs::create_dir(dir.path().join("outdir")).unwrap();
|
||||||
|
let directory_emit = emit(dir.path(), "index.mq.md", "outdir", &[]);
|
||||||
|
assert_eq!(directory_emit.status.code(), Some(2), "{directory_emit:?}");
|
||||||
|
|
||||||
|
let ok = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(ok.status.success(), "{ok:?}");
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(dir.path().join("analysis.json"))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode()
|
||||||
|
& 0o777;
|
||||||
|
assert_eq!(mode, 0o600, "Analysis output must be owner-only");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observation_binds_the_exact_emitted_analysis_bytes() {
|
||||||
|
let dir = TempDir::new("digest");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n`params(n: Int)`\n\n`return n + 1`\n",
|
||||||
|
);
|
||||||
|
let emitted = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
emitted.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&emitted.stderr)
|
||||||
|
);
|
||||||
|
let bytes = std::fs::read(dir.path().join("analysis.json")).unwrap();
|
||||||
|
let expected = format!("sha256:{}", digest(&bytes));
|
||||||
|
|
||||||
|
let run = cli(
|
||||||
|
dir.path(),
|
||||||
|
&[
|
||||||
|
"call",
|
||||||
|
"index.mq.md",
|
||||||
|
"main",
|
||||||
|
"--arg",
|
||||||
|
"n=1",
|
||||||
|
"--output",
|
||||||
|
"json",
|
||||||
|
"--observation-file",
|
||||||
|
"observation.json",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
run.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&run.stderr)
|
||||||
|
);
|
||||||
|
let observation = analysis(dir.path(), "observation.json");
|
||||||
|
let started = observation["events"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|event| event["kind"] == "run.started")
|
||||||
|
.expect("run.started");
|
||||||
|
assert_eq!(started["payload"]["source"]["analysis_digest"], expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn independent_view_lint_and_knowledge_consumers_drive_the_real_cli() {
|
||||||
|
let dir = TempDir::new("consumers");
|
||||||
|
dir.write(
|
||||||
|
"marqdo.yaml",
|
||||||
|
"project:\n name: consumers\n version: 0.1.0\n",
|
||||||
|
);
|
||||||
|
dir.write("theory.mq.md", "## @knowledge 公式\n\n正文\n");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n[公式](./theory.mq.md#公式) [未加载](./notes.mq.md)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
dir.write("notes.mq.md", "## @exec main\n\n`return 2`\n");
|
||||||
|
assert!(emit(dir.path(), "index.mq.md", "index.json", &[])
|
||||||
|
.status
|
||||||
|
.success());
|
||||||
|
assert!(emit(dir.path(), "notes.mq.md", "notes.json", &[])
|
||||||
|
.status
|
||||||
|
.success());
|
||||||
|
|
||||||
|
let consumers = repo_root().join("tests/consumers");
|
||||||
|
let run = |script: &str, args: &[&Path]| -> Output {
|
||||||
|
let mut command = Command::new("python3");
|
||||||
|
command.arg(consumers.join(script));
|
||||||
|
for arg in args {
|
||||||
|
command.arg(arg);
|
||||||
|
}
|
||||||
|
command.output().expect("python3 consumer")
|
||||||
|
};
|
||||||
|
let index_json = dir.path().join("index.json");
|
||||||
|
let notes_json = dir.path().join("notes.json");
|
||||||
|
|
||||||
|
let view = run("view_consumer.py", &[&index_json]);
|
||||||
|
assert!(
|
||||||
|
view.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&view.stderr)
|
||||||
|
);
|
||||||
|
assert!(String::from_utf8_lossy(&view.stdout).contains("view: rendered=1"));
|
||||||
|
|
||||||
|
let lint = run("lint_consumer.py", &[&index_json]);
|
||||||
|
assert!(
|
||||||
|
lint.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&lint.stderr)
|
||||||
|
);
|
||||||
|
let lint_text = String::from_utf8_lossy(&lint.stdout);
|
||||||
|
assert!(lint_text.contains("state=not_loaded"));
|
||||||
|
assert!(lint_text.contains("unresolved=1"));
|
||||||
|
|
||||||
|
let knowledge = run("knowledge_consumer.py", &[&index_json, ¬es_json]);
|
||||||
|
assert!(
|
||||||
|
knowledge.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&knowledge.stderr)
|
||||||
|
);
|
||||||
|
let knowledge_text = String::from_utf8_lossy(&knowledge.stdout);
|
||||||
|
assert!(knowledge_text.contains("entries=2"));
|
||||||
|
assert!(knowledge_text.contains("not_loaded=1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn protocol_validator_accepts_current_bytes_and_rejects_mutations() {
|
||||||
|
let dir = TempDir::new("protocol-validator");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n$$x^2$$\n\n```python\nprint(1)\n```\n\n[公式](./theory.mq.md#公式)\n\n`结果 = theory.加一(1)`\n\n`return 结果`\n",
|
||||||
|
);
|
||||||
|
dir.write(
|
||||||
|
"theory.mq.md",
|
||||||
|
"## @exec 加一\n\n`params(n: Int)`\n\n`return n + 1`\n\n## @knowledge 公式\n\n正文\n",
|
||||||
|
);
|
||||||
|
let check = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
check.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&check.stderr)
|
||||||
|
);
|
||||||
|
let run = cli(
|
||||||
|
dir.path(),
|
||||||
|
&[
|
||||||
|
"call",
|
||||||
|
"index.mq.md",
|
||||||
|
"main",
|
||||||
|
"--output",
|
||||||
|
"json",
|
||||||
|
"--observation-file",
|
||||||
|
"observation.json",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(run.status.success(), "{run:?}");
|
||||||
|
let validator = repo_root().join("tests/consumers/validate_protocols.py");
|
||||||
|
let output = Command::new("python3")
|
||||||
|
.arg(&validator)
|
||||||
|
.arg(dir.path().join("analysis.json"))
|
||||||
|
.arg(dir.path().join("observation.json"))
|
||||||
|
.arg(repo_root().join("examples/tool-unknown-name/tool.json"))
|
||||||
|
.output()
|
||||||
|
.expect("python3 protocol validator");
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
assert!(String::from_utf8_lossy(&output.stdout).contains("validated analysis"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_entries_keep_their_own_snapshot_context() {
|
||||||
|
let dir = TempDir::new("entries");
|
||||||
|
for (name, body) in [("first", "1"), ("second", "2")] {
|
||||||
|
dir.write(
|
||||||
|
&format!("{name}.mq.md"),
|
||||||
|
&format!("## @exec main\n\n`return {body}`\n"),
|
||||||
|
);
|
||||||
|
let output = emit(
|
||||||
|
dir.path(),
|
||||||
|
&format!("{name}.mq.md"),
|
||||||
|
&format!("{name}.json"),
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
assert!(output.status.success(), "{output:?}");
|
||||||
|
}
|
||||||
|
let first = analysis(dir.path(), "first.json");
|
||||||
|
let second = analysis(dir.path(), "second.json");
|
||||||
|
assert!(first["project"]["entry_module_id"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::first.mq.md"));
|
||||||
|
assert!(second["project"]["entry_module_id"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::second.mq.md"));
|
||||||
|
assert_ne!(first["project"]["root_id"], second["project"]["root_id"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_refs_verify_plain_files_reject_symlinks_and_never_guess_coverage() {
|
||||||
|
let dir = TempDir::new("refs-files");
|
||||||
|
dir.write("marqdo.yaml", "project:\n name: files\n version: 0.1.0\n");
|
||||||
|
dir.write("asset.pdf", "%PDF-1.4 not a program\n");
|
||||||
|
dir.write("notes.md", "# Notes\n\nplain markdown\n");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n[资产](./asset.pdf) [普通](./notes.md#notes) [越界](./%2e%2e/secret.mq.md)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
std::os::unix::fs::symlink("/etc/hostname", dir.path().join("escape.mq.md")).unwrap();
|
||||||
|
dir.write(
|
||||||
|
"symlink.mq.md",
|
||||||
|
"## @exec main\n\n[逃逸](./escape.mq.md)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let inspected = cli(dir.path(), &["inspect", "index.mq.md", "--refs", "--json"]);
|
||||||
|
assert!(inspected.status.success(), "{inspected:?}");
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
|
||||||
|
let refs = value["refs"].as_array().unwrap();
|
||||||
|
let by_url = |url: &str| {
|
||||||
|
refs.iter()
|
||||||
|
.find(|reference| reference["url"] == url)
|
||||||
|
.unwrap_or_else(|| panic!("missing {url}"))
|
||||||
|
};
|
||||||
|
assert_eq!(by_url("./asset.pdf")["state"], "resolved");
|
||||||
|
assert_eq!(by_url("./asset.pdf")["target_kind"], "file");
|
||||||
|
assert_eq!(by_url("./notes.md#notes")["state"], "not_loaded");
|
||||||
|
assert_eq!(by_url("./%2e%2e/secret.mq.md")["state"], "outside_scope");
|
||||||
|
let issues = value["reference_issues"].as_array().unwrap();
|
||||||
|
assert!(issues.iter().any(|issue| issue["code"] == "ref.invalid"));
|
||||||
|
assert!(issues.iter().any(|issue| issue["code"] == "ref.not_loaded"));
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let symlinked = cli(
|
||||||
|
dir.path(),
|
||||||
|
&["inspect", "symlink.mq.md", "--refs", "--json"],
|
||||||
|
);
|
||||||
|
assert!(symlinked.status.success(), "{symlinked:?}");
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&symlinked.stdout).unwrap();
|
||||||
|
assert_eq!(value["refs"][0]["state"], "not_loaded");
|
||||||
|
assert!(value["reference_issues"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.any(|issue| issue["code"] == "ref.invalid"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_unimported_program_is_an_explicit_refs_error_but_not_loaded_otherwise() {
|
||||||
|
let dir = TempDir::new("refs-missing");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n[不存在](./absent.mq.md#x)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
let ordinary = emit(dir.path(), "index.mq.md", "ordinary.json", &[]);
|
||||||
|
assert!(ordinary.status.success(), "{ordinary:?}");
|
||||||
|
let analysis = analysis(dir.path(), "ordinary.json");
|
||||||
|
assert_eq!(
|
||||||
|
analysis["modules"][0]["references"][0]["state"],
|
||||||
|
"not_loaded"
|
||||||
|
);
|
||||||
|
let refs = emit(dir.path(), "index.mq.md", "refs.json", &["--refs"]);
|
||||||
|
assert_eq!(refs.status.code(), Some(1), "{refs:?}");
|
||||||
|
assert!(!dir.path().join("refs.json").exists());
|
||||||
|
assert!(String::from_utf8_lossy(&refs.stderr).contains("ref.unresolved"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lock_digest_binds_the_prepared_lock_snapshot() {
|
||||||
|
let dir = TempDir::new("lock-digest");
|
||||||
|
dir.write("marqdo.yaml", "project:\n name: lock\n version: 0.1.0\n");
|
||||||
|
dir.write("index.mq.md", "## @exec main\n\n`return 1`\n");
|
||||||
|
let lock = cli(dir.path(), &["lock"]);
|
||||||
|
assert!(lock.status.success(), "{lock:?}");
|
||||||
|
let locked = emit(dir.path(), "index.mq.md", "locked.json", &[]);
|
||||||
|
assert!(locked.status.success(), "{locked:?}");
|
||||||
|
let lock_bytes = std::fs::read(dir.path().join("marqdo.lock")).unwrap();
|
||||||
|
let analysis = analysis(dir.path(), "locked.json");
|
||||||
|
assert_eq!(
|
||||||
|
analysis["project"]["lock_digest"],
|
||||||
|
format!("sha256:{}", digest(&lock_bytes))
|
||||||
|
);
|
||||||
|
let manifest_bytes = std::fs::read(dir.path().join("marqdo.yaml")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
analysis["project"]["manifest_digest"],
|
||||||
|
format!("sha256:{}", digest(&manifest_bytes))
|
||||||
|
);
|
||||||
|
|
||||||
|
// A lock that no longer validates cannot leave a success artifact behind.
|
||||||
|
std::fs::write(dir.path().join("marqdo.lock"), "lock_version: 4\n").unwrap();
|
||||||
|
let failed = emit(dir.path(), "index.mq.md", "locked.json", &[]);
|
||||||
|
assert_ne!(failed.status.code(), Some(0), "{failed:?}");
|
||||||
|
assert!(!dir.path().join("locked.json").exists());
|
||||||
|
}
|
||||||
@@ -267,9 +267,16 @@ print(1)
|
|||||||
assert_eq!(code["language"], "python");
|
assert_eq!(code["language"], "python");
|
||||||
assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64);
|
assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64);
|
||||||
assert_eq!(code["content_digest"].as_str().unwrap().len(), 64);
|
assert_eq!(code["content_digest"].as_str().unwrap().len(), 64);
|
||||||
assert!(
|
let source = analysis["modules"][0]["source"]
|
||||||
!analysis.to_string().contains("A = x + 1"),
|
.as_str()
|
||||||
"resource payloads stay in source, not Analysis"
|
.expect("exact source is public");
|
||||||
|
assert!(source.contains("A = x + 1"));
|
||||||
|
assert_eq!(
|
||||||
|
source.len(),
|
||||||
|
analysis["modules"][0]["source_digest"]
|
||||||
|
.as_str()
|
||||||
|
.map(|_| source.len())
|
||||||
|
.unwrap_or(0)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,6 +344,31 @@ fn failed_check_removes_stale_analysis() {
|
|||||||
assert!(!target.exists(), "stale success artifact must be removed");
|
assert!(!target.exists(), "stale success artifact must be removed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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]
|
#[test]
|
||||||
fn snapshot_records_calls_effects_and_status_without_secrets() {
|
fn snapshot_records_calls_effects_and_status_without_secrets() {
|
||||||
let dir = TempDir::new("trace");
|
let dir = TempDir::new("trace");
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
//! Architecture boundary gate (review RFC-CM P0/P1).
|
//! Architecture boundary gate (review RFC-CM P0/P1).
|
||||||
//!
|
//!
|
||||||
//! These checks pin the documented layering: the runtime depends on the host
|
//! These checks pin the documented layering: the engine depends on the neutral
|
||||||
//! platform layer, the bundled stdlib stays in this repository, `std:` import
|
//! Host contract (never the native host), the plugin ABI contract carries no
|
||||||
//! targets resolve only inside the bundle, and the host keeps the documented
|
//! loader/worker execution side, the bundled stdlib stays in this repository,
|
||||||
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an
|
//! `std:` import targets resolve only inside the bundle, and the host keeps the
|
||||||
//! OS-sandbox proof.
|
//! documented stdio/file/TCP resource endpoints. They are source and digest
|
||||||
|
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
|
||||||
|
//! adds the Cargo-metadata graph gate.
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -23,66 +25,114 @@ fn read(path: &Path) -> String {
|
|||||||
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
|
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
|
||||||
}
|
}
|
||||||
|
|
||||||
const WORKSPACE_CRATES: &[&str] = &[
|
/// Issue #13 / ADR-0071: the reviewed responsibility allowlist is the crate
|
||||||
"marqdo-span",
|
/// table in the single current architecture overview, not a frozen count. A new
|
||||||
"marqdo-value",
|
/// crate must be added there (and to the dependency gate's reviewed map) in the
|
||||||
"marqdo-expression",
|
/// same change.
|
||||||
"marqdo-markdown",
|
|
||||||
"marqdo-ir",
|
|
||||||
"marqdo-frontend",
|
|
||||||
"marqdo-foreign",
|
|
||||||
"marqdo-plugin-abi",
|
|
||||||
"marqdo-provider-worker",
|
|
||||||
"marqdo-worker-ipc",
|
|
||||||
"marqdo-plugin-sdk",
|
|
||||||
"marqdo-host",
|
|
||||||
"marqdo-runtime",
|
|
||||||
"marqdo-package",
|
|
||||||
"marqdo-sandbox",
|
|
||||||
"cli",
|
|
||||||
];
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn workspace_crates_match_the_documented_layers() {
|
fn workspace_crates_are_documented_responsibilities() {
|
||||||
let manifest = read(&repo_root().join("Cargo.toml"));
|
let root = repo_root();
|
||||||
|
let manifest = read(&root.join("Cargo.toml"));
|
||||||
let members = manifest
|
let members = manifest
|
||||||
.split("members = [")
|
.split("members = [")
|
||||||
.nth(1)
|
.nth(1)
|
||||||
.and_then(|rest| rest.split(']').next())
|
.and_then(|rest| rest.split(']').next())
|
||||||
.expect("workspace members");
|
.expect("workspace members");
|
||||||
let names: Vec<&str> = members
|
let names: Vec<String> = members
|
||||||
.split(',')
|
.split(',')
|
||||||
.map(|item| item.trim().trim_matches('"'))
|
.map(|item| item.trim().trim_matches('"'))
|
||||||
.filter(|item| !item.is_empty())
|
.filter(|item| !item.is_empty())
|
||||||
|
.map(|member| {
|
||||||
|
let directory = member
|
||||||
|
.strip_prefix("crates/")
|
||||||
|
.expect("workspace members are crates/<name>");
|
||||||
|
let manifest = read(&root.join(member).join("Cargo.toml"));
|
||||||
|
manifest
|
||||||
|
.lines()
|
||||||
|
.find_map(|line| line.strip_prefix("name = "))
|
||||||
|
.map(|name| name.trim().trim_matches('"').to_string())
|
||||||
|
.unwrap_or_else(|| directory.to_string())
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let expected: Vec<String> = WORKSPACE_CRATES
|
let current = read(&root.join("docs/architecture/CURRENT.md"));
|
||||||
.iter()
|
let responsibilities = current
|
||||||
.map(|name| format!("crates/{name}"))
|
.split("## Workspace crate responsibility map")
|
||||||
.collect();
|
.nth(1)
|
||||||
assert_eq!(
|
.expect("CURRENT.md must own the reviewed crate responsibility map")
|
||||||
names,
|
.split("\n## ")
|
||||||
expected.iter().map(String::as_str).collect::<Vec<_>>(),
|
.next()
|
||||||
"workspace members drifted; update docs/architecture/CURRENT.md with the layer"
|
.unwrap_or("");
|
||||||
);
|
for name in &names {
|
||||||
|
assert!(
|
||||||
|
responsibilities.contains(&format!("`{name}`")),
|
||||||
|
"workspace crate `{name}` has no documented responsibility in CURRENT.md"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in [
|
||||||
|
"marqdo-host-contract",
|
||||||
|
"marqdo-host",
|
||||||
|
"marqdo-plugin-abi",
|
||||||
|
"marqdo-cli",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
names.iter().any(|crate_name| crate_name == name),
|
||||||
|
"required layer crate `{name}` is missing from the workspace"
|
||||||
|
);
|
||||||
|
}
|
||||||
assert!(
|
assert!(
|
||||||
!names.contains(&"crates/marqdo-stdlib"),
|
!names.iter().any(|name| name == "marqdo-stdlib"),
|
||||||
"the stdlib must stay in this repository (ADR-0039), not become a crate"
|
"the stdlib is a Bundle input, not a workspace crate (ADR-0039/ADR-0070)"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn runtime_depends_on_the_host_platform_layer_without_a_cycle() {
|
fn engine_depends_on_the_neutral_host_contract_only() {
|
||||||
let runtime = read(&repo_root().join("crates/marqdo-runtime/Cargo.toml"));
|
let root = repo_root();
|
||||||
|
let runtime = read(&root.join("crates/marqdo-runtime/Cargo.toml"));
|
||||||
|
let runtime_dependencies = runtime
|
||||||
|
.split("[dependencies]")
|
||||||
|
.nth(1)
|
||||||
|
.expect("runtime dependencies")
|
||||||
|
.split("[dev-dependencies]")
|
||||||
|
.next()
|
||||||
|
.expect("runtime normal dependencies");
|
||||||
assert!(
|
assert!(
|
||||||
runtime
|
runtime_dependencies
|
||||||
|
.lines()
|
||||||
|
.any(|line| line.trim() == "marqdo-host-contract = { workspace = true }"),
|
||||||
|
"runtime must depend on the neutral marqdo-host-contract crate"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!runtime_dependencies
|
||||||
.lines()
|
.lines()
|
||||||
.any(|line| line.trim() == "marqdo-host = { workspace = true }"),
|
.any(|line| line.trim() == "marqdo-host = { workspace = true }"),
|
||||||
"runtime must keep the documented marqdo-runtime -> marqdo-host direction"
|
"runtime normal/build dependencies must not link the native host"
|
||||||
);
|
);
|
||||||
let host = read(&repo_root().join("crates/marqdo-host/Cargo.toml"));
|
let contract = read(&root.join("crates/marqdo-host-contract/Cargo.toml"));
|
||||||
|
let contract_deps: Vec<&str> = contract
|
||||||
|
.split("[dependencies]")
|
||||||
|
.nth(1)
|
||||||
|
.expect("contract dependencies")
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| line.split('=').next())
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|name| !name.is_empty() && !name.starts_with('['))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
contract_deps,
|
||||||
|
["marqdo-span", "marqdo-value"],
|
||||||
|
"the host contract must stay platform neutral (value/span only)"
|
||||||
|
);
|
||||||
|
let host = read(&root.join("crates/marqdo-host/Cargo.toml"));
|
||||||
|
for forbidden in ["marqdo-runtime", "marqdo-frontend", "marqdo-ir ="] {
|
||||||
|
assert!(
|
||||||
|
!host.contains(forbidden),
|
||||||
|
"the native host must not depend back on `{forbidden}`"
|
||||||
|
);
|
||||||
|
}
|
||||||
assert!(
|
assert!(
|
||||||
!host.contains("marqdo-runtime"),
|
host.contains("marqdo-host-contract = { workspace = true }"),
|
||||||
"marqdo-host must not depend back on marqdo-runtime"
|
"the native host must implement the neutral contract crate"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,7 +203,6 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
|
|||||||
}
|
}
|
||||||
for user in [
|
for user in [
|
||||||
"crates/marqdo-host/Cargo.toml",
|
"crates/marqdo-host/Cargo.toml",
|
||||||
"crates/marqdo-plugin-abi/Cargo.toml",
|
|
||||||
"crates/marqdo-provider-worker/Cargo.toml",
|
"crates/marqdo-provider-worker/Cargo.toml",
|
||||||
] {
|
] {
|
||||||
assert!(
|
assert!(
|
||||||
@@ -164,8 +213,8 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
|
|||||||
// The four-byte length prefix and its bounds live in exactly one crate.
|
// The four-byte length prefix and its bounds live in exactly one crate.
|
||||||
for private in [
|
for private in [
|
||||||
"crates/marqdo-host/src/plugin_worker.rs",
|
"crates/marqdo-host/src/plugin_worker.rs",
|
||||||
|
"crates/marqdo-host/src/plugin/worker.rs",
|
||||||
"crates/marqdo-host/src/provider_worker.rs",
|
"crates/marqdo-host/src/provider_worker.rs",
|
||||||
"crates/marqdo-plugin-abi/src/worker.rs",
|
|
||||||
"crates/marqdo-provider-worker/src/main.rs",
|
"crates/marqdo-provider-worker/src/main.rs",
|
||||||
] {
|
] {
|
||||||
let text = read(&root.join(private));
|
let text = read(&root.join(private));
|
||||||
@@ -409,12 +458,12 @@ fn builtin_names_and_aliases_are_reviewed() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
|
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
|
||||||
const _: fn(marqdo_host::HostOp) = |operation| match operation {
|
const _: fn(marqdo_host_contract::HostOp) = |operation| match operation {
|
||||||
marqdo_host::HostOp::ForeignRun
|
marqdo_host_contract::HostOp::ForeignRun
|
||||||
| marqdo_host::HostOp::ForeignCall
|
| marqdo_host_contract::HostOp::ForeignCall
|
||||||
| marqdo_host::HostOp::FsRead
|
| marqdo_host_contract::HostOp::FsRead
|
||||||
| marqdo_host::HostOp::FsWrite
|
| marqdo_host_contract::HostOp::FsWrite
|
||||||
| marqdo_host::HostOp::PluginInvoke => (),
|
| marqdo_host_contract::HostOp::PluginInvoke => (),
|
||||||
};
|
};
|
||||||
|
|
||||||
const _: fn(marqdo_value::Value) = |value| match value {
|
const _: fn(marqdo_value::Value) = |value| match value {
|
||||||
@@ -565,6 +614,133 @@ fn domain_math_kernel_is_not_part_of_the_core() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// E02/E03: there is exactly one Host trait/HostOp definition and it belongs to
|
||||||
|
/// the neutral contract; the native host only implements it.
|
||||||
|
#[test]
|
||||||
|
fn host_contract_is_the_single_side_effect_interface() {
|
||||||
|
let root = repo_root();
|
||||||
|
let mut host_traits = Vec::new();
|
||||||
|
let mut host_ops = Vec::new();
|
||||||
|
for source in walk_rs(&root.join("crates")) {
|
||||||
|
let relative = source
|
||||||
|
.strip_prefix(&root)
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string();
|
||||||
|
if relative.contains("/tests/") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let text = read(&source);
|
||||||
|
if text.contains("pub trait Host {") {
|
||||||
|
host_traits.push(relative.clone());
|
||||||
|
}
|
||||||
|
if text.contains("pub enum HostOp {") {
|
||||||
|
host_ops.push(relative);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
host_traits,
|
||||||
|
["crates/marqdo-host-contract/src/host.rs"],
|
||||||
|
"the Host trait must be defined once in the neutral contract"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
host_ops,
|
||||||
|
["crates/marqdo-host-contract/src/host.rs"],
|
||||||
|
"HostOp must be defined once in the neutral contract"
|
||||||
|
);
|
||||||
|
let runtime = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
|
||||||
|
assert!(
|
||||||
|
runtime.contains("use marqdo_host_contract::{"),
|
||||||
|
"the interpreter must consume the neutral contract"
|
||||||
|
);
|
||||||
|
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
|
||||||
|
assert!(
|
||||||
|
host.contains("impl Host for StdHost"),
|
||||||
|
"StdHost remains the single native host implementation"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A05/S01: the public ABI crate is a contract, not a loader; execution side
|
||||||
|
/// lives in the native host and the SDK consumes only the contract.
|
||||||
|
#[test]
|
||||||
|
fn plugin_contract_carries_no_native_execution() {
|
||||||
|
let root = repo_root();
|
||||||
|
let abi = read(&root.join("crates/marqdo-plugin-abi/Cargo.toml"));
|
||||||
|
for forbidden in ["libloading", "marqdo-worker-ipc", "serde_yaml", "sha2"] {
|
||||||
|
assert!(
|
||||||
|
!abi.contains(forbidden),
|
||||||
|
"marqdo-plugin-abi must not depend on execution-side `{forbidden}`"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for module in ["loader", "worker", "manifest", "artifact"] {
|
||||||
|
assert!(
|
||||||
|
!root
|
||||||
|
.join(format!("crates/marqdo-plugin-abi/src/{module}.rs"))
|
||||||
|
.exists(),
|
||||||
|
"`{module}` is execution-side and belongs to the native host"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for module in ["loader", "worker", "manifest", "artifact"] {
|
||||||
|
assert!(
|
||||||
|
root.join(format!("crates/marqdo-host/src/plugin/{module}.rs"))
|
||||||
|
.exists(),
|
||||||
|
"native host must own plugin `{module}`"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// ADR-0072: the SDK is an independent repository pinned to a contract
|
||||||
|
// revision. It must not be reintroduced as a second in-workspace copy.
|
||||||
|
assert!(
|
||||||
|
!root.join("crates/marqdo-plugin-sdk").exists(),
|
||||||
|
"the plugin SDK moved to cflmy/marqdo-plugin-sdk (ADR-0072)"
|
||||||
|
);
|
||||||
|
let manifest = read(&root.join("Cargo.toml"));
|
||||||
|
assert!(
|
||||||
|
!manifest.contains("marqdo-plugin-sdk"),
|
||||||
|
"the plugin SDK must not return as a CLI workspace member"
|
||||||
|
);
|
||||||
|
let current = read(&root.join("docs/architecture/CURRENT.md"));
|
||||||
|
assert!(
|
||||||
|
current.contains("cflmy/marqdo-plugin-sdk") && current.contains("ADR-0072"),
|
||||||
|
"CURRENT.md must name the independent SDK repository decision"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// E01/E04: the independent embedding consumer is a real package outside the
|
||||||
|
/// workspace and depends only on engine crates.
|
||||||
|
#[test]
|
||||||
|
fn embedding_consumer_is_engine_only() {
|
||||||
|
let root = repo_root();
|
||||||
|
let consumer = read(&root.join("tests/embedding/Cargo.toml"));
|
||||||
|
assert!(
|
||||||
|
consumer.contains("[workspace]"),
|
||||||
|
"the embedding consumer must be its own workspace to avoid feature unification"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
consumer.contains("marqdo-runtime"),
|
||||||
|
"the embedding consumer must execute through the real runtime"
|
||||||
|
);
|
||||||
|
for forbidden in [
|
||||||
|
"marqdo-host",
|
||||||
|
"marqdo-cli",
|
||||||
|
"marqdo-sandbox",
|
||||||
|
"marqdo-foreign",
|
||||||
|
] {
|
||||||
|
let dependency_line = format!("\n{forbidden} =");
|
||||||
|
assert!(
|
||||||
|
!consumer.contains(&dependency_line),
|
||||||
|
"the embedding consumer must not depend on `{forbidden}`"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
root.join("tests/embedding/Cargo.lock").is_file(),
|
||||||
|
"the independent consumer must pin its own lock file"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
root.join("tools/ci/check_engine_boundary.py").is_file(),
|
||||||
|
"the build-and-run engine gate must exist"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
fn hex(bytes: &[u8]) -> String {
|
fn hex(bytes: &[u8]) -> String {
|
||||||
let mut out = String::with_capacity(bytes.len() * 2);
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
for byte in bytes {
|
for byte in bytes {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::{Command, Output};
|
use std::process::{Command, Output};
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_plugin_abi::{sha256_file, HostTarget};
|
use marqdo_host::plugin::{sha256_file, HostTarget};
|
||||||
|
|
||||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,8 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::Host;
|
||||||
use marqdo_ir::{ModuleId, Program, ResolvedImport};
|
use marqdo_ir::{ModuleId, Program, ResolvedImport};
|
||||||
use marqdo_runtime::{run, EvaluatedArg};
|
use marqdo_runtime::{run, EvaluatedArg};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
|
|||||||
@@ -231,3 +231,72 @@ fn ci_configuration_uses_only_current_protocols() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::{Command, Output};
|
use std::process::{Command, Output};
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_plugin_abi::{sha256_file, HostTarget};
|
use marqdo_host::plugin::{sha256_file, HostTarget};
|
||||||
|
|
||||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
|||||||
@@ -663,7 +663,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
|
|||||||
assert_exit(&refs, 0, "inspect --refs");
|
assert_exit(&refs, 0, "inspect --refs");
|
||||||
let value = json_stdout(&refs);
|
let value = json_stdout(&refs);
|
||||||
let edges = value["refs"].as_array().expect("refs array");
|
let edges = value["refs"].as_array().expect("refs array");
|
||||||
assert!(edges.iter().any(|edge| edge["resolved"] == true));
|
assert!(edges.iter().any(|edge| edge["state"] == "resolved"));
|
||||||
|
|
||||||
// A broken #anchor is reported as unresolved by `inspect --refs`.
|
// A broken #anchor is reported as unresolved by `inspect --refs`.
|
||||||
let dir = TempDir::new("refs");
|
let dir = TempDir::new("refs");
|
||||||
@@ -677,7 +677,8 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
|
|||||||
let edges = value["refs"].as_array().expect("refs array");
|
let edges = value["refs"].as_array().expect("refs array");
|
||||||
assert_eq!(edges.len(), 1);
|
assert_eq!(edges.len(), 1);
|
||||||
assert_eq!(edges[0]["url"], "#不存在的标题");
|
assert_eq!(edges[0]["url"], "#不存在的标题");
|
||||||
assert_eq!(edges[0]["resolved"], false);
|
assert_eq!(edges[0]["state"], "missing");
|
||||||
|
assert_eq!(edges[0]["target_unit"], serde_json::Value::Null);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -782,7 +783,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
|
|||||||
/// the Linux-only example manifest. This is what makes the integration test a
|
/// the Linux-only example manifest. This is what makes the integration test a
|
||||||
/// real test on macOS/Windows rather than an accidental "no matching artifact".
|
/// real test on macOS/Windows rather than an accidental "no matching artifact".
|
||||||
fn host_triple() -> String {
|
fn host_triple() -> String {
|
||||||
marqdo_plugin_abi::artifact::current_target_triple()
|
marqdo_host::plugin::artifact::current_target_triple()
|
||||||
.as_str()
|
.as_str()
|
||||||
.to_string()
|
.to_string()
|
||||||
}
|
}
|
||||||
@@ -989,22 +990,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");
|
||||||
|
|||||||
@@ -280,7 +280,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
|
|||||||
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
|
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
|
||||||
let manifest = format!(
|
let manifest = format!(
|
||||||
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
|
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
|
||||||
marqdo_plugin_abi::HostTarget::current().triple(),
|
marqdo_host::plugin::HostTarget::current().triple(),
|
||||||
digest
|
digest
|
||||||
);
|
);
|
||||||
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
|
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
|
||||||
@@ -878,3 +878,46 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
|
|||||||
assert_eq!(statement["span"], span);
|
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"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::{Command, Output};
|
use std::process::{Command, Output};
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_plugin_abi::{sha256_file, HostTarget};
|
use marqdo_host::plugin::{sha256_file, HostTarget};
|
||||||
|
|
||||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ use std::process::{Command, Output};
|
|||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
use marqdo_plugin_abi::HostTarget;
|
use marqdo_host::plugin::HostTarget;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER";
|
const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER";
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ pub struct HeadingInfo {
|
|||||||
pub kind: UnitKind,
|
pub kind: UnitKind,
|
||||||
/// Semantic mode declared or inherited by this heading.
|
/// Semantic mode declared or inherited by this heading.
|
||||||
pub mode: SemanticMode,
|
pub mode: SemanticMode,
|
||||||
|
/// How the effective mode was established.
|
||||||
|
pub mode_origin: ModeOrigin,
|
||||||
|
/// Unit that provided the effective mode (this unit, an explicit ancestor,
|
||||||
|
/// or the document root).
|
||||||
|
pub mode_source_unit_id: UnitId,
|
||||||
|
/// Nearest real ancestor unit (the root for a top-level heading).
|
||||||
|
pub parent_id: UnitId,
|
||||||
|
/// Complete section range: this heading through the next same-or-higher
|
||||||
|
/// heading, or the end of the source. It includes child headings.
|
||||||
|
pub full_span: Span,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A function range mapped from a level-2 heading.
|
/// A function range mapped from a level-2 heading.
|
||||||
@@ -95,6 +105,38 @@ impl UnitIndex {
|
|||||||
.iter()
|
.iter()
|
||||||
.find(|f| block_index >= f.body_start && block_index < f.body_end)
|
.find(|f| block_index >= f.body_start && block_index < f.body_end)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Complete public range of one unit: the whole source for the root, the
|
||||||
|
/// heading-through-next-same-or-higher-heading range otherwise.
|
||||||
|
pub fn unit_range(&self, id: &UnitId) -> Option<Span> {
|
||||||
|
if id.path.is_empty() {
|
||||||
|
return self
|
||||||
|
.units
|
||||||
|
.iter()
|
||||||
|
.find(|unit| unit.id.path.is_empty())
|
||||||
|
.map(|unit| unit.span);
|
||||||
|
}
|
||||||
|
self.headings
|
||||||
|
.iter()
|
||||||
|
.find(|heading| heading.path == id.path)
|
||||||
|
.map(|heading| heading.full_span)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Innermost unit whose complete range contains `span`.
|
||||||
|
///
|
||||||
|
/// Used for document links: the root covers the whole source, so a linked
|
||||||
|
/// span always has an owner. Ties prefer the deeper path, then the later
|
||||||
|
/// start (a child cannot be larger than its parent).
|
||||||
|
pub fn unit_containing_span(&self, span: Span) -> Option<UnitId> {
|
||||||
|
self.units
|
||||||
|
.iter()
|
||||||
|
.filter_map(|unit| {
|
||||||
|
let range = self.unit_range(&unit.id)?;
|
||||||
|
(range.start <= span.start && span.end <= range.end).then_some((unit, range))
|
||||||
|
})
|
||||||
|
.max_by_key(|(unit, range)| (unit.id.path.len(), range.start))
|
||||||
|
.map(|(unit, _)| unit.id.clone())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn has_payload(node: &MdNode) -> bool {
|
fn has_payload(node: &MdNode) -> bool {
|
||||||
@@ -116,6 +158,28 @@ pub enum SemanticMode {
|
|||||||
Exec,
|
Exec,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How a heading's effective mode was established.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ModeOrigin {
|
||||||
|
/// The document root is Knowledge by default.
|
||||||
|
Default,
|
||||||
|
/// The ATX heading declares `@exec` or `@knowledge`.
|
||||||
|
Explicit,
|
||||||
|
/// The heading inherits the mode of an ancestor or the root.
|
||||||
|
Inherited,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModeOrigin {
|
||||||
|
/// Stable public name used by Analysis.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ModeOrigin::Default => "default",
|
||||||
|
ModeOrigin::Explicit => "explicit",
|
||||||
|
ModeOrigin::Inherited => "inherited",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn heading_declaration(
|
fn heading_declaration(
|
||||||
node: &MdNode,
|
node: &MdNode,
|
||||||
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
|
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
|
||||||
@@ -184,20 +248,22 @@ fn heading_declaration(
|
|||||||
/// Build the heading/function index for a parsed document.
|
/// Build the heading/function index for a parsed document.
|
||||||
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||||
let mut index = UnitIndex::default();
|
let mut index = UnitIndex::default();
|
||||||
|
let root_id = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: Vec::new(),
|
||||||
|
};
|
||||||
index.units.push(UnitInfo {
|
index.units.push(UnitInfo {
|
||||||
id: UnitId {
|
id: root_id.clone(),
|
||||||
module: module.clone(),
|
|
||||||
path: Vec::new(),
|
|
||||||
},
|
|
||||||
level: 0,
|
level: 0,
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
span: doc.root.span,
|
// The root covers the whole source, including a tolerated UTF-8 BOM.
|
||||||
|
span: Span::new(0, doc.source.len()),
|
||||||
kind: UnitKind::Root,
|
kind: UnitKind::Root,
|
||||||
function: None,
|
function: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Stack of (level, path, mode) for ancestors.
|
// Stack of (level, path, mode, mode_source_unit_id) for ancestors.
|
||||||
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new();
|
let mut stack: Vec<(u8, Vec<String>, SemanticMode, UnitId)> = Vec::new();
|
||||||
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
|
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
|
||||||
let mut current_namespace: Option<String> = None;
|
let mut current_namespace: Option<String> = None;
|
||||||
let mut current_function: Option<FunctionId> = None;
|
let mut current_function: Option<FunctionId> = None;
|
||||||
@@ -224,7 +290,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
// Resolve the ancestor scope before deriving the mode: remove every
|
// Resolve the ancestor scope before deriving the mode: remove every
|
||||||
// same-or-higher-level heading first so a heading can only inherit from
|
// same-or-higher-level heading first so a heading can only inherit from
|
||||||
// its nearest *ancestor*, never from the previous sibling.
|
// its nearest *ancestor*, never from the previous sibling.
|
||||||
while let Some((parent_level, _, _)) = stack.last() {
|
while let Some((parent_level, _, _, _)) = stack.last() {
|
||||||
if *parent_level >= level {
|
if *parent_level >= level {
|
||||||
stack.pop();
|
stack.pop();
|
||||||
} else {
|
} else {
|
||||||
@@ -233,8 +299,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
}
|
}
|
||||||
let inherited = stack
|
let inherited = stack
|
||||||
.last()
|
.last()
|
||||||
.map(|(_, _, mode)| *mode)
|
.map(|(_, _, mode, _)| *mode)
|
||||||
.unwrap_or(SemanticMode::Knowledge);
|
.unwrap_or(SemanticMode::Knowledge);
|
||||||
|
let inherited_source = stack
|
||||||
|
.last()
|
||||||
|
.map(|(_, _, _, source)| source.clone())
|
||||||
|
.unwrap_or_else(|| root_id.clone());
|
||||||
let mode = declared.unwrap_or(inherited);
|
let mode = declared.unwrap_or(inherited);
|
||||||
let raw_name = match declared_name {
|
let raw_name = match declared_name {
|
||||||
Some(name) => name,
|
Some(name) => name,
|
||||||
@@ -254,13 +324,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
|
|
||||||
let parent_path = stack
|
let parent_path = stack
|
||||||
.last()
|
.last()
|
||||||
.map(|(_, path, _)| path.clone())
|
.map(|(_, path, _, _)| path.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
let parent_id = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: parent_path.clone(),
|
||||||
|
};
|
||||||
let path = {
|
let path = {
|
||||||
let mut path = parent_path.clone();
|
let mut path = parent_path.clone();
|
||||||
path.push(name.clone());
|
path.push(name.clone());
|
||||||
path
|
path
|
||||||
};
|
};
|
||||||
|
let unit_id = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: path.clone(),
|
||||||
|
};
|
||||||
|
let (mode_origin, mode_source_unit_id) = match declared {
|
||||||
|
Some(_) => (ModeOrigin::Explicit, unit_id.clone()),
|
||||||
|
None => (ModeOrigin::Inherited, inherited_source),
|
||||||
|
};
|
||||||
|
|
||||||
let key = (parent_path.clone(), name.clone());
|
let key = (parent_path.clone(), name.clone());
|
||||||
if let Some(previous) = seen.get(&key) {
|
if let Some(previous) = seen.get(&key) {
|
||||||
@@ -304,6 +386,27 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
Some(namespace) => format!("{namespace}.{local}"),
|
Some(namespace) => format!("{namespace}.{local}"),
|
||||||
None => local.clone(),
|
None => local.clone(),
|
||||||
};
|
};
|
||||||
|
// `.` separates namespace from local name in a FunctionId. A
|
||||||
|
// component that itself contains `.` would make two different
|
||||||
|
// definitions render the same public id; reject it explicitly
|
||||||
|
// instead of silently producing a non-injective identity.
|
||||||
|
let ambiguous = local.contains('.')
|
||||||
|
|| current_namespace
|
||||||
|
.as_deref()
|
||||||
|
.map(|namespace| namespace.contains('.'))
|
||||||
|
.unwrap_or(false);
|
||||||
|
if ambiguous {
|
||||||
|
index.diagnostics.push(
|
||||||
|
Diagnostic::error(
|
||||||
|
codes::SEM_AMBIGUOUS_IDENTITY,
|
||||||
|
Some(child.span),
|
||||||
|
"function or namespace name contains `.`, which is the namespace separator; the public function id would be ambiguous",
|
||||||
|
)
|
||||||
|
.with_hint(
|
||||||
|
"rename the namespace or function so it does not contain a dot",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
let id = FunctionId {
|
let id = FunctionId {
|
||||||
module: module.clone(),
|
module: module.clone(),
|
||||||
name: qualified,
|
name: qualified,
|
||||||
@@ -327,10 +430,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
kind,
|
kind,
|
||||||
mode,
|
mode,
|
||||||
};
|
mode_origin,
|
||||||
let unit_id = UnitId {
|
mode_source_unit_id,
|
||||||
module: module.clone(),
|
parent_id,
|
||||||
path,
|
// Filled after all headings are known (the end is the next
|
||||||
|
// same-or-higher heading or EOF).
|
||||||
|
full_span: child.span,
|
||||||
};
|
};
|
||||||
index.units.push(UnitInfo {
|
index.units.push(UnitInfo {
|
||||||
id: unit_id,
|
id: unit_id,
|
||||||
@@ -361,7 +466,26 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
heading_infos.push(info.clone());
|
heading_infos.push(info.clone());
|
||||||
stack.push((level, info.path.clone(), mode));
|
stack.push((
|
||||||
|
level,
|
||||||
|
info.path.clone(),
|
||||||
|
mode,
|
||||||
|
info.mode_source_unit_id.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Complete section ranges: from this heading to the next heading of the
|
||||||
|
// same or a higher level, or EOF. Child headings are included.
|
||||||
|
let total = doc.source.len();
|
||||||
|
for position in 0..heading_infos.len() {
|
||||||
|
let level = heading_infos[position].level;
|
||||||
|
let start = heading_infos[position].span.start;
|
||||||
|
let end = heading_infos[position + 1..]
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.level <= level)
|
||||||
|
.map(|candidate| candidate.span.start)
|
||||||
|
.unwrap_or(total);
|
||||||
|
heading_infos[position].full_span = Span::new(start, end.max(start));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function body ranges and spans.
|
// Function body ranges and spans.
|
||||||
@@ -624,6 +748,117 @@ mod tests {
|
|||||||
assert_eq!(normal.kind, UnitKind::Knowledge);
|
assert_eq!(normal.kind, UnitKind::Knowledge);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn full_spans_cover_sections_and_parent_edges_form_a_tree() {
|
||||||
|
let source = "# @knowledge 力学\n\n## @exec 计算力\n\n`return 1`\n\n### 细节\n\n正文\n\n## 说明\n\n结尾\n";
|
||||||
|
let index = index_of(source);
|
||||||
|
let by_name = |name: &str| {
|
||||||
|
index
|
||||||
|
.headings
|
||||||
|
.iter()
|
||||||
|
.find(|heading| heading.name == name)
|
||||||
|
.unwrap_or_else(|| panic!("missing heading {name}"))
|
||||||
|
};
|
||||||
|
let calc = by_name("计算力");
|
||||||
|
let detail = by_name("细节");
|
||||||
|
let note = by_name("说明");
|
||||||
|
// The function range includes its H3 child but not the next H2.
|
||||||
|
assert_eq!(calc.full_span.start, calc.span.start);
|
||||||
|
assert!(calc.full_span.end > detail.span.start);
|
||||||
|
assert_eq!(calc.full_span.end, note.span.start);
|
||||||
|
assert_eq!(detail.full_span.end, note.span.start);
|
||||||
|
assert_eq!(note.full_span.end, source.len());
|
||||||
|
assert_eq!(
|
||||||
|
detail.parent_id.path,
|
||||||
|
vec!["力学".to_string(), "计算力".to_string()]
|
||||||
|
);
|
||||||
|
assert_eq!(calc.parent_id.path, vec!["力学".to_string()]);
|
||||||
|
let root = &index.units[0];
|
||||||
|
assert_eq!(root.span, marqdo_span::Span::new(0, source.len()));
|
||||||
|
assert_eq!(
|
||||||
|
calc.parent_id,
|
||||||
|
index
|
||||||
|
.units
|
||||||
|
.iter()
|
||||||
|
.find(|u| u.name == "力学")
|
||||||
|
.unwrap()
|
||||||
|
.id
|
||||||
|
.clone()
|
||||||
|
);
|
||||||
|
assert_eq!(by_name("力学").parent_id, root.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mode_origin_and_source_are_explicit() {
|
||||||
|
let index = index_of(
|
||||||
|
"# @knowledge 数学\n\n## @exec 计算\n\n### 细节\n\n`return 1`\n\n## 说明\n\n正文\n",
|
||||||
|
);
|
||||||
|
let by_name = |name: &str| {
|
||||||
|
index
|
||||||
|
.headings
|
||||||
|
.iter()
|
||||||
|
.find(|heading| heading.name == name)
|
||||||
|
.unwrap_or_else(|| panic!("missing heading {name}"))
|
||||||
|
};
|
||||||
|
let namespace = by_name("数学");
|
||||||
|
assert_eq!(namespace.mode_origin, ModeOrigin::Explicit);
|
||||||
|
assert_eq!(
|
||||||
|
namespace.mode_source_unit_id,
|
||||||
|
namespace_unit(&index, "数学")
|
||||||
|
);
|
||||||
|
let calc = by_name("计算");
|
||||||
|
assert_eq!(calc.mode_origin, ModeOrigin::Explicit);
|
||||||
|
assert_eq!(
|
||||||
|
calc.mode_source_unit_id.path,
|
||||||
|
vec!["数学".to_string(), "计算".to_string()]
|
||||||
|
);
|
||||||
|
let detail = by_name("细节");
|
||||||
|
assert_eq!(detail.mode_origin, ModeOrigin::Inherited);
|
||||||
|
assert_eq!(
|
||||||
|
detail.mode_source_unit_id.path,
|
||||||
|
calc.mode_source_unit_id.path
|
||||||
|
);
|
||||||
|
let note = by_name("说明");
|
||||||
|
assert_eq!(note.mode_origin, ModeOrigin::Inherited);
|
||||||
|
assert_eq!(note.mode_source_unit_id.path, vec!["数学".to_string()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn namespace_unit(index: &UnitIndex, name: &str) -> UnitId {
|
||||||
|
index
|
||||||
|
.units
|
||||||
|
.iter()
|
||||||
|
.find(|unit| unit.name == name)
|
||||||
|
.map(|unit| unit.id.clone())
|
||||||
|
.expect("namespace unit")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dot_in_a_function_component_is_rejected_as_an_ambiguous_identity() {
|
||||||
|
let index = index_of("# @knowledge a.b\n\n## @exec f\n\n`return 1`\n");
|
||||||
|
assert!(index
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|diagnostic| diagnostic.code == "sem.ambiguous_identity"));
|
||||||
|
let index = index_of("## @exec a.b\n\n`return 1`\n");
|
||||||
|
assert!(index
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|diagnostic| diagnostic.code == "sem.ambiguous_identity"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn innermost_unit_owns_a_linked_span() {
|
||||||
|
let source = "前置说明。\n\n# @knowledge 数学\n\n## @exec 计算\n\n见[链接](#细节)。\n\n### 细节\n\n`return 1`\n";
|
||||||
|
let index = index_of(source);
|
||||||
|
let link_start = source.find("[链接]").unwrap();
|
||||||
|
let owner = index
|
||||||
|
.unit_containing_span(Span::new(link_start, link_start + 2))
|
||||||
|
.expect("owning unit");
|
||||||
|
assert_eq!(owner.path, vec!["数学".to_string(), "计算".to_string()]);
|
||||||
|
let root = index.unit_containing_span(Span::new(0, 1)).expect("root");
|
||||||
|
assert!(root.path.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn knowledge_scope_payloads_and_sections_stay_inert() {
|
fn knowledge_scope_payloads_and_sections_stay_inert() {
|
||||||
let index = index_of(
|
let index = index_of(
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[package]
|
||||||
|
name = "marqdo-host-contract"
|
||||||
|
description = "Platform-neutral Host contract: the only side-effect boundary the runtime may know"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
marqdo-span = { workspace = true }
|
||||||
|
marqdo-value = { workspace = true }
|
||||||
File renamed without changes.
@@ -0,0 +1,194 @@
|
|||||||
|
//! The host boundary used by the interpreter and future frontends.
|
||||||
|
//!
|
||||||
|
//! The trait is implemented by the native CLI host, by the independent
|
||||||
|
//! embedding/test host and by any future host. Implementations own effects,
|
||||||
|
//! grants and budgets; the runtime only requests operations through this
|
||||||
|
//! interface and never performs external I/O itself.
|
||||||
|
|
||||||
|
use marqdo_span::Span;
|
||||||
|
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
||||||
|
|
||||||
|
use crate::context::ExecutionContext;
|
||||||
|
use crate::observe::{FrameId, RuntimeObservation};
|
||||||
|
use crate::resource::ResourceRead;
|
||||||
|
|
||||||
|
/// Host operations reachable from the language surface.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum HostOp {
|
||||||
|
/// One-shot foreign execution.
|
||||||
|
ForeignRun,
|
||||||
|
/// Typed foreign call.
|
||||||
|
ForeignCall,
|
||||||
|
/// Read a project file.
|
||||||
|
FsRead,
|
||||||
|
/// Write a project file.
|
||||||
|
FsWrite,
|
||||||
|
/// Invoke a plugin export.
|
||||||
|
PluginInvoke,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostOp {
|
||||||
|
/// Stable operation name used in traces and diagnostics.
|
||||||
|
pub const fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
HostOp::ForeignRun => "foreign.run",
|
||||||
|
HostOp::ForeignCall => "foreign.call",
|
||||||
|
HostOp::FsRead => "fs.read",
|
||||||
|
HostOp::FsWrite => "fs.write",
|
||||||
|
HostOp::PluginInvoke => "plugin.invoke",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host boundary used by the interpreter and future View/IDE frontends.
|
||||||
|
pub trait Host {
|
||||||
|
/// Invoke one operation with already-evaluated arguments.
|
||||||
|
fn invoke(
|
||||||
|
&mut self,
|
||||||
|
op: HostOp,
|
||||||
|
args: Vec<Value>,
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<Value, RuntimeError>;
|
||||||
|
|
||||||
|
/// Open a resource/stream by kind, descriptor and requested rights.
|
||||||
|
///
|
||||||
|
/// Default: unavailable. Only the standard host implements the first
|
||||||
|
/// resource kinds (ADR-0025).
|
||||||
|
fn resource_open(
|
||||||
|
&mut self,
|
||||||
|
_kind: &str,
|
||||||
|
_descriptor: &str,
|
||||||
|
_rights: &[String],
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<Value, RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide resource streams",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read up to `max_bytes` from a resource into host memory.
|
||||||
|
fn resource_read(
|
||||||
|
&mut self,
|
||||||
|
_handle: ResourceHandle,
|
||||||
|
_max_bytes: usize,
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<ResourceRead, RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide resource streams",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write bytes to a resource; returns the accepted count.
|
||||||
|
fn resource_write(
|
||||||
|
&mut self,
|
||||||
|
_handle: ResourceHandle,
|
||||||
|
_bytes: &[u8],
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<usize, RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide resource streams",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a resource handle.
|
||||||
|
fn resource_close(
|
||||||
|
&mut self,
|
||||||
|
_handle: ResourceHandle,
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<(), RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide resource streams",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept one inbound TCP connection from a `tcp-listener` handle.
|
||||||
|
///
|
||||||
|
/// Default: unavailable. The standard host returns a new `Resource` in a
|
||||||
|
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
|
||||||
|
fn resource_accept(
|
||||||
|
&mut self,
|
||||||
|
_handle: ResourceHandle,
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<Value, RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide tcp listeners",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute one non-streaming resource operation (ADR-0041).
|
||||||
|
///
|
||||||
|
/// Default: unavailable. The standard host implements the `fs.*` group;
|
||||||
|
/// every call is capability-checked and project-mode only.
|
||||||
|
fn resource_request(
|
||||||
|
&mut self,
|
||||||
|
_operation: &str,
|
||||||
|
_args: Vec<Value>,
|
||||||
|
ctx: &ExecutionContext,
|
||||||
|
) -> Result<Value, RuntimeError> {
|
||||||
|
Err(RuntimeError::new(
|
||||||
|
ErrorCategory::ResourceUnsupported,
|
||||||
|
ctx.span,
|
||||||
|
"this host does not provide resource operations",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume evaluation fuel.
|
||||||
|
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
|
||||||
|
|
||||||
|
/// Check call-stack depth.
|
||||||
|
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
|
||||||
|
|
||||||
|
/// Check the wall-clock deadline.
|
||||||
|
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
|
||||||
|
|
||||||
|
/// Take the buffered program output.
|
||||||
|
fn take_output(&mut self) -> Vec<u8>;
|
||||||
|
|
||||||
|
/// Whether the host has an installed observation sink.
|
||||||
|
///
|
||||||
|
/// The default host is inert; the interpreter uses this to skip building
|
||||||
|
/// any observation event when there is no capture destination.
|
||||||
|
fn observation_enabled(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Announce a successfully bound call frame.
|
||||||
|
///
|
||||||
|
/// Returns the run-unique frame identity, or `None` when observation is
|
||||||
|
/// disabled. Argument binding must have completed before this is called;
|
||||||
|
/// a binding failure never produces a frame.
|
||||||
|
fn observation_begin_frame(
|
||||||
|
&mut self,
|
||||||
|
_function_id: &str,
|
||||||
|
_module_id: &str,
|
||||||
|
_span: Option<Span>,
|
||||||
|
) -> Result<Option<FrameId>, RuntimeError> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a previously announced frame, including failure paths.
|
||||||
|
fn observation_end_frame(
|
||||||
|
&mut self,
|
||||||
|
_frame_id: Option<FrameId>,
|
||||||
|
_status: &str,
|
||||||
|
_module_id: &str,
|
||||||
|
_span: Option<Span>,
|
||||||
|
) -> Result<(), RuntimeError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emit one borrowed runtime observation event. Default: ignored.
|
||||||
|
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
//! Platform-neutral Host contract.
|
||||||
|
//!
|
||||||
|
//! This crate owns the only side-effect interface the language engine knows:
|
||||||
|
//! the [`Host`] trait, its [`HostOp`] surface, the per-call
|
||||||
|
//! [`ExecutionContext`], the opaque resource read result and the runtime
|
||||||
|
//! observation notifications. It is a Rust compile-time interface inside one
|
||||||
|
//! codebase, not a wire protocol: there is no HTTP, RPC, C ABI or dynamic
|
||||||
|
//! loading boundary here.
|
||||||
|
//!
|
||||||
|
//! The crate is deliberately neutral. It depends only on the language value
|
||||||
|
//! and span types; it must never link the native host, the CLI, the sandbox,
|
||||||
|
//! foreign kernels, the plugin loader or a project filesystem. Native and
|
||||||
|
//! embedded hosts implement [`Host`] without re-implementing any language
|
||||||
|
//! semantics. Authorization, budgets, resource identity and OS isolation stay
|
||||||
|
//! owned by the trusted host implementation that consumes this contract.
|
||||||
|
|
||||||
|
pub mod context;
|
||||||
|
pub mod host;
|
||||||
|
pub mod observe;
|
||||||
|
pub mod resource;
|
||||||
|
|
||||||
|
pub use context::ExecutionContext;
|
||||||
|
pub use host::{Host, HostOp};
|
||||||
|
pub use observe::{FrameId, LoopTransfer, ParameterSource, RuntimeObservation};
|
||||||
|
pub use resource::ResourceRead;
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
//! Runtime observation facts shared by the interpreter and the host contract.
|
||||||
|
//!
|
||||||
|
//! Only the types the interpreter itself produces and hands to [`crate::Host`]
|
||||||
|
//! live here. The host implementation keeps the concrete sink, redaction,
|
||||||
|
//! encoding and budget state; the public Observation protocol remains the
|
||||||
|
//! CLI's single producer. This module must not grow a second event vocabulary.
|
||||||
|
|
||||||
|
use marqdo_span::Span;
|
||||||
|
use marqdo_value::Value;
|
||||||
|
|
||||||
|
/// Opaque run-scoped call-instance identity.
|
||||||
|
///
|
||||||
|
/// Not a function identity, not a source location and never a memory pointer.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
pub struct FrameId(pub u64);
|
||||||
|
|
||||||
|
impl FrameId {
|
||||||
|
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
|
||||||
|
pub fn as_wire(self) -> String {
|
||||||
|
format!("f{}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a bound parameter's value came from.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ParameterSource {
|
||||||
|
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
|
||||||
|
Provided,
|
||||||
|
/// Evaluated from the declared default expression.
|
||||||
|
Default,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ParameterSource {
|
||||||
|
/// Stable wire name.
|
||||||
|
pub const fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ParameterSource::Provided => "provided",
|
||||||
|
ParameterSource::Default => "default",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The action carried by a structured loop transfer observation.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LoopTransfer {
|
||||||
|
/// Exit the enclosing loop.
|
||||||
|
Break,
|
||||||
|
/// Proceed to the enclosing loop's next condition check.
|
||||||
|
Continue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LoopTransfer {
|
||||||
|
/// The event kind in Observation.
|
||||||
|
pub fn event_kind(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Break => "control.break",
|
||||||
|
Self::Continue => "control.continue",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
|
||||||
|
///
|
||||||
|
/// Value and control observations carry the owning call frame.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum RuntimeObservation<'a> {
|
||||||
|
/// A local memory operation committed.
|
||||||
|
Effect {
|
||||||
|
operation: &'a str,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
/// A `return` statement committed (before the call exits).
|
||||||
|
Return {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
value_type: &'a str,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
/// A branch condition evaluated.
|
||||||
|
BranchEval {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
result: bool,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
/// A loop condition evaluated.
|
||||||
|
LoopIteration {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
decision: &'a str,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
/// An explicit loop control statement executed.
|
||||||
|
LoopTransfer {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
transfer: LoopTransfer,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Span,
|
||||||
|
},
|
||||||
|
/// A local variable assignment committed.
|
||||||
|
VariableAssigned {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
name: &'a str,
|
||||||
|
value: &'a Value,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
/// A parameter was bound.
|
||||||
|
ParameterBound {
|
||||||
|
frame_id: Option<FrameId>,
|
||||||
|
name: &'a str,
|
||||||
|
source: ParameterSource,
|
||||||
|
value: &'a Value,
|
||||||
|
module_id: &'a str,
|
||||||
|
span: Option<Span>,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
//! Values crossing the resource stream methods of [`crate::Host`].
|
||||||
|
|
||||||
|
/// Bytes returned by one stream read.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ResourceRead {
|
||||||
|
/// Bytes actually read (may be empty at EOF).
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
/// Whether the stream has reached EOF.
|
||||||
|
pub eof: bool,
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ authors.workspace = true
|
|||||||
libloading = { workspace = true }
|
libloading = { workspace = true }
|
||||||
rustls = { workspace = true }
|
rustls = { workspace = true }
|
||||||
rustls-native-certs = { workspace = true }
|
rustls-native-certs = { workspace = true }
|
||||||
|
marqdo-host-contract = { workspace = true }
|
||||||
marqdo-plugin-abi = { workspace = true }
|
marqdo-plugin-abi = { workspace = true }
|
||||||
marqdo-worker-ipc = { workspace = true }
|
marqdo-worker-ipc = { workspace = true }
|
||||||
flate2 = { workspace = true }
|
flate2 = { workspace = true }
|
||||||
@@ -23,6 +24,9 @@ marqdo-value = { workspace = true }
|
|||||||
marqdo-foreign = { workspace = true }
|
marqdo-foreign = { workspace = true }
|
||||||
marqdo-sandbox = { workspace = true }
|
marqdo-sandbox = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
|
sha2 = { workspace = true }
|
||||||
|
hex = { workspace = true }
|
||||||
|
serde_yaml = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
|
|
||||||
|
|||||||
+15
-194
@@ -9,27 +9,30 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use marqdo_plugin_abi::{
|
use crate::plugin::{
|
||||||
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
|
CapabilityHandler, HostTarget, LoadOptions, LoadedPlugin, PluginKind, PluginManifest,
|
||||||
};
|
};
|
||||||
|
use marqdo_host_contract::{
|
||||||
|
ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
|
||||||
|
};
|
||||||
|
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, PluginError};
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
||||||
use rustls::pki_types::CertificateDer;
|
use rustls::pki_types::CertificateDer;
|
||||||
|
|
||||||
use crate::budget::Budget;
|
use crate::budget::Budget;
|
||||||
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
||||||
use crate::context::ExecutionContext;
|
|
||||||
use crate::fs::ProjectFs;
|
use crate::fs::ProjectFs;
|
||||||
use crate::handles::{contains_plugin_handle, PluginHandleTable};
|
use crate::handles::{contains_plugin_handle, PluginHandleTable};
|
||||||
use crate::observe::{
|
use crate::observe::{
|
||||||
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
|
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
|
||||||
ObservationEvent, ObservationSink, ObservationState, RuntimeObservation,
|
ObservationSink, ObservationState,
|
||||||
};
|
};
|
||||||
use crate::plugin_worker::WorkerPlugin;
|
use crate::plugin_worker::WorkerPlugin;
|
||||||
use crate::provider_c::{load_package, CResourceProvider};
|
use crate::provider_c::{load_package, CResourceProvider};
|
||||||
use crate::provider_worker::WorkerResourceProvider;
|
use crate::provider_worker::WorkerResourceProvider;
|
||||||
use crate::resource::{
|
use crate::resource::{
|
||||||
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
|
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
|
||||||
};
|
};
|
||||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
||||||
|
|
||||||
@@ -38,187 +41,6 @@ mod providers;
|
|||||||
mod resource_ops;
|
mod resource_ops;
|
||||||
mod resource_requests;
|
mod resource_requests;
|
||||||
|
|
||||||
/// Host operations reachable from the language surface.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum HostOp {
|
|
||||||
/// One-shot foreign execution.
|
|
||||||
ForeignRun,
|
|
||||||
/// Typed foreign call.
|
|
||||||
ForeignCall,
|
|
||||||
/// Read a project file.
|
|
||||||
FsRead,
|
|
||||||
/// Write a project file.
|
|
||||||
FsWrite,
|
|
||||||
/// Invoke a plugin export.
|
|
||||||
PluginInvoke,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HostOp {
|
|
||||||
/// Stable operation name used in traces and diagnostics.
|
|
||||||
pub const fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
HostOp::ForeignRun => "foreign.run",
|
|
||||||
HostOp::ForeignCall => "foreign.call",
|
|
||||||
HostOp::FsRead => "fs.read",
|
|
||||||
HostOp::FsWrite => "fs.write",
|
|
||||||
HostOp::PluginInvoke => "plugin.invoke",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The host boundary used by the interpreter and future View/IDE frontends.
|
|
||||||
pub trait Host {
|
|
||||||
/// Invoke one operation with already-evaluated arguments.
|
|
||||||
fn invoke(
|
|
||||||
&mut self,
|
|
||||||
op: HostOp,
|
|
||||||
args: Vec<Value>,
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<Value, RuntimeError>;
|
|
||||||
|
|
||||||
/// Open a resource/stream by kind, descriptor and requested rights.
|
|
||||||
///
|
|
||||||
/// Default: unavailable. Only the standard host implements the first
|
|
||||||
/// resource kinds (ADR-0025).
|
|
||||||
fn resource_open(
|
|
||||||
&mut self,
|
|
||||||
_kind: &str,
|
|
||||||
_descriptor: &str,
|
|
||||||
_rights: &[String],
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<Value, RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide resource streams",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Read up to `max_bytes` from a resource into host memory.
|
|
||||||
fn resource_read(
|
|
||||||
&mut self,
|
|
||||||
_handle: ResourceHandle,
|
|
||||||
_max_bytes: usize,
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<ResourceRead, RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide resource streams",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Write bytes to a resource; returns the accepted count.
|
|
||||||
fn resource_write(
|
|
||||||
&mut self,
|
|
||||||
_handle: ResourceHandle,
|
|
||||||
_bytes: &[u8],
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<usize, RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide resource streams",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close a resource handle.
|
|
||||||
fn resource_close(
|
|
||||||
&mut self,
|
|
||||||
_handle: ResourceHandle,
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<(), RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide resource streams",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Accept one inbound TCP connection from a `tcp-listener` handle.
|
|
||||||
///
|
|
||||||
/// Default: unavailable. The standard host returns a new `Resource` in a
|
|
||||||
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
|
|
||||||
fn resource_accept(
|
|
||||||
&mut self,
|
|
||||||
_handle: ResourceHandle,
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<Value, RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide tcp listeners",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute one non-streaming resource operation (ADR-0041).
|
|
||||||
///
|
|
||||||
/// Default: unavailable. The standard host implements the `fs.*` group;
|
|
||||||
/// every call is capability-checked and project-mode only.
|
|
||||||
fn resource_request(
|
|
||||||
&mut self,
|
|
||||||
_operation: &str,
|
|
||||||
_args: Vec<Value>,
|
|
||||||
ctx: &ExecutionContext,
|
|
||||||
) -> Result<Value, RuntimeError> {
|
|
||||||
Err(RuntimeError::new(
|
|
||||||
ErrorCategory::ResourceUnsupported,
|
|
||||||
ctx.span,
|
|
||||||
"this host does not provide resource operations",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Consume evaluation fuel.
|
|
||||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
|
|
||||||
|
|
||||||
/// Check call-stack depth.
|
|
||||||
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
|
|
||||||
|
|
||||||
/// Check the wall-clock deadline.
|
|
||||||
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
|
|
||||||
|
|
||||||
/// Take the buffered program output.
|
|
||||||
fn take_output(&mut self) -> Vec<u8>;
|
|
||||||
|
|
||||||
/// Whether the host has an installed observation sink.
|
|
||||||
///
|
|
||||||
/// The default host is inert; the interpreter uses this to skip building
|
|
||||||
/// any observation event when there is no capture destination.
|
|
||||||
fn observation_enabled(&self) -> bool {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Announce a successfully bound call frame.
|
|
||||||
///
|
|
||||||
/// Returns the run-unique frame identity, or `None` when observation is
|
|
||||||
/// disabled. Argument binding must have completed before this is called;
|
|
||||||
/// a binding failure never produces a frame.
|
|
||||||
fn observation_begin_frame(
|
|
||||||
&mut self,
|
|
||||||
_function_id: &str,
|
|
||||||
_module_id: &str,
|
|
||||||
_span: Option<Span>,
|
|
||||||
) -> Result<Option<FrameId>, RuntimeError> {
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close a previously announced frame, including failure paths.
|
|
||||||
fn observation_end_frame(
|
|
||||||
&mut self,
|
|
||||||
_frame_id: Option<FrameId>,
|
|
||||||
_status: &str,
|
|
||||||
_module_id: &str,
|
|
||||||
_span: Option<Span>,
|
|
||||||
) -> Result<(), RuntimeError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Emit one borrowed runtime observation event. Default: ignored.
|
|
||||||
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Default capability host implementation.
|
/// Default capability host implementation.
|
||||||
pub struct StdHost {
|
pub struct StdHost {
|
||||||
/// Requested sandbox mode.
|
/// Requested sandbox mode.
|
||||||
@@ -372,7 +194,7 @@ impl StdHost {
|
|||||||
exports.insert(export.name.clone(), export.signature.clone());
|
exports.insert(export.name.clone(), export.signature.clone());
|
||||||
}
|
}
|
||||||
let artifact = manifest
|
let artifact = manifest
|
||||||
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current())
|
.resolve_artifact(&HostTarget::current())
|
||||||
.map_err(map_plugin_error)?;
|
.map_err(map_plugin_error)?;
|
||||||
let manifest_digest = artifact.sha256.clone();
|
let manifest_digest = artifact.sha256.clone();
|
||||||
let transport = match manifest.plugin.kind {
|
let transport = match manifest.plugin.kind {
|
||||||
@@ -398,8 +220,8 @@ impl StdHost {
|
|||||||
broker.allow_vendor(capability.clone());
|
broker.allow_vendor(capability.clone());
|
||||||
}
|
}
|
||||||
let package = manifest.plugin.name.clone();
|
let package = manifest.plugin.name.clone();
|
||||||
let options = marqdo_plugin_abi::LoadOptions {
|
let options = LoadOptions {
|
||||||
host_target: marqdo_plugin_abi::HostTarget::current(),
|
host_target: HostTarget::current(),
|
||||||
capability_handler: Some(Box::new(move |capability, request| {
|
capability_handler: Some(Box::new(move |capability, request| {
|
||||||
broker.execute(&package, capability, request)
|
broker.execute(&package, capability, request)
|
||||||
})),
|
})),
|
||||||
@@ -419,10 +241,9 @@ impl StdHost {
|
|||||||
broker.allow_vendor(capability.clone());
|
broker.allow_vendor(capability.clone());
|
||||||
}
|
}
|
||||||
let package = manifest.plugin.name.clone();
|
let package = manifest.plugin.name.clone();
|
||||||
let handler: marqdo_plugin_abi::CapabilityHandler =
|
let handler: CapabilityHandler = Box::new(move |capability, request| {
|
||||||
Box::new(move |capability, request| {
|
broker.execute(&package, capability, request)
|
||||||
broker.execute(&package, capability, request)
|
});
|
||||||
});
|
|
||||||
PluginTransport::Worker(
|
PluginTransport::Worker(
|
||||||
WorkerPlugin::spawn(manifest, base_dir, Some(handler))
|
WorkerPlugin::spawn(manifest, base_dir, Some(handler))
|
||||||
.map_err(map_plugin_error)?,
|
.map_err(map_plugin_error)?,
|
||||||
|
|||||||
@@ -516,7 +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.observe_effect("resource.request", "ok", ctx);
|
self.observe_effect(&format!("fs.{name}"), "ok", ctx);
|
||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
|
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
|
||||||
|
|
||||||
use crate::context::ExecutionContext;
|
use crate::host::StdHost;
|
||||||
use crate::host::{HostOp, StdHost};
|
use marqdo_host_contract::{ExecutionContext, HostOp};
|
||||||
|
|
||||||
pub(crate) fn foreign(
|
pub(crate) fn foreign(
|
||||||
host: &mut StdHost,
|
host: &mut StdHost,
|
||||||
|
|||||||
@@ -1,17 +1,28 @@
|
|||||||
//! CapabilityHost: capability checks, resource budgets, observation and the
|
//! Native Host: the one concrete implementation of the neutral
|
||||||
//! only bridge to math, foreign kernels, files and plugins.
|
//! [`marqdo_host_contract::Host`] boundary.
|
||||||
//!
|
//!
|
||||||
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks
|
//! Every side effect goes through this crate, checks happen at the point of
|
||||||
//! happen at the point of execution, and host failures are structured errors.
|
//! execution, and host failures are structured errors. The crate owns the OS
|
||||||
|
//! adapters, capability grants, resource handles, observation sink and trusted
|
||||||
|
//! extension execution; it never owns language semantics and never depends back
|
||||||
|
//! on the runtime, frontend or IR.
|
||||||
|
//!
|
||||||
|
//! Responsibility map (ADR-0071):
|
||||||
|
//! - [`capability`]/[`budget`]: grants, broker, audit, fuel/stack/deadline/output;
|
||||||
|
//! - [`resource`], [`fs`], `process`: resource kinds, handles and OS effects;
|
||||||
|
//! - [`plugin`], `plugin_worker`, `provider_c`, `provider_worker`, [`kernels`]:
|
||||||
|
//! trusted plugin/provider/foreign execution (no second static binder);
|
||||||
|
//! - [`observe`]: the runtime observation sink, redaction, budget and encoding;
|
||||||
|
//! - [`host`]: `StdHost` assembly and the single dispatch table.
|
||||||
|
|
||||||
pub mod budget;
|
pub mod budget;
|
||||||
pub mod capability;
|
pub mod capability;
|
||||||
pub mod context;
|
|
||||||
pub mod fs;
|
pub mod fs;
|
||||||
pub mod handles;
|
pub mod handles;
|
||||||
pub mod host;
|
pub mod host;
|
||||||
pub mod kernels;
|
pub mod kernels;
|
||||||
pub mod observe;
|
pub mod observe;
|
||||||
|
pub mod plugin;
|
||||||
mod plugin_worker;
|
mod plugin_worker;
|
||||||
mod process;
|
mod process;
|
||||||
mod provider_c;
|
mod provider_c;
|
||||||
@@ -23,18 +34,16 @@ pub use capability::{
|
|||||||
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
|
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
|
||||||
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
|
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
|
||||||
};
|
};
|
||||||
pub use context::ExecutionContext;
|
|
||||||
pub use fs::ProjectFs;
|
pub use fs::ProjectFs;
|
||||||
pub use handles::{contains_plugin_handle, PluginHandleTable};
|
pub use handles::{contains_plugin_handle, PluginHandleTable};
|
||||||
pub use host::{arity, expect_text, Host, HostOp, StdHost};
|
pub use host::{arity, expect_text, StdHost};
|
||||||
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
|
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
|
||||||
pub use observe::{
|
pub use observe::{
|
||||||
encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
|
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
|
||||||
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
|
ObservationSink, ObservedValue, ValueState, DEFAULT_MAX_OBSERVATION_BYTES,
|
||||||
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
|
||||||
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
|
|
||||||
};
|
};
|
||||||
pub use resource::{
|
pub use resource::{
|
||||||
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
|
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
|
||||||
CORE_RESOURCE_KINDS,
|
CORE_RESOURCE_KINDS,
|
||||||
};
|
};
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use marqdo_host_contract::{FrameId, LoopTransfer, ParameterSource};
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||||
|
|
||||||
@@ -24,38 +25,6 @@ pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
|
|||||||
/// Maximum committed stdio bytes carried by one chunk event.
|
/// Maximum committed stdio bytes carried by one chunk event.
|
||||||
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
|
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
|
||||||
|
|
||||||
/// Opaque run-scoped call-instance identity.
|
|
||||||
///
|
|
||||||
/// Not a function identity, not a source location and never a memory pointer.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct FrameId(pub u64);
|
|
||||||
|
|
||||||
impl FrameId {
|
|
||||||
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
|
|
||||||
pub fn as_wire(self) -> String {
|
|
||||||
format!("f{}", self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a bound parameter's value came from.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum ParameterSource {
|
|
||||||
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
|
|
||||||
Provided,
|
|
||||||
/// Evaluated from the declared default expression.
|
|
||||||
Default,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ParameterSource {
|
|
||||||
/// Stable wire name.
|
|
||||||
pub const fn as_str(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
ParameterSource::Provided => "provided",
|
|
||||||
ParameterSource::Default => "default",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Observation policy for one run.
|
/// Observation policy for one run.
|
||||||
///
|
///
|
||||||
/// `structural` always implies frame identity; value events only exist for
|
/// `structural` always implies frame identity; value events only exist for
|
||||||
@@ -238,83 +207,6 @@ pub enum ObservationEvent<'a> {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The action carried by a structured loop transfer observation.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum LoopTransfer {
|
|
||||||
/// Exit the enclosing loop.
|
|
||||||
Break,
|
|
||||||
/// Proceed to the enclosing loop's next condition check.
|
|
||||||
Continue,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LoopTransfer {
|
|
||||||
/// The event kind in Observation.
|
|
||||||
pub fn event_kind(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::Break => "control.break",
|
|
||||||
Self::Continue => "control.continue",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
|
|
||||||
///
|
|
||||||
/// Value and control observations carry the owning call frame.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum RuntimeObservation<'a> {
|
|
||||||
/// A local memory operation committed.
|
|
||||||
Effect {
|
|
||||||
operation: &'a str,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
/// A `return` statement committed (before the call exits).
|
|
||||||
Return {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
value_type: &'a str,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
/// A branch condition evaluated.
|
|
||||||
BranchEval {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
result: bool,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
/// A loop condition evaluated.
|
|
||||||
LoopIteration {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
decision: &'a str,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
/// An explicit loop control statement executed.
|
|
||||||
LoopTransfer {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
transfer: LoopTransfer,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Span,
|
|
||||||
},
|
|
||||||
/// A local variable assignment committed.
|
|
||||||
VariableAssigned {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
name: &'a str,
|
|
||||||
value: &'a Value,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
/// A parameter was bound.
|
|
||||||
ParameterBound {
|
|
||||||
frame_id: Option<FrameId>,
|
|
||||||
name: &'a str,
|
|
||||||
source: ParameterSource,
|
|
||||||
value: &'a Value,
|
|
||||||
module_id: &'a str,
|
|
||||||
span: Option<Span>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sink installed by the composition root (the CLI JSONL writer in product
|
/// Sink installed by the composition root (the CLI JSONL writer in product
|
||||||
/// builds, an in-memory recorder in tests).
|
/// builds, an in-memory recorder in tests).
|
||||||
pub trait ObservationSink {
|
pub trait ObservationSink {
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::error::PluginError;
|
use marqdo_plugin_abi::PluginError;
|
||||||
|
|
||||||
/// Length of a lowercase hexadecimal sha256 digest.
|
/// Length of a lowercase hexadecimal sha256 digest.
|
||||||
pub const SHA256_HEX_LEN: usize = 64;
|
pub const SHA256_HEX_LEN: usize = 64;
|
||||||
@@ -16,16 +16,16 @@ use std::ptr;
|
|||||||
use libloading::{Library, Symbol};
|
use libloading::{Library, Symbol};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::abi::{
|
use super::artifact::HostTarget;
|
||||||
|
use super::manifest::{PluginKind, PluginManifest};
|
||||||
|
use marqdo_plugin_abi::abi::{
|
||||||
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
|
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
|
||||||
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
|
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
|
||||||
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
|
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
|
||||||
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
|
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
|
||||||
};
|
};
|
||||||
use crate::artifact::HostTarget;
|
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
|
||||||
use crate::error::PluginError;
|
use marqdo_plugin_abi::PluginError;
|
||||||
use crate::manifest::{PluginKind, PluginManifest};
|
|
||||||
use crate::wire::{WireRequest, WireResponse};
|
|
||||||
|
|
||||||
/// A callback the host installs to answer capability requests from a plugin.
|
/// A callback the host installs to answer capability requests from a plugin.
|
||||||
///
|
///
|
||||||
@@ -304,13 +304,13 @@ impl LoadedPlugin {
|
|||||||
/// This is primarily for ABI conformance tests; prefer
|
/// This is primarily for ABI conformance tests; prefer
|
||||||
/// [`LoadedPlugin::invoke`] for normal use.
|
/// [`LoadedPlugin::invoke`] for normal use.
|
||||||
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
|
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
|
||||||
if args_wire.len() > crate::abi::MAX_REQUEST_WIRE_BYTES {
|
if args_wire.len() > marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES {
|
||||||
return Err(PluginError::wire(
|
return Err(PluginError::wire(
|
||||||
"request_too_large",
|
"request_too_large",
|
||||||
format!(
|
format!(
|
||||||
"request wire is {} bytes, limit is {}",
|
"request wire is {} bytes, limit is {}",
|
||||||
args_wire.len(),
|
args_wire.len(),
|
||||||
crate::abi::MAX_REQUEST_WIRE_BYTES
|
marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES
|
||||||
),
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
+6
-6
@@ -10,12 +10,12 @@ use std::path::{Component, Path, PathBuf};
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::abi::{
|
use super::artifact::{is_valid_sha256_hex, TargetTriple};
|
||||||
|
use super::artifact::{verify_sha256_file, HostTarget};
|
||||||
|
use marqdo_plugin_abi::abi::{
|
||||||
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
|
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
|
||||||
};
|
};
|
||||||
use crate::artifact::{is_valid_sha256_hex, TargetTriple};
|
use marqdo_plugin_abi::PluginError;
|
||||||
use crate::artifact::{verify_sha256_file, HostTarget};
|
|
||||||
use crate::error::PluginError;
|
|
||||||
|
|
||||||
/// Maximum number of exports a single plugin may register.
|
/// Maximum number of exports a single plugin may register.
|
||||||
pub const MAX_EXPORTS: usize = 256;
|
pub const MAX_EXPORTS: usize = 256;
|
||||||
@@ -648,7 +648,7 @@ plugin:
|
|||||||
#[test]
|
#[test]
|
||||||
fn malformed_yaml_is_rejected() {
|
fn malformed_yaml_is_rejected() {
|
||||||
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
|
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
|
||||||
assert_eq!(error.kind, crate::error::ErrorKind::Manifest);
|
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Manifest);
|
||||||
assert_eq!(error.code, "manifest_parse_failed");
|
assert_eq!(error.code, "manifest_parse_failed");
|
||||||
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
|
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
|
||||||
}
|
}
|
||||||
@@ -683,7 +683,7 @@ plugin:
|
|||||||
),
|
),
|
||||||
Err(error) => assert_eq!(
|
Err(error) => assert_eq!(
|
||||||
error.kind,
|
error.kind,
|
||||||
crate::error::ErrorKind::Manifest,
|
marqdo_plugin_abi::ErrorKind::Manifest,
|
||||||
"`{field}` = `{value}` should fail manifest handling"
|
"`{field}` = `{value}` should fail manifest handling"
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//! Execution side of the Callable Plugin ABI: manifest/artifact validation,
|
||||||
|
//! native loading, invocation dispatch and the worker process.
|
||||||
|
//!
|
||||||
|
//! The public contract (C layout, wire envelope and protocol errors) lives in
|
||||||
|
//! `marqdo-plugin-abi`; this module owns `dlopen`, process spawning, artifact
|
||||||
|
//! file selection and trusted invocation. The CLI may consume the static
|
||||||
|
//! descriptor types for `check`/`inspect` preparation, but preparation never
|
||||||
|
//! loads a library or starts a process.
|
||||||
|
//!
|
||||||
|
//! The `include/marqdo_plugin_abi_v1.h` header and the Rust layout assertions
|
||||||
|
//! in `marqdo_plugin_abi::abi` remain the single ABI authority.
|
||||||
|
|
||||||
|
pub mod artifact;
|
||||||
|
pub mod loader;
|
||||||
|
pub mod manifest;
|
||||||
|
pub mod worker;
|
||||||
|
|
||||||
|
pub use artifact::{
|
||||||
|
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
|
||||||
|
HostTarget, TargetTriple,
|
||||||
|
};
|
||||||
|
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
|
||||||
|
pub use manifest::{
|
||||||
|
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
|
||||||
|
KNOWN_CAPABILITIES,
|
||||||
|
};
|
||||||
@@ -13,10 +13,10 @@ use std::sync::{Arc, Mutex};
|
|||||||
|
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
use crate::error::PluginError;
|
use super::loader::{LoadOptions, LoadedPlugin};
|
||||||
use crate::loader::{LoadOptions, LoadedPlugin};
|
use super::manifest::{PluginKind, PluginManifest};
|
||||||
use crate::manifest::{PluginKind, PluginManifest};
|
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
|
||||||
use crate::wire::{WireRequest, WireResponse};
|
use marqdo_plugin_abi::PluginError;
|
||||||
|
|
||||||
/// Hidden CLI command name used to start a worker.
|
/// Hidden CLI command name used to start a worker.
|
||||||
pub const WORKER_COMMAND: &str = "__plugin-worker";
|
pub const WORKER_COMMAND: &str = "__plugin-worker";
|
||||||
@@ -91,7 +91,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
|
|||||||
let handler_stdout = Arc::clone(&stdout);
|
let handler_stdout = Arc::clone(&stdout);
|
||||||
let handler_ids = Arc::clone(&next_request_id);
|
let handler_ids = Arc::clone(&next_request_id);
|
||||||
let handler_calls = Arc::clone(&capability_calls);
|
let handler_calls = Arc::clone(&capability_calls);
|
||||||
let capability_handler: crate::loader::CapabilityHandler = Box::new(
|
let capability_handler: super::loader::CapabilityHandler = Box::new(
|
||||||
move |capability, request| {
|
move |capability, request| {
|
||||||
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
|
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
|
||||||
return Err(PluginError::capability(
|
return Err(PluginError::capability(
|
||||||
@@ -185,7 +185,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
let options = LoadOptions {
|
let options = LoadOptions {
|
||||||
host_target: crate::artifact::HostTarget::current(),
|
host_target: super::artifact::HostTarget::current(),
|
||||||
capability_handler: Some(capability_handler),
|
capability_handler: Some(capability_handler),
|
||||||
};
|
};
|
||||||
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
|
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
|
||||||
@@ -15,13 +15,12 @@ use std::path::Path;
|
|||||||
use std::process::{Child, Command, Stdio};
|
use std::process::{Child, Command, Stdio};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use marqdo_plugin_abi::worker::{
|
use crate::plugin::worker::{
|
||||||
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
|
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
|
||||||
WORKER_COMMAND,
|
WORKER_COMMAND,
|
||||||
};
|
};
|
||||||
use marqdo_plugin_abi::{
|
use crate::plugin::{CapabilityHandler, PluginManifest};
|
||||||
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
|
use marqdo_plugin_abi::{PluginError, WireRequest, WireResponse};
|
||||||
};
|
|
||||||
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
@@ -333,8 +332,39 @@ fn transport_error(error: TransportError) -> PluginError {
|
|||||||
"plugin.crashed",
|
"plugin.crashed",
|
||||||
format!("worker frame I/O failed: {error}"),
|
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) => {
|
TransportError::Frame(other) => {
|
||||||
PluginError::wire("worker_frame_invalid", other.to_string())
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||||
|
|
||||||
use crate::context::ExecutionContext;
|
use marqdo_host_contract::ExecutionContext;
|
||||||
|
|
||||||
fn process_error(code: &str, message: &str) -> Value {
|
fn process_error(code: &str, message: &str) -> Value {
|
||||||
let mut map = BTreeMap::new();
|
let mut map = BTreeMap::new();
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ use libloading::Library;
|
|||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
use marqdo_value::{ErrorCategory, RuntimeError};
|
use marqdo_value::{ErrorCategory, RuntimeError};
|
||||||
|
|
||||||
use crate::resource::{ResourceProvider, ResourceRead};
|
use crate::resource::ResourceProvider;
|
||||||
|
use marqdo_host_contract::ResourceRead;
|
||||||
|
|
||||||
const ABI_VERSION: u32 = 1;
|
const ABI_VERSION: u32 = 1;
|
||||||
const ERROR_MAX: usize = 1024;
|
const ERROR_MAX: usize = 1024;
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ use marqdo_span::Span;
|
|||||||
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
||||||
use serde_json::{json, Value as Json};
|
use serde_json::{json, Value as Json};
|
||||||
|
|
||||||
use crate::resource::{ResourceProvider, ResourceRead};
|
use crate::resource::ResourceProvider;
|
||||||
|
use marqdo_host_contract::ResourceRead;
|
||||||
use marqdo_value::{ErrorCategory, RuntimeError};
|
use marqdo_value::{ErrorCategory, RuntimeError};
|
||||||
|
|
||||||
const MAX_FRAME_BYTES: usize = 1024 * 1024;
|
const MAX_FRAME_BYTES: usize = 1024 * 1024;
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use rustls::{ClientConnection, StreamOwned};
|
|||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use marqdo_host_contract::ResourceRead;
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
|
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
|
||||||
|
|
||||||
@@ -83,15 +84,6 @@ pub trait ResourceProvider: Send {
|
|||||||
/// Shared provider handle registered on the host.
|
/// Shared provider handle registered on the host.
|
||||||
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
|
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
|
||||||
|
|
||||||
/// Bytes returned by one stream read.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct ResourceRead {
|
|
||||||
/// Bytes actually read (may be empty at EOF).
|
|
||||||
pub bytes: Vec<u8>,
|
|
||||||
/// Whether the stream has reached EOF.
|
|
||||||
pub eof: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct StdinCursor {
|
struct StdinCursor {
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
position: usize,
|
position: usize,
|
||||||
|
|||||||
@@ -3,12 +3,13 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::Host;
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::ErrorCategory;
|
use marqdo_value::ErrorCategory;
|
||||||
|
|
||||||
fn context() -> marqdo_host::ExecutionContext {
|
fn context() -> marqdo_host_contract::ExecutionContext {
|
||||||
marqdo_host::ExecutionContext::new("test".to_string(), None)
|
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
|
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
|
||||||
|
|||||||
@@ -5,8 +5,9 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
|
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
|
||||||
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::{Host, HostOp};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::{ErrorCategory, Value};
|
use marqdo_value::{ErrorCategory, Value};
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -11,9 +11,9 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_plugin_abi::{
|
use marqdo_host::plugin::{sha256_file, HostTarget, LoadedPlugin, PluginManifest};
|
||||||
sha256_file, ErrorKind, HostTarget, LoadedPlugin, PluginManifest, Value, WireRequest,
|
use marqdo_plugin_abi::{ErrorKind, WireRequest};
|
||||||
};
|
use marqdo_value::Value;
|
||||||
|
|
||||||
static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0);
|
static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
@@ -8,10 +8,10 @@ use std::cell::RefCell;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use marqdo_host::{
|
use marqdo_host::{
|
||||||
encode_value, Capabilities, ExecutionContext, FrameId, Host, ObservationConfig,
|
encode_value, Capabilities, ObservationConfig, ObservationError, ObservationEvent,
|
||||||
ObservationError, ObservationEvent, ObservationSink, ParameterSource, RuntimeObservation,
|
ObservationSink, StdHost, ValueState,
|
||||||
StdHost, ValueState,
|
|
||||||
};
|
};
|
||||||
|
use marqdo_host_contract::{ExecutionContext, FrameId, Host, ParameterSource, RuntimeObservation};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::{ErrorCategory, Value};
|
use marqdo_value::{ErrorCategory, Value};
|
||||||
|
|
||||||
@@ -462,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);
|
||||||
|
}
|
||||||
@@ -6,8 +6,9 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
|
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
|
||||||
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::{Host, HostOp};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::Value;
|
use marqdo_value::Value;
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, ExecutionContext, Host, HostOp, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::{ExecutionContext, Host, HostOp};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::{ErrorCategory, Value};
|
use marqdo_value::{ErrorCategory, Value};
|
||||||
|
|
||||||
@@ -325,12 +326,12 @@ impl marqdo_host::ResourceProvider for MockProvider {
|
|||||||
token: u64,
|
token: u64,
|
||||||
max_bytes: usize,
|
max_bytes: usize,
|
||||||
_span: Option<marqdo_span::Span>,
|
_span: Option<marqdo_span::Span>,
|
||||||
) -> Result<marqdo_host::ResourceRead, marqdo_value::RuntimeError> {
|
) -> Result<marqdo_host_contract::ResourceRead, marqdo_value::RuntimeError> {
|
||||||
assert_eq!(token, 7);
|
assert_eq!(token, 7);
|
||||||
let start = self.position;
|
let start = self.position;
|
||||||
let end = start.saturating_add(max_bytes).min(self.data.len());
|
let end = start.saturating_add(max_bytes).min(self.data.len());
|
||||||
self.position = end;
|
self.position = end;
|
||||||
Ok(marqdo_host::ResourceRead {
|
Ok(marqdo_host_contract::ResourceRead {
|
||||||
bytes: self.data[start..end].to_vec(),
|
bytes: self.data[start..end].to_vec(),
|
||||||
eof: end >= self.data.len(),
|
eof: end >= self.data.len(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use marqdo_host::{Capabilities, Host, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::Host;
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::ErrorCategory;
|
use marqdo_value::ErrorCategory;
|
||||||
|
|
||||||
fn context() -> marqdo_host::ExecutionContext {
|
fn context() -> marqdo_host_contract::ExecutionContext {
|
||||||
marqdo_host::ExecutionContext::new("test".to_string(), None)
|
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
|
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
|
||||||
|
|||||||
@@ -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.
|
||||||
//!
|
//!
|
||||||
|
|||||||
@@ -117,10 +117,19 @@ pub struct FunctionId {
|
|||||||
|
|
||||||
impl fmt::Display for FunctionId {
|
impl fmt::Display for FunctionId {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(f, "{}::{}", self.module, self.name)
|
write!(f, "{}::{}", self.module, escape_function_name(&self.name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Escape the module/function delimiter inside a function name.
|
||||||
|
///
|
||||||
|
/// The canonical form is `<module>::<name>`; a name that itself contains `::`
|
||||||
|
/// would make the delimiter ambiguous. Normal names are unchanged. `%` is
|
||||||
|
/// escaped first so a literal `%3A%3A` cannot collide with an escaped `::`.
|
||||||
|
pub fn escape_function_name(name: &str) -> String {
|
||||||
|
name.replace('%', "%25").replace("::", "%3A%3A")
|
||||||
|
}
|
||||||
|
|
||||||
/// Identity of an addressable heading range.
|
/// Identity of an addressable heading range.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
pub struct UnitId {
|
pub struct UnitId {
|
||||||
@@ -137,12 +146,31 @@ impl fmt::Display for UnitId {
|
|||||||
if index > 0 {
|
if index > 0 {
|
||||||
f.write_str("/")?;
|
f.write_str("/")?;
|
||||||
}
|
}
|
||||||
f.write_str(part)?;
|
f.write_str(&escape_identity_segment(part))?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Escape the structural separators of a canonical identity segment.
|
||||||
|
///
|
||||||
|
/// A unit display id is `<module>#<seg>/<seg>`. Escaping `%`, `/` and `#`
|
||||||
|
/// inside each segment keeps the rendering injective: a single heading named
|
||||||
|
/// `a/b` renders `a%2Fb`, never the two-level path `a` -> `b`. Headings that
|
||||||
|
/// do not contain a separator keep their existing rendering.
|
||||||
|
pub fn escape_identity_segment(segment: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(segment.len());
|
||||||
|
for ch in segment.chars() {
|
||||||
|
match ch {
|
||||||
|
'%' => out.push_str("%25"),
|
||||||
|
'/' => out.push_str("%2F"),
|
||||||
|
'#' => out.push_str("%23"),
|
||||||
|
other => out.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Role of a heading range.
|
/// Role of a heading range.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
@@ -491,7 +519,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)]
|
||||||
@@ -582,6 +610,52 @@ mod tests {
|
|||||||
assert_eq!(module.id.to_string(), "root:default::index.mq.md");
|
assert_eq!(module.id.to_string(), "root:default::index.mq.md");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_ids_escape_the_module_delimiter_inside_names() {
|
||||||
|
let module = ModuleId::from("index.mq.md");
|
||||||
|
let plain = FunctionId {
|
||||||
|
module: module.clone(),
|
||||||
|
name: "数学.计算".to_string(),
|
||||||
|
};
|
||||||
|
assert_eq!(plain.to_string(), "root:default::index.mq.md::数学.计算");
|
||||||
|
let dotted = FunctionId {
|
||||||
|
module: module.clone(),
|
||||||
|
name: "a::b".to_string(),
|
||||||
|
};
|
||||||
|
assert_eq!(dotted.to_string(), "root:default::index.mq.md::a%3A%3Ab");
|
||||||
|
let literal = FunctionId {
|
||||||
|
module,
|
||||||
|
name: "a%3A%3Ab".to_string(),
|
||||||
|
};
|
||||||
|
assert_ne!(literal.to_string(), dotted.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unit_ids_are_injective_across_separator_characters() {
|
||||||
|
let module = ModuleId::from("index.mq.md");
|
||||||
|
let one_segment = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: vec!["a/b".to_string()],
|
||||||
|
};
|
||||||
|
let two_segments = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: vec!["a".to_string(), "b".to_string()],
|
||||||
|
};
|
||||||
|
assert_ne!(one_segment.to_string(), two_segments.to_string());
|
||||||
|
assert!(one_segment.to_string().ends_with("#a%2Fb"));
|
||||||
|
assert!(two_segments.to_string().ends_with("#a/b"));
|
||||||
|
let hash = UnitId {
|
||||||
|
module: module.clone(),
|
||||||
|
path: vec!["a#b%c".to_string()],
|
||||||
|
};
|
||||||
|
assert_eq!(hash.to_string(), "root:default::index.mq.md#a%23b%25c");
|
||||||
|
let plain = UnitId {
|
||||||
|
module,
|
||||||
|
path: vec!["数学".to_string(), "计算力".to_string()],
|
||||||
|
};
|
||||||
|
assert_eq!(plain.to_string(), "root:default::index.mq.md#数学/计算力");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ir_serializes_for_inspect() {
|
fn ir_serializes_for_inspect() {
|
||||||
let stmt = Stmt::Return {
|
let stmt = Stmt::Return {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo-plugin-abi"
|
name = "marqdo-plugin-abi"
|
||||||
description = "Versioned C ABI v1 bindings, manifest validation and artifact loading"
|
description = "Public plugin ABI v1 contract: C layout, wire envelope and protocol errors"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -9,13 +9,7 @@ repository.workspace = true
|
|||||||
authors.workspace = true
|
authors.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
marqdo-span = { workspace = true }
|
|
||||||
marqdo-value = { workspace = true }
|
marqdo-value = { workspace = true }
|
||||||
marqdo-worker-ipc = { workspace = true }
|
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
serde_yaml = { workspace = true }
|
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
libloading = { workspace = true }
|
|
||||||
sha2 = { workspace = true }
|
|
||||||
hex = { workspace = true }
|
|
||||||
@@ -255,12 +255,17 @@ pub struct MqCallContext {
|
|||||||
|
|
||||||
impl MqCallContext {
|
impl MqCallContext {
|
||||||
/// Mint a context for a host invocation.
|
/// Mint a context for a host invocation.
|
||||||
pub(crate) fn new(host_data: *mut c_void) -> Self {
|
///
|
||||||
|
/// Host-side execution API: the native host owns the invocation lifetime
|
||||||
|
/// and passes an opaque pointer the plugin never dereferences.
|
||||||
|
pub fn new(host_data: *mut c_void) -> Self {
|
||||||
Self { host_data }
|
Self { host_data }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opaque host data pointer carried by this context.
|
/// Opaque host data pointer carried by this context.
|
||||||
pub(crate) fn host_data(&self) -> *mut c_void {
|
///
|
||||||
|
/// Host-side execution API; not part of the C layout exposed to plugins.
|
||||||
|
pub fn host_data(&self) -> *mut c_void {
|
||||||
self.host_data
|
self.host_data
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,23 @@
|
|||||||
//! Versioned plugin C ABI v1 bindings, manifest validation and artifact
|
//! Public contract for the versioned plugin C ABI v1.
|
||||||
//! loading (host side).
|
|
||||||
//!
|
//!
|
||||||
//! This crate is the host-side counterpart of
|
//! This crate is the single normative Rust side of
|
||||||
//! `include/marqdo_plugin_abi_v1.h` (the frozen C ABI) and of the
|
//! `include/marqdo_plugin_abi_v1.h`: the stable `#[repr(C)]` types with layout
|
||||||
//! `marqdo-plugin-sdk` crate (the plugin-developer side). It implements the
|
//! assertions and major/minor negotiation ([`abi`]), the `wire_version` 1
|
||||||
//! blueprint section 10 contract:
|
//! JSON request/response envelope with typed value tags ([`wire`]), and the
|
||||||
|
//! structured protocol [`PluginError`].
|
||||||
//!
|
//!
|
||||||
//! - stable `#[repr(C)]` Rust mirrors of the C types, with compile-time layout
|
//! It is a contract crate, not a loader. Native loading (`dlopen`), artifact
|
||||||
//! assertions and major/minor negotiation ([`abi`]),
|
//! selection on disk, manifest file validation, worker process management and
|
||||||
//! - `plugin.yaml` parsing and validation ([`manifest`]),
|
//! capability dispatch live in the native host (`marqdo-host::plugin`). The
|
||||||
//! - target-triple artifact selection and sha256 verification ([`artifact`]),
|
//! SDK consumes only this crate. There is no second wire encoding here: the
|
||||||
//! - `wire_version` 1 JSON request/response envelopes with typed value tags
|
//! wire envelope reuses the single [`marqdo_value`] encoding.
|
||||||
//! ([`wire`]),
|
|
||||||
//! - a native loader/invocation bridge built on `libloading` ([`loader`]),
|
|
||||||
//! - structured, serializable [`PluginError`]s ([`error`]).
|
|
||||||
//!
|
//!
|
||||||
//! A C ABI is not a sandbox: native plugins run in-process and require an
|
//! A C ABI is not a sandbox. A host that loads native code must separately make
|
||||||
//! explicit trust decision. This crate only validates and loads what the
|
//! and enforce an explicit trust decision; this crate grants no capability.
|
||||||
//! caller already decided to trust; it never grants capabilities.
|
|
||||||
|
|
||||||
pub mod abi;
|
pub mod abi;
|
||||||
pub mod artifact;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod loader;
|
|
||||||
pub mod manifest;
|
|
||||||
pub mod wire;
|
pub mod wire;
|
||||||
pub mod worker;
|
|
||||||
|
|
||||||
pub use abi::result as result_code;
|
pub use abi::result as result_code;
|
||||||
pub use abi::{
|
pub use abi::{
|
||||||
@@ -33,16 +25,7 @@ pub use abi::{
|
|||||||
MqOwnedBytes, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, MqRegisterFunctionFn,
|
MqOwnedBytes, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, MqRegisterFunctionFn,
|
||||||
MqRequestCapabilityFn, PluginMetadata, ABI_MAJOR, ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
|
MqRequestCapabilityFn, PluginMetadata, ABI_MAJOR, ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
|
||||||
};
|
};
|
||||||
pub use artifact::{
|
|
||||||
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
|
|
||||||
HostTarget, TargetTriple,
|
|
||||||
};
|
|
||||||
pub use error::{ErrorKind, PluginError};
|
pub use error::{ErrorKind, PluginError};
|
||||||
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
|
|
||||||
pub use manifest::{
|
|
||||||
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
|
|
||||||
KNOWN_CAPABILITIES,
|
|
||||||
};
|
|
||||||
pub use marqdo_value::Value;
|
pub use marqdo_value::Value;
|
||||||
pub use wire::{
|
pub use wire::{
|
||||||
bool_from_value, int_from_value, text_from_value, to_wire_json, WireContext, WireErrorBody,
|
bool_from_value, int_from_value, text_from_value, to_wire_json, WireContext, WireErrorBody,
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "marqdo-plugin-sdk"
|
|
||||||
description = "Rust SDK for writing Marqdo plugins against ABI v1"
|
|
||||||
version.workspace = true
|
|
||||||
edition.workspace = true
|
|
||||||
rust-version.workspace = true
|
|
||||||
license.workspace = true
|
|
||||||
repository.workspace = true
|
|
||||||
authors.workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
marqdo-plugin-abi = { workspace = true }
|
|
||||||
serde = { workspace = true }
|
|
||||||
serde_json = { workspace = true }
|
|
||||||
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
//! Safe wrappers around the raw `MqBytes` / `MqOwnedBytes` ABI buffers.
|
|
||||||
//!
|
|
||||||
//! Ownership rules (see the canonical header):
|
|
||||||
//! - [`BytesRef`] is a borrowed, validated view of host input; it is only
|
|
||||||
//! valid for the call that produced it.
|
|
||||||
//! - [`HostBuffer`] is plugin output allocated with the host allocator and
|
|
||||||
//! handed back to the host, which frees it after copying.
|
|
||||||
|
|
||||||
use std::ffi::c_void;
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
use std::ptr;
|
|
||||||
|
|
||||||
use marqdo_plugin_abi::abi::{MqBytes, MqHostApi, MqOwnedBytes};
|
|
||||||
|
|
||||||
use crate::PluginError;
|
|
||||||
|
|
||||||
/// Validated borrowed view of an ABI byte buffer (`MqBytes`).
|
|
||||||
pub struct BytesRef<'a> {
|
|
||||||
raw: MqBytes,
|
|
||||||
_marker: PhantomData<&'a [u8]>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> BytesRef<'a> {
|
|
||||||
/// Validate a raw borrowed buffer.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// If `raw.len > 0`, `raw.data` must point to `raw.len` initialized bytes
|
|
||||||
/// that stay alive for `'a`. Within the ABI, `'a` must not outlive the
|
|
||||||
/// call that produced the buffer.
|
|
||||||
pub unsafe fn from_raw(raw: MqBytes) -> Result<Self, PluginError> {
|
|
||||||
raw.validate()?;
|
|
||||||
Ok(Self {
|
|
||||||
raw,
|
|
||||||
_marker: PhantomData,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The underlying raw ABI view.
|
|
||||||
pub fn as_raw(&self) -> MqBytes {
|
|
||||||
self.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bytes as a slice (valid for `'a`).
|
|
||||||
pub fn as_slice(&self) -> &'a [u8] {
|
|
||||||
if self.raw.len == 0 {
|
|
||||||
return &[];
|
|
||||||
}
|
|
||||||
// SAFETY: `from_raw` validated the pointer/length pair and `'a` is
|
|
||||||
// tied to the caller's borrow guarantee.
|
|
||||||
unsafe { std::slice::from_raw_parts(self.raw.data, self.raw.len) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Length in bytes.
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.raw.len
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the buffer is empty.
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.raw.len == 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A byte buffer allocated with the host allocator and owned by the host.
|
|
||||||
///
|
|
||||||
/// The plugin writes its response/error wire into a [`HostBuffer`] and
|
|
||||||
/// transfers ownership through the ABI output parameter. The plugin must
|
|
||||||
/// never free this buffer itself; the host frees it after copying.
|
|
||||||
pub struct HostBuffer {
|
|
||||||
raw: MqOwnedBytes,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HostBuffer {
|
|
||||||
/// The empty buffer `{NULL, 0}`.
|
|
||||||
pub fn empty() -> Self {
|
|
||||||
Self {
|
|
||||||
raw: MqOwnedBytes::EMPTY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Allocate a host buffer and copy `bytes` into it.
|
|
||||||
///
|
|
||||||
/// `host` must be the host API table provided to the entry point (the SDK
|
|
||||||
/// stores it for the plugin lifetime). Returns an out-of-memory error if
|
|
||||||
/// the host allocator returns NULL.
|
|
||||||
pub fn copy_from(host: &MqHostApi, bytes: &[u8]) -> Result<Self, PluginError> {
|
|
||||||
if bytes.is_empty() {
|
|
||||||
return Ok(Self::empty());
|
|
||||||
}
|
|
||||||
// SAFETY: host alloc/free pointers are non-NULL and valid for the
|
|
||||||
// plugin lifetime (validated during the entry call).
|
|
||||||
let pointer = unsafe { (host.alloc)(host.host_data, bytes.len()) };
|
|
||||||
if pointer.is_null() {
|
|
||||||
return Err(PluginError::invoke(
|
|
||||||
"out_of_memory",
|
|
||||||
"host allocator returned NULL for a plugin output buffer",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
// SAFETY: pointer has bytes.len() writable bytes and does not overlap
|
|
||||||
// the source slice.
|
|
||||||
unsafe {
|
|
||||||
ptr::copy_nonoverlapping(bytes.as_ptr(), pointer as *mut u8, bytes.len());
|
|
||||||
}
|
|
||||||
Ok(Self {
|
|
||||||
raw: MqOwnedBytes::new(pointer as *mut u8, bytes.len()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The raw owner-transfer buffer.
|
|
||||||
pub fn into_raw(self) -> MqOwnedBytes {
|
|
||||||
self.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Length in bytes.
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.raw.len
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the buffer is empty.
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.raw.len == 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Borrowed view of a capability reply or other host-allocated buffer.
|
|
||||||
///
|
|
||||||
/// The plugin copies what it needs and then must release the buffer with the
|
|
||||||
/// host allocator; use [`release_host_buffer`].
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `buffer` must be a host-allocated buffer that is still alive; the returned
|
|
||||||
/// slice must not outlive the release of that buffer.
|
|
||||||
pub unsafe fn reply_slice<'a>(buffer: MqOwnedBytes) -> &'a [u8] {
|
|
||||||
if buffer.len == 0 {
|
|
||||||
return &[];
|
|
||||||
}
|
|
||||||
// SAFETY: host-allocated buffer is initialized for `buffer.len` bytes; the
|
|
||||||
// caller must not retain the slice beyond the release point.
|
|
||||||
unsafe { std::slice::from_raw_parts(buffer.data, buffer.len) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Release a host-allocated buffer through the host allocator.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `buffer.data` must be NULL or a pointer returned by the host allocator
|
|
||||||
/// (`MqHostApi::alloc`) that has not been freed yet.
|
|
||||||
pub unsafe fn release_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) {
|
|
||||||
if buffer.data.is_null() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// SAFETY: alloc/free pair and non-NULL pointer per the caller contract.
|
|
||||||
unsafe { (host.free)(host.host_data, buffer.data as *mut c_void) };
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
//! Per-invocation context passed to plugin handlers.
|
|
||||||
//!
|
|
||||||
//! The context is valid only for the duration of one invocation. It exists to
|
|
||||||
//! carry host capabilities into the plugin: capability requests are answered
|
|
||||||
//! by the host's authorization layer and can never be escalated by plugin
|
|
||||||
//! code. Do not cache this value, its raw pointer or any capability token.
|
|
||||||
|
|
||||||
use marqdo_plugin_abi::abi::{
|
|
||||||
MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MAX_CAPABILITY_REPLY_BYTES,
|
|
||||||
};
|
|
||||||
use marqdo_plugin_abi::PluginError;
|
|
||||||
|
|
||||||
use crate::bytes;
|
|
||||||
|
|
||||||
/// Context for one plugin invocation.
|
|
||||||
pub struct CallContext {
|
|
||||||
raw: *mut MqCallContext,
|
|
||||||
host: &'static MqHostApi,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CallContext {
|
|
||||||
/// Wrap the host-provided context pointer.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `raw` must be the context pointer provided by the host for the current
|
|
||||||
/// invocation, and `host` must be the validated host API table.
|
|
||||||
pub(crate) unsafe fn new(raw: *mut MqCallContext, host: &'static MqHostApi) -> Self {
|
|
||||||
Self { raw, host }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The host API table of this plugin instance.
|
|
||||||
pub fn host(&self) -> &'static MqHostApi {
|
|
||||||
self.host
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Request an already-authorized host capability for this call.
|
|
||||||
///
|
|
||||||
/// `request` is a UTF-8 JSON capability request; the reply is opaque bytes
|
|
||||||
/// owned by the host. The SDK copies the reply and releases the host buffer.
|
|
||||||
pub fn capability_request(
|
|
||||||
&mut self,
|
|
||||||
name: &str,
|
|
||||||
request: &[u8],
|
|
||||||
) -> Result<Vec<u8>, PluginError> {
|
|
||||||
if self.raw.is_null() {
|
|
||||||
return Err(PluginError::capability(
|
|
||||||
"missing_call_context",
|
|
||||||
"capability request requires an active invocation context",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let mut reply = MqOwnedBytes::EMPTY;
|
|
||||||
// SAFETY: raw context and host table are valid for this invocation.
|
|
||||||
let code = unsafe {
|
|
||||||
(self.host.request_capability)(
|
|
||||||
self.raw,
|
|
||||||
MqBytes::from_slice(name.as_bytes()),
|
|
||||||
MqBytes::from_slice(request),
|
|
||||||
&mut reply,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
// SAFETY: host-allocated reply is initialized for `reply.len` bytes.
|
|
||||||
let reply_bytes = unsafe { reply.to_vec() };
|
|
||||||
// SAFETY: the host allocated `reply` with its allocator for us; release
|
|
||||||
// it exactly once after copying.
|
|
||||||
unsafe { bytes::release_host_buffer(self.host, reply) };
|
|
||||||
let reply_bytes = reply_bytes.map_err(|error| {
|
|
||||||
PluginError::capability(
|
|
||||||
"invalid_capability_reply",
|
|
||||||
"host capability reply violates the buffer contract",
|
|
||||||
)
|
|
||||||
.with_detail(error.to_string())
|
|
||||||
})?;
|
|
||||||
if reply_bytes.len() > MAX_CAPABILITY_REPLY_BYTES {
|
|
||||||
return Err(PluginError::capability(
|
|
||||||
"capability_reply_too_large",
|
|
||||||
format!(
|
|
||||||
"capability reply is {} bytes, limit is {MAX_CAPABILITY_REPLY_BYTES}",
|
|
||||||
reply_bytes.len()
|
|
||||||
),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if code != crate::result_code::OK {
|
|
||||||
return Err(PluginError::capability(
|
|
||||||
"capability_request_failed",
|
|
||||||
format!("host rejected capability request `{name}`"),
|
|
||||||
)
|
|
||||||
.with_detail(format!(
|
|
||||||
"result code `{}` ({code})",
|
|
||||||
crate::result_code::name(code)
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
Ok(reply_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Best-effort structured log through the `log` capability.
|
|
||||||
pub fn log(&mut self, level: &str, message: &str) -> Result<(), PluginError> {
|
|
||||||
let request = serde_json::json!({"level": level, "message": message});
|
|
||||||
let request = serde_json::to_vec(&request).map_err(|error| {
|
|
||||||
PluginError::capability("log_encode_failed", "could not encode log request")
|
|
||||||
.with_detail(error.to_string())
|
|
||||||
})?;
|
|
||||||
let _ = self.capability_request("log", &request)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Debug for CallContext {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct("CallContext")
|
|
||||||
.field("raw", &self.raw)
|
|
||||||
.field("host", &(self.host as *const MqHostApi))
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
//! Entry-point plumbing used by [`mq_plugin_entry!`](crate::mq_plugin_entry).
|
|
||||||
//!
|
|
||||||
//! These functions are the "runtime" of the SDK macro. They are public so the
|
|
||||||
//! macro can reference them through `$crate` from a plugin crate, but they are
|
|
||||||
//! not intended for direct use.
|
|
||||||
|
|
||||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
||||||
use std::sync::atomic::{AtomicPtr, Ordering};
|
|
||||||
|
|
||||||
use marqdo_plugin_abi::abi::{
|
|
||||||
check_host_api, result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi,
|
|
||||||
MqPluginInvoke, ABI_MAJOR, ABI_MINOR, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
|
|
||||||
MAX_RESULT_WIRE_BYTES,
|
|
||||||
};
|
|
||||||
use marqdo_plugin_abi::{PluginError, WireResponse};
|
|
||||||
|
|
||||||
use crate::bytes::{release_host_buffer, HostBuffer};
|
|
||||||
use crate::call::CallContext;
|
|
||||||
use crate::HandlerFn;
|
|
||||||
|
|
||||||
/// Host API table captured by the entry point for the plugin lifetime.
|
|
||||||
static CURRENT_HOST: AtomicPtr<MqHostApi> = AtomicPtr::new(std::ptr::null_mut());
|
|
||||||
|
|
||||||
/// The host API table captured at load time, if a plugin is loaded.
|
|
||||||
pub(crate) fn current_host() -> Option<&'static MqHostApi> {
|
|
||||||
let pointer = CURRENT_HOST.load(Ordering::SeqCst);
|
|
||||||
if pointer.is_null() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
// SAFETY: the pointer was stored from a validated host table and the host
|
|
||||||
// guarantees it is valid for the plugin lifetime (single-threaded model).
|
|
||||||
Some(unsafe { &*pointer })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Initialize the ABI tables for the generated entry point.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `host` and `plugin` must be the pointers provided by the host to
|
|
||||||
/// `mq_plugin_entry_v1` and must satisfy the header contract.
|
|
||||||
pub unsafe fn initialize(
|
|
||||||
host: *const MqHostApi,
|
|
||||||
plugin: *mut MqPluginApi,
|
|
||||||
metadata: &'static [u8],
|
|
||||||
) -> i32 {
|
|
||||||
if plugin.is_null() {
|
|
||||||
return result::INVALID_ARGUMENT;
|
|
||||||
}
|
|
||||||
// SAFETY: host pointer comes from the host and is checked before use.
|
|
||||||
let negotiated = match unsafe { check_host_api(host) } {
|
|
||||||
Ok(version) => version,
|
|
||||||
Err(_) => return result::ABI_MISMATCH,
|
|
||||||
};
|
|
||||||
if negotiated.major != ABI_MAJOR {
|
|
||||||
return result::ABI_MISMATCH;
|
|
||||||
}
|
|
||||||
CURRENT_HOST.store(host as *mut MqHostApi, Ordering::SeqCst);
|
|
||||||
// SAFETY: plugin table is host-provided, writable and valid for this call.
|
|
||||||
unsafe {
|
|
||||||
(*plugin).struct_size = std::mem::size_of::<MqPluginApi>() as u32;
|
|
||||||
(*plugin).abi_major = ABI_MAJOR;
|
|
||||||
(*plugin).abi_minor = ABI_MINOR;
|
|
||||||
(*plugin).plugin_metadata_wire = MqBytes::from_slice(metadata);
|
|
||||||
}
|
|
||||||
result::OK
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Register one export through the host table.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `host` must be the table validated by [`initialize`]; both strings must be
|
|
||||||
/// valid UTF-8 dotted export names/signatures declared in `plugin.yaml`.
|
|
||||||
pub unsafe fn register_export(
|
|
||||||
host: *const MqHostApi,
|
|
||||||
name: &str,
|
|
||||||
signature: &str,
|
|
||||||
invoke: MqPluginInvoke,
|
|
||||||
) -> i32 {
|
|
||||||
if host.is_null() || name.is_empty() || name.len() > MAX_EXPORT_NAME_BYTES {
|
|
||||||
return result::INVALID_ARGUMENT;
|
|
||||||
}
|
|
||||||
// SAFETY: host pointer is non-NULL and valid for the plugin lifetime.
|
|
||||||
let host = unsafe { &*host };
|
|
||||||
let signature_wire = match serde_json::to_vec(&serde_json::json!({"signature": signature})) {
|
|
||||||
Ok(bytes) => bytes,
|
|
||||||
Err(_) => return result::BAD_WIRE,
|
|
||||||
};
|
|
||||||
// SAFETY: host table was validated; strings outlive the call.
|
|
||||||
unsafe {
|
|
||||||
(host.register_function)(
|
|
||||||
host.host_data,
|
|
||||||
MqBytes::from_slice(name.as_bytes()),
|
|
||||||
MqBytes::from_slice(&signature_wire),
|
|
||||||
invoke,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dispatch one invocation to a plugin handler and write the response.
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// Must be called as the body of a `MqPluginInvoke` callback with the buffers
|
|
||||||
/// provided by the host for that invocation.
|
|
||||||
pub unsafe fn dispatch(
|
|
||||||
handler: HandlerFn,
|
|
||||||
ctx: *mut MqCallContext,
|
|
||||||
args: MqBytes,
|
|
||||||
result_out: *mut MqOwnedBytes,
|
|
||||||
error_out: *mut MqOwnedBytes,
|
|
||||||
) -> i32 {
|
|
||||||
if result_out.is_null() || error_out.is_null() {
|
|
||||||
return result::INVALID_ARGUMENT;
|
|
||||||
}
|
|
||||||
// SAFETY: output pointers are non-NULL host-provided out-parameters.
|
|
||||||
unsafe {
|
|
||||||
*result_out = MqOwnedBytes::EMPTY;
|
|
||||||
*error_out = MqOwnedBytes::EMPTY;
|
|
||||||
}
|
|
||||||
let Some(host) = current_host() else {
|
|
||||||
return result::INTERNAL;
|
|
||||||
};
|
|
||||||
// SAFETY: borrowed request buffer is valid for this callback.
|
|
||||||
let args_bytes = match unsafe { args.as_slice() } {
|
|
||||||
Ok(bytes) => bytes.to_vec(),
|
|
||||||
Err(_) => return result::INVALID_ARGUMENT,
|
|
||||||
};
|
|
||||||
|
|
||||||
// SAFETY: context pointer is the host-minted context for this invocation.
|
|
||||||
let mut context = unsafe { CallContext::new(ctx, host) };
|
|
||||||
let outcome = catch_unwind(AssertUnwindSafe(|| handler(&mut context, &args_bytes)));
|
|
||||||
let response = match outcome {
|
|
||||||
Ok(Ok(bytes)) => Ok(bytes),
|
|
||||||
Ok(Err(error)) => Err(error),
|
|
||||||
Err(_) => Err(PluginError::invoke(
|
|
||||||
"plugin_panic",
|
|
||||||
"plugin handler panicked; the panic was caught at the ABI boundary",
|
|
||||||
)),
|
|
||||||
};
|
|
||||||
|
|
||||||
match response {
|
|
||||||
Ok(bytes) => {
|
|
||||||
if bytes.len() > MAX_RESULT_WIRE_BYTES {
|
|
||||||
return write_error(
|
|
||||||
host,
|
|
||||||
error_out,
|
|
||||||
&PluginError::wire(
|
|
||||||
"result_too_large",
|
|
||||||
format!(
|
|
||||||
"plugin result is {} bytes, limit is {MAX_RESULT_WIRE_BYTES}",
|
|
||||||
bytes.len()
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
match HostBuffer::copy_from(host, &bytes) {
|
|
||||||
Ok(buffer) => {
|
|
||||||
// SAFETY: result_out is a valid out-parameter.
|
|
||||||
unsafe { *result_out = buffer.into_raw() };
|
|
||||||
result::OK
|
|
||||||
}
|
|
||||||
Err(error) => write_error(host, error_out, &error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(error) => write_error(host, error_out, &error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_error(host: &'static MqHostApi, error_out: *mut MqOwnedBytes, error: &PluginError) -> i32 {
|
|
||||||
let encoded = match WireResponse::from_error(error).to_json_bytes() {
|
|
||||||
Ok(bytes) if bytes.len() <= MAX_ERROR_WIRE_BYTES => bytes,
|
|
||||||
_ => br#"{"wire_version":1,"kind":"response","error":{"kind":"invoke","code":"plugin_error","message":"plugin failed with an unencodable error"}}"#.to_vec(),
|
|
||||||
};
|
|
||||||
let code = match error.kind {
|
|
||||||
marqdo_plugin_abi::ErrorKind::Wire => result::BAD_WIRE,
|
|
||||||
marqdo_plugin_abi::ErrorKind::Capability => result::CAPABILITY,
|
|
||||||
marqdo_plugin_abi::ErrorKind::Unsupported => result::UNSUPPORTED,
|
|
||||||
_ => result::INTERNAL,
|
|
||||||
};
|
|
||||||
match HostBuffer::copy_from(host, &encoded) {
|
|
||||||
Ok(buffer) => {
|
|
||||||
// SAFETY: error_out is a valid out-parameter.
|
|
||||||
unsafe { *error_out = buffer.into_raw() };
|
|
||||||
code
|
|
||||||
}
|
|
||||||
Err(_) => result::OUT_OF_MEMORY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Free a host-owned buffer (used by generated code/tests).
|
|
||||||
///
|
|
||||||
/// # Safety
|
|
||||||
///
|
|
||||||
/// `buffer` must have been allocated by the host allocator and not freed yet.
|
|
||||||
pub unsafe fn free_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) {
|
|
||||||
// SAFETY: caller guarantees the alloc/free pair.
|
|
||||||
unsafe { release_host_buffer(host, buffer) };
|
|
||||||
}
|
|
||||||
@@ -1,143 +0,0 @@
|
|||||||
//! Rust SDK for writing Marqdo native plugins against plugin ABI v1.
|
|
||||||
//!
|
|
||||||
//! The SDK is the plugin-developer side of `include/marqdo_plugin_abi_v1.h`.
|
|
||||||
//! It hides the raw C layout behind safe wrappers and provides the
|
|
||||||
//! [`mq_plugin_entry!`] macro that exports the required
|
|
||||||
//! `mq_plugin_entry_v1` symbol:
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//! use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value};
|
|
||||||
//!
|
|
||||||
//! fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
|
|
||||||
//! let request = marqdo_plugin_sdk::wire::decode_request(args)?;
|
|
||||||
//! let values = request.typed_args()?;
|
|
||||||
//! let a = marqdo_plugin_sdk::wire::int_arg(&values, "a")?;
|
|
||||||
//! let b = marqdo_plugin_sdk::wire::int_arg(&values, "b")?;
|
|
||||||
//! marqdo_plugin_sdk::wire::success(Some(Value::Int((a + b).into())))
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! mq_plugin_entry! {
|
|
||||||
//! name: "demo.solver",
|
|
||||||
//! version: "0.1.0",
|
|
||||||
//! exports: {
|
|
||||||
//! "solver.add" => "($a: Int, $b: Int) -> Int" => add,
|
|
||||||
//! }
|
|
||||||
//! }
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! The SDK never depends on host-only crates: it only uses the shared ABI
|
|
||||||
//! types and the JSON wire envelope from `marqdo-plugin-abi`. Building a
|
|
||||||
//! plugin does not grant it any capability; authorization is a separate host
|
|
||||||
//! decision performed before loading.
|
|
||||||
|
|
||||||
#![deny(missing_docs)]
|
|
||||||
|
|
||||||
pub use marqdo_plugin_abi::abi::result as result_code;
|
|
||||||
pub use marqdo_plugin_abi::abi::{
|
|
||||||
MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, ABI_MAJOR,
|
|
||||||
ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
|
|
||||||
};
|
|
||||||
pub use marqdo_plugin_abi::{PluginError, Value, WireRequest, WireResponse, WIRE_VERSION};
|
|
||||||
|
|
||||||
pub mod bytes;
|
|
||||||
pub mod call;
|
|
||||||
pub mod entry;
|
|
||||||
pub mod wire;
|
|
||||||
|
|
||||||
pub use bytes::{BytesRef, HostBuffer};
|
|
||||||
pub use call::CallContext;
|
|
||||||
pub use wire::{
|
|
||||||
bool_arg, decode_request, error_response, int_arg, response_value, success, success_raw,
|
|
||||||
text_arg, value_arg,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Plugin handler signature.
|
|
||||||
///
|
|
||||||
/// A handler receives the per-call context (for capability requests and
|
|
||||||
/// logging) and the raw request envelope bytes, and returns the raw response
|
|
||||||
/// envelope bytes on success.
|
|
||||||
///
|
|
||||||
/// Use [`wire::decode_request`] and [`wire::success`] to build the response;
|
|
||||||
/// handlers should never panic: panics are caught by the SDK and converted
|
|
||||||
/// into a structured error, but the plugin process stays healthy only if the
|
|
||||||
/// panic does not corrupt plugin state.
|
|
||||||
pub type HandlerFn = fn(&mut CallContext, &[u8]) -> Result<Vec<u8>, PluginError>;
|
|
||||||
|
|
||||||
/// Declare a plugin and export `mq_plugin_entry_v1`.
|
|
||||||
///
|
|
||||||
/// ```ignore
|
|
||||||
/// marqdo_plugin_sdk::mq_plugin_entry! {
|
|
||||||
/// name: "demo.solver",
|
|
||||||
/// version: "0.1.0",
|
|
||||||
/// exports: {
|
|
||||||
/// "solver.add" => "($a: Int, $b: Int) -> Int" => add,
|
|
||||||
/// "solver.echo" => "($text: Text) -> Text" => echo,
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Each handler is a path (or non-capturing closure) with the [`HandlerFn`]
|
|
||||||
/// signature. The macro:
|
|
||||||
/// - validates the host ABI table (major version and `struct_size`),
|
|
||||||
/// - reports the plugin ABI version and a metadata envelope,
|
|
||||||
/// - registers every export and fails the load if registration fails.
|
|
||||||
#[macro_export]
|
|
||||||
macro_rules! mq_plugin_entry {
|
|
||||||
(
|
|
||||||
name: $name:literal,
|
|
||||||
version: $version:literal,
|
|
||||||
exports: {
|
|
||||||
$( $export_name:literal => $signature:literal => $handler:expr ),* $(,)?
|
|
||||||
}
|
|
||||||
) => {
|
|
||||||
/// Marqdo plugin ABI v1 entry point (generated by the SDK macro).
|
|
||||||
#[unsafe(no_mangle)]
|
|
||||||
pub unsafe extern "C" fn mq_plugin_entry_v1(
|
|
||||||
host: *const $crate::MqHostApi,
|
|
||||||
plugin: *mut $crate::MqPluginApi,
|
|
||||||
) -> i32 {
|
|
||||||
const METADATA: &[u8] = concat!(
|
|
||||||
"{\"name\":\"", $name, "\",\"version\":\"", $version, "\"}"
|
|
||||||
)
|
|
||||||
.as_bytes();
|
|
||||||
let metadata: &'static [u8] = METADATA;
|
|
||||||
// SAFETY: the host provides the ABI tables per the header contract.
|
|
||||||
let init = unsafe { $crate::entry::initialize(host, plugin, metadata) };
|
|
||||||
if init != 0 {
|
|
||||||
return init;
|
|
||||||
}
|
|
||||||
$(
|
|
||||||
{
|
|
||||||
extern "C" fn invoke(
|
|
||||||
ctx: *mut $crate::MqCallContext,
|
|
||||||
args: $crate::MqBytes,
|
|
||||||
result: *mut $crate::MqOwnedBytes,
|
|
||||||
error: *mut $crate::MqOwnedBytes,
|
|
||||||
) -> i32 {
|
|
||||||
// Expand the user's handler expression in a safe
|
|
||||||
// context (also required by `macro_metavars_in_unsafe`).
|
|
||||||
let handler: $crate::HandlerFn = $handler;
|
|
||||||
// SAFETY: the host owns the invocation buffers; the SDK
|
|
||||||
// validates them and never retains them.
|
|
||||||
unsafe {
|
|
||||||
$crate::entry::dispatch(handler, ctx, args, result, error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let export_name: &str = $export_name;
|
|
||||||
let signature: &str = $signature;
|
|
||||||
// SAFETY: host table is valid for the plugin lifetime and
|
|
||||||
// was validated by `initialize`.
|
|
||||||
let code =
|
|
||||||
unsafe { $crate::entry::register_export(host, export_name, signature, invoke) };
|
|
||||||
if code != 0 {
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)*
|
|
||||||
$crate::result_code::OK
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,245 +0,0 @@
|
|||||||
//! End-to-end SDK tests: run the macro-generated entry point against a tiny
|
|
||||||
//! in-process host table and invoke the registered export.
|
|
||||||
|
|
||||||
use std::ffi::c_void;
|
|
||||||
use std::ptr;
|
|
||||||
|
|
||||||
use marqdo_plugin_abi::abi::{
|
|
||||||
result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke,
|
|
||||||
ABI_MAJOR, ABI_MINOR,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::wire;
|
|
||||||
use crate::{CallContext, PluginError, Value, WireRequest, WireResponse};
|
|
||||||
|
|
||||||
/// ABI v1 is single-threaded: the generated plugin stores the host table in a
|
|
||||||
/// process-global. Serialize tests that call the entry point so they do not
|
|
||||||
/// race (the SDK's own contract, not a test-only limitation).
|
|
||||||
static ABI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
||||||
|
|
||||||
fn abi_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
|
||||||
ABI_TEST_LOCK
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct TestHostState {
|
|
||||||
registrations: Vec<(String, String, MqPluginInvoke)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn test_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void {
|
|
||||||
const HEADER: usize = 16;
|
|
||||||
if size == 0 {
|
|
||||||
return ptr::null_mut();
|
|
||||||
}
|
|
||||||
let Ok(layout) = std::alloc::Layout::from_size_align(size + HEADER, 16) else {
|
|
||||||
return ptr::null_mut();
|
|
||||||
};
|
|
||||||
// SAFETY: non-zero layout.
|
|
||||||
let base = unsafe { std::alloc::alloc(layout) };
|
|
||||||
if base.is_null() {
|
|
||||||
return ptr::null_mut();
|
|
||||||
}
|
|
||||||
// SAFETY: allocation has room for the header.
|
|
||||||
unsafe { (base as *mut usize).write(size) };
|
|
||||||
// SAFETY: offset within the allocation.
|
|
||||||
unsafe { base.add(HEADER) as *mut c_void }
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn test_free(_host_data: *mut c_void, pointer: *mut c_void) {
|
|
||||||
const HEADER: usize = 16;
|
|
||||||
if pointer.is_null() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// SAFETY: only pointers from test_alloc are freed.
|
|
||||||
unsafe {
|
|
||||||
let base = (pointer as *mut u8).sub(HEADER);
|
|
||||||
let size = (base as *const usize).read();
|
|
||||||
std::alloc::dealloc(
|
|
||||||
base,
|
|
||||||
std::alloc::Layout::from_size_align_unchecked(size + HEADER, 16),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn test_register(
|
|
||||||
host_data: *mut c_void,
|
|
||||||
export_name: MqBytes,
|
|
||||||
signature_wire: MqBytes,
|
|
||||||
invoke: MqPluginInvoke,
|
|
||||||
) -> i32 {
|
|
||||||
if host_data.is_null() {
|
|
||||||
return result::INVALID_ARGUMENT;
|
|
||||||
}
|
|
||||||
// SAFETY: host_data points at TestHostState for the test.
|
|
||||||
let state = unsafe { &mut *(host_data as *mut TestHostState) };
|
|
||||||
// SAFETY: buffers are valid for this callback.
|
|
||||||
let name = match unsafe { export_name.as_slice() } {
|
|
||||||
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
|
|
||||||
Err(_) => return result::INVALID_ARGUMENT,
|
|
||||||
};
|
|
||||||
// SAFETY: buffers are valid for this callback.
|
|
||||||
let signature = match unsafe { signature_wire.as_slice() } {
|
|
||||||
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
|
|
||||||
Err(_) => return result::INVALID_ARGUMENT,
|
|
||||||
};
|
|
||||||
state.registrations.push((name, signature, invoke));
|
|
||||||
result::OK
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe extern "C" fn test_capability(
|
|
||||||
_ctx: *mut MqCallContext,
|
|
||||||
_name: MqBytes,
|
|
||||||
_request: MqBytes,
|
|
||||||
reply: *mut MqOwnedBytes,
|
|
||||||
) -> i32 {
|
|
||||||
if !reply.is_null() {
|
|
||||||
// SAFETY: output pointer is non-NULL.
|
|
||||||
unsafe { *reply = MqOwnedBytes::EMPTY };
|
|
||||||
}
|
|
||||||
result::UNSUPPORTED
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
|
|
||||||
let request = wire::decode_request(args)?;
|
|
||||||
let values = request.typed_args()?;
|
|
||||||
let a = wire::int_arg(&values, "a")?;
|
|
||||||
let b = wire::int_arg(&values, "b")?;
|
|
||||||
wire::success(Some(Value::Int((a + b).into())))
|
|
||||||
}
|
|
||||||
|
|
||||||
crate::mq_plugin_entry! {
|
|
||||||
name: "sdk.test",
|
|
||||||
version: "0.1.0",
|
|
||||||
exports: {
|
|
||||||
"test.add" => "($a: Int, $b: Int) -> Int" => add,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestHost {
|
|
||||||
_state: Box<TestHostState>,
|
|
||||||
api: MqHostApi,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn test_host() -> TestHost {
|
|
||||||
let mut state = Box::new(TestHostState::default());
|
|
||||||
let api = MqHostApi {
|
|
||||||
struct_size: std::mem::size_of::<MqHostApi>() as u32,
|
|
||||||
abi_major: ABI_MAJOR,
|
|
||||||
abi_minor: ABI_MINOR,
|
|
||||||
host_data: (&mut *state) as *mut TestHostState as *mut c_void,
|
|
||||||
alloc: test_alloc,
|
|
||||||
free: test_free,
|
|
||||||
register_function: test_register,
|
|
||||||
request_capability: test_capability,
|
|
||||||
};
|
|
||||||
TestHost { _state: state, api }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn macro_exports_and_registers() {
|
|
||||||
let _guard = abi_test_lock();
|
|
||||||
let host = test_host();
|
|
||||||
let mut plugin_api = MqPluginApi::host_initialized();
|
|
||||||
// SAFETY: test host table follows the ABI contract.
|
|
||||||
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
|
|
||||||
assert_eq!(code, result::OK);
|
|
||||||
assert_eq!(plugin_api.abi_major, ABI_MAJOR);
|
|
||||||
assert_eq!(plugin_api.abi_minor, ABI_MINOR);
|
|
||||||
// SAFETY: metadata is plugin static data valid during the entry call.
|
|
||||||
let metadata = unsafe { plugin_api.plugin_metadata_wire.as_slice() }.expect("metadata");
|
|
||||||
let metadata = String::from_utf8_lossy(metadata);
|
|
||||||
assert!(metadata.contains("\"name\":\"sdk.test\""));
|
|
||||||
assert_eq!(host._state.registrations.len(), 1);
|
|
||||||
assert_eq!(host._state.registrations[0].0, "test.add");
|
|
||||||
assert!(host._state.registrations[0]
|
|
||||||
.1
|
|
||||||
.contains("($a: Int, $b: Int) -> Int"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn registered_export_roundtrips_wire_request() {
|
|
||||||
let _guard = abi_test_lock();
|
|
||||||
let host = test_host();
|
|
||||||
let mut plugin_api = MqPluginApi::host_initialized();
|
|
||||||
// SAFETY: test host table follows the ABI contract.
|
|
||||||
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
|
|
||||||
assert_eq!(code, result::OK);
|
|
||||||
|
|
||||||
let request = WireRequest::new("test.add")
|
|
||||||
.with_arg("a", &Value::Int(20_i64.into()))
|
|
||||||
.with_arg("b", &Value::Int(22_i64.into()));
|
|
||||||
let request_bytes = request.to_json_bytes().expect("request");
|
|
||||||
let (_, _, invoke) = &host._state.registrations[0];
|
|
||||||
let mut result_buffer = MqOwnedBytes::EMPTY;
|
|
||||||
let mut error_buffer = MqOwnedBytes::EMPTY;
|
|
||||||
// SAFETY: invoke is the SDK callback; null ctx is fine because the handler
|
|
||||||
// does not request a capability. Buffers are valid out-parameters.
|
|
||||||
let code = unsafe {
|
|
||||||
invoke(
|
|
||||||
ptr::null_mut(),
|
|
||||||
MqBytes::from_slice(&request_bytes),
|
|
||||||
&mut result_buffer,
|
|
||||||
&mut error_buffer,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
assert_eq!(code, result::OK);
|
|
||||||
assert!(error_buffer.is_empty());
|
|
||||||
// SAFETY: result buffer was allocated by test_alloc for us.
|
|
||||||
let response_bytes = unsafe { result_buffer.to_vec() }.expect("result");
|
|
||||||
// SAFETY: allocated by test_alloc; release exactly once.
|
|
||||||
unsafe { test_free(ptr::null_mut(), result_buffer.data as *mut c_void) };
|
|
||||||
|
|
||||||
let response = WireResponse::from_json_bytes(&response_bytes).expect("response");
|
|
||||||
assert_eq!(
|
|
||||||
response.typed_value().expect("typed"),
|
|
||||||
Some(Value::Int(42_i64.into()))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn handler_error_is_written_as_error_envelope() {
|
|
||||||
let _guard = abi_test_lock();
|
|
||||||
let host = test_host();
|
|
||||||
let mut plugin_api = MqPluginApi::host_initialized();
|
|
||||||
// SAFETY: test host table follows the ABI contract.
|
|
||||||
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
|
|
||||||
assert_eq!(code, result::OK);
|
|
||||||
|
|
||||||
let request = WireRequest::new("test.add"); // missing arguments
|
|
||||||
let request_bytes = request.to_json_bytes().expect("request");
|
|
||||||
let (_, _, invoke) = &host._state.registrations[0];
|
|
||||||
let mut result_buffer = MqOwnedBytes::EMPTY;
|
|
||||||
let mut error_buffer = MqOwnedBytes::EMPTY;
|
|
||||||
// SAFETY: invoke is the SDK callback with valid out-parameters.
|
|
||||||
let code = unsafe {
|
|
||||||
invoke(
|
|
||||||
ptr::null_mut(),
|
|
||||||
MqBytes::from_slice(&request_bytes),
|
|
||||||
&mut result_buffer,
|
|
||||||
&mut error_buffer,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
assert_ne!(code, result::OK);
|
|
||||||
assert!(result_buffer.is_empty());
|
|
||||||
// SAFETY: error buffer was allocated by test_alloc for us.
|
|
||||||
let error_bytes = unsafe { error_buffer.to_vec() }.expect("error");
|
|
||||||
// SAFETY: allocated by test_alloc; release exactly once.
|
|
||||||
unsafe { test_free(ptr::null_mut(), error_buffer.data as *mut c_void) };
|
|
||||||
let response = WireResponse::from_error_json_bytes(&error_bytes).expect("decode");
|
|
||||||
let error = response.into_result().expect_err("error");
|
|
||||||
assert_eq!(error.code, "missing_argument");
|
|
||||||
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Invoke);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn initialization_rejects_bad_host_major() {
|
|
||||||
let _guard = abi_test_lock();
|
|
||||||
let mut host = test_host();
|
|
||||||
host.api.abi_major = 2;
|
|
||||||
let mut plugin_api = MqPluginApi::host_initialized();
|
|
||||||
// SAFETY: intentionally inconsistent host table; entry must reject it.
|
|
||||||
let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) };
|
|
||||||
assert_eq!(code, result::ABI_MISMATCH);
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
//! Wire envelope helpers for plugin handlers.
|
|
||||||
//!
|
|
||||||
//! The canonical envelope is defined by `marqdo-plugin-abi` and documented in
|
|
||||||
//! `spec/value-wire.md`: UTF-8 JSON, `wire_version == 1`, type-tagged values.
|
|
||||||
//! Handlers normally do:
|
|
||||||
//!
|
|
||||||
//! ```ignore
|
|
||||||
//! fn add(ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, PluginError> {
|
|
||||||
//! let request = decode_request(args)?;
|
|
||||||
//! let values = request.typed_args()?;
|
|
||||||
//! success(Some(Value::Int((int_arg(&values, "a")? + int_arg(&values, "b")?).into())))
|
|
||||||
//! }
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use marqdo_plugin_abi::{
|
|
||||||
bool_from_value, int_from_value, text_from_value, PluginError, Value, WireRequest, WireResponse,
|
|
||||||
};
|
|
||||||
use serde_json::Value as Json;
|
|
||||||
|
|
||||||
/// Decode and validate a request envelope received from the host.
|
|
||||||
pub fn decode_request(bytes: &[u8]) -> Result<WireRequest, PluginError> {
|
|
||||||
WireRequest::from_json_bytes(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Look up a typed argument by name.
|
|
||||||
pub fn value_arg<'a>(
|
|
||||||
values: &'a BTreeMap<String, Value>,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<&'a Value, PluginError> {
|
|
||||||
values.get(name).ok_or_else(|| {
|
|
||||||
PluginError::invoke(
|
|
||||||
"missing_argument",
|
|
||||||
format!("required argument `{name}` is missing"),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Look up an integer argument (must fit in `i64`).
|
|
||||||
pub fn int_arg(values: &BTreeMap<String, Value>, name: &str) -> Result<i64, PluginError> {
|
|
||||||
let value = value_arg(values, name)?;
|
|
||||||
int_from_value(value).ok_or_else(|| {
|
|
||||||
PluginError::invoke(
|
|
||||||
"invalid_argument_type",
|
|
||||||
format!("argument `{name}` must be an Int"),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Look up a text argument.
|
|
||||||
pub fn text_arg<'a>(
|
|
||||||
values: &'a BTreeMap<String, Value>,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<&'a str, PluginError> {
|
|
||||||
let value = value_arg(values, name)?;
|
|
||||||
text_from_value(value).ok_or_else(|| {
|
|
||||||
PluginError::invoke(
|
|
||||||
"invalid_argument_type",
|
|
||||||
format!("argument `{name}` must be Text"),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Look up a boolean argument.
|
|
||||||
pub fn bool_arg(values: &BTreeMap<String, Value>, name: &str) -> Result<bool, PluginError> {
|
|
||||||
let value = value_arg(values, name)?;
|
|
||||||
bool_from_value(value).ok_or_else(|| {
|
|
||||||
PluginError::invoke(
|
|
||||||
"invalid_argument_type",
|
|
||||||
format!("argument `{name}` must be Bool"),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encode a successful response envelope.
|
|
||||||
pub fn success(value: Option<Value>) -> Result<Vec<u8>, PluginError> {
|
|
||||||
success_raw(value.as_ref().map(marqdo_plugin_abi::to_wire_json))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encode a successful response with an already-encoded type-tagged value.
|
|
||||||
pub fn success_raw(value: Option<Json>) -> Result<Vec<u8>, PluginError> {
|
|
||||||
WireResponse::success_raw(value).to_json_bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Encode an error response envelope.
|
|
||||||
///
|
|
||||||
/// The SDK's dispatch layer uses this automatically when a handler returns an
|
|
||||||
/// error; handlers may also build custom error responses with it.
|
|
||||||
pub fn error_response(error: &PluginError) -> Result<Vec<u8>, PluginError> {
|
|
||||||
WireResponse::from_error(error).to_json_bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decode a response value back into a typed [`Value`] (useful in tests and
|
|
||||||
/// plugins that compose calls).
|
|
||||||
pub fn response_value(bytes: &[u8]) -> Result<Option<Value>, PluginError> {
|
|
||||||
WireResponse::from_json_bytes(bytes)?.typed_value()
|
|
||||||
}
|
|
||||||
@@ -15,6 +15,7 @@ serde_json = { workspace = true }
|
|||||||
marqdo-worker-ipc = { workspace = true }
|
marqdo-worker-ipc = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
marqdo-host-contract = { workspace = true }
|
||||||
marqdo-host = { path = "../marqdo-host" }
|
marqdo-host = { path = "../marqdo-host" }
|
||||||
marqdo-sandbox = { path = "../marqdo-sandbox" }
|
marqdo-sandbox = { path = "../marqdo-sandbox" }
|
||||||
marqdo-value = { path = "../marqdo-value" }
|
marqdo-value = { path = "../marqdo-value" }
|
||||||
|
|||||||
@@ -3,12 +3,13 @@
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::{ExecutionContext, Host};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
use marqdo_value::{ErrorCategory, Value};
|
use marqdo_value::{ErrorCategory, Value};
|
||||||
|
|
||||||
fn context() -> marqdo_host::ExecutionContext {
|
fn context() -> ExecutionContext {
|
||||||
marqdo_host::ExecutionContext::new("test".to_string(), None)
|
ExecutionContext::new("test".to_string(), None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle(value: Value) -> marqdo_value::ResourceHandle {
|
fn handle(value: Value) -> marqdo_value::ResourceHandle {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ marqdo-span = { workspace = true }
|
|||||||
marqdo-value = { workspace = true }
|
marqdo-value = { workspace = true }
|
||||||
marqdo-ir = { workspace = true }
|
marqdo-ir = { workspace = true }
|
||||||
marqdo-expression = { workspace = true }
|
marqdo-expression = { workspace = true }
|
||||||
marqdo-host = { workspace = true }
|
marqdo-host-contract = { workspace = true }
|
||||||
num-bigint = { workspace = true }
|
num-bigint = { workspace = true }
|
||||||
num-rational = { workspace = true }
|
num-rational = { workspace = true }
|
||||||
num-traits = { workspace = true }
|
num-traits = { workspace = true }
|
||||||
@@ -21,6 +21,7 @@ thiserror = { workspace = true }
|
|||||||
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
marqdo-host = { workspace = true }
|
||||||
marqdo-frontend = { workspace = true }
|
marqdo-frontend = { workspace = true }
|
||||||
marqdo-sandbox = { workspace = true }
|
marqdo-sandbox = { workspace = true }
|
||||||
tempfile = { workspace = true }
|
tempfile = { workspace = true }
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use marqdo_host::{HostOp, ResourceRead};
|
use marqdo_host_contract::{HostOp, ResourceRead};
|
||||||
use marqdo_ir::builtins::Builtin;
|
use marqdo_ir::builtins::Builtin;
|
||||||
use marqdo_ir::Resource;
|
use marqdo_ir::Resource;
|
||||||
use marqdo_span::Span;
|
use marqdo_span::Span;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
|
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
|
||||||
use marqdo_host::{
|
use marqdo_host_contract::{
|
||||||
ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
|
ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
|
||||||
RuntimeObservation,
|
RuntimeObservation,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
//! The interpreter is Marqdo's own execution engine: expressions, scoping,
|
//! The interpreter is Marqdo's own execution engine: expressions, scoping,
|
||||||
//! calls, branches, loops and returns are evaluated here, never by translating
|
//! calls, branches, loops and returns are evaluated here, never by translating
|
||||||
//! to Python or another language. Every side effect goes through
|
//! to Python or another language. Every side effect goes through
|
||||||
//! [`marqdo_host::Host`]; prose never reaches this layer because it is absent
|
//! [`marqdo_host_contract::Host`]; prose never reaches this layer because it is absent
|
||||||
//! from the IR.
|
//! from the IR.
|
||||||
|
|
||||||
mod builtins_impl;
|
mod builtins_impl;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! End-to-end interpreter tests: Markdown source → frontend IR → execution.
|
//! End-to-end interpreter tests: Markdown source → frontend IR → execution.
|
||||||
|
|
||||||
use marqdo_host::{Capabilities, Host, StdHost};
|
use marqdo_host::{Capabilities, StdHost};
|
||||||
|
use marqdo_host_contract::Host;
|
||||||
use marqdo_ir::{ModuleId, Program};
|
use marqdo_ir::{ModuleId, Program};
|
||||||
use marqdo_runtime::{run, run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
|
use marqdo_runtime::{run, run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ use std::cell::RefCell;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use marqdo_host::{
|
use marqdo_host::{
|
||||||
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
|
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, StdHost,
|
||||||
ParameterSource, StdHost, ValueState,
|
ValueState,
|
||||||
};
|
};
|
||||||
|
use marqdo_host_contract::ParameterSource;
|
||||||
use marqdo_ir::{ModuleId, Program};
|
use marqdo_ir::{ModuleId, Program};
|
||||||
use marqdo_runtime::run;
|
use marqdo_runtime::run;
|
||||||
use marqdo_sandbox::SandboxMode;
|
use marqdo_sandbox::SandboxMode;
|
||||||
|
|||||||
@@ -53,6 +53,9 @@ pub mod codes {
|
|||||||
pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function";
|
pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function";
|
||||||
/// A signature was inferred rather than declared.
|
/// A signature was inferred rather than declared.
|
||||||
pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature";
|
pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature";
|
||||||
|
/// A canonical identity would be ambiguous (a separator appears inside a
|
||||||
|
/// component), so no injective public identity can be produced.
|
||||||
|
pub const SEM_AMBIGUOUS_IDENTITY: &str = "sem.ambiguous_identity";
|
||||||
/// An executable payload failed to parse as an expression or statement.
|
/// An executable payload failed to parse as an expression or statement.
|
||||||
pub const EXPR_PARSE: &str = "expr.parse";
|
pub const EXPR_PARSE: &str = "expr.parse";
|
||||||
/// A function name is referenced but no such function exists.
|
/// A function name is referenced but no such function exists.
|
||||||
@@ -69,6 +72,12 @@ pub mod codes {
|
|||||||
pub const MODULE_CYCLE: &str = "module.cycle";
|
pub const MODULE_CYCLE: &str = "module.cycle";
|
||||||
/// A Markdown reference or link target cannot be resolved.
|
/// A Markdown reference or link target cannot be resolved.
|
||||||
pub const REF_UNRESOLVED: &str = "ref.unresolved";
|
pub const REF_UNRESOLVED: &str = "ref.unresolved";
|
||||||
|
/// A Markdown reference has several exact canonical-name candidates.
|
||||||
|
pub const REF_AMBIGUOUS: &str = "ref.ambiguous";
|
||||||
|
/// A Markdown reference is malformed or outside the allowed scope.
|
||||||
|
pub const REF_INVALID: &str = "ref.invalid";
|
||||||
|
/// A Markdown reference target was not verified by the current catalog.
|
||||||
|
pub const REF_NOT_LOADED: &str = "ref.not_loaded";
|
||||||
/// The requested math operation is outside the supported subset.
|
/// The requested math operation is outside the supported subset.
|
||||||
pub const MATH_UNSUPPORTED: &str = "math.unsupported";
|
pub const MATH_UNSUPPORTED: &str = "math.unsupported";
|
||||||
/// A foreign language kernel is not available on this machine.
|
/// A foreign language kernel is not available on this machine.
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
# Marqdo CLI:语言规范、架构与开发总纲
|
# Marqdo CLI:语言规范、架构与开发总纲
|
||||||
|
|
||||||
|
> **Historical planning input (not current requirements).** This blueprint is an
|
||||||
|
> archived design baseline, not current architecture or status. The current
|
||||||
|
> architecture and dependency rules are
|
||||||
|
> [`architecture/CURRENT.md`](architecture/CURRENT.md) and
|
||||||
|
> [ADR-0071](adr/0071-engine-host-contract-boundary.md); executed state is
|
||||||
|
> [`STATUS.md`](STATUS.md). Do not derive a current gate or a crate split from
|
||||||
|
> this file.
|
||||||
|
>
|
||||||
> **状态**:架构基线提案 M0.5 / 新仓库实施蓝图(不是已实现功能清单)
|
> **状态**:架构基线提案 M0.5 / 新仓库实施蓝图(不是已实现功能清单)
|
||||||
> **面向**:语言设计者、编译器/运行时开发者、插件开发者、贡献者及自动化编码智能体
|
> **面向**:语言设计者、编译器/运行时开发者、插件开发者、贡献者及自动化编码智能体
|
||||||
> **日期**:2026-11-20
|
> **日期**:2026-11-20
|
||||||
> **建议仓库位置**:`docs/DEVELOPMENT_BLUEPRINT.md`
|
> **建议仓库位置**:`docs/DEVELOPMENT_BLUEPRINT.md`
|
||||||
> **优先阅读**:本文件 → `spec/` 形式规范 → `tests/conformance/` 金样 → 相关模块源码
|
> **优先阅读(归档语境)**:本文件 → `spec/` 形式规范 → `tests/conformance/` 金样 → 相关模块源码。当前入口请改用 `docs/architecture/CURRENT.md`、`docs/architecture/RFC-LANG-0002-unified-semantics.md` 与 `docs/developers/README.md`。
|
||||||
> **约定**:**[D]** 已确定的设计方向;**[P]** 本文提出的可实现细节,须经形式化测试和 ADR 批准后冻结;**[F]** 后期能力,不应阻塞首个独立运行版本。
|
> **约定**:**[D]** 已确定的设计方向;**[P]** 本文提出的可实现细节,须经形式化测试和 ADR 批准后冻结;**[F]** 后期能力,不应阻塞首个独立运行版本。
|
||||||
|
|
||||||
> **语言映射状态(2026-11-21,必读)**:本文档原本是 M0.5/M0.6 期的架构蓝图,其中关于 Markdown 程序角色的描述(旧映射:`Strong`=执行、`Emph`=返回、有序列表=分支、无序列表=循环、引用块=调用、首个独立 CodeSpan=签名)**已被废止,仅作为历史设计记录**。现行唯一语言语义权威是
|
> **语言映射状态(2026-11-21,必读)**:本文档原本是 M0.5/M0.6 期的架构蓝图,其中关于 Markdown 程序角色的描述(旧映射:`Strong`=执行、`Emph`=返回、有序列表=分支、无序列表=循环、引用块=调用、首个独立 CodeSpan=签名)**已被废止,仅作为历史设计记录**。现行唯一语言语义权威是
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
3. 冻结 CLI 的外部仓库黑盒验收在**发布 SHA**重新执行,至少 pure pinned-Git 包、Callable Worker、陌生 Foreign Kernel、Provider v2、Tool/Analysis/Trace、权限负例及工件改动负例全部 PASS;生成并校验 `docs/evidence/extension/<SHA>/manifest.json`。
|
3. 冻结 CLI 的外部仓库黑盒验收在**发布 SHA**重新执行,至少 pure pinned-Git 包、Callable Worker、陌生 Foreign Kernel、Provider v2、Tool/Analysis/Trace、权限负例及工件改动负例全部 PASS;生成并校验 `docs/evidence/extension/<SHA>/manifest.json`。
|
||||||
4. 冷安装、离线 `--version`/`--help`、`check/run/call`、lock/sync、Tool 安装与分发、Provider Worker 启动、错 SHA/错目标/未授权拒绝全部由发布归档中的**实际二进制**完成;不得依赖开发源码目录。
|
4. 冷安装、离线 `--version`/`--help`、`check/run/call`、lock/sync、Tool 安装与分发、Provider Worker 启动、错 SHA/错目标/未授权拒绝全部由发布归档中的**实际二进制**完成;不得依赖开发源码目录。
|
||||||
5. **不得虚假宣传安全隔离。** 发布包若保留并开放 Linux `strict`,必须有该 SHA 的真实 G3 隔离负例证据;若暂无证据,需采用明确经过测试的 fail-closed 禁用方式并在公告中写 `strict: unsupported`。不允许仅改 README 却继续将未验证的 `strict` 描述为安全保障。Beta 的这一策略必须经维护者明确签字并由 CI 可复查。
|
5. **不得虚假宣传安全隔离。** 发布包若保留并开放 Linux `strict`,必须有该 SHA 的真实 G3 隔离负例证据;若暂无证据,需采用明确经过测试的 fail-closed 禁用方式并在公告中写 `strict: unsupported`。不允许仅改 README 却继续将未验证的 `strict` 描述为安全保障。Beta 的这一策略必须经维护者明确签字并由 CI 可复查。
|
||||||
6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta-only WARN** 并公开环境和限制;必须通过 9 个正确性基准,不允许数值漂移或已确认的灾难性回退。
|
6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta/RC-only WARN** 并公开环境和限制;必须通过正确性基准,不允许数值漂移或已确认的灾难性回退。RC 允许经维护者批准的共享节点 WARN;最终 stable/LTS 必须使用专用固定节点,该共享节点例外不延续到 LTS。
|
||||||
7. 明确产品版本 `3.0.0-beta.1` 与协议独立版本;工具 SemVer 协商在真实测试版上可安装、拒绝不兼容范围、不会误把 `<1` 当成支持 3.x。
|
7. 明确产品版本 `3.0.0-beta.1` 与协议独立版本;工具 SemVer 协商在真实测试版上可安装、拒绝不兼容范围、不会误把 `<1` 当成支持 3.x。
|
||||||
8. `README`、`CHANGELOG`、`COMPATIBILITY`、`docs/STATUS`、`docs/releasing`、协议入口页、迁移说明,均更新至同一事实基线;无“未实现却声称已发布”或“已实现仍称 Proposed”的矛盾。
|
8. `README`、`CHANGELOG`、`COMPATIBILITY`、`docs/STATUS`、`docs/releasing`、协议入口页、迁移说明,均更新至同一事实基线;无“未实现却声称已发布”或“已实现仍称 Proposed”的矛盾。
|
||||||
9. 不发布未经实际构建/烟测的平台二进制;产物附 SHA256、SOURCE_SHA、构建工具链信息和已知限制。
|
9. 不发布未经实际构建/烟测的平台二进制;产物附 SHA256、SOURCE_SHA、构建工具链信息和已知限制。
|
||||||
|
|||||||
@@ -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,绝不默认为支持。
|
||||||
|
|||||||
+197
-33
@@ -1,13 +1,18 @@
|
|||||||
# Marqdo Implementation Status
|
# Marqdo Implementation Status
|
||||||
|
|
||||||
Snapshot: **2026-11-22**, product version **`3.0.0-beta.1`** (prerelease, tag
|
Snapshot: **2026-11-25**, product version **`3.0.0-rc.4`** (prerelease,
|
||||||
`v3.0.0-beta.1`). Released platform: **Linux x86_64 (glibc)**. Tagged source
|
released). Tag `v3.0.0-rc.4` at source SHA
|
||||||
SHA: **`2c7c4f31e7a388d3fcfa717a77067e696ed13854`**; release:
|
**`452e9a32bd9e40dba427d4180691c58bab74449e`**; release:
|
||||||
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. The
|
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4. The previous release is `3.0.0-rc.3` at source SHA
|
||||||
same-SHA evidence aggregate is
|
**`1e2a045cc78bf40972181abb44e7117c56cf4401`**; release:
|
||||||
[`evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3. The supported
|
||||||
(decision `BETA_RELEASE_CANDIDATE`); binary hashes are in the archive's
|
platform is **Linux x86_64 (glibc 2.39)**. The rc.3 same-SHA gate aggregate is
|
||||||
`RELEASE_INFO.json`. Do not copy a SHA from a plan.
|
[`evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
|
||||||
|
(decision `RC_RELEASE_CANDIDATE`); its binary hashes are in that archive's
|
||||||
|
`RELEASE_INFO.json`, not in the rc.4 candidate. Previous prereleases:
|
||||||
|
`3.0.0-rc.2` at `9149ee40a48fcda692c5c112f66c465487d13dfb` and
|
||||||
|
`3.0.0-beta.1` at `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. Do not copy a
|
||||||
|
SHA from a plan.
|
||||||
|
|
||||||
Current architecture overview:
|
Current architecture overview:
|
||||||
[`architecture/CURRENT.md`](architecture/CURRENT.md).
|
[`architecture/CURRENT.md`](architecture/CURRENT.md).
|
||||||
@@ -16,9 +21,11 @@ Authoritative release policy:
|
|||||||
evidence). Support matrix: [`../COMPATIBILITY.md`](../COMPATIBILITY.md).
|
evidence). Support matrix: [`../COMPATIBILITY.md`](../COMPATIBILITY.md).
|
||||||
Developer entry point: [`developers/README.md`](developers/README.md).
|
Developer entry point: [`developers/README.md`](developers/README.md).
|
||||||
|
|
||||||
This file records what was actually executed. "Implemented" does not mean
|
The rc.4 same-SHA gate aggregate is
|
||||||
"verified on every platform"; the evidence column says which commands were run
|
[`evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`](evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json)
|
||||||
and where. Status is generated from executed commands/logs; a gate row without a
|
(decision `RC_RELEASE_CANDIDATE`). This file records what was actually executed.
|
||||||
|
"Implemented" does not mean "verified on every platform"; the evidence column
|
||||||
|
says which commands were run and where. Status is generated from executed commands/logs; a gate row without a
|
||||||
command, log or source path is a defect, not a state. Historical snapshots
|
command, log or source path is a defect, not a state. Historical snapshots
|
||||||
(including M0.5 and the pre-beta `0.1.0` candidate) are preserved under
|
(including M0.5 and the pre-beta `0.1.0` candidate) are preserved under
|
||||||
[`history/`](history/README.md) and [`evidence/`](evidence/) and must not be read
|
[`history/`](history/README.md) and [`evidence/`](evidence/) and must not be read
|
||||||
@@ -26,11 +33,11 @@ as current status.
|
|||||||
|
|
||||||
## RC candidate
|
## RC candidate
|
||||||
|
|
||||||
The workspace reports `3.0.0-rc.3` and declares Rust 1.89 as its locked
|
The workspace reports `3.0.0-rc.4` 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 supported platform. The rc.4
|
||||||
[release procedure](releasing.md) requires a green manifest bound to the
|
manifest is green on its SHA with the documented strict-VM PASS and a
|
||||||
candidate SHA before publication. The release record below refers to the
|
maintainer-approved shared-node performance `WARN`; stable/LTS still requires a
|
||||||
published beta.
|
dedicated fixed node. The release records below refer to their tagged binaries.
|
||||||
|
|
||||||
## Current protocol integration
|
## Current protocol integration
|
||||||
|
|
||||||
@@ -68,6 +75,129 @@ The `spec/` tree contains only current contracts; retired specifications are in
|
|||||||
Git history and tagged archives. The earlier release records below describe
|
Git history and tagged archives. The earlier release records below describe
|
||||||
their tagged binaries and are not current protocol claims.
|
their tagged binaries and are not current protocol claims.
|
||||||
|
|
||||||
|
## 0.12 Engine / Host Contract boundary — issue #13 (unreleased candidate)
|
||||||
|
|
||||||
|
This is an **internal architecture candidate**, not a release. The product
|
||||||
|
version stays `3.0.0-rc.4`; no new tag or release claim is made. Baseline is
|
||||||
|
`master` at `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`; the PR records the exact
|
||||||
|
candidate SHA and evidence is
|
||||||
|
[`evidence/2026-11-26-issue-13-engine-host-boundary.md`](evidence/2026-11-26-issue-13-engine-host-boundary.md).
|
||||||
|
|
||||||
|
Implemented in the candidate:
|
||||||
|
|
||||||
|
- `marqdo-host-contract` owns the only Host trait/HostOp/ExecutionContext/
|
||||||
|
ResourceRead and runtime observation facts. `marqdo-runtime` depends on it,
|
||||||
|
never on `marqdo-host` in normal/build edges. `marqdo-host` implements it and
|
||||||
|
has no reverse dependency on runtime/frontend/IR.
|
||||||
|
- `tests/embedding` is a real independent Cargo workspace/lock consumer that
|
||||||
|
builds without the native host, executes the real Markdown→frontend→IR→runtime
|
||||||
|
path with real fuel/stack/deadline/memory limits and explicit effect
|
||||||
|
refusals, and matches a real CLI invocation on the same `.mq.md` for `Int` and
|
||||||
|
structural values.
|
||||||
|
- `marqdo-plugin-abi` is a contract crate only (C ABI, wire, errors);
|
||||||
|
manifest/artifact validation, `dlopen` and worker process live in
|
||||||
|
`marqdo-host::plugin`. `marqdo-plugin-sdk` transitively carries no loader,
|
||||||
|
worker, host or sandbox dependency.
|
||||||
|
- `tests/sdk-plugin` builds a third-party plugin with only the public SDK; the
|
||||||
|
real CLI loads/invokes it with explicit trust/grant and rejects a tampered
|
||||||
|
artifact digest.
|
||||||
|
- Dependency direction is enforced from Cargo metadata by
|
||||||
|
`tools/ci/check_dependency_boundaries.py` (with negative unit cases) and
|
||||||
|
`cargo test -p marqdo-cli --test architecture_boundaries`.
|
||||||
|
- The current architecture/developer entry and ADR-0071 record the
|
||||||
|
**keep-in-workspace** repository decision; no empty candidate repository was
|
||||||
|
created.
|
||||||
|
|
||||||
|
Executed in this environment (Linux x86_64, Rust 1.100): formatting, clippy,
|
||||||
|
locked workspace tests (**636 passed / 0 failed / 2 ignored**;
|
||||||
|
baseline `4bbefc9` 633 passed / 0 failed / 2 ignored, so no regression), docs/architecture gates, dependency gate, engine
|
||||||
|
differential gate and SDK gate PASS. The Windows GNU cross-target compile check
|
||||||
|
passes; it is not a native Windows runtime claim. Woodpecker PR pipeline #101
|
||||||
|
for code SHA `9b4f0a0` is **success**, including the `build` step (release
|
||||||
|
archive from that SHA, archive smoke, frozen external conformance) and the
|
||||||
|
`minimum-rust` lane; that is same-candidate CI evidence, not a release tag.
|
||||||
|
Deliberately **UNVERIFIED** here: Windows/macOS native lanes, strict VM, WASM
|
||||||
|
probe (target std not installed; `E0463`, not a forbidden native dependency)
|
||||||
|
and performance/RSS. RC.4 evidence is not reused.
|
||||||
|
|
||||||
|
Remaining, separately owned work: stdlib Bundle Phase B (issue #11/#12),
|
||||||
|
SDK physical repository after S07/S08, regex/compression replacement under
|
||||||
|
ADR-0062, foreign F-B (ADR-0063), platform and strict evidence, and the Engine/
|
||||||
|
Native Host split only if the ADR-0071 reopening conditions appear.
|
||||||
|
|
||||||
|
## 0.13 Independent plugin SDK repository — issue #15 (unreleased candidate)
|
||||||
|
|
||||||
|
This is a repository-ownership/architecture change, not a new product release.
|
||||||
|
The contract and plugin ABI behaviour are unchanged. Evidence:
|
||||||
|
[`evidence/2026-11-26-issue-15-sdk-independent-repository.md`](evidence/2026-11-26-issue-15-sdk-independent-repository.md);
|
||||||
|
decision: [ADR-0072](adr/0072-sdk-independent-repository.md).
|
||||||
|
|
||||||
|
- The Rust SDK moved to the public repository
|
||||||
|
[`cflmy/marqdo-plugin-sdk`](https://git.cflmy.cn/cflmy/marqdo-plugin-sdk)
|
||||||
|
(commit `b31187a`), with its own workspace/lock, AGENTS rules, README, license
|
||||||
|
and Woodpecker pipeline definition.
|
||||||
|
- It consumes `marqdo-plugin-abi` from the CLI repository at the exact
|
||||||
|
`rev = 2585915e16906dac75f8571bed02e7f6f868c6bc`; it never uses a `../cli`
|
||||||
|
path, a floating branch, a submodule or a copied ABI/Value Wire.
|
||||||
|
- The CLI repository no longer contains `crates/marqdo-plugin-sdk`,
|
||||||
|
`tests/sdk-plugin` or the CLI-side SDK gate; the SDK does not appear in the
|
||||||
|
workspace or `Cargo.lock`. The CLI does not depend on the SDK.
|
||||||
|
- Clean-clone SDK build/tests and a real integration against the frozen
|
||||||
|
released `3.0.0-rc.4` CLI pass (`Int 42`, tampered digest rejected). CLI
|
||||||
|
workspace tests: 631 passed / 0 failed / 0 ignored (the five SDK tests moved
|
||||||
|
to the SDK repository). The SDK
|
||||||
|
repository's CI repeats those checks; enabling the Woodpecker project for the
|
||||||
|
new repository is an administrative follow-up, not a code claim.
|
||||||
|
- Engine/Native Host remain in the CLI workspace under ADR-0071; no other
|
||||||
|
repository split is approved by this change.
|
||||||
|
|
||||||
|
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released)
|
||||||
|
|
||||||
|
The candidate replaces the program-only Analysis projection in place under
|
||||||
|
[ADR-0069](adr/0069-public-analysis-boundary.md): exact source and document
|
||||||
|
AST, complete heading scopes and anchors, entry/manifest/lock/stdlib/extension
|
||||||
|
snapshot identity, one shared document-link resolver with explicit states,
|
||||||
|
calls with target kind/owner/reason, and an owner-only atomic `--emit` writer.
|
||||||
|
The retired duplicate resolver and the post-preparation lock re-read are gone.
|
||||||
|
Local evidence and raw numbers:
|
||||||
|
[`evidence/2026-11-25-rc.4-analysis-boundary.md`](evidence/2026-11-25-rc.4-analysis-boundary.md).
|
||||||
|
|
||||||
|
Executed 2026-11-25 in the local Linux x86_64 development container
|
||||||
|
(workspace `3.0.0-rc.4`, Rust 1.100.0):
|
||||||
|
|
||||||
|
```text
|
||||||
|
cargo fmt --all -- --check PASS
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||||
|
cargo test --workspace --locked PASS
|
||||||
|
cargo test -p marqdo-cli --test analysis_boundary PASS
|
||||||
|
cargo test -p marqdo-cli --test analysis_observation PASS
|
||||||
|
cargo test -p marqdo-cli --test integration_cli PASS
|
||||||
|
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker PASS
|
||||||
|
python3 tests/consumers/analysis_consumer.py <artifact> PASS
|
||||||
|
python3 tests/consumers/validate_protocols.py <analysis> <observation> <tool> PASS
|
||||||
|
python3 tests/consumers/view_consumer.py <artifact> PASS
|
||||||
|
python3 tests/consumers/lint_consumer.py <artifact> PASS
|
||||||
|
python3 tests/consumers/knowledge_consumer.py <artifact...> PASS
|
||||||
|
```
|
||||||
|
|
||||||
|
Local development-container performance against the rc.3 archive binary on a
|
||||||
|
101-module fixture (p95 ratio, peak-RSS ratio): no-emit `0.999 / 1.001`,
|
||||||
|
`--emit` `1.210 / 1.186`, `--refs` `1.145 / 1.093`. These are smoke numbers,
|
||||||
|
not a dedicated-node G4 result.
|
||||||
|
|
||||||
|
Same-SHA CI ([pipeline #94](https://ci.cflmy.cn/repos/1/pipeline/94)) is PASS
|
||||||
|
for `452e9a3` on all four lanes; its build lane packaged the archive, ran smoke
|
||||||
|
and the frozen extension suite 7/7. The local same-SHA archive passed smoke,
|
||||||
|
the archive-only Ubuntu 24.04 cold-install container and frozen conformance
|
||||||
|
7/7. Strict L1 PASS is recorded from a disposable QEMU/TCG VM as non-root
|
||||||
|
`dev` (uid 1000), with the archived binary re-verified in that VM. Performance
|
||||||
|
is a maintainer-approved shared-node `WARN` for this RC only; stable/LTS still
|
||||||
|
requires a dedicated fixed node. The gate aggregate is
|
||||||
|
[`evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`](evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json)
|
||||||
|
(`RC_RELEASE_CANDIDATE`). Release
|
||||||
|
[notes and assets](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4).
|
||||||
|
Downstream migration issues: `marqdo-view#6`, `marqdo-lint#4`.
|
||||||
|
|
||||||
## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate)
|
## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate)
|
||||||
|
|
||||||
The current tree replaces the retired protocols in place, with no compatibility
|
The current tree replaces the retired protocols in place, with no compatibility
|
||||||
@@ -76,19 +206,21 @@ path. Policy: [ADR-0068](adr/0068-single-current-public-contracts.md) and
|
|||||||
section records commands executed on the candidate tree; it is local Linux
|
section records commands executed on the candidate tree; it is local Linux
|
||||||
evidence, not a same-SHA CI or archive gate.
|
evidence, not a same-SHA CI or archive gate.
|
||||||
|
|
||||||
Executed 2026-11-24 on Linux x86_64 (workspace `3.0.0-rc.3`, Rust 1.93.1):
|
Executed 2026-11-24 on the reviewed candidate tree, Linux x86_64
|
||||||
|
(workspace `3.0.0-rc.3`, Rust 1.100.0):
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cargo fmt --all -- --check PASS
|
cargo fmt --all -- --check PASS
|
||||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||||
cargo test --workspace --locked PASS: 601 passed, 0 failed, 2 ignored
|
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 architecture_boundaries PASS: 12 passed
|
||||||
cargo test -p marqdo-cli --test docs_consistency PASS: 5 passed
|
cargo test -p marqdo-cli --test docs_consistency PASS: 7 passed
|
||||||
cargo test -p marqdo-cli --test observation PASS: 15 passed
|
cargo test -p marqdo-cli --test observation PASS: 16 passed
|
||||||
cargo test -p marqdo-cli --test analysis_observation PASS: 10 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 tool_protocol PASS: 7 passed
|
||||||
cargo test -p marqdo-cli --test extension_selection PASS: 14 passed
|
cargo test -p marqdo-cli --test extension_selection PASS: 14 passed
|
||||||
cargo test -p marqdo-worker-ipc PASS: 5 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`:
|
Black-box consumer run against the real `target/debug/marqdo`:
|
||||||
@@ -107,7 +239,7 @@ observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected
|
|||||||
marqdo --version marqdo 3.0.0-rc.3
|
marqdo --version marqdo 3.0.0-rc.3
|
||||||
```
|
```
|
||||||
|
|
||||||
Same-SHA CI on Linux x86_64
|
Same-SHA CI on the first (pre-review) candidate build, Linux x86_64
|
||||||
([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit
|
([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit
|
||||||
`5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full
|
`5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full
|
||||||
Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows
|
Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows
|
||||||
@@ -119,16 +251,47 @@ passed the from-archive smoke, and passed the frozen external conformance suite
|
|||||||
(callable registry, plugin worker, foreign kernel, provider CLI, pinned package,
|
(callable registry, plugin worker, foreign kernel, provider CLI, pinned package,
|
||||||
tool Analysis consumer, negative security).
|
tool Analysis consumer, negative security).
|
||||||
|
|
||||||
The detailed local log and the CI addendum are in
|
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).
|
[`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.
|
||||||
|
|
||||||
Release status: the tree, contracts, archive and same-SHA Linux CI are ready for
|
### 0.9.1 Review closure on the candidate tree
|
||||||
`3.0.0-rc.3`, but **publication is not authorized by this evidence**. The RC
|
|
||||||
profile in [`releasing.md`](releasing.md) additionally requires a same-SHA
|
A code review of the first candidate build found and closed these defects
|
||||||
strict-L1 PASS on a disposable VM as a non-root user and fixed-node G4
|
(regression test for each):
|
||||||
performance evidence (or the recorded maintainer exception). Neither exists
|
|
||||||
here; the CI host truthfully reports `strict: unavailable` fail-closed. Do not
|
- A strict run no longer emits a partial JSONL stream for a destination it
|
||||||
tag or publish `v3.0.0-rc.3` from this section.
|
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: **published as `v3.0.0-rc.3`**. The RC profile gates in
|
||||||
|
[`releasing.md`](releasing.md) were executed on the tagged SHA: same-SHA Linux
|
||||||
|
CI (formatted, clippy-clean, 607 workspace tests, contract lane, minimum Rust
|
||||||
|
1.89, build lane with from-archive smoke and frozen extensions 7/7), the
|
||||||
|
archive-only clean install, frozen external conformance against the published
|
||||||
|
archive, version compatibility, a disposable-VM strict L1 PASS as non-root with
|
||||||
|
the published archive re-verified in that guest, and three paired shared-node
|
||||||
|
G4 runs whose maintainer-approved `WARN` is recorded for this named RC. The
|
||||||
|
per-gate manifest, release notes and logs are in
|
||||||
|
[`evidence/2026-11-24-rc.3-release.md`](evidence/2026-11-24-rc.3-release.md),
|
||||||
|
[`evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json) and 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`
|
||||||
|
|
||||||
@@ -613,8 +776,9 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
|||||||
- Test and documentation migration (review RFC-CM P0/P2):
|
- Test and documentation migration (review RFC-CM P0/P2):
|
||||||
`crates/cli/tests/docs_consistency.rs` pins one current overview, the
|
`crates/cli/tests/docs_consistency.rs` pins one current overview, the
|
||||||
status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs`
|
status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs`
|
||||||
pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib
|
pins the workspace graph, `marqdo-runtime -> marqdo-host` (historical at that
|
||||||
digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
|
snapshot; the current edge is `marqdo-runtime -> marqdo-host-contract` under
|
||||||
|
ADR-0071), the bundled stdlib digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
|
||||||
runs every public stdlib module (`clock/compress/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`)
|
runs every public stdlib module (`clock/compress/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`)
|
||||||
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
|
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
|
||||||
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
|
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
|
||||||
|
|||||||
@@ -6,9 +6,10 @@
|
|||||||
- **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
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# ADR-0069 — One public Analysis boundary for independent static tools
|
||||||
|
|
||||||
|
Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-25).
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Issue [#10](https://git.cflmy.cn/cflmy/marqdo-cli/issues/10) audited the
|
||||||
|
public Analysis contract at `master@e6066e6`. The CLI already restricts
|
||||||
|
View/Lint-style consumers to installed Tools, but the emitted
|
||||||
|
`marqdo.analysis` document only exposed program IR. It omitted the Markdown
|
||||||
|
document AST, the exact source text, the entry/context snapshot, heading
|
||||||
|
scopes and anchors, complete section ranges, and reference resolution states.
|
||||||
|
Independent tools therefore had to re-parse Markdown, guess section ends or run
|
||||||
|
a second non-public analysis path. Two implementations of Markdown-link
|
||||||
|
resolution existed (`analysis.rs` and `commands.rs`), the Analysis `unresolved`
|
||||||
|
state could not distinguish "not loaded" from "missing", and `analysis.rs`
|
||||||
|
re-read `marqdo.lock` after preparation.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
`marqdo check ENTRY --emit PATH` remains the only public static-analysis
|
||||||
|
producer. Before the first stable release, replace `marqdo.analysis` revision 3
|
||||||
|
in place under ADR-0068. There is one shape, one producer and one validation
|
||||||
|
path; retired fields are not read.
|
||||||
|
|
||||||
|
The projection is built by one typed encoder from the same
|
||||||
|
`project_prepare::prepare` facts consumed by `check`, `inspect`, `run` and
|
||||||
|
`call`:
|
||||||
|
|
||||||
|
* `project.entry_module_id`, `manifest_digest`, the captured `lock_digest`,
|
||||||
|
stdlib identity and the static extension identities that actually took part
|
||||||
|
in preparation;
|
||||||
|
* each loaded module's exact UTF-8 `source` and its `source_digest`, plus the
|
||||||
|
public Markdown AST (`document`) in the shape already described by
|
||||||
|
`spec/markdown-profile.md`;
|
||||||
|
* one heading index: canonical path, parent, effective mode, mode origin and
|
||||||
|
source unit, heading span, complete section span and the function created by
|
||||||
|
an Exec H2;
|
||||||
|
* the anchor map, functions, explicit imports, resources, static call bindings
|
||||||
|
and diagnostics;
|
||||||
|
* every Markdown link through one scoped `document_refs` resolver that
|
||||||
|
distinguishes `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`,
|
||||||
|
`outside_scope` and `invalid`.
|
||||||
|
|
||||||
|
The resolver is a pure function over an explicit catalog. Ordinary Analysis
|
||||||
|
uses the loaded-module catalog and never opens a link target. `check --refs`
|
||||||
|
and `inspect --refs` build a separate, explicitly limited catalog for direct
|
||||||
|
link targets and append diagnostics; they do not change the ordinary Analysis
|
||||||
|
module set and never execute or import a target.
|
||||||
|
|
||||||
|
Identity strings stay the current presentation for names that do not contain
|
||||||
|
the structural separators. Unit paths are now also exposed as the structured
|
||||||
|
`path` array, and identity display escapes `/`, `#` and `%` inside a path
|
||||||
|
segment so `<module>#<seg>/<seg>` cannot collide with a segment containing
|
||||||
|
`/`. `Function.local_name` and `namespace` remain structured fields; consumers
|
||||||
|
must not split display ids.
|
||||||
|
|
||||||
|
The public source field is an explicit local artifact. It is written with
|
||||||
|
owner-only permissions where the platform supports them, is never copied into
|
||||||
|
Observation, is never printed by default, and its digestion is the exact
|
||||||
|
UTF-8 bytes (SHA-256). Observation continues to bind to the SHA-256 of the
|
||||||
|
exact bytes emitted by `check --emit` with the same static options.
|
||||||
|
|
||||||
|
## Security and verification
|
||||||
|
|
||||||
|
The boundary remains non-executing: no plugin shared library, worker, foreign
|
||||||
|
kernel, network request or implicit module load. `--emit` publishes atomically
|
||||||
|
through an owner-only exclusive temporary file and rename, refuses to overwrite
|
||||||
|
a loaded source, manifest, lock file, symlink to one, or a hard link to one,
|
||||||
|
and only removes a previous artifact at a caller-specified output path under
|
||||||
|
the same guard.
|
||||||
|
|
||||||
|
Production checks local typed invariants and the canonical encoder; an
|
||||||
|
independent Python consumer validates the emitted bytes against the published
|
||||||
|
JSON Schema and semantic invariants, and mutation fixtures prove that missing
|
||||||
|
required fields, stale same-revision artifacts, tampered digests/spans,
|
||||||
|
duplicate ids, wrong ownership and invalid reference states are rejected.
|
||||||
|
`docs/STATUS.md` records exactly what was executed on which SHA; the
|
||||||
|
pre-stable line makes no compatibility promise for consumers linked to the
|
||||||
|
retired shape.
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
# ADR-0071 — Engine / Host Contract / Native Host / CLI boundaries
|
||||||
|
|
||||||
|
Status: **Accepted** for the pre-stable 3.0 line (2026-11-26).
|
||||||
|
The SDK portion of the repository decision was later implemented by
|
||||||
|
[ADR-0072](0072-sdk-independent-repository.md) (independent public SDK
|
||||||
|
repository pinned to this contract); the Engine/Native Host keep-in-workspace
|
||||||
|
decision is unchanged.
|
||||||
|
|
||||||
|
Supersedes the historical review-RFC position that a Host contract crate is a
|
||||||
|
second-step, optional move. It does not supersede the language contract
|
||||||
|
(ADR-0052 / RFC-LANG-0002), the resource/operation ownership rules (ADR-0062),
|
||||||
|
the foreign F-A boundary (ADR-0063), the single-contract policy (ADR-0068) or
|
||||||
|
the explicit stdlib Bundle build input (ADR-0070 where landed). It replaces only
|
||||||
|
the old architecture-gate constraints that asserted `marqdo-runtime ->
|
||||||
|
marqdo-host` and a frozen crate count.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Issue #13 audited the tree at `4bbefc9…` and found:
|
||||||
|
|
||||||
|
- the runtime linked the native host (`marqdo-host`) even though the interpreter
|
||||||
|
already accepted `&mut dyn Host`;
|
||||||
|
- the `Host` trait, `HostOp` and `StdHost` lived in one module, and
|
||||||
|
`ResourceRead` sat beside real file/TCP/TLS implementations;
|
||||||
|
- the plugin ABI crate contained the C contract, the wire envelope, manifest
|
||||||
|
validation, artifact selection, `dlopen` and the worker process, so the
|
||||||
|
third-party SDK transitively carried execution-side dependencies;
|
||||||
|
- old architecture gates froze sixteen crate names and the
|
||||||
|
runtime-to-native-host edge, so the intended boundary could not be tested;
|
||||||
|
- historical planning documents competed with the current overview as a source
|
||||||
|
of truth.
|
||||||
|
|
||||||
|
The same audit fixed the scope: one language implementation, one contract per
|
||||||
|
public boundary, no second interpreter, no new runtime protocol, no mandatory
|
||||||
|
remote repository split, and no empty candidate repositories. Missing
|
||||||
|
independent-consumer evidence means "keep in the workspace" is the correct
|
||||||
|
repository decision.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
### Responsibilities
|
||||||
|
|
||||||
|
| Layer | Owns | Must not own |
|
||||||
|
|---|---|---|
|
||||||
|
| Engine | Span, Value, expression, the one Markdown profile, IR, frontend mapping/static binding, Runtime evaluation and `Memory`, and the neutral Host contract | concrete OS I/O, sandbox launch, plugin loading, project filesystem, CLI commands |
|
||||||
|
| `marqdo-host-contract` | `Host` trait, `HostOp`, `ExecutionContext`, `ResourceRead`, `FrameId`, `ParameterSource`, `LoopTransfer`, `RuntimeObservation` | native implementation, grant policy, the public Observation wire encoding, any wire/RPC protocol |
|
||||||
|
| Native Host (`marqdo-host` and its sandbox/foreign support crates) | capability broker, resources and handles, OS adapters, budgets/deadlines, observation sink, trusted plugin/provider/foreign execution | language parsing/evaluation, a second static binder, CLI projection |
|
||||||
|
| `marqdo-plugin-abi` | C ABI v1 layout/assertions, wire envelope and protocol errors | `dlopen`, worker/process management, artifact/manifest file execution, capability grants |
|
||||||
|
| `marqdo-host::plugin` | manifest/artifact validation, native loading, worker process, invocation dispatch | a second ABI or wire definition |
|
||||||
|
| `marqdo-plugin-sdk` | third-party developer helpers over the public contract | host, loader, CLI, worker execution, sandbox |
|
||||||
|
| CLI | arguments, single `project_prepare`, command routing, product Analysis/Observation projection, Tool install/dispatch, Host+Runtime assembly | language evaluation, domain algorithms, a second binding path |
|
||||||
|
|
||||||
|
### Dependency rules
|
||||||
|
|
||||||
|
- `marqdo-runtime -> marqdo-host-contract` only. The engine crates must not reach
|
||||||
|
`marqdo-host`, sandbox, foreign, plugin ABI/SDK, worker, package, CLI,
|
||||||
|
`libloading`, `rustls` or other native/domain dependencies on normal or build
|
||||||
|
edges.
|
||||||
|
- `marqdo-host-contract -> marqdo-value, marqdo-span` only.
|
||||||
|
- The native host may implement the contract and consume the public ABI, but it
|
||||||
|
must not depend back on runtime, frontend, IR or the CLI.
|
||||||
|
- The CLI is the only composition root allowed to combine engine + native host +
|
||||||
|
package. `check`/`inspect` never load a native library, start a worker or
|
||||||
|
access the network.
|
||||||
|
- `marqdo-plugin-sdk` consumes only `marqdo-plugin-abi`; it must not depend on a
|
||||||
|
loader, host, worker process, sandbox or CLI.
|
||||||
|
- There is no second `Host`/`HostOp`, no second Value encoding, no
|
||||||
|
`EngineValue`/`HostValue`/`WireIR`, no HTTP/RPC/JSON handshake for the
|
||||||
|
engine-to-host edge and no `legacy` feature. The Rust trait is an internal
|
||||||
|
compile-time interface inside one codebase.
|
||||||
|
|
||||||
|
### Invariants preserved (not moved, not weakened)
|
||||||
|
|
||||||
|
- Fuel, stack depth, deadline, output budget and `Memory` limits stay owned and
|
||||||
|
checked exactly where they were; replacing the host must not remove a check.
|
||||||
|
The contract carries the calls, not platform-neutral defaults that silently
|
||||||
|
grant unlimited budgets.
|
||||||
|
- Capability grants, resource identity/handles, cleanup, provider registration,
|
||||||
|
strict isolation, plugin trust, foreign supervision and observation privacy
|
||||||
|
stay owned by the native host and CLI. `check`/`inspect` stay non-executing.
|
||||||
|
- Static binding remains single: one registry, one `bind_program_calls`, one
|
||||||
|
`CallBindingTable`; the runtime never re-resolves names.
|
||||||
|
- Public protocols are unchanged: Analysis revision 3, Observation revision 1,
|
||||||
|
Tool revision 1, Plugin ABI 1.0, Value Wire 1, Provider v2, lock v4. Moving
|
||||||
|
Rust modules is not a protocol change.
|
||||||
|
- Stdlib runtime contract is unchanged. Phase A/B of issue #11/#12 remain a
|
||||||
|
separate delivery; the CLI does not gain a second Bundle format or a dev
|
||||||
|
fallback authority.
|
||||||
|
|
||||||
|
### Repository decision
|
||||||
|
|
||||||
|
The Engine and Native Host stay in this workspace. Issue #13 §9.2 admission is
|
||||||
|
not met: there is no real external Engine consumer or independent platform
|
||||||
|
maintainer, and an empty candidate repository would be a prohibited boundary
|
||||||
|
violation. This ADR records **keep in workspace** as the legal conclusion and
|
||||||
|
names the reopening conditions in `docs/architecture/CURRENT.md` §7.
|
||||||
|
|
||||||
|
The plugin SDK's physical move landed as [ADR-0072](0072-sdk-independent-repository.md):
|
||||||
|
a standalone public repository consumes this contract at one pinned CLI `rev`.
|
||||||
|
The Engine and Native Host stay here; no gitlink/submodule or empty
|
||||||
|
`marqdo-cli-*` repository is created by this ADR.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
The acceptance gates are executable, not documentary:
|
||||||
|
|
||||||
|
- `tools/ci/check_dependency_boundaries.py` reads Cargo metadata for the
|
||||||
|
workspace and the independent consumer, checks the reviewed crate allowlist and
|
||||||
|
the forbidden transitive edges, and is itself covered by
|
||||||
|
`tools/ci/test_dependency_boundaries.py` negative cases.
|
||||||
|
- `tests/embedding` is a separate workspace and lock file; it executes a real
|
||||||
|
`.mq.md` through Markdown → frontend → static binding → runtime with a bounded
|
||||||
|
test host, and rejects fuel/stack/deadline/memory/resource violations.
|
||||||
|
- `tools/ci/check_engine_boundary.py` builds and runs that consumer, builds the
|
||||||
|
real CLI, executes the same file and compares terminal Value Wire results, and
|
||||||
|
checks the runtime build tree.
|
||||||
|
- `tools/ci/check_plugin_sdk.py` builds the SDK fixture with the public SDK and
|
||||||
|
loads it through the real CLI with explicit trust/grant, then rejects a
|
||||||
|
tampered artifact digest.
|
||||||
|
- `cargo test -p marqdo-cli --test architecture_boundaries` keeps the semantic
|
||||||
|
gates (single Host trait, plugin contract split, engine-only consumer, reviewed
|
||||||
|
HostOp/Value/builtin/resource-operation catalogues) and the existing security
|
||||||
|
and product checks.
|
||||||
|
- Evidence for the candidate commit lives in
|
||||||
|
`docs/evidence/2026-11-26-issue-13-engine-host-boundary.md` and
|
||||||
|
`docs/STATUS.md`. Platform lanes not executed here stay `UNVERIFIED`; no old
|
||||||
|
release evidence is reused as a new PASS.
|
||||||
|
|
||||||
|
## Rejected alternatives
|
||||||
|
|
||||||
|
- **Create `marqdo-engine`/`marqdo-host` remote repositories now.** No real
|
||||||
|
consumer, no ownership/release boundary, prohibited empty candidates; would
|
||||||
|
also create a cross-repository atomic-semantics tax.
|
||||||
|
- **Keep the runtime linked to `marqdo-host` and only rename the crate.** Does
|
||||||
|
not close the dependency edge; an embedded consumer would still link native
|
||||||
|
TLS, loading and process code.
|
||||||
|
- **Move the whole `observe` module or CLI projection into the contract.** The
|
||||||
|
interpreter needs only the emitted facts; the sink, redaction and public
|
||||||
|
envelope belong to the host/CLI, and moving them would create a second
|
||||||
|
protocol centre.
|
||||||
|
- **Leave manifest/artifact in the ABI crate.** The SDK would transitively keep
|
||||||
|
`serde_yaml`/digest/native-adjacent code and the contract crate would again own
|
||||||
|
execution-side choices.
|
||||||
|
- **Add a compatibility re-export of the old `marqdo_host::{Host, ...}` paths.**
|
||||||
|
Creates a second active path; all in-tree consumers are updated atomically.
|
||||||
|
- **Loosen the old gates instead of replacing them.** Security, product,
|
||||||
|
protocol and negative tests are retained; only the frozen crate-name and
|
||||||
|
runtime-to-native-host assertions are replaced by the responsibility graph.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- An independent consumer can build and compute without the native host or CLI.
|
||||||
|
- Adding a host capability does not change engine code; adding an engine semantic
|
||||||
|
change does not change host code.
|
||||||
|
- The workspace gains one small contract crate and one plugin module move; crate
|
||||||
|
count is explicitly not a KPI.
|
||||||
|
- Unfinished ecosystem work (stdlib Phase B, SDK physical repository, regex/
|
||||||
|
compression migration, foreign F-B, WASM probe, Windows/macOS/strict evidence)
|
||||||
|
remains open and honestly recorded; none of it is required to close the core
|
||||||
|
M0–M4 boundary work.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# ADR-0072 — Independent `marqdo-plugin-sdk` repository
|
||||||
|
|
||||||
|
Status: **Accepted** (2026-11-26).
|
||||||
|
|
||||||
|
Complements [ADR-0071](0071-engine-host-contract-boundary.md) and implements the
|
||||||
|
SDK follow-up tracked by issue [#15](https://git.cflmy.cn/cflmy/marqdo-cli/issues/15)
|
||||||
|
after the contract decoupling of issue #13.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Issue #13 / ADR-0071 separated the public plugin contract from its execution
|
||||||
|
side:
|
||||||
|
|
||||||
|
- `marqdo-plugin-abi` (CLI repository) now contains only the C ABI v1 layout,
|
||||||
|
the wire envelope and protocol errors;
|
||||||
|
- `dlopen`, manifest/artifact file handling, worker management and invocation
|
||||||
|
dispatch live in `marqdo-host::plugin`;
|
||||||
|
- `marqdo-plugin-sdk` consumed only the contract and was verified by a real
|
||||||
|
fixture loaded through the CLI.
|
||||||
|
|
||||||
|
The SDK is a leaf with a different consumer group (third-party plugin authors),
|
||||||
|
a different change cadence and an independent release need. Keeping it in the
|
||||||
|
CLI workspace made the architecture map imply that the CLI product owns SDK
|
||||||
|
publication and forced every SDK change through the CLI build. Issue #15
|
||||||
|
required either fixing the distribution input or recording a blocking ticket.
|
||||||
|
The CLI repository is public, so a fixed Cargo git `rev` is a fetchable
|
||||||
|
contract input; there is no need for a submodule, a vendored contract copy or a
|
||||||
|
second wire implementation.
|
||||||
|
|
||||||
|
This is a **deliberate, narrow repository split**, not a mechanical projection
|
||||||
|
of every crate: engine and native host remain in the CLI workspace (ADR-0071
|
||||||
|
reopening conditions unchanged), and no empty candidate repository is created.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
### Topology
|
||||||
|
|
||||||
|
| Item | Decision |
|
||||||
|
|---|---|
|
||||||
|
| SDK repository | Public `cflmy/marqdo-plugin-sdk` (`main`), own Cargo workspace and lock |
|
||||||
|
| Contract input | `marqdo-plugin-abi` from `https://git.cflmy.cn/cflmy/marqdo-cli.git` at exact `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc` (the merge commit that landed ADR-0071) |
|
||||||
|
| CLI dependency on SDK | **None**. CLI normal/build/test lanes do not fetch or build the SDK |
|
||||||
|
| CLI workspace | `crates/marqdo-plugin-sdk` removed; the SDK is not a workspace member |
|
||||||
|
| Submodule/gitlink | **Not used** for this split; the SDK leaf must not create a CLI↔SDK identity cycle |
|
||||||
|
| Acceptance fixture | `tests/fixture` in the SDK repository only; real invocation uses a **frozen released CLI binary** via `tools/check_with_frozen_cli.py` |
|
||||||
|
| Contract authority | Unchanged: CLI owns the C header, Rust layout, Value Wire and error encodings; the SDK never defines a second contract |
|
||||||
|
| Publication | SDK releases are versioned independently against a contract generation; bumping the pinned CLI `rev` is a reviewed change |
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
- The SDK repository must resolve and build from a clean clone without the CLI
|
||||||
|
checkout; only its fixed git dependency may reach the CLI repository.
|
||||||
|
- It must not depend on `libloading`, a native host, worker execution, sandbox
|
||||||
|
or CLI code.
|
||||||
|
- The SDK's fixture is a third-party plugin built with only the public SDK. It
|
||||||
|
is verified against a frozen CLI archive (same ABI 1.0 contract), not against a
|
||||||
|
locally rebuilt CLI.
|
||||||
|
- The CLI repository must not reintroduce the SDK as a workspace member, a
|
||||||
|
copied source tree or a compatibility path; `tools/ci/check_dependency_boundaries.py`
|
||||||
|
and `architecture_boundaries.rs` fail if it does.
|
||||||
|
- The CLI's public contract is authoritative; the SDK repository README and
|
||||||
|
AGENTS rules point back to `include/marqdo_plugin_abi_v1.h`,
|
||||||
|
`spec/plugin-abi.md` and the pinned commit.
|
||||||
|
- The existing security statement remains: a C ABI is not a sandbox, and native
|
||||||
|
loading requires explicit trust; the SDK grants no capability.
|
||||||
|
|
||||||
|
## Verification (candidate)
|
||||||
|
|
||||||
|
- SDK repository commit `b31187a` on `main`:
|
||||||
|
- clean-clone `cargo build --locked` and `cargo test --locked` pass;
|
||||||
|
- the fixture builds with only the SDK;
|
||||||
|
- `tools/check_with_frozen_cli.py --marqdo-bin <released marqdo 3.0.0-rc.4>`
|
||||||
|
returns `Int 42` and rejects a tampered artifact digest.
|
||||||
|
- CLI candidate removes the SDK crate, fixture and CLI-side gate; workspace
|
||||||
|
tests, architecture boundaries, docs consistency and dependency gates pass;
|
||||||
|
the SDK no longer appears in the workspace or lock file.
|
||||||
|
- Full evidence: `docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md`.
|
||||||
|
|
||||||
|
## Rejected alternatives
|
||||||
|
|
||||||
|
- **Keep the SDK in the CLI workspace** while calling the contract "decoupled":
|
||||||
|
leaves two release cadences and ownership in one repo; issue #15 cannot close.
|
||||||
|
- **Git submodule/gitlink into the CLI repo**: CLI does not consume the SDK, so
|
||||||
|
a submodule would create an unnecessary recursive identity and checkout
|
||||||
|
failure mode.
|
||||||
|
- **Relative path dependency `../cli`**: not an independent build; forbidden by
|
||||||
|
issue #13 §6.2.
|
||||||
|
- **Copy `marqdo-plugin-abi`/Value Wire into the SDK repo**: would create a
|
||||||
|
second contract and wire encoder authority.
|
||||||
|
- **Publish the contract to a registry first**: no registry/release channel is
|
||||||
|
approved here; the public git `rev` is the available precise input. A future
|
||||||
|
published artifact can replace the git `rev` without changing authority.
|
||||||
|
|
||||||
|
## Consequences and rollback
|
||||||
|
|
||||||
|
- The architecture map now shows one CLI contract producer and one independent
|
||||||
|
SDK consumer; CLI CI no longer carries SDK-only checks, and SDK CI owns them.
|
||||||
|
- The SDK remains pinned to a CLI merge commit. Changing the contract or
|
||||||
|
advancing the pin is a deliberate cross-repository change with its own
|
||||||
|
evidence; a contract change must land in the CLI first, then the SDK pin is
|
||||||
|
bumped.
|
||||||
|
- Rollback is a complete known-good combination: keep the CLI commit and the SDK
|
||||||
|
pin that were verified together; do not restore a copied SDK or an old ABI.
|
||||||
|
- External SDK consumers can fetch the public CLI contract today. If a
|
||||||
|
registry-published contract or a different visibility policy is later chosen,
|
||||||
|
that is a new ADR, not an implicit change.
|
||||||
@@ -66,3 +66,13 @@ Files: `0001`–`0050`, plus:
|
|||||||
* [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.
|
* [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers.
|
||||||
|
* [0068](0068-single-current-public-contracts.md) — one current contract per
|
||||||
|
pre-stable public boundary, replaced in place;
|
||||||
|
* [0069](0069-public-analysis-boundary.md) — one public Analysis projection for
|
||||||
|
independent document, lint and knowledge consumers.
|
||||||
|
* [0071](0071-engine-host-contract-boundary.md) — Engine / Host Contract /
|
||||||
|
Native Host / CLI responsibilities, dependency rules, plugin ABI contract split
|
||||||
|
and the keep-in-workspace repository decision.
|
||||||
|
|
||||||
|
* [0072](0072-sdk-independent-repository.md) — independent public
|
||||||
|
`cflmy/marqdo-plugin-sdk` repository pinned to one CLI contract `rev`.
|
||||||
@@ -4,11 +4,55 @@ Status: **current architecture overview**. This file summarises the tree as it
|
|||||||
is today. It is not a release promise, does not reopen a frozen ADR, and does not
|
is today. It is not a release promise, does not reopen a frozen ADR, and does not
|
||||||
replace `spec/` or a recorded test log.
|
replace `spec/` or a recorded test log.
|
||||||
|
|
||||||
- Baseline: `2c7c4f31e7a388d3fcfa717a77067e696ed13854` (2026-11-22, tagged `v3.0.0-beta.1`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`).
|
- Baseline: `452e9a32bd9e40dba427d4180691c58bab74449e` (2026-11-25, tagged `v3.0.0-rc.4`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`).
|
||||||
- Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`.
|
- Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`.
|
||||||
- This is the **single current overview**. Do not add a second running "current state" file;
|
- This is the **single current overview**. Do not add a second running "current state" file;
|
||||||
update this file, `docs/STATUS.md` and an evidence file together.
|
update this file, `docs/STATUS.md` and an evidence file together.
|
||||||
|
|
||||||
|
## Engine / Host Contract / Native Host boundary (issue #13, ADR-0071)
|
||||||
|
|
||||||
|
The language engine is independent of every concrete native platform
|
||||||
|
implementation. `marqdo-host-contract` owns the only side-effect interface the
|
||||||
|
runtime knows (`Host`, `HostOp`, `ExecutionContext`, `ResourceRead` and the
|
||||||
|
runtime observation facts); `marqdo-host` implements it with capabilities,
|
||||||
|
resources, OS adapters and trusted extension execution; `crates/cli` remains the
|
||||||
|
single product assembly. The plugin ABI crate is a public contract only: native
|
||||||
|
loading, artifact/manifest execution and worker processes live in
|
||||||
|
`marqdo-host::plugin`. The SDK depends on the contract, not on a loader or a
|
||||||
|
host.
|
||||||
|
|
||||||
|
The Engine and the Native Host stay in **this workspace**. Issue #13 §9.2
|
||||||
|
admission for a separate repository is not met yet: there is no real external
|
||||||
|
Engine consumer outside the in-repo acceptance fixture, and no independent
|
||||||
|
platform maintainer. A candidate empty `marqdo-engine`/`marqdo-host` repository
|
||||||
|
would violate the issue's boundary conditions. The decision and its reopening
|
||||||
|
conditions are recorded in [ADR-0071](../adr/0071-engine-host-contract-boundary.md).
|
||||||
|
|
||||||
|
## Workspace crate responsibility map
|
||||||
|
|
||||||
|
This is the reviewed allowlist for workspace members. A new crate must be added
|
||||||
|
here, in `tools/ci/check_dependency_boundaries.py`, and with its dependency edges
|
||||||
|
in the same change.
|
||||||
|
|
||||||
|
| Crate | Layer | Responsibility |
|
||||||
|
|---|---|---|
|
||||||
|
| `marqdo-span` | Engine | UTF-8 position and diagnostic base types |
|
||||||
|
| `marqdo-value` | Engine | `Value`, `RuntimeError`, the one Value Wire encoding |
|
||||||
|
| `marqdo-expression` | Engine | Expression grammar |
|
||||||
|
| `marqdo-markdown` | Engine | The only Markdown profile and AST |
|
||||||
|
| `marqdo-ir` | Engine | IR, function/binding identity, builtin inventory |
|
||||||
|
| `marqdo-frontend` | Engine | Document mapping, signatures, static binding |
|
||||||
|
| `marqdo-runtime` | Engine | Evaluator, control flow and `Memory` |
|
||||||
|
| `marqdo-host-contract` | Engine boundary | Neutral `Host` trait and runtime observation facts |
|
||||||
|
| `marqdo-host` | Native Host | Capabilities, resources, OS adapters, plugin loader and trusted execution |
|
||||||
|
| `marqdo-sandbox` | Native Host support | OS isolation probe and strict launch |
|
||||||
|
| `marqdo-foreign` | Native Host support | Controlled one-shot foreign kernels (F-A) |
|
||||||
|
| `marqdo-plugin-abi` | Public contract | C ABI v1 layout, wire envelope and protocol errors |
|
||||||
|
| `marqdo-worker-ipc` | Shared plumbing | One bounded worker frame transport |
|
||||||
|
| `marqdo-provider-worker` | Shipped worker | Provider helper process |
|
||||||
|
| `marqdo-package` | Product support | Project manifest, lock and dependency resolution |
|
||||||
|
| `marqdo-cli` | Composition root | Arguments, prepare, commands, product projection |
|
||||||
|
|
||||||
> **Language contract and implementation.** The language contract is
|
> **Language contract and implementation.** The language contract is
|
||||||
> [RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) (adopted by ADR-0052) and
|
> [RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) (adopted by ADR-0052) and
|
||||||
> `spec/mapping.md`. The frontend, `marqdo-expression`, IR lowering, runtime and
|
> `spec/mapping.md`. The frontend, `marqdo-expression`, IR lowering, runtime and
|
||||||
@@ -58,10 +102,14 @@ replace `spec/` or a recorded test log.
|
|||||||
|
|
||||||
[ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy
|
[ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy
|
||||||
for replacing public interfaces before the first stable release.
|
for replacing public interfaces before the first stable release.
|
||||||
|
[ADR-0069](../adr/0069-public-analysis-boundary.md) closes the public Analysis
|
||||||
|
boundary: the projection carries the exact source, document AST, complete
|
||||||
|
heading scope, entry/snapshot identity and one shared document-link resolver,
|
||||||
|
and the retired program-only fields and duplicate resolver have no active path.
|
||||||
|
|
||||||
| Boundary | Owner | Current contract |
|
| Boundary | Owner | Current contract |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Static facts | CLI Analysis projection of the prepared project | [Analysis](../../spec/analysis.md) |
|
| Static facts | CLI Analysis projection of the prepared project: source, document AST, heading scopes, entry/snapshot identity, calls, resources and one document-link resolver | [Analysis](../../spec/analysis.md), [Markdown profile](../../spec/markdown-profile.md), [References](../../spec/references.md) |
|
||||||
| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) |
|
| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) |
|
||||||
| Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.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) |
|
| 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) |
|
||||||
@@ -152,11 +200,14 @@ Layer rules:
|
|||||||
Current Rust dependency edges (documented, not proposed):
|
Current Rust dependency edges (documented, not proposed):
|
||||||
|
|
||||||
```text
|
```text
|
||||||
marqdo-cli -> marqdo-runtime -> marqdo-host
|
marqdo-cli -> marqdo-runtime -> marqdo-host-contract
|
||||||
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ...
|
marqdo-cli -> marqdo-host, marqdo-package, marqdo-sandbox, marqdo-frontend, ...
|
||||||
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
|
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
|
||||||
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc
|
marqdo-host-contract -> marqdo-value, marqdo-span
|
||||||
marqdo-plugin-abi -> marqdo-worker-ipc
|
marqdo-host -> marqdo-host-contract, marqdo-plugin-abi, marqdo-foreign,
|
||||||
|
marqdo-sandbox, marqdo-worker-ipc
|
||||||
|
marqdo-plugin-abi -> marqdo-value, serde/serde_json (contract only)
|
||||||
|
[cflmy/marqdo-plugin-sdk] -> cflmy/marqdo-cli#marqdo-plugin-abi @ pinned rev
|
||||||
marqdo-provider-worker -> marqdo-worker-ipc
|
marqdo-provider-worker -> marqdo-worker-ipc
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -166,10 +217,13 @@ copy of bounded worker framing, deadlines and process teardown
|
|||||||
host, the plugin ABI, or a worker binary; sharing plumbing must not share
|
host, the plugin ABI, or a worker binary; sharing plumbing must not share
|
||||||
capabilities. Foreign kernels and CLI Tools stay outside it.
|
capabilities. Foreign kernels and CLI Tools stay outside it.
|
||||||
|
|
||||||
`marqdo-runtime -> marqdo-host` is the current direction. Do not add a second
|
`marqdo-runtime -> marqdo-host-contract` is the only engine-to-host edge. The
|
||||||
execution backend or a `marqdo-stdlib` crate by implication. A future embedded
|
engine must never link `marqdo-host`, sandbox, foreign, plugin loading or the
|
||||||
runtime or a second backend needs the thin `ExecutionPort` contract described in the
|
CLI in normal/build dependencies. The native host must not depend back on the
|
||||||
review RFC, not a new crate per provider.
|
runtime/frontend/IR. `tools/ci/check_dependency_boundaries.py` enforces the
|
||||||
|
transitive graph from Cargo metadata; `tests/embedding` proves a real
|
||||||
|
platform-neutral consumer. Do not add a second execution backend, a per-provider
|
||||||
|
crate, or a `marqdo-stdlib` crate by implication.
|
||||||
|
|
||||||
| Public contract | API (`.mq.md`) | State | Tests |
|
| Public contract | API (`.mq.md`) | State | Tests |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
@@ -183,7 +237,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); the same index is exposed in Analysis with parent/mode-origin/full-range facts; third-party heading annotations are **Proposed** metadata only (H-05/H-07) | core mode and public scope facts: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, `analysis_boundary`, 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` |
|
||||||
@@ -199,7 +253,8 @@ 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` |
|
||||||
|
| document references | one pure `document_refs` resolver over an explicit catalog; Analysis uses the loaded catalog and never opens a link, `--refs` may verify direct local targets; states distinguish unloaded/missing/ambiguous/external/outside-scope/invalid | implemented (ADR-0069) | `analysis_boundary`, `document_refs` unit tests, `view_consumer`, `lint_consumer`, `knowledge_consumer` |
|
||||||
| 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` |
|
||||||
@@ -226,6 +281,7 @@ that a phase is complete.
|
|||||||
| P0 | **Language syntax migration**: RFC-LANG-0002 single contract | **closed at `9c1723d`**; implementation, stdlib digest, examples and fixtures green; platform/strict evidence remains separate |
|
| P0 | **Language syntax migration**: RFC-LANG-0002 single contract | **closed at `9c1723d`**; implementation, stdlib digest, examples and fixtures green; platform/strict evidence remains separate |
|
||||||
| P0 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo |
|
| P0 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo |
|
||||||
| P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate |
|
| P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate |
|
||||||
|
| P1 | Domain service ownership ledger (issue #13 §7): host-held `regex.*` and `compress.*` are ADR-0062 services, not a precedent for new domain operations | **DEFERRED** to the responsible `marqdo-ext-regex`/`marqdo-ext-archive` replacement issues; old entries stay until a real replacement passes authorization/negative tests |
|
||||||
| P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open |
|
| P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open |
|
||||||
| P1 | No file watch or binary `read_at` | open; future Resource Operation extension |
|
| P1 | No file watch or binary `read_at` | open; future Resource Operation extension |
|
||||||
| P1 | JSON/CSV product parsers are implemented with depth bound and multi-value/multi-row; no incremental streaming parser | open |
|
| P1 | JSON/CSV product parsers are implemented with depth bound and multi-value/multi-row; no incremental streaming parser | open |
|
||||||
@@ -263,7 +319,23 @@ that a phase is complete.
|
|||||||
current contract, replace in place, reject retired inputs, no compatibility
|
current contract, replace in place, reject retired inputs, no compatibility
|
||||||
path or version negotiation, and no version bump without a shape change.
|
path or version negotiation, and no version bump without a shape change.
|
||||||
|
|
||||||
## 7. References
|
## 7. Repository decision and split admission
|
||||||
|
|
||||||
|
| Component | Decision for this round | Reopen condition (issue #13 §9.2) |
|
||||||
|
|---|---|---|
|
||||||
|
| Engine (`span`/`value`/`expression`/`markdown`/`ir`/`frontend`/`runtime`/`host-contract`) | **Keep in this workspace** as one atomic semantic-change domain | A real, non-in-repo consumer needs independent build/release, and the semantic change cost is acceptable |
|
||||||
|
| Native Host (`host`/`sandbox`/`foreign`/plugin loader) | **Keep in this workspace**, dependent on the neutral contract | An independent platform maintainer or second product consumes it; security/conformance can be verified separately |
|
||||||
|
| `marqdo-plugin-sdk` | **Moved to independent public repository** `cflmy/marqdo-plugin-sdk` ([ADR-0072](../adr/0072-sdk-independent-repository.md)) | Contract input is a pinned CLI git `rev`; clean-clone build + frozen-CLI integration are the SDK repository's gates. CLI must not depend on it or re-add a copy |
|
||||||
|
| Stdlib | Separate issue #11/#12 (Phase A build input); runtime contract unchanged | Ecosystem-assembled Bundle and extension replacement accepted; then retire the in-repo source authority |
|
||||||
|
| Regex/compression domain services | **DEFERRED** under ADR-0062 ownership; no new domain operation may be added | A separately installable extension replaces the host-held service and the old entries are removed atomically |
|
||||||
|
| Foreign F-A | Retained; no F-B, session or new transport in this change | Separate ADR and milestone |
|
||||||
|
|
||||||
|
No candidate empty `marqdo-engine`, `marqdo-host` or `marqdo-cli-*` repository
|
||||||
|
is created by this decision. Git repository boundaries are ownership and release
|
||||||
|
boundaries, not a mechanical projection of Cargo crates. The engine and native
|
||||||
|
host are one source tree until the reopening evidence above exists.
|
||||||
|
|
||||||
|
## 8. References
|
||||||
|
|
||||||
- [Architecture index](README.md) — RFC/ADR/evidence history.
|
- [Architecture index](README.md) — RFC/ADR/evidence history.
|
||||||
- [Protocol convergence policy](PROTOCOL_CONVERGENCE_POLICY.md) — one-contract rules, anti-patterns and review checklist.
|
- [Protocol convergence policy](PROTOCOL_CONVERGENCE_POLICY.md) — one-contract rules, anti-patterns and review checklist.
|
||||||
@@ -283,7 +355,11 @@ that a phase is complete.
|
|||||||
- [ADR-0050: host regex extension](../adr/0050-host-regex-extension.md) — accepted project-mode groups/alternation/captures.
|
- [ADR-0050: host regex extension](../adr/0050-host-regex-extension.md) — accepted project-mode groups/alternation/captures.
|
||||||
- [ADR-0052: byte-exact HTTP framing](../adr/0051-byte-exact-http-framing.md) — accepted byte-list HTTP/1.1 parser/builder.
|
- [ADR-0052: byte-exact HTTP framing](../adr/0051-byte-exact-http-framing.md) — accepted byte-list HTTP/1.1 parser/builder.
|
||||||
- [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input.
|
- [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input.
|
||||||
- [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — review input for this migration.
|
- [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — historical review input; the current boundary decision is ADR-0071.
|
||||||
|
- [ADR-0071: Engine / Host Contract / Native Host boundaries](../adr/0071-engine-host-contract-boundary.md) — accepted responsibility split and keep-in-workspace decision for issue #13.
|
||||||
|
- [ADR-0072: Independent `marqdo-plugin-sdk` repository](../adr/0072-sdk-independent-repository.md) — the one deliberate repository split (public SDK leaf pinned to the CLI contract).
|
||||||
|
- [Issue #15 SDK split evidence](../evidence/2026-11-26-issue-15-sdk-independent-repository.md) — clean-clone build and frozen-CLI integration.
|
||||||
|
- [Issue #13 engine/host evidence](../evidence/2026-11-26-issue-13-engine-host-boundary.md) — executed candidate commands and results.
|
||||||
- [RFC-EXT-0001](RFC-EXT-0001.md) — extensibility closure task specification (implementation status tracked here and in STATUS).
|
- [RFC-EXT-0001](RFC-EXT-0001.md) — extensibility closure task specification (implementation status tracked here and in STATUS).
|
||||||
- [ADR-0054: single callable binding](../adr/0054-callable-binding-single-source.md) — one registry/binding pass, runtime dispatch by identity.
|
- [ADR-0054: single callable binding](../adr/0054-callable-binding-single-source.md) — one registry/binding pass, runtime dispatch by identity.
|
||||||
- [ADR-0055: resource provider CLI v2](../adr/0055-resource-provider-cli-v2.md) — provider v2 manifest/worker CLI closure and trust boundary.
|
- [ADR-0055: resource provider CLI v2](../adr/0055-resource-provider-cli-v2.md) — provider v2 manifest/worker CLI closure and trust boundary.
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ input and evidence. It is not a second running-status page.
|
|||||||
- Public-contract convergence rules and review checklist:
|
- Public-contract convergence rules and review checklist:
|
||||||
[`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md)
|
[`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md)
|
||||||
([ADR-0068](../adr/0068-single-current-public-contracts.md)).
|
([ADR-0068](../adr/0068-single-current-public-contracts.md)).
|
||||||
|
- **Current internal boundaries:** the Engine / Host Contract / Native Host /
|
||||||
|
CLI responsibilities, dependency edges, plugin ABI contract split and the
|
||||||
|
keep-in-workspace repository decision are in
|
||||||
|
[ADR-0071](../adr/0071-engine-host-contract-boundary.md) and
|
||||||
|
[`CURRENT.md`](CURRENT.md) §7. Issue #13 closure evidence lives in
|
||||||
|
[`../evidence/2026-11-26-issue-13-engine-host-boundary.md`](../evidence/2026-11-26-issue-13-engine-host-boundary.md).
|
||||||
- **Current language contract:**
|
- **Current language contract:**
|
||||||
[`RFC-LANG-0002-unified-semantics.md`](RFC-LANG-0002-unified-semantics.md),
|
[`RFC-LANG-0002-unified-semantics.md`](RFC-LANG-0002-unified-semantics.md),
|
||||||
adopted by [ADR-0052](../adr/0052-unified-markdown-semantics.md) and
|
adopted by [ADR-0052](../adr/0052-unified-markdown-semantics.md) and
|
||||||
@@ -23,7 +29,7 @@ input and evidence. It is not a second running-status page.
|
|||||||
| Document | Status | What it is |
|
| Document | Status | What it is |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. |
|
| [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. |
|
||||||
| [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002. |
|
| [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002 and its "contract crate only later" position is superseded by ADR-0071. |
|
||||||
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Historical: superseded by Observation (ADR-0068)** | Its event vocabulary and privacy model fed the current [Observation](../../spec/observation.md) contract; the Execution Events v1 name/options are retired. |
|
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Historical: superseded by Observation (ADR-0068)** | Its event vocabulary and privacy model fed the current [Observation](../../spec/observation.md) contract; the Execution Events v1 name/options are retired. |
|
||||||
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
|
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
|
||||||
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
|
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
|
||||||
@@ -77,6 +83,8 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
|||||||
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
|
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
|
||||||
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
|
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
|
||||||
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
|
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
|
||||||
|
| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, Engine/Native Host keep-in-workspace decision |
|
||||||
|
| Independent plugin SDK repository | [0072](../adr/0072-sdk-independent-repository.md) | Accepted and implemented: public `cflmy/marqdo-plugin-sdk`, pinned to CLI contract commit, CLI does not depend on it |
|
||||||
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
|
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
|
||||||
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
|
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
|
||||||
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user