Compare commits

120 Commits
Author SHA1 Message Date
cflmy 2c7c4f31e7 release(3.0.0-beta.1): product version migration, beta gates, archive tooling and developer docs
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
REL-01: workspace/CLI/Analysis product version 3.0.0-beta.1 with updated
Cargo.lock; project.marqdo is enforced against the running core with
package.marqdo_range_invalid/package.marqdo_incompatible fail-closed
diagnostics; Tool SemVer prerelease negotiation tests; init template and
examples use the beta range. Verify init derives the project name from the
target directory instead of falling back to 'example'.

REL-02: beta support matrix is Linux x86_64 only; macOS/Windows are explicitly
experimental/unclaimed; strict policy and G4 Beta-only WARN are documented for
the release evidence.

REL-03: deterministic release packaging (tools/release/package.py) ships the
CLI and provider worker together with SOURCE_SHA, RELEASE_INFO.json,
known-limitations, specs, developer docs, examples incl. built plugin/provider
artifacts and consumers; tools/release/smoke.py cold-install tests the archive.

REL-04: docs/developers entry pages; corrected and self-contained third-party
integration handbook; stale Proposed/native-only/informational spec claims
fixed; release/status/compatibility/changelog/releasing docs updated.

REL-05: release_evidence.py gains an explicit beta profile
(BETA_RELEASE_CANDIDATE) distinct from the stable profile; Woodpecker build
step now packages and smoke-tests the archive on every pipeline.

Adds a runnable Resource Provider v2 example and corrects check --emit to
Analysis v2.
2026-11-22 02:31:32 +08:00
cflmy 56189b176c ci(ext): install MinGW cross compiler for the Windows check lane
ci/woodpecker/push/main Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
The new x86_64-pc-windows-gnu cargo check needs x86_64-w64-mingw32-gcc
for ring's C build script; the rust:bookworm image does not ship it.
2026-11-22 01:08:50 +08:00
cflmy c8049d51bf ci(ext): ship provider worker in release archives, add Windows compile gate and evidence validator tests
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
ci/woodpecker/push/main Pipeline failed
CI / release evidence manifest (push) Canceled after 0s
- Woodpecker test: prebuild provider helper; cross-check windows target
- Woodpecker build: release-build marqdo-cli + marqdo-provider-worker, assert helper
- GitHub release candidate: package helper as sibling and smoke assert it
- release-evidence: validate committed external-extension manifest or report UNVERIFIED
- tools/ci: unit tests for verify_extension_contracts manifest validation
- docs/ci: document the CI/CD changes
2026-11-22 01:03:52 +08:00
cflmy 2cbde54602 docs(stdlib): document verified public aliases and aliases_digest 2026-11-22 00:49:18 +08:00
cflmy 0b01cbd2a4 evidence(ext): SHA-bound frozen-CLI external conformance manifest; finalize RFC-EXT-0001 record
- docs/evidence/extension/6a7bb98.../manifest.json: tested_sha 6a7bb98,
  cli sha256 28e3776d..., fixture repo e4b7352c..., all 7 required categories PASS
- RFC-EXT-0001 status Implemented with PR-by-PR record and honest release caveat
- STATUS/CURRENT/COMPATIBILITY/evidence report bind the executed result
- workspace gate re-run: fmt/clippy clean, 599 passed across 67 targets

Code tree at 6a7bb98 is byte-identical; this commit adds evidence/docs only.
2026-11-22 00:48:39 +08:00
cflmy 6a7bb983c3 docs(ext): finalize extension selection/lock v4 docs, STATUS, CURRENT, COMPATIBILITY, CHANGELOG 2026-11-22 00:45:20 +08:00
cflmy 89555382e0 feat(ext): extension selection + lock v4, inspect --extensions (RFC-EXT-0001 PR-04)
- marqdo.yaml.extensions accepts only ./path or @alias/path, resolves to a
  regular file inside its owning package, never grants
- lock_version 4 records plugin/kernel/provider manifest+artifact identity;
  v3 requires explicit 'marqdo lock' migration; sync/check/run compare identity
- check stays static; run re-verifies artifact bytes; pure/strict refuse
- inspect --extensions reports declared/locked identity, plugin descriptors and
  stdlib aliases with authorization 'not_granted'
- black-box extension_selection suite (13) + package-layer tests; specs/ADR-0056
- workspace gate: fmt/clippy clean, 599 passed across 67 targets
2026-11-22 00:43:18 +08:00
cflmy 1f6fd644a0 feat(ext): single callable binding, provider v2 CLI, capability handlers, stdlib aliases
Implements RFC-EXT-0001 PR-00..PR-07 first pass:
- CallSiteKey/CallBindingTable + one frontend binding pass; runtime dispatch by identity
- prepare composition root shared by check/run/inspect/Analysis; exact plugin reconciliation
- provider.json v2 --provider/--allow-provider worker CLI with fail-closed verification
- capability handler registry with real fs.read and audit
- verified stdlib public aliases replace print_override/AST scan
- docs: specs, ADR-0054/0055/0057/0058, README, CI/release gates, evidence

PR-04 extension selection/lock v4 and final frozen-binary evidence remain.
2026-11-22 00:17:36 +08:00
cflmy 9aa536c2c9 docs(ext): add RFC-EXT-0001 extensibility closure specification 2026-11-21 22:41:33 +08:00
cflmy 595279fe38 跟踪未跟踪的文档
ci/woodpecker/push/main Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
2026-11-21 21:04:42 +08:00
cflmy c11c1c858a perf: record the Woodpecker G4 measured baseline
ci/woodpecker/push/main Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
The manual .woodpecker/performance.yml workflow ran on the designated fixed
agent (platform_id woodpecker-agent-1): 5 warmups + 20 samples, all 9
workloads correctness-verified, CPU 0 pinned from the container cpuset. Two
runs differed by -10.9%..+7.1% p50 and -1.9% RSS. The node is a shared Docker
container with the powersave governor and loadavg ~5.7-6.1, so the release gate
is WARN, not PASS, and comparisons are same-platform only.

Store both marqdo.perf.v2 reports and the SHA-bound release manifest. The
manifest is DO_NOT_RELEASE only because strict_vm remains UNVERIFIED; Linux,
Windows, macOS and performance have real same-SHA results.
2026-11-21 20:07:58 +08:00
cflmy 1199c88e3e ci(perf): use POSIX sh options in the G4 step
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
Woodpecker runs commands with /bin/sh (dash), which has no pipefail option.
The G4 script failed before measuring; use set -eu.
2026-11-21 19:58:37 +08:00
cflmy a3f3ecf9d0 ci(perf): add the fixed Woodpecker G4 workflow
ci/woodpecker/push/main Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
ci/woodpecker/manual/performance Pipeline failed
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
Move the push/PR pipeline to .woodpecker/main.yml so the repository can use
Woodpecker's multi-workflow directory. Add .woodpecker/performance.yml: manual
only, master only, on the single fixed Woodpecker agent (platform_id
woodpecker-agent-1). It builds one release binary, pins the first CPU in the
container cpuset, runs 5 warmups + 20 samples with --approved-node, and prints
the full marqdo.perf.v2 report plus a compact G4 summary for extraction.

No PR code is executed on the performance agent; the workflow is manual.
2026-11-21 19:51:09 +08:00
cflmy a9cc1729e1 docs(status): clear stale native-unverified blockers
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
The native platform block is closed at 5fcc111 (GitHub run 30). Update the
work-package rows and open blockers: the remaining release gates are the remote
G3 artifact and a MEASURED G4 report, not Windows/macOS. Keep the historical
sections and their older SHAs intact.
2026-11-21 19:08:34 +08:00
cflmy fd04ffb98e docs(status): record the native-green matrix and final G3 evidence
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
GitHub run 30 on 5fcc111 is green for Linux, windows-latest and macos-latest
(the native failures were Windows PATHEXT/temp/rooted-path issues, macOS test
temp canonicalization and a Windows 1 MiB main-thread overflow). Woodpecker
#25 is green on the same SHA, and the disposable-VM G3 lane PASSes 7/7 plus the
strict JSON/inert-@knowledge contracts.

The release decision stays DO_NOT_RELEASE, now only for the remote G3 artifact
with matching tested_sha and the MEASURED G4 report; the native platform block
is closed. Document that the adversarial suite is G3-opt-in so ordinary
cargo test --workspace cannot turn a hosted namespace-capable host into a G0
failure.
2026-11-21 19:07:07 +08:00
cflmy 5fcc111a30 fix(package): reject rooted Windows dependency paths
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
A drive-less rooted path such as /tmp/x or \tmp\x is not Path::is_absolute()
on Windows, but joining it still escapes the project root. Validate with
has_root() so every rooted dependency path is rejected on every platform. The
existing rejection test now also covers the Windows root-relative form.
2026-11-21 18:55:53 +08:00
cflmy a24161c934 fix(foreign): keep Windows temp paths non-verbatim
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
fs::canonicalize on Windows returns a \\?\C:\... path. Node's module loader
lstats the working/script path and rejects the verbatim form, so all Node
foreign-kernel tests failed on windows-latest. Use the native temp directory on
Windows and retain canonicalization on Unix for symlink safety; widen the CI
annotator so any remaining native failure shows a full assertion block.
2026-11-21 18:49:05 +08:00
cflmy 4265231a14 fix(portable): run the CLI on an 8 MiB thread and scope G3 tests
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
Windows gives the main thread 1 MiB, unlike Linux/macOS at 8 MiB. The bundled
regex self-test overflowed that stack even though the same document passed on
Linux, so run the CLI dispatch on an explicit 8 MiB thread on every platform.

The macOS package test compared a raw temp path with a canonicalized one; on
macOS /var is a symlink to /private/var. Compare canonical forms on both sides.

The adversarial security matrix is G3-only: ordinary cargo test --workspace on
a namespace-capable but non-disposable hosted runner turned G0 red. Make it
opt-in (MARQDO_REQUIRE_STRICT_SECURITY=1 for the G3 lane, or
MARQDO_RUN_STRICT_SECURITY=1 for a developer); the lane still requires the
mechanism and fails on a missing one.
2026-11-21 18:42:53 +08:00
cflmy b898c419fe test(portable): fix native stack and process-fixture assumptions
ci/woodpecker/push/woodpecker Pipeline was successful
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
macOS arm64 aborted in nesting_depth_limit_is_enforced because the test-harness
thread stack is smaller than a production main thread. Run that contract test
on an explicit 8 MiB stack; the 128-level parser bound itself is unchanged.

The stdlib process product test hard-coded /bin/echo, which does not exist on
Windows. Use the test CLI itself as the granted program: the fixture reads
MARQDO_TEST_PROCESS_PROGRAM from the granted env, runs it with --version, and
the harness compares against the same invocation. process.run now forwards
SYSTEMROOT/WINDIR on Windows (process creation/DLL loading, not a capability),
and the bundled stdlib digest is regenerated for the changed test fixture.
2026-11-21 18:35:33 +08:00
cflmy 3a29fce061 fix(foreign): resolve Windows PATH executables with PATHEXT
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
The built-in Python provider scanned PATH for the extension-less token
python3; a Windows PATH contains python3.exe, so a working interpreter was
reported as kernel.unavailable and the semantic golden suite failed on
windows-latest. Expand candidates with PATHEXT (conservative default) and use
the same platform-aware resolver in the conformance test's availability probe.

Also make native failures diagnosable: strip ANSI before matching and emit the
panic/build context as public check annotations, and run Linux tests through
the same annotator. This fixes the Windows native lane and gives the macOS
failure the context needed to diagnose it.
2026-11-21 18:22:22 +08:00
cflmy d441d6f4cc ci: annotate the native test panic context
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
The native matrix only annotated the first matching line, which omitted the
fixture name and expected/actual values. Annotate the panic block and build
error context instead so the failing golden is identifiable from the public
check-run annotations.
2026-11-21 18:13:43 +08:00
cflmy 95e4c6b1a4 ci: annotate native workspace-test failures
ci/woodpecker/push/woodpecker Pipeline was canceled
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
The Windows/macOS jobs fail inside cargo test --workspace, but public check
annotations only show the step exit. Tee the output and emit the failing test,
panic or build-error line as a check annotation so the native failure is
diagnosable without repository-admin log access. Behaviour and exit status are
unchanged.
2026-11-21 18:09:28 +08:00
cflmy f9ef2328c6 docs(status): list the hardening and evidence commits
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
Complete the RFC-CI-0001 step table with the 512b9f5 lane-hardening and
beb68a9 evidence/CI fixes, and record pipeline #17.
2026-11-21 17:50:56 +08:00
cflmy beb68a911c docs(status): update G-C evidence to the hardened lane SHA
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
Record the 512b9f5 local disposable-VM run (7/7 plus strict JSON and inert
@knowledge, evidence.json/archive/log digests) and Woodpecker pipeline #16.
The lane now fails if strict-evidence.json cannot be written, so the green run
also proves the evidence path. Fix the cross-platform JSON smoke to tolerate
the expected non-zero strict refusal exit before parsing.

Tested code SHA: 512b9f5. Release decision remains DO_NOT_RELEASE for the
missing remote Windows/macOS native PASS, remote G3 artifact and MEASURED G4.
2026-11-21 17:46:16 +08:00
cflmy 512b9f5f1d ci(security): fail the lane when evidence generation fails
ci/woodpecker/push/woodpecker Pipeline was successful
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
A green lane without a strict-evidence.json must not count as a gate. The EXIT
trap now turns a generator failure into a lane failure. The self-hosted
workflow exports the archive path in the run step (env written by GITHUB_ENV is
not guaranteed in the env expression context), records the pinned image digest
as an input, and verifies schema/outcome/tested_sha/non-root before uploading.
Also define SOURCE_SHA before the VM overlay commands.
2026-11-21 17:41:23 +08:00
cflmy f01e8a9bb0 docs(status): record the CI/security convergence evidence
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
ci/woodpecker/push/woodpecker Pipeline was canceled
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Record the six-step RFC-CI-0001 series, the Woodpecker pipelines, the Windows
cross-target check, the local disposable-VM G-C PASS at 0d7e11b (7/7 plus the
strict JSON and inert-@knowledge contracts), and the correctness-verified
performance SMOKE run. Keep the release decision at DO_NOT_RELEASE because the
same SHA still lacks a remote Windows/macOS native PASS, a remote G3 artifact
and a MEASURED G4 report.

Include the RFC itself and link it from docs/ci.md. This is the documentation
follow-up to step 6; the tested code SHA is 0d7e11b.
2026-11-21 17:37:31 +08:00
cflmy 0d7e11b6f1 ci: aggregate SHA-bound release evidence and clear status drift
ci/woodpecker/push/woodpecker Pipeline was successful
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release evidence manifest (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
Add tools/ci/release_evidence.py (marqdo.release-gates.v1) plus unit tests:
missing/skipped/FAIL/UNVERIFIED and tested_sha mismatches stay
DO_NOT_RELEASE, performance may be PASS/WARN, unknown gate names are rejected.
The GitHub CI now has a release-evidence job that maps the Linux/schema and
native matrix results onto the manifest and uploads it, and both CI systems
run the evidence-tool tests.

Clear the contradictions the RFC calls out: remove the stale CURRENT.md rows
that claimed DNS/TLS/UDP and fs metadata were absent while the same table said
they were implemented; correct docs/ci.md to state that the GitHub-hosted
Windows/macOS matrix exists (Woodpecker has no such agent); keep the old
convergence plan historical; require the evidence manifest in releasing.md;
and add a docs-consistency guard for these claims.

This is step 6 of the CI/security RFC (B05/B06/B07).
2026-11-21 17:29:48 +08:00
cflmy d2267e912a perf: add correctness-verified marqdo.perf.v2 sampler
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
ci/woodpecker/push/woodpecker Pipeline was canceled
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
Replace the three-run baseline profile with tools/perf/runner.py: one fixed
release binary, per-child rusage via posix_spawn/wait4, 5 warmups and 20
samples by default, SHA-derived interleaved order, p50/p95/MAD, CPU user/sys
and peak RSS. Every warmup output is normalized and compared with a committed
wire digest before timing; a mismatch is CORRECTNESS_FAIL, never a fast
sample. Short or unapproved-host runs are SMOKE, and baselines from another
platform_id/profile are refused.

Add workloads.json, expected digests for nine existing workloads, a dedicated
fixed-node workflow (manual, self-hosted, requires --cpu-list), and
docs/performance.md. bench.py stays as a compatibility shim. This is step 5 of
the CI/security RFC (B08).
2026-11-21 17:28:05 +08:00
cflmy 990e984ab6 ci(security): bind the G-C lane to one SHA and emit evidence
Linux strict security lane (G-C) / strict isolation escape matrix (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
ci/woodpecker/push/woodpecker Pipeline was successful
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Add tools/ci/strict-evidence.py, which records only measured host/source
facts: tested SHA (git-verified when a checkout exists), source archive
digest, kernel, bwrap/rustc/cargo, uid, cgroup2, runner kind and outcome. The
lane now writes this document on every exit path, refuses a root-only PASS,
and covers the strict @knowledge-inert and forged-marker JSON contracts in
addition to the existing 7/7 adversarial matrix and positive CLI checks.

Rework security-linux.yml to run on trusted master pushes or an explicit
source_sha, bind the checkout to the tested SHA, create a git archive for the
digest, avoid PR execution and upload the evidence artifact. This is step 4 of
the CI/security RFC (B04/B09/B10); the runner must still be an ephemeral VM.
2026-11-21 17:14:43 +08:00
cflmy c9f509e161 test(cli): guard the platform-neutral strict child boundary
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Add an architecture test that rejects direct marker_present/verify_active
references from the CLI and keeps the Linux-only functions out of the
marqdo-sandbox crate root. Windows cross-target cargo check now compiles the
whole workspace (macOS cross-check is blocked only by ring's Darwin C/asm
build on this Linux host; its cfg(not(linux)) path is the same one Windows
exercises).

This completes the step 3 verification for the CI/security RFC B01.
2026-11-21 17:10:13 +08:00
cflmy f817cceb3b fix(cli): normalize strict failures to one JSON document
ci/woodpecker/push/woodpecker Pipeline was successful
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
Capture the strict child through launch_strict_capture and classify the
outcome before writing anything. In --json mode a control-plane failure now
emits exactly one error document with a stable code instead of forwarding
bubblewrap stderr and leaving stdout empty; a verified child's valid JSON is
forwarded unchanged with its own exit code. Empty, partial or non-JSON child
output becomes strict.child_invalid.

Route the remaining run --json error paths (mode, grants, missing entry,
trace) through the same contract, classify sandbox launch failures with
StrictFailureKind so probe/spawn/timeout/resource failures stay
distinguishable, and add deterministic routing tests plus forged-marker CLI
coverage. Document the decision in ADR-0053 and spec/security.md 1.2.

This is step 2 of the CI/security RFC (B02/B03).
2026-11-21 16:46:27 +08:00
cflmy f4a404bae9 fix(sandbox): add platform-neutral strict child inspection
ci/woodpecker/push/woodpecker Pipeline was successful
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
The CLI referenced Linux-only marker_present/verify_active directly, so
macOS and Windows builds failed with E0425. Add StrictChildState and
inspect_strict_child() to marqdo-sandbox: Linux performs the full identity
verification, while every other platform rejects even a forged
MARQDO_STRICT_ACTIVE marker. The Linux-only functions are no longer
re-exported from the crate root, so future callers cannot bypass the
platform boundary.

This is step 1 of the CI/security RFC (B01).
2026-11-21 16:36:49 +08:00
cflmy 32d8fe1f7a docs(status): record the merged master series and follow-up fixes
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
Master now contains the fast-forwarded RFC-LANG-0002 series; the former
semantics-v2-refactor branch was deleted, so only master remains.

- STATUS lists the full linear series (docs, implementation, expression
  grammar, status, seven follow-up fixes) and the verification at 9c1723d:
  fmt/clippy clean, 507 passed / 0 failed / 2 ignored, stdlib digest verified
- counts updated to 49 compile-negative fixtures and 507 workspace tests
  across README, COMPATIBILITY, CHANGELOG, CURRENT and the migration guide
- green evidence pins code commit 9c1723d and lists the follow-up fixes;
  CHANGELOG gains the follow-up correctness section
- migration inventory regenerated: 1019 classified files, 0 pending
- CURRENT.md baseline is the 40-hex 9c1723d commit required by the docs gate

Verified: docs_consistency 4/4, fmt, clippy -D warnings and the full
workspace suite green; python3 tools/pack-stdlib.py PASS.
2026-11-21 16:01:19 +08:00
cflmy 9c1723d44f test(markdown): cover the removed syntax-selector key probe
frontmatter::has_key() is what rejects marqdo_semantics/syntax directives;
add unit coverage for a present key, an absent key and invalid YAML (which
reports no key rather than panicking).

Verified: cargo test -p marqdo-markdown and the workspace suite green
(507 passed, 0 failed, 2 ignored).
2026-11-21 15:57:13 +08:00
cflmy b3429cbeb3 fix(frontend): emit diagnostics in the specified stable order
spec/mapping.md §8 requires diagnostics ordered by source position, then
code, so IDE/CI diffs are stable. analyze_source appended diagnostics by
pipeline stage (units, mapping, inference, call validation), so a later
heading error could precede an earlier payload error.

Sort the final list by (span.start, code) with span-less diagnostics last,
and pin the order with a test that mixes an indexing-stage duplicate-heading
error with an earlier mapping-stage syntax error.

Verified: clippy -D warnings clean; cargo test --workspace --locked green.
2026-11-21 15:55:23 +08:00
cflmy 0bbe0f6524 fix(frontend): honour the Setext no-declaration rule; drop dead helper
RFC-LANG-0002 allows a mode declaration only as an ATX heading prefix; a
Setext heading merely inherits the nearest ancestor mode. heading_declaration
was applied to every heading, so a Setext 'title' beginning with @exec/
@knowledge silently switched modes and could create a function.

- skip declaration parsing for Setext headings (they keep their literal name
  and inherited mode); add a regression test
- remove the dead normalized_heading_name helper and its imports, which only
  existed for the removed link-form call resolution

Verified: clippy -D warnings clean; cargo test --workspace --locked green
(505 passed, 0 failed, 2 ignored).
2026-11-21 15:52:46 +08:00
cflmy a3f9770761 fix(frontend): point unmatched end diagnostics at the end payload
A stray end after an earlier statement was reported with the span of the
previous payload (position-1) and a confusing 'ends outside its owning
function segment' message. Report it on the end payload itself with the
standard sem.unmatched_end wording, and pin the span with a unit test.

Verified: clippy -D warnings clean and cargo test --workspace --locked
green (62 targets).
2026-11-21 15:50:46 +08:00
cflmy 9fb97bc2df fix(frontend): recognize signatures only from Exec payloads
signature::detect() scanned the function body independently of heading
modes, skipping only level>=3 headings. A 'params(...)' code span in an
### @knowledge section was therefore taken as the function signature
('inspect --signature' reported it as explicit), even though that span is
inert documentation and is never executed.

Unify recognition with the executable traversal:

- MappedBody now reports the params(...) payload the mapper accepted; the
  mapper already enforces Exec mode, directness, first-function-wide
  position and single declaration
- signature::from_payload validates that text and rewrites default-value
  spans; signature::detect is removed along with its mode-blind heuristic
- analyze uses the mapper result, so Knowledge sections cannot declare a
  signature and prose/Knowledge subsections may still precede the first
  Exec declaration
- tests: Knowledge params ignored; Exec params after prose/Knowledge is the
  signature; spec/mapping.md states the recognition rule

Verified: clippy -D warnings clean; cargo test --workspace --locked green
(62 targets).
2026-11-21 15:48:37 +08:00
cflmy d5002ac826 docs(code): remove stale pre-RFC role wording and fix review aid
Follow-up cleanup of text left by the concurrent implementation:

- marqdo-markdown AST, marqdo-ir statements/branch arms, frontend units,
  payload and signature module docs now describe RFC-LANG-0002 roles
  (payload carriers, heading modes, if/else groups, while/end, params)
- marqdo-expression public docs list parse_payload_statement and stop
  describing a Markdown-link call that no longer exists
- retired markdown.invalid_construct/markdown.inert_executable constants
  are documented as decode-only history for old Analysis/Trace JSON
- drop the stale 'expected red' comment in the CLI integration test
- the dev-only .mq.md review aid no longer reports semicolons inside
  string literals, and skips AST baselines / expected-invalid negatives

Verified: fmt, clippy -D warnings and cargo test --workspace --locked green.
2026-11-21 15:44:31 +08:00
cflmy 361a6cc341 refactor(ir): drop the dead call-statement representation
The pre-RFC link-form block-quote call was removed by RFC-LANG-0002, but the
IR still carried Stmt::Call, CallSite and CallTarget with matching branches in
the runtime, infer, call validation, loader, analysis projection and JSON
output. No mapper produces that variant any more, so it was a second call
representation that could never be reached.

- remove Stmt::Call, CallSite and CallTarget from marqdo-ir
- remove the runtime exec_call_site path and every exhaustive match arm
- remove the 'call_site' Analysis node and its JSON helpers
- state in spec/analysis-v2.md that calls are expressions; keep v1 as history
  with a note that call_site is not produced by the current language

Verified: cargo clippy --workspace --all-targets -D warnings clean and
cargo test --workspace --locked green (62 targets).
2026-11-21 15:39:29 +08:00
cflmy b38b769932 fix(frontend): enforce function-wide params position
The concurrent mapper tracked the first params declaration in the Mapper (so
duplicates across heading segments were caught) but checked 'first payload'
with a per-segment vector index. A params(...) in a later ### @exec segment
was therefore accepted even after an earlier segment had executed statements,
and a duplicate could even be reported as a position error.

- track whether any statement has been lowered for the function and require
  params(...) to come before it, across all heading segments
- check duplicates first, then execution order, then the in-segment index
- add negative fixtures 48 (after an earlier segment) and 49 (duplicate
  across segments); update the corpus count and spec wording

Verified: cargo test --workspace --locked green (62 targets).
2026-11-21 15:36:30 +08:00
cflmy bbeb1de768 docs(status): record the landed RFC-LANG-0002 implementation
Update status, compatibility, changelog, README, architecture overview,
ADR status, migration guide, contributor/CI/security/release notes and
the per-file inventory from 'migration pending' to the verified state:

- language SHA ffd1cc9: fmt/clippy clean, workspace 501 passed / 0 failed
  / 2 ignored, stdlib digest regenerated and pack-verified
- green evidence report added; the prior intermediate evidence is marked
  superseded
- inventory regenerated: 1015 classified files, 0 pending
- explicit non-claims: Windows/macOS native lanes and the disposable-VM
  strict lane were not re-run at this SHA, so the release decision remains
  DO NOT RELEASE

Verified: cargo test -p marqdo-cli --test docs_consistency (4/4) and
git diff --check.
2026-11-21 12:31:38 +08:00
cflmy ffd1cc9862 refactor(expression): own the v2 payload statement grammar
Move keyword recognition out of the Markdown mapper and into the single
expression/statement parser:

- add parse_payload_statement + PayloadStatement for if/else/while/end/
  return/params/ordinary; keyword matching uses complete tokens, requires
  whitespace before a control expression, rejects trailing tokens/colons
  and reserves the statement words in expression positions
- keep expression spans payload-relative so the frontend can rewrite them
  onto the file; malformed params(...) interiors stay owned by the
  signature parser (one sem.syntax diagnostic, not a duplicate)
- simplify the frontend mapper to control-stack lowering and mapped
  semantic diagnostics only
- emit sem.no_entry_function from run when no Exec H2 main exists
- add else-under-while, params-in-quote, Knowledge-inertness and
  no-entry tests; update the corpus counts
- make the EBNF parameter type annotation optional (params(n) is valid)

Verified: cargo fmt --check, cargo clippy -D warnings and
cargo test --workspace --locked: 501 passed, 0 failed, 2 ignored.
2026-11-21 12:29:07 +08:00
cflmy e029853e32 feat(lang): implement RFC-LANG-0002 unified semantics (breaking)
One Markdown-to-program mapping, no version selector or legacy mapper.

Frontend/runtime:
- resolve @exec/@knowledge heading declarations with nearest-ancestor
  inheritance; only an Exec H2 is callable; add UnitKind::Knowledge and
  sem.* diagnostics (mode marker, unit name, exec-without-function,
  payload nesting/empty, syntax, control stack, params position,
  version directive, inferred-signature lint)
- extract Strong/Emph/inline Code as one-statement carriers, refuse
  nested carriers, and honour heading segment boundaries so an if/while
  cannot be closed across a heading
- lower if/else/while/end to the existing Branch/Loop/Return IR with a
  compile-time control stack; keep payload-relative source spans through
  expression parsing and rewrite them onto the file
- accept params(...) only as the first direct Exec H2 payload; keep the
  existing free-variable inference and named-only rule for inferred
  signatures; fix duplicate-mode/else/end and Knowledge-body inertness
- reject marqdo_semantics/syntax front matter directives

Data and tests:
- migrate stdlib/**/*.mq.md, regenerate stdlib.json digest
- migrate examples and the full semantics/negative/runtime corpus to
  the only current syntax; expected values/runtime codes preserved
- migrate Rust-embedded .mq.md fixtures, init template, CLI help and
  security-lane fixtures

Verified: cargo fmt --check, cargo clippy -D warnings and
cargo test --workspace --locked (green).
2026-11-21 12:26:46 +08:00
cflmy 49835424ee docs(spec): adopt RFC-LANG-0002 unified language semantics
Replace the Strong/Emph/List/Quote mapping in place with the single
@exec/@knowledge heading-mode model, unified payload carriers and keyword
control flow.

- add the authoritative RFC, ADR-0052 and a historical ADR index
- rewrite spec/mapping.md and spec/expression.ebnf as the normative
  mapping/statement grammar; update evaluation, references, math,
  foreign, package-format, plugin-abi, security and schema notes
- rewrite README, AGENTS, COMPATIBILITY and CHANGELOG for the breaking
  language change; update the architecture index/overview and active docs
- mark superseded planning docs, compute RFCs, evidence and syntax-role
  ADRs as historical/superseded without rewriting their decisions
- add migration guide, per-file inventory and dev-only audit scripts

The frontend/stdlib migration is completed in the following commits; this
commit contains documentation only.
2026-11-21 12:24:19 +08:00
Marqdo Agent 0d8ed44010 feat(http): parse and build HTTP/1.1 framing by bytes 2026-11-21 11:05:15 +08:00
Marqdo Agent 28b178fc70 feat(regex): add host-backed groups, alternation and captures 2026-11-21 10:58:06 +08:00
Marqdo Agent 94a13880c4 feat(json,csv): bound depth and add multi-value/multi-row APIs 2026-11-21 10:51:55 +08:00
Marqdo Agent efbb8007e1 feat(compress): add bounded gzip product codec 2026-11-21 10:48:27 +08:00
Marqdo Agent ff3f19a2ea feat(net): add DNS, UDP, TCP listener and TLS endpoints 2026-11-21 10:43:08 +08:00
Marqdo Agent ee0c6cc80a feat(random): add explicitly granted OS entropy API 2026-11-21 10:25:11 +08:00
Marqdo Agent 6338fa10e9 feat(fs): add append, read_at and recursive walk 2026-11-21 10:20:07 +08:00
Marqdo Agent 7859c26213 refactor(cli,host): finish command, dispatch and package module split 2026-11-21 08:59:50 +08:00
Marqdo Agent 8a0c068856 docs(stdlib): list every product test and fix digest snippet 2026-11-21 08:55:09 +08:00
Marqdo Agent 550e66b1e2 refactor(cli,host): split command entry points and provider/effects modules 2026-11-21 08:54:29 +08:00
Marqdo Agent 791819a725 refactor(cli,host): split sandbox, resource-open and process modules 2026-11-21 08:49:25 +08:00
Marqdo Agent 3ef18fb496 feat(process): add explicitly granted process API 2026-11-21 08:46:02 +08:00
Marqdo Agent 9922bfae98 feat(stdlib): add explicitly granted env API 2026-11-21 08:40:54 +08:00
Marqdo Agent ae69391bc0 feat(stdlib): add datetime and project-mode clock APIs 2026-11-21 08:36:40 +08:00
Marqdo Agent cffb6790be feat(stdlib): add path and regex product modules 2026-11-21 08:32:32 +08:00
Marqdo Agent bde6f1d0ba feat(stdlib): add JSON and CSV product parsers 2026-11-21 08:23:54 +08:00
Marqdo Agent fbe36bcc43 feat(resource): add grant-checked fs resource operations 2026-11-21 08:20:31 +08:00
Marqdo Agent cd90f059b4 feat(stdlib): add bounded std:fs/file read, write and copy 2026-11-21 08:10:10 +08:00
Marqdo Agent 8dd3d5eb76 docs(evidence): refresh the migration source baseline 2026-11-21 01:56:57 +08:00
Marqdo Agent 0d40de7645 test(stdlib): add the demo module to the product lane 2026-11-21 01:56:04 +08:00
Marqdo Agent 7a93fe8e7b docs(evidence): record the doc and stdlib test migration gate 2026-11-21 01:54:20 +08:00
Marqdo Agent f0c25be01d docs(tests): map architecture and e2e gates to executable lanes 2026-11-21 01:51:51 +08:00
Marqdo Agent 04eae8746e test(stdlib): cover every bundled module through std imports 2026-11-21 01:50:01 +08:00
Marqdo Agent a8ccac9e67 test(architecture): gate stdlib layout, digest and resource endpoints 2026-11-21 01:45:07 +08:00
Marqdo Agent ce70bc4c42 test(docs): gate the current architecture and evidence links 2026-11-21 01:38:21 +08:00
Marqdo Agent c2730ea445 docs(architecture): consolidate current state and history 2026-11-21 01:36:42 +08:00
cflmy 24c88bcc78 fix(resource): reject provider read and write over-reports
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
2026-11-21 01:05:14 +08:00
cflmy 6aa3d605af fix(stdlib): return the validated write-all byte count 2026-11-21 01:02:45 +08:00
cflmy e6b5678350 fix(stdlib): strip CR from console lines 2026-11-21 00:59:58 +08:00
cflmy 4a0caabc03 fix(runtime): keep resource.read destination bounds strict 2026-11-21 00:58:42 +08:00
cflmy 23e68cba5f docs(resource): record stdio stream endpoints and stdlib APIs 2026-11-21 00:58:34 +08:00
cflmy 02aecaa747 test(conformance): load nested stdlib imports without false cycles 2026-11-21 00:58:34 +08:00
cflmy 64a6b48866 fix(resource): share one stdin cursor across handles 2026-11-21 00:49:07 +08:00
cflmy 3b13d8499a feat(stdlib): add streaming IO and console line APIs 2026-11-21 00:48:46 +08:00
cflmy aed6a80ba7 feat(resource): add stdin and stderr stdio endpoints 2026-11-21 00:36:25 +08:00
cflmy 7fbe069196 docs(ci): record the Woodpecker pipeline and remaining native/security lanes
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
- Add docs/ci.md with the pipeline, Node 22 requirement, local credential
  policy and explicit non-coverage (strict VM, Windows/macOS, release publish).
- Update README/STATUS: private remote and Woodpecker CI are available; G-C
  strict and native lanes remain separate.
- Keep ADR-0039 stdlib-in-repo intent and its docs references.

Gate: fmt, clippy -D warnings, 440 tests passed.
2026-11-20 23:55:50 +08:00
cflmy c28482840b ci: use Node.js 22 for ES-module foreign tests
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
ci/woodpecker/push/woodpecker Pipeline was successful
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
Debian bookworm's Node 18 rejects the ES-module syntax used by the foreign-kernel
tests; install NodeSource 22 before cargo test.
2026-11-20 23:53:41 +08:00
cflmy 78fad5d1c6 ci: install Node.js for the optional foreign-kernel tests
ci/woodpecker/push/woodpecker Pipeline failed
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
The workspace test suite includes python/node foreign kernels; the Rust image
has Python but not Node, so marqdo-foreign tests failed with KernelUnavailable.
2026-11-20 23:52:49 +08:00
cflmy fbc59d1190 ci: install rustfmt alongside clippy
ci/woodpecker/push/woodpecker Pipeline failed
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
The rust image ships rustup but not the rustfmt component; the fmt step failed
before compiling anything.
2026-11-20 23:51:49 +08:00
cflmy de107839b7 ci: remove unsupported step artifacts property
ci/woodpecker/push/woodpecker Pipeline failed
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
Woodpecker rejected 'artifacts' as an additional property; the release binary is
still built by the build step.
2026-11-20 23:40:59 +08:00
cflmy 328f1a8db3 docs: defer stdlib extraction; add local credential and Woodpecker setup
ci/woodpecker/push/woodpecker Pipeline was canceled
CI / fmt + clippy + test (Linux x86_64) (push) Canceled after 0s
CI / schema instance validation + consumers (push) Canceled after 0s
CI / runtime contract (macos-latest) (push) Canceled after 0s
CI / runtime contract (windows-latest) (push) Canceled after 0s
CI / release candidate artifact (macos-latest) (push) Canceled after 0s
CI / release candidate artifact (ubuntu-latest) (push) Canceled after 0s
- Add ADR-0039: keep stdlib in-repo while architecture is small; extraction is
  a future trigger-driven option, not a pending gate. Update ADR-0028,
  STATUS, architecture index, package/P2/completion evidence.
- Add .woodpecker.yml (fmt/clippy/test + release build) for ci.cflmy.cn.
- Add docs/development-credentials.md and ignore .secrets/ plus .env.local;
  real credentials stay in the ignored local file and are never committed.

Gate: fmt, clippy -D warnings, 440 tests passed.
2026-11-20 23:40:38 +08:00
cflmy e3638f5720 docs(evidence): add the RFC-CM completion audit
- Map every objective bullet (P2 closure, Compat-B/C, CM-A08/A09/A10/A11,
  P4-P6) to commits, tests, ADRs and checked-in evidence.
- Record the final 440-test gate and strict VM lane result.
- Explicitly list external/unavailable items (GitHub CI URL, Windows/macOS,
  external stdlib repo publication, plugin-Worker ABI binding, P6 optimizer)
  so none is claimed as completed or CI-verified.

Gate: fmt, clippy -D warnings, 440 tests passed.
2026-11-20 23:31:10 +08:00
cflmy 757c5ed15e feat(provider): add C ABI provider worker binding v1
- Add the separate marqdo-provider-worker binary: loads one trusted c-abi-1
  shared library and serves the ADR-0035 framed-JSON resource protocol, with
  fail-closed startup and no in-process fallback (ADR-0038).
- Reuse StdHost::register_worker_resource_provider; language still sees only
  resource.* and project-mode/name grants.
- Compile a C test provider and run open/read/write/close through the helper;
  cover missing-library fail-closed. Trusted process boundary, not a sandbox;
  existing plugin-Worker ABI binding remains open.
- Add ADR/spec/status/README/changelog/evidence; workspace member and tests.

Gate: fmt, clippy -D warnings, 440 tests passed.
2026-11-20 23:30:22 +08:00
cflmy 313ac035e8 test(p2): prove foreign/plugin shortcuts fail in the pure lane
- Add negative tests: foreign.call -> permission.denied and plugin.invoke ->
  structured failure under --mode pure, complementing the 21-fixture pure lane.
- Update P2 evidence/tests README/changelog.

Gate: fmt, clippy -D warnings, 438 tests passed.
2026-11-20 23:29:14 +08:00
cflmy 974102dfc3 feat(host): add provider package manifest v1
- Add a marqdo.provider schema v1 loader (schema/version/ABI/platform library)
  and StdHost::register_provider_package, reusing the C ABI adapter and shared
  kind/name checks (ADR-0037).
- Add a compiled-provider + provider.json installation test; language use still
  requires project mode and allow_resource_provider.
- Update ADR/spec/status/README/changelog and evidence; no registry, signature
  or CLI install is claimed.

Gate: fmt, clippy -D warnings, 437 tests passed.
2026-11-20 23:28:30 +08:00
cflmy 5e5c3a84d9 test(host): cover C ABI version/mode fail-closed paths
- Build a second C provider reporting ABI v2 and assert registration fails
  with resource.unsupported.
- Assert pure/strict refuse a registered C provider kind with permission.denied.
- Refresh the C ABI evidence/test README.

Gate: fmt, clippy -D warnings, 436 tests passed.
2026-11-20 23:27:37 +08:00
cflmy d909de5c68 docs(status): clarify C ABI provider status and remaining CM-A09 gap 2026-11-20 23:26:51 +08:00
cflmy b22a89e7b4 feat(host): add trusted C ABI ResourceProvider v1
- Add the frozen marqdo_resource_provider.h ABI (version + open/read/write/
  close/last_error) and a libloading-based host adapter with version/symbol
  checks and callsite-attached host errors (ADR-0036).
- Add StdHost::register_c_resource_provider using the same kind/name validation
  and project-mode name grant as the in-process/worker providers.
- Compile a C shared-library test provider; cover round-trip and fail-closed
  missing-library behavior. Trusted native code, not a sandbox; plugin-Worker
  binding remains open.
- Update ADRs/spec/status/README/changelog and evidence.

Gate: fmt, clippy -D warnings, 435 tests passed.
2026-11-20 23:26:25 +08:00
cflmy 01f6fe46a7 feat(host): add worker resource-provider transport v1
- Add a host-managed helper process speaking framed JSON (4-byte BE length)
  with ping/open/read/write/close/shutdown, max 1 MiB frames and structured
  error mapping (ADR-0035).
- Add StdHost::register_worker_resource_provider using the same protocol,
  kind-conflict and name-grant checks as the in-process provider; pure/strict
  refuse provider kinds.
- Tests spawn a Python helper and cover round-trip, grant/mode denial and
  missing-program failure; no parser/Value/runtime/HostOp change.
- Update ADR/spec/status/README/changelog and evidence; C ABI binding remains
  open.

Gate: fmt, clippy -D warnings, 433 tests passed.
2026-11-20 23:25:09 +08:00
cflmy 12be02e24b docs(status): mark P4/P5 local gates PASS with explicit remaining work 2026-11-20 23:23:13 +08:00
cflmy 0946220f76 docs(security): record strict TCP refusal at 70d916d 2026-11-20 23:22:32 +08:00
cflmy 70d916d698 test(security): assert strict refuses TCP resources and --allow-net
- G-C lane now runs a .mq.md TCP resource open under strict and requires
  permission.denied, and rejects the --allow-net grant at the strict flag
  boundary.
- Complements the existing file-resource refusal and host TCP strict test.
2026-11-20 23:21:09 +08:00
cflmy 5ad2068038 docs(p2): include the sparse-matrix fixture in closure counts 2026-11-20 23:20:13 +08:00
cflmy 8bbed34bd3 test(c12): add sparse-matrix triples and multiply fixture
- Fixture 73 implements triple-list lookup, dense conversion and sparse
  multiply with Int arithmetic and exact indexing.
- Include it in the P2 pure closure lane and update golden count to 73,
  C12 evidence mapping, status/README/changelog.

Gate: fmt, clippy -D warnings, 430 tests passed.
2026-11-20 23:19:45 +08:00
cflmy 3484ab944c docs(security): refresh CM-A11 lane evidence at b241d1d 2026-11-20 23:18:53 +08:00
cflmy b241d1d978 feat(stdlib): add deterministic offline stdlib packaging
- tools/pack-stdlib.py builds a byte-deterministic
  marqdo-stdlib-0.1.0.tar.gz (fixed metadata, gzip mtime 0) plus a schema-tagged
  descriptor with tree digest, archive SHA-256 and file list.
- Verified repeated builds are identical and the extracted tree digest matches
  stdlib.json; archive is for the future external repo, not the CLI loader.
- Update ADR-0028, status/changelog/tests README and evidence.

Gate: fmt, clippy -D warnings, 430 tests passed.
2026-11-20 23:17:09 +08:00
cflmy e985da28a1 docs(status): refresh the current 430-test gate count 2026-11-20 23:16:35 +08:00
cflmy 4c8e7fd8ab perf(p6): add a reproducible baseline profile harness
- tools/perf/bench.py builds the release CLI and measures 7 .mq.md workloads
  three times with wall time and peak RSS, validating --json success.
- Check in the schema-tagged JSON report and interpretation; no bytecode/JIT/
  native backend was added, so P6 remains baseline-only, not complete.
- Update STATUS/changelog/tests README.

Gate: fmt, clippy -D warnings, 430 tests passed.
2026-11-20 23:16:02 +08:00
cflmy b020904199 test(p4): prove row-store/columnar table equivalence
- Add semantic fixture 72: a .mq.md columnar List/Map table store, converted,
  sorted and filtered; compare headers/cells with the T0 row Table via a
  cell-wise helper (Table == is not structural in this language version).
- Teach the direct-runtime semantic harness to resolve entry std: imports.
- Update ADR-0032, P4 status, docs/changelog/evidence; semantic goldens 72.

Gate: fmt, clippy -D warnings, 430 tests passed.
2026-11-20 23:14:38 +08:00
cflmy e981168d92 feat(stdlib): add HTTP framing over TCP and close P5 C10 locally
- Add stdlib/net/http.mq.md: status/header/chunked response parsing and request
  construction in .mq.md; no host HTTP/TLS implementation.
- Add stdlib/tests/http.mq.md and an end-to-end loopback test that sends a GET
  over resource.open("tcp"), reads bytes, parses the response and returns
  status/content-type/body.
- Update ADR-0034, status/spec/README/changelog and evidence; refresh the
  bundle digest.

Gate: fmt, clippy -D warnings, 430 tests passed.
2026-11-20 23:13:06 +08:00
cflmy 0d4dc1da03 test(p2): close C01-C06/C11/C12 in a pure no-Foreign/no-Plugin lane
- Add crates/cli/tests/p2_closure.rs: 20 semantic fixtures run through the real
  CLI in --mode pure (Capabilities::pure), source scan for foreign./plugin./
  import:, and golden value/stdout comparison.
- Run the stdlib table self-test in pure mode; no host shortcut or recompilation
  is needed for the selected algorithms.
- Mark P2 gate PASS locally (external stdlib repo publication and remote CI
  remain outside the C01-C12 gate); add evidence and docs.

Gate: fmt, clippy -D warnings, 428 tests passed.
2026-11-20 23:12:03 +08:00
cflmy d6cd785bdb docs(status): align print/table status with Compat-C and CM-A08 2026-11-20 23:10:56 +08:00
cflmy 69a28ed1e1 feat(stdlib): add table GFM rendering and an HTTP/1.1 parser fixture
- stdlib/data/table.mq.md adds 连接片段/连接行/转义单元格/转GFM; logical Table
  renders as a GFM pipe table with pipe/newline escaping (CM-A08 P4 gate).
- Add semantic fixture 71: HTTP/1.1 status/header/chunked response parsing and
  request construction in .mq.md; no host HTTP/TLS implementation (C10).
- Update table CLI test, golden count 71, specs/status/README/changelog and
  evidence.

Gate: fmt, clippy -D warnings, 426 tests passed; bundle digest refreshed.
2026-11-20 23:10:19 +08:00
cflmy 67a6d35daf docs(security): record CM-A11 strict resource verification
- Checked-in raw G-C lane log for 00bdcad: 7/7 adversarial helper matrix,
  positive CLI (Compat-C print via bundled stdlib), strict file-resource
  refusal, external-surface rejection, forged-marker rejection, lane PASS.
- Evidence documents the read-only /run/marqdo-stdlib bind, strict stdio-only
  policy, refused file/TCP/provider resources, and the remaining no-CI-URL /
  Windows/macOS limits.
- STATUS updated to the current 426-test gate and 00bdcad strict result.

Gate: fmt, clippy -D warnings, 426 tests passed; VM lane PASS.
2026-11-20 23:08:23 +08:00
cflmy 00bdcad1ff feat(host): add IP-literal blocking TCP resource endpoint (P5)
- resource.open("tcp", ip:port, ["read","write"]) with exact IP grants,
  project mode only, 5s connect/read/write timeouts; no DNS/TLS/UDP/server
  sockets (ADR-0034).
- Add TCP stream storage/dispatch in the resource table; CLI --allow-net IP;
  pure/strict preflight rejects the grant and the language endpoint.
- Host loopback echo/grant/DNS/strict tests and a .mq.md CLI echo test.
- Update specs, status, architecture, README, changelog and evidence.

Gate: fmt, clippy -D warnings, 426 tests passed.
2026-11-20 23:05:06 +08:00
cflmy 1d87f98539 fix(strict): bind the bundled stdlib and verify strict resources
- Strict child now gets the verified stdlib tree read-only at
  /run/marqdo-stdlib with MARQDO_STDLIB_DIR set, so Compat-C 打印 works under
  strict without exposing a host path (ADR-0021 update).
- Add a strict-lane negative: resource.open(file) is refused with
  permission.denied; hello/factorial/multi-module and --json still pass.
- StrictHostCommand gains stdlib_dir; CLI discovers the bundle and sandbox
  binds it; sandbox tests constructors updated.

Evidence: G-C lane PASS on the disposable Ubuntu 26.04 VM (7/7 adversarial
matrix, positive CLI, strict language-resource refusal, forged marker), plus
fmt/clippy/423 local tests.
2026-11-20 22:57:49 +08:00
cflmy 1be4662049 feat(host): add in-process ResourceProvider v1 (CM-A09 slice)
- Add ResourceProvider v1 trait with name/protocol/kinds/open/read/write/close;
  host still issues the opaque language Resource handle, provider tokens stay
  private.
- Add StdHost::register_resource_provider with protocol/version, reserved-name
  and duplicate-kind checks; add Capabilities.allow_resource_provider grants.
- Provider kinds are project-mode only; pure/strict refuse them; in-process
  providers are trusted and not a sandbox (ADR-0033).
- Reuse resource.* and Result shapes; no parser/Value/runtime/HostOp changes.
- Add mock read/write provider and rejection tests, docs/spec/status/evidence.

Gate: fmt, clippy -D warnings, 423 tests passed.
2026-11-20 22:38:16 +08:00
cflmy a8e62a5ba9 feat(stdlib): add table logical-value algorithms (CM-A08)
- Add stdlib/data/table.mq.md with select/filter/sort/append/set-cell/join/
  group as value-returning .mq.md functions over table.columns/row/cell.
- Keep Value::Table logical semantics, GFM AST laziness and T0 physical
  storage unchanged; no new table builtin or HostOp (ADR-0032).
- Add stdlib/tests/table.mq.md and a CLI test asserting shapes/order and
  input immutability; refresh the bundle digest.
- Update architecture/status/spec/README/changelog and evidence.

Gate: fmt, clippy -D warnings, 420 tests passed.
2026-11-20 22:28:52 +08:00
cflmy 49910ece43 refactor(print): remove HostOp::Print and legacy formatting (Compat-C)
- Delete HostOp::Print and StdHost::op_print; the print builtin only routes to
  bundled io.写值 when Program.print_override is set, otherwise returns a
  structured kernel.unavailable error (ADR-0031).
- Keep the 打印/print builtin name for arity/static validation; Value::display
  remains only for CLI result rendering, not print execution.
- Teach the direct-runtime semantic harness to mirror loader stdlib injection
  and import edges; replace runtime tests that used print with non-print
  effects.
- Update spec/security/status/changelog/README, add ADR-0031 and evidence.

Gate: fmt, clippy -D warnings, 419 tests passed.
2026-11-20 22:22:51 +08:00
cflmy e26971f489 feat(cli): route print through the bundled stdlib (Compat-B)
- Add Program.print_override and lazy stdlib injection: only programs that
  call 打印/print load std:io and route to io.写值 (ADR-0030).
- Record resource.open/read/write/close as trace effect events so the stdlib
  print path is auditable; HostOp::Print no longer runs on that path.
- Permit only stdio/stdout (existing console) in strict; file/network
  resource opens remain permission.denied.
- Exclude std: modules from the human-readable checked-module count; update
  the Python analysis consumer to accept std: instance ids.
- Add print-routing and strict-console tests, ADR-0030 and evidence.

Gate: fmt, clippy -D warnings, 418 tests passed.
2026-11-20 22:10:59 +08:00
cflmy e119727c5d feat(stdlib): format all value types and expose handle identity members
- Add read-only FunctionRef.module/name and PluginHandle.plugin/export
  members; PluginHandle.id stays private (ADR-0029).
- Extend stdlib/format.mq.md to Formula/Code/FunctionRef/PluginHandle/
  Memory/Resource/Unit, with UTF-8 byte length for Code.
- Fix two-digit ordered-list body indentation so arms 10+ stay inside their
  branch (they were previously top-level statements).
- Extend stdlib demo to Formula/Code/FunctionRef and assert all three
  io.写值/打印 pairs match byte-for-byte.
- Add runtime member observation test, ADR-0029, spec/status/changelog/evidence.

Gate: fmt, clippy -D warnings, 416 tests passed.
2026-11-20 21:57:04 +08:00
cflmy 1377af1601 feat(stdlib): ship a verified bundled stdlib with std: imports
- Move the Compat-A print prototype into stdlib/ as the official offline
  bundle with stdlib.json (version 0.1.0 + sha256 content digest).
- Add std:<relative> import resolution in the loader with bundle path
  confinement, extension inference and fail-closed digest verification.
- Record the verified version/digest/instance_id in Analysis v2
  project.stdlib; stdlib modules get a std:name@version#digest instance id.
- Add CLI tests: std:io execution, digest-tamper rejection, missing manifest,
  Analysis identity, no foreign/plugin calls, and frozen binary hash equality.
- Update ADR-0028, specs, status, changelog and evidence.

Gate: fmt, clippy -D warnings, 415 tests passed.
2026-11-20 21:43:14 +08:00
cflmy 1a978c7a42 feat(rfc-cm): add JSON floats and compact formatting
- Replace the JSON number scanner with sign/integer/fraction/exponent
  scanning; return Int or Float via 整数/小数 and reject missing digits.
- Add 片段/格式化文本/格式化列表/格式化对象/格式化 recursive formatter.
- Extend fixture 62 with floats ({1,2.5,-3e2,4E-1,{a:1.0},x}) and a compact
  round-trip string.
- Update P2 status: only the separate stdlib package and frozen-CLI closure
  lane remain.

Gate: fmt, clippy -D warnings, 407 tests passed.
2026-11-20 21:26:56 +08:00
cflmy 5d3a5fb13b test(rfc-cm): close P2 evidence gaps for C01/C06/C12
- Add alloc.double_free detection to the .mq.md free-list allocator and a
  fixture assertion for a second free returning a recoverable Result.
- Add table group fixture 69 (table.row -> Map of value lists).
- Add Int matrix-multiply fixture 70 for C12 layout/iteration.
- Update counts and P2 evidence/status docs.

Gate: fmt, clippy -D warnings, 407 tests passed.
2026-11-20 21:22:44 +08:00
cflmy 92bfbf2568 feat(rfc-cm): baseline P0-P3 compute machine, stdlib and resource slices
Implements the first vertical slices of RFC-CM-0001/0002 on top of a113d89:

- P1: opaque Memory regions (64 KiB pages, budgets, grow-only), byte
  read/write, Memory-index place assignment, wire/host-boundary rejection.
- CM-A04/A05: value-semantics List/Map/Text/Table primitives and the
  recoverable Result map convention.
- CM-A06: opaque Resource handles, resource.open/read/write/close, stdout
  write, granted project-file read and buffered write, strict fail-closed.
- CM-A07 Compat-A: explicit .mq.md format/utf8/io chain matching builtin
  print for the covered value types; builtin remains default.
- P2 fixtures: allocators, list/tree/graph/hash, integer codecs, UTF-8
  encode/decode, CSV/JSON subsets, table filter/sort/join, bytecode VM.
- ADRs 0022-0027, spec updates, evidence reports and 68 semantic goldens.

Gate: cargo fmt --check, clippy -D warnings, 407 tests passed.
2026-11-20 21:16:54 +08:00
699 changed files with 61765 additions and 4479 deletions

No files matched your search

+104 -4
View File
@@ -24,7 +24,25 @@ jobs:
- name: Clippy
run: cargo clippy --workspace --all-targets -- -D warnings
- name: Tests
run: cargo test --workspace
shell: bash
run: |
set +e
CARGO_TERM_COLOR=never cargo test --workspace 2>&1 | tee workspace-tests.log
status=${PIPESTATUS[0]}
set -e
if [ "$status" -ne 0 ]; then
python3 tools/ci/annotate_workspace_tests.py \
workspace-tests.log "Linux workspace tests"
fi
exit "$status"
- name: Documentation consistency
run: cargo test -p marqdo-cli --test docs_consistency
- name: Architecture boundaries
run: cargo test -p marqdo-cli --test architecture_boundaries
- name: CI evidence tool tests
run: python3 -m unittest discover -s tools/ci -p "test_*.py"
- name: Whole stdlib product tests
run: cargo test -p marqdo-cli --test stdlib_product
- name: Validate public JSON schemas
run: |
python3 - <<'PY'
@@ -116,7 +134,17 @@ jobs:
(command -v python3 && python3 --version) || echo "python3: unavailable"
(command -v node && node --version) || echo "node: unavailable"
- name: Workspace tests
run: cargo test --workspace
shell: bash
run: |
set +e
CARGO_TERM_COLOR=never cargo test --workspace 2>&1 | tee workspace-tests.log
status=${PIPESTATUS[0]}
set -e
if [ "$status" -ne 0 ]; then
python3 tools/ci/annotate_workspace_tests.py \
workspace-tests.log "Workspace tests on ${{ matrix.os }}"
fi
exit "$status"
- name: Portable CLI, analysis and trace smoke
shell: bash
run: |
@@ -138,6 +166,72 @@ jobs:
test "$code" -eq 1
echo "$output" | grep -qi "strict"
echo "$output"
- name: Strict JSON refusal is exactly one document
shell: bash
run: |
set -euo pipefail
set +e
json=$(cargo run -q -p marqdo-cli -- run examples/hello.mq.md --mode strict --json)
code=$?
set -e
test "$code" -eq 1
JSON_DOC="$json" python3 - <<'PY'
import json, os
document = json.loads(os.environ["JSON_DOC"])
assert document["success"] is False, document
assert document["command"] == "run", document
assert document["code"] == "strict.probe_unavailable", document
PY
release-evidence:
name: release evidence manifest
needs: [test, schema, cross-platform]
if: always()
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build SHA-bound manifest
shell: bash
env:
TARGET_SHA: ${{ github.sha }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
LINUX_RESULT: ${{ needs.test.result }}
SCHEMA_RESULT: ${{ needs.schema.result }}
PORTABLE_RESULT: ${{ needs.cross-platform.result }}
run: |
set -euo pipefail
state() {
case "$1" in
success) echo PASS ;;
failure) echo FAIL ;;
*) echo UNVERIFIED ;;
esac
}
linux="$(state "$LINUX_RESULT")"
portable="$(state "$PORTABLE_RESULT")"
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ]; then
linux="FAIL"
fi
python3 tools/ci/release_evidence.py --target-sha "$TARGET_SHA" --out "docs/evidence/ci/$TARGET_SHA/manifest.json" --gate "linux=$linux:$TARGET_SHA:$RUN_URL" --gate "windows=$portable:$TARGET_SHA:$RUN_URL" --gate "macos=$portable:$TARGET_SHA:$RUN_URL" --gate "strict_vm=UNVERIFIED::${{ github.server_url }}/${{ github.repository }}/actions/workflows/security-linux.yml" --gate "performance=UNVERIFIED::"
- name: Validate external-extension evidence when committed
shell: bash
env:
TARGET_SHA: ${{ github.sha }}
run: |
set -euo pipefail
manifest="docs/evidence/extension/$TARGET_SHA/manifest.json"
if [ -f "$manifest" ]; then
python3 tools/ci/verify_extension_contracts.py --validate "$manifest"
else
echo "UNVERIFIED: no external-extension manifest for $TARGET_SHA."
echo "Release requires tools/ci/verify_extension_contracts.py on the tagged SHA (docs/releasing.md §7)."
fi
- name: Upload release manifest
uses: actions/upload-artifact@v4
with:
name: release-evidence-${{ github.sha }}
path: docs/evidence/ci/${{ github.sha }}/manifest.json
if-no-files-found: error
release-candidate:
name: release candidate artifact (${{ matrix.os }})
@@ -156,8 +250,10 @@ jobs:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build release binary
run: cargo build --release --locked -p marqdo-cli
- name: Build release binaries
run: |
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
test -x target/release/marqdo-provider-worker
- name: Package and checksum
shell: bash
run: |
@@ -166,6 +262,9 @@ jobs:
stage="dist/marqdo-${version}-${{ matrix.target }}"
mkdir -p "$stage"
install -m 0755 target/release/marqdo "$stage/"
# The provider worker is required for provider.json v2 and must be a
# sibling of the marqdo executable (no PATH fallback).
install -m 0755 target/release/marqdo-provider-worker "$stage/"
cp LICENSE-MIT LICENSE-APACHE CHANGELOG.md COMPATIBILITY.md README.md "$stage/"
cp -r spec examples "$stage/"
mkdir -p "$stage/tests"
@@ -192,6 +291,7 @@ jobs:
cd marqdo-*
./marqdo --version
./marqdo --help >/dev/null
test -x ./marqdo-provider-worker
./marqdo check examples/multi-module/index.mq.md --refs --emit analysis.json
./marqdo run examples/hello.mq.md
./marqdo run examples/multi-module/index.mq.md --trace-file trace.json
+70
View File
@@ -0,0 +1,70 @@
name: Linux performance measurements (G4)
# This workflow needs a dedicated, fixed Linux performance node. It is never
# run on GitHub-hosted runners or on TCG/QEMU guests: those numbers are not
# comparable with a native release baseline. A short smoke run is not release
# evidence; runner.py marks it SMOKE unless 5 warmups / 20 samples and
# --approved-node are used.
#
# Trust model: the node carries no untrusted PR code and no repository
# secrets. It must not share hardware with the G3 security VM.
on:
workflow_dispatch:
inputs:
platform_id:
description: "Fixed node identifier, e.g. linux-x86_64-fixed-node-01"
required: true
type: string
cpu_list:
description: "taskset CPU list, e.g. 2,3 (empty = unbound smoke only)"
required: false
default: ""
type: string
baseline_run_id:
description: "Optional previous run id whose artifact is the baseline"
required: false
default: ""
type: string
permissions:
contents: read
jobs:
measure:
name: correctness-verified performance sample
runs-on: [self-hosted, linux, marqdo-perf]
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Toolchain report
run: |
rustc -vV
uname -a
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || true
cat /proc/loadavg
- name: Measure
shell: bash
env:
PLATFORM_ID: ${{ inputs.platform_id }}
CPU_LIST: ${{ inputs.cpu_list }}
run: |
set -euo pipefail
args=(--warmups 5 --samples 20 --approved-node --platform-id "$PLATFORM_ID" --out perf.json)
if [ -n "$CPU_LIST" ]; then
args+=(--cpu-list "$CPU_LIST")
else
echo "error: a release measurement requires a fixed --cpu-list" >&2
exit 1
fi
python3 tools/perf/runner.py "${args[@]}"
- name: Upload report
if: always()
uses: actions/upload-artifact@v4
with:
name: marqdo-perf-${{ inputs.platform_id }}
path: perf.json
if-no-files-found: warn
retention-days: 90
+89 -4
View File
@@ -5,27 +5,112 @@ name: Linux strict security lane (G-C)
# mount, PID and network namespaces and the Bubblewrap AppArmor profile.
# A missing runner or a skipped test fails the gate; it is never counted as a
# pass. See docs/security-gate.md and ADR-0021.
#
# Trust model: the runner registration must be issued by a trusted, short-lived
# orchestrator and the VM destroyed after the job. A persistent self-hosted
# runner with GitHub/SSH/cloud credentials is NOT acceptable. The workflow
# records tested_sha separately from workflow_sha and never runs on PRs.
on:
push:
branches: [master]
workflow_dispatch:
schedule:
- cron: "17 3 * * 1"
inputs:
source_sha:
description: "Exact reviewed commit SHA"
required: true
type: string
runner_image_sha256:
description: "Pinned VM base-image digest (evidence, not a secret)"
required: false
default: "unrecorded"
type: string
permissions:
contents: read
jobs:
strict-security:
name: strict isolation escape matrix
if: github.event_name != 'pull_request'
runs-on: [self-hosted, linux, marqdo-security]
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host capability report
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.source_sha || github.sha }}
persist-credentials: false
- name: Bind tested SHA and archive
shell: bash
run: |
set -euo pipefail
tested_sha="$(git rev-parse HEAD)"
expected="${{ github.event_name == 'workflow_dispatch' && inputs.source_sha || github.sha }}"
if [ "$tested_sha" != "$expected" ]; then
echo "tested SHA $tested_sha does not match expected $expected" >&2
exit 1
fi
printf 'TESTED_SHA=%s\n' "$tested_sha" >> "$GITHUB_ENV"
printf 'WORKFLOW_SHA=%s\n' "$GITHUB_SHA" >> "$GITHUB_ENV"
archive="$RUNNER_TEMP/marqdo-source-$tested_sha.tar"
git archive --format=tar "$tested_sha" > "$archive"
printf 'SOURCE_ARCHIVE_SHA256=%s\n' \
"sha256:$(sha256sum "$archive" | cut -d' ' -f1)" >> "$GITHUB_ENV"
- name: Host capability report
shell: bash
run: |
set -euo pipefail
test "$(id -u)" -ne 0
id
uname -a
systemd-detect-virt --container || true
bwrap --version
cc --version | head -1
rustc -vV
cat /proc/self/uid_map
findmnt -t cgroup2 || true
- name: Run G-C matrix
run: ./tests/security/run-lane.sh
shell: bash
env:
MARQDO_STRICT_EVIDENCE: ${{ runner.temp }}/strict-evidence.json
MARQDO_STRICT_LANE_LOG: ${{ runner.temp }}/gc-lane.log
MARQDO_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
MARQDO_RUNNER_KIND: disposable-vm
MARQDO_RUNNER_IMAGE_SHA256: ${{ inputs.runner_image_sha256 || 'unrecorded' }}
run: |
set -euo pipefail
export MARQDO_SOURCE_ARCHIVE="$RUNNER_TEMP/marqdo-source-${TESTED_SHA}.tar"
./tests/security/run-lane.sh 2>&1 | tee "$MARQDO_STRICT_LANE_LOG"
- name: Verify strict evidence matches the tested SHA
if: success()
shell: bash
env:
MARQDO_STRICT_EVIDENCE: ${{ runner.temp }}/strict-evidence.json
run: |
set -euo pipefail
python3 - <<'PY'
import json, os
path = os.environ["MARQDO_STRICT_EVIDENCE"]
with open(path, encoding="utf-8") as handle:
evidence = json.load(handle)
assert evidence["schema"] == "marqdo.strict-evidence.v1", evidence
assert evidence["run"]["outcome"] == "PASS", evidence
assert evidence["tested_sha"] == os.environ["TESTED_SHA"], evidence
assert evidence["environment"]["uid"] != 0, evidence
print("strict evidence verified for", evidence["tested_sha"])
PY
- name: Upload strict evidence
if: always()
uses: actions/upload-artifact@v4
with:
name: strict-evidence-${{ inputs.source_sha || github.sha }}
path: |
${{ runner.temp }}/strict-evidence.json
${{ runner.temp }}/gc-lane.log
if-no-files-found: warn
retention-days: 30
+16
View File
@@ -10,13 +10,29 @@ examples/plugin-multi-export/solver.so
# Local cargo home used on hosts with a read-only $HOME
.cargo-home/
# Local rustup home used for cross-target `cargo check` verification
.rustup-home/
# Generated plugin fixture manifests/artifacts
examples/plugin-demo/build/
examples/plugin-multi-export/build/
examples/provider-demo/build/
# Release artifacts
dist/
# Local VM/QEMU tooling and disk images
.tools/
# Local-only credentials and environment files
.secrets/
.env.local
# stdlib product test output
stdlib/tests/out/
# Python tooling caches and perf capture files
__pycache__/
*.pyc
.perf-out-*
.perf-err-*
+46
View File
@@ -0,0 +1,46 @@
# Woodpecker CI pipeline for the Rust workspace.
# The strict security lane needs a disposable VM/self-hosted runner and is
# intentionally not part of this docker pipeline; see docs/security-vm.md.
when:
event: [push, pull_request]
steps:
test:
image: rust:1.100-bookworm
commands:
- rustup component add clippy rustfmt
- apt-get update
- apt-get install -y --no-install-recommends curl ca-certificates python3 build-essential gcc-mingw-w64-x86-64
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y --no-install-recommends nodejs
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
# The provider CLI tests resolve a real provider worker next to the CLI
# binary. Build it once so the test harness does not need a nested build.
- cargo build --locked -p marqdo-provider-worker
- cargo test --workspace --locked
- cargo test -p marqdo-cli --test docs_consistency
- cargo test -p marqdo-cli --test architecture_boundaries
- python3 -m unittest discover -s tools/ci -p "test_*.py"
- cargo test -p marqdo-cli --test stdlib_product
# Windows compile gate: runtime lanes are native on GitHub; this catches
# cfg/compile regressions on the Linux CI without a Windows runner.
- rustup target add x86_64-pc-windows-gnu
- cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
build:
image: rust:1.100-bookworm
depends_on: [test]
commands:
# Release archives must ship both binaries: the provider worker is the
# only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- test -x target/release/marqdo-provider-worker
# Build the deterministic archive from this exact commit and cold-install
# smoke-test it; the package script refuses a dirty tree or wrong SHA.
- |
set -eu
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
+52
View File
@@ -0,0 +1,52 @@
# G4 fixed performance node.
#
# Manual only: this workflow never runs on push or pull_request and therefore
# never executes untrusted PR code on the designated performance agent. The
# repository currently has one Woodpecker agent (agent_id 1), so it is the
# fixed node; the CPU affinity and hardware/toolchain manifest are recorded in
# every report. Do not compare its timings with another machine or with
# QEMU/TCG.
when:
event: [manual]
branch: [master]
steps:
measure:
image: rust:1.100-bookworm
commands:
- apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates
- cargo build --release --locked -p marqdo-cli
- |
set -eu
allowed="$(awk '/^Cpus_allowed_list:/ {print $2}' /proc/self/status)"
cpu_list="${MARQDO_PERF_CPU_LIST:-$(printf '%s' "$allowed" | cut -d, -f1 | cut -d- -f1)}"
echo "G4_NODE host=$(uname -n) kernel=$(uname -r) arch=$(uname -m) allowed_cpus=$allowed pin=$cpu_list"
echo "G4_CPU $(awk -F: '/model name/ {print $2; exit}' /proc/cpuinfo | xargs)"
echo "G4_GOVERNOR $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo unavailable)"
python3 tools/perf/runner.py --no-build --warmups 5 --samples 20 \
--approved-node --platform-id woodpecker-agent-1 \
--cpu-list "$cpu_list" --out perf.json
python3 - <<'PY'
import json
with open("perf.json", encoding="utf-8") as handle:
report = json.load(handle)
print(
"G4_STATUS "
f"{report['status']} correctness={report['correctness']} "
f"platform={report['platform_id']} "
f"binary={report['binary']['sha256']}"
)
for workload in report["workloads"]:
print(
"G4_WORKLOAD "
f"{workload['name']} {workload['status']} "
f"p50={workload.get('median_ms')} "
f"p95={workload.get('p95_ms')} "
f"rss={workload.get('max_rss_kb_median')}"
)
PY
echo "G4_REPORT_BEGIN"
cat perf.json
echo "G4_REPORT_END"
+23 -18
View File
@@ -1,14 +1,17 @@
# Marqdo CLI — Agent / Contributor Operating Rules
**Start here:** read `docs/DEVELOPMENT_BLUEPRINT.md` before proposing code. It is the project architecture baseline. Then read `docs/STATUS.md` (what is actually implemented), the relevant `spec/` files, `docs/adr/` for frozen decisions, `docs/contributor-guide.md` for the workflow, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative.
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative.
For next-phase work, the single authoritative plan is
`docs/STABLE_RELEASE_IMPLEMENTATION.md` (stable-release gates G-A/G-B/G-C,
PR order and release checklist). Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
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,
REL-01..REL-05, version axes, LTS conditions). `docs/STABLE_RELEASE_IMPLEMENTATION.md`
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
(historical stabilization spec, baseline `0adebe4`), `docs/NEXT_PHASE_IMPLEMENTATION.md`
(M0.6 plan), `docs/EXTENSIBILITY_AUDIT.md` (E01–E16), `COMPATIBILITY.md` and
`docs/security-gate.md`. The older plans are historical input: the stable-release
spec supersedes them on current baseline, gap list, PR order and release gates.
`docs/security-gate.md`. Older plans are historical input; the 3.0 prerelease plan is authoritative for
current release decisions, and the stable-release spec applies only when the
project moves from beta to stable.
None describes implemented behavior; re-check against HEAD and tests. `strict`
remains fail-closed until G-C passes.
@@ -21,29 +24,31 @@ correctness and release evidence before expanding the surface.
1. New independent language/toolchain. **Do not silently modify `cflmy/marqdo`** or claim compatibility with its syntax, package format or plugin ABI.
2. CommonMark/GFM/Math AST is the sole Markdown syntax structure. Do **not** implement a second Markdown parser or use regex heuristics to decide whether text is executable.
3. Executable roles are based on AST type and valid structural context: `Strong` execution, `Emph` return, ordered list branch, bullet list loop, blockquote invocation, heading scoping. Invalid executable shapes are compile errors, not ordinary prose fallbacks.
4. Prose and executable nodes may mix freely in one function/branch/loop body. Prose itself never causes an action.
3. The language has **one** Markdown→program mapping (RFC-LANG-0002): `@exec`/`@knowledge` heading modes with ancestor inheritance; only an Exec H2 is callable; `Strong`, `Emph` and inline `Code` are interchangeable one-statement payload carriers; `if`/`else`/`while`/`end`/`return`/`params` decide control flow; lists, block quotes and paragraphs are presentation containers with no instruction type. Invalid payloads are hard errors, never prose fallbacks. Do not reintroduce Strong=execute, Emph=return, ordered-list=branch, bullet-list=loop or block-quote=call, and do not add a per-file syntax switch, `map_v1`, `--legacy` or a second active spec.
4. Prose and executable payloads may mix freely in one function/branch/loop body. Prose itself never causes an action; executable payloads with no owning H2 Exec function are errors (`sem.exec_without_function`).
5. Marqdo is executed by **its own Rust interpreter**. Python/Node are optional foreign kernels, never the official compiler target.
6. Code fences and math expressions create inert native `Code` and `Formula` values. Evaluation requires explicit calls and relevant capability grants.
7. YAML project/dependency and frontmatter imports must be explicit. Markdown Links are static references, not implicit calls or imports.
6. Code fences and math expressions create inert native `Code` and `Formula` values. Evaluation requires explicit calls and relevant capability grants. Inline `Code` spans are payload carriers only in an Exec scope; fenced code is never executed.
7. YAML project/dependency and frontmatter imports must be explicit. Markdown Links are static references, never calls or imports. Calls are expressions inside executable payloads.
8. Third-party plugins require a versioned **C ABI and SDK**. A C ABI is not a sandbox. Default third-party execution must be isolated; in-process native loading requires explicit trust.
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
## Development workflow
1. Identify the affected rule and cite the section of `docs/DEVELOPMENT_BLUEPRINT.md`.
2. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST and execution IR.
3. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, runtime and host separated.
4. Run formatting, clippy, unit tests, gold 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. 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 blueprint divergences explicitly.
1. Identify the affected rule and cite RFC-LANG-0002 / `spec/mapping.md` (or, for architecture-only changes, the relevant `docs/DEVELOPMENT_BLUEPRINT.md` section).
2. Update the normative spec **in place** first; there is never a second active syntax spec.
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
5. Run formatting, clippy, unit tests, golden tests and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`).
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
The blueprint's section **17** lists issues that need separate Accepted ADRs (e.g. emphasis conflicts, parameter inference ambiguity, plugin memory ownership, strict platform isolation). Use its proposed baseline for prototypes, but do not freeze these topics through undocumented code.
RFC-LANG-0002 resolves the old emphasis/control-role conflict: `Strong`, `Emph` and inline `Code` are equivalent carriers and controls are keywords with explicit `end`. Remaining topics still need separate Accepted ADRs (parameter inference policy, plugin memory ownership, strict platform isolation, future `elif`/`for`/`break`, knowledge anchors). Do not freeze them through undocumented code.
## Priorities
P0 AST/grammar contracts → P1 independent interpreter → P2 references/CLI → P3 package/env → P4 sandbox → P5 math/foreign → P6 plugin ABI/SDK → P7 performance/release. Design the Host security boundary and ABI early, even if full implementation arrives later.
P0 language contract maintenance (RFC-LANG-0002, single grammar, corpus and stdlib) → P1 independent interpreter → P2 references/CLI → P3 package/env → P4 sandbox → P5 math/foreign → P6 plugin ABI/SDK → P7 performance/release. Design the Host security boundary and ABI early, even if full implementation arrives later.
**Never** translate Marqdo into Python as the official execution method; **never** silently downgrade an invalid execution node to prose or a requested strict sandbox to an unrestricted process.
**Never** translate Marqdo into Python as the official execution method; **never** silently downgrade an invalid payload to prose, a requested strict sandbox to an unrestricted process, or the current syntax to a legacy mapper.
+349 -8
View File
@@ -1,9 +1,200 @@
# Changelog
All notable changes to the Marqdo CLI workspace. The workspace version is
currently `0.1.0`; no release tag has been cut. Dates use ISO 8601.
All notable changes to the Marqdo CLI workspace. Product version
`3.0.0-beta.1` was tagged on 2026-11-22; the next section collects post-beta
changes. Protocol versions (Analysis v2, Trace v2, Tool v1, Plugin ABI v1,
Foreign wire v1, Provider manifest v2, lock v4) and independent package
versions (including the bundled stdlib `0.1.0`) are versioned separately and
do not follow the product version. Dates use ISO 8601.
## Unreleased (stabilization candidate)
## 3.0.0-beta.1 (2026-11-22)
First public prerelease of the independent Marqdo toolchain. This is a
**prerelease, not stable and not LTS**; the support claim is Linux x86_64 until
the stable `3.0.0` gate passes. The complete beta policy, gates and deferred
items are in
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) and
[`docs/developers/release-limits.md`](docs/developers/release-limits.md).
### Product version and compatibility
- Workspace/crate product version, `marqdo --version` and Analysis
`producer.version` are now `3.0.0-beta.1`. `Cargo.lock` is committed and all
release builds use `--locked`.
- `project.marqdo` in `marqdo.yaml` is now **enforced** against the running
core instead of being informational. Incompatible ranges fail closed with
`package.marqdo_incompatible`; malformed ranges fail with
`package.marqdo_range_invalid`. The `init` template writes
`>=3.0.0-beta.1,<4.0.0`.
- SemVer prerelease negotiation is covered by tests: a stable-only range such
as `>=3.0.0,<4.0.0` does **not** silently accept a beta core, while an
explicit `>=3.0.0-beta.1,<4.0.0` Tool/Project range does.
- The official bundled stdlib stays `0.1.0`; plugin, tool and example package
versions are independent of the product version. No protocol major is
renumbered because the product is 3.0.
### Release engineering
- Release archives now ship **both** `marqdo` and `marqdo-provider-worker` in
the same directory for the same target triple, plus `RELEASE_INFO.json`
(source SHA, target, toolchain, binary SHA-256), `SOURCE_SHA`,
`KNOWN_LIMITATIONS.md`, the public specs, developer docs, runnable examples
(including host-built plugin/provider artifacts) and the Analysis/Trace
consumers. `tools/release/package.py` builds deterministically;
`tools/release/smoke.py` verifies a cold install from the archive only.
- Release evidence distinguishes the **beta** profile from the stable profile:
`tools/ci/release_evidence.py --profile beta` requires Linux, strict-policy,
frozen-binary extension, clean-install and version-compatibility gates,
records unsupported platforms explicitly and never turns a missing or
SHA-mismatched gate into a release.
- Added a runnable Resource Provider v2 example
(`examples/provider-demo/`) and used the frozen external conformance
repository as the same-SHA black-box gate.
### Developer entry points
- New [`docs/developers/`](docs/developers/README.md): quickstart, `.mq.md`
libraries, Tool Protocol, extensions (plugin/kernel/provider), Analysis/Trace
consumers, compatibility and release limits.
- The third-party integration handbook was corrected and exercised against the
released binary; `spec/tool-v1.md` no longer says Proposed,
`spec/plugin-abi.md` no longer says native-only, and `spec/package-format.md`
documents the enforced `project.marqdo` field and lock v4.
- `check --emit` help now correctly says Analysis v2.
### Support policy
- Supported release platform: **Linux x86_64 (glibc)**. macOS/Windows are
experimental and not claimed; the Windows cross-target check remains a CI
compile gate only.
- `strict` policy for this beta is recorded with same-SHA evidence in
[`docs/STATUS.md`](docs/STATUS.md); unsupported hosts fail closed. strict L2
is unsupported and refused.
- The G4 performance gate is recorded as a Beta-only WARN on the fixed
Woodpecker agent, with environment and limits, instead of being promoted to a
stable PASS.
## Unreleased (post-beta)
### Planned changes
- Fixes collected from the first beta users; see `docs/MARQDO_3_0_PRERELEASE_PLAN.md`
§5 for the conditional `3.0.0-beta.2` / `rc.1` line.
## Historical: stabilization candidate
### Breaking changes — extensibility closure (RFC-EXT-0001)
Implements [`docs/architecture/RFC-EXT-0001.md`](docs/architecture/RFC-EXT-0001.md)
(ADR-0054/0055/0056/0057/0058). These are the 3.0 breaking changes; the
independent protocol versions listed above are unchanged:
- **One callable resolution.** `check`/`run`/`call`/`inspect`/Analysis share a
single registry and binding pass (`CallSiteKey`). The runtime no longer
re-resolves names or guesses a plugin when no descriptor is loaded. An import
alias that collides with a builtin/plugin dotted namespace (for example
importing a module as `math`) is now `ext.import_namespace_conflict`; rename
the alias. Unknown plugin exports are `symbol.unknown` at compile time.
- **Exact plugin binding.** A plugin manifest is the static signature contract;
`run` verifies artifact bytes and reconciles exports/signatures/owners/digests
one-to-one (`ext.plugin_binding_mismatch`). Empty/synthesised signatures are
gone; ABI v1 signature defaults are rejected; positional arguments are
normalised to manifest order.
- **Lock v4.** `marqdo.lock` upgrades to `lock_version: 4` with an `extensions:`
identity table. Lock v3 is rejected with an explicit `marqdo lock` migration
error; it is never reinterpreted silently. Projects can declare explicit
activation sources under `marqdo.yaml.extensions` (`./path` or `@alias/path`
only); a declaration is not a grant.
- **Analysis calls projection.** `calls[].state/target` now come from the same
binding; official stdlib aliases such as `打印` project as `function` targets.
Analysis v2 schema/version are unchanged and the private binding table is not
serialized.
- **Print magic removed.** `打印`/`print` are verified `stdlib.json`
`public_aliases` bound to `io.mq.md::写值`; `Program.print_override`, the
AST-wide print scan and the runtime print branch are deleted. Output bytes are
unchanged; programs without print do not load the stdlib module graph.
- **Third-party resource providers via CLI.** `--provider PATH` /
`--allow-provider NAME` on `run`/`call` select and authorize a
`provider.json` schema-2 worker artifact; verified before spawn; pure/strict
refuse; linux/x86_64 only (other platforms fail closed).
- **Capability handler registry.** Granted capabilities execute only through a
trusted installed handler under budget/audit; a declared-but-unhandled
capability stays `capability.unavailable`.
### Breaking changes — language source syntax (RFC-LANG-0002)
**The `.mq.md` source language changed incompatibly. Old source files are not
executable.** The current contract is
[`docs/architecture/RFC-LANG-0002-unified-semantics.md`](docs/architecture/RFC-LANG-0002-unified-semantics.md)
(accepted by [`docs/adr/0052-unified-markdown-semantics.md`](docs/adr/0052-unified-markdown-semantics.md)),
summarized normatively in [`spec/mapping.md`](spec/mapping.md) and
[`spec/expression.ebnf`](spec/expression.ebnf).
- Removed the old mapping in which `Strong` executes, `Emph` returns, an
ordered list is a branch, a bullet list is a loop, a block quote is a call and
the first standalone code span is a signature.
- Headings now declare `@exec` / `@knowledge`; unmarked headings inherit the
nearest ancestor's mode, and the document root is Knowledge.
- Only an Exec H2 is a callable function; H2 Knowledge is inert and H3–H6 are
non-callable sections. A payload with no owning Exec H2 is
`sem.exec_without_function`.
- `Strong`, `Emph` and inline `Code` are interchangeable carriers of exactly one
statement; the AST kind no longer selects the operation.
- Control flow comes from keywords in the payload: `if`/`else`/`while`/`end`
(explicitly closed) plus `return <expr>` and `params(...)`. Ordered lists,
bullet lists, block quotes and paragraphs are presentation containers with no
instruction type; a plain list or quote produces zero statements.
- `params(...)` is the only function-signature declaration, legal only as the
first direct payload of an Exec H2. An Emph/Strong payload in a signature
position is no longer special.
- There is no syntax version switch, per-file selector, `--legacy` path or
fallback mapper; `marqdo_semantics`/syntax-selection front matter is rejected.
**Historical implementation record (at `9c1723d`).** The language migration
landed in the `semantics-v2-refactor` history (docs/spec `4983542`,
frontend/runtime/stdlib/corpus `e029853`, expression-owned statement grammar
`ffd1cc9`, then the follow-up fixes through `9c1723d`). At `9c1723d` the
workspace gate was green (507 passed, 0 failed, 2 ignored). That count is
history; the current release-SHA gate is recorded in
[`docs/STATUS.md`](docs/STATUS.md). See also
[`docs/evidence/2026-11-21-semantics-v2-green.md`](docs/evidence/2026-11-21-semantics-v2-green.md).
**Follow-up correctness fixes in the same series:**
- `params(...)` is enforced as the first function-wide direct Exec H2 payload, so
a later `### @exec` segment cannot add a signature after earlier statements;
- a `params(...)` code span in a `@knowledge` section is inert documentation and
never becomes a signature (`inspect --signature` now reports `inferred`);
- a stray `end` diagnostic points at the `end` payload instead of the previous
statement;
- Setext headings inherit but never declare a mode, as `spec/mapping.md` states;
- diagnostics are emitted in the documented stable order (source position, then
code);
- the unreachable `Stmt::Call`/`CallSite`/`CallTarget` IR left over from the
removed link-form block-quote call was deleted.
**Required migration actions for consumers and the repository:**
1. Rewrite every active `.mq.md` source by AST role (not by a global regex):
stdlib modules, examples, fixtures, project templates, Rust-embedded samples
and documentation snippets.
2. Give callable functions an explicit `## @exec 名称` heading, or place them
under an `# @exec` namespace. Knowledge documents and visual emphasis belong
in `@knowledge` sections; a `Strong`/`Emph` payload in an Exec section is a
statement and may fail as an unknown symbol.
3. Replace italic returns with `return <expr>` in any carrier.
4. Convert an ordered-list branch to a first-true nested `if`/`else`/`end`
chain; convert each bullet-list item to its own `while`/`end` loop, preserving
item order and early-return behavior.
5. Convert block-quote calls to payload calls (`**print(x)**`,
`` `print(x)` `` or `> **print(x)**`) and standalone code-span signatures to
`params(...)` as the first direct Exec H2 payload.
6. Replace old shape expectations with the `sem.*` diagnostics in
`spec/mapping.md` §8; ordinary lists/quotes are now valid inert Markdown.
7. Regenerate `stdlib/stdlib.json` only in the same change that migrates the
stdlib sources, and never use `UPDATE_*_GOLDENS=1` to mask a semantic change.
8. A dependency or lock built from old source syntax is not compatible; relock
and re-verify the package instance identity after migration.
### Added
@@ -35,7 +226,9 @@ currently `0.1.0`; no release tag has been cut. Dates use ISO 8601.
compile-negative fixtures and 2 runtime-negative fixtures covering
right-associative `**`, unary-minus precedence, parentheses, float negative
exponents, Strong+CodeSpan payloads, branch/loop conditions, inert prose and
code fences, and source spans inside one/two-backtick code spans.
code fences, and source spans inside one/two-backtick code spans. (The
fixtures were migrated to the unified payload/keyword syntax and are green at
`9c1723d`.)
- Independent Tool Protocol v1 consumers `sample-view`, `sample-knowledge` and
`sample-proof` (analysis/trace readers) with install, dispatch and remove
tests; none is a hard-coded CLI command.
@@ -43,12 +236,158 @@ currently `0.1.0`; no release tag has been cut. Dates use ISO 8601.
without rewriting `marqdo.lock` or the materialized `.marqdo/env`.
- G-C lane honours `CARGO_TARGET_DIR`, so a run from a clean `git archive` with
an external target directory uses the binary it just built.
- Addressable `Memory` (RFC-CM-0001 P1, ADR-0022): an opaque run-scoped
region value with 64 KiB zero-filled pages, grow-only capacity, bounded
byte read/write, `memory.new/size/grow`, and `m[offset] = byte`. Copies share
the region identity; different regions never alias. Default budgets are
64 MiB committed per run and 16 MiB per region; `--max-memory` and
`--max-region-memory` override the budgets on `run`/`call`.
- Memory-index place assignment in the expression/IR model
(`AssignTarget::Index` / `PlaceTarget::Index`) with the frozen evaluation
order base, index, RHS and no change to `List`/`Map`/`Table` value semantics.
- Stable `runtime.memory` error category for invalid/stale handles and page
counts; `runtime.index` for offsets, `runtime.type` for operand/byte-range
errors, `resource.exhausted` for budgets.
- Analysis v2 projects an index assignment target as an additive
`{"kind":"index",...}` object while local targets keep the v1 string.
- `examples/memory-buffer.mq.md`, semantic goldens 45–47 and runtime negatives
13–18 cover sharing, isolation, growth, zero-fill, offsets, byte range,
non-Memory index assignment, declared-max growth and negative page counts.
- Partial RFC-CM P2 closure evidence (`.mq.md` only, no Rust algorithm
additions): fixtures 48–50 implement a big-endian u32 codec, a bump
allocator, node allocation and a linked-list traversal/sum, and prove that a
failed allocation leaves the allocator header unchanged. This is **not** the
full P2 gate: a separate stdlib package and a frozen-CLI closure lane are
still missing.
- `Memory` handles are never transferable: `to_wire` emits a bare rejected tag,
`from_wire` fails, and every host/plugin/foreign call rejects arguments that
contain a handle.
- Minimal structure observation/construction (RFC-CM CM-A04, ADR-0023):
`list.append/concat`, `map.keys/has/get/set/remove`,
`text.codepoints/from_codepoint`, and `table.columns/row/cell`. All are pure,
value-returning builtins; inputs are never mutated and no new syntax is
added. Semantic fixtures 51–53 and runtime negatives 19–21 cover value
semantics, Unicode scalars, table projection, wrong types and bounds.
- `.mq.md` table filter (`过滤`) built on `table.columns/row/cell`,
`list.append` and `表`, with a semantic golden showing the input table is
unchanged (fixture 54). No `table.filter`/`HostOp` is added.
- Recoverable `Result` convention (RFC-CM CM-A05, ADR-0024): an ordinary Map
`{ok:true,value}` / `{ok:false,code,message[,details]}`, constructed by
`.mq.md` functions, with expected failures recoverable and language
invariant violations still fatal. No `Result` type, exception or
`try`/`catch` syntax.
- `.mq.md` first-fit free-list allocator (fixture 55): 8-byte block headers,
free-block reuse, block splitting, address-adjacent coalescing (tested in a
second region whose bump space is exhausted, so only a merged block can
satisfy the request), non-overlapping reused payloads and `alloc.no_space`
returned as a `Result` without aborting the run. No allocator Rust builtin or
`HostOp` was added.
- `.mq.md` P2 closures beyond the first slice: binary tree insert/in-order
traversal (56), CSV row splitter (57), open-addressing hash table (58),
UTF-8 encoder/validating decoder (59–60), graph adjacency list (61),
recursive JSON parser for arrays/objects/strings (62), stack bytecode VM
(63), 16/32/64-bit + LEB128 codecs (64), table sort (65), table equality join
(67) and quoted/escaped CSV (68). No Rust algorithm, container or parser was
added for these; algorithms remain `.mq.md` code. JSON float parsing and a
compact formatter are included.
- Resource/stream first slice (RFC-CM CM-A06, ADR-0025): opaque host-issued
`Resource` handles, `resource.open/read/write/close`, bytes transferred
through `Memory`, stdout write in pure/project under console/output budgets,
granted project-file chunked read in project, EOF as success, closed-handle
Result errors, forged-handle fatal errors, wire/host-boundary rejection, and
strict refusing every resource open. Semantic fixture 66 and host/CLI tests.
- Buffered project-file write streams (ADR-0026): `file` + `["write"]` requires
an `fs_write` grant, buffers in the host, flushes only on `close`, never
flushes on drop, has an 8 MiB ceiling, and is refused in pure/strict. A
`.mq.md` chunked copy loop reproduces a file without a Rust `copy_file`.
- Compat-C print completion (ADR-0031): remove `HostOp::Print` and
`StdHost::op_print`; the print builtin only routes to bundled `io.写值` or
returns `kernel.unavailable`; print traces contain only resource effects.
- Compat-B `打印`/`print` routing (ADR-0030): a `Program.print_override` sends
print calls to bundled `io.写值` when the program uses them; stdlib modules
are injected lazily, resource operations appear as trace effects and the
legacy `HostOp::Print` path does not run. Strict permits only stdio/stdout
(existing console), not file/network resources. No Compat-C removal yet.
- Full-value stdlib formatting (ADR-0029): FunctionRef `module/name` and
PluginHandle `plugin/export` read-only members (host id private);
`stdlib/format.mq.md` now reproduces builtin `打印`/`repr` for all 15 value
types, including Formula/Code and UTF-8 byte length for Code.
- CM-A10 bundled stdlib (ADR-0028): a fixed `stdlib/` tree with
`format/text/io`, explicit `std:<path>` imports, SHA-256 digest verification
before module loading, a `std:marqdo-stdlib@<version>#<digest>` package
instance id, `project.stdlib` in Analysis v2, and test coverage for
`std:` resolution, tamper rejection and frozen-binary hash equality.
- P2 closure gate: add a pure no-Foreign/no-Plugin lane for C01–C06/C11/C12
(20 fixtures + stdlib table), source shortcut scan and golden comparison.
- CM-A10 offline packaging: `tools/pack-stdlib.py` emits a deterministic
`marqdo-stdlib-0.1.0.tar.gz` plus tree/archive digests and a file manifest;
the archive is for the future external repository, not the CLI loader.
- P2 anti-evasion: explicit pure-lane negative tests prove `foreign.call` is
`permission.denied` and `plugin.invoke` fails, alongside the 21 fixture lane.
- C12 sparse matrix: fixture 73 adds triple-list sparse multiply and dense
conversion, included in the P2 pure closure lane.
- P6 baseline profile: add `tools/perf/bench.py` and a checked-in 7-workload
JSON report; no bytecode/JIT/native backend is introduced.
- P4 cross-storage table equivalence: fixture 72 compares row-store Table
sort/filter output with a `.mq.md` columnar store cell-by-cell.
- CM-A09 C ABI provider worker binding (ADR-0038): add the separate
`marqdo-provider-worker` helper that loads a trusted C ABI library and serves
the ADR-0035 framed-JSON protocol; crash isolation but not a sandbox.
- CM-A09 provider package manifest v1 (ADR-0037): local manifest resolves a
trusted C ABI library and registers it; no registry/signatures/CLI install.
- CM-A09 C ABI provider v1 (ADR-0036): trusted shared libraries implement
open/read/write/close/version/last_error; host loads them with version and
symbol checks, project-mode + name grant only. Plugin-Worker binding remains
open.
- CM-A09 worker provider transport (ADR-0035): host-managed helper process
speaking framed JSON for resource open/read/write/close; trusted-only,
project-mode + name grant; C ABI binding still open.
- P5 HTTP framing/client: `stdlib/net/http.mq.md` parses status/headers/chunked
responses and builds requests; `http_over_tcp.rs` runs a loopback TCP HTTP
exchange through `resource.open("tcp")`. No host HTTP/TLS implementation.
- CM-A08 GFM rendering: `stdlib/data/table.mq.md::转GFM` renders a logical
Table as a GFM pipe table with cell escaping; CLI test added.
- P5 HTTP parser fixture (C10): semantic fixture 71 parses HTTP/1.1 status,
headers and chunked transfer bodies and builds requests in `.mq.md`; no host
HTTP/HTTPS implementation is claimed.
- P5 blocking TCP endpoint v1 (ADR-0034): `resource.open("tcp", ip:port,
["read","write"])` with exact IP-literal grants, project mode only, 5s
connect/read/write timeouts; no DNS/TLS/UDP/server sockets. CLI `--allow-net
<IP>`; loopback host and `.mq.md` echo tests. Strict/pure refuse.
- CM-A09 in-process ResourceProvider v1 (ADR-0033): `ResourceProvider` trait,
`StdHost::register_resource_provider`, per-kind registration with protocol
version/conflict checks and `Capabilities.allow_resource_provider`; provider
streams reuse `resource.*` and are project-mode only. A mock read/write
provider test runs without parser/runtime/`HostOp` changes. C/Worker provider
transport remains open.
- CM-A08 table logical/stdlib slice (ADR-0032): `stdlib/data/table.mq.md`
adds select/filter/sort/append/set-cell/join/group as value-returning
`.mq.md` functions; `Value::Table` semantics and GFM AST laziness unchanged;
no physical storage migration or new table builtin.
- CM-A07 **Compat-A** prototype (ADR-0027): `stdlib/` provides
`format.显示`, UTF-8 encoding and `io.写值` (`resource.write(stdout)`), and
its output is comparison-tested byte-for-byte against builtin `打印` for
Unit/None/Bool/Int/Float/Text/List/Map/Table. Builtin `打印` remains the
default; no alias routing, bundled stdlib or `HostOp::Print` removal; the
other value types lack public observation.
### Changed
- `docs/STABLE_RELEASE_IMPLEMENTATION.md` is the single next-phase
implementation plan. Older plan documents are historical input, not current
status.
- `spec/mapping.md` and `spec/expression.ebnf` were replaced in place by the
RFC-LANG-0002 contract (heading modes, unified payload carriers, keyword
control flow). `spec/markdown-profile.md` remains `marqdo.md.v1`; only the
Markdown→program mapping changed. The frontend, expression parser, IR,
runtime and bundled stdlib implement these specs in the same tree; see
"Breaking changes" above.
- Assignment targets are no longer restricted to bare identifiers: a single
index place is accepted at statement level. Member assignment stays a parse
error; chained assignment stays a parse error. `spec/expression.ebnf`,
`spec/evaluation.md`, `spec/value-wire.md`, `spec/analysis-v2.md` and
`spec/security.md` document the new semantics.
- `docs/MARQDO_3_0_PRERELEASE_PLAN.md` is the current release policy;
`docs/STABLE_RELEASE_IMPLEMENTATION.md` is historical roadmap input, not
current status.
- AST conformance tests fail early when a golden contains CR bytes instead of
reporting an opaque mismatch.
- Worker plugin fixtures use the platform dynamic-library name and compiler
@@ -56,7 +395,9 @@ currently `0.1.0`; no release tag has been cut. Dates use ISO 8601.
- List-item condition paragraphs now accept only inert description; an
executable `Strong`/`Emph` there is a hard `markdown.invalid_construct`
error instead of being silently swallowed. Condition expression spans are
mapped from the literal bytes inside the code-span backticks.
mapped from the literal bytes inside the code-span backticks. (Pre-RFC
mapping; superseded by RFC-LANG-0002, where lists have no condition head at
all.)
- Linux strict `inspect --platform` remains a snapshot, not a promise. A run
that loses namespace/resources between probe and launch must fail closed.
+99 -20
View File
@@ -1,20 +1,64 @@
# Compatibility and support matrix
Snapshot: workspace version **0.1.0**, code/security SHA **`8af7262`**, no
release tag cut. This file records what was actually verified and separates it
from what is only implemented.
Snapshot: product version **`3.0.0-beta.1`** (prerelease), branch `master`,
tagged `v3.0.0-beta.1`. This file records what was actually verified and
separates it from what is only implemented. The supported release platform is
**Linux x86_64 (glibc)**; everything else is experimental and not claimed for
this beta. Executed status and same-SHA evidence are in
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under
[`docs/evidence/extension/`](docs/evidence/extension/README.md).
## Language source syntax (breaking change)
**The `.mq.md` source language is a breaking change.** The current contract is
[RFC-LANG-0002](docs/architecture/RFC-LANG-0002-unified-semantics.md)
(accepted by [ADR-0052](docs/adr/0052-unified-markdown-semantics.md)), with the
normative summaries in [`spec/mapping.md`](spec/mapping.md) and
[`spec/expression.ebnf`](spec/expression.ebnf):
- H1–H6 headings declare `@exec`/`@knowledge` modes; unmarked headings inherit
the nearest ancestor's mode and the document root is Knowledge.
- Only an Exec H2 is a callable function. H2 Knowledge is inert and H3–H6 are
non-callable sections.
- In an Exec scope, `Strong`, `Emph` and inline `Code` are interchangeable
carriers of one statement; the original emphasis role is gone.
- Control flow comes from keywords in the payload (`if`/`else`/`while`/`end`/
`return`/`params(...)`). Ordered lists, bullet lists and block quotes are
inert presentation containers.
- There is no version selector, `--legacy` path or fallback mapper.
Consequences for compatibility:
- **Old pre-RFC `.mq.md` source is not executable.** A file that relied on
`Strong` = execute, `Emph` = return, ordered list = branch, bullet list =
loop, block quote = call or a first code-span signature must be rewritten by
AST role (see `docs/migration/README.md`). A parse failure is a hard
diagnostic, never a fallback to prose.
- The Markdown parser profile stays `marqdo.md.v1`; only the Markdown→program
mapping changed. Rendering of otherwise-ordinary Markdown is unaffected.
- **Implementation state:** RFC-LANG-0002 is implemented by the frontend,
expression parser, IR lowering, runtime and bundled stdlib. At
`9c1723d` the workspace gate is
`cargo test --workspace --locked`: 507 passed, 0 failed, 2 ignored, and the
stdlib digest is regenerated and verified. See
[`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/2026-11-21-semantics-v2-green.md`](docs/evidence/2026-11-21-semantics-v2-green.md).
## Public protocol versions
| Surface | Version | Compatibility rule |
|---|---|---|
| Markdown profile | `marqdo.md.v1` | Frozen parser/options; semantic change needs an ADR, new goldens and a profile id bump. |
| Language / CLI | workspace `0.1.0` | Pre-1.0. CLI flags may change with a changelog note; `strict` refusal is contractual. |
| `marqdo.lock` | v3 | v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. |
| 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-beta.1` (prerelease) | 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). |
| Analysis | v2 | Consumers reject unknown majors; incompatible field changes require v3. |
| Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
## Platform / feature evidence
@@ -26,9 +70,17 @@ portable/tested locally but the native platform lane has not run here;
| Feature | Ubuntu Linux x86_64 | macOS arm64 | Windows x86_64 |
|---|---|---|---|
| Markdown profile / AST goldens (160) | PASS | UNVERIFIED (cfg fix + CRLF fix) | UNVERIFIED (cfg fix + CRLF fix) |
| Rust interpreter / semantics (44) | PASS | UNVERIFIED | UNVERIFIED |
| Rust interpreter / unified semantics (73) | PASS | UNVERIFIED | UNVERIFIED |
| Addressable `Memory` P1 (ADR-0022) | PASS | UNVERIFIED | UNVERIFIED |
| Resource streams CM-A06 (ADR-0025/0026: stdout + project file read/write) | PASS | UNVERIFIED | **FAIL-CLOSED** (`strict` refuses resource opens) |
| `run` / `call` / `check` / `inspect` / `fmt` | PASS | UNVERIFIED | UNVERIFIED |
| lock v3 path/Git graph + sync + tamper | PASS | UNVERIFIED | UNVERIFIED |
| lock v4 path/Git graph + sync + tamper | PASS | UNVERIFIED | UNVERIFIED |
| Extension selection/lock v4 (`extensions:`, identities, `inspect --extensions`) | PASS | UNVERIFIED | UNVERIFIED |
| Callable single binding + `ext.import_namespace_conflict`/`symbol.unknown`/plugin reconciliation | 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** |
| 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 |
| Analysis v2 / Trace v2 + Python 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** |
@@ -38,11 +90,15 @@ portable/tested locally but the native platform lane has not run here;
| `strict` Linux L1 (pure Marqdo + Math) | PASS, probe-gated, 7/7 VM lane | **FAIL-CLOSED** | **FAIL-CLOSED** |
| `strict` L2 (Worker/Foreign/native) | **UNSUPPORTED** (flags refused) | **UNSUPPORTED** | **UNSUPPORTED** |
The Ubuntu column is from this development host (Ubuntu 26.04 container) and a
disposable Ubuntu 26.04 QEMU/TCG VM for the security lane. It is **not** a
GitHub Actions result: this checkout has a Gitee remote and no GitHub
credentials. A fresh local clone with `core.autocrlf=true` was used to
reproduce the Windows checkout byte behavior.
The Linux column is the supported beta platform. Lanes marked PASS were
executed on the release commit: the Woodpecker Linux pipeline (fmt, clippy,
workspace tests with `--locked`, Windows cross-target compile check, release
build of both binaries), the release-archive cold-install smoke, the external
frozen-binary conformance repository, and the disposable-VM strict lane. The
source of truth is the Gitea remote `git.cflmy.cn/cflmy/marqdo-cli` with
Woodpecker at `ci.cflmy.cn`; a GitHub mirror is not the authoritative lane for
this beta. macOS/Windows entries are implementation notes, not support claims;
the Windows C ABI/provider paths remain fail-closed.
## Strict L1 scope (ADR-0021)
@@ -68,8 +124,24 @@ reproduce the Windows checkout byte behavior.
permits user, mount, PID and network namespaces. See
[`docs/security-gate.md`](docs/security-gate.md) and ADR-0021.
## Explicitly unsupported in this candidate
## RFC-EXT-0001 platform statements
* Provider worker transport: linux/x86_64 only; macOS/Windows return
`ext.platform_unsupported` (compile-only, fail-closed). The RFC's macOS
provider lane is **not claimed**.
* Windows Native/Worker ABI remains **UNSUPPORTED**; a Linux PASS does not
substitute for it.
* `strict` L1 continues to refuse plugins/providers/foreign kernels; strict L2
is not implemented. A worker is a trusted process, not an OS sandbox.
* The external conformance suite is a mandatory **additional** release gate
(`docs/releasing.md` §7); it does not replace G3/G4/native lanes.
## Explicitly unsupported in this beta
- Pre-RFC `.mq.md` source syntax (Strong-execute / Emph-return / ordered-list
branch / bullet-list loop / block-quote call / first code-span signature).
Old sources are a rewrite task, not a compatibility mode: there is no
`--legacy`, `marqdo_semantics` selector or second mapper.
- OS-level strict isolation on macOS/Windows (Linux only, probe-gated).
- Strict L2: Worker/Foreign execution inside strict (refused in L1).
- Windows Native/Worker ABI runtime support.
@@ -78,11 +150,18 @@ reproduce the Windows checkout byte behavior.
- Registry/package publishing, JIT, Knowledge/Proof/View built-ins,
sessions, and general-purpose CAS. The three `sample-*` tools are test
fixtures for the generic Tool protocol, not product features.
- Windows/macOS release archives from this host; the GitHub release job may
build macOS but has not run for the convergence SHA.
- 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;
the Windows lane is a Linux-hosted compile gate only.
## Release decision
**DO NOT RELEASE.** G1/G2/G3 (native CI) and G9 (self-hosted security-lane CI
URL) have no real remote PASS for this SHA. See
[`docs/evidence/RELEASE_CANDIDATE_0.1.0_8af7262.md`](docs/evidence/RELEASE_CANDIDATE_0.1.0_8af7262.md).
**`3.0.0-beta.1` prerelease — approved as a Linux x86_64 beta with explicitly
recorded gaps.** The beta profile in
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3.1
was used, not the stable profile: Linux is the only supported platform,
macOS/Windows are declared unsupported/experimental, G4 is a Beta-only `WARN`
on the fixed Woodpecker agent, and strict policy and frozen-binary conformance
are recorded with same-SHA evidence in [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/ci/`](docs/evidence/ci/README.md). Beta status does not imply
stable `3.0.0` or LTS; the stable gate remains stricter and separate.
Generated
+458 -22
View File
@@ -2,6 +2,21 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
@@ -38,7 +53,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -49,7 +64,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -58,6 +73,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -82,6 +103,16 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -151,6 +182,22 @@ dependencies = [
"typed-arena",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -160,6 +207,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -170,6 +226,12 @@ dependencies = [
"typenum",
]
[[package]]
name = "deranged"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "digest"
version = "0.10.7"
@@ -199,7 +261,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -225,12 +287,29 @@ dependencies = [
"syn",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "finl_unicode"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -241,6 +320,17 @@ dependencies = [
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -322,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "marqdo-cli"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"clap",
"hex",
@@ -343,12 +433,13 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"tempfile",
"walkdir",
]
[[package]]
name = "marqdo-expression"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-span",
"num-bigint",
@@ -359,7 +450,7 @@ dependencies = [
[[package]]
name = "marqdo-foreign"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"hex",
"libc",
@@ -375,7 +466,7 @@ dependencies = [
[[package]]
name = "marqdo-frontend"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-expression",
"marqdo-ir",
@@ -390,15 +481,23 @@ dependencies = [
[[package]]
name = "marqdo-host"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"flate2",
"getrandom 0.4.3",
"glob",
"libloading",
"marqdo-foreign",
"marqdo-math",
"marqdo-plugin-abi",
"marqdo-sandbox",
"marqdo-span",
"marqdo-value",
"rcgen",
"regex",
"rustls",
"rustls-native-certs",
"rustls-pemfile",
"serde",
"serde_json",
"tempfile",
@@ -407,7 +506,7 @@ dependencies = [
[[package]]
name = "marqdo-ir"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-expression",
"marqdo-span",
@@ -417,7 +516,7 @@ dependencies = [
[[package]]
name = "marqdo-markdown"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"comrak",
"marqdo-span",
@@ -428,7 +527,7 @@ dependencies = [
[[package]]
name = "marqdo-math"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-value",
"num-bigint",
@@ -439,9 +538,10 @@ dependencies = [
[[package]]
name = "marqdo-package"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"hex",
"semver",
"serde",
"serde_json",
"serde_yaml",
@@ -452,7 +552,7 @@ dependencies = [
[[package]]
name = "marqdo-plugin-abi"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"hex",
"libloading",
@@ -467,16 +567,28 @@ dependencies = [
[[package]]
name = "marqdo-plugin-sdk"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-plugin-abi",
"serde",
"serde_json",
]
[[package]]
name = "marqdo-provider-worker"
version = "3.0.0-beta.1"
dependencies = [
"libloading",
"marqdo-host",
"marqdo-sandbox",
"marqdo-value",
"serde_json",
"tempfile",
]
[[package]]
name = "marqdo-runtime"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-expression",
"marqdo-frontend",
@@ -495,7 +607,7 @@ dependencies = [
[[package]]
name = "marqdo-sandbox"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"libc",
"serde",
@@ -503,14 +615,14 @@ dependencies = [
[[package]]
name = "marqdo-span"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"serde",
]
[[package]]
name = "marqdo-value"
version = "0.1.0"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-span",
"num-bigint",
@@ -535,6 +647,16 @@ dependencies = [
"fearless_simd_macros",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -546,6 +668,12 @@ dependencies = [
"serde",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-integer"
version = "0.1.47"
@@ -588,6 +716,22 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "openssl-probe"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
[[package]]
name = "pem"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
dependencies = [
"base64",
"serde_core",
]
[[package]]
name = "phf"
version = "0.14.0"
@@ -627,6 +771,12 @@ dependencies = [
"siphasher",
]
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -651,6 +801,62 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rcgen"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2"
dependencies = [
"pem",
"ring",
"rustls-pki-types",
"time",
"yasna",
]
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -667,7 +873,62 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
@@ -685,6 +946,38 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "semver"
version = "1.0.28"
@@ -758,6 +1051,18 @@ dependencies = [
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "siphasher"
version = "1.0.4"
@@ -776,6 +1081,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "3.0.10"
@@ -794,10 +1105,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -820,6 +1131,25 @@ dependencies = [
"syn",
]
[[package]]
name = "time"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
dependencies = [
"deranged",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "tinyvec"
version = "1.13.3"
@@ -859,6 +1189,12 @@ version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -881,13 +1217,19 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
"windows-sys 0.61.2",
]
[[package]]
@@ -896,6 +1238,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -905,6 +1256,91 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "yasna"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
dependencies = [
"time",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
+9 -1
View File
@@ -10,6 +10,7 @@ members = [
"crates/marqdo-math",
"crates/marqdo-foreign",
"crates/marqdo-plugin-abi",
"crates/marqdo-provider-worker",
"crates/marqdo-plugin-sdk",
"crates/marqdo-host",
"crates/marqdo-runtime",
@@ -19,7 +20,7 @@ members = [
]
[workspace.package]
version = "0.1.0"
version = "3.0.0-beta.1"
edition = "2021"
rust-version = "1.82"
license = "MIT OR Apache-2.0"
@@ -52,6 +53,13 @@ semver = "1"
hex = "0.4"
libloading = "0.8"
tempfile = "3"
flate2 = "1"
getrandom = "0.4"
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-native-certs = "0.8"
rustls-pemfile = "2"
rcgen = "0.13"
regex = "1"
thiserror = "2"
clap = { version = "4", features = ["derive"] }
walkdir = "2"
+327 -55
View File
@@ -1,33 +1,54 @@
# Marqdo CLI
Marqdo is a **Markdown-native, independently interpreted programming language**:
standard CommonMark/GFM structures carry program control (headings scope,
`**strong**` executes, `*emph*` returns, ordered lists branch, bullet lists
loop, block quotes call), prose and executable nodes mix in one document, and
all side effects go through a capability-checked host boundary. The official
implementation is a Rust workspace; Python/Node are optional foreign kernels,
never the compiler target.
Marqdo is a **Markdown-native, independently interpreted programming language**.
A `.mq.md` file is ordinary CommonMark/GFM prose plus explicit executable
regions: a heading declares `@exec` or `@knowledge`, `**strong**`, `*emph*` and
inline `` `code` `` are interchangeable carriers of one statement, and keywords
inside that payload — `if`, `else`, `while`, `end`, `return`, `params` — decide
control flow. Lists, block quotes and emphasis are document presentation only.
The official implementation is a Rust workspace; Python/Node are optional
foreign kernels, never the compiler target.
This repository is the new, independent Marqdo toolchain (M0.5). It is **not**
a compatibility rewrite of `cflmy/marqdo`; the old syntax, package format and
plugin ABI v2 are not claimed to work here.
This repository is the new, independent Marqdo toolchain, now at product
version **`3.0.0-beta.1`**. It is **not** a compatibility rewrite of
`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
third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta
release policy.
> **Status: stabilization candidate, not released.** The language, lock v3,
> Analysis v2, Trace v2, Tool v1, Plugin ABI v1 (native + worker) and pinned
> Foreign providers are implemented and covered by tests on Linux. The
> macOS/Windows `E0433` platform-cfg failure and the Linux strict
> probe→launch race are fixed in source at `8af7262`, but the native
> Windows/macOS and GitHub Linux lanes have not been re-run from this
> checkout. **`strict` OS isolation is available on Linux only when the
> runtime Bubblewrap probe passes**; it was verified against the full
> escape/resource matrix in a disposable Ubuntu 26.04 VM at `8af7262`
> (ADR-0021). macOS/Windows fail closed, strict L2 (Worker/Foreign) is not
> implemented, and the broker/worker are not a sandbox. The release decision
> is **DO NOT RELEASE** until the remote gates have same-SHA URLs. See
> [`docs/STATUS.md`](docs/STATUS.md), [`COMPATIBILITY.md`](COMPATIBILITY.md)
> and [`docs/security-gate.md`](docs/security-gate.md). The single current CI
> convergence plan is
> [`docs/NEXT_RELEASE_CI_CONVERGENCE.md`](docs/NEXT_RELEASE_CI_CONVERGENCE.md).
> **Breaking language revision landed.** The single semantic contract is
> [RFC-LANG-0002](docs/architecture/RFC-LANG-0002-unified-semantics.md), with
> normative summaries in [`spec/mapping.md`](spec/mapping.md) and
> [`spec/expression.ebnf`](spec/expression.ebnf). The frontend, expression
> parser, stdlib, examples and test corpus all implement it; the language
> migration is closed and old syntax (`**strong**` = execute, `*emph*` =
> return, `1.` = branch, `-` = loop, `>` = call) is **not** an active language.
> `marqdo_semantics`/`--legacy` selectors do not exist. See
> [`docs/STATUS.md`](docs/STATUS.md) and
> [`docs/migration/README.md`](docs/migration/README.md).
> **Status: `3.0.0-beta.1` prerelease.** 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
> (RFC-LANG-0002), lock v4, Analysis v2, Trace v2, Tool v1, Plugin ABI v1
> (native + worker), pinned Foreign providers and Resource Provider v2 are
> implemented and covered by tests. **`strict` OS isolation is Linux-only and
> probe-gated**; unsupported hosts must fail closed, and strict L2
> (Worker/Foreign/Provider) is not implemented. The broker and worker
> transports are not sandboxes. The beta release decision, support matrix and
> remaining gaps are recorded in [`docs/STATUS.md`](docs/STATUS.md),
> [`COMPATIBILITY.md`](COMPATIBILITY.md),
> [`docs/developers/release-limits.md`](docs/developers/release-limits.md) and
> [`docs/releasing.md`](docs/releasing.md). The authoritative release policy is
> [`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md).
CI: the source of truth is the Gitea remote
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
runs fmt, clippy, workspace tests with `--locked`, the Windows cross-target
compile gate and a release build of both binaries. The strict OS-isolation lane
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
mirror is not used as the authoritative lane for this beta.
## Build
@@ -44,7 +65,7 @@ cargo build -p marqdo-cli
marqdo init demo
cd demo
marqdo check index.mq.md
marqdo run index.mq.md # executes ## main
marqdo run index.mq.md # executes ## @exec main
marqdo inspect index.mq.md --ast
marqdo inspect index.mq.md --signature
marqdo call index.mq.md main
@@ -53,19 +74,22 @@ marqdo call index.mq.md main
Example project from scratch (`index.mq.md`):
````markdown
# 数学
# @knowledge 数学
## 阶乘
## @exec 阶乘
1. `n <= 1`
`params(n: Int)`
*1*
`if n <= 1`
2. `n > 1`
`return 1`
**结果 = n * 阶乘(n=n-1)**
`else`
*结果*
`结果 = n * 阶乘(n=n-1)`
`return 结果`
`end`
````
```bash
@@ -76,22 +100,114 @@ marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5 # 120
The parser is frozen: `marqdo.md.v1` = CommonMark 0.31.2 + GFM tables,
strikethrough, task lists + `$...$`/`$$...$$` math (comrak `=1.0.0`). A `.mq.md`
file still renders normally in any compatible Markdown reader; rendering never
executes anything.
executes anything. The Markdown profile is unchanged by the semantic rewrite.
## Language in 60 seconds
* **Headings declare the mode.** `# @knowledge 笔记` is a document namespace;
`## @exec main` overrides to an executable function. Any H1–H6 may carry
`@exec`/`@knowledge`; unmarked headings inherit the nearest ancestor. The
document root is Knowledge. An Exec H2 is the only callable function; H3–H6
are sections inside it.
* **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`,
`*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans
for expressions containing `*` or `**`.
* **Statements are explicit.** `if <Bool>`, `else`, `while <Bool>`, `end`,
`return <expr>`, `params(n: Int)`, assignment, or an expression call. Each
carrier holds exactly one statement; every `if`/`while` is closed by `end`
inside the same heading body.
* **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the
document. `> print(1)` is prose; `> **print(1)**` contains a call.
* **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is
the place for normal emphasis, explanatory lists, tables and formula
resources.
* **No syntax switch.** There is no `marqdo_semantics` field or `--legacy`
flag; all `.mq.md` files use this syntax.
The full contract is [`spec/mapping.md`](spec/mapping.md) and
[`spec/expression.ebnf`](spec/expression.ebnf); the rationale and migration
rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md).
## What works (implemented and tested)
* **P0 contracts** — frozen Markdown profile, AST → program mapping, strict
expression grammar, evaluation semantics; 160 AST goldens, 44 semantic
goldens, 52 compile-error fixtures and 12 runtime-error fixtures
(`tests/`).
* **P0 contracts** — frozen `marqdo.md.v1` profile, RFC-LANG-0002 AST → program
mapping, the v2 statement grammar and evaluation semantics; 160 AST goldens,
73 semantic fixtures, 49 compile-error fixtures, 2 warning fixtures and 21
runtime-error fixtures, all green (`tests/`).
* **P1 interpreter** — native Rust tree-walk interpreter: values, scopes,
functions, static parameter inference, assignments, branches, loops,
returns, recursion, structured errors, fuel/stack/output budgets.
* **Addressable memory (RFC-CM P1)** — opaque run-scoped `Memory` regions with
64 KiB zero-filled pages, grow-only `memory.new/size/grow`, bounded byte
read/write, `m[i] = byte`, run/per-region budgets, host-boundary and wire
rejection (ADR-0022).
* **Minimal structure primitives (RFC-CM CM-A04)** — value-semantics
`list.append/concat`, `map.keys/has/get/set/remove`, Unicode scalar
`text.codepoints/from_codepoint`, and non-negative `table.columns/row/cell`;
pure builtins with no mutation or new syntax (ADR-0023).
* **Recoverable results (RFC-CM CM-A05)** — `{ok:true,value}` /
`{ok:false,code,message}` as an ordinary Map, with a `.mq.md` first-fit
free-list allocator demonstrating reuse, splitting and `alloc.no_space`
recovery (ADR-0024). No `Result` type or exception syntax.
* **Bundled stdlib + official print aliases (RFC-CM CM-A07/A10)** — offline
`stdlib/` with explicit `std:io`/`std:format`/`std:text` imports, SHA-256
digest verification, Analysis identity and a frozen-CLI closure test; the
`.mq.md` print chain is the only execution path for `打印`/`print` on an official install (ADR-0031),
covering all 15 value types; `HostOp::Print` and the legacy formatter are
removed (ADR-0027/0028/0029/0030/0031).
* **HTTP/1.1 framing in `.mq.md`** — `stdlib/net/http.mq.md` status/header/
chunked parsing and request construction; a loopback TCP test runs a real
exchange (ADR-0034; no TLS/host HTTP claim).
* **Blocking TCP endpoint (RFC-CM P5 first slice)** — `resource.open("tcp",
"<ip>:<port>", ["read","write"])` with exact IP grants, project mode and
5-second timeouts; DNS/TLS/UDP/server sockets excluded (ADR-0034).
* **C ABI provider worker (RFC-CM CM-A09)** — `marqdo-provider-worker` loads a
trusted C ABI library in a separate framed-JSON helper process (ADR-0038).
* **Provider package manifest v1 (RFC-CM CM-A09)** — local `marqdo.provider`
manifest installs a trusted C ABI provider; no registry/signature/CLI install
(ADR-0037).
* **Third-party Resource Provider v2 through the normal CLI (RFC-EXT-0001
PR-03)** — a `provider.json` v2 bundle with a targeted, sha256-verified
`c-abi-1` artifact is selected with repeatable `--provider` and authorized by
the exact `--allow-provider` name on `run`/`call`; the existing
`marqdo-provider-worker` transport is spawned only after every manifest,
artifact, grant and duplicate-kind check passes. `check`/`inspect` never load
providers, `pure`/`strict` refuse them, and the worker transport is
linux/x86_64-only in this release (ADR-0055,
[`spec/resource-provider-v2.md`](spec/resource-provider-v2.md)).
* **Single callable binding through the frozen composition root
(RFC-EXT-0001 PR-01/02)** — one `CallableRegistry` and one binding pass feed
`check`/`run`/`call`/`inspect`/Analysis; the runtime dispatches by
`CallSiteKey` and never re-resolves a name or guesses a plugin. Static plugin
descriptors must reconcile one-to-one with the loaded exports (ADR-0054,
[`spec/callable-resolution.md`](spec/callable-resolution.md)).
* **Official stdlib public aliases (RFC-EXT-0001 PR-06)** — `打印`/`print` are
verified `stdlib.json` metadata bound to `io.mq.md::写值`; the
`print_override`/AST-scan/runtime special case is removed with byte-identical
output (ADR-0058).
* **C ABI ResourceProvider v1 (RFC-CM CM-A09)** — trusted native shared
libraries expose resource open/read/write/close through a frozen header;
project + name grant; the worker transport binding is implemented (ADR-0036/ADR-0038).
* **Worker ResourceProvider transport v1 (RFC-CM CM-A09)** — trusted helper
process with framed JSON resource operations; project + name grant; the C ABI
library is loaded by the helper (ADR-0035/ADR-0038).
* **In-process ResourceProvider v1 (RFC-CM CM-A09 first slice)** — trusted
providers register extra resource kinds, project-mode + name-grant gated,
using the existing `resource.*`/`Result` ABI; no parser/runtime/`HostOp`
change (ADR-0033).
* **Table stdlib algorithms (RFC-CM CM-A08)** — `stdlib/data/table.mq.md`
select/filter/sort/append/set/join/group over the logical `Table` value;
value-returning, input-immutable, with GFM AST laziness unchanged (ADR-0032).
* **Resource streams (RFC-CM CM-A06)** — opaque host-issued `Resource` handles;
`resource.open/read/write/close` transfer bytes through `Memory`; stdout
write in pure/project, granted project-file read, and buffered project-file
write flushed on `close` in project; strict refuses all resource opens until
verified (ADR-0025/0026).
* **P2 references + CLI** — explicit YAML front-matter imports, `ModuleId`/
`UnitId`/anchors, import cycle detection, multi-module calls,
`run/call/check/inspect/fmt`, reference validation (`check --refs`) and the
static link graph (`inspect --refs`).
* **P3 project** — lock v3 full transitive package-instance graph for path and
* **P3 project** — lock v4 full transitive package-instance graph for path and
pinned Git sources, verified content-addressed Git cache, deterministic
`lock`, strict `sync --locked` with atomic `.marqdo/env` materialization.
`run`/`call`/`check` never fetch or rewrite the lock.
@@ -118,9 +234,9 @@ executes anything.
Run everything:
```bash
cargo test --workspace
cargo test --workspace --locked
cargo test -p marqdo-cli # conformance corpus + CLI contract tests
cargo fmt --check
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
```
@@ -140,8 +256,9 @@ cargo clippy --workspace --all-targets -- -D warnings
`capabilities` are requests, never grants.
* **Reference validation is opt-in**: `check --refs` reports broken links;
plain `check` ignores them because links are static knowledge references.
Link-form calls cannot cross modules; cross-module calls use imported alias
expressions such as `geometry.圆面积(r=2)`.
Markdown links never call; calls are expressions inside executable payloads,
and cross-module calls use imported alias expressions such as
`geometry.圆面积(r=2)`.
* **`ref("#anchor")` is module-local** and errors with `ref.ambiguous` when a
heading range contains more than one formula/code block instead of picking
the first.
@@ -183,26 +300,43 @@ tests/ conformance/negative corpus (see tests/README.md)
## Documentation index
* [`AGENTS.md`](AGENTS.md) — operating rules for contributors and coding agents.
* [`docs/architecture/RFC-LANG-0002-unified-semantics.md`](docs/architecture/RFC-LANG-0002-unified-semantics.md)
— **the single language authority**: full new syntax, breaking changes,
architecture, migration and acceptance gates. Adopted by
[ADR-0052](docs/adr/0052-unified-markdown-semantics.md).
* [`spec/mapping.md`](spec/mapping.md) — normative AST→program mapping
(heading modes, unified carriers, control stack, diagnostics).
* [`spec/expression.ebnf`](spec/expression.ebnf) — normative statement and
expression grammar.
* [`docs/migration/README.md`](docs/migration/README.md) — migration rules and
the inventory of remaining work.
* [`docs/DEVELOPMENT_BLUEPRINT.md`](docs/DEVELOPMENT_BLUEPRINT.md) — architecture
baseline (Chinese; the M0.6 plan below supersedes it on command-surface scope,
extension registration, plugin addressing, package identity, repository
decoupling and release gates).
baseline (Chinese); historical sections are marked and the current language
contract is RFC-LANG-0002, not the blueprint's old mapping.
* [`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md)
— **the authoritative release policy for this line**: beta gates, version
axes, support matrix, REL work items and LTS conditions. It is a plan, not
evidence.
* [`docs/developers/README.md`](docs/developers/README.md) — third-party and
integrator entry point (libraries, tools, plugins, kernels, providers,
Analysis/Trace consumers, compatibility).
* [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md)
— end-to-end third-party integration handbook.
* [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md)
— **the single authoritative next-phase plan**: PR order, G-A/G-B/G-C gates,
Windows/macOS fixes, protocol/environment stabilization, strict isolation
requirements and the release checklist.
— historical stable-release roadmap input (its own header marks it Proposed
and superseded by the 3.0 prerelease plan for current decisions).
* [`COMPATIBILITY.md`](COMPATIBILITY.md) — protocol versions, per-platform
feature evidence and explicit unsupported features.
* [`CHANGELOG.md`](CHANGELOG.md) — unreleased stabilization changes and the
`0.1.0` baseline.
feature evidence, the breaking language change and unsupported features.
* [`CHANGELOG.md`](CHANGELOG.md) — `3.0.0-beta.1` release notes plus the
historical `0.1.0` baseline, including the syntax breaking change.
* [`docs/security-gate.md`](docs/security-gate.md) — G-C evidence and limits;
[`docs/security-vm.md`](docs/security-vm.md) reproduces the disposable VM and
the self-hosted security runner.
* [`docs/releasing.md`](docs/releasing.md) — artifact, checksum, clean-install
smoke, tagging and rollback procedure.
* [`docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`](docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md)
— historical stabilization spec (baseline `0adebe4`), superseded on current
priorities by the stable-release plan.
— historical stabilization spec (baseline `0adebe4`), superseded by the
3.0 prerelease plan for current release decisions.
* [`docs/NEXT_PHASE_IMPLEMENTATION.md`](docs/NEXT_PHASE_IMPLEMENTATION.md) —
historical M0.6 plan.
* [`docs/EXTENSIBILITY_AUDIT.md`](docs/EXTENSIBILITY_AUDIT.md) — source-backed
@@ -229,6 +363,7 @@ tests/ conformance/negative corpus (see tests/README.md)
## Examples
```bash
marqdo run examples/hello.mq.md
marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5
@@ -254,6 +389,143 @@ marqdo benchmark run .
marqdo tool remove benchmark
```
### Extending Marqdo without modifying or rebuilding the CLI
RFC-EXT-0001 defines five extension kinds. Each one is discovered only through
an explicit manifest/flag, is versioned, and is authorized separately from
being visible. A physically separate repository exercising all five against a
frozen binary is `marqdo-extension-conformance`
(`https://git.cflmy.cn/cflmy/marqdo-extension-conformance`).
| Kind | Static discovery | Execution | Grant |
|---|---|---|---|
| `.mq.md` package | `marqdo.yaml` dependency + `marqdo.lock` | Marqdo interpreter | project mode |
| Callable plugin | `plugin.yaml` ABI v1 exports | worker (default) or trusted native | `--plugin` + `--allow-plugin NAME` |
| Foreign kernel | `kernel.json` + pinned executable digest | one-shot child process | `--kernel` + `--allow-foreign` |
| Resource provider | `provider.json` schema v2 | `marqdo-provider-worker` + C ABI | `--provider` + `--allow-provider NAME` |
| CLI Tool | `tool.json` install record | independent CLI process | tool installation, no project grants |
```bash
# 1. Pure Markdown library from a pinned Git dependency
marqdo lock && marqdo sync
marqdo check consumer/index.mq.md
marqdo run consumer/index.mq.md
# 2. Callable ABI plugin (worker transport by default)
marqdo run plugin/demo.mq.md \
--plugin plugin/build --allow-plugin demo.ext
# 3. Foreign kernel with a language label the CLI has never heard of
marqdo run kernel/demo.mq.md \
--kernel kernel/build/kernel.json --allow-foreign
# 4. Resource provider v2 (examples/provider-demo/build.sh first; see below)
marqdo run provider/demo.mq.md \
--provider provider/build/provider.json --allow-provider demo.sensor
# 5. Independent CLI Tool consuming only public Analysis v2
marqdo tool install tool/tool.json
marqdo inspect-ext tool/demo.mq.md
```
#### One callable resolution, visible in `check` and `run`
Calls are bound statically once per prepared program (ADR-0054, normative
details in [`spec/callable-resolution.md`](spec/callable-resolution.md)):
* `f(...)`: local callable value → official alias/reserved builtin → current
namespace → canonical name → unique local name;
* `alias.f(...)`: explicit import alias → builtin dotted name → exact plugin
export;
* `some_value.f(...)`: dynamic language value only.
`check` and `run` consume the same binding; an unknown export, wrong arguments
or a duplicate export fails before execution. An import alias that collides
with a builtin/plugin dotted namespace (for example importing a module as
`math`) is rejected with `ext.import_namespace_conflict`; rename it. A plugin
manifest is the static contract: `run` verifies the loaded artifact and its
exports/signatures match the manifest exactly
(`ext.plugin_binding_mismatch` otherwise) and never synthesises a signature.
#### Declaring extensions in the project (lock v4)
A project can declare explicit activation sources and lock their identity; a
declaration is visibility/activation, never a grant:
```yaml
extensions:
plugins:
- from: ./adapter/plugin.yaml
kernels: []
providers:
- from: "@vendor/device/provider.json"
```
```bash
marqdo lock # writes lock_version: 4 with manifest/artifact identities
marqdo inspect index.mq.md --extensions --json # identity + lock status, no execution
```
Only `./relative/path` (project) and `@alias/relative/path` (declared
dependency) are accepted; absolute paths, URLs, globs and `..` are rejected.
`check`/`sync` compare the declaration with the lock
(`ext.extension_lock_mismatch`), `run` additionally re-verifies the real
artifact bytes, and `pure`/`strict` refuse project-declared third-party
extensions. Lock v3 requires an explicit `marqdo lock` migration. See
[`spec/extension-selection.md`](spec/extension-selection.md) and
[`docs/adr/0056-extension-selection-locking.md`](docs/adr/0056-extension-selection-locking.md).
#### Official stdlib aliases, no print magic
`打印`/`print` are declared in the verified `stdlib/stdlib.json`
(`public_aliases`, covered by `aliases_digest`) and bound as ordinary
`Marqdo` calls to `io.mq.md::写值` (ADR-0058). There is no
`Program.print_override`, no AST-wide print scan and no runtime print branch;
output bytes, permissions and Trace behavior are unchanged, and a program that
never uses the alias does not load the stdlib module graph. Third-party
packages cannot claim `打印`/`print` or `std.*` names.
### Third-party resource providers (`provider.json` v2)
An external repository adds a new resource kind (for example `demo.sensor`)
with a `provider.json` schema-version-2 bundle and a targeted `c-abi-1` shared
library. No CLI rebuild and no core change are needed: select the manifest with
repeatable `--provider` and authorize it by its exact manifest `name` with
`--allow-provider` (also repeatable). A `--provider` without a matching
`--allow-provider` is `permission.denied` and the helper is never started;
wildcards (`*`) are not accepted.
```bash
marqdo run index.mq.md \
--provider vendor/demo-sensor/provider.json \
--allow-provider demo.sensor
marqdo call index.mq.md main \
--provider vendor/demo-sensor/provider.json \
--allow-provider demo.sensor
```
The document still uses the ordinary resource surface, e.g.
`resource.open("demo.sensor", "unit-1", ["read"])`; provider kinds do not become
new callables.
* `check`/`inspect` do not accept these options and never load a provider.
* `--mode pure` and `--mode strict` reject `--provider`/`--allow-provider` in
preflight; strict L1 stays fail-closed and does not silently switch to
`project`.
* Everything is verified before any worker starts: `schema_version: 2`,
`abi: c-abi-1`, `transport: worker`, strict SemVer, non-reserved kinds, the
current target artifact's bundle containment and sha256, exact grants and
duplicate provider names/kinds.
* The helper `marqdo-provider-worker` must ship next to the `marqdo` executable
for the same target (no `PATH` fallback); a missing helper is
`ext.worker_unavailable`. The worker transport is linux/x86_64-only in this
release; other platforms fail with `ext.platform_unsupported`.
* The helper is a trusted process, not an OS sandbox: it runs with the user's
privileges. `sha256` is an integrity check, not publisher authentication.
See [`spec/resource-provider-v2.md`](spec/resource-provider-v2.md) and
[ADR-0055](docs/adr/0055-resource-provider-cli-v2.md).
## References
* [CommonMark 0.31.2](https://spec.commonmark.org/0.31.2/) ·
+3
View File
@@ -33,3 +33,6 @@ semver = { workspace = true }
[[bin]]
name = "marqdo"
path = "src/main.rs"
[dev-dependencies]
tempfile = { workspace = true }
+57 -61
View File
@@ -8,7 +8,7 @@
use std::path::Path;
use marqdo_expression::{BinaryOp, Expr, UnaryOp};
use marqdo_ir::{CallTarget, Function, Module, ModuleId, Resource, SignatureKind, Stmt, UnitKind};
use marqdo_ir::{Function, Module, ModuleId, PlaceTarget, Resource, SignatureKind, Stmt, UnitKind};
use marqdo_span::Span;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
@@ -59,6 +59,11 @@ pub fn build(project: &LoadedProject) -> Value {
"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),
@@ -192,6 +197,7 @@ fn units_json(module: &Module) -> Vec<Value> {
UnitKind::Root => "root",
UnitKind::Namespace => "namespace",
UnitKind::Function => "function",
UnitKind::Knowledge => "knowledge",
UnitKind::Section => "section",
};
json!({
@@ -232,13 +238,31 @@ fn function_json(function: &Function) -> Value {
})
}
/// 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 {
name, value, span, ..
target,
value,
span,
..
} => json!({
"kind": "assign",
"target": name,
"target": place_json(target),
"value": expr_json(value),
"span": span_json(*span),
}),
@@ -247,12 +271,6 @@ fn stmt_json(stmt: &Stmt) -> Value {
"value": expr_json(expr),
"span": span_json(*span),
}),
Stmt::Call { call, span } => json!({
"kind": "call_site",
"target": call_target_json(&call.target),
"args": call.args.iter().map(arg_json).collect::<Vec<_>>(),
"span": span_json(*span),
}),
Stmt::Branch { arms, span } => json!({
"kind": "branch",
"arms": arms.iter().map(|arm| json!({
@@ -352,19 +370,6 @@ fn arg_json(arg: &marqdo_expression::Arg) -> Value {
})
}
fn call_target_json(target: &CallTarget) -> Value {
match target {
CallTarget::Function { name } => json!({"kind":"function","name":name}),
CallTarget::Qualified {
module_alias,
function,
} => json!({"kind":"qualified","module_alias":module_alias,"function":function}),
CallTarget::Resolved { module, function } => {
json!({"kind":"resolved","module":module.to_string(),"function":function})
}
}
}
fn reference_edges(project: &LoadedProject, module_id: &marqdo_ir::ModuleId) -> Vec<Value> {
let Some(file) = project.files.get(module_id) else {
return Vec::new();
@@ -497,16 +502,15 @@ fn collect_calls(
) {
for stmt in body {
match stmt {
Stmt::Assign { value, .. } | Stmt::Eval { expr: value, .. } => {
expr_calls(project, module, function, value, calls)
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::Call { call, span } => calls.push(json!({
"function": function.id.to_string(),
"span": span_json(*span),
"callee": call_target_json(&call.target),
"state": "resolved",
})),
Stmt::Branch { arms, .. } => {
for arm in arms {
expr_calls(project, module, function, &arm.condition, calls);
@@ -532,7 +536,7 @@ fn expr_calls(
) {
match expr {
Expr::Call { callee, args, span } => {
let (state, target) = resolve_callee(project, module, callee);
let (state, target) = resolve_callee(project, module, function, *span);
calls.push(json!({
"function": function.id.to_string(),
"span": span_json(*span),
@@ -568,42 +572,34 @@ fn expr_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,
callee: &Expr,
_module: &Module,
function: &Function,
span: Span,
) -> (&'static str, Value) {
match callee {
Expr::Ident(ident) => {
if marqdo_ir::builtins::find(&ident.name).is_some() {
("builtin", json!(ident.name))
} else if let Some(function) = module.function(&ident.name) {
("function", json!(function.id.to_string()))
} else {
("unresolved", Value::Null)
}
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))
}
Expr::Member { base, name, .. } => {
if let Expr::Ident(alias) = base.as_ref() {
let qualified = format!("{}.{}", alias.name, name);
if marqdo_ir::builtins::find(&qualified).is_some() {
return ("builtin", json!(qualified));
}
if let Some(target_module) = project.program.resolve_import(&module.id, &alias.name)
{
if let Some(target) = project.program.module(target_module) {
if let Some(function) = target.function(name) {
return ("function", json!(function.id.to_string()));
}
}
}
if project.program.external_callable(&qualified).is_some() {
return ("plugin", json!(qualified));
}
}
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)
}
_ => ("unresolved", Value::Null),
}
}
+279 -1131
View File
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
//! `marqdo check` command.
use super::*;
pub fn check(
file: Option<&Path>,
json: bool,
refs: bool,
plugins: &[PathBuf],
emit: Option<&Path>,
) -> i32 {
let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
};
let mut project = prepared.loaded;
if refs {
let ref_diagnostics = validate_refs(&project);
project.diagnostics.extend(ref_diagnostics);
}
let errors = output::error_count(&project.diagnostics);
if let Some(path) = emit {
if errors > 0 {
let _ = std::fs::remove_file(path);
} else if let Err(error) = crate::analysis::write(&project, path) {
eprintln!("error: {error}");
return 2;
}
}
if json {
output::print_json(&json!({
"command": "check",
"success": errors == 0,
"errors": errors,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
let text = output::render_text(&project.diagnostics);
eprint!("{text}");
if errors == 0 {
let checked = project
.program
.modules
.keys()
.filter(|id| !id.instance.starts_with("std:"))
.count();
println!("checked {checked} module(s): ok");
} else {
eprintln!(
"check failed: {} error(s), {} warning(s)",
errors,
project.diagnostics.len() - errors
);
}
}
if errors == 0 {
0
} else {
1
}
}
+49
View File
@@ -0,0 +1,49 @@
//! `marqdo init` command.
use super::*;
/// `marqdo init`.
pub fn init(dir: Option<&Path>) -> i32 {
let dir = dir.unwrap_or_else(|| Path::new("."));
if dir.join(marqdo_package::MANIFEST_FILE).exists() {
eprintln!(
"error: `{}` already contains {}",
dir.display(),
marqdo_package::MANIFEST_FILE
);
return 1;
}
if let Err(error) = std::fs::create_dir_all(dir) {
eprintln!("error: cannot create {}: {error}", dir.display());
return 1;
}
// Create the directory before canonicalizing: `init new-project` must name
// the project `new-project`, not silently fall back to `example` because
// the path did not exist yet.
let name = dir
.canonicalize()
.ok()
.and_then(|path| {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
})
.unwrap_or_else(|| "example".to_string());
let manifest = marqdo_package::Manifest::template(&name);
if let Err(error) = std::fs::write(dir.join(marqdo_package::MANIFEST_FILE), manifest.to_yaml())
{
eprintln!("error: cannot write manifest: {error}");
return 1;
}
let entry = dir.join("index.mq.md");
if let Err(error) = std::fs::write(&entry, INIT_TEMPLATE) {
eprintln!("error: cannot write {}: {error}", entry.display());
return 1;
}
let _ = std::fs::write(dir.join(".gitignore"), ".marqdo/\n");
println!("Initialized Marqdo project `{name}` in {}", dir.display());
println!("Next: marqdo check index.mq.md && marqdo run index.mq.md");
0
}
const INIT_TEMPLATE: &str =
"## @exec main\n\n`问候 = \"你好,Marqdo\"`\n\n`打印(问候)`\n\n`return 问候`\n";
+240
View File
@@ -0,0 +1,240 @@
//! `marqdo inspect` command.
use super::*;
/// Options for `marqdo inspect`.
#[derive(Debug, Clone, Default)]
pub struct InspectFlags {
/// Show the Markdown AST.
pub ast: bool,
/// Show heading units.
pub units: bool,
/// Show inferred/explicit signatures.
pub signature: bool,
/// Show executable IR.
pub ir: bool,
/// Show link reference edges.
pub refs: bool,
/// Show platform capability report.
pub platform: bool,
/// Show declared/loaded extension identities (never grants).
pub extensions: bool,
}
pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &[PathBuf]) -> i32 {
let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
};
let project = &prepared.loaded;
let entry = project.entry_file();
let module = &entry.analysis.module;
let selected_any = flags.ast
|| flags.units
|| flags.signature
|| flags.ir
|| flags.refs
|| flags.platform
|| flags.extensions;
if json {
let mut object = serde_json::Map::new();
object.insert("command".into(), json!("inspect"));
object.insert("module".into(), json!(entry.module_id.to_string()));
if !selected_any {
object.insert("summary".into(), summary_json(project));
}
if flags.ast {
object.insert(
"ast".into(),
serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(),
);
}
if flags.units {
object.insert(
"units".into(),
serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(),
);
}
if flags.signature {
object.insert("signatures".into(), signatures_json(module));
}
if flags.ir {
object.insert(
"ir".into(),
serde_json::to_value(&module.functions).unwrap_or_default(),
);
}
if flags.refs {
object.insert("refs".into(), json!(refs_json(project)));
}
if flags.platform {
object.insert(
"platform".into(),
serde_json::to_value(PlatformCapabilities::detect()).unwrap_or_default(),
);
}
if flags.extensions {
object.insert("extensions".into(), extensions_json(&prepared, project));
}
output::print_json(&serde_json::Value::Object(object));
return 0;
}
if !selected_any {
println!("module: {}", entry.module_id);
println!("path: {}", entry.path.display());
println!("project root: {}", project.root.display());
println!("functions:");
for function in &module.functions {
let params = function
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>()
.join(", ");
let kind = match function.signature {
marqdo_ir::SignatureKind::Explicit => "explicit",
marqdo_ir::SignatureKind::Inferred => "inferred",
};
println!(" {} ({params}) [{kind}]", function.id.name);
}
println!(
"resources: {} formula/code block(s)",
module.resources.len()
);
return 0;
}
if flags.ast {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default()
);
}
if flags.units {
println!(
"{}",
serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default()
);
}
if flags.signature {
println!(
"{}",
serde_json::to_string_pretty(&signatures_json(module)).unwrap_or_default()
);
}
if flags.ir {
println!(
"{}",
serde_json::to_string_pretty(&module.functions).unwrap_or_default()
);
}
if flags.refs {
println!(
"{}",
serde_json::to_string_pretty(&refs_json(project)).unwrap_or_default()
);
}
if flags.platform {
println!(
"{}",
serde_json::to_string_pretty(&PlatformCapabilities::detect()).unwrap_or_default()
);
}
if flags.extensions {
let value = extensions_json(&prepared, project);
println!(
"{}",
serde_json::to_string_pretty(&value).unwrap_or_default()
);
}
0
}
/// Static extension identity projection for `inspect --extensions`.
///
/// Reports declared sources, lock identity, static plugin descriptors and
/// official stdlib aliases. It deliberately never shows environment variables,
/// secrets, binary contents or an authorization result beyond
/// `not_granted` (inspection does not grant anything).
fn extensions_json(
prepared: &crate::project_prepare::PreparedProgram,
project: &crate::loader::LoadedProject,
) -> serde_json::Value {
let root = project.root.as_path();
let relative = |path: &Path| {
path.strip_prefix(root)
.map(|value| value.to_string_lossy().to_string())
.unwrap_or_else(|_| path.to_string_lossy().to_string())
};
let declared: Vec<serde_json::Value> = project
.extension_sources
.iter()
.map(|extension| {
let identity = prepared.extension_identities.iter().find(|identity| {
identity.kind == extension.kind
&& identity.source == extension.from
&& identity.logical_owner == extension.logical_owner
});
let locked = project.lock.as_ref().is_some_and(|lock| {
identity.is_some_and(|identity| {
lock.extension(identity.kind, &identity.name, &identity.logical_owner)
.is_some()
})
});
json!({
"kind": extension.kind.as_str(),
"source": extension.from,
"path": relative(&extension.path),
"logical_owner": extension.logical_owner,
"name": identity.map(|identity| identity.name.clone()),
"version": identity.map(|identity| identity.version.clone()),
"manifest_digest": identity.map(|identity| identity.manifest_digest.clone()),
"artifact_digest": identity.map(|identity| identity.artifact_digest.clone()),
"selected_target": identity.map(|identity| identity.selected_target.clone()),
"status": if locked { "locked" } else { "unlocked" },
"authorization": "not_granted",
})
})
.collect();
let plugins: Vec<serde_json::Value> = prepared
.plugins
.plugins
.iter()
.map(|plugin| {
json!({
"package": plugin.package,
"version": plugin.version,
"kind": plugin.kind.as_str(),
"manifest_path": relative(&plugin.manifest_path),
"manifest_digest": plugin.manifest_sha256,
"selected_target": plugin.artifact_target,
"artifact_digest": plugin.artifact_sha256,
"artifact_path": relative(&plugin.artifact_path()),
"exports": plugin.exports.iter().map(|export| json!({
"name": export.name,
"signature": export.signature,
})).collect::<Vec<_>>(),
"validation": "static_manifest_ok",
"authorization": "not_granted",
})
})
.collect();
let aliases: Vec<serde_json::Value> = project
.official_aliases
.iter()
.map(|alias| {
json!({
"public_names": alias.public_names,
"target": alias.function.to_string(),
"owner_package": alias.owner_package,
"source": "verified stdlib bundle",
"authorization": "official_bundle",
})
})
.collect();
json!({
"declared": declared,
"plugins": plugins,
"stdlib_aliases": aliases,
"note": "inspect never loads or executes an extension and never grants a permission",
})
}
+299
View File
@@ -0,0 +1,299 @@
//! Package lock/sync/add/remove commands.
use super::*;
use crate::extension_selection;
/// `marqdo lock`.
pub fn lock(json: bool) -> i32 {
let root = match discover_project_root() {
Ok(root) => root,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
Ok(manifest) => manifest,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let resolver = marqdo_package::PackageResolver::new(root.clone(), Some(manifest.clone()), None)
.with_fetch(true)
.with_unlocked(true);
let graph = match resolver.resolve_lock_graph() {
Ok(graph) => graph,
Err(error) => {
eprintln!("error: {error}");
return 1;
}
};
let mut lockfile = graph.lock;
// Lock v4: record the exact extension identity declared by the project.
// Reading manifests/declared digests is static; no binary is loaded and no
// grant is implied.
let extension_sources = match resolver.resolve_extension_sources() {
Ok(sources) => sources,
Err(error) => {
eprintln!("error: extension selection: {error}");
return 1;
}
};
let identities = match extension_selection::extension_identities(&extension_sources) {
Ok(identities) => identities,
Err(error) => {
eprintln!("error[{}]: {}", error.code, error.message);
return error.exit_code;
}
};
for identity in identities {
if let Err(error) = lockfile.merge_extension(identity) {
eprintln!("error[ext.extension_lock_mismatch]: {error}");
return 1;
}
}
let path = root.join(marqdo_package::LOCK_FILE);
if let Err(error) = write_atomic(&path, lockfile.to_yaml().as_bytes()) {
eprintln!("error: cannot write {}: {error}", path.display());
return 1;
}
if json {
output::print_json(&json!({
"command": "lock",
"success": true,
"packages": lockfile.packages,
"extensions": lockfile.extensions,
}));
} else {
println!(
"locked {} package(s) in {}",
lockfile.packages.len(),
path.display()
);
}
0
}
/// `marqdo sync [--locked]`.
pub fn sync(locked: bool, json: bool) -> i32 {
let root = match discover_project_root() {
Ok(root) => root,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let manifest = match marqdo_package::Manifest::load(&root.join(marqdo_package::MANIFEST_FILE)) {
Ok(manifest) => manifest,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let lock_path = root.join(marqdo_package::LOCK_FILE);
if !lock_path.is_file() {
eprintln!(
"error: {} is missing; run `marqdo lock` first",
lock_path.display()
);
return 1;
}
let lockfile = match marqdo_package::LockFile::load(&lock_path) {
Ok(lockfile) => lockfile,
Err(error) => {
eprintln!("error: {error}");
return 1;
}
};
if let Err(error) = lockfile.validate_root(&manifest) {
eprintln!("error: {error}");
return 1;
}
let resolver =
marqdo_package::PackageResolver::new(root, Some(manifest.clone()), Some(lockfile.clone()))
.with_fetch(!locked);
// Verify the declared extension selection against the lock before using
// any materialized content. A missing/changed identity fails closed.
let extension_sources = match resolver.resolve_extension_sources() {
Ok(sources) => sources,
Err(error) => {
eprintln!("error: extension selection: {error}");
return 1;
}
};
let identities = match extension_selection::extension_identities(&extension_sources) {
Ok(identities) => identities,
Err(error) => {
eprintln!("error[{}]: {}", error.code, error.message);
return error.exit_code;
}
};
if let Err(error) = lockfile.validate_extension_declarations(&manifest) {
eprintln!("error[ext.extension_lock_mismatch]: {error}");
return 1;
}
if let Err(error) = extension_selection::validate_against_lock(&lockfile, &identities) {
eprintln!("error[{}]: {}", error.code, error.message);
return error.exit_code;
}
if let Err(error) = resolver.materialize_env(&lockfile) {
eprintln!("error: cannot materialize project environment: {error}");
return 1;
}
if json {
output::print_json(&json!({
"command": "sync",
"success": true,
"locked": locked,
"packages": lockfile.packages,
}));
} else {
println!(
"synchronized {} package(s){} into {}",
lockfile.packages.len(),
if locked { " (locked)" } else { "" },
resolver.env_root().display()
);
}
0
}
fn discover_project_root() -> Result<PathBuf, String> {
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
marqdo_package::discover_root(&cwd).ok_or_else(|| {
format!(
"no {} found in {} or any parent",
marqdo_package::MANIFEST_FILE,
cwd.display()
)
})
}
fn write_atomic(path: &Path, contents: &[u8]) -> Result<(), String> {
let file_name = path
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "marqdo.lock".to_string());
let temp = path.with_file_name(format!(
".{file_name}.tmp-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
));
let result = (|| -> Result<(), String> {
let mut file = std::fs::File::create(&temp)
.map_err(|error| format!("cannot create {}: {error}", temp.display()))?;
std::io::Write::write_all(&mut file, contents)
.map_err(|error| format!("cannot write {}: {error}", temp.display()))?;
file.sync_all()
.map_err(|error| format!("cannot sync {}: {error}", temp.display()))?;
std::fs::rename(&temp, path)
.map_err(|error| format!("cannot publish {}: {error}", path.display()))?;
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temp);
}
result
}
/// `marqdo add <name> --path <dir> [--git URL --rev SHA]`.
pub fn add(
name: &str,
path: Option<&Path>,
git: Option<&str>,
rev: Option<&str>,
json: bool,
) -> i32 {
let root = match discover_project_root() {
Ok(root) => root,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let dependency = marqdo_package::Dependency {
path: path.map(|path| path.to_path_buf()),
git: git.map(str::to_string),
rev: rev.map(str::to_string),
};
if let Err(error) = dependency.validate(name) {
eprintln!("error: {error}");
return 2;
}
if manifest.dependencies.contains_key(name) {
eprintln!("error: dependency `{name}` already exists; remove it first");
return 1;
}
manifest.dependencies.insert(name.to_string(), dependency);
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
eprintln!("error: cannot write {}: {error}", manifest_path.display());
return 1;
}
if json {
output::print_json(&json!({
"command": "add",
"success": true,
"dependency": name,
"manifest": manifest_path.display().to_string(),
}));
} else {
println!("added dependency `{name}` to {}", manifest_path.display());
println!(
"run `marqdo lock` to pin it in {}",
marqdo_package::LOCK_FILE
);
}
0
}
/// `marqdo remove <name>`.
pub fn remove(name: &str, json: bool) -> i32 {
let root = match discover_project_root() {
Ok(root) => root,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
let manifest_path = root.join(marqdo_package::MANIFEST_FILE);
let mut manifest = match marqdo_package::Manifest::load(&manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
eprintln!("error: {error}");
return 2;
}
};
if manifest.dependencies.remove(name).is_none() {
eprintln!("error: dependency `{name}` is not declared");
return 1;
}
if let Err(error) = std::fs::write(&manifest_path, manifest.to_yaml()) {
eprintln!("error: cannot write {}: {error}", manifest_path.display());
return 1;
}
// The lock is a graph, not a per-name list: regenerating it here would
// require resolving the new manifest. Leave it stale and tell the user.
if json {
output::print_json(&json!({
"command": "remove",
"success": true,
"dependency": name,
}));
} else {
println!("removed dependency `{name}`");
println!("run `marqdo lock` to refresh {}", marqdo_package::LOCK_FILE);
}
0
}
+561
View File
@@ -0,0 +1,561 @@
//! `marqdo run` execution assembly.
//!
//! Child module of `commands`: it may use the parent's project loader and
//! runtime helpers, but keeps the run session out of the command table.
use super::*;
use crate::provider_manifest;
use marqdo_sandbox::StrictChildState;
pub fn execute(
file: Option<&Path>,
function: Option<&str>,
named_args: &[(String, Value)],
settings: &SandboxSettings,
json: bool,
trace: bool,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
let prepared = match prepare_project(file, json, &settings.plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
};
let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded;
let static_plugins = prepared.plugins;
if project.has_errors() {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
return 1;
}
let warnings: Vec<FileDiagnostic> = project
.diagnostics
.iter()
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !json && !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
emit_error(json, command_name, "cli.invalid_mode", &error);
return 2;
}
};
// A project-declared extension is activation, not authorization, but it is
// still third-party executable code. `pure`/`strict` never activate it.
if !extension_sources.is_empty() && mode != SandboxMode::Project {
let code = if mode == SandboxMode::Strict {
"strict.unsupported_grant"
} else {
"cli.invalid_grants"
};
let message = format!(
"this project declares {} extension activation source(s) in {}; \
--mode {} cannot activate third-party extensions. Use --mode project \
with explicit grants, or remove the extensions block",
extension_sources.len(),
marqdo_package::MANIFEST_FILE,
settings.mode
);
emit_error(json, command_name, code, &message);
return 2;
}
let mut kernel_paths = settings.kernels.clone();
kernel_paths.extend(
extension_sources
.iter()
.filter(|extension| extension.kind == marqdo_package::ExtensionKind::Kernel)
.map(|extension| extension.path.clone()),
);
kernel_paths.sort();
kernel_paths.dedup();
let mut provider_paths = settings.providers.clone();
provider_paths.extend(
extension_sources
.iter()
.filter(|extension| extension.kind == marqdo_package::ExtensionKind::Provider)
.map(|extension| extension.path.clone()),
);
provider_paths.sort();
provider_paths.dedup();
if mode == SandboxMode::Strict {
if let Err(error) = settings.strict_preflight() {
emit_error(json, command_name, "strict.unsupported_grant", &error);
return 2;
}
match marqdo_sandbox::inspect_strict_child() {
// A verified supervisor child may run project code.
Ok(StrictChildState::VerifiedChild) => {}
// Not a child: enforce capability and launch under the supervisor.
Ok(StrictChildState::NotChild) => {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
emit_error(json, command_name, error.code(), &error.to_string());
return 1;
}
return launch_strict_process(&project.root, file, settings, json, command_name);
}
// A marker without a verified identity is never trusted, and the
// platform-neutral inspection keeps Linux-only symbols out of this
// module so macOS/Windows builds compile.
Err(reason) => {
let message = format!("strict isolation verification failed: {reason}");
emit_error(json, command_name, "strict.identity_invalid", &message);
return 1;
}
}
}
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
emit_error(
json,
command_name,
"sandbox.unavailable",
&error.to_string(),
);
return 1;
}
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
emit_error(json, command_name, "cli.invalid_grants", &error);
return 2;
}
};
let stdin = read_stdin();
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
if let Some(stack) = settings.stack {
host.budget.stack_limit = stack;
}
if let Some(max_output) = settings.max_output {
host.budget.max_output_bytes = max_output;
}
if let Some(timeout) = settings.timeout {
host.budget.deadline = Some(Instant::now() + Duration::from_secs(timeout));
}
for kernel_path in &kernel_paths {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
if json {
output::print_json(&json!({"success": false, "error": error}));
} else {
eprintln!("error: {error}");
}
return 2;
}
}
// T6: verify every selected artifact/path/hash before starting a worker or
// loading native code. Static path/signature checks happened in `prepare`.
//
// Provider selection is host assembly, not callable semantics: `check`
// never sees it. Parse and verify every `--provider` manifest, resolve the
// current target artifact, check the exact grant and reject duplicate
// names/kinds *before* any provider or plugin worker process is spawned
// (RFC-EXT-0001 §5.4.6/§18.2 T6–T7).
let providers = match provider_manifest::read_provider_manifests(&provider_paths) {
Ok(providers) => providers,
Err(error) => {
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
};
// `--provider` alone never authorizes; the exact `--allow-provider NAME`
// is required before the helper process may be started. An ungranted
// provider fails closed instead of being silently ignored.
for provider in &providers {
if !settings
.allow_provider
.iter()
.any(|grant| grant == &provider.name)
{
let error = extension_descriptors::PrepareError::load(
"permission.denied",
format!(
"resource provider `{}` was selected with --provider but is not granted; \
add --allow-provider {}",
provider.name, provider.name
),
);
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
}
// A grant that matches no selected provider is a deterministic option
// error: providers are never discovered from PATH, the working directory or
// the network.
for grant in &settings.allow_provider {
if !providers.iter().any(|provider| &provider.name == grant) {
let error = extension_descriptors::PrepareError::option(
"ext.provider_grant_unmatched",
format!(
"--allow-provider `{grant}` matches no selected --provider manifest; \
providers are never discovered automatically"
),
);
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
}
for plugin in &static_plugins.plugins {
if let Err(error) = extension_descriptors::verify_bundle_regular_file(
&plugin.base_dir,
&plugin.artifact_relative,
) {
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
let artifact = plugin.artifact_path();
if let Err(error) = extension_descriptors::verify_sha256(&artifact, &plugin.artifact_sha256)
{
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
}
// T7: start only selected, granted and verified extensions.
for plugin in &static_plugins.plugins {
if let Err(message) = load_plugin_into_host(
&mut host,
&plugin.manifest_path,
settings.trust_native_plugin,
) {
if json {
output::print_json(&json!({"success": false, "error": message}));
} else {
eprintln!("error: {message}");
}
return 1;
}
}
// T8: exact one-to-one reconciliation with the static descriptors. Never
// synthesise a missing signature (`params: Vec::new()`) or guess an export.
if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) {
emit_error(json, command_name, "ext.plugin_binding_mismatch", &message);
return 1;
}
// T7b: start only granted and verified provider helpers. Every manifest,
// artifact, target, grant and duplicate-kind check above already passed, so
// no worker is spawned for a provider that failed verification.
for provider in &providers {
if let Err(error) = provider_manifest::load_resource_provider_into_host(
&mut host,
provider,
&settings.allow_provider,
) {
emit_prepare_error(json, command_name, &error);
return error.exit_code;
}
}
let function_name = function.unwrap_or("main").to_string();
let entry_module = &project.program.modules[&project.entry];
if entry_module.function(&function_name).is_none() {
let message = if function.is_none() {
format!(
"{} has no callable `main`; declare an Exec H2 (`## @exec main`) or pass an \
explicit function name",
project.entry_file().path.display()
)
} else {
format!(
"no function named `{function_name}` in {}",
project.entry_file().path.display()
)
};
if json {
emit_error(true, command_name, "sem.no_entry_function", &message);
} else {
eprintln!("error[sem.no_entry_function]: {message}");
}
return 1;
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
.map(|(name, value)| EvaluatedArg::named(name.clone(), value.clone(), Span::default()))
.collect();
let memory_limits = MemoryLimits {
max_total_bytes: settings
.max_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_TOTAL_BYTES),
max_region_bytes: settings
.max_region_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_REGION_BYTES),
};
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
&function_name,
runtime_args,
memory_limits,
);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(&project, &host, &entry, status, path) {
emit_error(json, command_name, "cli.trace_failed", &error);
return 1;
}
}
let stdout = host.take_output();
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
let stderr = host.take_error();
let stderr_text = String::from_utf8_lossy(&stderr).to_string();
let trace_entries = host.trace().to_vec();
match result {
Ok(outcome) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
}
0
}
Err(error) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
1
}
}
}
fn emit_prepare_error(
json: bool,
command_name: &str,
error: &crate::extension_descriptors::PrepareError,
) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": {"code": error.code, "message": error.message},
}));
} else {
eprintln!("error[{}]: {}", error.code, error.message);
}
}
/// Compare the Host's actual plugin exports with the static manifest set.
///
/// Names, raw signatures, owners and verified artifact digests must match
/// exactly; extra, missing or altered exports fail closed with
/// `ext.plugin_binding_mismatch` and the main function never runs.
fn reconcile_plugin_exports(
static_plugins: &StaticPluginSet,
host: &StdHost,
) -> Result<(), String> {
let mut expected: std::collections::BTreeMap<String, (String, String, String)> =
std::collections::BTreeMap::new();
for plugin in &static_plugins.plugins {
for export in &plugin.exports {
expected.insert(
export.name.clone(),
(
export.signature.clone(),
plugin.artifact_sha256.clone(),
plugin.package.clone(),
),
);
}
}
let loaded = host.plugin_exports();
if loaded.len() != expected.len() {
return Err(format!(
"static plugin descriptors declare {} export(s) but the runtime loaded {}; \
refusing to execute",
expected.len(),
loaded.len()
));
}
for (name, signature, digest, package) in loaded {
let Some((expected_signature, expected_digest, expected_package)) = expected.get(&name)
else {
return Err(format!(
"runtime export `{name}` was not declared by any selected plugin manifest"
));
};
if &signature != expected_signature {
return Err(format!(
"export `{name}` signature mismatch: manifest `{expected_signature}`, runtime `{signature}`"
));
}
if &digest != expected_digest {
return Err(format!(
"export `{name}` artifact digest mismatch: manifest `{expected_digest}`, runtime `{digest}`"
));
}
if &package != expected_package {
return Err(format!(
"export `{name}` owner mismatch: manifest `{expected_package}`, runtime `{package}`"
));
}
}
Ok(())
}
/// Read piped stdin once at the composition boundary.
///
/// A terminal stdin is not read, so `marqdo run` never blocks waiting for an
/// interactive EOF. Non-terminal input is a finite pipe/file and is copied into
/// the run-scoped `stdio/stdin` resource.
fn read_stdin() -> Vec<u8> {
use std::io::{IsTerminal, Read};
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
return Vec::new();
}
let mut bytes = Vec::new();
if let Err(error) = stdin.read_to_end(&mut bytes) {
eprintln!("error: cannot read stdin: {error}");
return Vec::new();
}
bytes
}
#[cfg(test)]
mod tests {
use super::*;
fn empty_host() -> StdHost {
StdHost::new(
SandboxMode::Project,
marqdo_host::Capabilities::pure(),
std::env::temp_dir(),
)
}
fn static_plugin_with_export() -> StaticPluginSet {
let descriptor = marqdo_ir::callable::CallableDescriptor {
id: marqdo_ir::callable::CallableId("plugin:demo.ext:solver.add".into()),
public_name: "solver.add".into(),
owner_package: "demo.ext".into(),
signature: marqdo_ir::callable::CallableSignature {
params: vec![
marqdo_ir::Param {
name: "a".into(),
span: Span::default(),
type_annotation: None,
default: None,
},
marqdo_ir::Param {
name: "b".into(),
span: Span::default(),
type_annotation: None,
default: None,
},
],
kind: marqdo_ir::SignatureKind::Explicit,
},
effects_requested: vec!["math.compute".into()],
origin: marqdo_ir::callable::CallableOrigin::AbiPlugin {
package: "demo.ext".into(),
export: "solver.add".into(),
},
implementation_digest: Some("a".repeat(64)),
source_span: None,
};
StaticPluginSet {
plugins: vec![crate::extension_descriptors::StaticPlugin {
manifest_path: PathBuf::from("/fixtures/demo/plugin.yaml"),
base_dir: PathBuf::from("/fixtures/demo"),
package: "demo.ext".into(),
version: "0.1.0".into(),
kind: marqdo_plugin_abi::PluginKind::Worker,
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
artifact_target: marqdo_plugin_abi::HostTarget::current()
.triple()
.to_string(),
artifact_sha256: "a".repeat(64),
artifact_relative: "build/plugin.so".into(),
exports: vec![crate::extension_descriptors::StaticPluginExport {
name: "solver.add".into(),
signature: "($a: Int, $b: Int) -> Int".into(),
descriptor,
}],
requires: Vec::new(),
}],
}
}
#[test]
fn reconcile_accepts_matching_empty_sets() {
assert!(
reconcile_plugin_exports(&StaticPluginSet::default(), &empty_host()).is_ok(),
"no selected plugin and no loaded plugin must reconcile"
);
}
#[test]
fn reconcile_rejects_missing_runtime_exports() {
let error = reconcile_plugin_exports(&static_plugin_with_export(), &empty_host())
.expect_err("a declared export that the runtime did not load must fail closed");
assert!(
error.contains("declare 1 export(s)") || error.contains("not declared"),
"{error}"
);
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Sandbox mode parsing and capability construction.
//!
//! This module owns the CLI-to-`Capabilities` mapping and strict preflight;
//! command implementations only consume the resulting grant set.
use std::path::PathBuf;
use marqdo_host::Capabilities;
use marqdo_sandbox::SandboxMode;
/// Effective sandbox settings from the command line.
#[derive(Debug, Clone, Default)]
pub struct SandboxSettings {
/// Mode name.
pub mode: String,
/// Read grants.
pub allow_read: Vec<String>,
/// Write grants.
pub allow_write: Vec<String>,
/// Network grants (IP literals, ADR-0034).
pub allow_net: Vec<String>,
/// Environment variable grants (ADR-0043).
pub allow_env: Vec<String>,
/// Process program grants (ADR-0044).
pub allow_process: Vec<String>,
/// OS entropy grant (ADR-0046).
pub allow_random: bool,
/// Foreign execution grant.
pub allow_foreign: bool,
/// Plugin grants.
pub allow_plugin: Vec<String>,
/// Fuel override.
pub fuel: Option<u64>,
/// Stack depth override.
pub stack: Option<usize>,
/// Output limit override.
pub max_output: Option<usize>,
/// Total committed addressable-memory budget override (bytes).
pub max_memory: Option<usize>,
/// Per-region committed addressable-memory budget override (bytes).
pub max_region_memory: Option<usize>,
/// Wall-clock timeout in seconds.
pub timeout: Option<u64>,
/// Explicitly trusted plugin manifests to load.
pub plugins: Vec<PathBuf>,
/// Explicitly selected resource provider v2 manifests (RFC-EXT-0001 §5.4).
pub providers: Vec<PathBuf>,
/// Exact resource provider name grants (declaration is not a grant).
pub allow_provider: Vec<String>,
/// Explicit trust decision for in-process native plugin loading.
pub trust_native_plugin: bool,
/// Optional Trace v2 output path.
pub trace_file: Option<PathBuf>,
/// Trace event budget override (0 = unlimited).
pub trace_max_events: Option<usize>,
/// Trace approximate byte budget override (0 = unlimited).
pub trace_max_bytes: Option<usize>,
/// External foreign-kernel descriptor paths.
pub kernels: Vec<PathBuf>,
}
impl SandboxSettings {
/// Parse the mode string.
pub fn sandbox_mode(&self) -> Result<SandboxMode, String> {
SandboxMode::parse(&self.mode).ok_or_else(|| {
format!(
"unknown sandbox mode `{}` (expected pure, project or strict)",
self.mode
)
})
}
/// Reject strict-mode requests that this L1 isolation level does not
/// support. Strict currently covers pure Marqdo and native Math only;
/// granting Foreign, ABI plugins, resource providers, tools or trace files
/// would require extending the supervisor contract first.
pub fn strict_preflight(&self) -> Result<(), String> {
let requested = self.allow_foreign
|| !self.allow_read.is_empty()
|| !self.allow_net.is_empty()
|| !self.allow_write.is_empty()
|| !self.allow_env.is_empty()
|| !self.allow_process.is_empty()
|| self.allow_random
|| !self.allow_plugin.is_empty()
|| !self.plugins.is_empty()
|| !self.providers.is_empty()
|| !self.allow_provider.is_empty()
|| self.trust_native_plugin
|| !self.kernels.is_empty()
|| self.trace_file.is_some();
if requested {
return Err(
"strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\
--trust-native-plugin/--kernel/--trace-file are rejected. \
Use --mode project for those capabilities."
.to_string(),
);
}
Ok(())
}
/// Build the effective capability set.
pub fn capabilities(&self) -> Result<Capabilities, String> {
let mode = self.sandbox_mode()?;
match mode {
SandboxMode::Pure => {
if !self.allow_read.is_empty()
|| !self.allow_net.is_empty()
|| !self.allow_write.is_empty()
|| !self.allow_env.is_empty()
|| !self.allow_process.is_empty()
|| self.allow_random
|| self.allow_foreign
|| !self.allow_plugin.is_empty()
|| !self.providers.is_empty()
|| !self.allow_provider.is_empty()
{
return Err(
"pure mode prohibits external I/O grants and extension providers; \
use --mode project"
.to_string(),
);
}
Ok(Capabilities::pure())
}
SandboxMode::Project => {
let mut capabilities = Capabilities::project();
for pattern in &self.allow_read {
capabilities = capabilities.allow_read(pattern.clone());
}
for pattern in &self.allow_write {
capabilities = capabilities.allow_write(pattern.clone());
}
for host in &self.allow_net {
capabilities = capabilities.allow_net(host.clone());
}
for name in &self.allow_env {
capabilities = capabilities.allow_env(name.clone());
}
for program in &self.allow_process {
capabilities = capabilities.allow_process(program.clone());
}
if self.allow_random {
capabilities = capabilities.allow_random();
}
if self.allow_foreign {
capabilities = capabilities.allow_foreign();
}
for plugin in &self.allow_plugin {
capabilities = capabilities.allow_plugin(plugin.clone());
}
for provider in &self.allow_provider {
validate_provider_grant(provider)?;
capabilities = capabilities.allow_resource_provider(provider.clone());
}
Ok(capabilities)
}
SandboxMode::Strict => {
self.strict_preflight()?;
Ok(Capabilities::project())
}
}
}
}
/// Reject non-exact `--allow-provider` grants.
///
/// Provider grants are exact stable names (RFC-EXT-0001 §5.2): there is no `*`
/// wildcard, no prefix matching and no implicit discovery, so a grant either
/// names a selected manifest or the run fails closed.
fn validate_provider_grant(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("--allow-provider requires a non-empty provider name".to_string());
}
if name
.chars()
.any(|character| matches!(character, '*' | '?' | '[' | ']'))
{
return Err(format!(
"--allow-provider `{name}`: wildcards are not supported; grants are exact provider names"
));
}
if name.chars().any(char::is_control) {
return Err(format!(
"--allow-provider `{name}`: provider names must not contain control characters"
));
}
Ok(())
}
+138
View File
@@ -0,0 +1,138 @@
//! CLI formatter and plugin/tool inspection commands.
use super::*;
/// `marqdo fmt`.
pub fn fmt(file: Option<&Path>, check_only: bool) -> i32 {
let file = file.unwrap_or_else(|| Path::new("index.mq.md"));
let Ok(source) = std::fs::read_to_string(file) else {
eprintln!("error: cannot read `{}`", file.display());
return 2;
};
let mut formatted = source.replace("\r\n", "\n");
while formatted.ends_with("\n\n") {
formatted.pop();
}
if !formatted.ends_with('\n') {
formatted.push('\n');
}
if formatted == source {
return 0;
}
if check_only {
eprintln!(
"error: `{}` is not formatted (trailing whitespace/newlines or CRLF)",
file.display()
);
return 1;
}
if let Err(error) = std::fs::write(file, formatted) {
eprintln!("error: cannot write `{}`: {error}", file.display());
return 1;
}
0
}
/// `marqdo plugin inspect`.
pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
let manifest_path = if target.is_dir() {
target.join("plugin.yaml")
} else {
target.to_path_buf()
};
let base_dir = manifest_path
.parent()
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
report_plugin_error(&error, json);
return 1;
}
};
if let Err(error) = manifest.validate() {
report_plugin_error(&error, json);
return 1;
}
let host_target = marqdo_plugin_abi::HostTarget::current();
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
Ok((path, artifact)) => {
let abi = match manifest.abi_requirement() {
Ok(requirement) => {
if requirement.is_compatible_with(marqdo_plugin_abi::AbiVersion::current()) {
"compatible"
} else {
"incompatible"
}
}
Err(error) => {
report_plugin_error(&error, json);
return 1;
}
};
(path, artifact, abi)
}
Err(error) => {
report_plugin_error(&error, json);
return 1;
}
};
let (artifact_path, artifact_info, abi) = artifact;
if json {
output::print_json(&json!({
"command": "plugin.inspect",
"success": true,
"plugin": manifest.plugin.name,
"version": manifest.plugin.version,
"abi": manifest.plugin.abi,
"abi_compatibility": abi,
"target": host_target.triple().as_str(),
"artifact": {
"file": artifact_info.file,
"path": artifact_path.display().to_string(),
"sha256": artifact_info.sha256,
"verified": true,
},
"exports": manifest.plugin.exports.iter().map(|export| json!({
"name": export.name,
"signature": export.signature,
})).collect::<Vec<_>>(),
"loaded": false,
}));
} else {
println!(
"plugin: {} {}",
manifest.plugin.name, manifest.plugin.version
);
println!("abi: {} ({abi})", manifest.plugin.abi);
println!("target: {}", host_target.triple().as_str());
println!(
"artifact: {} (sha256 verified: {})",
artifact_path.display(),
artifact_info.sha256
);
println!("exports:");
for export in &manifest.plugin.exports {
println!(" {} {}", export.name, export.signature);
}
println!("loaded: false (inspection never executes plugin code)");
}
0
}
fn report_plugin_error(error: &marqdo_plugin_abi::PluginError, json: bool) {
if json {
output::print_json(&json!({
"command": "plugin.inspect",
"success": false,
"error": {
"kind": error.kind,
"code": error.code,
"message": error.message,
}
}));
} else {
eprintln!("error[{}]: {}", error.code, error.message);
}
}
+414
View File
@@ -0,0 +1,414 @@
//! Static extension descriptors for the CLI composition root
//! (RFC-EXT-0001 §4.4/§6, ADR-0054/0056).
//!
//! This module only *reads* manifests. It never `dlopen`s a library, never
//! spawns a worker, never opens a network connection and never executes a
//! side-effect script. The descriptors produced here feed the single
//! [`marqdo_ir::callable::CallableRegistry`] and binding pass; `run` later
//! verifies the real artifacts against these recorded identities.
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
use marqdo_ir::SignatureKind;
use marqdo_plugin_abi::{HostTarget, PluginKind, PluginManifest};
use marqdo_span::Span;
use sha2::{Digest, Sha256};
/// A structured prepare-stage failure.
#[derive(Debug, Clone)]
pub struct PrepareError {
/// Stable diagnostic code (`ext.*` unless reusing an existing event code).
pub code: String,
/// Human-readable message; never contains secrets or binary content.
pub message: String,
/// CLI exit code (2 for manifest/option errors, 1 for load/verify errors).
pub exit_code: i32,
}
impl PrepareError {
/// Construct a manifest/option error (exit code 2).
pub fn option(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
exit_code: 2,
}
}
/// Construct a loading/verification error (exit code 1).
pub fn load(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
exit_code: 1,
}
}
}
/// One statically declared export.
#[derive(Debug, Clone)]
pub struct StaticPluginExport {
/// Complete dotted export name.
pub name: String,
/// Raw manifest signature string, compared exactly at run time.
pub signature: String,
/// Parsed static descriptor used by the binding pass.
pub descriptor: CallableDescriptor,
}
/// One statically read plugin package.
///
/// The identity fields are recorded for `inspect --extensions`, evidence and
/// reconciliation; they are not consulted for name resolution (the binding
/// table is).
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct StaticPlugin {
/// Canonical manifest path.
pub manifest_path: PathBuf,
/// Package directory (artifact root).
pub base_dir: PathBuf,
/// Declared package name.
pub package: String,
/// Declared package version.
pub version: String,
/// Deployment kind (`native`, `worker`, `wasm`).
pub kind: PluginKind,
/// `sha256:<hex>` of the manifest file bytes.
pub manifest_sha256: String,
/// Target triple selected for this host.
pub artifact_target: String,
/// Declared (not yet verified) artifact sha256, lowercase hex.
pub artifact_sha256: String,
/// Bundle-relative artifact path.
pub artifact_relative: String,
/// Exports in manifest order.
pub exports: Vec<StaticPluginExport>,
/// Declared capability requests (metadata only; never grants).
pub requires: Vec<String>,
}
impl StaticPlugin {
/// Absolute artifact path inside the package bundle.
pub fn artifact_path(&self) -> PathBuf {
self.base_dir.join(&self.artifact_relative)
}
}
/// Static plugin selection read from explicit CLI `--plugin` flags.
#[derive(Debug, Clone, Default)]
pub struct StaticPluginSet {
/// Packages in deterministic manifest order.
pub plugins: Vec<StaticPlugin>,
}
impl StaticPluginSet {
/// All export descriptors in deterministic order.
pub fn descriptors(&self) -> Vec<CallableDescriptor> {
let mut descriptors = Vec::new();
for plugin in &self.plugins {
for export in &plugin.exports {
descriptors.push(export.descriptor.clone());
}
}
descriptors
}
}
/// Read and validate all explicitly selected `--plugin` manifests.
///
/// No binary is opened or executed. Duplicate package identities, duplicate
/// full export names, reserved names and malformed signatures are rejected
/// here, before any binding is produced.
pub fn read_plugin_descriptors(paths: &[PathBuf]) -> Result<StaticPluginSet, PrepareError> {
let mut set = StaticPluginSet::default();
let mut export_names: BTreeSet<String> = BTreeSet::new();
let mut packages: BTreeSet<(String, String)> = BTreeSet::new();
for path in paths {
let manifest_path = if path.is_dir() {
path.join("plugin.yaml")
} else {
path.clone()
};
let manifest_path = manifest_path.canonicalize().map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot open plugin manifest `{}`: {error}",
manifest_path.display()
),
)
})?;
let base_dir = manifest_path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
let base_dir = base_dir.canonicalize().unwrap_or(base_dir);
let manifest_bytes = std::fs::read(&manifest_path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot read plugin manifest `{}`: {error}",
manifest_path.display()
),
)
})?;
let manifest = PluginManifest::load(&manifest_path)
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
manifest
.validate()
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
let host = HostTarget::current();
let artifact = manifest.resolve_artifact(&host).map_err(|error| {
PrepareError::option("ext.no_matching_artifact", error.message.clone())
})?;
let artifact_relative = artifact.file.clone();
ensure_bundle_relative(&artifact_relative).map_err(|error| {
PrepareError::option(
"ext.artifact_integrity",
format!(
"plugin `{}` artifact path `{artifact_relative}` is invalid: {error}",
manifest.plugin.name
),
)
})?;
let manifest_sha256 = format!("sha256:{}", hex(&Sha256::digest(&manifest_bytes)));
let identity = (manifest.plugin.name.clone(), manifest_sha256.clone());
if !packages.insert(identity.clone()) {
// The exact same package declaration twice is idempotent.
continue;
}
if set
.plugins
.iter()
.any(|plugin| plugin.package == identity.0)
{
return Err(PrepareError::option(
"ext.duplicate_callable",
format!(
"plugin package `{}` is selected with two different manifests; \
explicit aliases are not implemented, so this is rejected",
identity.0
),
));
}
let mut exports = Vec::new();
for export in &manifest.plugin.exports {
if !export_names.insert(export.name.clone()) {
return Err(PrepareError::option(
"ext.duplicate_callable",
format!(
"plugin export `{}` is declared by more than one selected package",
export.name
),
));
}
let signature = plugin_signature(&export.signature).map_err(|error| {
PrepareError::option(
"ext.plugin_invalid_signature",
format!(
"plugin export `{}` has an invalid signature: {error}",
export.name
),
)
})?;
let descriptor = CallableDescriptor {
id: CallableId(format!("plugin:{}:{}", manifest.plugin.name, export.name)),
public_name: export.name.clone(),
owner_package: manifest.plugin.name.clone(),
signature,
effects_requested: manifest.plugin.requires.clone(),
origin: CallableOrigin::AbiPlugin {
package: manifest.plugin.name.clone(),
export: export.name.clone(),
},
implementation_digest: Some(artifact.sha256.clone()),
source_span: None,
};
exports.push(StaticPluginExport {
name: export.name.clone(),
signature: export.signature.clone(),
descriptor,
});
}
set.plugins.push(StaticPlugin {
manifest_path,
base_dir,
package: manifest.plugin.name.clone(),
version: manifest.plugin.version.clone(),
kind: manifest.plugin.kind,
manifest_sha256,
artifact_target: host.triple().to_string(),
artifact_sha256: artifact.sha256.clone(),
artifact_relative,
exports,
requires: manifest.plugin.requires.clone(),
});
}
set.plugins.sort_by(|left, right| {
(&left.package, &left.manifest_sha256).cmp(&(&right.package, &right.manifest_sha256))
});
Ok(set)
}
/// Convert a plugin manifest signature (`($a: Int, $b: Int) -> Int`) to the
/// language parameter list.
///
/// ABI v1 transports named arguments as a map, so positional arguments are a
/// static-validated convenience: the binding pass normalises them to the
/// manifest order. Default values are rejected until the ABI wire semantics for
/// them are versioned (RFC-EXT-0001 §4.5.3); silently injecting defaults at run
/// time is forbidden.
pub fn plugin_signature(raw: &str) -> Result<CallableSignature, String> {
let before_return = raw.split("->").next().unwrap_or(raw).trim();
let open = before_return
.find('(')
.ok_or_else(|| "missing `(`".to_string())?;
let close = before_return
.rfind(')')
.ok_or_else(|| "missing `)`".to_string())?;
if close < open {
return Err("malformed parameter list".to_string());
}
let params = before_return[open + 1..close].replace('$', "");
let parsed = marqdo_frontend::signature::parse(&format!("({params})"), Span::default());
if parsed.has_errors() {
return Err(parsed
.diagnostics
.iter()
.map(|diagnostic| diagnostic.message.clone())
.collect::<Vec<_>>()
.join("; "));
}
if parsed.params.iter().any(|param| param.default.is_some()) {
return Err(
"ABI v1 plugin signatures must not declare default values; make parameters required"
.to_string(),
);
}
Ok(CallableSignature {
params: parsed.params,
kind: SignatureKind::Explicit,
})
}
/// Reject absolute paths, `..` components and empty paths.
pub fn ensure_bundle_relative(path: &str) -> Result<(), String> {
let mut normalised = PathBuf::new();
for component in Path::new(path).components() {
match component {
Component::Normal(part) => normalised.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err("must be a relative path inside the package".to_string())
}
}
}
if normalised.as_os_str().is_empty() {
return Err("must not be empty".to_string());
}
Ok(())
}
/// Verify a bundle file is a regular file below `bundle_root`, travelling
/// through symlinks only if the final canonical target stays inside the bundle.
pub fn verify_bundle_regular_file(
bundle_root: &Path,
relative: &str,
) -> Result<PathBuf, PrepareError> {
ensure_bundle_relative(relative).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!("artifact path `{relative}` is invalid: {error}"),
)
})?;
let root = bundle_root.canonicalize().map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!(
"cannot resolve package root `{}`: {error}",
bundle_root.display()
),
)
})?;
let candidate = root.join(relative);
let canonical = candidate.canonicalize().map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!("cannot open artifact `{}`: {error}", candidate.display()),
)
})?;
if !canonical.starts_with(&root) {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"artifact `{relative}` resolves outside its package bundle (`{}`)",
canonical.display()
),
));
}
let metadata = std::fs::metadata(&canonical).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!("cannot stat artifact `{}`: {error}", canonical.display()),
)
})?;
if !metadata.is_file() {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!("artifact `{}` is not a regular file", canonical.display()),
));
}
Ok(canonical)
}
/// Verify a file's lowercase sha256 against a declared value.
pub fn verify_sha256(path: &Path, declared: &str) -> Result<(), PrepareError> {
let bytes = std::fs::read(path).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!("cannot read artifact `{}`: {error}", path.display()),
)
})?;
let actual = hex(&Sha256::digest(&bytes));
if actual != declared.to_ascii_lowercase() {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"artifact `{}` sha256 mismatch: declared {declared}, actual {actual}",
path.display()
),
));
}
Ok(())
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plugin_signature_rejects_defaults_and_parses_positional() {
assert!(plugin_signature("($a: Int, $b: Int) -> Int").is_ok());
let error = plugin_signature("($a: Int = 1) -> Int").unwrap_err();
assert!(error.contains("default"), "{error}");
}
#[test]
fn bundle_relative_paths_reject_traversal() {
assert!(ensure_bundle_relative("lib/demo.so").is_ok());
assert!(ensure_bundle_relative("../demo.so").is_err());
assert!(ensure_bundle_relative("/etc/passwd").is_err());
assert!(ensure_bundle_relative("").is_err());
}
}
+318
View File
@@ -0,0 +1,318 @@
//! Extension selection identities (RFC-EXT-0001 §6, ADR-0056).
//!
//! `marqdo.yaml.extensions` declares activation sources; the lock file records
//! the exact selected identity (manifest digest, artifact digest, target).
//! This module computes those identities from static manifests only:
//!
//! * it never `dlopen`s a library, spawns a worker or runs a script;
//! * it reads the declared artifact SHA-256 (plus the manifest bytes) so
//! `check`/`sync` can compare against the lock without requiring a built
//! binary; `run` separately verifies the actual artifact bytes before use.
//!
//! A declaration is visibility/activation, never a grant. Grants stay in
//! `--allow-plugin`/`--allow-provider`/`--allow-foreign` and the capability
//! broker.
use std::collections::BTreeSet;
use marqdo_package::{ExtensionKind, LockedExtension, ResolvedExtension};
use sha2::{Digest, Sha256};
use crate::extension_descriptors::PrepareError;
/// Compute the declared identity of every resolved extension source.
///
/// Duplicate `(kind, name, logical_owner)` identities with different digests
/// are rejected deterministically; the same identity declared twice is
/// idempotent.
pub fn extension_identities(
resolved: &[ResolvedExtension],
) -> Result<Vec<LockedExtension>, PrepareError> {
let mut identities = Vec::new();
let mut seen: BTreeSet<(ExtensionKind, String, String)> = BTreeSet::new();
for extension in resolved {
let identity = match extension.kind {
ExtensionKind::Plugin => plugin_identity(extension)?,
ExtensionKind::Provider => provider_identity(extension)?,
ExtensionKind::Kernel => kernel_identity(extension)?,
};
let key = (
identity.kind,
identity.name.clone(),
identity.logical_owner.clone(),
);
if !seen.insert(key.clone()) {
let existing = identities
.iter()
.find(|item: &&LockedExtension| {
item.kind == key.0 && item.name == key.1 && item.logical_owner == key.2
})
.expect("identity was inserted with its key");
if existing == &identity {
continue;
}
return Err(PrepareError::option(
"ext.duplicate_callable",
format!(
"extension {} `{}` for owner `{}` is declared with two different manifests",
key.0, key.1, key.2
),
));
}
identities.push(identity);
}
identities.sort_by(|left, right| {
(&left.kind, &left.name, &left.logical_owner).cmp(&(
&right.kind,
&right.name,
&right.logical_owner,
))
});
Ok(identities)
}
fn plugin_identity(extension: &ResolvedExtension) -> Result<LockedExtension, PrepareError> {
let manifest_bytes = std::fs::read(&extension.path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot read plugin manifest `{}`: {error}",
extension.path.display()
),
)
})?;
let manifest = marqdo_plugin_abi::PluginManifest::load(&extension.path)
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
manifest
.validate()
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
let host = marqdo_plugin_abi::HostTarget::current();
let artifact = manifest
.resolve_artifact(&host)
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
Ok(LockedExtension {
kind: ExtensionKind::Plugin,
logical_owner: extension.logical_owner.clone(),
name: manifest.plugin.name.clone(),
version: manifest.plugin.version.clone(),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: artifact.sha256.clone(),
selected_target: host.triple().to_string(),
source: extension.from.clone(),
})
}
fn provider_identity(extension: &ResolvedExtension) -> Result<LockedExtension, PrepareError> {
let manifest_bytes = std::fs::read(&extension.path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot read provider manifest `{}`: {error}",
extension.path.display()
),
)
})?;
let manifest: serde_json::Value = serde_json::from_slice(&manifest_bytes).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"invalid provider manifest `{}`: {error}",
extension.path.display()
),
)
})?;
if manifest.get("schema").and_then(serde_json::Value::as_str) != Some("marqdo.provider") {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!(
"`{}` must declare schema `marqdo.provider`",
extension.path.display()
),
));
}
if manifest
.get("schema_version")
.and_then(serde_json::Value::as_u64)
!= Some(2)
{
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"`{}` is not a provider schema version 2 manifest; run `marqdo lock` only with v2",
extension.path.display()
),
));
}
let name = manifest
.get("name")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("`{}` has no name", extension.path.display()),
)
})?;
let version = manifest
.get("version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("`{}` has no version", extension.path.display()),
)
})?;
let target = marqdo_plugin_abi::HostTarget::current()
.triple()
.to_string();
let artifacts = manifest
.get("artifacts")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("`{}` has no artifacts array", extension.path.display()),
)
})?;
let artifact = artifacts
.iter()
.find(|artifact| {
artifact.get("target").and_then(serde_json::Value::as_str) == Some(&target)
})
.ok_or_else(|| {
PrepareError::option(
"ext.no_matching_artifact",
format!("provider `{name}` has no artifact for target `{target}`"),
)
})?;
let sha256 = artifact
.get("sha256")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("provider `{name}` artifact has no sha256"),
)
})?;
if sha256.len() != 64 || !sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!("provider `{name}` artifact sha256 is not 64 hex characters"),
));
}
Ok(LockedExtension {
kind: ExtensionKind::Provider,
logical_owner: extension.logical_owner.clone(),
name: name.to_string(),
version: version.to_string(),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: sha256.to_ascii_lowercase(),
selected_target: target,
source: extension.from.clone(),
})
}
fn kernel_identity(extension: &ResolvedExtension) -> Result<LockedExtension, PrepareError> {
let manifest_bytes = std::fs::read(&extension.path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot read kernel descriptor `{}`: {error}",
extension.path.display()
),
)
})?;
let manifest: serde_json::Value = serde_json::from_slice(&manifest_bytes).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"invalid kernel descriptor `{}`: {error}",
extension.path.display()
),
)
})?;
let name = manifest
.get("provider_id")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("`{}` has no provider_id", extension.path.display()),
)
})?;
let wire_version = manifest
.get("wire_version")
.and_then(serde_json::Value::as_u64)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("`{}` has no wire_version", extension.path.display()),
)
})?;
if wire_version != 1 {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!("kernel descriptor `{name}` uses unsupported wire_version {wire_version}"),
));
}
let digest = manifest
.get("digest")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("kernel descriptor `{name}` has no digest"),
)
})?;
if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!("kernel descriptor `{name}` digest is not 64 hex characters"),
));
}
let entrypoint = manifest
.get("entrypoint")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
PrepareError::option(
"ext.manifest_invalid",
format!("kernel descriptor `{name}` has no entrypoint"),
)
})?;
// The descriptor's entrypoint is package/descriptor-relative or absolute
// (existing foreign.md contract). Reject explicit path escaping here.
if entrypoint.is_empty() {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!("kernel descriptor `{name}` has an empty entrypoint"),
));
}
Ok(LockedExtension {
kind: ExtensionKind::Kernel,
logical_owner: extension.logical_owner.clone(),
name: name.to_string(),
version: format!("wire:{wire_version}"),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: digest.to_ascii_lowercase(),
selected_target: marqdo_plugin_abi::HostTarget::current()
.triple()
.to_string(),
source: extension.from.clone(),
})
}
/// Validate that the lock still describes the current declared selection.
pub fn validate_against_lock(
lock: &marqdo_package::LockFile,
identities: &[LockedExtension],
) -> Result<(), PrepareError> {
lock.validate_extension_selection(identities)
.map_err(|message| PrepareError::load("ext.extension_lock_mismatch", message))
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
+231 -15
View File
@@ -13,13 +13,17 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use marqdo_frontend::{analyze_source, AnalysisResult};
use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_expression::Expr;
use marqdo_frontend::AnalysisResult;
use marqdo_ir::callable::OfficialAlias;
use marqdo_ir::{ModuleId, PlaceTarget, Program, ResolvedImport, Stmt};
use marqdo_package::{
discover_root, LockFile, Manifest, PackageResolver, ResolvedPackage, LOCK_FILE, MANIFEST_FILE,
};
use marqdo_value::{codes, Diagnostic};
use crate::stdlib::StdlibBundle;
/// One analysed source file.
pub struct LoadedFile {
/// Canonical module identity (package instance + package-relative path).
@@ -125,6 +129,17 @@ pub struct LocatedSource<'a> {
pub column: usize,
}
/// Identity of the verified bundled stdlib used by a load, if any.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StdlibInfo {
/// Declared version.
pub version: String,
/// Verified content digest.
pub digest: String,
/// Package instance id.
pub instance_id: String,
}
/// A fully loaded project ready for checking or running.
pub struct LoadedProject {
/// Project root.
@@ -141,6 +156,19 @@ pub struct LoadedProject {
pub packages: BTreeMap<String, PathBuf>,
/// All diagnostics in deterministic order.
pub diagnostics: Vec<FileDiagnostic>,
/// Verified bundled stdlib identity, when one was available.
pub stdlib: Option<StdlibInfo>,
/// Official stdlib public aliases referenced by this program (ADR-0058).
///
/// These are ordinary `Marqdo` bindings; the runtime has no print special
/// case and no `Program.print_override`.
pub official_aliases: Vec<marqdo_ir::callable::OfficialAlias>,
/// Project manifest, when the entry belongs to a project.
pub manifest: Option<Manifest>,
/// Verified lock file, when present (lock v4).
pub lock: Option<LockFile>,
/// Resolved `marqdo.yaml.extensions` activation sources (static paths only).
pub extension_sources: Vec<marqdo_package::ResolvedExtension>,
}
impl LoadedProject {
@@ -205,6 +233,7 @@ struct Loader {
program: Program,
diagnostics: Vec<FileDiagnostic>,
stack: Vec<PathBuf>,
stdlib: Option<StdlibBundle>,
}
/// Load the entry file and its explicitly imported modules.
@@ -248,8 +277,9 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
}
None
};
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock);
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone());
let entry_module = resolver.resolve_entry(&entry)?;
let stdlib = StdlibBundle::discover().map_err(|error| format!("stdlib: {error}"))?;
let mut loader = Loader {
resolver,
packages: BTreeMap::new(),
@@ -257,19 +287,25 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
program: Program::default(),
diagnostics: Vec::new(),
stack: Vec::new(),
stdlib,
};
let entry_id = loader.load_module(&entry_module.package, &entry_module.relative_path)?;
loader.program.main_module = Some(entry_id.clone());
for (module_id, diagnostic) in marqdo_frontend::calls::validate_program(&loader.program) {
if let Some(file) = loader.files.get(&module_id) {
loader.diagnostics.push(FileDiagnostic {
module_id,
path: file.path.clone(),
source: file.source.clone(),
diagnostic,
});
}
}
// Official stdlib public aliases (ADR-0058): the verified metadata names
// the target module/function; only aliases the program actually references
// load their module, and the runtime binds them as ordinary Marqdo calls.
let official_aliases = loader.load_official_aliases()?;
let extension_sources = loader
.resolver
.resolve_extension_sources()
.map_err(|error| format!("extension selection: {error}"))?;
let stdlib_info = loader.stdlib.as_ref().map(|bundle| StdlibInfo {
version: bundle.version().to_string(),
digest: bundle.digest().to_string(),
instance_id: bundle.instance_id(),
});
let identity = match &manifest {
Some(_) => ProjectIdentity::Manifest {
instance: entry_id.instance.clone(),
@@ -286,6 +322,11 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
files: loader.files,
packages: loader.packages,
diagnostics: loader.diagnostics,
stdlib: stdlib_info,
official_aliases,
manifest,
lock,
extension_sources,
})
}
@@ -336,7 +377,7 @@ impl Loader {
.or_insert_with(|| package_root.clone());
let source = std::fs::read_to_string(&path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
let analysis = analyze_source(&module_id.to_string(), &source);
let analysis = marqdo_frontend::analyze_source_for_program(&module_id.to_string(), &source);
let imports: Vec<(String, String, marqdo_span::Span)> = analysis
.document
.frontmatter()
@@ -360,7 +401,16 @@ impl Loader {
.unwrap_or_default();
for (alias, target, span) in imports {
let resolved = if let Some(alias_name) = target.strip_prefix('@') {
let resolved = if let Some(std_target) = target.strip_prefix("std:") {
match &self.stdlib {
Some(stdlib) => stdlib.resolve(std_target),
None => Err(format!(
"no bundled stdlib is available for `{target}`; install the official \
CLI bundle or set {STDLIB_DIR_ENV}",
STDLIB_DIR_ENV = crate::stdlib::STDLIB_DIR_ENV
)),
}
} else if let Some(alias_name) = target.strip_prefix('@') {
self.resolver.resolve_alias_from(package, alias_name)
} else {
self.resolver.resolve_relative(package, &path, &target)
@@ -465,4 +515,170 @@ impl Loader {
}
Ok(module_id)
}
/// Resolve the official stdlib public aliases referenced by the program.
///
/// Only the verified `stdlib.json` metadata can declare an official alias;
/// a third-party package cannot claim `打印`/`print` or `std.*`. Modules are
/// loaded only when the program references one of the alias names, so an
/// ordinary program does not grow its module graph or startup cost.
fn load_official_aliases(&mut self) -> Result<Vec<OfficialAlias>, String> {
let Some(stdlib) = self.stdlib.clone() else {
return Ok(Vec::new());
};
if stdlib.public_aliases().is_empty() {
return Ok(Vec::new());
}
let referenced = referenced_identifiers(&self.program);
let mut aliases = Vec::new();
for alias in stdlib.public_aliases() {
if !alias
.public_names
.iter()
.any(|name| referenced.contains(name))
{
continue;
}
let resolved = stdlib.resolve(&alias.target_module)?;
let module_id = self.load_module(&resolved.package, &resolved.relative_path)?;
let Some(module) = self.program.module(&module_id) else {
return Err(format!(
"stdlib public alias target module `{}` was not loaded",
alias.target_module
));
};
let Some(function) = module.function(&alias.target_function) else {
return Err(format!(
"stdlib public alias `{}` target `{}::{}` does not exist",
alias.public_names.join("/"),
alias.target_module,
alias.target_function
));
};
if let Some(expected) = &alias.expected_signature {
let parsed =
marqdo_frontend::signature::parse(expected, marqdo_span::Span::default());
if parsed.has_errors() {
return Err(format!(
"stdlib public alias `{}` has an invalid expected_signature `{expected}`",
alias.public_names.join("/")
));
}
let expected_names: Vec<&str> = parsed
.params
.iter()
.map(|param| param.name.as_str())
.collect();
let actual_names: Vec<&str> = function
.params
.iter()
.map(|param| param.name.as_str())
.collect();
if expected_names != actual_names
|| function.signature != marqdo_ir::SignatureKind::Explicit
{
return Err(format!(
"stdlib public alias `{}` expected signature `{expected}` does not match \
target `{}::{}` (params {:?}, kind {:?})",
alias.public_names.join("/"),
alias.target_module,
alias.target_function,
actual_names,
function.signature
));
}
}
aliases.push(OfficialAlias {
public_names: alias.public_names.clone(),
function: function.id.clone(),
signature: marqdo_ir::callable::CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
owner_package: module_id.instance.clone(),
effects_requested: alias.effects.clone(),
});
}
Ok(aliases)
}
}
/// Collect every identifier referenced by a program.
///
/// This is a conservative "is this alias used at all?" scan; it only decides
/// whether an official alias target module should be loaded. It does not decide
/// call targets (that is the single binding pass).
fn referenced_identifiers(program: &Program) -> std::collections::BTreeSet<String> {
let mut names = std::collections::BTreeSet::new();
for module in program.modules.values() {
for function in &module.functions {
for param in &function.params {
if let Some(default) = &param.default {
collect_identifiers_expr(default, &mut names);
}
}
collect_identifiers_stmts(&function.body, &mut names);
}
}
names
}
fn collect_identifiers_stmts(stmts: &[Stmt], names: &mut std::collections::BTreeSet<String>) {
for stmt in stmts {
match stmt {
Stmt::Assign { target, value, .. } => {
if let PlaceTarget::Index { base, index, .. } = target {
collect_identifiers_expr(base, names);
collect_identifiers_expr(index, names);
}
collect_identifiers_expr(value, names);
}
Stmt::Eval { expr, .. } | Stmt::Return { value: expr, .. } => {
collect_identifiers_expr(expr, names)
}
Stmt::Branch { arms, .. } => {
for arm in arms {
collect_identifiers_expr(&arm.condition, names);
collect_identifiers_stmts(&arm.body, names);
}
}
Stmt::Loop {
condition, body, ..
} => {
collect_identifiers_expr(condition, names);
collect_identifiers_stmts(body, names);
}
}
}
}
fn collect_identifiers_expr(expr: &Expr, names: &mut std::collections::BTreeSet<String>) {
match expr {
Expr::Ident(ident) => {
names.insert(ident.name.clone());
}
Expr::List(items) => items
.iter()
.for_each(|item| collect_identifiers_expr(item, names)),
Expr::Record(entries) => entries
.iter()
.for_each(|entry| collect_identifiers_expr(&entry.value, names)),
Expr::Unary { operand, .. } => collect_identifiers_expr(operand, names),
Expr::Binary { left, right, .. } => {
collect_identifiers_expr(left, names);
collect_identifiers_expr(right, names);
}
Expr::Member { base, .. } => collect_identifiers_expr(base, names),
Expr::Index { base, index, .. } => {
collect_identifiers_expr(base, names);
collect_identifiers_expr(index, names);
}
Expr::Call { callee, args, .. } => {
collect_identifiers_expr(callee, names);
for arg in args {
collect_identifiers_expr(&arg.value, names);
}
}
Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {}
}
}
+75 -7
View File
@@ -7,8 +7,13 @@
mod analysis;
mod args;
mod commands;
mod extension_descriptors;
mod extension_selection;
mod loader;
mod output;
mod project_prepare;
mod provider_manifest;
mod stdlib;
mod tool;
mod trace;
@@ -22,7 +27,7 @@ use clap::{Args, Parser, Subcommand};
name = "marqdo",
version,
about = "Markdown-native programming language (independent Rust interpreter)",
long_about = "Marqdo executes Markdown documents whose AST structures carry program meaning. `check` and `inspect` never execute project code; `run` and `call` execute through the capability host."
long_about = "Marqdo executes .mq.md documents: headings declare @exec/@knowledge modes, Strong/Emph/inline Code carry one statement each, and if/else/while/end/return/params decide control flow. `check` and `inspect` never execute project code; `run` and `call` execute through the capability host."
)]
struct Cli {
#[command(subcommand)]
@@ -85,9 +90,21 @@ struct SandboxArgs {
/// Grant read access to a project-relative glob (repeatable).
#[arg(long = "allow-read", value_name = "GLOB")]
allow_read: Vec<String>,
/// Grant network access to a host name or IP literal (repeatable, ADR-0034/0047).
#[arg(long = "allow-net", value_name = "HOST")]
allow_net: Vec<String>,
/// Grant write access to a project-relative glob (repeatable).
#[arg(long = "allow-write", value_name = "GLOB")]
allow_write: Vec<String>,
/// Grant read access to an environment variable (repeatable, ADR-0043).
#[arg(long = "allow-env", value_name = "NAME")]
allow_env: Vec<String>,
/// Grant execution of an exact program path (repeatable, ADR-0044).
#[arg(long = "allow-process", value_name = "PROGRAM")]
allow_process: Vec<String>,
/// Grant OS entropy reads (ADR-0046).
#[arg(long = "allow-random")]
allow_random: bool,
/// Grant explicit foreign kernel execution.
#[arg(long = "allow-foreign")]
allow_foreign: bool,
@@ -103,12 +120,28 @@ struct SandboxArgs {
/// Override the program output byte limit.
#[arg(long = "max-output")]
max_output: Option<usize>,
/// Override the total committed addressable-memory budget in bytes.
#[arg(long = "max-memory", value_name = "BYTES")]
max_memory: Option<usize>,
/// Override the per-region committed addressable-memory budget in bytes.
#[arg(long = "max-region-memory", value_name = "BYTES")]
max_region_memory: Option<usize>,
/// Wall-clock timeout in seconds.
#[arg(long)]
timeout: Option<u64>,
/// Explicitly trusted plugin manifest/directory to load (repeatable).
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Explicitly selected resource provider v2 manifest (repeatable).
///
/// Selecting a provider never authorizes it; `--allow-provider NAME` is
/// required as well. `check`/`inspect` do not load providers.
#[arg(long = "provider", value_name = "PATH")]
provider: Vec<PathBuf>,
/// Grant one selected resource provider by its exact manifest name
/// (repeatable; wildcards are not supported).
#[arg(long = "allow-provider", value_name = "NAME")]
allow_provider: Vec<String>,
/// Write a versioned Trace v2 file for this run.
#[arg(long = "trace-file", value_name = "PATH")]
trace_file: Option<PathBuf>,
@@ -131,14 +164,22 @@ impl SandboxArgs {
commands::SandboxSettings {
mode: self.mode.clone(),
allow_read: self.allow_read.clone(),
allow_net: self.allow_net.clone(),
allow_write: self.allow_write.clone(),
allow_env: self.allow_env.clone(),
allow_process: self.allow_process.clone(),
allow_random: self.allow_random,
allow_foreign: self.allow_foreign,
allow_plugin: self.allow_plugin.clone(),
fuel: self.fuel,
stack: self.stack,
max_output: self.max_output,
max_memory: self.max_memory,
max_region_memory: self.max_region_memory,
timeout: self.timeout,
plugins: self.plugin.clone(),
providers: self.provider.clone(),
allow_provider: self.allow_provider.clone(),
trust_native_plugin: self.trust_native_plugin,
trace_file: self.trace_file.clone(),
trace_max_events: self.trace_max_events,
@@ -191,7 +232,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Write the public Analysis v1 projection (only on successful check).
/// Write the public Analysis v2 projection (only on successful check).
#[arg(long, value_name = "PATH")]
emit: Option<PathBuf>,
/// Machine readable JSON output.
@@ -221,6 +262,12 @@ struct InspectArgs {
/// Print sandbox/platform capability report.
#[arg(long)]
platform: bool,
/// Print declared/loaded extension identities (never grants).
#[arg(long)]
extensions: bool,
/// Explicitly selected plugin manifest for extension inspection (repeatable).
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Machine readable JSON output.
#[arg(long)]
json: bool,
@@ -333,7 +380,7 @@ struct ToolRemoveArgs {
#[derive(Args)]
struct SyncArgs {
/// Fail instead of silently updating when the lockfile is stale.
/// Do not fetch pinned Git revisions; verify and materialize only from the local cache.
#[arg(long)]
locked: bool,
/// Machine readable JSON output.
@@ -342,8 +389,29 @@ struct SyncArgs {
}
fn main() {
// The interpreter and the bundled pure stdlib recurse on the parse/execute
// path. Windows gives the main thread 1 MiB by default (Linux/macOS use
// 8 MiB), which overflowed on the regex self-test. Run the CLI on an
// explicit 8 MiB thread on every platform so behavior does not depend on
// the host's main-thread default.
const STACK_BYTES: usize = 8 * 1024 * 1024;
let code = match std::thread::Builder::new()
.name("marqdo-main".to_string())
.stack_size(STACK_BYTES)
.spawn(dispatch)
{
Ok(handle) => handle.join().unwrap_or(101),
Err(error) => {
eprintln!("error: cannot start the marqdo main thread: {error}");
1
}
};
std::process::exit(code);
}
fn dispatch() -> i32 {
let cli = Cli::parse();
let code = match cli.command {
match cli.command {
Command::Init(args) => commands::init(args.dir.as_deref()),
Command::Check(args) => commands::check(
args.file.as_deref(),
@@ -360,8 +428,9 @@ fn main() {
ir: args.ir,
refs: args.refs,
platform: args.platform,
extensions: args.extensions,
};
commands::inspect(args.file.as_deref(), &flags, args.json)
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
}
Command::Run(args) => commands::execute(
args.file.as_deref(),
@@ -408,6 +477,5 @@ fn main() {
Command::PluginWorker(args) => {
marqdo_plugin_abi::worker::serve(&args.manifest, &args.base_dir)
}
};
std::process::exit(code);
}
}
+186
View File
@@ -0,0 +1,186 @@
//! The single `prepare` composition-root step (RFC-EXT-0001 §4.4, §18.2).
//!
//! Order of operations (T1–T5 of the RFC):
//!
//! 1. load the Markdown/package graph (read only, no execution);
//! 2. read static extension descriptors (never `dlopen`/spawn);
//! 3. build the unique [`CallableRegistry`] and reject static conflicts;
//! 4. run the single program-wide call binding pass;
//! 5. produce a [`PreparedProgram`] consumed by `check`, `run`, `call`,
//! `inspect` and Analysis.
//!
//! `run` may only assemble the Host and start workers after this returns.
use std::path::PathBuf;
use marqdo_ir::callable::CallableRegistry;
use marqdo_package::{ExtensionKind, LockedExtension};
use crate::extension_descriptors::{read_plugin_descriptors, PrepareError, StaticPluginSet};
use crate::extension_selection;
use crate::loader::{self, FileDiagnostic, LoadedProject};
/// Options that influence static preparation.
#[derive(Debug, Clone, Default)]
pub struct PrepareOptions {
/// Explicit `--plugin` manifests (repeatable, no implicit discovery).
pub plugins: Vec<PathBuf>,
}
/// A statically prepared program: everything `check`/`run`/`inspect` share.
pub struct PreparedProgram {
/// Loaded project graph with authoritative diagnostics.
pub loaded: LoadedProject,
/// Static plugin descriptors (identity only; no binary loaded).
pub plugins: StaticPluginSet,
/// Unique callable registry used by the binding pass.
///
/// Kept on the prepared value so later consumers (`inspect --extensions`,
/// evidence) can report the same static table without rebuilding it.
#[allow(dead_code)]
pub registry: CallableRegistry,
/// Static identities of the declared extensions, already compared with the
/// lock when one is present (never grants). Consumed by
/// `inspect --extensions` and evidence.
#[allow(dead_code)]
pub extension_identities: Vec<LockedExtension>,
}
/// Prepare one document without executing any project or extension code.
pub fn prepare(
file: Option<&std::path::Path>,
options: &PrepareOptions,
) -> Result<PreparedProgram, PrepareError> {
// T1: static module/package loading. No call diagnostics are produced by
// the loader; the single binding pass below owns them.
let mut loaded = loader::load(file.unwrap_or_else(|| std::path::Path::new("index.mq.md")))
.map_err(|message| default_load_error(&message))?;
// T2: extension descriptors are read from manifests only. Explicit CLI
// `--plugin` paths are merged with the project's declared and locked
// activation sources; CLI paths remain a development form and grant
// nothing by themselves.
let mut plugin_paths = options.plugins.clone();
for extension in &loaded.extension_sources {
if extension.kind == ExtensionKind::Plugin {
plugin_paths.push(extension.path.clone());
}
}
plugin_paths.sort();
plugin_paths.dedup();
let plugins = read_plugin_descriptors(&plugin_paths)?;
// T3a: declared extensions must have a locked identity (lock v4). The
// declaration is activation, not authorization; a mismatched/missing lock
// is fail-closed rather than silently "latest".
let extension_identities =
extension_selection::extension_identities(&loaded.extension_sources)?;
if !loaded.extension_sources.is_empty() {
match &loaded.lock {
Some(lock) => {
lock.validate_extension_declarations(
loaded
.manifest
.as_ref()
.expect("extension sources require a project manifest"),
)
.map_err(|message| PrepareError::load("ext.extension_lock_mismatch", message))?;
extension_selection::validate_against_lock(lock, &extension_identities)?;
}
None => {
return Err(PrepareError::load(
"ext.extension_lock_mismatch",
format!(
"the project declares {} extension(s) but marqdo.lock is missing; run `marqdo lock` first",
loaded.extension_sources.len()
),
));
}
}
}
// T3: unique static table. Duplicate exports/builtin shadowing are rejected
// before any call site can be bound.
for descriptor in plugins.descriptors() {
if loaded
.program
.external_callable(&descriptor.public_name)
.is_some()
{
return Err(PrepareError::option(
"ext.duplicate_callable",
format!(
"plugin export `{}` is declared more than once",
descriptor.public_name
),
));
}
if marqdo_ir::builtins::find(&descriptor.public_name).is_some() {
return Err(PrepareError::option(
"ext.duplicate_callable",
format!(
"plugin export `{}` conflicts with a builtin; plugins may not shadow builtins",
descriptor.public_name
),
));
}
loaded.program.external_callables.push(descriptor);
}
let mut registry = CallableRegistry::try_from_program(&loaded.program).map_err(|conflict| {
PrepareError::option(
"ext.duplicate_callable",
format!("static callable table conflict: {conflict}"),
)
})?;
// Official stdlib public aliases (ADR-0058) are ordinary Marqdo bindings.
for alias in &loaded.official_aliases {
registry
.insert_official_alias(alias.clone())
.map_err(|error| {
PrepareError::option(
"ext.duplicate_callable",
format!("stdlib public alias: {error}"),
)
})?;
}
// T4: exactly one call binding pass for the whole program.
let bound = marqdo_frontend::calls::bind_program_calls(&loaded.program, &registry);
for (module_id, diagnostic) in bound.diagnostics {
let Some(file) = loaded.files.get(&module_id) else {
continue;
};
let (path, source) = (file.path.clone(), file.source.clone());
let duplicate = loaded.diagnostics.iter().any(|existing| {
existing.module_id == module_id
&& existing.diagnostic.code == diagnostic.code
&& existing.diagnostic.span == diagnostic.span
&& existing.diagnostic.message == diagnostic.message
});
if !duplicate {
loaded.diagnostics.push(FileDiagnostic {
module_id,
path,
source,
diagnostic,
});
}
}
loaded.program.set_call_bindings(bound.bindings);
Ok(PreparedProgram {
loaded,
plugins,
registry,
extension_identities,
})
}
fn default_load_error(message: &str) -> PrepareError {
if message.contains("marqdo.lock") || message.contains("lockfile") {
PrepareError::load("project.lock", message)
} else {
PrepareError::option("project.load", message)
}
}
+952
View File
@@ -0,0 +1,952 @@
//! Strict third-party Resource Provider v2 manifests for the CLI composition
//! root (RFC-EXT-0001 §5.3, ADR-0055).
//!
//! This module *reads* `provider.json` schema version 2 and verifies the
//! selected artifact. It never `dlopen`s a library, never spawns a helper and
//! never authorizes a provider: parsing a manifest is not a grant. The v1
//! `marqdo.provider` manifest stays a host-embedding path
//! (`StdHost::register_provider_package`, ADR-0037) and is rejected here with
//! `ext.unsupported_provider_schema`; there is no silent migration.
//!
//! The CLI only accepts the `c-abi-1` + `worker` transport combination and
//! resolves the helper as a sibling of the running `marqdo` executable; PATH
//! lookup is never used. Integrity hashes are content-integrity checks, not
//! publisher authentication.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use marqdo_host::StdHost;
use marqdo_plugin_abi::{HostTarget, TargetTriple};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use crate::extension_descriptors::{
ensure_bundle_relative, verify_bundle_regular_file, verify_sha256, PrepareError,
};
/// Provider manifest file name used by the CLI (`--provider` accepts this file).
pub const PROVIDER_MANIFEST_FILE: &str = "provider.json";
/// Provider manifest schema name.
pub const PROVIDER_SCHEMA: &str = "marqdo.provider";
/// Provider manifest schema version accepted by the CLI.
pub const PROVIDER_SCHEMA_VERSION: u64 = 2;
/// Provider ABI accepted by the CLI (ADR-0036/0038).
pub const PROVIDER_ABI: &str = "c-abi-1";
/// Provider transport accepted by the CLI (ADR-0035/0038).
pub const PROVIDER_TRANSPORT: &str = "worker";
/// Helper executable shipped next to the `marqdo` binary (ADR-0038).
pub const PROVIDER_WORKER_BINARY: &str = "marqdo-provider-worker";
/// Upper bounds for a single provider manifest; these bound parser work only.
pub const MAX_PROVIDER_NAME_BYTES: usize = 128;
pub const MAX_PROVIDER_KINDS: usize = 64;
pub const MAX_PROVIDER_ARTIFACTS: usize = 32;
pub const MAX_PROVIDER_PERMISSIONS: usize = 64;
/// Maximum selected artifact size (256 MiB).
pub const MAX_PROVIDER_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
/// Maximum manifest size (1 MiB); a manifest is metadata, not an artifact.
pub const MAX_PROVIDER_MANIFEST_BYTES: u64 = 1024 * 1024;
/// Core resource kinds owned by the host; third parties may never override
/// them (RFC-EXT-0001 §5.3.1). `stdio`/`file`/`tcp`/`tls`/`udp`/`tcp-listener`
/// are dispatched by `marqdo-host` before the provider registry is consulted.
pub const RESERVED_RESOURCE_KINDS: &[&str] =
&["stdio", "file", "tcp", "tls", "udp", "tcp-listener"];
/// Raw `provider.json` schema version 2 document.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ProviderManifest {
schema: String,
schema_version: u64,
name: String,
version: String,
abi: String,
transport: String,
kinds: Vec<String>,
artifacts: Vec<ManifestArtifact>,
#[serde(default)]
permissions_requested: Vec<String>,
/// Free-form, non-executable metadata. Ignored for execution and never used
/// to select artifacts or grant permissions.
#[serde(rename = "metadata", default)]
_metadata: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestArtifact {
target: String,
path: String,
sha256: String,
}
/// A manifest whose selected artifact has been resolved and verified.
///
/// Producing one requires reading the manifest, checking the schema rules,
/// selecting the artifact for the current host target and verifying the
/// content hash. It still does not grant access and no worker has been started.
#[derive(Debug, Clone)]
pub struct VerifiedProvider {
/// Stable grant name (`--allow-provider NAME` must match exactly).
pub name: String,
/// Strict SemVer version declared by the manifest.
pub version: String,
/// Non-reserved resource kinds served by this provider.
pub kinds: Vec<String>,
/// Canonical manifest path.
pub manifest_path: PathBuf,
/// Canonical bundle directory (manifest parent).
pub base_dir: PathBuf,
/// `sha256:<hex>` of the manifest bytes at verification time.
pub manifest_digest: String,
/// Selected transport (`worker` in v2).
pub transport: String,
/// Canonical path of the selected, hash-verified artifact.
pub selected_artifact_path: PathBuf,
/// Bundle-relative artifact path exactly as declared.
pub selected_artifact_relative: String,
/// Lowercase hex sha256 declared by the manifest.
pub selected_artifact_sha256: String,
/// Target triple the selected artifact was built for.
pub selected_target: String,
}
impl VerifiedProvider {
/// Re-verify the manifest bytes and the selected artifact immediately
/// before the provider worker is spawned.
///
/// `run` must never trust a hash it checked earlier: another process can
/// replace the manifest or the artifact between selection and use.
pub fn reverify(&self) -> Result<(), PrepareError> {
let bytes = std::fs::read(&self.manifest_path).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!(
"provider manifest `{}` could not be re-read before use: {error}",
self.manifest_path.display()
),
)
})?;
if bytes.len() as u64 > MAX_PROVIDER_MANIFEST_BYTES {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"provider manifest `{}` grew beyond the {MAX_PROVIDER_MANIFEST_BYTES}-byte limit before use",
self.manifest_path.display()
),
));
}
let digest = manifest_digest(&bytes);
if digest != self.manifest_digest {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"provider manifest `{}` changed after verification (expected {}, actual {}); refusing to start its worker",
self.manifest_path.display(),
self.manifest_digest,
digest
),
));
}
let artifact =
verify_bundle_regular_file(&self.base_dir, &self.selected_artifact_relative)?;
if artifact != self.selected_artifact_path {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"provider `{}` artifact `{}` now resolves to `{}` instead of the verified `{}`",
self.name,
self.selected_artifact_relative,
artifact.display(),
self.selected_artifact_path.display()
),
));
}
check_artifact_size(&artifact)?;
verify_sha256(&artifact, &self.selected_artifact_sha256)?;
Ok(())
}
}
/// Read, validate and verify every explicitly selected `--provider` manifest.
///
/// No worker is spawned and no artifact is executed. Duplicate provider names
/// and duplicate resource kinds across providers are rejected deterministically
/// (the returned list is sorted by provider name) so a later registration can
/// never overwrite an earlier one.
pub fn read_provider_manifests(paths: &[PathBuf]) -> Result<Vec<VerifiedProvider>, PrepareError> {
let mut manifest_paths: BTreeSet<PathBuf> = BTreeSet::new();
for path in paths {
if path.is_dir() {
return Err(PrepareError::option(
"ext.manifest_unreadable",
format!(
"--provider `{}` must name a `{PROVIDER_MANIFEST_FILE}` file, not a directory",
path.display()
),
));
}
let canonical = path.canonicalize().map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot open provider manifest `{}`: {error}",
path.display()
),
)
})?;
manifest_paths.insert(canonical);
}
let mut providers = Vec::with_capacity(manifest_paths.len());
for path in manifest_paths {
providers.push(read_provider_manifest(&path)?);
}
// Deterministic conflict resolution independent of CLI argument order.
providers.sort_by(|left, right| {
(&left.name, &left.manifest_digest).cmp(&(&right.name, &right.manifest_digest))
});
let mut unique: Vec<VerifiedProvider> = Vec::with_capacity(providers.len());
for provider in providers {
if let Some(existing) = unique.iter().find(|item| item.name == provider.name) {
if existing.manifest_digest != provider.manifest_digest {
return Err(PrepareError::option(
"ext.duplicate_provider",
format!(
"provider name `{}` is selected with two different manifests (`{}` and `{}`); \
explicit aliases are not implemented, so this is rejected",
provider.name,
existing.manifest_path.display(),
provider.manifest_path.display()
),
));
}
// The exact same declaration selected twice is idempotent.
continue;
}
unique.push(provider);
}
let mut claimed_kinds: BTreeMap<String, String> = BTreeMap::new();
for provider in &unique {
for kind in &provider.kinds {
if let Some(owner) = claimed_kinds.get(kind) {
return Err(PrepareError::option(
"ext.duplicate_provider_kind",
format!(
"resource kind `{kind}` is declared by both provider `{owner}` and provider `{}`; \
duplicate kinds are rejected before any worker starts",
provider.name
),
));
}
claimed_kinds.insert(kind.clone(), provider.name.clone());
}
}
Ok(unique)
}
fn read_provider_manifest(canonical_path: &Path) -> Result<VerifiedProvider, PrepareError> {
let metadata = std::fs::metadata(canonical_path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot stat provider manifest `{}`: {error}",
canonical_path.display()
),
)
})?;
if metadata.len() > MAX_PROVIDER_MANIFEST_BYTES {
return Err(PrepareError::option(
"ext.manifest_invalid",
format!(
"provider manifest `{}` is {} bytes, larger than the {MAX_PROVIDER_MANIFEST_BYTES}-byte limit",
canonical_path.display(),
metadata.len()
),
));
}
let bytes = std::fs::read(canonical_path).map_err(|error| {
PrepareError::option(
"ext.manifest_unreadable",
format!(
"cannot read provider manifest `{}`: {error}",
canonical_path.display()
),
)
})?;
let digest = manifest_digest(&bytes);
let value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|error| {
PrepareError::option(
"ext.manifest_invalid",
format!(
"provider manifest `{}` is not valid UTF-8 JSON: {error}",
canonical_path.display()
),
)
})?;
// Schema/version gate runs before structural parsing so a v1 (or future)
// manifest gets the stable `ext.unsupported_provider_schema` code instead
// of a generic field error.
let schema = value.get("schema").and_then(serde_json::Value::as_str);
if schema != Some(PROVIDER_SCHEMA) {
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider manifest `{}` does not declare `schema: \"{PROVIDER_SCHEMA}\"`; \
the CLI accepts schema version {PROVIDER_SCHEMA_VERSION} only",
canonical_path.display()
),
));
}
let schema_version = value
.get("schema_version")
.and_then(serde_json::Value::as_u64);
if schema_version != Some(PROVIDER_SCHEMA_VERSION) {
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider manifest `{}` declares schema_version {}; the CLI accepts {PROVIDER_SCHEMA_VERSION} only \
(v1 and future versions are rejected, there is no silent migration)",
canonical_path.display(),
schema_version
.map(|version| version.to_string())
.unwrap_or_else(|| "<missing>".to_string())
),
));
}
let manifest: ProviderManifest = serde_json::from_value(value).map_err(|error| {
PrepareError::option(
"ext.manifest_invalid",
format!(
"provider manifest `{}` is not a valid {PROVIDER_SCHEMA} v{PROVIDER_SCHEMA_VERSION} document: {error}",
canonical_path.display()
),
)
})?;
if manifest.schema != PROVIDER_SCHEMA || manifest.schema_version != PROVIDER_SCHEMA_VERSION {
// Unreachable after the Value-level gate; kept fail-closed.
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider manifest `{}` uses an unsupported schema",
canonical_path.display()
),
));
}
validate_manifest(&manifest, canonical_path)?;
let base_dir = canonical_path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
let selected_target = HostTarget::current().triple().to_string();
let artifact = manifest
.artifacts
.iter()
.find(|artifact| artifact.target == selected_target)
.ok_or_else(|| {
PrepareError::option(
"ext.no_matching_artifact",
format!(
"provider `{}` has no artifact for the current target `{selected_target}`; \
other platforms are never substituted",
manifest.name
),
)
})?;
let artifact_relative = normalise_artifact_path(&manifest.name, &artifact.path)?;
let artifact_path = verify_bundle_regular_file(&base_dir, &artifact_relative)?;
check_artifact_size(&artifact_path)?;
verify_sha256(&artifact_path, &artifact.sha256)?;
Ok(VerifiedProvider {
name: manifest.name,
version: manifest.version,
kinds: manifest.kinds,
manifest_path: canonical_path.to_path_buf(),
base_dir,
manifest_digest: digest,
transport: manifest.transport,
selected_artifact_path: artifact_path,
selected_artifact_relative: artifact_relative,
selected_artifact_sha256: artifact.sha256.to_ascii_lowercase(),
selected_target,
})
}
fn validate_manifest(
manifest: &ProviderManifest,
manifest_path: &Path,
) -> Result<(), PrepareError> {
let invalid = |message: String| {
PrepareError::option(
"ext.manifest_invalid",
format!("provider manifest `{}`: {message}", manifest_path.display()),
)
};
validate_provider_name(&manifest.name)
.map_err(|error| invalid(format!("invalid provider name: {error}")))?;
if RESERVED_RESOURCE_KINDS.contains(&manifest.name.as_str()) {
return Err(invalid(format!(
"provider name `{}` is a reserved core resource kind",
manifest.name
)));
}
semver::Version::parse(&manifest.version).map_err(|error| {
invalid(format!(
"version `{}` is not strict SemVer: {error}",
manifest.version
))
})?;
if manifest.abi != PROVIDER_ABI {
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider `{}` declares abi `{}`; schema v{PROVIDER_SCHEMA_VERSION} accepts `{PROVIDER_ABI}` only",
manifest.name, manifest.abi
),
));
}
if manifest.transport != PROVIDER_TRANSPORT {
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider `{}` declares transport `{}`; schema v{PROVIDER_SCHEMA_VERSION} accepts `{PROVIDER_TRANSPORT}` only",
manifest.name, manifest.transport
),
));
}
if manifest.kinds.is_empty() {
return Err(invalid(
"kinds must declare at least one resource kind".to_string(),
));
}
if manifest.kinds.len() > MAX_PROVIDER_KINDS {
return Err(invalid(format!(
"kinds declares more than {MAX_PROVIDER_KINDS} entries"
)));
}
let mut kinds = BTreeSet::new();
for kind in &manifest.kinds {
validate_provider_name(kind)
.map_err(|error| invalid(format!("invalid resource kind `{kind}`: {error}")))?;
if RESERVED_RESOURCE_KINDS.contains(&kind.as_str()) {
return Err(invalid(format!(
"resource kind `{kind}` is reserved by the host and cannot be overridden by a provider"
)));
}
if !kinds.insert(kind.clone()) {
return Err(invalid(format!(
"resource kind `{kind}` is declared more than once"
)));
}
}
if manifest.artifacts.is_empty() {
return Err(invalid(
"artifacts must declare at least one target artifact".to_string(),
));
}
if manifest.artifacts.len() > MAX_PROVIDER_ARTIFACTS {
return Err(invalid(format!(
"artifacts declares more than {MAX_PROVIDER_ARTIFACTS} entries"
)));
}
let mut targets = BTreeSet::new();
for artifact in &manifest.artifacts {
let triple = TargetTriple::parse(&artifact.target).map_err(|error| {
invalid(format!(
"artifact target `{}` is not a target triple: {error}",
artifact.target
))
})?;
if !targets.insert(triple.to_string()) {
return Err(invalid(format!(
"artifact target `{triple}` is declared more than once"
)));
}
if !is_lowercase_sha256(&artifact.sha256) {
return Err(invalid(format!(
"artifact for target `{:?}` must declare a 64-character lowercase hex sha256",
artifact.target
)));
}
}
if manifest.permissions_requested.len() > MAX_PROVIDER_PERMISSIONS {
return Err(invalid(format!(
"permissions_requested declares more than {MAX_PROVIDER_PERMISSIONS} entries"
)));
}
let mut permissions = BTreeSet::new();
for permission in &manifest.permissions_requested {
if !is_known_capability(permission) && !is_vendor_capability(permission) {
return Err(invalid(format!(
"permissions_requested entry `{permission}` is not a known capability or a dotted vendor capability"
)));
}
if !permissions.insert(permission.clone()) {
return Err(invalid(format!(
"permission `{permission}` is declared more than once"
)));
}
}
// `metadata` is intentionally not validated: it has no execution meaning.
Ok(())
}
/// Validate a dotted provider/kind name using the plugin name grammar
/// (ASCII lowercase segment start, then lowercase/digits/`-`/`_`).
pub fn validate_provider_name(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("must not be empty".to_string());
}
if name.len() > MAX_PROVIDER_NAME_BYTES {
return Err(format!(
"must not be longer than {MAX_PROVIDER_NAME_BYTES} bytes"
));
}
for segment in name.split('.') {
if segment.is_empty() {
return Err(format!("`{name}` contains an empty segment"));
}
let mut bytes = segment.bytes();
let first = bytes.next().unwrap_or(b'a');
if !first.is_ascii_lowercase() {
return Err(format!(
"`{name}` must start every `.`-separated segment with a lowercase ASCII letter"
));
}
if !bytes.all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' || byte == b'_'
}) {
return Err(format!(
"`{name}` may only contain lowercase ASCII letters, digits, `-` and `_`"
));
}
}
Ok(())
}
/// Reject absolute paths and `..` traversal in declared artifact paths.
fn normalise_artifact_path(provider: &str, path: &str) -> Result<String, PrepareError> {
ensure_bundle_relative(path).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!("provider `{provider}` artifact path `{path}` is invalid: {error}"),
)
})?;
Ok(path.to_string())
}
fn check_artifact_size(path: &Path) -> Result<(), PrepareError> {
let metadata = std::fs::metadata(path).map_err(|error| {
PrepareError::load(
"ext.artifact_integrity",
format!(
"cannot stat provider artifact `{}`: {error}",
path.display()
),
)
})?;
if metadata.len() > MAX_PROVIDER_ARTIFACT_BYTES {
return Err(PrepareError::load(
"ext.artifact_integrity",
format!(
"provider artifact `{}` is {} bytes, larger than the {MAX_PROVIDER_ARTIFACT_BYTES}-byte limit",
path.display(),
metadata.len()
),
));
}
Ok(())
}
fn is_lowercase_sha256(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
fn is_known_capability(name: &str) -> bool {
marqdo_plugin_abi::KNOWN_CAPABILITIES.contains(&name)
}
/// A dotted vendor capability proposal (validation only, never a grant).
fn is_vendor_capability(name: &str) -> bool {
let segments: Vec<&str> = name.split('.').collect();
if segments.len() < 3 {
return false;
}
if matches!(
segments[0],
"console" | "math" | "fs" | "net" | "process" | "log" | "clock" | "random"
) {
return false;
}
segments.iter().all(|segment| {
!segment.is_empty()
&& segment.bytes().enumerate().all(|(index, byte)| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || (byte == b'-' && index > 0)
})
})
}
fn manifest_digest(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
hex.push_str(&format!("{byte:02x}"));
}
format!("sha256:{hex}")
}
/// Whether the provider `worker` transport is supported on this build.
///
/// RFC-EXT-0001 §5.6 makes Linux x86_64 the mandatory lane. Other targets stay
/// compilable but must fail closed with `ext.platform_unsupported` instead of
/// pretending a helper works.
pub fn provider_worker_platform_supported() -> bool {
cfg!(all(target_os = "linux", target_arch = "x86_64"))
}
/// Resolve the provider helper shipped next to the running `marqdo` executable.
///
/// Resolution is *only* the sibling file: there is no PATH lookup and no
/// directory search (RFC-EXT-0001 §5.4.5). A missing helper is
/// `ext.worker_unavailable`, never a fallback to in-process native loading.
pub fn provider_worker_executable() -> Result<PathBuf, PrepareError> {
if !provider_worker_platform_supported() {
return Err(PrepareError::load(
"ext.platform_unsupported",
format!(
"the resource provider worker transport is supported on linux/x86_64 only in this release; \
this build targets {}/{}",
std::env::consts::OS,
std::env::consts::ARCH
),
));
}
let executable = std::env::current_exe().map_err(|error| {
PrepareError::load(
"ext.worker_unavailable",
format!(
"cannot locate the marqdo executable to find `{PROVIDER_WORKER_BINARY}`: {error}"
),
)
})?;
let directory = executable.parent().ok_or_else(|| {
PrepareError::load(
"ext.worker_unavailable",
format!(
"the marqdo executable `{}` has no parent directory",
executable.display()
),
)
})?;
let helper = directory.join(format!(
"{PROVIDER_WORKER_BINARY}{}",
std::env::consts::EXE_SUFFIX
));
match std::fs::metadata(&helper) {
Ok(metadata) if metadata.is_file() => Ok(helper),
_ => Err(PrepareError::load(
"ext.worker_unavailable",
format!(
"the resource provider worker helper `{}` is missing; it must be shipped next to the \
marqdo executable (PATH lookup is not allowed)",
helper.display()
),
)),
}
}
/// Check the exact `--allow-provider` grant, re-verify the manifest and
/// artifact, then register the existing worker resource-provider transport.
///
/// The grant check is repeated here (it was already checked during pre-spawn
/// verification) so no caller can register an ungranted provider. The provider
/// is always registered through
/// [`StdHost::register_worker_resource_provider`]; this path never falls back
/// to the trusted in-process C ABI or a native library.
pub fn load_resource_provider_into_host(
host: &mut StdHost,
provider: &VerifiedProvider,
allow_provider: &[String],
) -> Result<(), PrepareError> {
if !allow_provider.iter().any(|grant| grant == &provider.name) {
return Err(PrepareError::load(
"permission.denied",
format!(
"resource provider `{}` was selected but not granted; add --allow-provider {}",
provider.name, provider.name
),
));
}
if provider.transport != PROVIDER_TRANSPORT {
return Err(PrepareError::option(
"ext.unsupported_provider_schema",
format!(
"provider `{}` transport `{}` cannot be loaded by the CLI",
provider.name, provider.transport
),
));
}
// Re-verify immediately before use; never trust an earlier hash.
provider.reverify()?;
let worker = provider_worker_executable()?;
let kinds: Vec<&str> = provider.kinds.iter().map(String::as_str).collect();
let args = vec![provider
.selected_artifact_path
.to_string_lossy()
.into_owned()];
host.register_worker_resource_provider(&provider.name, &kinds, &worker, &args)
.map_err(|error| {
PrepareError::load(
"ext.worker_unavailable",
format!(
"cannot start the worker for resource provider `{}` v{} (target {}) using `{}`: {}",
provider.name,
provider.version,
provider.selected_target,
worker.display(),
error.message
),
)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn tempdir(tag: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!(
"marqdo-provider-manifest-{}-{tag}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
));
std::fs::create_dir_all(&path).unwrap();
path
}
fn write_manifest(dir: &Path, manifest: &str) -> PathBuf {
let path = dir.join(PROVIDER_MANIFEST_FILE);
std::fs::write(&path, manifest).unwrap();
path
}
fn artifact(dir: &Path, name: &str, bytes: &[u8]) -> (String, String) {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
let mut hasher = Sha256::new();
hasher.update(bytes);
let mut hex = String::new();
for byte in hasher.finalize() {
hex.push_str(&format!("{byte:02x}"));
}
(name.to_string(), hex)
}
fn manifest_text(name: &str, kinds: &[&str], path: &str, sha: &str) -> String {
let kinds = kinds
.iter()
.map(|kind| format!("\"{kind}\""))
.collect::<Vec<_>>()
.join(", ");
format!(
r#"{{
"schema": "marqdo.provider",
"schema_version": 2,
"name": "{name}",
"version": "0.1.0",
"abi": "c-abi-1",
"transport": "worker",
"kinds": [{kinds}],
"artifacts": [
{{"target": "{}", "path": "{path}", "sha256": "{sha}"}}
],
"permissions_requested": []
}}"#,
HostTarget::current().triple()
)
}
#[test]
fn valid_v2_manifest_verifies_artifact() {
let dir = tempdir("valid");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let manifest = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &sha),
);
let providers = read_provider_manifests(&[manifest]).unwrap();
assert_eq!(providers.len(), 1);
assert_eq!(providers[0].name, "demo.sensor");
assert_eq!(
providers[0].selected_target,
HostTarget::current().triple().to_string()
);
assert!(providers[0].manifest_digest.starts_with("sha256:"));
providers[0].reverify().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn v1_manifest_is_rejected_without_migration() {
let dir = tempdir("v1");
let manifest = write_manifest(
&dir,
r#"{"schema":"marqdo.provider","schema_version":1,"name":"cabi","kinds":["cabi.sensor"],"abi":"c-abi-1","library":{"linux":"libcabi.so"}}"#,
);
let error = read_provider_manifests(&[manifest]).unwrap_err();
assert_eq!(error.code, "ext.unsupported_provider_schema");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn missing_target_is_no_matching_artifact() {
let dir = tempdir("target");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let manifest = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &sha).replace(
&HostTarget::current().triple().to_string(),
"aarch64-unknown-linux-gnu",
),
);
let error = read_provider_manifests(&[manifest]).unwrap_err();
assert_eq!(error.code, "ext.no_matching_artifact");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn reserved_kind_is_rejected() {
let dir = tempdir("reserved");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let manifest = write_manifest(&dir, &manifest_text("demo.sensor", &["file"], &path, &sha));
let error = read_provider_manifests(&[manifest]).unwrap_err();
assert_eq!(error.code, "ext.manifest_invalid");
assert!(error.message.contains("reserved"), "{}", error.message);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn traversal_and_digest_mismatch_are_artifact_integrity() {
let dir = tempdir("integrity");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let traversal = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], "../libdemo.so", &sha),
);
let error = read_provider_manifests(&[traversal]).unwrap_err();
assert_eq!(error.code, "ext.artifact_integrity");
let mismatch = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &"0".repeat(64)),
);
let error = read_provider_manifests(&[mismatch]).unwrap_err();
assert_eq!(error.code, "ext.artifact_integrity");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn duplicate_kinds_across_providers_are_rejected() {
let dir = tempdir("duplicate-kind");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let first = write_manifest(
&dir,
&manifest_text("demo.one", &["demo.sensor"], &path, &sha),
);
let second_dir = dir.join("second");
std::fs::create_dir_all(&second_dir).unwrap();
std::fs::copy(dir.join(&path), second_dir.join(&path)).unwrap();
let second = write_manifest(
&second_dir,
&manifest_text("demo.two", &["demo.sensor"], &path, &sha),
);
let error = read_provider_manifests(&[first, second]).unwrap_err();
assert_eq!(error.code, "ext.duplicate_provider_kind");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn duplicate_provider_name_with_different_manifests_is_rejected() {
let dir = tempdir("duplicate-name");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let first = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &sha),
);
let second_dir = dir.join("second");
std::fs::create_dir_all(&second_dir).unwrap();
std::fs::copy(dir.join(&path), second_dir.join(&path)).unwrap();
// Same name, different version => different manifest digest.
let second = write_manifest(
&second_dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &sha)
.replace("\"version\": \"0.1.0\"", "\"version\": \"0.2.0\""),
);
let error = read_provider_manifests(&[first.clone(), second]).unwrap_err();
assert_eq!(error.code, "ext.duplicate_provider");
// Selecting the exact same manifest twice is idempotent.
let providers = read_provider_manifests(&[first.clone(), first]).unwrap();
assert_eq!(providers.len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn unknown_fields_and_bad_names_are_manifest_invalid() {
let dir = tempdir("invalid");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let unknown = write_manifest(
&dir,
&manifest_text("demo.sensor", &["demo.sensor"], &path, &sha).replace(
"\"permissions_requested\": []",
"\"permissions_requested\": [], \"exec\": true",
),
);
let error = read_provider_manifests(&[unknown]).unwrap_err();
assert_eq!(error.code, "ext.manifest_invalid");
let bad_name = write_manifest(
&dir,
&manifest_text("Demo.Sensor", &["demo.sensor"], &path, &sha),
);
let error = read_provider_manifests(&[bad_name]).unwrap_err();
assert_eq!(error.code, "ext.manifest_invalid");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn worker_helper_resolution_only_uses_the_executable_sibling() {
// The real helper is installed next to the CLI binary by the
// integration fixture; this test only asserts the platform/absence
// contract and that a path is never derived from PATH.
if provider_worker_platform_supported() {
let helper = provider_worker_executable();
// In a unit-test binary `current_exe()` is the test binary, so the
// sibling helper is normally absent: the error must be structured.
match helper {
Ok(path) => assert!(path.is_file()),
Err(error) => assert_eq!(error.code, "ext.worker_unavailable"),
}
} else {
let error = provider_worker_executable().unwrap_err();
assert_eq!(error.code, "ext.platform_unsupported");
}
}
}
+474
View File
@@ -0,0 +1,474 @@
//! Bundled standard library discovery, digest verification and `std:` imports.
//!
//! The official CLI ships a fixed `marqdo-stdlib` tree (ADR-0026/CM-A10). This
//! module finds that tree, verifies its declared content digest before any
//! module is loaded, and resolves explicit `std:<relative>` imports to it.
//! Nothing is fetched implicitly and there is no second module search path.
use std::path::{Component, Path, PathBuf};
use marqdo_package::{PackageOrigin, ResolvedModule, ResolvedPackage};
use sha2::{Digest, Sha256};
/// Environment override used by tests and relocatable installations.
pub const STDLIB_DIR_ENV: &str = "MARQDO_STDLIB_DIR";
/// One official bundled-stdlib public alias (ADR-0058).
///
/// The alias table lives in the verified `stdlib.json` metadata, not in Rust
/// source: `打印`/`print` are ordinary `Marqdo` bindings to `io.mq.md::写值`
/// and the runtime no longer special-cases print names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicAlias {
/// Public names that resolve to the target function.
pub public_names: Vec<String>,
/// Package-relative target module (for example `io.mq.md`).
pub target_module: String,
/// Canonical/local target function name.
pub target_function: String,
/// Declared parameter names, used to verify the target signature.
pub expected_signature: Option<String>,
/// Conservative effect request summary.
pub effects: Vec<String>,
}
/// Verified bundled standard library.
#[derive(Debug, Clone)]
pub struct StdlibBundle {
root: PathBuf,
name: String,
version: String,
digest: String,
aliases: Vec<PublicAlias>,
}
impl StdlibBundle {
/// Discover the bundle.
///
/// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid), a `stdlib`
/// directory next to the executable, then the development tree.
pub fn discover() -> Result<Option<Self>, String> {
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
return Self::load(PathBuf::from(dir)).map(Some);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(parent) = exe.parent() {
let candidate = parent.join("stdlib");
if candidate.is_dir() {
return Self::load(candidate).map(Some);
}
}
}
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("stdlib");
if dev.is_dir() {
return Self::load(dev).map(Some);
}
Ok(None)
}
/// Load and verify one bundle directory.
pub fn load(root: impl Into<PathBuf>) -> Result<Self, String> {
let root = root.into();
let root = root.canonicalize().map_err(|error| {
format!("cannot open stdlib directory `{}`: {error}", root.display())
})?;
let manifest_path = root.join("stdlib.json");
let text = std::fs::read_to_string(&manifest_path)
.map_err(|error| format!("cannot read `{}`: {error}", manifest_path.display()))?;
let manifest: serde_json::Value = serde_json::from_str(&text)
.map_err(|error| format!("invalid `{}`: {error}", manifest_path.display()))?;
let name = manifest
.get("name")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("`{}` has no name", manifest_path.display()))?
.to_string();
let version = manifest
.get("version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("`{}` has no version", manifest_path.display()))?
.to_string();
let declared = manifest
.get("digest")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("`{}` has no digest", manifest_path.display()))?
.to_string();
let actual = tree_digest(&root)?;
if declared != actual {
return Err(format!(
"stdlib digest mismatch: declared {declared}, actual {actual}"
));
}
let aliases = parse_public_aliases(&manifest, &manifest_path)?;
let declared_alias_digest = manifest
.get("aliases_digest")
.and_then(serde_json::Value::as_str);
let actual_alias_digest = aliases_digest(&aliases);
match (declared_alias_digest, aliases.is_empty()) {
(Some(declared), _) => {
if declared != actual_alias_digest {
return Err(format!(
"stdlib public-alias metadata digest mismatch: declared {declared}, \
actual {actual_alias_digest}"
));
}
}
(None, false) => {
return Err(format!(
"`{}` declares public_aliases without aliases_digest",
manifest_path.display()
));
}
(None, true) => {}
}
Ok(Self {
root,
name,
version,
digest: actual,
aliases,
})
}
/// Verified official public aliases.
pub fn public_aliases(&self) -> &[PublicAlias] {
&self.aliases
}
/// Bundle root.
pub fn root(&self) -> &Path {
&self.root
}
/// Declared stdlib version.
pub fn version(&self) -> &str {
&self.version
}
/// Verified content digest (`sha256:<hex>`).
pub fn digest(&self) -> &str {
&self.digest
}
/// Logical package identity used for module ids.
pub fn instance_id(&self) -> String {
format!(
"std:{}@{}#{}",
self.name,
self.version,
self.digest.trim_start_matches("sha256:")
)
}
/// Package view consumed by the loader.
pub fn package(&self) -> ResolvedPackage {
ResolvedPackage {
instance_id: self.instance_id(),
name: self.name.clone(),
version: self.version.clone(),
origin: PackageOrigin::Path {
declared: PathBuf::from("stdlib"),
},
revision: None,
content_digest: Some(self.digest.clone()),
module_root: self.root.clone(),
entry_module: "index.mq.md".to_string(),
manifest: None,
}
}
/// Resolve a `std:<relative>` target inside the bundle.
pub fn resolve(&self, target: &str) -> Result<ResolvedModule, String> {
let mut normalised = PathBuf::new();
for component in Path::new(target).components() {
match component {
Component::Normal(part) => normalised.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err(format!(
"stdlib import `{target}` must be a relative path inside the stdlib"
))
}
}
}
if normalised.as_os_str().is_empty() {
return Err("stdlib import must name a module".to_string());
}
if normalised.extension().is_none() {
normalised.set_extension("mq.md");
}
let candidate = self.root.join(&normalised);
let canonical = candidate.canonicalize().map_err(|error| {
format!(
"cannot open stdlib module `{target}` at `{}`: {error}",
candidate.display()
)
})?;
let relative = canonical
.strip_prefix(&self.root)
.map_err(|_| format!("stdlib import `{target}` escapes the stdlib root"))?;
let relative_path = relative
.components()
.map(|component| component.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/");
Ok(ResolvedModule {
package: self.package(),
relative_path,
})
}
}
/// Content digest over all `.mq.md` files: sorted path, NUL, bytes, NUL.
pub fn tree_digest(root: &Path) -> Result<String, String> {
let mut files = Vec::new();
collect_markdown(root, root, &mut files)?;
files.sort();
let mut hasher = Sha256::new();
for (relative, path) in files {
let bytes = std::fs::read(&path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
hasher.update(relative.as_bytes());
hasher.update([0]);
hasher.update(&bytes);
hasher.update([0]);
}
Ok(format!("sha256:{}", hex(&hasher.finalize())))
}
fn collect_markdown(
root: &Path,
dir: &Path,
out: &mut Vec<(String, PathBuf)>,
) -> Result<(), String> {
let entries = std::fs::read_dir(dir)
.map_err(|error| format!("cannot read `{}`: {error}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|error| format!("cannot read `{}`: {error}", dir.display()))?;
let path = entry.path();
if path.is_dir() {
collect_markdown(root, &path, out)?;
} else if path
.file_name()
.is_some_and(|name| name.to_string_lossy().ends_with(".mq.md"))
{
let relative = path
.strip_prefix(root)
.map_err(|_| "stdlib file escaped its root".to_string())?
.components()
.map(|component| component.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/");
out.push((relative, path));
}
}
Ok(())
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
fn parse_public_aliases(
manifest: &serde_json::Value,
manifest_path: &Path,
) -> Result<Vec<PublicAlias>, String> {
let Some(entries) = manifest.get("public_aliases") else {
return Ok(Vec::new());
};
let entries = entries.as_array().ok_or_else(|| {
format!(
"`{}` public_aliases must be an array",
manifest_path.display()
)
})?;
let mut aliases = Vec::new();
let mut seen_names = std::collections::BTreeSet::new();
for entry in entries {
let public_names = entry
.get("public_names")
.and_then(serde_json::Value::as_array)
.ok_or_else(|| {
format!(
"`{}` public alias has no public_names array",
manifest_path.display()
)
})?
.iter()
.map(|name| {
name.as_str().map(ToString::to_string).ok_or_else(|| {
format!(
"`{}` public alias name must be a string",
manifest_path.display()
)
})
})
.collect::<Result<Vec<_>, _>>()?;
if public_names.is_empty() {
return Err(format!(
"`{}` public alias declares no names",
manifest_path.display()
));
}
for name in &public_names {
if name.is_empty() {
return Err(format!(
"`{}` public alias name must not be empty",
manifest_path.display()
));
}
if !seen_names.insert(name.clone()) {
return Err(format!(
"`{}` public alias name `{name}` is declared more than once",
manifest_path.display()
));
}
}
let target_module = entry
.get("target_module")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
format!(
"`{}` public alias has no target_module",
manifest_path.display()
)
})?
.to_string();
validate_bundle_relative(&target_module).map_err(|error| {
format!(
"`{}` public alias target_module `{target_module}` is invalid: {error}",
manifest_path.display()
)
})?;
let target_function = entry
.get("target_function")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
format!(
"`{}` public alias has no target_function",
manifest_path.display()
)
})?
.to_string();
if target_function.is_empty() {
return Err(format!(
"`{}` public alias target_function must not be empty",
manifest_path.display()
));
}
let expected_signature = entry
.get("expected_signature")
.and_then(serde_json::Value::as_str)
.map(ToString::to_string);
let effects = entry
.get("effects")
.and_then(serde_json::Value::as_array)
.map(|effects| {
effects
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect()
})
.unwrap_or_default();
aliases.push(PublicAlias {
public_names,
target_module,
target_function,
expected_signature,
effects,
});
}
aliases.sort_by(|left, right| {
(&left.target_module, &left.target_function)
.cmp(&(&right.target_module, &right.target_function))
});
Ok(aliases)
}
fn validate_bundle_relative(path: &str) -> Result<(), String> {
let mut normalised = PathBuf::new();
for component in Path::new(path).components() {
match component {
Component::Normal(part) => normalised.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err("must be a relative path inside the bundle".to_string())
}
}
}
if normalised.as_os_str().is_empty() {
return Err("must not be empty".to_string());
}
Ok(())
}
/// Canonical digest over the official public-alias table.
///
/// Format (identical to `tools/pack-stdlib.py`): for every alias sorted by
/// `(target_module, target_function)`: module, NUL, function, NUL, then every
/// public name sorted, NUL. A fixed binary format avoids JSON formatting drift.
pub fn aliases_digest(aliases: &[PublicAlias]) -> String {
let mut sorted = aliases.to_vec();
sorted.sort_by(|left, right| {
(&left.target_module, &left.target_function)
.cmp(&(&right.target_module, &right.target_function))
});
let mut hasher = Sha256::new();
for alias in &sorted {
hasher.update(alias.target_module.as_bytes());
hasher.update([0]);
hasher.update(alias.target_function.as_bytes());
hasher.update([0]);
let mut names = alias.public_names.clone();
names.sort();
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
}
format!("sha256:{}", hex(&hasher.finalize()))
}
#[cfg(test)]
mod tests {
use super::*;
fn dev_bundle() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("stdlib")
}
#[test]
fn dev_bundle_verifies_and_resolves() {
let bundle = StdlibBundle::load(dev_bundle()).unwrap();
assert!(bundle.digest.starts_with("sha256:"));
let io = bundle.resolve("io").unwrap();
assert_eq!(io.relative_path, "io.mq.md");
assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@"));
assert!(bundle.resolve("../escape").is_err());
}
#[test]
fn digest_tamper_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let source = dev_bundle();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
if entry.path().is_file() {
std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap();
}
}
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
let error = StdlibBundle::load(dir.path()).unwrap_err();
assert!(error.contains("digest mismatch"), "{error}");
}
}
+44 -15
View File
@@ -49,21 +49,21 @@ fn write(dir: &Path, name: &str, source: &str) -> PathBuf {
path
}
const PROGRAM: &str = r#"# 数学
const PROGRAM: &str = r#"# @knowledge 数学
## 加一
## @exec 加一
`(n)`
`params(n)`
*n + 1*
`return n + 1`
## main
## @exec main
**结果 = 加一(41)**
`结果 = 加一(41)`
> 打印("secret-value")
`打印("secret-value")`
*结果*
`return 结果`
"#;
#[test]
@@ -143,7 +143,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
fn analysis_v2_identity_is_location_independent() {
let first = TempDir::new("analysis-identity-a");
let second = TempDir::new("analysis-identity-b");
let source = "## main\n\n**x = 1**\n\n*x*\n";
let source = "## @exec main\n\n`x = 1`\n\n`return x`\n";
for dir in [&first, &second] {
write(
dir.path(),
@@ -181,12 +181,41 @@ fn analysis_v2_identity_is_location_independent() {
assert_eq!(analysis["project"]["identity_kind"], "manifest");
}
#[test]
fn analysis_v2_projects_memory_place_targets_additively() {
let dir = TempDir::new("analysis-place");
let source =
"## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n";
write(dir.path(), "index.mq.md", source);
let target = dir.path().join("analysis.json");
let output = cli(
dir.path(),
&["check", "index.mq.md", "--emit", target.to_str().unwrap()],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(&target).unwrap()).unwrap();
let body = analysis["modules"][0]["functions"][0]["body"]
.as_array()
.expect("body is an array");
assert_eq!(body[0]["target"], "内存");
assert_eq!(body[1]["target"]["kind"], "index");
assert_eq!(body[1]["target"]["base"]["kind"], "variable");
assert_eq!(body[1]["target"]["index"]["kind"], "literal");
assert_eq!(body[1]["target"]["index"]["type"], "int");
}
#[test]
fn analysis_v2_projects_addressable_formula_and_code_resources() {
let dir = TempDir::new("analysis-resources");
let source = r#"## calc
let source = r#"## @exec calc
`(x)`
`params(x)`
$$A = x + 1$$
@@ -194,7 +223,7 @@ $$A = x + 1$$
print(1)
```
*x*
`return x`
"#;
write(
dir.path(),
@@ -247,7 +276,7 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
write(
dir.path(),
"index.mq.md",
"## main\n\n**i = 0**\n\n- `i < 500`\n\n **i = i + 1**\n\n*i*\n",
"## @exec main\n\n`i = 0`\n\n`while i < 500`\n\n`i = i + 1`\n\n`end`\n\n`return i`\n",
);
let trace_path = dir.path().join("trace.json");
let output = cli(
@@ -290,7 +319,7 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
#[test]
fn failed_check_removes_stale_analysis() {
let dir = TempDir::new("analysis-error");
write(dir.path(), "bad.mq.md", "## main\n\n1. 没有条件\n");
write(dir.path(), "bad.mq.md", "## @exec main\n\n`return x +`\n");
let target = dir.path().join("analysis.json");
std::fs::write(&target, "stale").unwrap();
let output = cli(
@@ -348,7 +377,7 @@ fn trace_records_calls_effects_and_status_without_secrets() {
}
// Error runs still write a terminal trace.
write(dir.path(), "bad.mq.md", "## main\n\n**x = 1 // 0**\n");
write(dir.path(), "bad.mq.md", "## @exec main\n\n`x = 1 // 0`\n");
let error_trace = dir.path().join("error-trace.json");
let output = cli(
dir.path(),
+396
View File
@@ -0,0 +1,396 @@
//! Architecture boundary gate (review RFC-CM P0/P1).
//!
//! These checks pin the documented layering: the runtime depends on the host
//! platform layer, the bundled stdlib stays in this repository, `std:` import
//! targets resolve only inside the bundle, and the host keeps the documented
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an
//! OS-sandbox proof.
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
}
const WORKSPACE_CRATES: &[&str] = &[
"marqdo-span",
"marqdo-value",
"marqdo-expression",
"marqdo-markdown",
"marqdo-ir",
"marqdo-frontend",
"marqdo-math",
"marqdo-foreign",
"marqdo-plugin-abi",
"marqdo-provider-worker",
"marqdo-plugin-sdk",
"marqdo-host",
"marqdo-runtime",
"marqdo-package",
"marqdo-sandbox",
"cli",
];
#[test]
fn workspace_crates_match_the_documented_layers() {
let manifest = read(&repo_root().join("Cargo.toml"));
let members = manifest
.split("members = [")
.nth(1)
.and_then(|rest| rest.split(']').next())
.expect("workspace members");
let names: Vec<&str> = members
.split(',')
.map(|item| item.trim().trim_matches('"'))
.filter(|item| !item.is_empty())
.collect();
let expected: Vec<String> = WORKSPACE_CRATES
.iter()
.map(|name| format!("crates/{name}"))
.collect();
assert_eq!(
names,
expected.iter().map(String::as_str).collect::<Vec<_>>(),
"workspace members drifted; update docs/architecture/CURRENT.md with the layer"
);
assert!(
!names.contains(&"crates/marqdo-stdlib"),
"the stdlib must stay in this repository (ADR-0039), not become a crate"
);
}
#[test]
fn runtime_depends_on_the_host_platform_layer_without_a_cycle() {
let runtime = read(&repo_root().join("crates/marqdo-runtime/Cargo.toml"));
assert!(
runtime
.lines()
.any(|line| line.trim() == "marqdo-host = { workspace = true }"),
"runtime must keep the documented marqdo-runtime -> marqdo-host direction"
);
let host = read(&repo_root().join("crates/marqdo-host/Cargo.toml"));
assert!(
!host.contains("marqdo-runtime"),
"marqdo-host must not depend back on marqdo-runtime"
);
}
#[test]
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
let root = repo_root().join("stdlib");
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], "marqdo-stdlib");
assert_eq!(manifest["version"], "0.1.0");
let declared = manifest["digest"].as_str().expect("digest string");
let actual = format!("sha256:{}", tree_digest(&root).unwrap());
assert_eq!(
actual, declared,
"stdlib digest mismatch; regenerate it with tools/pack-stdlib.py and commit the digest"
);
}
#[test]
fn stdlib_imports_resolve_inside_the_bundle() {
let root = repo_root().join("stdlib");
for entry in walk_markdown(&root) {
let is_test = entry.starts_with(root.join("tests"));
let text = read(&entry);
for target in import_targets(&text) {
if let Some(path) = target.strip_prefix("std:") {
assert!(
is_test,
"{} imports `{}`; a product stdlib module uses a relative bundle path",
entry.display(),
target
);
let resolved = root.join(path).with_extension("mq.md");
assert!(
resolved.exists(),
"{} imports `{}`, which does not resolve inside the bundle",
entry.display(),
target
);
continue;
}
let resolved = entry.parent().unwrap().join(&target);
assert!(
resolved.starts_with(&root),
"{} imports `{}` outside the bundle",
entry.display(),
target
);
assert!(
resolved.exists(),
"{} imports missing `{}`",
entry.display(),
target
);
}
}
}
#[test]
fn host_keeps_the_documented_resource_endpoints() {
let resource = read(&repo_root().join("crates/marqdo-host/src/resource.rs"));
for endpoint in ["stdin", "stdout", "stderr", "file", "tcp"] {
let literal = format!("\"{endpoint}\"");
assert!(
resource.contains(&literal),
"host resource layer no longer mentions the documented `{endpoint}` endpoint"
);
}
}
fn import_targets(text: &str) -> Vec<String> {
let mut targets = Vec::new();
let mut in_import = false;
for line in text.lines() {
if line.trim() == "import:" {
in_import = true;
continue;
}
if in_import {
let trimmed = line.trim();
if trimmed.is_empty() {
in_import = false;
continue;
}
if !line.starts_with(' ') && !line.starts_with('\t') {
in_import = false;
continue;
}
if let Some((_, value)) = trimmed.split_once(':') {
let value = value.trim().trim_matches('"');
if !value.is_empty() {
targets.push(value.to_string());
}
}
}
}
targets
}
fn walk_markdown(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
out.extend(walk_markdown(&path));
} else if path
.file_name()
.is_some_and(|name| name.to_string_lossy().ends_with(".mq.md"))
{
out.push(path);
}
}
out.sort();
out
}
fn tree_digest(root: &Path) -> Result<String, String> {
let mut files: Vec<(String, PathBuf)> = walk_markdown(root)
.into_iter()
.map(|path| {
let relative = path
.strip_prefix(root)
.map_err(|error| error.to_string())?
.to_string_lossy()
.replace('\\', "/");
Ok((relative, path))
})
.collect::<Result<_, String>>()?;
files.sort();
let mut hasher = Sha256::new();
for (relative, path) in files {
hasher.update(relative.as_bytes());
hasher.update(b"\0");
hasher.update(std::fs::read(&path).map_err(|error| error.to_string())?);
hasher.update(b"\0");
}
Ok(hex::encode(hasher.finalize()))
}
/// The CLI must consume the platform-neutral strict-child API. Direct use of
/// the Linux-only `marker_present`/`verify_active` symbols reintroduces the
/// macOS/Windows `E0425` build break (RFC-CI-0001 B01).
#[test]
fn cli_uses_only_the_platform_neutral_strict_child_api() {
let root = repo_root();
let run = read(&root.join("crates/cli/src/commands/run.rs"));
assert!(
run.contains("inspect_strict_child"),
"run.rs must use marqdo_sandbox::inspect_strict_child"
);
for source in walk_rs(&root.join("crates/cli/src")) {
let text = read(&source);
for forbidden in ["marker_present", "verify_active"] {
assert!(
!text.contains(forbidden),
"{} references Linux-only `{forbidden}`; use StrictChildState instead",
source.display()
);
}
}
let sandbox = read(&root.join("crates/marqdo-sandbox/src/lib.rs"));
assert!(
sandbox.contains("pub fn inspect_strict_child"),
"the sandbox crate must expose inspect_strict_child"
);
assert!(
!sandbox.contains("pub use linux::{marker_present"),
"the Linux-only marker functions must not be re-exported from the crate root"
);
}
fn walk_rs(root: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(directory) = stack.pop() {
let entries = std::fs::read_dir(&directory)
.unwrap_or_else(|error| panic!("read_dir {}: {error}", directory.display()));
for entry in entries {
let entry = entry.expect("directory entry");
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if path.extension().and_then(|value| value.to_str()) == Some("rs") {
files.push(path);
}
}
}
files
}
/// RFC-EXT-0001 §4/§14: the runtime must dispatch by the prepared binding and
/// never re-resolve a name or special-case a print function.
#[test]
fn callable_binding_is_the_only_static_resolution_path() {
let root = repo_root();
let loader = read(&root.join("crates/cli/src/loader.rs"));
let interpreter = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
let run = read(&root.join("crates/cli/src/commands/run.rs"));
let frontend = read(&root.join("crates/marqdo-frontend/src/calls.rs"));
assert!(
!loader.contains("program_uses_print"),
"loader must not scan for per-function names (ADR-0058)"
);
assert!(
!interpreter.contains("print_override"),
"the runtime must not special-case print (ADR-0054/0058)"
);
assert!(
!interpreter.contains("external_callables.is_empty"),
"the runtime must not fall back to plugin guessing (ADR-0054)"
);
assert!(
interpreter.contains("call_bindings.get"),
"the runtime must dispatch by the prepared call binding table"
);
assert!(
!interpreter.contains("builtins::find(&qualified)"),
"a qualified name must not be re-resolved at run time"
);
assert!(
!run.contains("external_callables")
|| !run.contains("external_callables")
|| !run.contains("push(marqdo_ir::callable::CallableDescriptor"),
"run must not synthesise plugin descriptors (ADR-0054/§4.5)"
);
assert!(
frontend.contains("bind_program_calls"),
"the frontend must expose the single binding entry point"
);
}
/// RFC-EXT-0001 §14.2/S4: no business-domain builtin or host-op branch may be
/// added for an ecosystem feature. These must be implemented as `.mq.md`,
/// plugin exports or provider streams.
#[test]
fn no_business_domain_builtins_or_host_ops() {
let root = repo_root();
let builtins = read(&root.join("crates/marqdo-ir/src/builtins.rs"));
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
for forbidden in ["quantum.", "ai.chat", "vendor.", "demo.sensor", "marqdo."] {
assert!(
!builtins.contains(forbidden),
"business builtin namespace `{forbidden}` must not exist"
);
}
assert!(
!host.contains("\"demo.sensor\""),
"provider kinds must be data, not host-op string branches"
);
}
/// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not
/// hard-coded runtime names. Recompute the canonical metadata digest.
#[test]
fn official_stdlib_public_aliases_are_verified_metadata() {
let root = repo_root().join("stdlib");
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
let aliases = manifest["public_aliases"]
.as_array()
.expect("stdlib.json must declare public_aliases");
assert!(!aliases.is_empty());
let mut hasher = Sha256::new();
let mut entries: Vec<&serde_json::Value> = aliases.iter().collect();
entries.sort_by_key(|alias| {
(
alias["target_module"].as_str().unwrap_or("").to_string(),
alias["target_function"].as_str().unwrap_or("").to_string(),
)
});
for alias in &entries {
hasher.update(alias["target_module"].as_str().unwrap().as_bytes());
hasher.update([0]);
hasher.update(alias["target_function"].as_str().unwrap().as_bytes());
hasher.update([0]);
let mut names: Vec<&str> = alias["public_names"]
.as_array()
.unwrap()
.iter()
.filter_map(serde_json::Value::as_str)
.collect();
names.sort();
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
}
let actual = format!("sha256:{}", hex(&hasher.finalize()));
assert_eq!(
manifest["aliases_digest"], actual,
"stdlib.json aliases_digest must cover the public alias table"
);
for alias in aliases {
let target_module = alias["target_module"].as_str().unwrap();
let target_function = alias["target_function"].as_str().unwrap();
let module = read(&root.join(target_module));
assert!(
module.contains(&format!("## {target_function}")),
"public alias target `{target_module}::{target_function}` must exist"
);
}
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
+653
View File
@@ -0,0 +1,653 @@
//! Black-box callable resolution / binding conformance (RFC-EXT-0001 §4.6).
//!
//! Every test drives the real `marqdo` binary through the public CLI. The
//! point is to prove that `check` and `run` share one static resolution and
//! that the runtime never guesses a plugin from a dotted string prefix.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
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-callable-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn write(path: &Path, text: &str) {
std::fs::write(path, text).unwrap();
}
fn library_name() -> &'static str {
if cfg!(target_os = "macos") {
"solver.dylib"
} else {
"solver.so"
}
}
fn shared_flags() -> &'static [&'static str] {
if cfg!(target_os = "macos") {
&["-dynamiclib", "-fPIC"]
} else {
&["-shared", "-fPIC"]
}
}
fn have_cc() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn compile_plugin(dir: &Path, extra: &[&str]) -> PathBuf {
let output = dir.join(library_name());
let status = Command::new("cc")
.args(["-std=c11", "-O2"])
.args(shared_flags())
.arg("-I")
.arg(repo().join("include"))
.args(extra)
.arg(repo().join("examples/plugin-demo/solver.c"))
.arg("-o")
.arg(&output)
.status()
.expect("cc");
assert!(status.success(), "cc failed");
output
}
fn write_worker_manifest(dir: &Path, artifact: &Path, exports: &str) {
let sha = sha256_file(artifact).unwrap();
write(
&dir.join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.solver
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
{exports} requires:
- math.compute
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
}
fn add_export(name: &str, signature: &str) -> String {
format!(" - name: {name}\n signature: \"{signature}\"\n")
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
// CALL-01
#[test]
fn import_alias_conflicting_with_builtin_namespace_is_rejected() {
let dir = TempDir::new("call01");
write(
&dir.path().join("math.mq.md"),
"## @exec eval\n\n`params(a: Int)`\n\n`return a + 100`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n math: \"./math.mq.md\"\n---\n\n## @exec main\n\n`return math.eval(a=1)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.import_namespace_conflict"),
"{}",
stderr(&check)
);
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1));
assert!(stdout(&run).is_empty());
assert!(
stderr(&run).contains("ext.import_namespace_conflict"),
"{}",
stderr(&run)
);
}
// CALL-02
#[test]
fn dotted_builtin_call_binds_without_an_import() {
let output = cli(&["check", "examples/math.mq.md"], &repo());
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let run = cli(&["call", "examples/math.mq.md", "计算圆面积"], &repo());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
// CALL-03
#[test]
fn renamed_import_alias_binds_the_module_function() {
let dir = TempDir::new("call03");
write(
&dir.path().join("math.mq.md"),
"## @exec eval\n\n`params(a: Int)`\n\n`return a + 100`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n mymath: \"./math.mq.md\"\n---\n\n## @exec main\n\n`return mymath.eval(a=1)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "101"})
);
}
// CALL-04 / CALL-05
#[test]
fn unknown_plugin_export_is_a_static_symbol_error() {
let dir = TempDir::new("call04");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1));
assert!(
stderr(&check).contains("symbol.unknown"),
"{}",
stderr(&check)
);
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1));
assert!(stderr(&run).contains("symbol.unknown"), "{}", stderr(&run));
assert!(stdout(&run).is_empty());
// CALL-05: the diagnostic does not change when an unrelated plugin is
// loaded, because the static export table is still the only source.
if !have_cc() {
return;
}
let plugin_dir = TempDir::new("call05-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.subtract(a=1, b=2)`\n",
);
let with_plugin = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(with_plugin.status.code(), Some(1));
assert!(
stderr(&with_plugin).contains("symbol.unknown"),
"{}",
stderr(&with_plugin)
);
}
// CALL-06
#[test]
fn plugin_with_two_prefixes_binds_both_exports() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call06");
let plugin_dir = TempDir::new("call06-plugin");
let artifact = compile_plugin(plugin_dir.path(), &["-DMQ_SOLVER_MULTI_EXPORT"]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&(add_export("solver.add", "($a: Int, $b: Int) -> Int")
+ &add_export("solver.neg", "($a: Int) -> Int")),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`和 = solver.add(20, b=22)`\n\n`相反数 = solver.neg(7)`\n\n`打印(和)`\n\n`打印(相反数)`\n",
);
let output = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
assert_eq!(stdout(&output), "42\n-7\n");
}
// CALL-07
#[test]
fn duplicate_complete_export_across_plugins_is_rejected_at_prepare() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call07");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let mut plugins = Vec::new();
for tag in ["a", "b"] {
let plugin_dir = TempDir::new(tag);
let artifact = compile_plugin(plugin_dir.path(), &[]);
let sha = sha256_file(&artifact).unwrap();
write(
&plugin_dir.path().join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.{tag}.solver
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: solver.add
signature: "($a: Int, $b: Int) -> Int"
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
plugins.push(plugin_dir);
}
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugins[0].path().to_str().unwrap(),
"--plugin",
plugins[1].path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(2), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.duplicate_callable"),
"{}",
stderr(&check)
);
}
// CALL-08
#[test]
fn bad_plugin_arguments_fail_in_check_and_run_identically() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call08");
let plugin_dir = TempDir::new("call08-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
for (tag, call) in [
("missing", "solver.add(a=1)"),
("unknown", "solver.add(a=1, b=2, c=3)"),
("duplicate", "solver.add(a=1, a=2, b=3)"),
("too-many-positional", "solver.add(1, 2, 3)"),
] {
write(
&dir.path().join("index.mq.md"),
&format!("## @exec main\n\n`return {call}`\n"),
);
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(1), "{tag}: {}", stderr(&check));
let expected = if tag == "duplicate" {
// The expression grammar rejects duplicate named arguments before
// call binding; either way the failure is static.
"sem.syntax"
} else {
"call.arity"
};
assert!(
stderr(&check).contains(expected),
"{tag}: {}",
stderr(&check)
);
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(1), "{tag}: {}", stderr(&run));
assert!(stdout(&run).is_empty(), "{tag}");
// `check` appends a summary line and `run` a refusal line, but the
// structured call.arity diagnostic itself must be identical.
let arity = |text: &str| {
text.lines()
.filter(|line| line.contains("call.arity") || line.contains("sem.syntax"))
.map(ToString::to_string)
.collect::<Vec<_>>()
};
assert!(!arity(&stderr(&check)).is_empty(), "{tag}");
assert_eq!(
arity(&stderr(&check)),
arity(&stderr(&run)),
"{tag}: check != run"
);
}
}
// CALL-09
#[test]
fn changed_artifact_digest_is_rejected_before_main_runs() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call09");
let plugin_dir = TempDir::new("call09-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(\"must-not-run\")`\n\n`return solver.add(a=1, b=2)`\n",
);
// Static check succeeds: it never opens the artifact.
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
// Corrupt the artifact bytes; run must reject before the entry function.
let mut bytes = std::fs::read(&artifact).unwrap();
bytes.push(0);
std::fs::write(&artifact, bytes).unwrap();
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(1), "{}", stderr(&run));
assert!(
stderr(&run).contains("ext.artifact_integrity"),
"{}",
stderr(&run)
);
assert!(stdout(&run).is_empty(), "{}", stdout(&run));
}
// CALL-11
#[test]
fn local_function_reference_is_a_dynamic_language_call() {
let dir = TempDir::new("call11");
write(
&dir.path().join("index.mq.md"),
"## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n",
);
let run = cli(&["call", "index.mq.md", "主", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "16"})
);
}
// CALL-12
#[test]
fn calling_a_text_value_is_not_callable_and_never_reaches_the_host() {
let dir = TempDir::new("call12");
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`f = \"text\"`\n\n`return f()`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1), "{}", stderr(&run));
assert!(
stderr(&run).contains("call.not_callable") || stderr(&run).contains("not_callable"),
"{}",
stderr(&run)
);
}
// CALL-13
#[test]
fn explicit_import_aliases_bind_same_named_functions_independently() {
let dir = TempDir::new("call13");
write(
&dir.path().join("a.mq.md"),
"## @exec value\n\n`params()`\n\n`return 10`\n",
);
write(
&dir.path().join("b.mq.md"),
"## @exec value\n\n`params()`\n\n`return 20`\n",
);
write(
&dir.path().join("index.mq.md"),
"---\nimport:\n aa: \"./a.mq.md\"\n bb: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return aa.value() + bb.value()`\n",
);
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
serde_json::json!({"type": "int", "decimal": "30"})
);
}
// CALL-14
#[test]
fn check_never_executes_a_plugin_artifact_or_side_effect_script() {
let dir = TempDir::new("call14");
let plugin_dir = TempDir::new("call14-plugin");
let marker = plugin_dir.path().join("executed.marker");
let artifact = plugin_dir.path().join(library_name());
write(
&artifact,
&format!("#!/bin/sh\ntouch '{}'\nexit 0\n", marker.display()),
);
let sha = sha256_file(&artifact).unwrap();
write(
&plugin_dir.path().join("plugin.yaml"),
&format!(
r#"plugin:
name: demo.script
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: demo.run
signature: "() -> Int"
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return demo.run()`\n",
);
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
assert!(!marker.exists(), "check executed the artifact");
}
// CALL-15
#[test]
fn check_emit_and_run_share_the_same_static_binding_source() {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return;
}
let dir = TempDir::new("call15");
let plugin_dir = TempDir::new("call15-plugin");
let artifact = compile_plugin(plugin_dir.path(), &[]);
write_worker_manifest(
plugin_dir.path(),
&artifact,
&add_export("solver.add", "($a: Int, $b: Int) -> Int"),
);
write(
&dir.path().join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=1, b=2)`\n",
);
let analysis_path = dir.path().join("analysis.json");
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let functions = analysis["modules"]
.as_array()
.and_then(|modules| modules.first())
.and_then(|module| module["functions"].as_array())
.unwrap_or_else(|| panic!("analysis has no module functions: {analysis}"));
assert!(!functions.is_empty());
let run = cli(
&[
"run",
"index.mq.md",
"--plugin",
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
"--json",
],
dir.path(),
);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
// Without the descriptor the same call is statically unknown: run/check
// consume the same prepared binding, not a runtime name probe.
let without = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(without.status.code(), Some(1));
assert!(stderr(&without).contains("symbol.unknown"));
}
// CALL-16
#[test]
fn print_alias_keeps_the_existing_output_bytes() {
let run = cli(&["run", "examples/hello.mq.md"], &repo());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
assert_eq!(stdout(&run), "你好,Marqdo\n");
}
+201 -7
View File
@@ -21,10 +21,9 @@
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_ir::ModuleId;
use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
@@ -68,11 +67,10 @@ fn expected_path(fixture: &Path) -> PathBuf {
}
fn python_available() -> bool {
Command::new("python3")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
// Ask the same platform-aware resolver the runtime uses. On Windows a
// PATH entry is `python3.exe`, not the extension-less `python3` token, so a
// raw `Command::new("python3")` probe can disagree with execution.
marqdo_foreign::detect("python").is_some()
}
/// Unique scratch directory for the host project root. Program fixtures are
@@ -168,6 +166,8 @@ fn semantic_goldens_match_end_to_end_execution() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
install_entry_stdlib_imports(&mut program, &module_id, &analysis);
bind_calls_with_stdlib_aliases(&mut program);
let mut capabilities = Capabilities::pure();
if grant_foreign {
@@ -263,3 +263,197 @@ fn semantic_goldens_match_end_to_end_execution() {
fixtures.len()
);
}
fn normalise_relative(path: &Path) -> String {
let mut parts: Vec<std::ffi::OsString> = Vec::new();
for component in path.components() {
match component {
std::path::Component::Normal(part) => parts.push(part.to_os_string()),
std::path::Component::ParentDir => {
parts.pop();
}
std::path::Component::CurDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_) => {}
}
}
parts
.iter()
.map(|part| part.to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/")
}
/// Bind direct-runtime fixtures exactly like the CLI composition root.
///
/// The semantic harness builds a `Program` directly, so it mirrors the
/// production path: load the official stdlib public-alias targets, build the
/// unique registry, run the single binding pass and install its table. There is
/// no `print_override` and no runtime name guessing.
fn bind_calls_with_stdlib_aliases(program: &mut Program) {
let root = repo_root().join("stdlib");
let mut loaded = std::collections::BTreeSet::new();
let mut official = Vec::new();
if root.join("stdlib.json").is_file() {
let text = fs::read_to_string(root.join("stdlib.json"))
.unwrap_or_else(|error| panic!("cannot read stdlib.json: {error}"));
let manifest: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("invalid stdlib.json: {error}"));
if let Some(aliases) = manifest
.get("public_aliases")
.and_then(serde_json::Value::as_array)
{
for entry in aliases {
let public_names: Vec<String> = entry
.get("public_names")
.and_then(serde_json::Value::as_array)
.unwrap_or_else(|| panic!("public alias has no public_names"))
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect();
let target_module = entry
.get("target_module")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("public alias has no target_module"));
let target_function = entry
.get("target_function")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("public alias has no target_function"));
let module_id = load_stdlib_module(&root, target_module, program, &mut loaded)
.unwrap_or_else(|error| panic!("cannot load stdlib alias module: {error}"));
let function = program
.module(&module_id)
.and_then(|module| module.function(target_function))
.unwrap_or_else(|| {
panic!("stdlib alias target `{target_function}` is missing")
});
let effects = entry
.get("effects")
.and_then(serde_json::Value::as_array)
.map(|effects| {
effects
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect()
})
.unwrap_or_default();
official.push(marqdo_ir::callable::OfficialAlias {
public_names,
function: function.id.clone(),
signature: marqdo_ir::callable::CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
owner_package: module_id.instance.clone(),
effects_requested: effects,
});
}
}
}
let mut registry = program.callable_registry();
for alias in official {
registry
.insert_official_alias(alias)
.unwrap_or_else(|error| panic!("cannot register stdlib alias: {error}"));
}
let bound = marqdo_frontend::calls::bind_program_calls(program, &registry);
if !bound.diagnostics.is_empty() {
panic!(
"fixture failed static call binding: {:#?}",
bound.diagnostics
);
}
program.set_call_bindings(bound.bindings);
}
fn load_stdlib_module(
root: &Path,
relative: &str,
program: &mut Program,
loaded: &mut std::collections::BTreeSet<String>,
) -> Result<ModuleId, String> {
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let relative = normalise_relative(Path::new(relative));
if loaded.contains(&relative) {
if let Some((id, _)) = program
.modules
.iter()
.find(|(id, _)| id.relative_path == relative)
{
return Ok(id.clone());
}
return Err(format!("stdlib import cycle at `{relative}`"));
}
loaded.insert(relative.clone());
let path = root.join(&relative);
let source = fs::read_to_string(&path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
let module_id = ModuleId::new("std:test", relative.clone());
let analysis = marqdo_frontend::analyze_source(&module_id.to_string(), &source);
if analysis.has_errors() {
return Err(format!("stdlib module `{relative}` has diagnostics"));
}
let imports: Vec<(String, String)> = analysis
.document
.frontmatter()
.and_then(|frontmatter| frontmatter.imports().ok())
.map(|mapping| mapping.into_iter().collect())
.unwrap_or_default();
for (alias, target) in imports {
let target = target.strip_prefix("std:").unwrap_or(&target);
let child = if target.starts_with("./") || target.starts_with("../") {
let base = Path::new(&relative)
.parent()
.unwrap_or_else(|| Path::new(""));
normalise_relative(&base.join(target))
} else {
target.to_string()
};
let to = load_stdlib_module(&root, &child, program, loaded)?;
program.resolved_imports.push(ResolvedImport {
from: module_id.clone(),
alias,
to,
});
}
program.insert(analysis.module);
Ok(module_id)
}
/// Resolve `std:` imports declared by a direct-runtime fixture entry.
fn install_entry_stdlib_imports(
program: &mut Program,
module_id: &ModuleId,
analysis: &marqdo_frontend::AnalysisResult,
) {
let root = repo_root().join("stdlib");
let Some(imports) = analysis
.document
.frontmatter()
.and_then(|frontmatter| frontmatter.imports().ok())
else {
return;
};
let mut loaded = std::collections::BTreeSet::new();
for (alias, target) in imports {
let Some(relative) = target.strip_prefix("std:") else {
continue;
};
let relative = if relative.ends_with(".mq.md") {
relative.to_string()
} else {
format!("{relative}.mq.md")
};
let to = match load_stdlib_module(&root, &relative, program, &mut loaded) {
Ok(id) => id,
Err(error) => panic!("cannot load stdlib import `{target}`: {error}"),
};
program.resolved_imports.push(ResolvedImport {
from: module_id.clone(),
alias,
to,
});
}
}
+204
View File
@@ -0,0 +1,204 @@
//! Documentation consistency gate (review RFC-CM P0).
//!
//! The current architecture lives in one file, the status file must link it,
//! relative links must resolve, and a removed "running status" claim must not
//! come back. This is a source check, not a release proof.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|error| {
panic!("read {}: {error}", path.display());
})
}
#[test]
fn current_architecture_has_one_overview_and_four_state_dimensions() {
let current = read(&repo_root().join("docs/architecture/CURRENT.md"));
for heading in [
"## 1. Four state dimensions",
"## 2. Responsibility layers",
"## 3. Dependency direction and public contracts",
"## 4. Extension path classification",
"## 5. Gap and closure backlog",
"## 6. Documentation governance",
] {
assert!(current.contains(heading), "CURRENT.md is missing {heading}");
}
for dimension in [
"Implemented",
"Tested locally",
"Bundled stdlib released",
"Multi-platform verified",
] {
assert!(
current.contains(dimension),
"CURRENT.md is missing the `{dimension}` state dimension"
);
}
let baseline = current
.lines()
.find(|line| line.starts_with("- Baseline:"))
.expect("CURRENT.md has no Baseline line");
let sha = baseline
.split('`')
.nth(1)
.expect("Baseline line has no backtick-quoted SHA");
assert_eq!(sha.len(), 40, "Baseline SHA is not 40 hex digits: {sha}");
assert!(
sha.chars().all(|c| c.is_ascii_hexdigit()),
"Baseline SHA is not hex: {sha}"
);
}
#[test]
fn index_and_status_point_at_the_current_overview_and_history() {
let root = repo_root();
let index = read(&root.join("docs/architecture/README.md"));
for target in ["CURRENT.md", "../STATUS.md", "../history/README.md"] {
assert!(
index.contains(target),
"architecture index does not link {target}"
);
}
// The index is an index, not a second running-status page.
assert!(
!index.contains("P5 providers") && !index.contains("P5 Provider"),
"architecture index must not duplicate the current P5 status"
);
let status = read(&root.join("docs/STATUS.md"));
assert!(
status.contains("architecture/CURRENT.md"),
"STATUS.md does not link the current overview"
);
assert!(
!status.contains("is still `c9f01aa8"),
"STATUS.md still claims the stale `c9f01aa8` remote baseline"
);
}
#[test]
fn current_relative_markdown_links_resolve() {
let root = repo_root();
for relative in [
"docs/architecture/CURRENT.md",
"docs/architecture/README.md",
"docs/STATUS.md",
"docs/history/README.md",
] {
let path = root.join(relative);
let text = read(&path);
let mut checked = BTreeSet::new();
for target in markdown_targets(&text) {
if target.starts_with("http://")
|| target.starts_with("https://")
|| target.starts_with('#')
{
continue;
}
let file = target.split('#').next().unwrap();
if file.is_empty() || !checked.insert(file.to_string()) {
continue;
}
let resolved = path.parent().unwrap().join(file);
assert!(
resolved.exists(),
"{} links missing `{target}` (resolved {})",
path.display(),
resolved.display()
);
}
}
}
/// CI/security status drift is a defect: the current architecture table must
/// not simultaneously claim a network endpoint is implemented and absent, and
/// the CI doc must not claim the GitHub-hosted Windows/macOS matrix does not
/// exist (it does; Woodpecker has no such agent).
#[test]
fn ci_and_architecture_status_do_not_contradict_the_workflows() {
let root = repo_root();
let current = read(&root.join("docs/architecture/CURRENT.md"));
assert!(
!current.contains("no DNS/TLS/server socket/UDP"),
"CURRENT.md repeats the stale TCP row that contradicts the network endpoint row"
);
assert!(
!current.contains("file metadata / directory / rename / remove / mkdir"),
"CURRENT.md repeats the stale not-implemented filesystem row"
);
let ci = read(&root.join("docs/ci.md"));
assert!(
!ci.contains("no runners are configured"),
"docs/ci.md denies the existing GitHub-hosted Windows/macOS matrix"
);
assert!(
ci.contains("windows-latest") && ci.contains("macos-latest"),
"docs/ci.md must name the native matrix it cannot replace with Woodpecker"
);
let historical = read(&root.join("docs/NEXT_RELEASE_CI_CONVERGENCE.md"));
assert!(
historical.contains("Historical / Superseded baseline"),
"the old convergence plan must keep its historical banner"
);
}
#[test]
fn evidence_files_are_sha_pinned() {
let evidence = repo_root().join("docs/evidence");
for entry in std::fs::read_dir(&evidence).expect("read evidence dir") {
let path = entry.unwrap().path();
if path.extension().and_then(|ext| ext.to_str()) != Some("md") {
continue;
}
let text = read(&path);
assert!(
has_hex_sha(&text),
"{} has no 7–40 hex commit/security SHA",
path.display()
);
}
}
fn markdown_targets(text: &str) -> Vec<String> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i + 1 < bytes.len() {
if bytes[i] == b']' && bytes[i + 1] == b'(' {
let start = i + 2;
let mut end = start;
while end < bytes.len() && bytes[end] != b')' && bytes[end] != b'\n' {
end += 1;
}
if end < bytes.len() && bytes[end] == b')' {
out.push(text[start..end].to_string());
i = end;
}
}
i += 1;
}
out
}
fn has_hex_sha(text: &str) -> bool {
for word in text.split(|c: char| !c.is_ascii_hexdigit()) {
if (7..=40).contains(&word.len()) {
return true;
}
}
false
}
+52
View File
@@ -24,6 +24,58 @@ fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
#[test]
fn mqmd_stdlib_print_output_matches_builtin_print() {
let output = cli(&["run", "stdlib/demo.mq.md"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let stdout = String::from_utf8_lossy(&output.stdout);
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 6, "{stdout:?}");
for pair in [(0, 1), (2, 3), (4, 5)] {
assert_eq!(
lines[pair.0], lines[pair.1],
"stdlib formatting differs from 打印 at line {}",
pair.0
);
}
assert_eq!(
lines[0],
r#"["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]"#
);
assert_eq!(lines[2], "Table[名称 | 分数]{甲 | 87; 乙 | 92}");
assert_eq!(
lines[4],
r#"[Formula("a = 1"), Code("text", 9 bytes), FunctionRef(root:default::demo.mq.md::演示函数)]"#
);
}
#[test]
fn addressable_memory_example_runs_through_the_cli() {
let output = cli(&["run", "examples/memory-buffer.mq.md", "--json"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON");
assert_eq!(report["success"], true);
assert_eq!(report["value"]["type"], "int");
assert_eq!(report["value"]["decimal"], "141");
}
#[test]
fn cli_memory_budget_override_fails_closed() {
let output = cli(&[
"run",
"examples/memory-buffer.mq.md",
"--max-memory",
"0",
"--json",
]);
assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "resource.exhausted");
}
#[test]
fn multi_version_packages_run_without_an_implicit_override() {
let output = cli(&["run", "examples/packages-multi-version/index.mq.md"]);
+495
View File
@@ -0,0 +1,495 @@
//! Extension selection and lock v4 conformance (RFC-EXT-0001 §6.6).
//!
//! These are black-box CLI tests: `marqdo.yaml.extensions` declares activation
//! sources, `marqdo lock` records their exact identity, and `check`/`run`
//! compare the current declaration with the lock before using any extension.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
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-ext-selection-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn have_cc() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn library_name() -> &'static str {
if cfg!(target_os = "macos") {
"plugin.dylib"
} else {
"plugin.so"
}
}
fn compile_plugin(dir: &Path) -> PathBuf {
let output = dir.join(library_name());
let flags: &[&str] = if cfg!(target_os = "macos") {
&["-dynamiclib", "-fPIC"]
} else {
&["-shared", "-fPIC"]
};
let status = Command::new("cc")
.args(["-std=c11", "-O2"])
.args(flags)
.arg("-I")
.arg(repo().join("include"))
.arg(repo().join("examples/plugin-demo/solver.c"))
.arg("-o")
.arg(&output)
.status()
.expect("cc");
assert!(status.success(), "cc failed");
output
}
fn write_plugin_manifest(adapter: &Path, artifact: &Path) {
let sha = sha256_file(artifact).unwrap();
std::fs::write(
adapter.join("plugin.yaml"),
format!(
r#"plugin:
name: demo.solver
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: solver.add
signature: "($a: Int, $b: Int) -> Int"
requires:
- math.compute
artifacts:
- target: {}
file: {}
sha256: "{sha}"
"#,
HostTarget::current().triple(),
artifact.file_name().unwrap().to_string_lossy()
),
)
.unwrap();
}
fn write_project(project: &Path, extension_yaml: &str) {
std::fs::create_dir_all(project.join("adapter")).unwrap();
std::fs::write(
project.join("marqdo.yaml"),
format!("project:\n name: ext-project\n version: 0.1.0\n{extension_yaml}"),
)
.unwrap();
std::fs::write(
project.join("index.mq.md"),
"## @exec main\n\n`return solver.add(a=20, b=22)`\n",
)
.unwrap();
}
/// Build a project with one worker plugin declared through `extensions:`.
fn plugin_project(tag: &str) -> Option<TempDir> {
if !have_cc() {
eprintln!("skipping: cc is unavailable");
return None;
}
let project = TempDir::new(tag);
let artifact = compile_plugin(&project.path().join("adapter").create_dir_all_ok());
write_plugin_manifest(&project.path().join("adapter"), &artifact);
write_project(
project.path(),
"extensions:\n plugins:\n - from: ./adapter/plugin.yaml\n",
);
Some(project)
}
fn lock(project: &Path) -> Output {
cli(&["lock"], project)
}
#[test]
fn declared_plugin_extension_locks_and_runs() {
let Some(project) = plugin_project("positive") else {
return;
};
let locked = lock(project.path());
assert_eq!(locked.status.code(), Some(0), "{}", stderr(&locked));
let lock_text = std::fs::read_to_string(project.path().join("marqdo.lock")).unwrap();
assert!(lock_text.contains("lock_version: 4"));
assert!(lock_text.contains("kind: plugin"));
assert!(lock_text.contains("source: ./adapter/plugin.yaml"));
let check = cli(&["check", "index.mq.md"], project.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(
&["run", "index.mq.md", "--allow-plugin", "demo.solver"],
project.path(),
);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
#[test]
fn declared_extension_without_a_lock_is_fail_closed() {
let Some(project) = plugin_project("no-lock") else {
return;
};
let check = cli(&["check", "index.mq.md"], project.path());
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.extension_lock_mismatch"),
"{}",
stderr(&check)
);
assert!(stderr(&check).contains("marqdo lock"), "{}", stderr(&check));
}
#[test]
fn changed_manifest_after_lock_is_rejected() {
let Some(project) = plugin_project("manifest-change") else {
return;
};
assert_eq!(lock(project.path()).status.code(), Some(0));
let adapter = project.path().join("adapter");
let manifest = std::fs::read_to_string(adapter.join("plugin.yaml")).unwrap();
std::fs::write(
adapter.join("plugin.yaml"),
manifest.replace("version: 0.1.0", "version: 0.2.0"),
)
.unwrap();
let check = cli(&["check", "index.mq.md"], project.path());
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.extension_lock_mismatch"),
"{}",
stderr(&check)
);
}
#[test]
fn changed_artifact_after_lock_fails_before_main_runs() {
let Some(project) = plugin_project("artifact-change") else {
return;
};
assert_eq!(lock(project.path()).status.code(), Some(0));
let artifact = project.path().join("adapter").join(library_name());
let mut bytes = std::fs::read(&artifact).unwrap();
bytes.push(0);
std::fs::write(&artifact, bytes).unwrap();
let run = cli(
&["run", "index.mq.md", "--allow-plugin", "demo.solver"],
project.path(),
);
assert_eq!(run.status.code(), Some(1), "{}", stderr(&run));
assert!(
stderr(&run).contains("ext.artifact_integrity"),
"{}",
stderr(&run)
);
assert!(stdout(&run).is_empty());
}
#[test]
fn extension_source_traversal_is_rejected_at_load() {
let project = TempDir::new("traversal");
write_project(
project.path(),
"extensions:\n plugins:\n - from: ../escape/plugin.yaml\n",
);
let check = cli(&["check", "index.mq.md"], project.path());
assert_eq!(check.status.code(), Some(2), "{}", stderr(&check));
assert!(
stderr(&check).contains("extension") || stderr(&check).contains("must stay inside"),
"{}",
stderr(&check)
);
}
#[test]
fn undeclared_dependency_alias_is_rejected() {
let project = TempDir::new("alias");
write_project(
project.path(),
"extensions:\n plugins:\n - from: \"@missing/plugin.yaml\"\n",
);
let check = cli(&["check", "index.mq.md"], project.path());
assert_eq!(check.status.code(), Some(2), "{}", stderr(&check));
assert!(
stderr(&check).contains("not a declared dependency"),
"{}",
stderr(&check)
);
}
#[test]
fn lock_v3_is_rejected_with_an_explicit_migration() {
let Some(project) = plugin_project("v3") else {
return;
};
let lock_path = project.path().join("marqdo.lock");
std::fs::write(
&lock_path,
"lock_version: 3\ncontent_profile_version: 1\nroot:\n package: root:ext-project@0.1.0\n manifest_digest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\npackages: []\nroot_dependencies: {}\n",
)
.unwrap();
let check = cli(&["check", "index.mq.md"], project.path());
assert!(!check.status.success(), "{}", stderr(&check));
assert!(
stderr(&check).contains("lock v3 is superseded by lock v4"),
"{}",
stderr(&check)
);
assert!(!stdout(&check).contains("ok"));
}
#[test]
fn pure_and_strict_refuse_project_declared_extensions() {
let Some(project) = plugin_project("modes") else {
return;
};
assert_eq!(lock(project.path()).status.code(), Some(0));
let pure = cli(&["run", "index.mq.md", "--mode", "pure"], project.path());
assert_eq!(pure.status.code(), Some(2), "{}", stderr(&pure));
let strict = cli(&["run", "index.mq.md", "--mode", "strict"], project.path());
assert_eq!(strict.status.code(), Some(2), "{}", stderr(&strict));
}
#[test]
fn provider_extension_is_locked_but_still_requires_an_exact_grant() {
let project = TempDir::new("provider");
std::fs::create_dir_all(project.path().join("vendor/lib")).unwrap();
let artifact = project.path().join("vendor/lib/libsensor.so");
std::fs::write(&artifact, b"fixture provider artifact").unwrap();
let sha = sha256_file(&artifact).unwrap();
std::fs::write(
project.path().join("vendor/provider.json"),
format!(
r#"{{
"schema": "marqdo.provider",
"schema_version": 2,
"name": "demo.sensor",
"version": "0.1.0",
"abi": "c-abi-1",
"transport": "worker",
"kinds": ["demo.sensor"],
"artifacts": [{{"target": "{}", "path": "lib/libsensor.so", "sha256": "{sha}"}}],
"permissions_requested": []
}}"#,
HostTarget::current().triple()
),
)
.unwrap();
write_project(
project.path(),
"extensions:\n providers:\n - from: ./vendor/provider.json\n",
);
std::fs::write(
project.path().join("index.mq.md"),
"## @exec main\n\n`流 = resource.open(\"demo.sensor\", \"unit-1\", [\"read\"])`\n\n`return resource.close(流)`\n",
)
.unwrap();
let locked = lock(project.path());
assert_eq!(locked.status.code(), Some(0), "{}", stderr(&locked));
let lock_text = std::fs::read_to_string(project.path().join("marqdo.lock")).unwrap();
assert!(lock_text.contains("kind: provider"));
// Locked identity is not a grant: the provider is selected from the
// manifest but `--allow-provider` is still required before any worker.
let no_grant = cli(&["run", "index.mq.md"], project.path());
assert_eq!(no_grant.status.code(), Some(1), "{}", stderr(&no_grant));
assert!(
stderr(&no_grant).contains("permission.denied"),
"{}",
stderr(&no_grant)
);
}
trait CreateDirOk {
fn create_dir_all_ok(&self) -> PathBuf;
}
impl CreateDirOk for PathBuf {
fn create_dir_all_ok(&self) -> PathBuf {
std::fs::create_dir_all(self).unwrap();
self.clone()
}
}
#[test]
fn inspect_extensions_reports_lock_identity_without_executing() {
let Some(project) = plugin_project("inspect") else {
return;
};
assert_eq!(lock(project.path()).status.code(), Some(0));
let artifact = project.path().join("adapter").join(library_name());
std::fs::remove_file(&artifact).unwrap();
// Inspection is static: a missing artifact does not prevent identity
// reporting, and no worker is started.
let output = cli(
&["inspect", "index.mq.md", "--extensions", "--json"],
project.path(),
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let report: serde_json::Value = serde_json::from_str(&stdout(&output)).unwrap();
let declared = report["extensions"]["declared"].as_array().unwrap();
assert_eq!(declared.len(), 1);
assert_eq!(declared[0]["kind"], "plugin");
assert_eq!(declared[0]["status"], "locked");
assert_eq!(declared[0]["authorization"], "not_granted");
assert_eq!(declared[0]["name"], "demo.solver");
let plugins = report["extensions"]["plugins"].as_array().unwrap();
assert_eq!(plugins[0]["package"], "demo.solver");
assert_eq!(plugins[0]["exports"][0]["name"], "solver.add");
assert_eq!(plugins[0]["authorization"], "not_granted");
}
#[test]
fn cli_and_manifest_selection_of_the_same_plugin_is_idempotent() {
let Some(project) = plugin_project("idempotent") else {
return;
};
assert_eq!(lock(project.path()).status.code(), Some(0));
let adapter = project.path().join("adapter");
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
adapter.to_str().unwrap(),
],
project.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
}
#[test]
fn two_different_manifests_for_one_package_conflict() {
let Some(project) = plugin_project("conflict") else {
return;
};
let second = project.path().join("adapter-v2");
std::fs::create_dir_all(&second).unwrap();
let artifact = project.path().join("adapter").join(library_name());
std::fs::copy(&artifact, second.join(library_name())).unwrap();
write_plugin_manifest(&second, &second.join(library_name()));
let manifest = std::fs::read_to_string(second.join("plugin.yaml")).unwrap();
std::fs::write(
second.join("plugin.yaml"),
manifest.replace("version: 0.1.0", "version: 0.2.0"),
)
.unwrap();
let check = cli(
&[
"check",
"index.mq.md",
"--plugin",
project.path().join("adapter").to_str().unwrap(),
"--plugin",
second.to_str().unwrap(),
],
project.path(),
);
assert_eq!(check.status.code(), Some(2), "{}", stderr(&check));
assert!(
stderr(&check).contains("ext.duplicate_callable"),
"{}",
stderr(&check)
);
}
#[test]
fn declared_kernel_extension_is_activated_from_the_manifest() {
let project = TempDir::new("kernel");
std::fs::create_dir_all(project.path().join("kernel")).unwrap();
let provider = project.path().join("kernel/mocklang");
std::fs::write(
&provider,
"#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"type\":\"int\",\"decimal\":\"42\"}'\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&provider, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let digest = sha256_file(&provider).unwrap();
std::fs::write(
project.path().join("kernel/kernel.json"),
format!(
r#"{{
"provider_id": "mocklang-provider",
"languages": ["mocklang-only"],
"wire_version": 1,
"entrypoint": "{}",
"permissions_requested": [],
"digest": "{digest}"
}}"#,
provider.display()
),
)
.unwrap();
write_project(
project.path(),
"extensions:\n kernels:\n - from: ./kernel/kernel.json\n",
);
std::fs::write(
project.path().join("index.mq.md"),
"## @exec main\n\n`结果 = foreign.call(ref(\"#代码\"), {})`\n\n`return 结果`\n\n### @knowledge 代码\n\n```mocklang-only\ninert\n```\n",
)
.unwrap();
assert_eq!(lock(project.path()).status.code(), Some(0));
let lock_text = std::fs::read_to_string(project.path().join("marqdo.lock")).unwrap();
assert!(lock_text.contains("kind: kernel"));
let run = cli(&["run", "index.mq.md", "--allow-foreign"], project.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
+122
View File
@@ -0,0 +1,122 @@
//! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint.
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::Command;
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let path =
std::env::temp_dir().join(format!("marqdo-http-tcp-{}-{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
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn mqmd_http_client_parses_a_response_from_a_tcp_stream() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut request = [0u8; 512];
let count = stream.read(&mut request).unwrap();
assert!(String::from_utf8_lossy(&request[..count]).starts_with("GET / HTTP/1.1\r\n"));
stream
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello",
)
.unwrap();
});
let dir = TempDir::new("client");
let program = format!(
r#"---
import:
http: "std:net/http"
编码: "std:text"
---
## @exec main
`流 = resource.open("tcp", "{address}", ["read", "write"])`
`请求 = http.构建请求("GET", "/", [["Host", "example.test"]], "")`
`请求内存 = memory.new(1, 1)`
`请求长度 = 编码.utf8编码(请求, 请求内存, 0)`
`写入 = resource.write(流, 请求内存, 0, 请求长度)`
`接收 = memory.new(1, 1)`
`读出 = resource.read(流, 接收, 0, 4096)`
`数量 = 读出.value.count`
`响应文本 = ""`
`下标 = 0`
`while 下标 < 数量`
`响应文本 = 响应文本 + text.from_codepoint(接收[下标])`
`下标 = 下标 + 1`
`end`
`关闭 = resource.close(流)`
`响应 = http.解析响应(响应文本)`
`return [写入.ok, 读出.ok, 响应.状态, 响应.头["Content-Type"], 响应.体, 关闭.ok]`
"#
);
std::fs::write(dir.path().join("index.mq.md"), program).unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"])
.current_dir(dir.path())
.env(
"MARQDO_STDLIB_DIR",
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.join("stdlib"),
)
.output()
.expect("run marqdo");
assert_eq!(
output.status.code(),
Some(0),
"stderr={} stdout={}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["decimal"], "200");
assert_eq!(items[3]["value"], "text/plain");
assert_eq!(items[4]["value"], "hello");
assert_eq!(items[5]["value"], true);
server.join().unwrap();
}
+180 -47
View File
@@ -79,6 +79,16 @@ fn cli(dir: &Path, args: &[&str]) -> Output {
.unwrap_or_else(|error| panic!("cannot run marqdo {args:?}: {error}"))
}
/// Run the CLI in `dir` with one extra environment variable.
fn cli_env(dir: &Path, args: &[&str], key: &str, value: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.env(key, value)
.output()
.unwrap_or_else(|error| panic!("cannot run marqdo {args:?}: {error}"))
}
fn stdout_text(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
@@ -133,6 +143,11 @@ fn init_creates_a_runnable_project() {
let output = cli(dir.path(), &["init", "proj"]);
assert_exit(&output, 0, "init must succeed");
assert!(stdout_text(&output).contains("Initialized Marqdo project"));
let manifest = std::fs::read_to_string(dir.path().join("proj/marqdo.yaml")).unwrap();
assert!(
manifest.contains("name: proj"),
"init must derive the project name from the target directory: {manifest}"
);
let project = dir.path().join("proj");
assert!(project.join("marqdo.yaml").is_file(), "manifest missing");
assert!(
@@ -170,9 +185,12 @@ fn init_creates_a_runnable_project() {
#[test]
fn check_exit_codes_and_diagnostics() {
let dir = TempDir::new("check");
dir.write("good.mq.md", "## main\n\n*1 + 1*\n");
dir.write("bad.mq.md", "## f\n\n**a *b* c**\n");
dir.write("warning.mq.md", "**x = 1**\n\n## main\n\n*1*\n");
dir.write("good.mq.md", "## @exec main\n\n`return 1 + 1`\n");
dir.write("bad.mq.md", "## @exec f\n\n**a *b* c**\n");
dir.write(
"warning.mq.md",
"**x = 1**\n\n## @exec main\n\n`return 1`\n",
);
let good = cli(dir.path(), &["check", "good.mq.md"]);
assert_exit(&good, 0, "clean document");
@@ -181,7 +199,7 @@ fn check_exit_codes_and_diagnostics() {
let bad = cli(dir.path(), &["check", "bad.mq.md"]);
assert_exit(&bad, 1, "invalid executable shape is a hard error");
let bad_stderr = stderr_text(&bad);
assert!(bad_stderr.contains("error[markdown.invalid_construct]"));
assert!(bad_stderr.contains("error[sem.payload_nested]"));
assert!(bad_stderr.contains("check failed"));
assert!(stdout_text(&bad).is_empty());
@@ -192,20 +210,36 @@ fn check_exit_codes_and_diagnostics() {
assert_eq!(value["success"], false);
assert_eq!(value["errors"], 1);
let diagnostics = value["diagnostics"].as_array().expect("diagnostics array");
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0]["code"], "markdown.invalid_construct");
assert_eq!(diagnostics[0]["severity"], "error");
assert_eq!(diagnostics[0]["line"], 3);
let nested = diagnostics
.iter()
.find(|diagnostic| diagnostic["code"] == "sem.payload_nested")
.expect("sem.payload_nested diagnostic");
assert_eq!(nested["severity"], "error");
assert_eq!(nested["line"], 3);
assert!(
diagnostics
.iter()
.all(|diagnostic| diagnostic["severity"] == "error"
|| diagnostic["code"] == "sem.inferred_signature"),
"the fixture may carry the inferred-signature warning but no other diagnostic"
);
assert!(stderr_text(&bad_json).is_empty());
let warning = cli(dir.path(), &["check", "warning.mq.md"]);
assert_exit(&warning, 0, "a warning does not fail check");
assert!(stdout_text(&warning).contains("checked 1 module(s): ok"));
assert!(stderr_text(&warning).contains("warning[markdown.inert_executable]"));
let warning_json = cli(dir.path(), &["check", "warning.mq.md", "--json"]);
let value = json_stdout(&warning_json);
// RFC-LANG-0002: a Strong at the Knowledge root is inert prose, not an
// executable shape, and the old `markdown.inert_executable` warning no
// longer exists.
let inert = cli(dir.path(), &["check", "warning.mq.md"]);
assert_exit(&inert, 0, "inert Knowledge prose does not fail check");
assert!(stdout_text(&inert).contains("checked 1 module(s): ok"));
assert!(!stderr_text(&inert).contains("warning["));
let inert_json = cli(dir.path(), &["check", "warning.mq.md", "--json"]);
let value = json_stdout(&inert_json);
assert_eq!(value["success"], true);
assert_eq!(value["diagnostics"][0]["severity"], "warning");
assert_eq!(
value["diagnostics"].as_array().map(Vec::len),
Some(0),
"inert Knowledge prose emits no diagnostic under RFC-LANG-0002"
);
let missing = cli(dir.path(), &["check", "missing.mq.md"]);
assert_exit(&missing, 2, "missing file is a usage/IO error");
@@ -217,7 +251,7 @@ fn run_json_embeds_program_stdout() {
let dir = TempDir::new("run-json");
dir.write(
"print.mq.md",
"## main\n\n> 打印(\"你好\")\n\n> 打印(42)\n\n*None*\n",
"## @exec main\n\n`打印(\"你好\")`\n\n`打印(42)`\n\n`return None`\n",
);
let output = cli(dir.path(), &["run", "print.mq.md", "--json"]);
assert_exit(&output, 0, "run --json must succeed");
@@ -240,11 +274,11 @@ fn run_json_embeds_program_stdout() {
#[test]
fn run_refuses_documents_with_compile_errors() {
let dir = TempDir::new("run-errors");
dir.write("bad.mq.md", "## f\n\n**a *b* c**\n");
dir.write("bad.mq.md", "## @exec f\n\n**a *b* c**\n");
let output = cli(dir.path(), &["run", "bad.mq.md"]);
assert_exit(&output, 1, "compile errors must prevent execution");
let stderr = stderr_text(&output);
assert!(stderr.contains("markdown.invalid_construct"));
assert!(stderr.contains("sem.payload_nested"));
assert!(stderr.contains("refusing to run"));
assert!(stdout_text(&output).is_empty());
}
@@ -449,6 +483,90 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
.contains("strict mode"));
}
/// A forged `MARQDO_STRICT_ACTIVE` marker must never be trusted and every
/// `--json` refusal must still contain exactly one JSON document. This runs on
/// every platform; Linux rejects the marker during identity verification and
/// non-Linux builds reject it as unsupported.
#[test]
fn forged_strict_marker_is_rejected_with_one_json_document() {
let root = repo_root();
let hello = root.join("examples").join("hello.mq.md");
let hello = hello.to_str().unwrap();
let json = cli_env(
&root,
&["run", hello, "--mode", "strict", "--json"],
"MARQDO_STRICT_ACTIVE",
"1",
);
assert_exit(&json, 1, "forged strict marker must fail closed");
let value = json_stdout(&json);
assert_eq!(value["command"], "run");
assert_eq!(value["success"], false);
assert_eq!(value["code"], "strict.identity_invalid");
let human = cli_env(
&root,
&["run", hello, "--mode", "strict"],
"MARQDO_STRICT_ACTIVE",
"1",
);
assert_exit(&human, 1, "forged strict marker must fail closed");
assert!(
stdout_text(&human).is_empty(),
"project output appeared for a rejected marker: {}",
stdout_text(&human)
);
assert!(stderr_text(&human).contains("strict isolation verification failed"));
}
/// CLI usage errors in `--json` mode keep the same one-document contract as
/// successful and runtime-failure paths.
#[test]
fn json_mode_reports_cli_errors_as_one_document() {
let root = repo_root();
let hello = root.join("examples").join("hello.mq.md");
let hello = hello.to_str().unwrap();
let mode = cli(&root, &["run", hello, "--mode", "bogus", "--json"]);
assert_exit(&mode, 2, "unknown mode");
let value = json_stdout(&mode);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "cli.invalid_mode");
let grants = cli(
&root,
&[
"run",
hello,
"--mode",
"pure",
"--allow-read",
"x",
"--json",
],
);
assert_exit(&grants, 2, "pure mode must reject grants");
let value = json_stdout(&grants);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "cli.invalid_grants");
let strict = cli(
&root,
&[
"run",
hello,
"--mode",
"strict",
"--allow-foreign",
"--json",
],
);
assert_exit(&strict, 2, "strict L1 must reject foreign grants");
let value = json_stdout(&strict);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "strict.unsupported_grant");
}
#[test]
fn inspect_outputs_ast_units_signatures_ir_and_refs() {
let root = repo_root();
@@ -501,7 +619,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
let dir = TempDir::new("refs");
dir.write(
"broken.mq.md",
"## main\n\n见[断链](#不存在的标题)。\n\n*1*\n",
"## @exec main\n\n见[断链](#不存在的标题)。\n\n`return 1`\n",
);
let broken = cli(dir.path(), &["inspect", "broken.mq.md", "--refs", "--json"]);
assert_exit(&broken, 0, "inspect --refs never executes the document");
@@ -515,7 +633,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
#[test]
fn fmt_normalises_line_endings_and_trailing_newlines() {
let dir = TempDir::new("fmt");
dir.write("doc.mq.md", "## main\r\n\r\n*1*\r\n\r\n\r\n");
dir.write("doc.mq.md", "## @exec main\r\n\r\n`return 1`\r\n\r\n\r\n");
let before = cli(dir.path(), &["fmt", "--check", "doc.mq.md"]);
assert_exit(&before, 1, "unformatted document is detected");
assert!(stderr_text(&before).contains("is not formatted"));
@@ -523,7 +641,7 @@ fn fmt_normalises_line_endings_and_trailing_newlines() {
let format = cli(dir.path(), &["fmt", "doc.mq.md"]);
assert_exit(&format, 0, "fmt must rewrite the document");
let formatted = dir.read("doc.mq.md");
assert_eq!(formatted, "## main\n\n*1*\n");
assert_eq!(formatted, "## @exec main\n\n`return 1`\n");
assert!(!formatted.contains('\r'));
let after = cli(dir.path(), &["fmt", "--check", "doc.mq.md"]);
@@ -535,11 +653,11 @@ fn multi_module_imports_and_cycles() {
let dir = TempDir::new("modules");
dir.write(
"geometry.mq.md",
"## 圆面积\n\n`(r: Number)`\n\n*math.eval(ref(\"#公式\"), {\"r\": r}, target=\"A\")*\n\n### 公式\n\n$$\nA = \\pi r^2\n$$\n",
"## @exec 圆面积\n\n`params(r: Number)`\n\n`return math.eval(ref(\"#公式\"), {\"r\": r}, target=\"A\")`\n\n### @knowledge 公式\n\n$$\nA = \\pi r^2\n$$\n",
);
dir.write(
"index.mq.md",
"---\nimport:\n geometry: \"./geometry.mq.md\"\n---\n\n## main\n\n**面积 = geometry.圆面积(r=2)**\n\n> 打印(面积)\n",
"---\nimport:\n geometry: \"./geometry.mq.md\"\n---\n\n## @exec main\n\n`面积 = geometry.圆面积(r=2)`\n\n`打印(面积)`\n",
);
let run = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&run, 0, "multi-module import must run");
@@ -552,11 +670,11 @@ fn multi_module_imports_and_cycles() {
let cycle = TempDir::new("cycle");
cycle.write(
"a.mq.md",
"---\nimport:\n b: \"./b.mq.md\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n b: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return 1`\n",
);
cycle.write(
"b.mq.md",
"---\nimport:\n a: \"./a.mq.md\"\n---\n\n## f\n\n*1*\n",
"---\nimport:\n a: \"./a.mq.md\"\n---\n\n## @exec f\n\n`return 1`\n",
);
let output = cli(cycle.path(), &["check", "a.mq.md"]);
assert_exit(&output, 1, "import cycle is an error");
@@ -568,7 +686,7 @@ fn multi_module_imports_and_cycles() {
let missing = TempDir::new("missing-import");
missing.write(
"index.mq.md",
"---\nimport:\n gone: \"./gone.mq.md\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n gone: \"./gone.mq.md\"\n---\n\n## @exec main\n\n`return 1`\n",
);
let output = cli(missing.path(), &["check", "index.mq.md"]);
assert_exit(&output, 1, "missing import target is an error");
@@ -582,8 +700,8 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
"marqdo.yaml",
"project:\n name: locktest\n version: 0.1.0\ndependencies:\n dep:\n path: \"./dep\"\n",
);
dir.write("index.mq.md", "## main\n\n*1*\n");
dir.write("dep/index.mq.md", "## main\n\n*1*\n");
dir.write("index.mq.md", "## @exec main\n\n`return 1`\n");
dir.write("dep/index.mq.md", "## @exec main\n\n`return 1`\n");
let lock = cli(dir.path(), &["lock"]);
assert_exit(&lock, 0, "lock must succeed");
@@ -596,7 +714,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
assert!(stdout_text(&sync).contains("synchronized 1 package(s)"));
// Tamper with the dependency contents: `sync --locked` must fail.
dir.write("dep/index.mq.md", "## main\n\n*2*\n");
dir.write("dep/index.mq.md", "## @exec main\n\n`return 2`\n");
let tampered = cli(dir.path(), &["sync", "--locked"]);
assert_exit(&tampered, 1, "tampered dependency must fail sync --locked");
assert!(stderr_text(&tampered).contains("lockfile is out of date"));
@@ -711,7 +829,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
let dir = TempDir::new("plugin-run");
dir.write(
"doc.mq.md",
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
"## @exec main\n\n`结果 = solver.add(a=20, b=22)`\n\n`打印(结果)`\n",
);
let plugin_path = plugin_dir.to_str().unwrap();
let doc = dir.path().join("doc.mq.md");
@@ -756,7 +874,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
// Unknown plugin namespace is a hard runtime symbol error.
dir.write(
"unknown.mq.md",
"## main\n\n**结果 = other.add(a=1, b=1)**\n",
"## @exec main\n\n`结果 = other.add(a=1, b=1)`\n",
);
let unknown = cli(
dir.path(),
@@ -775,7 +893,7 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
// The export signature requires both named arguments: with a declared
// plugin manifest this is rejected statically, before any library load.
dir.write("args.mq.md", "## main\n\n**结果 = solver.add(a=1)**\n");
dir.write("args.mq.md", "## @exec main\n\n`结果 = solver.add(a=1)`\n");
let bad_args = cli(
dir.path(),
&[
@@ -798,11 +916,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
let dir = TempDir::new("cross-module-error");
dir.write(
"index.mq.md",
"---\nimport:\n physics: \"./physics.mq.md\"\n---\n\n## main\n\n> 打印(physics.boom())\n",
"---\nimport:\n physics: \"./physics.mq.md\"\n---\n\n## @exec main\n\n`打印(physics.boom())`\n",
);
dir.write(
"physics.mq.md",
"## boom\n\n说明文字。\n\n**x = 1 / 0**\n\n*x*\n",
"## @exec boom\n\n说明文字。\n\n`x = 1 / 0`\n\n`return x`\n",
);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
@@ -957,7 +1075,7 @@ fn plugin_abi_major_mismatch_is_rejected_before_execution() {
let dir = TempDir::new("plugin-abi-run");
dir.write(
"doc.mq.md",
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
"## @exec main\n\n`结果 = solver.add(a=20, b=22)`\n\n`打印(结果)`\n",
);
let output = cli(
dir.path(),
@@ -1019,7 +1137,7 @@ fn check_never_spawns_a_foreign_kernel() {
);
dir.write(
"doc.mq.md",
"## 代码\n\n```mocklang\nignored\n```\n\n## main\n\n**值 = foreign.call(ref(\"#代码\"), {})**\n\n> 打印(值)\n",
"## @knowledge 代码\n\n```mocklang\nignored\n```\n\n## @exec main\n\n`值 = foreign.call(ref(\"#代码\"), {})`\n\n`打印(值)`\n",
);
let checked = cli(dir.path(), &["check", "doc.mq.md"]);
@@ -1051,7 +1169,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
let dir = TempDir::new("power");
dir.write(
"branch.mq.md",
"## main\n\n**n = 2**\n\n1. `n ** 2 == 4`,正确分支。\n\n > print(\"乘方正确\")\n\n2. `n ** 2 != 4`,另一分支。\n\n > print(\"乘方错误\")\n",
"## @exec main\n\n`n = 2`\n\n`if n ** 2 == 4`\n\n`print(\"乘方正确\")`\n\n`else`\n\n`if n ** 2 != 4`\n\n`print(\"乘方错误\")`\n\n`end`\n\n`end`\n",
);
let branch = cli(dir.path(), &["run", "branch.mq.md", "--json"]);
assert_exit(&branch, 0, "power branch run");
@@ -1062,7 +1180,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
dir.write(
"loop.mq.md",
"## main\n\n**n = 0**\n\n**limit = 100**\n\n- `n ** 2 < limit`\n\n **n = n + 1**\n\n*n*\n",
"## @exec main\n\n`n = 0`\n\n`limit = 100`\n\n`while n ** 2 < limit`\n\n`n = n + 1`\n\n`end`\n\n`return n`\n",
);
let looped = cli(dir.path(), &["run", "loop.mq.md", "--json"]);
assert_exit(&looped, 0, "power loop run");
@@ -1074,7 +1192,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
// diagnostics and never changes the returned value.
dir.write(
"inert.mq.md",
"## main\n\n```text\n**n = 2 ** 3**\n```\n\n正文里的 `2 ** 3` 不执行。\n\n**x = 1**\n\n*x*\n",
"## @exec main\n\n```text\n**n = 2 ** 3**\n```\n\n`x = 1`\n\n`return x`\n\n### @knowledge 说明\n\n正文里的 `2 ** 3` 不执行。\n",
);
let inert = cli(dir.path(), &["run", "inert.mq.md", "--json"]);
assert_exit(&inert, 0, "inert code run");
@@ -1085,7 +1203,7 @@ fn power_branch_loop_and_inert_code_end_to_end() {
#[test]
fn condition_parse_diagnostic_points_inside_the_code_span() {
let dir = TempDir::new("condition-span");
let source = "## main\n\n**n = 2**\n\n1. `n ** 2 ==`\n\n > print(1)\n";
let source = "## @exec main\n\n`n = 2`\n\n`if n ** 2 ==`\n\n`print(1)`\n\n`end`\n";
dir.write("bad.mq.md", source);
let output = cli(dir.path(), &["check", "bad.mq.md", "--json"]);
assert_exit(&output, 1, "condition parse error");
@@ -1094,12 +1212,27 @@ fn condition_parse_diagnostic_points_inside_the_code_span() {
.as_array()
.expect("diagnostics array")
.iter()
.find(|diagnostic| diagnostic["code"] == "expr.parse")
.expect("expr.parse diagnostic");
.find(|diagnostic| diagnostic["code"] == "sem.syntax")
.expect("sem.syntax diagnostic");
assert_eq!(diagnostic["line"], 5);
// 1-based column 14 is the closing backtick: the empty end-of-input span
// must not be shifted by the delimiter.
assert_eq!(diagnostic["column"], 14);
let line = source.lines().nth(4).expect("line 5");
assert_eq!(&line[13..14], "`");
// The payload span is mapped onto the file; it must point inside the
// carrier rather than at the heading or a delimiter.
let column = diagnostic["column"].as_u64().expect("column");
assert!((11..=14).contains(&column), "unexpected column {column}");
}
#[test]
fn run_reports_sem_no_entry_function_without_exec_main() {
let dir = TempDir::new("no-entry");
dir.write(
"index.mq.md",
"# @knowledge 文档\n\n这里没有可调用的函数。\n",
);
let output = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&output, 1, "missing Exec H2 main is an error");
let stderr = stderr_text(&output);
assert!(
stderr.contains("sem.no_entry_function"),
"stderr must carry the stable code: {stderr}"
);
}
+13
View File
@@ -224,6 +224,7 @@ fn runtime_negative_goldens() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
bind_program_calls(&mut program);
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
@@ -284,3 +285,15 @@ fn runtime_negative_goldens() {
}
let _ = fs::remove_dir_all(&project_root);
}
/// Bind direct-runtime fixtures exactly like the CLI composition root.
fn bind_program_calls(program: &mut marqdo_ir::Program) {
let registry = program.callable_registry();
let bound = marqdo_frontend::calls::bind_program_calls(program, &registry);
assert!(
bound.diagnostics.is_empty(),
"fixture failed static call binding: {:#?}",
bound.diagnostics
);
program.set_call_bindings(bound.bindings);
}
+159
View File
@@ -0,0 +1,159 @@
//! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host.
use std::path::{Path, PathBuf};
use std::process::Command;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn fixture(name: &str) -> PathBuf {
repo_root()
.join("tests")
.join("conformance")
.join("semantics")
.join(name)
}
fn expected(name: &str) -> serde_json::Value {
let path = fixture(&name.replace(".mq.md", ".expected.json"));
serde_json::from_slice(&std::fs::read(&path).expect("expected golden")).expect("golden json")
}
#[test]
fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
// P2 gate (RFC-CM-0002 §8): C01-C06, C11, C12 use only .mq.md plus the
// declared low-level primitives. These fixtures are run through the real
// CLI in `--mode pure`, which has no foreign/plugin grants, and the source
// is checked for host shortcuts that would violate the anti-evasion rule.
let cases: &[(&str, &str)] = &[
("48-memory-bump-allocator.mq.md", "C01 bump allocator"),
(
"50-memory-allocation-failure-atomic.mq.md",
"C01 allocation atomicity",
),
(
"55-first-fit-free-list-allocator.mq.md",
"C01 free-list split/coalesce",
),
("49-memory-linked-list.mq.md", "C02 linked list"),
("56-memory-binary-tree.mq.md", "C02 tree"),
("61-memory-graph-adjacency.mq.md", "C02 graph"),
("58-memory-hash-table.mq.md", "C02 hash table"),
("64-memory-integer-codecs.mq.md", "C03 codecs"),
("59-utf8-encoder.mq.md", "C04 UTF-8 encode"),
("60-utf8-decoder.mq.md", "C04 UTF-8 decode"),
("57-csv-row-splitter.mq.md", "C05 CSV"),
("62-json-array-parser.mq.md", "C05 JSON"),
("68-csv-quoted-row.mq.md", "C05 CSV quoted"),
("53-table-projection.mq.md", "C06 table projection"),
("54-table-filter-stdlib.mq.md", "C06 table filter"),
("65-table-sort-stdlib.mq.md", "C06 table sort"),
("67-table-join-stdlib.mq.md", "C06 table join"),
("69-table-group-stdlib.mq.md", "C06 table group"),
("63-memory-bytecode-vm.mq.md", "C11 bytecode VM"),
("70-matrix-multiply.mq.md", "C12 matrix"),
("73-sparse-matrix.mq.md", "C12 sparse matrix"),
];
for (name, criterion) in cases {
let path = fixture(name);
let source = std::fs::read_to_string(&path).expect("fixture source");
for forbidden in ["foreign.", "plugin.", "import:"] {
assert!(
!source.contains(forbidden),
"{criterion} fixture {name} uses forbidden host shortcut `{forbidden}`"
);
}
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"])
.current_dir(repo_root())
.output()
.expect("run marqdo");
assert_eq!(
output.status.code(),
Some(0),
"{criterion} fixture {name} failed in pure mode: {}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("json report");
assert_eq!(report["success"], true, "{name}");
let golden = expected(name);
assert_eq!(
report["value"], golden["value"],
"{criterion} fixture {name}"
);
assert_eq!(
report["stdout"].as_str().unwrap_or_default(),
golden["stdout"].as_str().unwrap_or_default(),
"{criterion} fixture {name} stdout"
);
}
}
#[test]
fn p2_stdlib_table_also_runs_in_pure_mode() {
let path = repo_root().join("stdlib").join("tests").join("table.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"]
.as_array()
.expect("table test list");
assert_eq!(items.len(), 9);
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
#[test]
fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
let dir = tempfile::tempdir().unwrap();
let foreign = dir.path().join("foreign.mq.md");
std::fs::write(
&foreign,
"## @knowledge 代码\n\n```python\nprint(1)\n```\n\n## @exec main\n\n`return foreign.call(ref(\"#代码\"), None)`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", foreign.to_str().unwrap(), "--mode", "pure", "--json"])
.current_dir(dir.path())
.output()
.expect("run foreign fixture");
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "permission.denied");
let plugin = dir.path().join("plugin.mq.md");
std::fs::write(
&plugin,
"## @exec main\n\n`plugin.invoke(\"missing.export\", {})`\n\n`return None`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", plugin.to_str().unwrap(), "--mode", "pure", "--json"])
.current_dir(dir.path())
.output()
.expect("run plugin fixture");
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false);
}
+76 -20
View File
@@ -82,20 +82,23 @@ fn transitive_path_dependency_resolves_from_its_own_manifest() {
);
write(
&root.join("deps/a/index.mq.md"),
"---\nimport:\n b: \"@b\"\n---\n\n## outer\n\n*b.inner()*\n",
"---\nimport:\n b: \"@b\"\n---\n\n## @exec outer\n\n`return b.inner()`\n",
);
write(
&root.join("deps/a/b/marqdo.yaml"),
"project:\n name: b\n version: 0.1.0\n",
);
write(&root.join("deps/a/b/index.mq.md"), "## inner\n\n*42*\n");
write(
&root.join("deps/a/b/index.mq.md"),
"## @exec inner\n\n`return 42`\n",
);
write(
&root.join("marqdo.yaml"),
"project:\n name: root\n version: 0.1.0\ndependencies:\n a:\n path: ./deps/a\n",
);
write(
&root.join("index.mq.md"),
"---\nimport:\n a: \"@a\"\n---\n\n## main\n\n> 打印(a.outer())\n",
"---\nimport:\n a: \"@a\"\n---\n\n## @exec main\n\n`打印(a.outer())`\n",
);
let lock = cli(root, &["lock"]);
assert_eq!(
@@ -133,7 +136,7 @@ fn pinned_git_dependency_locks_syncs_and_runs() {
&dep.join("marqdo.yaml"),
"project:\n name: remote\n version: 0.3.0\n",
);
write(&dep.join("index.mq.md"), "## hello\n\n*7*\n");
write(&dep.join("index.mq.md"), "## @exec hello\n\n`return 7`\n");
git(&dep, &["init", "-q"]);
git(&dep, &["add", "."]);
git(&dep, &["commit", "-q", "-m", "initial"]);
@@ -156,7 +159,7 @@ fn pinned_git_dependency_locks_syncs_and_runs() {
);
write(
&root.join("index.mq.md"),
"---\nimport:\n remote: \"@remote\"\n---\n\n## main\n\n> 打印(remote.hello())\n",
"---\nimport:\n remote: \"@remote\"\n---\n\n## @exec main\n\n`打印(remote.hello())`\n",
);
let lock = cli(&root, &["lock"]);
@@ -167,7 +170,7 @@ fn pinned_git_dependency_locks_syncs_and_runs() {
String::from_utf8_lossy(&lock.stderr)
);
let lock_text = std::fs::read_to_string(root.join("marqdo.lock")).unwrap();
assert!(lock_text.contains("lock_version: 3"));
assert!(lock_text.contains("lock_version: 4"));
assert!(lock_text.contains("root_dependencies:"));
assert!(lock_text.contains("instance_id: dep:remote@0.3.0#"));
assert!(lock_text.contains("kind: git"));
@@ -206,7 +209,7 @@ fn check_does_not_fetch_a_missing_git_revision() {
);
write(
&root.join("index.mq.md"),
"---\nimport:\n remote: \"@remote\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n remote: \"@remote\"\n---\n\n## @exec main\n\n`return 1`\n",
);
let output = cli(root, &["check", "index.mq.md"]);
assert_eq!(output.status.code(), Some(1));
@@ -223,10 +226,13 @@ fn run_and_check_require_a_lock_when_dependencies_exist() {
&root.join("marqdo.yaml"),
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
);
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 1`\n",
);
write(
&root.join("index.mq.md"),
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
);
for command in ["check", "run"] {
let output = cli(root, &[command, "index.mq.md"]);
@@ -244,14 +250,20 @@ fn sync_is_strict_and_never_rewrites_the_lock() {
&root.join("marqdo.yaml"),
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
);
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
write(&root.join("index.mq.md"), "## main\n\n*1*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 1`\n",
);
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
let lock = cli(root, &["lock"]);
assert_eq!(lock.status.code(), Some(0));
let original = std::fs::read(root.join("marqdo.lock")).unwrap();
write(&root.join("dep/index.mq.md"), "## value\n\n*2*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 2`\n",
);
let stale = cli(root, &["sync"]);
assert_eq!(stale.status.code(), Some(1), "plain sync must be strict");
let stderr = String::from_utf8_lossy(&stale.stderr);
@@ -285,13 +297,19 @@ fn lock_records_transitive_closure_and_sync_materializes_it() {
&root.join("deps/a/marqdo.yaml"),
"project:\n name: a\n version: 0.1.0\ndependencies:\n b:\n path: ./b\n",
);
write(&root.join("deps/a/index.mq.md"), "## a\n\n*1*\n");
write(
&root.join("deps/a/index.mq.md"),
"## @exec a\n\n`return 1`\n",
);
write(
&root.join("deps/a/b/marqdo.yaml"),
"project:\n name: b\n version: 0.1.0\n",
);
write(&root.join("deps/a/b/index.mq.md"), "## b\n\n*2*\n");
write(&root.join("index.mq.md"), "## main\n\n*1*\n");
write(
&root.join("deps/a/b/index.mq.md"),
"## @exec b\n\n`return 2`\n",
);
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
let lock = cli(root, &["lock"]);
assert_eq!(lock.status.code(), Some(0));
@@ -326,10 +344,13 @@ fn deleted_lock_edge_fails_check_and_run() {
&root.join("marqdo.yaml"),
"project:\n name: root\n version: 0.1.0\ndependencies:\n dep:\n path: ./dep\n",
);
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 1`\n",
);
write(
&root.join("index.mq.md"),
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
);
assert_eq!(cli(root, &["lock"]).status.code(), Some(0));
let lock = std::fs::read_to_string(root.join("marqdo.lock")).unwrap();
@@ -362,10 +383,13 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
&root.join("dep/marqdo.yaml"),
"project:\n name: dep\n version: 0.1.0\n",
);
write(&root.join("dep/index.mq.md"), "## value\n\n*1*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 1`\n",
);
write(
&root.join("index.mq.md"),
"---\nimport:\n dep: \"@dep\"\n---\n\n## main\n\n*1*\n",
"---\nimport:\n dep: \"@dep\"\n---\n\n## @exec main\n\n`return 1`\n",
);
assert_eq!(cli(root, &["lock"]).status.code(), Some(0));
let lock_before = std::fs::read(root.join("marqdo.lock")).unwrap();
@@ -375,7 +399,10 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
// Content change after the lock is a tamper/staleness signal. `run` and
// `check` must never silently accept it, re-lock, or materialize a new
// environment.
write(&root.join("dep/index.mq.md"), "## value\n\n*2*\n");
write(
&root.join("dep/index.mq.md"),
"## @exec value\n\n`return 2`\n",
);
for args in [
vec!["sync", "--locked"],
vec!["run", "index.mq.md"],
@@ -407,3 +434,32 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
"a failed locked operation must not replace the materialized environment"
);
}
#[test]
fn incompatible_project_marqdo_range_fails_closed_before_program_load() {
let dir = TempDir::new("runtime-range");
let root = dir.path();
write(
&root.join("marqdo.yaml"),
"project:\n name: stale\n version: 0.1.0\n marqdo: \">=0.1,<1\"\n",
);
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
for command in [["check", "index.mq.md"], ["run", "index.mq.md"]] {
let output = cli(root, &command);
assert!(
!output.status.success(),
"{} must fail closed: {}",
command[0],
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("package.marqdo_incompatible"),
"unexpected stderr: {stderr}"
);
assert!(
stderr.contains(env!("CARGO_PKG_VERSION")),
"diagnostic must name the running core: {stderr}"
);
}
}
+2 -2
View File
@@ -112,7 +112,7 @@ fn write_manifest(dir: &Path, sha: &str) {
.unwrap();
std::fs::write(
dir.join("doc.mq.md"),
"## main\n\n**结果 = solver.add(a=20, b=22)**\n\n> 打印(结果)\n",
"## @exec main\n\n`结果 = solver.add(a=20, b=22)`\n\n`打印(结果)`\n",
)
.unwrap();
}
@@ -227,7 +227,7 @@ fn write_capability_manifest(dir: &Path, sha: &str) {
.unwrap();
std::fs::write(
dir.join("doc.mq.md"),
"## main\n\n**结果 = capability.read()**\n\n> 打印(结果)\n",
"## @exec main\n\n`结果 = capability.read()`\n\n`打印(结果)`\n",
)
.unwrap();
std::fs::create_dir_all(dir.join("data")).unwrap();
+111
View File
@@ -0,0 +1,111 @@
//! Compat-B `打印` routing tests (ADR-0030).
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let path =
std::env::temp_dir().join(format!("marqdo-print-route-{}-{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
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.expect("run marqdo")
}
fn write(dir: &Path, name: &str, source: &str) -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, source).unwrap();
path
}
#[test]
fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
let dir = TempDir::new("routed");
write(
dir.path(),
"index.mq.md",
"## @exec main\n\n`打印([\"x\", 1])`\n\n`return None`\n",
);
let trace = dir.path().join("trace.json");
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--trace-file",
trace.to_str().unwrap(),
],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(String::from_utf8_lossy(&output.stdout), "[\"x\", 1]\n");
let trace: serde_json::Value = serde_json::from_slice(&std::fs::read(&trace).unwrap()).unwrap();
let operations: Vec<&str> = trace["events"]
.as_array()
.unwrap()
.iter()
.filter_map(|event| event["operation"].as_str())
.collect();
assert!(
operations.contains(&"resource.write"),
"stdlib print must write through the resource ABI: {operations:?}"
);
assert!(
!operations.contains(&"print"),
"legacy HostOp::Print must not run in Compat-B: {operations:?}"
);
}
#[test]
fn stdlib_print_modules_are_injected_only_when_print_is_used() {
let dir = TempDir::new("lazy");
write(dir.path(), "plain.mq.md", "## @exec main\n\n`return 1`\n");
write(
dir.path(),
"prints.mq.md",
"## @exec main\n\n`打印(1)`\n\n`return None`\n",
);
for (file, expected_stdlib) in [("plain.mq.md", false), ("prints.mq.md", true)] {
let target = dir.path().join(format!("{file}.json"));
let output = cli(
dir.path(),
&["check", file, "--emit", target.to_str().unwrap()],
);
assert_eq!(output.status.code(), Some(0), "{file}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(&target).unwrap()).unwrap();
let modules = analysis["modules"].as_array().unwrap();
let has_stdlib = modules
.iter()
.any(|module| module["id"].as_str().unwrap_or("").starts_with("std:"));
assert_eq!(has_stdlib, expected_stdlib, "{file}: {modules:?}");
// The bundle identity is recorded whenever a bundle is available; it
// does not imply that this program loaded any stdlib module.
assert!(analysis["project"]["stdlib"].is_object(), "{file}");
}
}
+83 -53
View File
@@ -29,39 +29,45 @@ struct Base {
const BASES: &[Base] = &[
Base {
name: "factorial",
source: r##"# 数学
source: r##"# @knowledge 数学
## 阶乘
## @exec 阶乘
计算阶乘的叙述一。
1. `n <= 1`
`if n <= 1`
递归终点叙述。
递归终点叙述。
*1*
`return 1`
2. `n > 1`
`else`
递归步骤叙述。
`if n > 1`
**结果 = n * 阶乘(n=n-1)**
递归步骤叙述。
*结果*
`结果 = n * 阶乘(n=n-1)`
`return 结果`
`end`
`end`
"##,
narration: &["计算阶乘的叙述一。", "递归终点叙述。", "递归步骤叙述。"],
},
Base {
name: "explicit-signature",
source: r##"## 圆面积
source: r##"## @exec 圆面积
`(r: Number)`
`params(r: Number)`
半径叙述。
*math.eval(ref("#公式"), {"r": r}, target="A")*
`return math.eval(ref("#公式"), {"r": r}, target="A")`
### 公式
### @knowledge 公式
$$
A = \pi r^2
@@ -71,117 +77,133 @@ $$
},
Base {
name: "countdown-loop",
source: r##"## 倒计时
source: r##"## @exec 倒计时
循环叙述。
**n = 3**
`n = 3`
- `n > 0`
`while n > 0`
循环体叙述。
循环体叙述。
> 打印(n)
`打印(n)`
**n = n - 1**
`n = n - 1`
*n*
`end`
`return n`
"##,
narration: &["循环叙述。", "循环体叙述。"],
},
Base {
name: "branch-classification",
source: r##"## 分类
source: r##"## @exec 分类
背景叙述。
**结果 = 0**
`结果 = 0`
1. `n < 0`
`if n < 0`
负数分支叙述。
负数分支叙述。
**结果 = -1**
`结果 = -1`
2. `n >= 0`
`else`
非负分支叙述。
`if n >= 0`
**结果 = 1**
非负分支叙述。
*结果*
`结果 = 1`
`end`
`end`
`return 结果`
"##,
narration: &["背景叙述。", "负数分支叙述。", "非负分支叙述。"],
},
Base {
name: "call-and-print",
source: r##"## 问候
source: r##"## @exec 问候
说明为什么这样写。
> 打印("你好")
`打印("你好")`
**问候 = "你好,Marqdo"**
`问候 = "你好,Marqdo"`
再补充一句叙述。
*问候*
`return 问候`
"##,
narration: &["说明为什么这样写。", "再补充一句叙述。"],
},
Base {
name: "inline-prose-in-executable-paragraph",
source: r##"## 加一
source: r##"## @exec 加一
这是行内叙述 **结果 = 1 + 1** 后面继续叙述。
*结果*
`return 结果`
"##,
narration: &["这是行内叙述 ", " 后面继续叙述。"],
},
Base {
name: "nested-control-flow",
source: r##"## 嵌套
source: r##"## @exec 嵌套
说明嵌套结构。
**total = 0**
`total = 0`
1. `n > 0`
`if n > 0`
**m = 3**
`m = 3`
- `m > 0`
`while m > 0`
**total = total + m**
`total = total + m`
**m = m - 1**
`m = m - 1`
2. `n <= 0`
`end`
**total = 0**
`else`
*total*
`if n <= 0`
`total = 0`
`end`
`end`
`return total`
"##,
narration: &["说明嵌套结构。"],
},
Base {
name: "two-namespaces",
source: r##"# 数学
source: r##"# @knowledge 数学
命名空间叙述。
## 平方
## @exec 平方
**结果 = n * n**
`结果 = n * n`
*结果*
`return 结果`
# 文本
# @knowledge 文本
## 长度
## @exec 长度
*长度(s)*
`return 长度(s)`
"##,
narration: &["命名空间叙述。"],
},
@@ -265,7 +287,7 @@ fn insert_prose_after_headings(source: &str) -> String {
while next < lines.len() && lines[next].trim().is_empty() {
next += 1;
}
let signature = next < lines.len() && lines[next].trim_start().starts_with("`(");
let signature = next < lines.len() && lines[next].trim_start().starts_with("`params(");
if signature {
while index + 1 < lines.len() && lines[index + 1].trim().is_empty() {
index += 1;
@@ -373,6 +395,14 @@ fn narration_removal_preserves_execution() {
let mut program = marqdo_ir::Program::default();
program.insert(analysis.module.clone());
program.main_module = Some(module_id.clone());
let registry = program.callable_registry();
let bound = marqdo_frontend::calls::bind_program_calls(&program, &registry);
assert!(
bound.diagnostics.is_empty(),
"property fixture failed binding: {:#?}",
bound.diagnostics
);
program.set_call_bindings(bound.bindings);
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::pure(),
File diff suppressed because it is too large. Load diff
+452
View File
@@ -0,0 +1,452 @@
//! End-to-end resource stream tests through the CLI.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let path =
std::env::temp_dir().join(format!("marqdo-resource-test-{}-{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
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.expect("run marqdo")
}
fn cli_with_stdin(dir: &Path, args: &[&str], input: &[u8]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo");
child
.stdin
.take()
.expect("stdin pipe")
.write_all(input)
.expect("write stdin");
child.wait_with_output().expect("wait for marqdo")
}
fn write_file(path: &Path, contents: &str) {
std::fs::write(path, contents).unwrap();
}
const READER: &str = r#"## @exec main
`内存 = memory.new(1, 1)`
`流 = resource.open("file", "data.txt", ["read"])`
`第一次 = resource.read(流, 内存, 0, 2)`
`第二次 = resource.read(流, 内存, 2, 4)`
`第三次 = resource.read(流, 内存, 6, 1)`
`关闭 = resource.close(流)`
`return [第一次.value.count, 第一次.value.eof, 第二次.value.count, 第二次.value.eof, 第三次.value.count, 第三次.value.eof, 内存[0], 内存[1], 内存[2], 内存[3], 内存[4], 内存[5], 关闭.ok]`
"#;
#[test]
fn project_file_stream_reads_chunks_into_memory() {
let dir = TempDir::new("file-read");
write_file(&dir.path().join("data.txt"), "abcdef");
write_file(&dir.path().join("index.mq.md"), READER);
let output = cli(
dir.path(),
&["run", "index.mq.md", "--allow-read", "data.txt", "--json"],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values: Vec<&serde_json::Value> = report["value"]["items"]
.as_array()
.expect("list result")
.iter()
.collect();
assert_eq!(values[0]["decimal"], "2");
assert_eq!(values[1]["value"], false);
assert_eq!(values[2]["decimal"], "4");
assert_eq!(values[3]["value"], true);
assert_eq!(values[4]["decimal"], "0");
assert_eq!(values[5]["value"], true);
for (index, expected) in ["97", "98", "99", "100", "101", "102"]
.into_iter()
.enumerate()
{
assert_eq!(values[6 + index]["decimal"], expected);
}
assert_eq!(values[12]["value"], true);
}
const WRITER: &str = r#"## @exec main
`内存 = memory.new(1, 1)`
`内存[0] = 65`
`内存[1] = 66`
`内存[2] = 67`
`写 = resource.open("file", "out.bin", ["write"])`
`写入 = resource.write(写, 内存, 0, 3)`
`关闭写 = resource.close(写)`
`读 = resource.open("file", "out.bin", ["read"])`
`读出 = resource.read(读, 内存, 0, 3)`
`关闭读 = resource.close(读)`
`return [写入.value.count, 关闭写.ok, 读出.value.count, 读出.value.eof, 内存[0], 内存[1], 内存[2], 关闭读.ok]`
"#;
#[test]
fn project_file_stream_writes_on_close_then_reads_back() {
let dir = TempDir::new("file-write");
write_file(&dir.path().join("index.mq.md"), WRITER);
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--allow-write",
"out.bin",
"--allow-read",
"out.bin",
"--json",
],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["decimal"], "3");
assert_eq!(values[3]["value"], true);
assert_eq!(values[4]["decimal"], "65");
assert_eq!(values[5]["decimal"], "66");
assert_eq!(values[6]["decimal"], "67");
assert_eq!(values[7]["value"], true);
assert_eq!(std::fs::read(dir.path().join("out.bin")).unwrap(), b"ABC");
}
const COPY: &str = r#"## @exec main
`输入 = resource.open("file", "data.txt", ["read"])`
`输出 = resource.open("file", "out.bin", ["write"])`
`内存 = memory.new(1, 1)`
`总数 = 0`
`继续 = true`
`while 继续`
`块 = resource.read(输入, 内存, 0, 16)`
`if 块.ok`
`resource.write(输出, 内存, 0, 块.value.count)`
`总数 = 总数 + 块.value.count`
`继续 = not 块.value.eof`
`else`
`继续 = false`
`end`
`end`
`关闭读 = resource.close(输入)`
`关闭写 = resource.close(输出)`
`return [总数, 关闭读.ok, 关闭写.ok]`
"#;
#[test]
fn file_copy_is_written_in_mqmd_through_chunked_streams() {
let dir = TempDir::new("file-copy");
write_file(&dir.path().join("data.txt"), "abcdef");
write_file(&dir.path().join("index.mq.md"), COPY);
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--allow-read",
"data.txt",
"--allow-write",
"out.bin",
"--json",
],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(values[0]["decimal"], "6");
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], true);
assert_eq!(
std::fs::read(dir.path().join("out.bin")).unwrap(),
b"abcdef"
);
}
#[test]
fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
use std::io::{Read, Write};
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut buffer = [0u8; 4];
stream.read_exact(&mut buffer).unwrap();
stream.write_all(&buffer).unwrap();
});
let dir = TempDir::new("tcp");
let program = format!(
r#"## @exec main
`内存 = memory.new(1, 1)`
`内存[0] = 112`
`内存[1] = 105`
`内存[2] = 110`
`内存[3] = 103`
`流 = resource.open("tcp", "{address}", ["read", "write"])`
`写入 = resource.write(流, 内存, 0, 4)`
`读出 = resource.read(流, 内存, 0, 4)`
`关闭 = resource.close(流)`
`return [写入.value.count, 读出.value.count, 内存[0], 内存[1], 内存[2], 内存[3], 关闭.ok]`
"#
);
write_file(&dir.path().join("index.mq.md"), &program);
let output = cli(
dir.path(),
&["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list");
assert_eq!(values[0]["decimal"], "4");
assert_eq!(values[1]["decimal"], "4");
for (index, expected) in ["112", "105", "110", "103"].into_iter().enumerate() {
assert_eq!(values[2 + index]["decimal"], expected);
}
assert_eq!(values[6]["value"], true);
server.join().unwrap();
}
#[test]
fn file_stream_requires_a_read_grant() {
let dir = TempDir::new("file-denied");
write_file(&dir.path().join("data.txt"), "abcdef");
write_file(&dir.path().join("index.mq.md"), READER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "permission.denied");
}
const STDIN_READER: &str = r#"## @exec main
`输入 = resource.open("stdio", "stdin", ["read"])`
`内存 = memory.new(1, 1)`
`第一 = resource.read(输入, 内存, 0, 2)`
`第二 = resource.read(输入, 内存, 2, 8)`
`第三 = resource.read(输入, 内存, 0, 1)`
`return [第一.value.count, 第一.value.eof, 第二.value.count, 第二.value.eof, 第三.value.eof, 内存[0], 内存[1], 内存[2], 内存[3]]`
"#;
#[test]
fn piped_stdin_is_chunked_and_reaches_eof() {
let dir = TempDir::new("stdin");
write_file(&dir.path().join("index.mq.md"), STDIN_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"abcd");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(values[0]["decimal"], "2");
assert_eq!(values[1]["value"], false);
assert_eq!(values[2]["decimal"], "2");
assert_eq!(values[3]["value"], true);
assert_eq!(values[4]["value"], true);
for (index, expected) in ["97", "98", "99", "100"].into_iter().enumerate() {
assert_eq!(values[5 + index]["decimal"], expected);
}
}
const STDERR_WRITER: &str = r#"## @exec main
`错误 = resource.open("stdio", "stderr", ["write"])`
`输出 = resource.open("stdio", "stdout", ["write"])`
`内存 = memory.new(1, 1)`
`内存[0] = 101`
`内存[1] = 114`
`内存[2] = 114`
`写错误 = resource.write(错误, 内存, 0, 3)`
`内存[0] = 111`
`内存[1] = 117`
`内存[2] = 116`
`写输出 = resource.write(输出, 内存, 0, 3)`
`关闭错误 = resource.close(错误)`
`关闭输出 = resource.close(输出)`
`return [写错误.value.count, 写输出.value.count, 关闭错误.ok, 关闭输出.ok]`
"#;
#[test]
fn program_stderr_is_separate_from_stdout_and_diagnostics() {
let dir = TempDir::new("stderr");
write_file(&dir.path().join("index.mq.md"), STDERR_WRITER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
assert_eq!(report["stdout"], "out");
assert_eq!(report["stderr"], "err");
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["decimal"], "3");
assert_eq!(values[2]["value"], true);
assert_eq!(values[3]["value"], true);
}
const CONSOLE_READER: &str = r#"---
import:
console: "std:io/console"
---
## @exec main
`第一 = console.读取行()`
`第二 = console.读取行()`
`第三 = console.读取行()`
`输出 = console.打印(第一.value + "|" + 第二.value)`
`return [第一.ok, 第二.ok, 第三.ok, 第三.code, 输出.ok]`
"#;
#[test]
fn stdlib_console_reads_lines_and_reports_eof() {
let dir = TempDir::new("console");
write_file(&dir.path().join("index.mq.md"), CONSOLE_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"one\ntwo\n");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
assert_eq!(report["stdout"], "one|two\n");
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(values[0]["value"], true);
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], false);
assert_eq!(values[3]["value"], "io.eof");
assert_eq!(values[4]["value"], true);
}
+260
View File
@@ -0,0 +1,260 @@
//! Official stdlib public alias routing (RFC-EXT-0001 §8, ADR-0058).
//!
//! `打印`/`print` are ordinary `Marqdo` bindings to `io.mq.md::写值` declared
//! in the verified `stdlib.json` metadata. There is no `print_override`, no
//! runtime name special case and no hard-coded per-function scan.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
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-stdlib-alias-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
command.args(args).current_dir(dir);
for (key, value) in env {
command.env(key, value);
}
command.output().unwrap()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn copy_stdlib(target: &Path) {
let source = repo().join("stdlib");
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
copy_dir(&path, &target.join(entry.file_name()));
} else {
std::fs::copy(&path, target.join(entry.file_name())).unwrap();
}
}
}
fn copy_dir(source: &Path, target: &Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
copy_dir(&path, &target.join(entry.file_name()));
} else {
std::fs::copy(&path, target.join(entry.file_name())).unwrap();
}
}
}
#[test]
fn print_and_its_alias_are_bound_to_the_official_module() {
let dir = TempDir::new("print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(1)`\n\n`print(\"two\")`\n\n`return None`\n",
)
.unwrap();
let output = cli(&["run", "index.mq.md"], dir.path(), &[]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
assert_eq!(stdout(&output), "1\ntwo\n");
}
#[test]
fn program_without_print_does_not_load_the_stdlib_module_graph() {
let dir = TempDir::new("no-print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`params()`\n\n`return 1 + 2`\n",
)
.unwrap();
let analysis_path = dir.path().join("factorial.json");
let output = cli(
&[
"check",
"index.mq.md",
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
&[],
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let modules = analysis["modules"].as_array().unwrap();
assert!(
modules
.iter()
.all(|module| !module["id"].as_str().unwrap_or("").starts_with("std:")),
"a program without print must not load the stdlib: {analysis}"
);
}
#[test]
fn print_program_loads_exactly_the_declared_alias_target() {
let dir = TempDir::new("with-print");
std::fs::write(
dir.path().join("index.mq.md"),
"## @exec main\n\n`打印(\"x\")`\n\n`return None`\n",
)
.unwrap();
let analysis_path = dir.path().join("hello.json");
let output = cli(
&[
"check",
"index.mq.md",
"--emit",
analysis_path.to_str().unwrap(),
],
dir.path(),
&[],
);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let analysis: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&analysis_path).unwrap()).unwrap();
let ids: Vec<&str> = analysis["modules"]
.as_array()
.unwrap()
.iter()
.filter_map(|module| module["id"].as_str())
.collect();
assert!(
ids.iter().any(|id| id.ends_with("::io.mq.md")),
"print must load io.mq.md: {ids:?}"
);
assert!(
ids.iter().any(|id| id.ends_with("::format.mq.md")),
"io.mq.md imports format.mq.md: {ids:?}"
);
}
#[test]
fn tampered_public_alias_metadata_digest_is_rejected() {
let dir = TempDir::new("alias-digest");
let stdlib = dir.path().join("stdlib");
copy_stdlib(&stdlib);
let manifest_path = stdlib.join("stdlib.json");
let text = std::fs::read_to_string(&manifest_path).unwrap();
let mut manifest: serde_json::Value = serde_json::from_str(&text).unwrap();
manifest["aliases_digest"] = serde_json::json!("sha256:".to_string() + &"0".repeat(64));
std::fs::write(
&manifest_path,
serde_json::to_string_pretty(&manifest).unwrap() + "\n",
)
.unwrap();
let doc = dir.path().join("index.mq.md");
std::fs::write(&doc, "## @exec main\n\n`打印(1)`\n\n`return None`\n").unwrap();
let output = cli(
&["run", doc.to_str().unwrap()],
dir.path(),
&[("MARQDO_STDLIB_DIR", &stdlib)],
);
assert!(!output.status.success(), "{}", stderr(&output));
assert!(
stderr(&output).contains("public-alias metadata digest mismatch"),
"{}",
stderr(&output)
);
}
#[test]
fn tampered_alias_target_signature_is_rejected() {
let dir = TempDir::new("alias-target");
let stdlib = dir.path().join("stdlib");
copy_stdlib(&stdlib);
let manifest_path = stdlib.join("stdlib.json");
let text = std::fs::read_to_string(&manifest_path).unwrap();
let mut manifest: serde_json::Value = serde_json::from_str(&text).unwrap();
manifest["public_aliases"][0]["expected_signature"] = serde_json::json!("params(值, 额外)");
// Recompute the declared metadata digest so only the target check can fail.
let canonical = manifest["public_aliases"][0].clone();
let module = canonical["target_module"].as_str().unwrap();
let function = canonical["target_function"].as_str().unwrap();
let mut names: Vec<&str> = canonical["public_names"]
.as_array()
.unwrap()
.iter()
.filter_map(serde_json::Value::as_str)
.collect();
names.sort();
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(module.as_bytes());
hasher.update([0]);
hasher.update(function.as_bytes());
hasher.update([0]);
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
let digest = format!("sha256:{}", hex(&hasher.finalize()));
manifest["aliases_digest"] = serde_json::json!(digest);
std::fs::write(
&manifest_path,
serde_json::to_string_pretty(&manifest).unwrap() + "\n",
)
.unwrap();
let doc = dir.path().join("index.mq.md");
std::fs::write(&doc, "## @exec main\n\n`打印(1)`\n\n`return None`\n").unwrap();
let output = cli(
&["run", doc.to_str().unwrap()],
dir.path(),
&[("MARQDO_STDLIB_DIR", &stdlib)],
);
assert!(!output.status.success(), "{}", stderr(&output));
assert!(
stderr(&output).contains("expected signature") || stderr(&output).contains("alias"),
"{}",
stderr(&output)
);
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
+199
View File
@@ -0,0 +1,199 @@
//! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10).
use std::path::{Path, PathBuf};
use std::process::Command;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
}
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
Command::new(binary())
.args(args)
.current_dir(dir)
.env("MARQDO_STDLIB_DIR", stdlib)
.output()
.expect("run marqdo")
}
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let path = std::env::temp_dir().join(format!("marqdo-stdlib-{}-{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
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn copy_stdlib(source: &Path, target: &Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
copy_stdlib(&path, &target.join(entry.file_name()));
} else {
std::fs::copy(&path, target.join(entry.file_name())).unwrap();
}
}
}
fn write_project(dir: &Path, program: &str) {
std::fs::write(dir.join("index.mq.md"), program).unwrap();
}
const IMPORT_IO: &str = r#"---
import:
io: "std:io"
---
## @exec main
`io.写值(["bundle", 1, 2.5])`
`return None`
"#;
#[test]
fn std_import_resolves_the_verified_bundle() {
let dir = TempDir::new("resolve");
write_project(dir.path(), IMPORT_IO);
let output = run(dir.path(), &stdlib_dir(), &["run", "index.mq.md"]);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout),
"[\"bundle\", 1, 2.5]\n"
);
}
#[test]
fn analysis_records_the_verified_stdlib_digest() {
let dir = TempDir::new("analysis");
write_project(dir.path(), IMPORT_IO);
let target = dir.path().join("analysis.json");
let output = run(
dir.path(),
&stdlib_dir(),
&["check", "index.mq.md", "--emit", target.to_str().unwrap()],
);
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(&target).unwrap()).unwrap();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(stdlib_dir().join("stdlib.json")).unwrap()).unwrap();
assert_eq!(
analysis["project"]["stdlib"]["version"],
manifest["version"]
);
assert_eq!(analysis["project"]["stdlib"]["digest"], manifest["digest"]);
assert!(analysis["project"]["stdlib"]["instance_id"]
.as_str()
.unwrap()
.starts_with("std:marqdo-stdlib@"));
}
#[test]
fn frozen_binary_hash_is_unchanged_after_stdlib_execution() {
let before = std::fs::read(binary()).unwrap();
let before_hash = marqdo_value_sha(&before);
let dir = TempDir::new("frozen");
write_project(dir.path(), IMPORT_IO);
let output = run(dir.path(), &stdlib_dir(), &["run", "index.mq.md"]);
assert_eq!(output.status.code(), Some(0));
let after = std::fs::read(binary()).unwrap();
assert_eq!(before_hash, marqdo_value_sha(&after));
}
fn marqdo_value_sha(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
#[test]
fn tampered_bundle_is_rejected_before_module_loading() {
let dir = TempDir::new("tamper");
let bundle = dir.path().join("stdlib");
copy_stdlib(&stdlib_dir(), &bundle);
std::fs::write(bundle.join("io.mq.md"), "## @knowledge tampered\n").unwrap();
write_project(dir.path(), IMPORT_IO);
let output = run(dir.path(), &bundle, &["run", "index.mq.md"]);
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("stdlib digest mismatch"), "{stderr}");
}
#[test]
fn bundle_uses_no_foreign_or_plugin_calls() {
fn visit(dir: &Path, offenders: &mut Vec<String>) {
for entry in std::fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
visit(&path, offenders);
} else if path.to_string_lossy().ends_with(".mq.md") {
let source = std::fs::read_to_string(&path).unwrap();
if source.contains("foreign.") || source.contains("plugin.") {
offenders.push(path.display().to_string());
}
}
}
}
let mut offenders = Vec::new();
visit(&stdlib_dir(), &mut offenders);
assert!(
offenders.is_empty(),
"stdlib bundle must not depend on foreign/plugin calls: {offenders:?}"
);
}
#[test]
fn missing_bundle_manifest_is_a_hard_error() {
let dir = TempDir::new("missing");
let empty = dir.path().join("empty-stdlib");
std::fs::create_dir_all(&empty).unwrap();
write_project(dir.path(), IMPORT_IO);
let output = run(dir.path(), &empty, &["run", "index.mq.md"]);
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("stdlib"), "{stderr}");
}
+43
View File
@@ -0,0 +1,43 @@
//! CM-A08/P5 stdlib HTTP framing module tests.
use std::path::Path;
use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
#[test]
fn stdlib_http_parses_chunked_responses_and_builds_requests() {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/http.mq.md", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run http self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["decimal"], "200");
assert_eq!(items[1]["value"], "OK");
assert_eq!(items[2]["value"], "text/plain");
assert_eq!(items[3]["value"], "hello world");
assert_eq!(
items[4]["value"],
"POST /echo HTTP/1.1\r\nHost: example.test\r\nContent-Length: 2\r\n\r\nok"
);
assert_eq!(items[5]["decimal"], "200");
assert_eq!(items[6]["value"], "你好");
assert_eq!(items[7]["value"], "POST / HTTP/1.1\r\n\r\nAB");
}
+511
View File
@@ -0,0 +1,511 @@
//! Product-level tests for the whole bundled `marqdo-stdlib` tree.
//!
//! Every public module in `stdlib/README.md` has a `.mq.md` self-test under
//! `stdlib/tests/`, and this lane runs the whole directory through the real
//! user import path (`std:` + the verified bundle), not through a conformance
//! fixture or a Rust shortcut.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard};
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
static FS_LOCK: Mutex<()> = Mutex::new(());
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
if name == "fs.mq.md" {
Some(FS_LOCK.lock().unwrap_or_else(|error| error.into_inner()))
} else {
None
}
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
}
struct TestFile {
name: String,
stdin: &'static str,
stdout: &'static str,
args: Vec<String>,
env: Vec<(String, String)>,
}
fn product_tests() -> Vec<TestFile> {
let dir = stdlib_dir().join("tests");
let mut files: Vec<TestFile> = std::fs::read_dir(&dir)
.expect("read stdlib tests")
.map(|entry| {
let path = entry.unwrap().path();
if !path.is_file() {
return TestFile {
name: String::new(),
stdin: "",
stdout: "",
args: Vec::new(),
env: Vec::new(),
};
}
let name = path.file_name().unwrap().to_string_lossy().to_string();
let (stdin, stdout) = match name.as_str() {
"console.mq.md" => ("hello\n", ""),
"io.mq.md" => ("", "stdlib self-test\n"),
"stream.mq.md" => ("", "stream\n"),
_ => ("", ""),
};
let text_args = |values: &[&str]| -> Vec<String> {
values.iter().map(|value| value.to_string()).collect()
};
let (args, env) = if name == "fs.mq.md" {
(
text_args(&[
"--allow-read",
"out",
"--allow-read",
"out/**",
"--allow-write",
"out",
"--allow-write",
"out/**",
]),
Vec::new(),
)
} else if name == "env.mq.md" {
(
text_args(&[
"--allow-env",
"MARQDO_TEST_ENV",
"--allow-env",
"MARQDO_MISSING_ENV",
]),
vec![("MARQDO_TEST_ENV".to_string(), "env-value".to_string())],
)
} else if name == "process.mq.md" {
// Use the test binary itself as the granted program: it exists
// on every native platform, unlike the old `/bin/echo` fixture.
let program = env!("CARGO_BIN_EXE_marqdo").to_string();
(
vec![
"--allow-env".to_string(),
"MARQDO_TEST_PROCESS_PROGRAM".to_string(),
"--allow-process".to_string(),
program.clone(),
],
vec![("MARQDO_TEST_PROCESS_PROGRAM".to_string(), program)],
)
} else if name == "random.mq.md" {
(text_args(&["--allow-random"]), Vec::new())
} else {
(Vec::new(), Vec::new())
};
TestFile {
name,
stdin,
stdout,
args,
env,
}
})
.filter(|file| !file.name.is_empty())
.collect();
files.sort_by(|left, right| left.name.cmp(&right.name));
files
}
fn run_product_test(file: &TestFile) -> serde_json::Value {
if file.name == "fs.mq.md" {
let _ = std::fs::remove_dir_all(stdlib_dir().join("tests/out"));
}
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run"])
.arg(stdlib_dir().join("tests").join(&file.name))
.args(file.args.iter())
.args(["--json"])
.current_dir(stdlib_dir())
.env("MARQDO_STDLIB_DIR", stdlib_dir())
.envs(
file.env
.iter()
.map(|(key, value)| (key.as_str(), value.as_str())),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo");
child
.stdin
.as_mut()
.unwrap()
.write_all(file.stdin.as_bytes())
.unwrap();
let output = child.wait_with_output().expect("wait marqdo");
assert_eq!(
output.status.code(),
Some(0),
"{} failed: {}",
file.name,
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json report")
}
#[test]
fn every_public_stdlib_module_has_a_product_test() {
let names: Vec<String> = product_tests().into_iter().map(|file| file.name).collect();
assert_eq!(
names,
vec![
"clock.mq.md",
"compress.mq.md",
"console.mq.md",
"csv.mq.md",
"datetime.mq.md",
"demo.mq.md",
"env.mq.md",
"format.mq.md",
"fs.mq.md",
"http.mq.md",
"io.mq.md",
"json.mq.md",
"path.mq.md",
"process.mq.md",
"random.mq.md",
"regex.mq.md",
"stream.mq.md",
"table.mq.md",
"text.mq.md",
"utf8.mq.md",
],
"a public stdlib module is missing a product test"
);
}
#[test]
fn the_whole_bundled_library_runs_through_std_imports() {
for file in product_tests() {
let _guard = lock_fs(&file.name);
let report = run_product_test(&file);
assert_eq!(report["success"], true, "{}", file.name);
assert_eq!(
report["stdout"], file.stdout,
"{} wrote unexpected stdout",
file.name
);
}
}
#[test]
fn fs_test_exercises_the_file_operation_surface() {
let _guard = lock_fs("fs.mq.md");
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "fs.mq.md")
.expect("fs test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "7");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "file");
assert_eq!(items[4]["decimal"], "7");
assert_eq!(items[5]["items"][0]["value"], "fs-a.txt");
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], "你好\n");
assert_eq!(items[10]["decimal"], "7");
assert_eq!(items[11]["value"], "你好\n世界\n");
assert_eq!(items[12]["items"][0]["value"], "fs-b.txt");
assert_eq!(items[13]["value"], true);
assert_eq!(items[14]["value"], true);
assert!(
!stdlib_dir().join("tests/out").exists(),
"the fs test did not remove its directory"
);
}
#[test]
fn json_test_parses_and_formats_nested_values() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "json.mq.md")
.expect("json test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "1");
assert_eq!(items[2]["value"], "说\"好");
assert_eq!(
items[3]["value"],
"[1, 2.5, -300.0, 0.4, {\"a\": 1.0}, \"x\"]"
);
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "json.invalid_array");
assert_eq!(items[6]["value"], "json.trailing");
assert_eq!(items[7]["value"], false);
assert_eq!(items[8]["value"], "json.depth");
assert_eq!(items[9]["value"], true);
assert_eq!(items[10]["items"][2]["items"][0]["decimal"], "3");
}
#[test]
fn csv_test_parses_and_formats_quoted_rows() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "csv.mq.md")
.expect("csv test"),
);
let items = report["value"]["items"].as_array().expect("list");
let row = items[0]["items"].as_array().expect("row");
assert_eq!(row.len(), 3);
assert_eq!(row[0]["value"], "甲");
assert_eq!(row[1]["value"], "乙,丙");
assert_eq!(row[2]["value"], "说\"好");
assert_eq!(items[1]["value"], "甲,\"乙,丙\",\"说\"\"好\"");
let empty = items[2]["items"].as_array().expect("empty row");
assert_eq!(empty.len(), 1);
assert_eq!(empty[0]["value"], "");
assert_eq!(items[3]["value"], "csv.unterminated_quote");
let quoted = items[4]["items"].as_array().expect("quoted row");
assert_eq!(quoted[0]["value"], "a");
assert_eq!(quoted[1]["value"], "b");
assert_eq!(items[5]["value"], true);
let rows = items[6]["items"].as_array().expect("rows");
assert_eq!(rows.len(), 2);
assert_eq!(rows[1]["items"][0]["value"], "说\"好");
assert_eq!(items[7]["value"], "甲,\"乙,丙\"\n\"说\"\"好\",2");
}
#[test]
fn path_test_joins_and_normalizes_project_paths() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "path.mq.md")
.expect("path test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], "a/b/c");
assert_eq!(items[1]["value"], "c.txt");
assert_eq!(items[2]["value"], "a/b");
assert_eq!(items[3]["value"], "txt");
assert_eq!(items[4]["value"], "a/c");
assert_eq!(items[5]["value"], "/a/c");
assert_eq!(items[6]["value"], "../a/b");
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], false);
}
#[test]
fn regex_test_matches_anchors_classes_and_search() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "regex.mq.md")
.expect("regex test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], false);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
assert_eq!(items[5]["value"], true);
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], false);
assert_eq!(items[10]["value"], "regex.invalid");
assert_eq!(items[11]["value"], "regex.unsupported");
assert_eq!(items[12]["value"], true);
assert_eq!(items[13]["value"], true);
let groups = items[14]["items"].as_array().expect("groups");
assert_eq!(groups[0]["value"], "aab");
assert_eq!(groups[1]["value"], "aa");
assert_eq!(groups[2]["value"], "b");
}
#[test]
fn datetime_test_formats_and_parses_utc_instants() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "datetime.mq.md")
.expect("datetime test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z");
assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z");
assert_eq!(items[2]["decimal"], "0");
assert_eq!(items[3]["decimal"], "1795248000123");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], false);
assert_eq!(items[6]["value"], "1969-12-31T23:59:59.999Z");
}
#[test]
fn clock_test_reports_project_mode_unix_millis() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "clock.mq.md")
.expect("clock test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], "Int");
assert_eq!(items[2]["value"], true);
}
#[test]
fn env_test_reads_only_granted_names() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "env.mq.md")
.expect("env test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "env-value");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "env.not_found");
}
#[test]
fn process_test_runs_an_explicitly_granted_program() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "process.mq.md")
.expect("process test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "0");
let expected = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.arg("--version")
.output()
.expect("run marqdo --version");
let expected_stdout = String::from_utf8_lossy(&expected.stdout);
assert_eq!(
items[2]["value"].as_str().expect("process stdout"),
expected_stdout.as_ref(),
"process stdout must match the granted program"
);
assert_eq!(items[3]["value"], "");
}
#[test]
fn random_test_reads_bounded_entropy() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "random.mq.md")
.expect("random test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "16");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
}
#[test]
fn compress_test_round_trips_gzip_text() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "compress.mq.md")
.expect("compress test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "hello 世界");
}
#[test]
fn format_test_pins_value_semantics_and_handle_observation() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "format.mq.md")
.expect("format test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["decimal"], "3");
assert_eq!(items[1]["value"], "[\"文本\", 2, 1.5]");
assert_eq!(items[2]["value"], "{a: 1}");
assert_eq!(items[3]["value"], "[\"a\", 2]");
assert_eq!(items[4]["value"], "None");
}
#[test]
fn text_and_utf8_tests_agree_on_the_byte_encoding() {
let text = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "text.mq.md")
.expect("text test"),
);
let utf8 = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "utf8.mq.md")
.expect("utf8 test"),
);
assert_eq!(text["value"]["items"][0]["decimal"], "2");
assert_eq!(text["value"]["items"][1]["decimal"], "195");
assert_eq!(text["value"]["items"][2]["decimal"], "169");
assert_eq!(utf8["value"]["items"][0]["decimal"], "2");
assert_eq!(utf8["value"]["items"][1]["value"], "é");
assert_eq!(utf8["value"]["items"][2]["value"], false);
}
#[test]
fn stream_and_console_use_the_resource_endpoints() {
let stream = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "stream.mq.md")
.expect("stream test"),
);
assert_eq!(stream["value"]["items"][0]["value"], true);
assert_eq!(stream["value"]["items"][1]["decimal"], "7");
let console = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "console.mq.md")
.expect("console test"),
);
assert_eq!(console["value"]["items"][0]["value"], true);
assert_eq!(console["value"]["items"][1]["value"], "hello");
assert!(
console["trace"]
.as_array()
.unwrap()
.iter()
.any(|event| event["op"] == "resource.read" || event["op"] == "resource.open"),
"console test did not go through a resource endpoint"
);
}
+72
View File
@@ -0,0 +1,72 @@
//! CM-A08 table stdlib module tests.
use std::path::Path;
use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn run_table_self_test() -> serde_json::Value {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/table.mq.md", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json output")
}
fn rows(value: &serde_json::Value) -> &Vec<serde_json::Value> {
value["rows"].as_array().expect("rows")
}
#[test]
fn stdlib_table_algorithms_rebuild_without_mutating_inputs() {
let report = run_table_self_test();
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items.len(), 9);
assert_eq!(items[0]["header"], serde_json::json!(["分数"]));
assert_eq!(items[0]["rows"].as_array().unwrap().len(), 3);
assert_eq!(rows(&items[1]).len(), 2);
assert_eq!(rows(&items[2]).len(), 3);
assert_eq!(rows(&items[2])[0][1]["decimal"], "71");
assert_eq!(rows(&items[3]).len(), 4);
assert_eq!(rows(&items[3])[3][0]["value"], "丁");
assert_eq!(rows(&items[4])[0][1]["decimal"], "99");
assert_eq!(rows(&items[5]).len(), 2);
assert_eq!(items[5]["header"].as_array().unwrap().len(), 4);
assert_eq!(
items[6]["entries"]["a"]["items"].as_array().unwrap().len(),
2
);
assert_eq!(
items[6]["entries"]["b"]["items"].as_array().unwrap().len(),
1
);
// Original input is unchanged.
assert_eq!(rows(&items[7]).len(), 3);
assert_eq!(rows(&items[7])[0][1]["decimal"], "87");
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
+41 -7
View File
@@ -95,7 +95,7 @@ fn write_tool(dir: &Path, command: &str, _script: &str) -> PathBuf {
std::fs::write(
&manifest,
format!(
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=0.1,<1"}}}}"#
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0"}}}}"#
),
)
.unwrap();
@@ -142,7 +142,7 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
std::fs::write(
&manifest,
format!(
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=0.1,<1","analysis":[2],"trace":[2]}}}}"#
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0","analysis":[2],"trace":[2]}}}}"#
),
)
.unwrap();
@@ -301,7 +301,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
let incompatible = std::fs::read_to_string(&manifest)
.unwrap()
.replace(">=0.1,<1", ">=99.0");
.replace(">=3.0.0-beta.1,<4.0.0", ">=99.0");
let incompatible_manifest = dir.path().join("incompatible.json");
std::fs::write(&incompatible_manifest, incompatible).unwrap();
let output = cli(
@@ -364,8 +364,8 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
"#!/bin/sh\nprintf 'analysis=%s\\ntrace=%s\\n' \"$MARQDO_PROTOCOL_ANALYSIS\" \"$MARQDO_PROTOCOL_TRACE\"\n",
);
let text = std::fs::read_to_string(&manifest).unwrap().replace(
"\"marqdo\":\">=0.1,<1\"",
"\"marqdo\":\">=0.1,<1\",\"analysis\":[2],\"trace\":[2]",
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"",
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",\"analysis\":[2],\"trace\":[2]",
);
std::fs::write(&manifest, text).unwrap();
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
@@ -384,8 +384,8 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
let command = format!("bad-{tag}");
let manifest = write_tool(dir.path(), &command, "#!/bin/sh\nexit 0\n");
let text = std::fs::read_to_string(&manifest).unwrap().replace(
"\"marqdo\":\">=0.1,<1\"",
&format!("\"marqdo\":\">=0.1,<1\",{compat}"),
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"",
&format!("\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",{compat}"),
);
std::fs::write(&manifest, text).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
@@ -449,3 +449,37 @@ fn a_root_record_json_in_the_source_package_is_rejected() {
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("must not contain a root record.json"));
}
#[test]
fn beta_core_requires_an_explicit_prerelease_compatible_range() {
let dir = TempDir::new("prerelease-range");
let home = dir.path().join("home");
let core = env!("CARGO_PKG_VERSION");
// The shipped example range opt-in must install on this real core.
let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n");
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
if core.contains('-') {
// SemVer: a stable-only requirement must not silently accept a
// prerelease core. The operator has to opt in with a prerelease range.
let manifest = write_tool(dir.path(), "stableonly", "#!/bin/sh\nexit 0\n");
let text = std::fs::read_to_string(&manifest)
.unwrap()
.replace(">=3.0.0-beta.1,<4.0.0", ">=3.0.0,<4.0.0");
std::fs::write(&manifest, text).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(
output.status.code(),
Some(1),
"a stable-only range must reject prerelease core {core}: {}",
stderr(&output)
);
assert!(
stderr(&output).contains("requires marqdo"),
"{}",
stderr(&output)
);
}
}
+39 -4
View File
@@ -195,15 +195,50 @@ impl Expr {
}
}
/// The payload of a statement.
/// The writable target on the left of `=` (ADR-0022).
///
/// v1 accepted only [`AssignTarget::Local`]. RFC-CM-0001 adds the second
/// variant because addressable `Memory` needs a writable place; no other
/// collection becomes mutable. Both variants use the same assignment syntax
/// and the same statement position.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StatementKind {
/// `<bare identifier> = <expression>`; the only assignment form in v1.
Assign {
#[serde(tag = "place", rename_all = "snake_case")]
pub enum AssignTarget {
/// `name = value`: rebind a local slot in the current frame.
Local {
/// Assigned identifier.
name: String,
/// Span of the identifier token (not the whole assignment).
name_span: Span,
},
/// `base[index] = value`: write one byte into an addressable `Memory`.
Index {
/// Base expression, evaluated first.
base: Box<Expr>,
/// Index expression, evaluated second.
index: Box<Expr>,
/// Span from the base start through the closing `]`.
span: Span,
},
}
impl AssignTarget {
/// Best known source span of the assignment target.
pub fn span(&self) -> Span {
match self {
AssignTarget::Local { name_span, .. } => *name_span,
AssignTarget::Index { span, .. } => *span,
}
}
}
/// The payload of a statement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StatementKind {
/// `target = expression`; see [`AssignTarget`] for the writable places.
Assign {
/// Assigned place.
target: AssignTarget,
/// Right-hand side expression.
value: Expr,
},
+18
View File
@@ -41,6 +41,18 @@ pub enum TokenKind {
Or,
/// `not`
Not,
/// `if` (statement keyword, not an identifier)
If,
/// `else` (statement keyword)
Else,
/// `while` (statement keyword)
While,
/// `end` (statement keyword)
End,
/// `return` (statement keyword)
Return,
/// `params` (signature keyword)
Params,
/// `(`
LParen,
/// `)`
@@ -307,6 +319,12 @@ impl<'a> Lexer<'a> {
"and" => TokenKind::And,
"or" => TokenKind::Or,
"not" => TokenKind::Not,
"if" => TokenKind::If,
"else" => TokenKind::Else,
"while" => TokenKind::While,
"end" => TokenKind::End,
"return" => TokenKind::Return,
"params" => TokenKind::Params,
_ => TokenKind::Ident(text.to_owned()),
}
}
+29 -15
View File
@@ -1,10 +1,12 @@
//! Strict, independent expression and statement parser for executable Markdown
//! payloads.
//! Strict, independent payload statement and expression parser for executable
//! Markdown payloads.
//!
//! This crate is the only grammar for Marqdo executable payloads. It knows
//! nothing about Markdown and nothing about the runtime: the Markdown AST
//! decides *where* a payload exists, this crate decides *what the payload
//! means* (see `spec/expression.ebnf` and `spec/evaluation.md`).
//! means* (see `spec/expression.ebnf` and `spec/evaluation.md`). The
//! [`statement`] module owns the `if`/`else`/`while`/`end`/`return`/`params`
//! statement keywords; the parser here owns their expressions.
//!
//! # Public API
//!
@@ -21,10 +23,15 @@
//! The contractual surface is:
//!
//! * [`parse_expression`] — parse a complete expression payload.
//! * [`parse_statement`] — parse a complete statement payload (assignment or
//! expression).
//! * [`parse_arguments`] — parse a leading `( ... )` argument list, used for
//! Markdown-link calls such as `> [计算面积](./math.mq.md#计算面积)(r=3)`.
//! * [`parse_payload_statement`]/[`PayloadStatement`] — parse one complete
//! payload under the v2 statement grammar (control keyword, `params`, or an
//! ordinary assignment/expression).
//! * [`parse_statement`] — parse a complete assignment/expression payload
//! (without control keywords).
//! * [`parse_arguments`] — parse a leading `( ... )` argument list. There is no
//! Markdown-link call in the current language; this remains the shared
//! argument-list grammar used by callers that must parse arguments without a
//! callee (for example builtin signature validation tests).
//! * the [`ast`] module (re-exported at the crate root).
//! * [`ParseError`] — structured `expr.parse` diagnostics with byte spans.
//!
@@ -33,11 +40,14 @@
//!
//! # Grammar summary
//!
//! The grammar is frozen in `spec/expression.ebnf`. In order of decreasing
//! precedence: prefix `not` / `-` / `+`, `**` (right associative), postfix
//! calls `.name` / `[index]`, `* / // %`, `+ -`, a single non-associative
//! comparison, `and`, `or`. Assignment is only available at statement start
//! and only for a bare identifier target.
//! The grammar is frozen in `spec/expression.ebnf`. One payload is exactly one
//! statement: `if <expr>`, `else`, `while <expr>`, `end`, `return <expr>`,
//! `params(...)`, an assignment or a bare expression. Within an expression, in
//! order of decreasing precedence: prefix `not` / `-` / `+`, `**` (right
//! associative), postfix calls `.name` / `[index]`, `* / // %`, `+ -`, a single
//! non-associative comparison, `and`, `or`. Assignment is only available at
//! statement start; its target is a bare identifier or an index expression
//! (`m[8] = 42`).
//!
//! Notable lexical rules:
//!
@@ -79,14 +89,18 @@
pub mod ast;
pub mod lexer;
mod parser;
pub mod statement;
use std::fmt;
use serde::Serialize;
pub use ast::{Arg, BinaryOp, Expr, Ident, RecordEntry, Statement, StatementKind, UnaryOp};
pub use ast::{
Arg, AssignTarget, BinaryOp, Expr, Ident, RecordEntry, Statement, StatementKind, UnaryOp,
};
pub use marqdo_span::Span;
pub use parser::MAX_NESTING_DEPTH;
pub use statement::{parse_payload_statement, PayloadStatement};
/// Stable diagnostic code for every expression parse failure.
pub const EXPR_PARSE: &str = "expr.parse";
@@ -152,8 +166,8 @@ pub fn parse_statement(source: &str) -> Result<Statement, ParseError> {
/// positional arguments precede named arguments, named arguments are unique,
/// and a single trailing comma is allowed. Trailing tokens are an error.
///
/// This exists so the frontend can parse Markdown-link calls of the form
/// `> [计算面积](./math.mq.md#计算面积)(r=3)` without re-lexing the payload.
/// This is the shared argument-list grammar (call postfixes and callers that
/// validate arguments without a callee expression).
pub fn parse_arguments(source: &str) -> Result<Vec<Arg>, ParseError> {
parser::parse_arguments(source)
}
+139 -40
View File
@@ -17,7 +17,9 @@
//! recursing into any sub-expression so adversarial inputs fail with a
//! structured [`ParseError`] instead of overflowing the stack.
use crate::ast::{Arg, BinaryOp, Expr, Ident, RecordEntry, Statement, StatementKind, UnaryOp};
use crate::ast::{
Arg, AssignTarget, BinaryOp, Expr, Ident, RecordEntry, Statement, StatementKind, UnaryOp,
};
use crate::lexer::{self, Token, TokenKind};
use crate::ParseError;
use marqdo_span::Span;
@@ -47,21 +49,16 @@ pub(crate) fn parse_statement(source: &str) -> Result<Statement, ParseError> {
return Err(parser.error_here("expected a statement, found end of input"));
}
let start = parser.peek().span.start;
if let TokenKind::Ident(_) = parser.peek().kind {
if matches!(
parser.peek_n(1).map(|token| &token.kind),
Some(TokenKind::Assign)
) {
return parser.assignment(start);
}
let left = parser.expression()?;
if matches!(parser.peek().kind, TokenKind::Assign) {
return parser.assignment(start, left);
}
let expr = parser.expression()?;
if !parser.at_eof() {
return Err(parser.trailing_statement_error(&expr));
return Err(parser.trailing_statement_error());
}
let end = parser.previous_end();
Ok(Statement {
kind: StatementKind::Expr(expr),
kind: StatementKind::Expr(left),
span: Span::new(start, end),
})
}
@@ -201,11 +198,8 @@ impl Parser {
// Statements
// ------------------------------------------------------------------
fn assignment(&mut self, start: usize) -> Result<Statement, ParseError> {
let TokenKind::Ident(name) = self.peek().kind.clone() else {
return Err(self.error_here("expected an identifier on the left of `=`"));
};
let name_token = self.bump();
fn assignment(&mut self, start: usize, left: Expr) -> Result<Statement, ParseError> {
let target = self.assign_target(left)?;
self.bump(); // `=`
if self.at_eof() {
return Err(self.error_here("expected an expression after `=`"));
@@ -226,29 +220,40 @@ impl Parser {
}
let end = self.previous_end();
Ok(Statement {
kind: StatementKind::Assign {
name,
name_span: name_token.span,
value,
},
kind: StatementKind::Assign { target, value },
span: Span::new(start, end),
})
}
fn trailing_statement_error(&self, expr: &Expr) -> ParseError {
if matches!(self.peek().kind, TokenKind::Assign) {
return if matches!(expr, Expr::Member { .. } | Expr::Index { .. }) {
self.error_here(
"invalid assignment target: member and index assignment are not supported \
in v1; assign a bare identifier",
)
} else {
self.error_here(
"invalid assignment target: assignment requires a bare identifier on the \
left of `=`",
)
};
/// Turn the already-parsed left expression into a writable target.
///
/// v1 only writes local slots. Addressable `Memory` adds index targets;
/// member assignment and every other shape stay hard parse errors so an
/// invalid executable shape never silently becomes prose (ADR-0022).
fn assign_target(&self, left: Expr) -> Result<AssignTarget, ParseError> {
match left {
Expr::Ident(Ident { name, span }) => Ok(AssignTarget::Local {
name,
name_span: span,
}),
Expr::Index { base, index, span } => Ok(AssignTarget::Index { base, index, span }),
Expr::Member { span, .. } => Err(ParseError::new(
span,
"member assignment is not supported in v1; only a local name or a \
Memory index is writable",
)),
other => Err(ParseError::new(
other.span(),
format!(
"invalid assignment target: {} is not a writable place; assign a local \
name or a Memory index",
describe_expr(&other)
),
)),
}
}
fn trailing_statement_error(&self) -> ParseError {
self.error_here(format!(
"unexpected {} after expression",
self.describe_current()
@@ -702,9 +707,33 @@ fn is_keyword(kind: &TokenKind) -> bool {
| TokenKind::And
| TokenKind::Or
| TokenKind::Not
| TokenKind::If
| TokenKind::Else
| TokenKind::While
| TokenKind::End
| TokenKind::Return
| TokenKind::Params
)
}
fn describe_expr(expr: &Expr) -> &'static str {
match expr {
Expr::Int(_) => "an integer literal",
Expr::Float(_) => "a float literal",
Expr::Text(_) => "a text literal",
Expr::Bool(_) => "a boolean literal",
Expr::None => "`None`",
Expr::Ident(_) => "an identifier",
Expr::List(_) => "a list literal",
Expr::Record(_) => "a record literal",
Expr::Unary { .. } => "a unary expression",
Expr::Binary { .. } => "a binary expression",
Expr::Call { .. } => "a call expression",
Expr::Member { .. } => "a member access",
Expr::Index { .. } => "an index expression",
}
}
fn describe_token(kind: &TokenKind) -> String {
match kind {
TokenKind::Int(raw) => format!("integer literal `{raw}`"),
@@ -717,6 +746,12 @@ fn describe_token(kind: &TokenKind) -> String {
TokenKind::And => "`and`".to_owned(),
TokenKind::Or => "`or`".to_owned(),
TokenKind::Not => "`not`".to_owned(),
TokenKind::If => "`if`".to_owned(),
TokenKind::Else => "`else`".to_owned(),
TokenKind::While => "`while`".to_owned(),
TokenKind::End => "`end`".to_owned(),
TokenKind::Return => "`return`".to_owned(),
TokenKind::Params => "`params`".to_owned(),
TokenKind::LParen => "`(`".to_owned(),
TokenKind::RParen => "`)`".to_owned(),
TokenKind::LBracket => "`[`".to_owned(),
@@ -1154,14 +1189,19 @@ mod tests {
assert_eq!(
stmt.kind,
StatementKind::Assign {
name: "x".to_owned(),
name_span: Span::new(0, 1),
target: AssignTarget::Local {
name: "x".to_owned(),
name_span: Span::new(0, 1),
},
value: Expr::Int(BigInt::from(1)),
}
);
let stmt = st("结果 = 阶乘(n=3)");
match &stmt.kind {
StatementKind::Assign { name, value, .. } => {
StatementKind::Assign {
target: AssignTarget::Local { name, .. },
value,
} => {
assert_eq!(name, "结果");
assert_eq!(sexpr(value), "(call 阶乘 n=3)");
}
@@ -1170,6 +1210,40 @@ mod tests {
assert_eq!(st("x = y + 1").span(), Span::new(0, 9));
}
#[test]
fn memory_index_assignment_parses_as_a_place() {
let stmt = st("m[8] = 42");
let StatementKind::Assign { target, value } = &stmt.kind else {
panic!("expected assignment, got {:?}", stmt.kind);
};
let AssignTarget::Index { base, index, span } = target else {
panic!("expected index target, got {target:?}");
};
assert_eq!(
**base,
Expr::Ident(Ident {
name: "m".to_owned(),
span: Span::new(0, 1),
})
);
assert_eq!(**index, Expr::Int(BigInt::from(8)));
assert_eq!(*span, Span::new(0, 4));
assert_eq!(*value, Expr::Int(BigInt::from(42)));
assert_eq!(stmt.span, Span::new(0, 9));
// Nested targets are syntactically places; the runtime decides whether
// the base value is a writable Memory region.
let stmt = st("outer[0][1] = 2");
let StatementKind::Assign {
target: AssignTarget::Index { base, .. },
..
} = &stmt.kind
else {
panic!("expected nested index target, got {:?}", stmt.kind);
};
assert!(matches!(base.as_ref(), Expr::Index { .. }));
}
#[test]
fn expression_statements_parse() {
assert_eq!(st("打印(1)").kind, StatementKind::Expr(ex("打印(1)")));
@@ -1185,8 +1259,8 @@ mod tests {
"x =",
"x = 1 = 2",
"a.b = 1",
"a[0] = 1",
"1 = 2",
"f() = 1",
"= 1",
"x = 1 2",
] {
@@ -1194,7 +1268,8 @@ mod tests {
assert_eq!(err.code, "expr.parse", "input {bad:?}");
}
assert!(st_err("x = 1 = 2").message.contains("chained assignment"));
assert!(st_err("a.b = 1").message.contains("member and index"));
assert!(st_err("a.b = 1").message.contains("member assignment"));
assert!(st_err("1 = 2").message.contains("writable place"));
assert!(st_err("x =").message.contains("after `=`"));
}
@@ -1228,7 +1303,10 @@ mod tests {
let stmt = st(" x = 1 ");
assert_eq!(stmt.span(), Span::new(2, 7));
match stmt.kind {
StatementKind::Assign { name_span, .. } => assert_eq!(name_span, Span::new(2, 3)),
StatementKind::Assign {
target: AssignTarget::Local { name_span, .. },
..
} => assert_eq!(name_span, Span::new(2, 3)),
other => panic!("expected assignment, got {other:?}"),
}
@@ -1299,8 +1377,29 @@ mod tests {
format!("{}1{}", "(".repeat(depth), ")".repeat(depth))
}
/// Run a deeply recursive parser test on an explicit stack.
///
/// The test harness gives each test thread a small stack on some native
/// platforms (macOS arm64 aborted with a stack overflow at the 128-level
/// nesting check). Production parsing happens on the main thread; pinning
/// this test to 8 MiB keeps the contract test meaningful without depending
/// on the harness default.
fn with_parser_stack<F: FnOnce() + Send + 'static>(body: F) {
std::thread::Builder::new()
.name("parser-nesting-depth".to_string())
.stack_size(8 * 1024 * 1024)
.spawn(body)
.expect("spawn parser nesting thread")
.join()
.expect("parser nesting thread panicked");
}
#[test]
fn nesting_depth_limit_is_enforced() {
with_parser_stack(nesting_depth_limit_is_enforced_body);
}
fn nesting_depth_limit_is_enforced_body() {
assert!(parse_expression(&nested_parens(MAX_NESTING_DEPTH)).is_ok());
let err = parse_expression(&nested_parens(MAX_NESTING_DEPTH + 1)).unwrap_err();
assert_eq!(err.code, "expr.parse");
+229
View File
@@ -0,0 +1,229 @@
//! The v2 payload statement grammar (RFC-LANG-0002).
//!
//! One Markdown carrier holds exactly one payload. This module is the only
//! place that decides whether that payload is a control statement
//! (`if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an
//! ordinary assignment/expression. The frontend still owns pairing the control
//! words into blocks; this module owns their lexical recognition and the
//! expression grammar they embed.
//!
//! Keyword matching is by complete token: `ifdef(x)` and `returning()` are
//! ordinary calls, while a bare `if` used as an identifier is a reserved-word
//! error. `if`/`while`/`return` require whitespace before their expression and
//! the whole payload must be consumed.
use crate::ast::{Expr, Statement};
use crate::lexer::{self, TokenKind};
use crate::{parse_expression, parse_statement, ParseError};
use marqdo_span::Span;
/// A payload parsed by the v2 statement grammar.
#[derive(Debug, Clone, PartialEq)]
pub enum PayloadStatement {
/// `if <expr>`
If(Expr),
/// `else` (no expression)
Else,
/// `while <expr>`
While(Expr),
/// `end` (no expression)
End,
/// `return <expr>`
Return(Expr),
/// `params(...)`; the parameter list itself is validated by the frontend
/// signature parser, which owns IR parameter types and defaults.
Params,
/// An ordinary assignment or expression statement.
Ordinary(Statement),
}
/// Parse one complete executable payload under the v2 statement grammar.
///
/// The input is the concatenated carrier text, already trimmed or not; leading
/// and trailing whitespace is ignored. Expressions keep byte spans relative to
/// the original payload, including the keyword prefix, so diagnostics and IR
/// source maps point inside the file after the frontend rewrites them.
pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseError> {
let trimmed = source.trim();
if trimmed.is_empty() {
return Err(ParseError::new(Span::empty(0), "empty executable payload"));
}
// `params(...)` is a declaration whose interior is validated by
// `signature::parse`; recognize the prefix before tokenizing so malformed
// parameter text (for example `params(1x: Int)`) is reported once by the
// signature parser instead of as a lexer failure.
if trimmed.starts_with("params(") {
return Ok(PayloadStatement::Params);
}
if trimmed == "params" || trimmed.starts_with("params ") || trimmed.starts_with("params\t") {
return Err(ParseError::new(
Span::new(0, "params".len()),
"malformed params declaration; write `params(name: Type, ...)`",
));
}
let tokens = lexer::tokenize(trimmed)?;
let first = tokens.first().expect("tokenize always returns EOF");
match first.kind {
TokenKind::If => {
let expr = control_expression(trimmed, first.span, "if")?;
Ok(PayloadStatement::If(expr))
}
TokenKind::While => {
let expr = control_expression(trimmed, first.span, "while")?;
Ok(PayloadStatement::While(expr))
}
TokenKind::Return => {
let expr = control_expression(trimmed, first.span, "return")?;
Ok(PayloadStatement::Return(expr))
}
TokenKind::Else => {
require_only_keyword(&tokens, "else")?;
Ok(PayloadStatement::Else)
}
TokenKind::End => {
require_only_keyword(&tokens, "end")?;
Ok(PayloadStatement::End)
}
TokenKind::Params => Err(ParseError::new(
first.span,
"malformed params declaration; write `params(name: Type, ...)`",
)),
_ => parse_statement(trimmed).map(PayloadStatement::Ordinary),
}
}
fn control_expression(source: &str, keyword: Span, name: &str) -> Result<Expr, ParseError> {
let rest = &source[keyword.end..];
if rest.is_empty() || !rest.starts_with(char::is_whitespace) {
return Err(ParseError::new(
keyword,
format!("`{name}` must be followed by whitespace and an expression"),
));
}
// Pad the expression so its AST spans stay payload-relative.
let padded = format!("{}{}", " ".repeat(keyword.end), rest);
parse_expression(&padded)
}
fn require_only_keyword(tokens: &[crate::lexer::Token], name: &str) -> Result<(), ParseError> {
let mut non_eof = tokens
.iter()
.filter(|token| !matches!(token.kind, TokenKind::Eof));
let _keyword = non_eof.next();
if let Some(extra) = non_eof.next() {
return Err(ParseError::new(
extra.span,
format!("`{name}` takes no expression"),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn expr_of(source: &str) -> Expr {
match parse_payload_statement(source).expect("valid payload") {
PayloadStatement::If(expr)
| PayloadStatement::While(expr)
| PayloadStatement::Return(expr) => expr,
other => panic!("unexpected payload: {other:?}"),
}
}
#[test]
fn parses_control_statements_with_payload_relative_spans() {
for keyword in ["if", "while", "return"] {
let source = format!("{keyword} x > 0");
let expr = expr_of(&source);
assert_eq!(expr.span().start, keyword.len() + 1);
}
}
#[test]
fn else_and_end_are_exact_payloads() {
assert_eq!(
parse_payload_statement("else").unwrap(),
PayloadStatement::Else
);
assert_eq!(
parse_payload_statement("end").unwrap(),
PayloadStatement::End
);
assert!(parse_payload_statement("else x").is_err());
assert!(parse_payload_statement("end if").is_err());
}
#[test]
fn keywords_require_whitespace_and_an_expression() {
for source in ["if", "while", "return", "if(x)", "while(1)", "return(x)"] {
assert!(
parse_payload_statement(source).is_err(),
"{source} must be rejected"
);
}
}
#[test]
fn control_expressions_must_consume_the_payload() {
assert!(parse_payload_statement("if x > 0:").is_err());
assert!(parse_payload_statement("if x y").is_err());
}
#[test]
fn keyword_prefixes_are_ordinary_identifiers() {
for source in ["ifdef(x)", "returning(x)", "endpoint(x)", "while_count(x)"] {
match parse_payload_statement(source).unwrap() {
PayloadStatement::Ordinary(statement) => {
assert!(matches!(statement.kind, crate::StatementKind::Expr(_)));
}
other => panic!("{source} parsed as {other:?}"),
}
}
}
#[test]
fn bare_keywords_are_reserved_in_expressions() {
for source in ["x = if", "x = return", "[else]", "{while: 1}"] {
assert!(parse_payload_statement(source).is_err(), "{source}");
}
}
#[test]
fn params_are_recognized_before_signature_validation() {
assert_eq!(
parse_payload_statement("params(n: Int)").unwrap(),
PayloadStatement::Params
);
// Interior validation belongs to `signature::parse`; the statement
// grammar only needs to recognize the declaration payload.
assert_eq!(
parse_payload_statement("params(1x: Int)").unwrap(),
PayloadStatement::Params
);
assert!(parse_payload_statement("params").is_err());
assert!(parse_payload_statement("params (x)").is_err());
assert!(parse_payload_statement("params\t(x)").is_err());
}
#[test]
fn ordinary_statements_stay_ordinary() {
for source in ["x = 1", "print(x)", "m[0] = 1", "x = 1; return x"] {
let parsed = parse_payload_statement(source);
if source.contains(';') {
assert!(parsed.is_err(), "{source}");
} else {
assert!(matches!(parsed.unwrap(), PayloadStatement::Ordinary(_)));
}
}
}
#[test]
fn expressions_cannot_use_statement_keywords_as_identifiers() {
assert!(crate::parse_expression("if").is_err());
assert!(crate::parse_expression("return").is_err());
}
}
+54 -3
View File
@@ -864,6 +864,27 @@ fn execute(request: &RunRequest, registry: &KernelRegistry) -> Result<RawRun, Fo
})
}
/// Expand a PATH lookup name to the platform's executable file names.
///
/// Unix uses the name verbatim. Windows applies `PATHEXT` (with a conservative
/// default) because a PATH directory contains `python3.exe`, never `python3`.
fn executable_candidates(name: &str) -> Vec<std::ffi::OsString> {
// Only the Windows branch appends suffixes, so `mut` is unused on Unix.
#[allow(unused_mut)]
let mut names = vec![std::ffi::OsString::from(name)];
#[cfg(windows)]
{
if Path::new(name).extension().is_none() {
let extensions =
std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
for extension in extensions.split(';').filter(|value| !value.is_empty()) {
names.push(std::ffi::OsString::from(format!("{name}{extension}")));
}
}
}
names
}
fn program_candidates(language: &str) -> &'static [&'static str] {
match language {
"python" => &["python3", "python"],
@@ -973,9 +994,14 @@ fn resolve_program(descriptor: &KernelDescriptor) -> Result<PathBuf, ForeignErro
let candidates = program_candidates(&descriptor.provider_id);
for name in candidates {
for directory in std::env::split_paths(&path_var) {
let candidate = directory.join(name);
if is_executable_file(&candidate) {
return Ok(candidate);
// Windows PATH entries contain `python.exe`, not the extension-less
// `python3` token `Command::new` accepts. Scanning PATH manually
// must apply PATHEXT or a valid interpreter is reported missing.
for executable in executable_candidates(name) {
let candidate = directory.join(executable);
if is_executable_file(&candidate) {
return Ok(candidate);
}
}
}
}
@@ -1032,6 +1058,14 @@ struct TempArtifacts {
impl TempArtifacts {
fn create(extension: &str) -> Result<Self, ForeignError> {
// `fs::canonicalize` on Windows returns a verbatim `\\?\C:\...`
// path. Node's module loader uses the working directory/script path
// with `lstat` and rejects that form (`node:fs` ENOENT/UNKNOWN), even
// though Rust can open it. Use the native temp path on Windows and
// keep canonicalization for Unix symlink safety.
#[cfg(windows)]
let base = std::env::temp_dir();
#[cfg(not(windows))]
let base = fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
let mut last_error: Option<io::Error> = None;
for _ in 0..16 {
@@ -1394,6 +1428,23 @@ mod tests {
assert_eq!(normalize_language(""), None);
}
#[test]
fn path_lookup_expands_windows_executable_suffixes() {
let names = executable_candidates("python3");
#[cfg(windows)]
{
assert!(names.iter().any(|name| {
name.to_string_lossy()
.to_ascii_lowercase()
.ends_with(".exe")
}));
}
#[cfg(not(windows))]
{
assert_eq!(names.len(), 1);
}
}
#[test]
fn request_envelope_is_versioned() {
let mut request = RunRequest::new("python", "print(1)");
+189 -46
View File
@@ -39,7 +39,30 @@ impl AnalysisResult {
/// Analyze one Markdown source as a Marqdo module.
///
/// `module_id` is the canonical project-relative identity (e.g. `index.mq.md`).
///
/// This standalone entry point also runs the module-local call check so that a
/// single document can be validated without a program graph. The CLI
/// composition root uses [`analyze_source_for_program`] instead: it defers all
/// call resolution to the single program-wide binding pass (ADR-0054).
pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
analyze_source_inner(module_id, source, true)
}
/// Analyze one Markdown source for the composition root.
///
/// Identical to [`analyze_source`] except that it does not run the provisional
/// module-local call check; the caller binds calls exactly once over the whole
/// program (including extension descriptors) and therefore owns the only
/// authoritative call diagnostics.
pub fn analyze_source_for_program(module_id: &str, source: &str) -> AnalysisResult {
analyze_source_inner(module_id, source, false)
}
fn analyze_source_inner(
module_id: &str,
source: &str,
validate_local_calls: bool,
) -> AnalysisResult {
let id = ModuleId::from(module_id);
let document = marqdo_markdown::parse(source);
let units = units::build_units(&document, &id);
@@ -57,25 +80,45 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
)
.with_hint("front matter must be valid YAML between `---` delimiters"),
),
Ok(_) => match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
Ok(_) => {
for key in ["marqdo_semantics", "syntax"] {
if frontmatter.has_key(key) {
diagnostics.push(
Diagnostic::error(
codes::SEM_UNSUPPORTED_VERSION_DIRECTIVE,
Some(frontmatter.yaml_span),
format!(
"`{key}` is not a syntax selector; there is one current syntax"
),
)
.with_hint(
"remove the directive and migrate the source to RFC-LANG-0002 syntax",
),
);
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint("imports are an explicit mapping: `import: { alias: \"@module\" }`"),
),
},
match frontmatter.imports() {
Ok(mapping) => {
for (alias, target) in mapping {
imports.push(ImportDecl {
alias,
target,
span: frontmatter.span,
});
}
}
Err(error) => diagnostics.push(
Diagnostic::error(
codes::FRONTMATTER_INVALID,
Some(frontmatter.span),
format!("invalid import declaration: {error}"),
)
.with_hint(
"imports are an explicit mapping: `import: { alias: \"@module\" }`",
),
),
}
}
}
}
@@ -85,15 +128,14 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
let mut functions: Vec<Function> = Vec::new();
for scope in &units.functions {
let blocks: Vec<&marqdo_markdown::MdNode> = document.root.children
[scope.body_start..scope.body_end]
.iter()
.collect();
let signature = signature::detect(&document, &blocks);
let explicit = signature.as_ref().map(|(_, sig)| sig);
let mut mapped = map::map_function(&document, &units, &imports, scope);
let mut mapped = map::map_function(&document, &units, scope);
diagnostics.append(&mut mapped.diagnostics);
// The mapper already proved that this payload is the function's first
// direct executable payload; a Knowledge section can never supply one.
let signature = mapped.params.as_ref().map(|declaration| {
signature::from_payload(&declaration.text, declaration.span, &declaration.segments)
});
let explicit = signature.as_ref();
let mut params: Vec<Param> = Vec::new();
let mut kind = SignatureKind::Inferred;
@@ -104,7 +146,12 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
}
let inference = infer::infer(&mapped.stmts, explicit, &import_names);
diagnostics.extend(inference.diagnostics);
if kind == SignatureKind::Inferred {
if kind == SignatureKind::Inferred && !inference.params.is_empty() {
diagnostics.push(Diagnostic::warning(
codes::SEM_INFERRED_SIGNATURE,
Some(scope.heading_span),
"function signature was inferred; declare it with `params(...)`",
));
params = inference
.params
.into_iter()
@@ -137,7 +184,22 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
resources,
anchors: units.anchors.clone(),
};
diagnostics.extend(calls::validate_module(&module));
if validate_local_calls {
diagnostics.extend(calls::validate_module(&module));
}
// One stable order for every consumer: source position first, then the
// stable code, as required by `spec/mapping.md` §8. Diagnostics without a
// precise span sort last.
diagnostics.sort_by(|left, right| {
let left_key = (left.span.map(|span| span.start), left.code.as_str());
let right_key = (right.span.map(|span| span.start), right.code.as_str());
left_key
.0
.unwrap_or(usize::MAX)
.cmp(&right_key.0.unwrap_or(usize::MAX))
.then_with(|| left_key.1.cmp(right_key.1))
});
AnalysisResult {
module,
@@ -157,19 +219,25 @@ mod tests {
#[test]
fn maps_recursive_factorial() {
let source = r#"# 数学
let source = r#"# @knowledge 数学
## 阶乘
## @exec 阶乘
1. `n <= 1`
`if n <= 1`
*1*
`return 1`
2. `n > 1`
`else`
**结果 = n * 阶乘(n=n-1)**
`if n > 1`
*结果*
`结果 = n * 阶乘(n=n-1)`
`return 结果`
`end`
`end`
"#;
let result = analyze(source);
assert!(
@@ -186,17 +254,19 @@ mod tests {
#[test]
fn maps_countdown_loop() {
let source = r#"## 倒计时
let source = r#"## @exec 倒计时
**n = 3**
`n = 3`
- `n > 0`
`while n > 0`
> 打印(n)
`打印(n)`
**n = n - 1**
`n = n - 1`
*n*
`end`
`return n`
"#;
let result = analyze(source);
assert!(!result.has_errors(), "{:#?}", result.diagnostics);
@@ -205,24 +275,96 @@ mod tests {
assert!(matches!(function.body[1], marqdo_ir::Stmt::Loop { .. }));
}
#[test]
fn diagnostics_are_sorted_by_position_then_code() {
// The duplicate-heading error is found while indexing (later in the
// file); the payload syntax error is found while mapping (earlier).
// The public order must be by source position, not pipeline stage.
let source = "## @exec f\n\n`x =`\n\n## @exec f\n";
let result = analyze(source);
let codes: Vec<&str> = result
.diagnostics
.iter()
.map(|diagnostic| diagnostic.code.as_str())
.collect();
assert_eq!(
codes,
vec!["sem.syntax", "sem.duplicate_unit_name"],
"{:#?}",
result.diagnostics
);
}
#[test]
fn knowledge_section_cannot_declare_a_signature() {
// The `params(...)` payload sits in a Knowledge section, so it is inert
// documentation and must not become the function's signature.
let source = "## @exec f\n\n### @knowledge 说明\n\n`params(x: Int)`\n\n### @exec 计算\n\n`return 1`\n";
let result = analyze(source);
assert!(
!result.has_errors(),
"unexpected diagnostics: {:#?}",
result.diagnostics
);
let function = result.module.function("f").expect("f");
assert_eq!(function.signature, SignatureKind::Inferred);
assert!(function.params.is_empty());
}
#[test]
fn exec_section_params_after_prose_is_the_signature() {
// Prose and a Knowledge subsection may precede the declaration, so a
// later Exec section can still declare the first executable payload.
let source = "## @exec f\n\n说明文字。\n\n### @knowledge 原理\n\n`params(ignored: Int)`\n\n### @exec 计算\n\n`params(x: Int)`\n\n`return x`\n";
let result = analyze(source);
assert!(
!result.has_errors(),
"unexpected diagnostics: {:#?}",
result.diagnostics
);
let function = result.module.function("f").expect("f");
assert_eq!(function.signature, SignatureKind::Explicit);
assert_eq!(function.params.len(), 1);
assert_eq!(function.params[0].name, "x");
}
#[test]
fn unmatched_end_points_at_the_end_payload() {
let source = "## @exec f\n\n`x = 1`\n\n`end`\n";
let result = analyze(source);
let diagnostic = result
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == "sem.unmatched_end")
.expect("sem.unmatched_end");
let span = diagnostic.span.expect("span");
assert_eq!(
&source[span.start..span.end],
"`end`",
"the diagnostic must point at the stray end payload"
);
}
#[test]
fn invalid_strong_payload_is_a_hard_error() {
let result = analyze("## f\n\n**a *b* c**\n");
let result = analyze("## @exec f\n\n**a *b* c**\n");
assert!(result.has_errors());
assert!(result
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
.any(|d| d.code == "sem.payload_nested"));
}
#[test]
fn invalid_list_header_is_a_hard_error() {
let result = analyze("## f\n\n1. 没有条件\n");
// RFC-LANG-0002: a plain list is inert Markdown; the v2 negative is an
// unclosed control frame inside the owning Exec H2.
let result = analyze("## @exec f\n\n`if 1`\n");
assert!(result.has_errors());
assert!(result
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT));
.any(|d| d.code == "sem.unclosed_control"));
}
/// Strip source spans so that pure narrative edits (which shift byte
@@ -252,8 +394,9 @@ mod tests {
#[test]
fn prose_changes_do_not_change_ir() {
let base = "## f\n\n说明文字。\n\n**x = 1**\n\n更多说明。\n\n*x*\n";
let edited = "## f\n\n另一段完全不同的叙述。\n\n**x = 1**\n\n继续叙述。\n\n*x*\n";
let base = "## @exec f\n\n说明文字。\n\n`x = 1`\n\n更多说明。\n\n`return x`\n";
let edited =
"## @exec f\n\n另一段完全不同的叙述。\n\n`x = 1`\n\n继续叙述。\n\n`return x`\n";
let a = analyze(base);
let b = analyze(edited);
let a_ir = serde_json::to_value(&a.module.functions).unwrap();
+505 -252
View File
@@ -1,33 +1,51 @@
//! Static call validation.
//! Static call resolution and binding (RFC-EXT-0001 §4, ADR-0054).
//!
//! Calls are resolved after all functions have signatures (including inferred
//! ones), so arity/name mistakes are compile errors with source spans instead
//! of surprises at runtime. Type errors stay runtime concerns: v1 has no static
//! type inference beyond literal checks.
//! This module owns the *single* resolution algorithm used by `check`, `run`,
//! `inspect` and Analysis: it walks every statically visible call site exactly
//! once, resolves it against [`marqdo_ir::callable::CallableRegistry`] and
//! records a [`marqdo_ir::call_binding::BoundTarget`] in one
//! [`marqdo_ir::call_binding::CallBindingTable`]. The runtime consumes that
//! table and never re-resolves a name.
//!
//! Resolution priority is explicit and order-independent:
//!
//! | call form | rule |
//! |---|---|
//! | `f(...)` | local variable (dynamic) → official alias/plugin-fixed builtin → module function (current namespace first, then canonical, then unique local) |
//! | `alias.f(...)` | explicit import alias → builtin dotted prefix → exact plugin export |
//! | `some_value.f(...)` | dynamic language value only |
//!
//! Import aliases that collide with a builtin dotted namespace or a visible
//! plugin namespace are rejected with `ext.import_namespace_conflict`; declared
//! plugin exports that collide with each other or with builtins are rejected
//! when the registry is built. The previous "try builtin, then guess plugin at
//! runtime" behaviour is gone.
//!
//! `validate_module` keeps the standalone frontend API (a single document with
//! no program graph) for AST/conformance tests: unresolved imports are
//! *deferred* there because only the composition root can bind a whole program.
use std::collections::{BTreeMap, BTreeSet};
use marqdo_expression::{Arg, Expr, Ident};
use marqdo_ir::{builtins, Module, ModuleId, Param, Program, SignatureKind, Stmt};
use marqdo_ir::builtins;
use marqdo_ir::call_binding::{BoundTarget, CallBindingTable, CallSiteKey};
use marqdo_ir::callable::{CallableDescriptor, CallableRegistry};
use marqdo_ir::{
Function, FunctionId, Module, ModuleId, PlaceTarget, Program, SignatureKind, Stmt,
};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
/// Signature information needed to validate a call.
#[derive(Debug, Clone)]
pub struct CallableSignature {
/// Parameter list.
pub params: Vec<Param>,
/// Explicit signatures allow positional arguments; inferred do not.
pub kind: SignatureKind,
}
/// Build the callable signature table for a module.
pub fn signature_table(module: &Module) -> BTreeMap<String, CallableSignature> {
/// Build the callable signature table for one module (diagnostics helper).
pub fn signature_table(
module: &Module,
) -> BTreeMap<String, marqdo_ir::callable::CallableSignature> {
let mut table = BTreeMap::new();
for function in &module.functions {
table.insert(
function.id.name.clone(),
CallableSignature {
marqdo_ir::callable::CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
@@ -36,10 +54,107 @@ pub fn signature_table(module: &Module) -> BTreeMap<String, CallableSignature> {
table
}
/// Validate every call in every function body of the module.
/// Result of binding a whole program.
#[derive(Debug, Clone, Default)]
pub struct BoundProgram {
/// One deterministic binding per static call site.
pub bindings: CallBindingTable,
/// Call-resolution diagnostics, sorted later by the caller.
pub diagnostics: Vec<(ModuleId, Diagnostic)>,
}
/// Validate every call in a single module (standalone frontend entry).
///
/// Imports and plugin exports cannot be resolved without a program graph, so
/// those call sites are deferred to the composition-root binding pass instead
/// of producing false errors or a second priority order.
pub fn validate_module(module: &Module) -> Vec<Diagnostic> {
let table = signature_table(module);
let mut program = Program::default();
program.modules.insert(module.id.clone(), module.clone());
program.main_module = Some(module.id.clone());
let registry = CallableRegistry::try_from_program(&program)
.expect("a single module cannot contain duplicate external declarations");
bind_with(module, &program, &registry, true)
.diagnostics
.into_iter()
.map(|(_, diagnostic)| diagnostic)
.collect()
}
/// Validate every call in a loaded program (tests and standalone frontend API).
///
/// The CLI composition root uses [`bind_program_calls`] and keeps the binding
/// table; this wrapper keeps the historical API for frontend tests.
pub fn validate_program(program: &Program) -> Vec<(ModuleId, Diagnostic)> {
let registry = match CallableRegistry::try_from_program(program) {
Ok(registry) => registry,
Err(_) => CallableRegistry::from_program(program),
};
bind_program_calls_with(program, &registry, false).diagnostics
}
/// Resolve every call site in `program` against `registry` exactly once.
///
/// This is the only binding entry point used by the composition root. The
/// returned table must be installed on [`Program::set_call_bindings`] before
/// execution.
pub fn bind_program_calls(program: &Program, registry: &CallableRegistry) -> BoundProgram {
bind_program_calls_with(program, registry, false)
}
fn bind_program_calls_with(
program: &Program,
registry: &CallableRegistry,
standalone: bool,
) -> BoundProgram {
let mut result = BoundProgram::default();
for module in program.modules.values() {
let mut bound = bind_with(module, program, registry, standalone);
// Conflict diagnostics are produced once per module import, before
// any call site; keep them in front of call diagnostics.
result.diagnostics.append(&mut bound.diagnostics);
for (key, target) in bound.bindings.iter() {
result.bindings.insert(key.clone(), target.clone());
}
}
result
}
fn bind_with(
module: &Module,
program: &Program,
registry: &CallableRegistry,
standalone: bool,
) -> BoundProgram {
let mut conflicted = BTreeSet::new();
let mut diagnostics = Vec::new();
// Reject import aliases that collide with a fixed builtin dotted namespace
// or a visible plugin namespace. `alias.f(...)` must have one target.
for import in &module.imports {
let builtin_conflict = registry.has_builtin_dotted_prefix(&import.alias);
let plugin_conflict = registry.has_external_dotted_prefix(&import.alias);
if builtin_conflict || plugin_conflict {
conflicted.insert(import.alias.clone());
let owner = if builtin_conflict {
"a builtin dotted namespace"
} else {
"a declared plugin export namespace"
};
diagnostics.push((
module.id.clone(),
Diagnostic::error(
codes::EXT_IMPORT_NAMESPACE_CONFLICT,
Some(import.span),
format!("import alias `{}` conflicts with {owner}", import.alias),
)
.with_hint(format!(
"rename the import alias, for example `{}_lib`, so `{}.…` has one meaning",
import.alias, import.alias
)),
));
}
}
let mut bound = BoundProgram::default();
for function in &module.functions {
let mut locals: BTreeSet<String> = function
.params
@@ -47,70 +162,50 @@ pub fn validate_module(module: &Module) -> Vec<Diagnostic> {
.map(|param| param.name.clone())
.collect();
collect_assigned(&function.body, &mut locals);
let mut check = CallChecker {
current_namespace: function.namespace.clone(),
let mut binder = Binder {
module,
program,
registry,
function_id: function.id.clone(),
namespace: function.namespace.clone(),
locals: &locals,
table: &table,
imports: module
.imports
.iter()
.map(|import| import.alias.clone())
.collect(),
module_id: module.id.clone(),
program: None,
cross_only: false,
standalone,
conflicted: &conflicted,
bindings: CallBindingTable::default(),
diagnostics: Vec::new(),
};
check.stmts(&function.body);
diagnostics.extend(check.diagnostics);
}
diagnostics
}
/// Validate cross-module and qualified-builtin calls once a whole program is
/// loaded. Local calls are already validated by [`validate_module`].
pub fn validate_program(program: &Program) -> Vec<(ModuleId, Diagnostic)> {
let mut results = Vec::new();
for module in program.modules.values() {
let table = signature_table(module);
for function in &module.functions {
let mut locals: BTreeSet<String> = function
.params
.iter()
.map(|param| param.name.clone())
.collect();
collect_assigned(&function.body, &mut locals);
let mut check = CallChecker {
current_namespace: function.namespace.clone(),
locals: &locals,
table: &table,
imports: module
.imports
.iter()
.map(|import| import.alias.clone())
.collect(),
module_id: module.id.clone(),
program: Some(program),
cross_only: true,
diagnostics: Vec::new(),
};
check.stmts(&function.body);
results.extend(
check
.diagnostics
.into_iter()
.map(|diagnostic| (module.id.clone(), diagnostic)),
);
for param in &function.params {
// Signature defaults are compile-time expressions evaluated by the
// runtime in the callee's own frame; bind their calls with the
// callee identity so the runtime lookup matches.
if let Some(default) = &param.default {
binder.expr(default);
}
}
binder.stmts(&function.body);
for (key, target) in binder.bindings.iter() {
bound.bindings.insert(key.clone(), target.clone());
}
diagnostics.extend(
binder
.diagnostics
.into_iter()
.map(|diagnostic| (module.id.clone(), diagnostic)),
);
}
BoundProgram {
bindings: bound.bindings,
diagnostics,
}
results
}
fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
for stmt in stmts {
match stmt {
Stmt::Assign { name, .. } => {
out.insert(name.clone());
Stmt::Assign { target, .. } => {
if let PlaceTarget::Local { name, .. } = target {
out.insert(name.clone());
}
}
Stmt::Branch { arms, .. } => {
for arm in arms {
@@ -118,35 +213,37 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
}
}
Stmt::Loop { body, .. } => collect_assigned(body, out),
_ => {}
Stmt::Eval { .. } | Stmt::Return { .. } => {}
}
}
}
struct CallChecker<'a> {
current_namespace: Option<String>,
struct Binder<'a> {
module: &'a Module,
program: &'a Program,
registry: &'a CallableRegistry,
function_id: FunctionId,
namespace: Option<String>,
locals: &'a BTreeSet<String>,
table: &'a BTreeMap<String, CallableSignature>,
imports: BTreeSet<String>,
module_id: ModuleId,
program: Option<&'a Program>,
cross_only: bool,
standalone: bool,
conflicted: &'a BTreeSet<String>,
bindings: CallBindingTable,
diagnostics: Vec<Diagnostic>,
}
impl<'a> CallChecker<'a> {
impl<'a> Binder<'a> {
fn stmts(&mut self, stmts: &[Stmt]) {
for stmt in stmts {
match stmt {
Stmt::Assign { value, .. }
| Stmt::Eval { expr: value, .. }
| Stmt::Return { value, .. } => {
Stmt::Assign { target, value, .. } => {
if let PlaceTarget::Index { base, index, .. } = target {
self.expr(base);
self.expr(index);
}
self.expr(value);
}
Stmt::Call { call, .. } => {
for Arg { value, .. } in &call.args {
self.expr(value);
}
Stmt::Eval { expr: value, .. } | Stmt::Return { value, .. } => {
self.expr(value);
}
Stmt::Branch { arms, .. } => {
for arm in arms {
@@ -189,205 +286,309 @@ impl<'a> CallChecker<'a> {
}
}
fn bind(&mut self, span: Span, target: BoundTarget) {
let key = CallSiteKey::new(self.function_id.clone(), span);
self.bindings.insert(key, target);
}
fn diagnostic(&mut self, code: &str, span: Span, message: String, hint: Option<String>) {
let mut diagnostic = Diagnostic::error(code, Some(span), message);
if let Some(hint) = hint {
diagnostic = diagnostic.with_hint(hint);
}
self.diagnostics.push(diagnostic);
}
fn call(&mut self, callee: &Expr, args: &[Arg], span: Span) {
match callee {
Expr::Ident(Ident { name, .. }) => {
if self.cross_only {
Expr::Ident(Ident {
name,
span: name_span,
}) => {
if self.locals.contains(name) {
self.bind(span, BoundTarget::DynamicValue);
return;
}
if let Some(target) = self.registry.alias_target(name).cloned() {
if let Some(descriptor) = self.registry.builtin(name) {
self.validate_signature(
&descriptor.signature,
args,
name,
span,
*name_span,
);
}
self.bind(span, BoundTarget::Marqdo { function: target });
return;
}
if let Some(builtin) = builtins::find(name) {
if let Err(message) = builtins::validate_args(builtin, args) {
self.diagnostics.push(
Diagnostic::error(codes::CALL_ARITY, Some(span), message)
.with_hint("check the builtin parameter list"),
self.diagnostic(
codes::CALL_ARITY,
span,
message,
Some("check the builtin parameter list".to_string()),
);
}
self.bind(
span,
BoundTarget::Builtin {
canonical_name: builtin.name.to_string(),
},
);
return;
}
let name_span = match callee {
Expr::Ident(Ident { span, .. }) => *span,
_ => span,
};
if let Some(signature) = self.resolve(name) {
self.validate_against(name, signature, args, span, name_span);
return;
match self.resolve_module_function(name) {
Resolution::One(function) => {
if let Some(target) = self.program.function(&function) {
let signature = marqdo_ir::callable::CallableSignature {
params: target.params.clone(),
kind: target.signature,
};
self.validate_signature(&signature, args, name, span, *name_span);
}
self.bind(span, BoundTarget::Marqdo { function });
}
Resolution::Ambiguous => {
self.diagnostic(
codes::SYMBOL_UNKNOWN,
*name_span,
format!("ambiguous function name `{name}`"),
Some(
"qualify it with its namespace, for example `namespace.函数(...)`"
.to_string(),
),
);
}
Resolution::None => {
if self.standalone
&& self
.module
.imports
.iter()
.any(|import| import.alias == *name)
{
// A local may hold import-related values in the
// standalone frontend API; defer.
return;
}
self.diagnostic(
codes::SYMBOL_UNKNOWN,
*name_span,
format!("unknown function `{name}`"),
Some(
"define it as a level-2 heading, call a builtin, or load the \
plugin that declares it"
.to_string(),
),
);
}
}
if self.locals.contains(name) || self.imports.contains(name) {
// A local may hold a FunctionRef value; resolved at runtime.
return;
}
self.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNKNOWN,
Some(name_span),
format!("unknown function `{name}`"),
)
.with_hint("define it as a level-2 heading or call a builtin"),
);
}
Expr::Member { base, name, .. } => {
if let Expr::Ident(Ident { name: alias, .. }) = base.as_ref() {
let qualified = format!("{}.{name}", alias);
if let Some(builtin) = builtins::find(&qualified) {
if let Err(message) = builtins::validate_args(builtin, args) {
self.diagnostics.push(
Diagnostic::error(codes::CALL_ARITY, Some(span), message)
.with_hint("check the builtin parameter list"),
if let Expr::Ident(Ident {
name: alias,
span: alias_span,
}) = base.as_ref()
{
if self.locals.contains(alias) {
self.bind(span, BoundTarget::DynamicValue);
return;
}
if self.conflicted.contains(alias) {
// The import conflict diagnostic already tells the user
// that `alias.…` has no single meaning; do not cascade.
return;
}
if let Some(target_module) =
self.program.resolve_import(&self.module.id, alias).cloned()
{
if let Some(function) = self.registry.function_id(&target_module, name) {
if let Some(target) = self.program.function(&function) {
let signature = marqdo_ir::callable::CallableSignature {
params: target.params.clone(),
kind: target.signature,
};
self.validate_signature(
&signature,
args,
&format!("{alias}.{name}"),
span,
span,
);
}
self.bind(span, BoundTarget::Marqdo { function });
} else {
self.diagnostic(
codes::SYMBOL_UNKNOWN,
span,
format!("module `{alias}` has no function `{name}`"),
Some(format!(
"check `inspect --signature` on the imported module `{alias}`"
)),
);
}
return;
}
if self.imports.contains(alias) {
if let Some(program) = self.program {
if let Some(target_module) =
program.resolve_import(&self.module_id, alias)
{
if let Some(target) = program.module(target_module) {
if let Some(function) = target.function(name) {
let signature = CallableSignature {
params: function.params.clone(),
kind: function.signature,
};
self.validate_against(
&qualified, &signature, args, span, span,
);
return;
}
self.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNKNOWN,
Some(span),
format!("module `{alias}` has no function `{name}`"),
)
.with_hint(
"check `inspect --signature` on the imported module",
),
);
return;
let qualified = format!("{alias}.{name}");
if let Some(builtin) = builtins::find(&qualified) {
if let Err(message) = builtins::validate_args(builtin, args) {
self.diagnostic(
codes::CALL_ARITY,
span,
message,
Some("check the builtin parameter list".to_string()),
);
}
self.bind(
span,
BoundTarget::Builtin {
canonical_name: builtin.name.to_string(),
},
);
return;
}
if let Some(descriptor) = self.registry.external(&qualified) {
self.validate_signature(
&descriptor.signature,
args,
&qualified,
span,
span,
);
let param_names = descriptor
.signature
.params
.iter()
.map(|param| param.name.clone())
.collect();
let target = match &descriptor.origin {
marqdo_ir::callable::CallableOrigin::AbiPlugin { package, export } => {
BoundTarget::AbiPlugin {
package: package.clone(),
export: export.clone(),
digest: descriptor
.implementation_digest
.clone()
.unwrap_or_default(),
param_names,
}
}
}
_ => BoundTarget::DynamicValue,
};
self.bind(span, target);
return;
}
// A declared ABI export is a static descriptor: validate
// its signature here, without loading the shared library.
if let Some(program) = self.program {
if let Some(descriptor) = program.external_callable(&qualified) {
if let Err(message) =
descriptor.signature.validate_args(args, &qualified)
{
self.diagnostics.push(
Diagnostic::error(codes::CALL_ARITY, Some(span), message)
.with_hint("check the plugin manifest export signature"),
);
}
return;
}
if self.standalone {
// Without a program graph an import or plugin export
// cannot be distinguished statically; defer instead of
// emitting a false error.
return;
}
self.diagnostic(
codes::SYMBOL_UNKNOWN,
*alias_span,
format!("unknown function or plugin export `{qualified}`"),
Some(
"declare the export in a plugin manifest and pass `--plugin` for \
`run`, or fix the module import alias"
.to_string(),
),
);
return;
}
self.bind(span, BoundTarget::DynamicValue);
self.expr(base);
}
other => self.expr(other),
}
}
fn resolve(&self, name: &str) -> Option<&'a CallableSignature> {
if let Some(namespace) = &self.current_namespace {
if let Some(found) = self.table.get(&format!("{namespace}.{name}")) {
return Some(found);
other => {
self.bind(span, BoundTarget::DynamicValue);
self.expr(other);
}
}
if let Some(found) = self.table.get(name) {
return Some(found);
}
// Unique local name across namespaces.
let mut matches = self
.table
.iter()
.filter(|(key, _)| key.ends_with(&format!(".{name}")))
.map(|(_, signature)| signature);
let first = matches.next()?;
if matches.next().is_some() {
None
} else {
Some(first)
}
}
fn validate_against(
fn validate_signature(
&mut self,
name: &str,
signature: &CallableSignature,
signature: &marqdo_ir::callable::CallableSignature,
args: &[Arg],
display: &str,
call_span: Span,
name_span: Span,
) {
if signature.kind == SignatureKind::Inferred {
if let Some(positional) = args.iter().find(|arg| arg.name.is_none()) {
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(positional.span),
format!(
"`{name}` has an inferred signature and only accepts named arguments"
),
)
.with_hint("pass arguments as `name = value`"),
);
if let Err(message) = signature.validate_args(args, display) {
// Positional overflow and missing arguments point at the call or
// the function name respectively; keep messages deterministic.
let span = if message.contains("missing required") {
name_span
} else {
call_span
};
self.diagnostic(
codes::CALL_ARITY,
span,
message,
Some("check `inspect --signature` or the plugin manifest signature".to_string()),
);
}
}
fn resolve_module_function(&self, name: &str) -> Resolution {
if let Some(namespace) = &self.namespace {
let canonical = format!("{namespace}.{name}");
if let Some(function) = self
.module
.functions
.iter()
.find(|function| function.id.name == canonical)
{
return Resolution::One(function.id.clone());
}
}
let mut supplied: BTreeSet<&str> = BTreeSet::new();
let mut positional = 0usize;
for arg in args {
match &arg.name {
Some(argument_name) => {
if !signature
.params
.iter()
.any(|param| param.name == *argument_name)
{
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(arg.span),
format!("`{name}` has no parameter named `{argument_name}`"),
)
.with_hint("check `inspect --signature`"),
);
}
supplied.insert(argument_name.as_str());
}
None => {
if let Some(param) = signature.params.get(positional) {
supplied.insert(param.name.as_str());
positional += 1;
} else {
self.diagnostics.push(Diagnostic::error(
codes::CALL_ARITY,
Some(call_span),
format!(
"`{name}` accepts at most {} positional argument(s)",
signature.params.len()
),
));
}
}
}
if let Some(function) = self
.module
.functions
.iter()
.find(|function| function.id.name == name)
{
return Resolution::One(function.id.clone());
}
for param in &signature.params {
if param.default.is_none() && !supplied.contains(param.name.as_str()) {
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(name_span),
format!("`{name}` is missing required argument `{}`", param.name),
)
.with_hint("pass it by name, e.g. `x = value`"),
);
}
let mut matches = self
.module
.functions
.iter()
.filter(|function| function.local_name == name);
match (matches.next(), matches.next()) {
(Some(function), None) => Resolution::One(function.id.clone()),
(None, _) => Resolution::None,
(Some(_), Some(_)) => Resolution::Ambiguous,
}
}
}
enum Resolution {
One(FunctionId),
Ambiguous,
None,
}
/// Whether a descriptor is a statically declared ABI plugin export.
pub fn is_abi_export(descriptor: &CallableDescriptor) -> bool {
matches!(
descriptor.origin,
marqdo_ir::callable::CallableOrigin::AbiPlugin { .. }
)
}
/// Whether a function signature requires explicit named/positional checking.
pub fn _signature_kind(signature: &marqdo_ir::callable::CallableSignature) -> SignatureKind {
signature.kind
}
/// Helper used by tests and by `inspect` to render a function body trace.
#[allow(dead_code)]
fn _unused(_: &Function, _: &Program) {}
#[cfg(test)]
mod tests {
use super::*;
@@ -491,11 +692,36 @@ mod tests {
package: "demo".into(),
export: "solver.add".into(),
},
implementation_digest: None,
implementation_digest: Some("a".repeat(64)),
source_span: None,
});
let diagnostics = validate_program(&program);
assert!(diagnostics.iter().any(|(_, d)| d.code == codes::CALL_ARITY));
let registry = CallableRegistry::try_from_program(&program).unwrap();
let bound = bind_program_calls(&program, &registry);
assert!(bound
.diagnostics
.iter()
.any(|(_, d)| d.code == codes::CALL_ARITY));
// A valid positional/named mix binds to the exact export identity.
let module = make_module(vec![function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("solver.add(1, b=2)")],
)]);
program.modules.insert(module.id.clone(), module);
let registry = CallableRegistry::try_from_program(&program).unwrap();
let bound = bind_program_calls(&program, &registry);
assert!(bound.diagnostics.is_empty(), "{:?}", bound.diagnostics);
let target = bound.bindings.iter().next().unwrap().1;
match target {
BoundTarget::AbiPlugin {
package, export, ..
} => {
assert_eq!(package, "demo");
assert_eq!(export, "solver.add");
}
other => panic!("unexpected target {other:?}"),
}
}
#[test]
@@ -553,4 +779,31 @@ mod tests {
.iter()
.any(|d| d.code == codes::CALL_ARITY));
}
#[test]
fn import_alias_conflicting_with_builtin_namespace_is_rejected() {
let module = Module {
id: ModuleId::from("index.mq.md"),
units: vec![],
functions: vec![function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("math.eval(x=1)")],
)],
imports: vec![marqdo_ir::ImportDecl {
alias: "math".into(),
target: "./math.mq.md".into(),
span: Span::new(0, 1),
}],
resources: vec![],
anchors: std::collections::BTreeMap::new(),
};
let diagnostics = validate_module(&module);
assert!(diagnostics
.iter()
.any(|d| d.code == codes::EXT_IMPORT_NAMESPACE_CONFLICT));
// Standalone mode defers unresolved imports, but the composition root
// run is covered by the CLI black-box CALL-01 test.
}
}
+41 -12
View File
@@ -17,7 +17,7 @@
use std::collections::{BTreeMap, BTreeSet};
use marqdo_expression::{Arg, Expr, Ident, RecordEntry};
use marqdo_ir::{BranchArm, Stmt};
use marqdo_ir::{BranchArm, PlaceTarget, Stmt};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
@@ -178,21 +178,30 @@ impl<'a> Analyzer<'a> {
fn analyze_stmts(&mut self, stmts: &[Stmt], mut state: State) -> State {
for stmt in stmts {
state = match stmt {
Stmt::Assign { name, value, .. } => {
self.read_expr(value, &state);
self.assign(name, &mut state);
Stmt::Assign { target, value, .. } => {
match target {
PlaceTarget::Local { name, .. } => {
// Preserve v1 order: the RHS is read before the
// local rebinding makes the name definitely
// assigned.
self.read_expr(value, &state);
self.assign(name, &mut state);
}
PlaceTarget::Index { base, index, .. } => {
// Runtime order for an index place is base, index,
// RHS; reads in the place are free reads like any
// other.
self.read_expr(base, &state);
self.read_expr(index, &state);
self.read_expr(value, &state);
}
}
state
}
Stmt::Eval { expr, .. } => {
self.read_expr(expr, &state);
state
}
Stmt::Call { call, .. } => {
for Arg { value, .. } in &call.args {
self.read_expr(value, &state);
}
state
}
Stmt::Return { value, .. } => {
self.read_expr(value, &state);
state
@@ -312,8 +321,10 @@ mod tests {
fn assign(name: &str, value: &str) -> Stmt {
Stmt::Assign {
name: name.to_string(),
name_span: Span::new(0, 0),
target: PlaceTarget::Local {
name: name.to_string(),
name_span: Span::new(0, 0),
},
value: parse_expression(value).unwrap(),
span: Span::new(0, 0),
}
@@ -334,6 +345,24 @@ mod tests {
.collect()
}
#[test]
fn index_assignment_reads_its_base_and_index_without_binding_a_local() {
let stmts = vec![
Stmt::Assign {
target: PlaceTarget::Index {
base: parse_expression("m").unwrap(),
index: parse_expression("i").unwrap(),
span: Span::new(0, 0),
},
value: parse_expression("9").unwrap(),
span: Span::new(0, 0),
},
ret("m[0]"),
];
// `m` and `i` are free reads; the place never rebinds `m` as a local.
assert_eq!(params(&stmts), vec!["i".to_string(), "m".to_string()]);
}
#[test]
fn infers_free_reads() {
// n * 阶乘(n=n-1)
+1 -1
View File
@@ -14,5 +14,5 @@ pub mod resources;
pub mod signature;
pub mod units;
pub use analyze::{analyze_source, AnalysisResult};
pub use analyze::{analyze_source, analyze_source_for_program, AnalysisResult};
pub use units::{build_units, github_slug, FunctionScope, HeadingInfo, UnitIndex};
+332 -453
View File
@@ -6,16 +6,32 @@
//! diagnostics and never fall back to prose.
use marqdo_expression::{
parse_arguments, parse_expression, parse_statement, Arg, Expr, StatementKind,
parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind,
};
use marqdo_ir::{CallSite, CallTarget, ImportDecl, Stmt};
use marqdo_markdown::{normalize_name, MarkdownDocument, MdKind, MdNode};
use marqdo_ir::{PlaceTarget, Stmt};
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
use crate::payload::PayloadSegments;
use crate::units::{FunctionScope, UnitIndex};
/// The `params(...)` payload accepted for one function.
///
/// Only the first function-wide direct payload qualifies; the signature parser
/// validates the interior. Keeping the carrier text and span map here means the
/// declaration is recognized by the same traversal and mode rules that decide
/// what executes, so a Knowledge section can never declare a signature.
#[derive(Debug, Clone)]
pub struct ParamsDeclaration {
/// Payload text, e.g. `params(n: Int)`.
pub text: String,
/// Span of the carrier node.
pub span: Span,
/// Payload-offset → file-span map for default expressions.
pub segments: PayloadSegments,
}
/// A mapped function body plus diagnostics.
#[derive(Debug, Clone, Default)]
pub struct MappedBody {
@@ -23,36 +39,84 @@ pub struct MappedBody {
pub stmts: Vec<Stmt>,
/// Diagnostics produced while mapping.
pub diagnostics: Vec<Diagnostic>,
/// The accepted `params(...)` declaration, if the function has one.
pub params: Option<ParamsDeclaration>,
}
/// Map one function scope to executable statements.
pub fn map_function(
doc: &MarkdownDocument,
index: &UnitIndex,
imports: &[ImportDecl],
scope: &FunctionScope,
) -> MappedBody {
let mut mapper = Mapper {
index,
imports,
diagnostics: Vec::new(),
params: None,
saw_params: None,
executed: false,
};
let blocks = &doc.root.children[scope.body_start..scope.body_end];
let stmts = mapper.blocks(blocks);
let mut stmts = Vec::new();
let mut segment = Vec::new();
let mut mode = crate::units::SemanticMode::Exec;
for (node_index, block) in doc.root.children.iter().enumerate() {
if node_index < scope.body_start || node_index >= scope.body_end {
continue;
}
if let MdKind::Heading { .. } = block.kind {
if mode == crate::units::SemanticMode::Exec {
stmts.extend(mapper.blocks(&segment));
}
segment.clear();
if let Some(heading) = index.headings.iter().find(|h| h.node_index == node_index) {
mode = heading.mode;
}
continue;
}
if mode == crate::units::SemanticMode::Exec {
segment.push(block.clone());
}
}
if mode == crate::units::SemanticMode::Exec {
stmts.extend(mapper.blocks(&segment));
}
MappedBody {
stmts,
diagnostics: mapper.diagnostics,
params: mapper.params,
}
}
struct Mapper<'a> {
index: &'a UnitIndex,
#[allow(dead_code)]
imports: &'a [ImportDecl],
struct Mapper {
diagnostics: Vec<Diagnostic>,
/// Accepted `params(...)` payload for the function being mapped.
params: Option<ParamsDeclaration>,
/// First direct `params(...)` payload of the **function** (not just the
/// current heading segment), used to reject duplicate declarations.
saw_params: Option<Span>,
/// Whether any executable statement has already been lowered for this
/// function. `params(...)` is legal only before that point, even when the
/// earlier statements live in an earlier heading segment.
executed: bool,
}
impl<'a> Mapper<'a> {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stop {
End,
Else,
Eof,
}
struct RawPayload {
payload: Payload,
text: String,
span: Span,
segments: PayloadSegments,
/// True only for a carrier in the heading's direct body, not inside a
/// list or block quote (`params` is legal only there).
direct: bool,
}
impl Mapper {
fn error(&mut self, code: &str, span: Option<Span>, message: impl Into<String>) {
self.diagnostics
.push(Diagnostic::error(code, span, message));
@@ -70,463 +134,278 @@ impl<'a> Mapper<'a> {
}
fn blocks(&mut self, blocks: &[MdNode]) -> Vec<Stmt> {
let mut stmts = Vec::new();
let mut raw = Vec::new();
for block in blocks {
stmts.extend(self.block(block));
self.extract(block, &mut raw, true);
}
let mut position = 0;
let (stmts, stop) = self.sequence(&raw, &mut position, false, false);
if stop != Stop::Eof {
// `sequence` leaves `position` on the stray `end` payload, so the
// diagnostic points at the keyword instead of the previous
// statement. A control frame may never close across a heading.
self.error(
codes::SEM_UNMATCHED_END,
raw.get(position).map(|node| node.span),
"`end` has no open `if`/`while` in this heading segment",
);
}
stmts
}
fn block(&mut self, block: &MdNode) -> Vec<Stmt> {
match &block.kind {
MdKind::Paragraph => self.paragraph(block),
MdKind::List { ordered, .. } => self.list(block, *ordered),
MdKind::BlockQuote => self.quote(block),
// Level>=3 headings and inert document values stay out of the IR.
_ => Vec::new(),
}
}
fn paragraph(&mut self, paragraph: &MdNode) -> Vec<Stmt> {
let mut stmts = Vec::new();
for child in &paragraph.children {
match &child.kind {
MdKind::Strong => {
if let Some(stmt) = self.exec_statement(child) {
stmts.push(stmt);
fn extract(&mut self, node: &MdNode, out: &mut Vec<RawPayload>, direct: bool) {
match &node.kind {
MdKind::Paragraph => {
for child in &node.children {
self.extract(child, out, direct);
}
}
MdKind::BlockQuote | MdKind::Item { .. } | MdKind::List { .. } => {
for child in &node.children {
self.extract(child, out, false);
}
}
MdKind::Strong | MdKind::Emph => {
let (text, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error(
codes::SEM_PAYLOAD_NESTED,
Some(error.span),
format!("invalid payload carrier: {}", error.reason),
);
return;
}
}
MdKind::Emph => {
if let Some(stmt) = self.return_statement(child) {
stmts.push(stmt);
}
}
// Lazy/inert inline structures: never recurse into them.
MdKind::Link { .. }
| MdKind::Image { .. }
| MdKind::Strikethrough
| MdKind::Code { .. }
| MdKind::Math { .. }
| MdKind::Text
| MdKind::SoftBreak
| MdKind::LineBreak
| MdKind::HtmlInline
| MdKind::FootnoteReference { .. } => {}
_ => {}
};
self.push(text, node.span, segments, out, direct);
}
MdKind::Code { ticks } => {
let literal = node.literal.as_deref().unwrap_or_default();
let inner = Span::new(
node.span.start.saturating_add(*ticks),
node.span.end.saturating_sub(*ticks),
);
self.push(
literal.to_string(),
node.span,
PayloadSegments::single(literal, inner),
out,
direct,
);
}
MdKind::Heading { .. } => {}
_ => {}
}
stmts
}
fn exec_statement(&mut self, node: &MdNode) -> Option<Stmt> {
let (payload, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"keep the executable payload as plain text or a single code span",
);
return None;
}
};
if payload.trim().is_empty() {
fn push(
&mut self,
text: String,
span: Span,
segments: PayloadSegments,
out: &mut Vec<RawPayload>,
direct: bool,
) {
if text.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(node.span),
"execution statement has an empty payload",
codes::SEM_EMPTY_PAYLOAD,
Some(span),
"executable payload is empty",
);
return None;
return;
}
match parse_statement(&payload) {
Ok(mut statement) => {
segments.rewrite_statement(&mut statement);
Some(match statement.kind {
StatementKind::Assign {
name,
name_span,
value,
} => Stmt::Assign {
name,
name_span,
value,
span: node.span,
},
StatementKind::Expr(expr) => Stmt::Eval {
expr,
span: node.span,
},
})
if let Some(mut payload) = self.parse_payload(&text, &segments) {
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload {
segments.rewrite_expr(expr);
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid execution statement: {}", error.message),
"statements are `name = expression` or an expression; put the payload in a code span when Markdown emphasis conflicts",
);
None
}
}
}
fn return_statement(&mut self, node: &MdNode) -> Option<Stmt> {
let (payload, segments) = match PayloadSegments::of(node) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"a return payload must be plain text or a single code span",
);
return None;
}
};
if payload.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(node.span),
"return statement has an empty payload",
);
return None;
}
match parse_expression(&payload) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
Some(Stmt::Return {
value: expr,
span: node.span,
})
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid return expression: {}", error.message),
"`*表达式*` returns the value of the expression",
);
None
}
}
}
fn list(&mut self, list: &MdNode, ordered: bool) -> Vec<Stmt> {
if list.children.is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(list.span),
"list in an executable position has no items",
);
return Vec::new();
}
let mut arms = Vec::new();
let mut loops = Vec::new();
for item in &list.children {
let Some((condition, condition_span, body_blocks)) = self.condition_of(item) else {
continue;
};
let body = self.blocks(body_blocks);
if ordered {
arms.push(marqdo_ir::BranchArm {
condition,
condition_span,
body,
span: item.span,
});
} else {
loops.push(Stmt::Loop {
condition,
condition_span,
body,
span: item.span,
});
}
}
if ordered {
if arms.is_empty() {
return Vec::new();
}
vec![Stmt::Branch {
arms,
span: list.span,
}]
} else {
loops
}
}
/// Extract the condition header of a list item and its remaining blocks.
fn condition_of<'b>(&mut self, item: &'b MdNode) -> Option<(Expr, Span, &'b [MdNode])> {
let Some(first) = item.children.first() else {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(item.span),
"list item in an executable position must start with a condition code span",
"write the condition first: `` `n > 0` ``",
);
return None;
};
if !matches!(first.kind, MdKind::Paragraph) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(first.span),
"list item must start with a paragraph containing the condition code span",
"put the condition on the first line of the item",
);
return None;
}
let Some(condition_node) = first.children.first() else {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(first.span),
"list item paragraph is empty; a condition code span is required",
);
return None;
};
if !matches!(condition_node.kind, MdKind::Code { .. }) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(condition_node.span),
"list item must start with a condition inside an inline code span",
"the condition is a `Code` span: `` `n > 0` ``; other text is description",
);
return None;
}
// The remainder of the condition paragraph is description only. The
// semantic mapper does not descend into it, so an executable `Strong`
// or `Emph` there would otherwise be silently swallowed. Reject it as
// a hard shape error instead of guessing the author's intent.
for tail in first.children.iter().skip(1) {
if matches!(tail.kind, MdKind::Strong | MdKind::Emph) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(tail.span),
format!(
"`{}` inside a list-item condition paragraph is not executed and cannot be silently ignored",
tail.kind.tag()
),
"put executable statements in their own paragraph after the condition line",
);
return None;
}
}
let literal = condition_node.literal.clone().unwrap_or_default();
// `condition_node.span` includes the backtick delimiters. The payload
// map must start at the first literal byte so parse diagnostics and
// expression spans point at the expression, not at a delimiter.
let ticks = match condition_node.kind {
MdKind::Code { ticks } => ticks,
_ => 0,
};
let literal_span = Span::new(
condition_node.span.start.saturating_add(ticks),
condition_node.span.end.saturating_sub(ticks),
);
let segments = PayloadSegments::single(&literal, literal_span);
match parse_expression(&literal) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
Some((expr, condition_node.span, &item.children[1..]))
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid condition expression: {}", error.message),
"conditions are Boolean expressions, e.g. `n > 0`",
);
None
}
}
}
fn quote(&mut self, quote: &MdNode) -> Vec<Stmt> {
if quote.children.len() != 1 || quote.children[0].kind != MdKind::Paragraph {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"a block quote invocation must contain exactly one paragraph",
"use one block quote per call; prose belongs in normal paragraphs",
);
return Vec::new();
}
let paragraph = &quote.children[0];
self.call_paragraph(quote, paragraph)
}
fn call_paragraph(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
let first = paragraph.children.first();
let is_link_form = first
.map(|node| matches!(node.kind, MdKind::Link { .. }))
.unwrap_or(false);
if is_link_form {
return self.link_call(quote, paragraph);
}
let (payload, segments) = match PayloadSegments::of(paragraph) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"a block quote call payload must be plain text or one code span",
);
return Vec::new();
}
};
if payload.trim().is_empty() {
self.error(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"block quote invocation has an empty payload",
);
return Vec::new();
}
match parse_expression(&payload) {
Ok(mut expr) => {
segments.rewrite_expr(&mut expr);
if !matches!(expr, Expr::Call { .. }) {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(segments.map_span(expr_span(&expr))),
"a block quote must be a complete function call",
"write `> 函数(参数)`; use a `**strong**` statement to bind a result",
);
return Vec::new();
}
vec![Stmt::Eval {
expr,
span: quote.span,
}]
}
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid call expression: {}", error.message),
"block quotes call functions explicitly: `> 函数(参数)`",
);
Vec::new()
}
}
}
fn link_call(&mut self, quote: &MdNode, paragraph: &MdNode) -> Vec<Stmt> {
let link = &paragraph.children[0];
let (url, link_span) = match &link.kind {
MdKind::Link { url, .. } => (url.clone(), link.span),
_ => unreachable!("link form checked by caller"),
};
let target = self.resolve_link_target(&url, link_span);
let rest = &paragraph.children[1..];
let (suffix, segments) = match PayloadSegments::from_children(rest) {
Ok(result) => result,
Err(error) => {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(error.span),
error.reason,
"link call arguments must follow the link as plain text or code spans",
);
return Vec::new();
}
};
if suffix.trim().is_empty() {
self.error_with_hint(
codes::MARKDOWN_INVALID_CONSTRUCT,
Some(quote.span),
"link-form call requires an explicit argument list",
"write `> [函数](#函数)()` even for zero arguments",
);
return Vec::new();
}
let mut args: Vec<Arg> = match parse_arguments(&suffix) {
Ok(args) => args,
Err(error) => {
self.error_with_hint(
codes::EXPR_PARSE,
Some(segments.map_span(error.span)),
format!("invalid call arguments: {}", error.message),
"arguments are `name = value` or positional values",
);
return Vec::new();
}
};
segments.rewrite_args(&mut args);
let Some(target) = target else {
return Vec::new();
};
vec![Stmt::Call {
call: CallSite {
target,
args,
span: quote.span,
},
span: quote.span,
}]
}
fn resolve_link_target(&mut self, url: &str, span: Span) -> Option<CallTarget> {
if let Some(fragment) = url.strip_prefix('#') {
let unit_id = self.index.anchors.get(fragment).cloned().or_else(|| {
self.index
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| unit.id.clone())
out.push(RawPayload {
payload,
text,
span,
segments,
direct,
});
let Some(unit_id) = unit_id else {
self.error(
codes::REF_UNRESOLVED,
Some(span),
format!("no heading matches call target `{url}`"),
);
return None;
};
let Some(scope) = self
.index
.functions
.iter()
.find(|scope| scope.unit == unit_id)
else {
self.error(
codes::REF_UNRESOLVED,
Some(span),
format!("call target `{url}` is not a function"),
);
return None;
};
Some(CallTarget::Resolved {
module: unit_id.module.clone(),
function: scope.id.name.clone(),
})
} else if url.starts_with("http://") || url.starts_with("https://") {
self.error_with_hint(
codes::REF_UNRESOLVED,
Some(span),
"external links cannot be called",
"link targets used as calls must resolve to a Marqdo function",
);
None
} else {
self.error_with_hint(
codes::MODULE_UNRESOLVED,
Some(span),
format!("cannot resolve cross-module call target `{url}`"),
"import the module explicitly in front matter and call it through the alias",
);
None
}
}
}
fn expr_span(expr: &Expr) -> Span {
marqdo_expression::Expr::span(expr)
}
fn parse_payload(&mut self, text: &str, segments: &PayloadSegments) -> Option<Payload> {
match parse_payload_statement(text) {
Ok(payload) => Some(payload),
Err(error) => {
self.error_with_hint(
codes::SEM_SYNTAX,
Some(segments.map_span(error.span)),
format!("invalid execution payload: {}", error.message),
"one carrier is exactly one statement; control keywords need their own carrier",
);
None
}
}
}
/// Normalise a heading name (re-exported for callers that resolve link targets).
pub fn normalized_heading_name(node: &MdNode) -> Option<String> {
normalize_name(&marqdo_markdown::plain_text(node))
fn sequence(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
stop_on_else: bool,
in_else_body: bool,
) -> (Vec<Stmt>, Stop) {
let mut out = Vec::new();
while *position < nodes.len() {
let raw = &nodes[*position];
match &raw.payload {
Payload::Else => {
if stop_on_else {
return (out, Stop::Else);
}
self.error(
if in_else_body {
codes::SEM_DUPLICATE_ELSE
} else {
codes::SEM_UNMATCHED_ELSE
},
Some(raw.span),
if in_else_body {
"`if` has more than one `else`"
} else {
"`else` has no open `if`"
},
);
*position += 1;
}
Payload::End => {
return (out, Stop::End);
}
Payload::If(condition) => {
self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (then_body, stop) = self.sequence(nodes, position, true, false);
let mut else_body = Vec::new();
let finish = match stop {
Stop::Else => {
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, true);
else_body = body;
stop
}
other => other,
};
if finish != Stop::End {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`if` is not closed by `end`",
);
} else {
*position += 1;
}
let mut arms = vec![marqdo_ir::BranchArm {
condition,
condition_span: span,
body: then_body,
span,
}];
if !else_body.is_empty() {
arms.push(marqdo_ir::BranchArm {
condition: Expr::Bool(true),
condition_span: span,
body: else_body,
span,
});
}
out.push(Stmt::Branch { arms, span });
}
Payload::While(condition) => {
self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, false);
if stop != Stop::End {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`while` is not closed by `end`",
);
} else {
*position += 1;
}
out.push(Stmt::Loop {
condition,
condition_span: span,
body,
span,
});
}
Payload::Return(value) => {
self.executed = true;
out.push(Stmt::Return {
value: value.clone(),
span: raw.span,
});
*position += 1;
}
Payload::Params => {
if !raw.direct {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` must be a direct payload, not inside a list or block quote",
);
} else if self.saw_params.is_some() {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` may be declared only once per function",
);
} else if self.executed || *position != 0 {
self.error(
codes::SEM_SIGNATURE_POSITION,
Some(raw.span),
"`params(...)` must be the first executable payload of the Exec H2, before any statement in any heading segment",
);
} else {
self.saw_params = Some(raw.span);
self.params = Some(ParamsDeclaration {
text: raw.text.clone(),
span: raw.span,
segments: raw.segments.clone(),
});
}
*position += 1;
}
Payload::Ordinary(statement) => {
self.executed = true;
let mut statement = statement.clone();
raw.segments.rewrite_statement(&mut statement);
let span = raw.span;
match statement.kind {
StatementKind::Assign { target, value } => out.push(Stmt::Assign {
target: match target {
AssignTarget::Local { name, name_span } => {
PlaceTarget::Local { name, name_span }
}
AssignTarget::Index {
base,
index,
span: target_span,
} => PlaceTarget::Index {
base: *base,
index: *index,
span: target_span,
},
},
value,
span,
}),
StatementKind::Expr(expr) => out.push(Stmt::Eval { expr, span }),
}
*position += 1;
}
}
}
(out, Stop::Eof)
}
}
+38 -25
View File
@@ -1,11 +1,13 @@
//! Executable payload extraction with a payload → file span map.
//! Payload extraction with a payload → file span map.
//!
//! A payload is the concatenation of the direct `text` and `code` children of
//! an executable node. The expression parser sees only that concatenated
//! Inside an `@exec` scope, `Strong`, `Emph` and inline `Code` are equivalent
//! one-statement carriers. For `Strong`/`Emph` the payload is the
//! concatenation of their direct `text` and `code` children; a nested carrier
//! is an error. The expression/statement parser sees only the concatenated
//! string, so its spans are payload-relative; this module maps them back to the
//! original file so diagnostics point at real source.
use marqdo_expression::{Arg, Expr, RecordEntry, Statement, StatementKind};
use marqdo_expression::{Arg, AssignTarget, Expr, RecordEntry, Statement, StatementKind};
use marqdo_markdown::{MdKind, MdNode, PayloadError};
use marqdo_span::Span;
@@ -140,11 +142,17 @@ impl PayloadSegments {
/// Map and rewrite every span in a parsed statement.
pub fn rewrite_statement(&self, statement: &mut Statement) {
statement.span = self.map_span(statement.span);
if let StatementKind::Assign {
name_span, value, ..
} = &mut statement.kind
{
*name_span = self.map_span(*name_span);
if let StatementKind::Assign { target, value } = &mut statement.kind {
match target {
AssignTarget::Local { name_span, .. } => {
*name_span = self.map_span(*name_span);
}
AssignTarget::Index { base, index, span } => {
*span = self.map_span(*span);
self.rewrite_expr(base);
self.rewrite_expr(index);
}
}
self.rewrite_expr(value);
}
if let StatementKind::Expr(expr) = &mut statement.kind {
@@ -305,40 +313,42 @@ mod extra_span_tests {
#[test]
fn condition_literal_span_excludes_backticks_for_one_and_two_ticks() {
for source in ["## f\n\n1. `n ** 2 ==`\n", "## f\n\n1. ``n ** 2 ==``\n"] {
for source in [
"## @exec f\n\n`if n ** 2 ==`\n",
"## @exec f\n\n``if n ** 2 ==``\n",
] {
let result = crate::analyze_source("index.mq.md", source);
let diagnostic = result
.diagnostics
.iter()
.find(|diagnostic| diagnostic.code == marqdo_value::codes::EXPR_PARSE)
.unwrap_or_else(|| panic!("no expr.parse diagnostic for {source:?}"));
.find(|diagnostic| diagnostic.code == marqdo_value::codes::SEM_SYNTAX)
.unwrap_or_else(|| panic!("no sem.syntax diagnostic for {source:?}"));
let span = diagnostic
.span
.expect("condition parse error has a source span");
assert_eq!(
source.as_bytes()[span.start],
b'`',
"span must stop before the closing backtick: {span:?} in {source:?}"
);
assert_eq!(
&source[span.start.saturating_sub(2)..span.start],
"==",
"span must point at the missing operand"
let condition = source.find("n ** 2 ==").expect("condition text");
let closing = source.rfind('`').expect("closing backtick");
assert!(
span.start >= condition && span.end <= closing,
"span must point inside the carrier payload, before the closing backtick: {span:?} in {source:?}"
);
}
}
#[test]
fn condition_description_rejects_executable_roles() {
// RFC-LANG-0002 no longer rejects Strong/Emph next to a code span:
// every carrier is an independent statement. The preserved intent is
// that a malformed control sequence after `if` is a hard error; it is
// repurposed as an unclosed-control negative.
for tail in ["**print(1)**", "*1*"] {
let source = format!("## f\n\n1. `n > 0` {tail}\n\n > print(1)\n");
let source = format!("## @exec f\n\n`if n > 0` {tail}\n");
let result = crate::analyze_source("index.mq.md", &source);
assert!(
result
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code
== marqdo_value::codes::MARKDOWN_INVALID_CONSTRUCT),
.any(|diagnostic| diagnostic.code == "sem.unclosed_control"),
"executable tail `{tail}` was not rejected: {:#?}",
result.diagnostics
);
@@ -347,7 +357,10 @@ mod extra_span_tests {
#[test]
fn condition_description_allows_inert_inline_content() {
let source = "## f\n\n**n = 1**\n\n1. `n > 0` 普通说明、`惰性代码` 与 [链接](#f)。\n\n > print(1)\n";
// Inline code spans are payload carriers in Exec scope, so the old inert
// `惰性代码` example is now a statement; prose, a link and a carrier-free
// block quote remain inert and must not be rejected.
let source = "## @exec f\n\n`n = 1`\n\n1. `n > 0` 普通说明与 [链接](#f)。\n\n > print(1)\n\n`return n`\n";
let result = crate::analyze_source("index.mq.md", source);
assert!(
!result.has_errors(),
+1 -1
View File
@@ -121,7 +121,7 @@ mod tests {
#[test]
fn formulas_and_code_are_attributed_to_functions() {
let resources = resources_of(
"# ns\n\n## f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## g\n\n$$B = 1$$\n",
"# @knowledge ns\n\n## @exec f\n\n$$A = pi r^2$$\n\n```python\nprint(1)\n```\n\n## @exec g\n\n$$B = 1$$\n",
);
assert_eq!(resources.len(), 3);
let Resource::Formula { unit, latex, .. } = &resources[0] else {
+48 -59
View File
@@ -1,12 +1,13 @@
//! Optional explicit function signatures.
//!
//! `` `(r: Number, precision: Int = 2)` `` as the first paragraph of a
//! function body declares the public parameter list. It is a *declaration*:
//! it does not execute. Without it, parameters are inferred from free reads.
//! `` `params(r: Number, precision: Int = 2)` `` as the first function-wide
//! direct payload of an Exec H2 declares the public parameter list. It is a
//! *declaration*: it does not execute. Without it, parameters are inferred from
//! free reads (and an inferred signature keeps the named-arguments-only rule).
//! See RFC-LANG-0002 and `spec/mapping.md` §6.
use marqdo_expression::{parse_expression, Expr, Statement, StatementKind};
use marqdo_ir::{Param, SignatureKind};
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
use unicode_ident::{is_xid_continue, is_xid_start};
@@ -18,7 +19,7 @@ use crate::payload::PayloadSegments;
pub struct Signature {
/// Parameters in declaration order.
pub params: Vec<Param>,
/// Span of the declaration code span.
/// Span of the declaration payload carrier.
pub span: Span,
/// Diagnostics raised while parsing the declaration.
pub diagnostics: Vec<Diagnostic>,
@@ -31,65 +32,53 @@ impl Signature {
}
}
/// Detect and parse a signature paragraph.
/// Parse the `params(...)` payload the mapper accepted for a function.
///
/// A paragraph qualifies only when it is the first block in the function body
/// (ignoring inert level>=3 section headings) and consists of exactly one
/// inline code span whose payload starts with `(`. Any other first paragraph is
/// prose and inference is used instead.
pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Signature)> {
for (index, block) in blocks.iter().enumerate() {
match &block.kind {
MdKind::Heading { level, .. } if *level >= 3 => continue,
MdKind::Paragraph => {
let is_candidate = block.children.len() == 1
&& matches!(block.children[0].kind, MdKind::Code { .. })
&& block.children[0]
.literal
.as_deref()
.map(|text| text.trim_start().starts_with('('))
.unwrap_or(false);
if !is_candidate {
return None;
}
let code = &block.children[0];
let source = code.literal.clone().unwrap_or_default();
let mut signature = parse(&source, code.span);
// Rewrite parameter default expression spans onto the file.
let segments = PayloadSegments::of(&MdNode {
kind: MdKind::Strong,
span: code.span,
literal: None,
children: vec![code.clone()],
})
.ok()
.map(|(_, segments)| segments);
if let Some(segments) = segments {
for param in &mut signature.params {
if let Some(default) = &mut param.default {
segments.rewrite_expr(default);
}
}
}
return Some((index, signature));
}
_ => return None,
/// The mapper owns recognition: only the first function-wide direct payload of
/// an Exec H2 can be a declaration, and Knowledge sections never produce
/// payloads. This function only validates the declaration text and rewrites
/// default-value spans onto the file.
pub fn from_payload(text: &str, span: Span, segments: &PayloadSegments) -> Signature {
let mut signature = parse(text, span);
for param in &mut signature.params {
if let Some(default) = &mut param.default {
segments.rewrite_expr(default);
}
}
None
signature
}
/// Parse signature payload text (without the code span delimiters).
pub fn parse(source: &str, span: Span) -> Signature {
let mut diagnostics = Vec::new();
let trimmed = source.trim();
let inner = if let Some(rest) = trimmed.strip_prefix('(') {
let is_params = trimmed.starts_with("params(");
let syntax_code = if is_params {
codes::SEM_SYNTAX
} else {
codes::EXPR_PARSE
};
let inner = if let Some(rest) = trimmed.strip_prefix("params(") {
match rest.strip_suffix(')') {
Some(inner) => inner,
None => {
diagnostics.push(Diagnostic::error(
codes::SEM_SYNTAX,
Some(span),
"function signature must be closed by `)`",
));
rest
}
}
} else if let Some(rest) = trimmed.strip_prefix('(') {
// Plugin/ABI descriptors keep their existing parenthesised signature
// spelling; language payloads are detected only as `params(...)`.
rest.strip_suffix(')').unwrap_or(rest)
} else {
diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
"function signature must be parenthesised, e.g. `(r: Number)`",
"function signature must be `params(...)`, e.g. `params(r: Number)`",
));
trimmed
};
@@ -102,7 +91,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
if entry.trim().is_empty() {
if !inner.trim().is_empty() {
diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
"empty parameter in function signature",
));
@@ -129,7 +118,7 @@ pub fn parse(source: &str, span: Span) -> Signature {
}
}
Err(message) => diagnostics.push(Diagnostic::error(
codes::EXPR_PARSE,
syntax_code,
Some(span),
format!("invalid function signature: {message}"),
)),
@@ -293,7 +282,7 @@ mod tests {
#[test]
fn parses_typed_signature_with_default() {
let signature = parse("(r: Number, precision: Int = 2)", Span::new(0, 38));
let signature = parse("params(r: Number, precision: Int = 2)", Span::new(0, 38));
assert!(!signature.has_errors(), "{:?}", signature.diagnostics);
assert_eq!(signature.params.len(), 2);
assert_eq!(signature.params[0].name, "r");
@@ -307,20 +296,20 @@ mod tests {
#[test]
fn parses_untyped_and_empty() {
let signature = parse("()", Span::new(0, 2));
let signature = parse("params()", Span::new(0, 8));
assert!(signature.params.is_empty());
assert!(!signature.has_errors());
let signature = parse("(n)", Span::new(0, 3));
let signature = parse("params(n)", Span::new(0, 9));
assert_eq!(signature.params[0].name, "n");
}
#[test]
fn rejects_duplicates_and_bad_defaults() {
let duplicate = parse("(a, a)", Span::new(0, 6));
let duplicate = parse("params(a, a)", Span::new(0, 12));
assert!(duplicate.has_errors());
let bad_default = parse("(a = f())", Span::new(0, 10));
let bad_default = parse("params(a = f())", Span::new(0, 16));
assert!(bad_default.has_errors());
let bad_name = parse("(1x)", Span::new(0, 4));
let bad_name = parse("params(1x)", Span::new(0, 10));
assert!(bad_name.has_errors());
}
+234 -113
View File
@@ -1,22 +1,24 @@
//! Heading scope index.
//! Heading scope and semantic-mode index (RFC-LANG-0002).
//!
//! Markdown headings are sibling blocks, so function scopes are derived from
//! heading levels, not from container nesting:
//! Markdown headings are sibling blocks, so scopes are derived from heading
//! levels, not from container nesting:
//!
//! * `heading(level=1)` -> namespace / object domain (blueprint 1.2, 2.1)
//! * `heading(level=2)` -> function
//! * `heading(level>=3)` -> named section inside the enclosing unit, never a
//! new callable function
//! * `heading(level=1)` -> namespace / top-level unit
//! * `heading(level=2, mode=Exec)` -> callable function
//! * `heading(level=2, mode=Knowledge)` -> inert knowledge unit
//! * `heading(level>=3)` -> section of the enclosing unit, never a callable
//! function
//!
//! The range of a heading extends to the next heading of the same or a lower
//! level (same or smaller number). Headings inside block quotes, list items or
//! code fences cannot appear as direct children of the document, hence they can
//! never create functions.
//! Each heading declares `@exec`/`@knowledge` or inherits the nearest ancestor
//! heading's mode; the document root is Knowledge. The range of a heading
//! extends to the next heading of the same or a lower level (same or smaller
//! number). Headings inside block quotes, list items or code fences cannot
//! appear as direct children of the document, hence they never create units.
use std::collections::BTreeMap;
use marqdo_ir::{FunctionId, ModuleId, UnitId, UnitInfo, UnitKind};
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind};
use marqdo_markdown::{normalize_name, plain_text, MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
@@ -35,6 +37,8 @@ pub struct HeadingInfo {
pub path: Vec<String>,
/// Role derived from level and position.
pub kind: UnitKind,
/// Semantic mode declared or inherited by this heading.
pub mode: SemanticMode,
}
/// A function range mapped from a level-2 heading.
@@ -93,6 +97,90 @@ impl UnitIndex {
}
}
fn has_payload(node: &MdNode) -> bool {
match &node.kind {
MdKind::Strong | MdKind::Emph | MdKind::Code { .. } => true,
MdKind::Paragraph | MdKind::List { .. } | MdKind::Item { .. } | MdKind::BlockQuote => {
node.children.iter().any(has_payload)
}
_ => false,
}
}
/// Semantic mode declared or inherited by a heading (RFC-LANG-0002).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemanticMode {
/// Document/knowledge region; no executable statements.
Knowledge,
/// Executable region; only an Exec H2 is callable.
Exec,
}
fn heading_declaration(
node: &MdNode,
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
let Some(first) = node.children.first() else {
return (None, None, None);
};
let MdKind::Text = first.kind else {
return (None, None, None);
};
let literal = first.literal.as_deref().unwrap_or_default();
let (mode, rest) = if let Some(rest) = literal.strip_prefix("@exec") {
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return (None, None, None);
}
(SemanticMode::Exec, rest)
} else if let Some(rest) = literal.strip_prefix("@knowledge") {
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return (None, None, None);
}
(SemanticMode::Knowledge, rest)
} else if literal.starts_with('@')
&& literal
.trim_start_matches('@')
.chars()
.next()
.is_some_and(char::is_alphabetic)
{
return (
None,
None,
Some(Diagnostic::error(
codes::SEM_INVALID_MODE_MARKER,
Some(first.span),
"unknown heading mode marker; use exactly `@exec` or `@knowledge`",
)),
);
} else {
return (None, None, None);
};
let title = rest.trim();
if title.is_empty() {
return (
Some(mode),
None,
Some(Diagnostic::error(
codes::SEM_EMPTY_UNIT_NAME,
Some(node.span),
"mode declaration has an empty heading name",
)),
);
}
if title.starts_with("@exec") || title.starts_with("@knowledge") {
return (
Some(mode),
None,
Some(Diagnostic::error(
codes::SEM_INVALID_MODE_MARKER,
Some(node.span),
"a heading may declare only one semantic mode",
)),
);
}
(Some(mode), Some(title.to_string()), None)
}
/// Build the heading/function index for a parsed document.
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let mut index = UnitIndex::default();
@@ -108,23 +196,44 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
function: None,
});
// Stack of (level, path) for ancestor headings with smaller level.
let mut stack: Vec<(u8, Vec<String>)> = Vec::new();
// Stack of (level, path, mode) for ancestors.
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new();
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
let mut current_namespace: Option<String> = None;
let mut current_function: Option<FunctionId> = None;
let mut heading_infos: Vec<HeadingInfo> = Vec::new();
for (node_index, child) in doc.root.children.iter().enumerate() {
let MdKind::Heading { level, .. } = &child.kind else {
let MdKind::Heading { level, setext } = &child.kind else {
continue;
};
let level = *level;
let raw_name = normalize_name(&plain_text(child));
let Some(name) = raw_name else {
// RFC-LANG-0002: only ATX headings may carry a mode declaration; a
// Setext heading simply inherits the nearest ancestor mode.
let (declared, declared_name, declaration_error) = if *setext {
(None, None, None)
} else {
heading_declaration(child)
};
if let Some(error) = declaration_error {
index.diagnostics.push(error);
if declared_name.is_none() {
continue;
}
}
let inherited = stack
.last()
.map(|(_, _, mode)| *mode)
.unwrap_or(SemanticMode::Knowledge);
let mode = declared.unwrap_or(inherited);
let raw_name = match declared_name {
Some(name) => name,
None => plain_text(child),
};
let Some(name) = normalize_name(&raw_name) else {
index.diagnostics.push(
Diagnostic::error(
codes::MARKDOWN_INVALID_CONSTRUCT,
codes::SEM_EMPTY_UNIT_NAME,
Some(child.span),
"heading name must not be empty",
)
@@ -133,7 +242,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
continue;
};
while let Some((parent_level, _)) = stack.last() {
while let Some((parent_level, _, _)) = stack.last() {
if *parent_level >= level {
stack.pop();
} else {
@@ -142,7 +251,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
}
let parent_path = stack
.last()
.map(|(_, path)| path.clone())
.map(|(_, path, _)| path.clone())
.unwrap_or_default();
let path = {
let mut path = parent_path.clone();
@@ -150,14 +259,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
path
};
// Duplicate canonical names in the same scope are a hard error; never
// silently rename with -1/-2 suffixes.
let key = (parent_path.clone(), name.clone());
if let Some(previous) = seen.get(&key) {
let previous = *previous;
index.diagnostics.push(
Diagnostic::error(
codes::MARKDOWN_INVALID_CONSTRUCT,
codes::SEM_DUPLICATE_UNIT_NAME,
Some(child.span),
format!("duplicate heading name `{name}` in the same scope"),
)
@@ -170,14 +277,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let kind = match level {
1 => UnitKind::Namespace,
2 => UnitKind::Function,
2 if mode == SemanticMode::Exec => UnitKind::Function,
2 => UnitKind::Knowledge,
_ => UnitKind::Section,
};
if level == 1 {
current_namespace = Some(name.clone());
current_function = None;
}
let function = if level == 2 {
if level >= 3 && mode == SemanticMode::Exec && current_function.is_none() {
index.diagnostics.push(
Diagnostic::error(
codes::SEM_EXEC_WITHOUT_FUNCTION,
Some(child.span),
"executable section has no owning Exec H2 function",
)
.with_hint("put the section under an Exec H2, or mark it @knowledge"),
);
}
let function = if level == 2 && mode == SemanticMode::Exec {
let local = name.clone();
let qualified = match &current_namespace {
Some(namespace) => format!("{namespace}.{local}"),
@@ -189,9 +307,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
};
current_function = Some(id.clone());
Some(id)
} else if level >= 3 {
} else if level >= 3 && mode == SemanticMode::Exec {
current_function.clone()
} else {
if level <= 2 {
current_function = None;
}
None
};
@@ -202,6 +323,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
span: child.span,
path: path.clone(),
kind,
mode,
};
let unit_id = UnitId {
module: module.clone(),
@@ -215,12 +337,40 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
kind,
function,
});
if level == 1 && mode == SemanticMode::Exec {
// H1 Exec: direct-body carriers before the next heading have no
// owning H2 function. A Knowledge H2 body is inert (inline code
// there is documentation), and Exec H3 sections are checked above.
let mut scan = node_index + 1;
while scan < doc.root.children.len() {
if let MdKind::Heading { .. } = doc.root.children[scan].kind {
break;
}
if has_payload(&doc.root.children[scan]) {
index.diagnostics.push(Diagnostic::error(
codes::SEM_EXEC_WITHOUT_FUNCTION,
Some(doc.root.children[scan].span),
"executable payload has no owning Exec H2 function",
));
break;
}
scan += 1;
}
}
heading_infos.push(info.clone());
stack.push((level, info.path.clone()));
stack.push((level, info.path.clone(), mode));
}
// Function body ranges and spans.
for heading in heading_infos.iter().filter(|h| h.level == 2) {
// A Knowledge H2 has no function range.
if !index
.units
.iter()
.any(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
{
continue;
}
let body_start = heading.node_index + 1;
let body_end = doc.root.children[body_start..]
.iter()
@@ -239,33 +389,23 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
} else {
heading.span
};
let local_name = heading.name.clone();
let namespace = match heading.path.len() {
0 => None,
_ if heading.path.len() == 1 => None,
_ => Some(heading.path[0].clone()),
};
let namespace = namespace.filter(|_| {
index
.units
.iter()
.any(|unit| unit.kind == UnitKind::Namespace && unit.name == heading.path[0])
});
let qualified = match &namespace {
Some(namespace) => format!("{namespace}.{local_name}"),
None => local_name.clone(),
let unit = index
.units
.iter()
.find(|unit| unit.id.path == heading.path && unit.kind == UnitKind::Function)
.expect("function unit exists");
let FunctionId { name, .. } = unit.function.clone().expect("function id");
let local_name = name.rsplit('.').next().unwrap_or(&name).to_string();
let namespace = if name.contains('.') {
Some(name.rsplit_once('.').unwrap().0.to_string())
} else {
None
};
index.functions.push(FunctionScope {
id: FunctionId {
module: module.clone(),
name: qualified,
},
id: unit.function.clone().unwrap(),
local_name,
namespace,
unit: UnitId {
module: module.clone(),
path: heading.path.clone(),
},
unit: unit.id.clone(),
heading_span: heading.span,
body_start,
body_end,
@@ -273,67 +413,34 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
});
}
// Warnings for would-be execution nodes outside every function body.
for (node_index, child) in doc.root.children.iter().enumerate() {
if index.function_containing_block(node_index).is_some() {
for heading in &heading_infos {
let Some(unit) = index.units.iter().find(|unit| unit.id.path == heading.path) else {
continue;
};
let slug = github_slug(&heading.name);
if slug.is_empty() {
continue;
}
let mut warn = |span: Span, what: &str| {
index.diagnostics.push(
Diagnostic::warning(
codes::MARKDOWN_INERT_EXECUTABLE,
Some(span),
format!("{what} outside a function body is inert document content"),
)
.with_hint("move it under a level-2 heading (`## 函数名`) to execute it"),
);
};
match &child.kind {
MdKind::BlockQuote => warn(child.span, "a block quote invocation"),
MdKind::List { .. } => warn(child.span, "a list control structure"),
MdKind::Paragraph => {
let mut found: Option<(Span, &'static str)> = None;
child.walk(&mut |node| {
if found.is_none() {
match node.kind {
MdKind::Strong => found = Some((node.span, "an execution statement")),
MdKind::Emph => found = Some((node.span, "a return statement")),
_ => {}
}
}
});
if let Some((span, what)) = found {
warn(span, what);
let mut count = index.anchors.keys().filter(|key| *key == &slug).count();
let key = if count == 0 {
slug.clone()
} else {
loop {
count += 1;
let candidate = format!("{slug}-{count}");
if !index.anchors.contains_key(&candidate) {
break candidate;
}
}
_ => {}
}
}
// Derive GitHub-style anchors for navigation and `ref("#...")`. Anchors are
// not identity: they may collide and receive -1/-2 suffixes exactly like
// GitHub's slugger, while internal ids stay canonical.
let mut slug_counts: BTreeMap<String, usize> = BTreeMap::new();
for unit in &index.units {
if unit.level == 0 {
continue;
}
let base = github_slug(&unit.name);
if base.is_empty() {
continue;
}
let count = slug_counts.entry(base.clone()).or_insert(0);
let slug = if *count == 0 {
base
} else {
format!("{base}-{count}")
};
*count += 1;
index.anchors.insert(slug, unit.id.clone());
index.anchors.insert(key, unit.id.clone());
}
index.headings = heading_infos;
index
.diagnostics
.dedup_by(|a, b| a.code == b.code && a.span == b.span && a.message == b.message);
index
}
/// GitHub-style heading slug, kept in a separate namespace from canonical
@@ -366,7 +473,7 @@ mod tests {
#[test]
fn builds_function_ranges() {
let index = index_of(
"# 命名空间\n\n## 阶乘\n\n**x = 1**\n\n### 小节\n\n正文\n\n## 下一个\n\n*y*\n",
"# @knowledge 命名空间\n\n## @exec 阶乘\n\n`x = 1`\n\n### 小节\n\n正文\n\n## @exec 下一个\n\n`return y`\n",
);
assert_eq!(index.functions.len(), 2);
assert_eq!(index.functions[0].local_name, "阶乘");
@@ -380,25 +487,40 @@ mod tests {
#[test]
fn root_level_function_without_namespace() {
let index = index_of("## main\n\n> 打印(1)\n");
let index = index_of("## @exec main\n\n`打印(1)`\n");
assert_eq!(index.functions.len(), 1);
assert_eq!(index.functions[0].id.name, "main");
assert!(index.functions[0].namespace.is_none());
assert!(index.diagnostics.is_empty());
}
#[test]
fn setext_headings_inherit_and_never_declare_a_mode() {
// `@exec f` is the level-2 heading text under a Setext underline; it is
// not a declaration, so the H2 stays Knowledge and creates no function.
let index = index_of("# @knowledge 项目\n\n@exec f\n---\n\n`return 1`\n");
assert!(index.functions.is_empty(), "{:?}", index.functions);
let heading = index
.headings
.iter()
.find(|heading| heading.level == 2)
.expect("level-2 heading");
assert_eq!(heading.mode, SemanticMode::Knowledge);
assert_eq!(heading.name, "@exec f");
}
#[test]
fn empty_heading_is_an_error() {
let index = index_of("## \n\n正文\n");
let index = index_of("## @exec\n\n正文\n");
assert!(index
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INVALID_CONSTRUCT && d.message.contains("empty")));
.any(|d| d.code == "sem.empty_unit_name" && d.message.contains("empty")));
}
#[test]
fn duplicate_function_names_are_errors() {
let index = index_of("## f\n\n## f\n");
let index = index_of("## @exec f\n\n## @exec f\n");
let errors = index
.diagnostics
.iter()
@@ -409,7 +531,7 @@ mod tests {
#[test]
fn same_name_in_different_namespaces_is_allowed() {
let index = index_of("# a\n\n## f\n\n# b\n\n## f\n");
let index = index_of("# @knowledge a\n\n## @exec f\n\n# @knowledge b\n\n## @exec f\n");
let duplicates = index
.diagnostics
.iter()
@@ -423,11 +545,10 @@ mod tests {
#[test]
fn executable_outside_function_warns_but_does_not_execute() {
let index = index_of("**x = 1**\n\n## f\n\n*y*\n");
assert!(index
.diagnostics
.iter()
.any(|d| d.code == codes::MARKDOWN_INERT_EXECUTABLE));
// RFC-LANG-0002: a Strong at the Knowledge root is inert prose with no
// diagnostic; only an Exec H2 is a callable function.
let index = index_of("**x = 1**\n\n## @exec f\n\n`return y`\n");
assert!(index.diagnostics.is_empty());
assert_eq!(index.functions.len(), 1);
}
}
+8
View File
@@ -9,7 +9,13 @@ repository.workspace = true
authors.workspace = true
[dependencies]
libloading = { workspace = true }
rustls = { workspace = true }
rustls-native-certs = { workspace = true }
marqdo-plugin-abi = { workspace = true }
flate2 = { workspace = true }
getrandom = { workspace = true }
regex = { workspace = true }
glob = { workspace = true }
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
@@ -23,3 +29,5 @@ thiserror = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
rcgen = { workspace = true }
rustls-pemfile = { workspace = true }
@@ -0,0 +1,37 @@
/* Marqdo ResourceProvider C ABI v1 (ADR-0036).
*
* This ABI is for trusted native adapters, not a sandbox. The host loads the
* shared library, checks marqdo_resource_provider_abi_version() == 1 and calls
* these symbols for language-level resource.* operations.
*
* Conventions:
* - return 0 on success, nonzero on failure;
* - failure text is available from marqdo_resource_last_error();
* - rights is a comma-separated list (e.g. "read,write");
* - provider tokens are private to the adapter and must not be exposed to
* language Values, wire frames or trace output.
*/
#ifndef MARQDO_RESOURCE_PROVIDER_H
#define MARQDO_RESOURCE_PROVIDER_H
#include <stdint.h>
#define MARQDO_RESOURCE_PROVIDER_ABI_VERSION 1u
uint32_t marqdo_resource_provider_abi_version(void);
int32_t marqdo_resource_open(const char *kind, const char *descriptor,
const char *rights_csv, uint64_t *out_token);
int32_t marqdo_resource_read(uint64_t token, uint8_t *buffer,
uint32_t capacity, uint32_t *out_read,
int32_t *out_eof);
int32_t marqdo_resource_write(uint64_t token, const uint8_t *bytes,
uint32_t length, uint32_t *out_written);
int32_t marqdo_resource_close(uint64_t token);
int32_t marqdo_resource_last_error(char *buffer, uint32_t capacity);
#endif /* MARQDO_RESOURCE_PROVIDER_H */
+540 -84
View File
@@ -1,12 +1,19 @@
//! Capability model.
//! Capability model and the trusted capability-handler registry.
//!
//! A project manifest can *request* capabilities, but requests are not grants.
//! Effective permissions are the host default for the sandbox mode intersected
//! with what the operator/CLI explicitly granted. Every host operation checks
//! against this set at the point of execution.
//!
//! Executable vendor/core capabilities additionally need an explicitly
//! registered trusted [`CapabilityHandler`] (ADR-0057, RFC-EXT-0001 §7.2).
//! Being authorized is never the same as being executable: a request without a
//! handler fails with `capability.unavailable` instead of returning an empty
//! successful reply.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use glob::Pattern;
use marqdo_plugin_abi::abi::MAX_CAPABILITY_REPLY_BYTES;
@@ -14,8 +21,33 @@ use marqdo_plugin_abi::PluginError;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::budget::Budget;
use crate::fs::ProjectFs;
/// Core capability names understood by [`CapabilityBroker::decide`].
///
/// This is the closed set of host primitives (ADR-0011). A trusted embedder
/// may install a [`CapabilityHandler`] for one of these names; until it does,
/// the capability is authorized by policy but *unavailable* at execution.
pub const CORE_CAPABILITIES: [&str; 10] = [
"console",
"math.compute",
"fs.read",
"fs.write",
"net.request",
"process",
"clock",
"random",
"log",
"artifact.record",
];
/// Capability namespace prefixes reserved for the host itself.
///
/// Handler registration rejects these prefixes so a vendor package can never
/// shadow a host-internal operation.
pub const RESERVED_HANDLER_PREFIXES: [&str; 2] = ["marqdo.", "host."];
/// One audited capability request from a plugin.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityAudit {
@@ -27,19 +59,143 @@ pub struct CapabilityAudit {
pub decision: &'static str,
/// Human-readable reason.
pub reason: String,
/// Wall-clock duration of the decision/execution in microseconds.
pub duration_micros: u64,
}
/// Broker for plugin host-capability requests (ADR-0011).
/// One capability request handed to an installed [`CapabilityHandler`].
#[derive(Debug, Clone, Copy)]
pub struct CapabilityRequest<'a> {
/// Trusted package identity supplied by the host, never by plugin wire data.
pub package_instance: &'a str,
/// Capability being requested.
pub capability: &'a str,
/// Raw request payload (JSON for the predefined capabilities).
pub payload: &'a [u8],
/// Run/session trace id used to correlate audit entries with a run.
pub trace_id: &'a str,
}
/// Trusted, explicitly registered executor for one capability.
///
/// Core capabilities are checked against the effective grant set. Vendor
/// capabilities are accepted only when a trusted host policy registered the
/// exact name; a declaration in a manifest is never enough.
#[derive(Debug, Clone)]
/// RFC-EXT-0001 §7.2 names the policy parameter `EffectiveGrant` and the budget
/// `ResourceBudget`; this build deliberately reuses the existing
/// [`Capabilities`] grant set and [`Budget`] instead of introducing a second
/// permission system (the RFC explicitly allows that substitution).
///
/// A handler is only reachable after [`CapabilityBroker::decide`] authorizes
/// the request, but it must still verify its own scope (project-relative paths,
/// globs, per-file limits) and must charge work to `budget` where applicable.
/// Registration is host-only: there is no wire path from a plugin to this
/// registry.
pub trait CapabilityHandler: Send {
/// Stable capability name this handler serves.
fn name(&self) -> &str;
/// Execute one already-authorized request.
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
capabilities: &Capabilities,
budget: &mut Budget,
) -> Result<Vec<u8>, PluginError>;
}
/// Built-in handler for granted `fs.read` requests.
///
/// Reads go through [`ProjectFs`] (root confinement, traversal rejection,
/// regular-file/UTF-8/8 MiB limits) and the grant is checked **again** against
/// the normalized project-relative path at the execution point, so a raw
/// payload cannot win the glob check with a path the filesystem later
/// normalizes differently.
pub struct FsReadHandler {
fs: ProjectFs,
}
impl FsReadHandler {
/// Install the built-in handler over one project filesystem view.
pub fn new(fs: ProjectFs) -> Self {
Self { fs }
}
}
impl CapabilityHandler for FsReadHandler {
fn name(&self) -> &str {
"fs.read"
}
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
capabilities: &Capabilities,
_budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
// Reply-size limits are enforced by the broker, so this handler keeps
// the historical per-read behavior and only needs the grant re-check.
let raw_path = request_path(request.payload)?;
let (_, relative) = self.fs.resolve(&raw_path, None).map_err(map_runtime)?;
capabilities
.check_read(&relative, None)
.map_err(map_runtime)?;
let contents = self.fs.read(&raw_path, None).map_err(map_runtime)?;
Ok(contents.into_bytes())
}
}
struct HandlerEntry {
handler: Box<dyn CapabilityHandler>,
/// Exact trusted package binding. `None` means the handler is authorized
/// by the capability grant alone (for example project-scoped `fs.read`).
package: Option<String>,
}
/// Broker for plugin host-capability requests (ADR-0011, ADR-0057).
///
/// The broker keeps two independent sets: trusted vendor *policy* entries and
/// installed *handlers*. Execution is
///
/// ```text
/// decide (grant + policy + payload shape)
/// -> handler installed? (else capability.unavailable)
/// -> package-bound handler owns the claimed package? (else permission.denied)
/// -> handler executes under the broker budget and reply limit
/// -> audit { package, capability, granted|denied|unavailable, reason, duration }
/// ```
///
/// A capability that is merely authorized never executes: there is no
/// empty-success path.
pub struct CapabilityBroker {
capabilities: Capabilities,
vendor_policy: BTreeSet<String>,
handlers: BTreeMap<String, HandlerEntry>,
reply_limit: usize,
budget: Budget,
trace_id: String,
audit: Arc<Mutex<Vec<CapabilityAudit>>>,
fs: Option<ProjectFs>,
}
impl std::fmt::Debug for CapabilityBroker {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let bound: Vec<(&str, &str)> = self
.handlers
.iter()
.filter_map(|(name, entry)| {
entry
.package
.as_deref()
.map(|package| (name.as_str(), package))
})
.collect();
formatter
.debug_struct("CapabilityBroker")
.field("capabilities", &self.capabilities)
.field("vendor_policy", &self.vendor_policy)
.field("handlers", &self.handlers.keys().collect::<Vec<_>>())
.field("package_bound_handlers", &bound)
.field("reply_limit", &self.reply_limit)
.field("budget", &self.budget)
.field("trace_id", &self.trace_id)
.finish()
}
}
impl CapabilityBroker {
@@ -53,19 +209,116 @@ impl CapabilityBroker {
Self {
capabilities,
vendor_policy: BTreeSet::new(),
handlers: BTreeMap::new(),
reply_limit: MAX_CAPABILITY_REPLY_BYTES,
budget: Budget::default(),
trace_id: String::new(),
audit,
fs: None,
}
}
/// Attach the project filesystem used to execute granted `fs.read`
/// requests. Without it, `fs.read` is authorized but unavailable.
/// Attach the project filesystem and install the trusted built-in
/// `fs.read` handler.
///
/// Without an attached filesystem, granted `fs.read` requests stay
/// authorized but have no handler, so execution returns
/// `capability.unavailable` (never an empty success).
///
/// # Panics
///
/// Panics if a handler for `fs.read` was already registered on this broker,
/// which would make the built-in handler ambiguous.
pub fn with_fs(mut self, fs: ProjectFs) -> Self {
self.fs = Some(fs);
self.register_handler(FsReadHandler::new(fs))
.expect("a fresh broker has no fs.read handler to conflict with");
self
}
/// Override the maximum reply size a handler may return.
pub fn with_reply_limit(mut self, bytes: usize) -> Self {
self.reply_limit = bytes;
self
}
/// Attach the per-run budget that handlers charge work to.
pub fn with_budget(mut self, budget: Budget) -> Self {
self.budget = budget;
self
}
/// Set the run/session trace id surfaced to handlers.
pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
self.trace_id = trace_id.into();
self
}
/// Remaining broker budget (diagnostics and tests).
pub fn budget(&self) -> &Budget {
&self.budget
}
/// Install a trusted handler reachable by any package that holds a grant.
///
/// Registration is a host-only operation; a plugin manifest cannot reach
/// this API. Duplicate, reserved and empty/invalid names are rejected.
pub fn register_handler<H>(&mut self, handler: H) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
self.install_handler(handler, None)
}
/// Install a trusted handler bound to one exact trusted package identity.
///
/// A request that claims any other package is `permission.denied`, even
/// when the capability grant and vendor policy match.
pub fn register_package_handler<H>(
&mut self,
package: impl Into<String>,
handler: H,
) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
self.install_handler(handler, Some(package.into()))
}
fn install_handler<H>(&mut self, handler: H, package: Option<String>) -> Result<(), PluginError>
where
H: CapabilityHandler + 'static,
{
let name = handler.name().to_string();
validate_handler_name(&name)?;
if self.handlers.contains_key(&name) {
return Err(PluginError::capability(
"capability.handler_conflict",
format!("a capability handler is already registered for `{name}`"),
));
}
self.handlers.insert(
name,
HandlerEntry {
handler: Box::new(handler),
package,
},
);
Ok(())
}
/// Names with an installed trusted handler, in deterministic order.
pub fn handler_names(&self) -> Vec<&str> {
self.handlers.keys().map(String::as_str).collect()
}
/// Whether a trusted executing handler is installed for `capability`.
pub fn has_handler(&self, capability: &str) -> bool {
self.handlers.contains_key(capability)
}
/// Register a trusted vendor capability policy entry.
///
/// This is policy only: execution additionally requires an installed
/// handler. Registering a vendor name does not install anything.
pub fn allow_vendor(&mut self, capability: impl Into<String>) {
self.vendor_policy.insert(capability.into());
}
@@ -76,103 +329,132 @@ impl CapabilityBroker {
}
/// Authorize one request, returning reply bytes on success.
///
/// This is the grant decision only; it does not prove that an executor is
/// installed. Call [`Self::execute`] to actually run a capability.
pub fn authorize(
&mut self,
package: &str,
capability: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
let started = Instant::now();
let result = self.decide(package, capability, request);
let (decision, reason) = match &result {
Ok(()) => ("granted", String::new()),
Err(error) => ("denied", format!("{}: {}", error.code, error.message)),
};
if let Ok(mut audit) = self.audit.lock() {
audit.push(CapabilityAudit {
package: package.to_string(),
capability: capability.to_string(),
decision,
reason,
});
}
self.record(package, capability, decision, &reason, started);
result.map(|()| Vec::new())
}
/// Authorize and execute one capability request.
/// Authorize and execute one capability request through its trusted
/// handler.
///
/// Only `fs.read` has a real implementation in this build. Other
/// capabilities return `capability.unavailable` instead of pretending an
/// empty reply means success (ADR-0011, spec §12.2).
/// The chain is fixed: `decide` → handler installed → package binding →
/// handler execution under the broker budget and reply limit → audit.
/// Anything without an installed handler is `capability.unavailable`; it
/// is never reported as an empty success (ADR-0011, ADR-0057).
pub fn execute(
&mut self,
package: &str,
capability: &str,
request: &[u8],
) -> Result<Vec<u8>, PluginError> {
let started = Instant::now();
// 1. Authorization: effective grants, vendor policy, payload shape.
if let Err(error) = self.decide(package, capability, request) {
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
let result = match capability {
"fs.read" => {
let path = request_path(request)?;
let Some(fs) = &self.fs else {
return self.unavailable(
package,
capability,
"no project filesystem is attached",
);
};
match fs.read(&path, None) {
Ok(contents) => {
if contents.len() > MAX_CAPABILITY_REPLY_BYTES {
return self.unavailable(
package,
capability,
"the file exceeds the capability reply limit",
);
}
Ok(contents.into_bytes())
}
Err(error) => {
let error = map_runtime(error);
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason);
Err(error)
}
}
// 2. A trusted executor must exist; a package-bound executor must own
// the trusted package identity the host is claiming.
let bound_package = match self.handlers.get(capability) {
Some(entry) => entry.package.clone(),
None => {
let message = "this capability has no executing handler in this build";
self.record(package, capability, "unavailable", message, started);
return Err(PluginError::capability(
"capability.unavailable",
message.to_string(),
));
}
_ => self.unavailable(
package,
capability,
"this capability has no executing handler in this build",
),
};
if result.is_ok() {
self.record(package, capability, "granted", "");
if let Some(bound) = bound_package {
if bound != package {
let error = plugin_denied(&format!(
"capability `{capability}` is bound to another trusted package"
));
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
}
// 3. Execute under the broker budget and reply limit.
let broker_request = CapabilityRequest {
package_instance: package,
capability,
payload: request,
trace_id: &self.trace_id,
};
let reply_limit = self.reply_limit;
let outcome = self
.handlers
.get_mut(capability)
.expect("handler presence was checked above")
.handler
.execute(&broker_request, &self.capabilities, &mut self.budget);
match outcome {
Ok(contents) => {
if contents.len() > reply_limit {
let error = PluginError::capability(
"resource.exhausted",
format!(
"capability reply is {} bytes; the limit is {reply_limit} bytes",
contents.len()
),
);
let reason = format!("{}: {}", error.code, error.message);
self.record(package, capability, "denied", &reason, started);
return Err(error);
}
self.record(package, capability, "granted", "", started);
Ok(contents)
}
Err(error) => {
let reason = format!("{}: {}", error.code, error.message);
let decision = if error.code == "capability.unavailable" {
"unavailable"
} else {
"denied"
};
self.record(package, capability, decision, &reason, started);
Err(error)
}
}
result
}
fn unavailable<T>(
fn record(
&mut self,
package: &str,
capability: &str,
message: &str,
) -> Result<T, PluginError> {
let error = PluginError::capability("capability.unavailable", message.to_string());
self.record(package, capability, "unavailable", message);
Err(error)
}
fn record(&mut self, package: &str, capability: &str, decision: &'static str, reason: &str) {
decision: &'static str,
reason: &str,
started: Instant,
) {
let elapsed = started.elapsed();
let duration_micros = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
if let Ok(mut audit) = self.audit.lock() {
audit.push(CapabilityAudit {
package: package.to_string(),
capability: capability.to_string(),
decision,
reason: reason.to_string(),
duration_micros,
});
}
}
@@ -214,17 +496,14 @@ impl CapabilityBroker {
.then_some(())
.ok_or_else(|| plugin_denied("process capability was not granted")),
other => {
if is_vendor_capability(other)
&& (self.vendor_policy.contains(other) || self.vendor_policy.contains("*"))
{
Ok(())
} else if is_vendor_capability(other) {
Err(PluginError::capability(
"capability.unavailable",
format!(
"vendor capability `{other}` has no trusted handler for package `{package}`"
),
))
if is_vendor_capability(other) {
if self.vendor_policy.contains(other) || self.vendor_policy.contains("*") {
Ok(())
} else {
Err(plugin_denied(&format!(
"vendor capability `{other}` has no trusted policy entry for package `{package}`"
)))
}
} else {
Err(PluginError::capability(
"capability.unknown",
@@ -304,6 +583,38 @@ pub fn is_vendor_capability(name: &str) -> bool {
})
}
/// Validate a trusted handler name before registration.
///
/// Registration uses [`CapabilityHandler::name`] as the registry key, so there
/// is no second name argument that could disagree with the handler's declared
/// capability (the RFC's "declared protocol mismatch" rejection).
fn validate_handler_name(name: &str) -> Result<(), PluginError> {
if name.is_empty() || name.trim() != name {
return Err(PluginError::capability(
"capability.handler_invalid",
"capability handler names must be non-empty and must not contain surrounding whitespace",
));
}
if RESERVED_HANDLER_PREFIXES
.iter()
.any(|prefix| name.starts_with(prefix))
{
return Err(PluginError::capability(
"capability.handler_reserved",
format!("capability handler name `{name}` uses a reserved host namespace"),
));
}
if !CORE_CAPABILITIES.contains(&name) && !is_vendor_capability(name) {
return Err(PluginError::capability(
"capability.handler_invalid",
format!(
"`{name}` is not a registrable capability name: expected a core capability or a vendor-namespaced name"
),
));
}
Ok(())
}
/// Effective capability grants for one run.
#[derive(Debug, Clone, Default)]
pub struct Capabilities {
@@ -317,12 +628,20 @@ pub struct Capabilities {
pub fs_write: Vec<String>,
/// Allowed network hosts (empty = no network).
pub net_hosts: Vec<String>,
/// Allowed environment variable names (empty = no environment).
pub env: Vec<String>,
/// Allowed process program paths (empty = no process execution).
pub process_programs: Vec<String>,
/// Whether OS entropy may be read (ADR-0046).
pub random: bool,
/// May spawn processes (foreign kernels).
pub process: bool,
/// May run foreign kernels (Python/Node).
pub foreign: bool,
/// Allowed plugin names.
pub plugins: Vec<String>,
/// Allowed resource-provider names (ADR-0033).
pub resource_providers: Vec<String>,
}
impl Capabilities {
@@ -334,9 +653,13 @@ impl Capabilities {
fs_read: Vec::new(),
fs_write: Vec::new(),
net_hosts: Vec::new(),
env: Vec::new(),
process_programs: Vec::new(),
random: false,
process: false,
foreign: false,
plugins: Vec::new(),
resource_providers: Vec::new(),
}
}
@@ -358,6 +681,67 @@ impl Capabilities {
self
}
/// Grant read access to one environment variable name (ADR-0043).
pub fn allow_env(mut self, name: impl Into<String>) -> Self {
self.env.push(name.into());
self
}
/// Check an environment variable grant. Names are exact, not globs.
pub fn check_env(&self, name: &str, span: Option<Span>) -> Result<(), RuntimeError> {
if self.env.iter().any(|allowed| allowed == name) {
Ok(())
} else {
Err(denied(
span,
format!("environment variable `{name}` was not granted"),
format!("grant it with --allow-env {name}"),
))
}
}
/// Grant execution of one exact program path (ADR-0044).
pub fn allow_process(mut self, program: impl Into<String>) -> Self {
self.process_programs.push(program.into());
self
}
/// Check an exact process-program grant.
pub fn check_process(&self, program: &str, span: Option<Span>) -> Result<(), RuntimeError> {
if self
.process_programs
.iter()
.any(|allowed| allowed == program)
{
Ok(())
} else {
Err(denied(
span,
format!("process `{program}` was not granted"),
format!("grant it with --allow-process {program}"),
))
}
}
/// Grant OS entropy reads (ADR-0046).
pub fn allow_random(mut self) -> Self {
self.random = true;
self
}
/// Check the entropy grant.
pub fn check_random(&self, span: Option<Span>) -> Result<(), RuntimeError> {
if self.random {
Ok(())
} else {
Err(denied(
span,
"OS entropy was not granted",
"grant it with --allow-random",
))
}
}
/// Grant foreign kernel execution.
pub fn allow_foreign(mut self) -> Self {
self.foreign = true;
@@ -371,6 +755,39 @@ impl Capabilities {
self
}
/// Grant network access to one IP literal host (ADR-0034).
pub fn allow_net(mut self, host: impl Into<String>) -> Self {
self.net_hosts.push(host.into());
self
}
/// Grant a registered resource provider by its stable name (ADR-0033).
pub fn allow_resource_provider(mut self, name: impl Into<String>) -> Self {
self.resource_providers.push(name.into());
self
}
/// Check a resource-provider grant.
pub fn check_resource_provider(
&self,
name: &str,
span: Option<Span>,
) -> Result<(), RuntimeError> {
if self
.resource_providers
.iter()
.any(|allowed| allowed == name)
{
Ok(())
} else {
Err(denied(
span,
format!("resource provider `{name}` was not granted"),
format!("grant it with Capabilities::allow_resource_provider({name:?})"),
))
}
}
/// Whether a project-relative path matches a granted pattern.
///
/// Patterns and paths are normalised by stripping a leading `./` so that
@@ -488,20 +905,56 @@ mod tests {
.unwrap_err();
assert_eq!(denied.code, "permission.denied");
assert!(broker.authorize("demo.solver", "fs.read", b"{}").is_err());
let unavailable = broker
// Declaring a vendor capability is not a grant: without a trusted
// policy entry authorization is denied (RFC-EXT-0001 CAP-01).
let vendor_denied = broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(unavailable.code, "capability.unavailable");
assert_eq!(vendor_denied.code, "permission.denied");
broker.allow_vendor("vendor.device.read");
assert!(broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.is_ok());
// Policy is not a handler: authorize() succeeds but execution still
// needs an executor and reports `capability.unavailable`.
assert!(!broker.has_handler("vendor.device.read"));
assert_eq!(
broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err()
.code,
"capability.unavailable"
);
assert!(!is_vendor_capability("vendor"));
assert!(!is_vendor_capability("fs.read.extra"));
let audit = broker.audit();
let audit = audit.lock().unwrap();
assert_eq!(audit.len(), 5);
assert_eq!(audit.len(), 6);
assert!(audit.iter().any(|entry| entry.decision == "denied"));
assert!(audit.iter().any(|entry| entry.decision == "unavailable"));
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
}
#[test]
fn every_core_capability_is_understood_by_decide() {
for name in CORE_CAPABILITIES {
let broker = CapabilityBroker::new(Capabilities::project());
let payload: &[u8] = match name {
"fs.read" => br#"{"path":"data/a.csv"}"#,
"fs.write" => br#"{"path":"data/a.csv","contents":"x"}"#,
"net.request" => br#"{"host":"127.0.0.1"}"#,
_ => b"{}",
};
let error = broker
.decide("demo.solver", name, payload)
.err()
.map(|error| error.code);
assert_ne!(
error.as_deref(),
Some("capability.unknown"),
"core capability `{name}` must be handled by decide"
);
}
}
#[test]
@@ -532,6 +985,9 @@ mod execute_tests {
.allow_read("data/**")
.allow_write("data/**");
let mut broker = CapabilityBroker::new(capabilities).with_fs(fs);
assert!(broker.has_handler("fs.read"));
assert_eq!(broker.handler_names(), vec!["fs.read"]);
assert_eq!(broker.reply_limit, MAX_CAPABILITY_REPLY_BYTES);
let contents = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/allowed.txt"}"#)
+496 -10
View File
@@ -4,10 +4,12 @@
//! symlink escapes outside the project root are rejected before the capability
//! check, and the capability check happens before any I/O.
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Component, Path, PathBuf};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use marqdo_value::{ErrorCategory, RuntimeError, Value};
use std::collections::BTreeMap;
/// Maximum size for a single file read.
pub const MAX_READ_BYTES: u64 = 8 * 1024 * 1024;
@@ -83,6 +85,22 @@ impl ProjectFs {
/// Read a UTF-8 file, bounded by [`MAX_READ_BYTES`].
pub fn read(&self, user_path: &str, span: Option<Span>) -> Result<String, RuntimeError> {
let bytes = self.read_bytes(user_path, span)?;
String::from_utf8(bytes).map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
span,
format!("`{user_path}` is not valid UTF-8"),
)
})
}
/// Read a file as raw bytes, bounded by [`MAX_READ_BYTES`].
///
/// Used by the resource stream provider; path/capability checks are the
/// caller's responsibility for grants, while this method still rejects
/// traversal and symlink escapes.
pub fn read_bytes(&self, user_path: &str, span: Option<Span>) -> Result<Vec<u8>, RuntimeError> {
let (absolute, relative) = self.resolve(user_path, span)?;
let metadata = std::fs::metadata(&absolute).map_err(|error| {
RuntimeError::new(
@@ -118,28 +136,418 @@ impl ProjectFs {
if !canonical.starts_with(&self.root) {
return Err(invalid_path(span, "path escapes the project root"));
}
let bytes = std::fs::read(&canonical).map_err(|error| {
std::fs::read(&canonical).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot read `{relative}`: {error}"),
)
})?;
String::from_utf8(bytes).map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
span,
format!("`{relative}` is not valid UTF-8"),
)
})
}
/// Execute a path operation on the project filesystem.
///
/// This is the host side of `resource.request`; it validates every path
/// against the project root, then returns the recoverable `Result` map.
/// Capability checks are performed by the host before this method is
/// called. Unknown operations are a programming error and stay fatal.
pub fn request(
&self,
operation: &str,
args: &[String],
span: Option<Span>,
) -> Result<Value, RuntimeError> {
match operation {
"exists" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
if !absolute.exists() {
return Ok(fs_ok(Value::Bool(false)));
}
self.ensure_inside(&absolute, &relative, span)?;
Ok(fs_ok(Value::Bool(true)))
}
"metadata" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
if !absolute.exists() {
return Ok(fs_error(
"fs.not_found",
&format!("`{relative}` does not exist"),
));
}
let absolute = self.ensure_inside(&absolute, &relative, span)?;
let metadata = std::fs::metadata(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot stat `{relative}`: {error}"),
)
})?;
let kind = if metadata.is_file() {
"file"
} else if metadata.is_dir() {
"directory"
} else {
"other"
};
let size = if metadata.is_file() {
metadata.len()
} else {
0
};
let mut value = BTreeMap::new();
value.insert("kind".to_string(), Value::text(kind));
value.insert(
"size".to_string(),
Value::int(size.min(i64::MAX as u64) as i64),
);
Ok(fs_ok(Value::Map(value)))
}
"list" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
if !absolute.exists() {
return Ok(fs_error(
"fs.not_found",
&format!("`{relative}` does not exist"),
));
}
let absolute = self.ensure_inside(&absolute, &relative, span)?;
let metadata = std::fs::metadata(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot stat `{relative}`: {error}"),
)
})?;
if !metadata.is_dir() {
return Ok(fs_error(
"fs.not_directory",
&format!("`{relative}` is not a directory"),
));
}
let mut names = Vec::new();
let entries = std::fs::read_dir(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot list `{relative}`: {error}"),
)
})?;
for entry in entries {
let entry = entry.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot list `{relative}`: {error}"),
)
})?;
names.push(entry.file_name().to_string_lossy().to_string());
}
names.sort();
Ok(fs_ok(Value::List(
names.into_iter().map(Value::text).collect(),
)))
}
"mkdir" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
self.ensure_parent_inside(&absolute, &relative, span)?;
if absolute.exists() {
return Ok(fs_error(
"fs.exists",
&format!("`{relative}` already exists"),
));
}
match std::fs::create_dir(&absolute) {
Ok(()) => Ok(fs_ok(Value::None)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(fs_error(
"fs.not_found",
&format!("parent directory of `{relative}` does not exist"),
)),
Err(error) => Err(RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot create directory `{relative}`: {error}"),
)),
}
}
"remove" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
if !absolute.exists() {
return Ok(fs_error(
"fs.not_found",
&format!("`{relative}` does not exist"),
));
}
let absolute = self.ensure_inside(&absolute, &relative, span)?;
let metadata = std::fs::metadata(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot stat `{relative}`: {error}"),
)
})?;
if metadata.is_dir() {
let mut entries = std::fs::read_dir(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot list `{relative}`: {error}"),
)
})?;
if entries.next().is_some() {
return Ok(fs_error(
"fs.not_empty",
&format!("`{relative}` is not empty"),
));
}
std::fs::remove_dir(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot remove `{relative}`: {error}"),
)
})?;
} else {
std::fs::remove_file(&absolute).map_err(|error| {
let category = if error.kind() == std::io::ErrorKind::PermissionDenied {
ErrorCategory::PermissionDenied
} else {
ErrorCategory::HostError
};
RuntimeError::new(
category,
span,
format!("cannot remove `{relative}`: {error}"),
)
})?;
}
Ok(fs_ok(Value::None))
}
"append" => {
if args.len() != 2 {
return Err(fs_arity(operation, 2, args.len(), span));
}
let (absolute, relative) = self.resolve(&args[0], span)?;
self.ensure_parent_inside(&absolute, &relative, span)?;
let bytes = args[1].as_bytes();
if bytes.len() > MAX_READ_BYTES as usize {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
format!(
"append to `{relative}` exceeds the {} byte limit",
MAX_READ_BYTES
),
));
}
let mut file = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(&absolute)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot append to `{relative}`: {error}"),
)
})?;
file.write_all(bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot append to `{relative}`: {error}"),
)
})?;
Ok(fs_ok(Value::int(bytes.len() as i64)))
}
"read_at" => {
if args.len() != 3 {
return Err(fs_arity(operation, 3, args.len(), span));
}
let (absolute, relative) = self.resolve(&args[0], span)?;
let offset = parse_offset(&args[1], span)?;
let length = parse_offset(&args[2], span)?;
if length > MAX_READ_BYTES {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
format!("read_at length exceeds the {} byte limit", MAX_READ_BYTES),
));
}
let mut file = std::fs::File::open(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot read `{relative}`: {error}"),
)
})?;
file.seek(SeekFrom::Start(offset)).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot seek `{relative}`: {error}"),
)
})?;
let mut buffer = Vec::new();
file.take(length)
.read_to_end(&mut buffer)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot read `{relative}`: {error}"),
)
})?;
let text = String::from_utf8(buffer).map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
span,
format!("`{relative}` slice is not valid UTF-8"),
)
})?;
Ok(fs_ok(Value::text(text)))
}
"walk" => {
let (absolute, relative) = self.resolve(one_arg(operation, args, span)?, span)?;
if !absolute.exists() {
return Ok(fs_error(
"fs.not_found",
&format!("`{relative}` does not exist"),
));
}
let absolute = self.ensure_inside(&absolute, &relative, span)?;
let metadata = std::fs::metadata(&absolute).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot stat `{relative}`: {error}"),
)
})?;
if !metadata.is_dir() {
return Ok(fs_error(
"fs.not_directory",
&format!("`{relative}` is not a directory"),
));
}
let mut entries = Vec::new();
walk_directory(&absolute, "", &mut entries, 0).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot walk `{relative}`: {error}"),
)
})?;
if entries.len() > 4096 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
"walk exceeds the 4096 entry limit",
));
}
Ok(fs_ok(Value::List(
entries.into_iter().map(Value::text).collect(),
)))
}
"rename" => {
if args.len() != 2 {
return Err(fs_arity(operation, 2, args.len(), span));
}
let (from_absolute, from) = self.resolve(&args[0], span)?;
let (to_absolute, to) = self.resolve(&args[1], span)?;
if !from_absolute.exists() {
return Ok(fs_error(
"fs.not_found",
&format!("`{from}` does not exist"),
));
}
let from_absolute = self.ensure_inside(&from_absolute, &from, span)?;
self.ensure_parent_inside(&to_absolute, &to, span)?;
if to_absolute.exists() {
return Ok(fs_error("fs.exists", &format!("`{to}` already exists")));
}
match std::fs::rename(&from_absolute, &to_absolute) {
Ok(()) => Ok(fs_ok(Value::None)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(fs_error(
"fs.not_found",
&format!("parent directory of `{to}` does not exist"),
)),
Err(error) => Err(RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot rename `{from}` to `{to}`: {error}"),
)),
}
}
other => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
format!("unsupported filesystem operation `{other}`"),
)),
}
}
fn ensure_inside(
&self,
absolute: &Path,
relative: &str,
span: Option<Span>,
) -> Result<PathBuf, RuntimeError> {
let canonical = absolute.canonicalize().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot resolve `{relative}`: {error}"),
)
})?;
if !canonical.starts_with(&self.root) {
return Err(invalid_path(span, "path escapes the project root"));
}
Ok(canonical)
}
fn ensure_parent_inside(
&self,
absolute: &Path,
relative: &str,
span: Option<Span>,
) -> Result<(), RuntimeError> {
let mut ancestor = absolute.parent();
while let Some(current) = ancestor {
if current.exists() {
let canonical = current.canonicalize().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("cannot resolve `{relative}`: {error}"),
)
})?;
if !canonical.starts_with(&self.root) {
return Err(invalid_path(span, "path escapes the project root"));
}
return Ok(());
}
ancestor = current.parent();
}
Ok(())
}
/// Write a file inside the project root, creating parent directories.
pub fn write(
&self,
user_path: &str,
contents: &str,
span: Option<Span>,
) -> Result<(), RuntimeError> {
self.write_bytes(user_path, contents.as_bytes(), span)
}
/// Write raw bytes inside the project root, creating parent directories.
///
/// This is a single validated write, not a transactional replace.
pub fn write_bytes(
&self,
user_path: &str,
bytes: &[u8],
span: Option<Span>,
) -> Result<(), RuntimeError> {
let (absolute, relative) = self.resolve(user_path, span)?;
// Validate the closest existing ancestor stays inside the root.
@@ -169,7 +577,7 @@ impl ProjectFs {
)
})?;
}
std::fs::write(&absolute, contents).map_err(|error| {
std::fs::write(&absolute, bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
@@ -179,10 +587,88 @@ impl ProjectFs {
}
}
fn parse_offset(raw: &str, span: Option<Span>) -> Result<u64, RuntimeError> {
raw.parse::<u64>().map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
span,
format!("`{raw}` is not a non-negative integer offset"),
)
})
}
fn walk_directory(
dir: &Path,
prefix: &str,
out: &mut Vec<String>,
depth: usize,
) -> std::io::Result<()> {
if depth > 64 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"directory depth exceeds 64",
));
}
let mut entries = std::fs::read_dir(dir)?.collect::<Result<Vec<_>, _>>()?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let file_type = entry.file_type()?;
if file_type.is_symlink() {
continue;
}
let name = entry.file_name().to_string_lossy().to_string();
let relative = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
if file_type.is_dir() {
walk_directory(&entry.path(), &relative, out, depth + 1)?;
} else {
out.push(relative);
}
}
Ok(())
}
fn invalid_path(span: Option<Span>, message: impl Into<String>) -> RuntimeError {
RuntimeError::new(ErrorCategory::PermissionDenied, span, message)
}
fn one_arg<'a>(
operation: &str,
args: &'a [String],
span: Option<Span>,
) -> Result<&'a str, RuntimeError> {
if args.len() != 1 {
return Err(fs_arity(operation, 1, args.len(), span));
}
Ok(&args[0])
}
fn fs_arity(operation: &str, expected: usize, actual: usize, span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::Arity,
span,
format!("filesystem operation `{operation}` expects {expected} argument(s), got {actual}"),
)
}
fn fs_ok(value: Value) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), value);
Value::Map(map)
}
fn fs_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
#[cfg(test)]
mod tests {
use super::*;
File diff suppressed because it is too large. Load diff
+83
View File
@@ -0,0 +1,83 @@
//! `Host::invoke` dispatch table.
//!
//! Child module of `host`: it may call the parent's private capability,
//! resource and trace helpers. `StdHost` remains the only host implementation.
use super::*;
pub(crate) fn invoke(
host: &mut StdHost,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
// Addressable memory is language-local state. Handles must not reach a
// plugin, foreign kernel or file adapter, where they could not be
// interpreted safely (RFC-CM-0001 §8, ADR-0022 §4).
if args.iter().any(Value::contains_memory) {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!(
"Memory values cannot cross the host boundary (`{}`); copy bytes into \
Text explicitly first",
op.name()
),
));
}
if args.iter().any(Value::contains_resource) {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!(
"Resource handles cannot cross the generic host boundary (`{}`); use \
resource.* operations",
op.name()
),
));
}
let started = Instant::now();
let result = host.dispatch(op, args, ctx);
let summary = match &result {
Ok(_) => "ok".to_string(),
Err(error) => error.code().to_string(),
};
let estimate = TraceState::estimate(
"effect",
None,
Some(&ctx.module_id),
Some(&summary),
Some(op.name()),
);
if host.trace_state.accept(estimate) {
let seq = host.next_seq();
host.trace.record(
seq,
op.name(),
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary,
);
}
result
}
pub(crate) fn dispatch(
host: &mut StdHost,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
match op {
HostOp::FsRead => host.op_fs_read(args, ctx),
HostOp::FsWrite => host.op_fs_write(args, ctx),
HostOp::MathParse
| HostOp::MathEval
| HostOp::MathSubstitute
| HostOp::MathSimplify
| HostOp::MathDifferentiate => crate::kernels::math(host, op, args, ctx),
HostOp::ForeignRun | HostOp::ForeignCall => crate::kernels::foreign(host, op, args, ctx),
HostOp::PluginInvoke => host.op_plugin_invoke(args, ctx),
}
}
+41
View File
@@ -0,0 +1,41 @@
//! Trace/effect bookkeeping helpers for `StdHost`.
//!
//! Child module of `host`; it may use the parent's private trace state.
use super::*;
impl StdHost {
pub(crate) fn next_seq(&mut self) -> u64 {
let seq = self.next_event_seq;
self.next_event_seq += 1;
seq
}
pub(crate) fn record_resource_effect(
&mut self,
op: &str,
ctx: &ExecutionContext,
started: Instant,
summary: &str,
) {
let estimate = TraceState::estimate(
"effect",
None,
Some(&ctx.module_id),
Some(summary),
Some(op),
);
if !self.trace_state.accept(estimate) {
return;
}
let seq = self.next_seq();
self.trace.record(
seq,
op,
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary.to_string(),
);
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Trusted resource-provider registration (ADR-0033/0035/0036/0037/0038).
//!
//! Registration is host-side installation metadata; language imports cannot
//! install or authorize a provider. Native libraries and helper processes are
//! trusted, not sandboxed.
use super::*;
impl StdHost {
/// Register an explicitly trusted in-process provider (ADR-0033).
///
/// In-process providers share the host address space and are not a
/// sandbox; only trusted adapters may be registered. Registration is not a
/// language operation and does not grant access by itself.
pub fn register_resource_provider(
&mut self,
provider: Box<dyn ResourceProvider>,
) -> Result<(), RuntimeError> {
self.register_provider_checked(provider)
}
/// Register a trusted C ABI resource provider (ADR-0036).
///
/// The shared library runs in the host address space and is **trusted**, not
/// sandboxed. Registration still requires the provider-name grant at
/// `resource.open` and is project-mode only.
pub fn register_c_resource_provider(
&mut self,
name: &str,
kinds: &[&str],
library: &std::path::Path,
) -> Result<(), RuntimeError> {
let kinds = kinds
.iter()
.map(|kind| (*kind).to_string())
.collect::<Vec<_>>();
let provider = CResourceProvider::open(name, &kinds, library)?;
self.register_provider_checked(Box::new(provider))
}
/// Register a trusted C ABI provider from a `marqdo.provider` manifest
/// (ADR-0037). The manifest is host-side installation metadata; language
/// imports cannot install or authorize a provider.
pub fn register_provider_package(
&mut self,
manifest_path: &std::path::Path,
) -> Result<(), RuntimeError> {
let provider = load_package(manifest_path)?;
self.register_provider_checked(Box::new(provider))
}
/// Register a trusted worker-process resource provider (ADR-0035).
///
/// The helper speaks framed JSON over stdin/stdout and is **not** an OS
/// sandbox; only explicitly trusted helpers may be spawned.
pub fn register_worker_resource_provider(
&mut self,
name: &str,
kinds: &[&str],
program: &std::path::Path,
args: &[String],
) -> Result<(), RuntimeError> {
let kinds = kinds
.iter()
.map(|kind| (*kind).to_string())
.collect::<Vec<_>>();
let provider = WorkerResourceProvider::spawn(name, &kinds, program, args)?;
self.register_provider_checked(Box::new(provider))
}
fn register_provider_checked(
&mut self,
provider: Box<dyn ResourceProvider>,
) -> Result<(), RuntimeError> {
if provider.protocol_version() != 1 {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"resource provider `{}` uses unsupported protocol version {}",
provider.name(),
provider.protocol_version()
),
));
}
let name = provider.name().to_string();
if name.is_empty() || name == "stdio" || name == "file" {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider name `{name}` is reserved or empty"),
));
}
let kinds = provider.kind_strings();
if kinds.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider `{name}` declares no kinds"),
));
}
for kind in &kinds {
if kind.is_empty() || kind == "stdio" || kind == "file" {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider `{name}` declares reserved kind `{kind}`"),
));
}
if let Some((existing, _)) = self.resource_providers.get(kind) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"resource kind `{kind}` is already registered by provider `{existing}`"
),
));
}
}
let provider: SharedResourceProvider = std::sync::Arc::new(std::sync::Mutex::new(provider));
for kind in kinds {
self.resource_providers
.insert(kind, (name.clone(), std::sync::Arc::clone(&provider)));
}
Ok(())
}
}
+462
View File
@@ -0,0 +1,462 @@
//! Resource/stream open dispatch plus provider and TCP endpoints.
//!
//! Child module of `host`: it may use the parent's private fields, and keeps
//! the open-path policy out of the generic `Host::invoke` dispatch.
use super::*;
fn parse_host_port(descriptor: &str, span: Option<Span>) -> Result<(String, u16), RuntimeError> {
let invalid = || {
RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
format!("tcp descriptor `{descriptor}` must be `host:port` or `[ipv6]:port`"),
)
};
if let Some(rest) = descriptor.strip_prefix('[') {
let (host, tail) = rest.split_once(']').ok_or_else(invalid)?;
let port = tail.strip_prefix(':').ok_or_else(invalid)?;
let port = port.parse::<u16>().map_err(|_| invalid())?;
if host.is_empty() {
return Err(invalid());
}
return Ok((host.to_string(), port));
}
let (host, port) = descriptor.rsplit_once(':').ok_or_else(invalid)?;
if host.is_empty() {
return Err(invalid());
}
let port = port.parse::<u16>().map_err(|_| invalid())?;
Ok((host.to_string(), port))
}
impl StdHost {
pub(crate) fn open_resource_stream(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
if self.mode == SandboxMode::Strict {
// stdio/stdout is the existing console channel already permitted by
// strict L1 (CM-A11); stdin, stderr, file/network/process providers
// are not, because strict isolation has not been proven for them.
let stdio_console =
kind == "stdio" && descriptor == "stdout" && requested == BTreeSet::from(["write"]);
if !stdio_console {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"strict mode permits only the existing stdio/stdout console channel; \
other resource streams are refused",
));
}
}
if self.mode == SandboxMode::Pure && kind == "file" {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"pure mode does not provide project file resources",
));
}
match kind {
"stdio" => {
let allowed = match descriptor {
"stdout" | "stderr" => requested == BTreeSet::from(["write"]),
"stdin" => requested == BTreeSet::from(["read"]),
_ => false,
};
if !allowed {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"stdio supports stdout/stderr with rights [write] and stdin with rights [read]",
));
}
if !self.capabilities.console {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"the console capability is required for stdio resources",
));
}
let handle = match descriptor {
"stdin" => self.resources.open_stdin(),
"stderr" => self.resources.open_stderr(),
"stdout" => self.resources.open_stdout(),
_ => unreachable!(),
};
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=stdio descriptor={descriptor}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
"file" => {
if requested == BTreeSet::from(["read"]) {
self.capabilities.check_read(descriptor, ctx.span)?;
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let bytes = self.fs.read_bytes(descriptor, ctx.span)?;
let handle = self.resources.open_file(relative, bytes);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=read"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
return Ok(Value::Resource(handle));
}
if requested == BTreeSet::from(["write"]) {
self.capabilities.check_write(descriptor, ctx.span)?;
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let handle = self.resources.open_file_writer(relative);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=write"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
return Ok(Value::Resource(handle));
}
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"project file streams support exactly [read] or [write] in this build",
))
}
"tcp" => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"tcp resources are available only in project mode",
));
}
if requested != BTreeSet::from(["read", "write"]) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"tcp resources require exactly [read, write] in this build",
));
}
let (host, port) = parse_host_port(descriptor, ctx.span)?;
self.capabilities.check_net(&host, ctx.span)?;
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot resolve `{host}:{port}`: {error}"),
)
})?;
let mut stream = None;
let mut last_error = None;
for address in addresses {
match TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
Ok(connected) => {
stream = Some(connected);
break;
}
Err(error) => last_error = Some((address, error)),
}
}
let Some(stream) = stream else {
let detail = match last_error {
Some((address, error)) => format!("{address}: {error}"),
None => format!("`{host}:{port}` resolved to no addresses"),
};
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot connect to `{host}:{port}`: {detail}"),
));
};
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_tcp(stream);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
"tls" => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"tls resources are available only in project mode",
));
}
if requested != BTreeSet::from(["read", "write"]) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"tls resources require exactly [read, write] in this build",
));
}
let (host, port) = parse_host_port(descriptor, ctx.span)?;
self.capabilities.check_net(&host, ctx.span)?;
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot resolve `{host}:{port}`: {error}"),
)
})?;
let mut tcp = None;
let mut last_error = None;
for address in addresses {
match TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
Ok(connected) => {
tcp = Some(connected);
break;
}
Err(error) => last_error = Some((address, error)),
}
}
let Some(tcp) = tcp else {
let detail = match last_error {
Some((address, error)) => format!("{address}: {error}"),
None => format!("`{host}:{port}` resolved to no addresses"),
};
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot connect tls to `{host}:{port}`: {detail}"),
));
};
let _ = tcp.set_read_timeout(Some(Duration::from_secs(5)));
let _ = tcp.set_write_timeout(Some(Duration::from_secs(5)));
let mut roots = rustls::RootCertStore::empty();
for certificate in rustls_native_certs::load_native_certs().certs {
let _ = roots.add(certificate);
}
for certificate in &self.tls_extra_roots {
roots.add(certificate.clone()).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot add TLS root: {error}"),
)
})?;
}
if roots.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
"no trusted TLS roots are available",
));
}
let config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let server_name =
rustls::pki_types::ServerName::try_from(host.clone()).map_err(|_| {
RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("`{host}` is not a valid TLS server name"),
)
})?;
let connection =
rustls::ClientConnection::new(std::sync::Arc::new(config), server_name)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot start TLS: {error}"),
)
})?;
let stream = rustls::StreamOwned::new(connection, tcp);
let handle = self.resources.open_tls(stream);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tls host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
"tcp-listener" => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"tcp-listener resources are available only in project mode",
));
}
if requested != BTreeSet::from(["accept"]) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"tcp-listener requires exactly [accept] in this build",
));
}
let (host, port) = parse_host_port(descriptor, ctx.span)?;
self.capabilities.check_net(&host, ctx.span)?;
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot resolve `{host}:{port}`: {error}"),
)
})?;
let mut listener = None;
let mut last_error = None;
for address in addresses {
match TcpListener::bind(address) {
Ok(bound) => {
listener = Some(bound);
break;
}
Err(error) => last_error = Some((address, error)),
}
}
let Some(listener) = listener else {
let detail = match last_error {
Some((address, error)) => format!("{address}: {error}"),
None => format!("`{host}:{port}` resolved to no addresses"),
};
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot listen on `{host}:{port}`: {detail}"),
));
};
listener.set_nonblocking(true).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot configure tcp-listener: {error}"),
)
})?;
let handle = self.resources.open_tcp_listener(listener);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp-listener host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
"udp" => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"udp resources are available only in project mode",
));
}
if requested != BTreeSet::from(["read", "write"]) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"udp resources require exactly [read, write] in this build",
));
}
let (host, port) = parse_host_port(descriptor, ctx.span)?;
self.capabilities.check_net(&host, ctx.span)?;
let addresses = (host.as_str(), port).to_socket_addrs().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot resolve `{host}:{port}`: {error}"),
)
})?;
let mut socket = None;
let mut last_error = None;
for address in addresses {
let bind = if address.is_ipv4() {
"0.0.0.0:0"
} else {
"[::]:0"
};
let candidate = UdpSocket::bind(bind).and_then(|socket| {
socket.connect(address)?;
Ok(socket)
});
match candidate {
Ok(connected) => {
socket = Some(connected);
break;
}
Err(error) => last_error = Some((address, error)),
}
}
let Some(socket) = socket else {
let detail = match last_error {
Some((address, error)) => format!("{address}: {error}"),
None => format!("`{host}:{port}` resolved to no addresses"),
};
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot connect udp to `{host}:{port}`: {detail}"),
));
};
let _ = socket.set_read_timeout(Some(Duration::from_secs(5)));
let _ = socket.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_udp(socket);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=udp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
other => {
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource providers are available only in project mode",
));
}
let Some((provider_name, provider)) = self.resource_providers.get(other).cloned()
else {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("resource kind `{other}` is not registered"),
));
};
self.capabilities
.check_resource_provider(&provider_name, ctx.span)?;
let handle = self
.resources
.open_provider(provider, other, descriptor, rights, ctx.span)?;
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={other} provider={provider_name}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
Ok(Value::Resource(handle))
}
}
}
}
+9 -1
View File
@@ -12,13 +12,21 @@ pub mod handles;
pub mod host;
pub mod kernels;
mod plugin_worker;
mod process;
mod provider_c;
mod provider_worker;
pub mod resource;
pub mod trace;
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
pub use capability::Capabilities;
pub use capability::{
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
};
pub use context::ExecutionContext;
pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider};
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
+139
View File
@@ -0,0 +1,139 @@
//! Explicitly granted process execution (ADR-0044).
//!
//! The child is **not** an OS sandbox: it inherits the CLI user's privileges.
//! The host checks an exact program grant before calling this module.
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use marqdo_value::{ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext;
fn process_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
pub(crate) fn run_process(
root: &Path,
program: &str,
args: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
const LIMIT: usize = 1024 * 1024;
let mut command = Command::new(program);
command
.args(args)
.current_dir(root)
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(windows)]
{
// Windows process creation and DLL loading require the system root;
// this is not a package-resolution path or a capability grant.
for name in ["SYSTEMROOT", "WINDIR"] {
if let Some(value) = std::env::var_os(name) {
command.env(name, value);
}
}
}
let child = command.spawn();
let child = match child {
Ok(child) => child,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(process_error(
"process.not_found",
&format!("program `{program}` was not found"),
))
}
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
format!("cannot execute `{program}`: {error}"),
))
}
Err(error) => {
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot start `{program}`: {error}"),
))
}
};
let mut child = child;
let deadline = Instant::now() + Duration::from_secs(5);
let mut timed_out = false;
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if Instant::now() < deadline => {
std::thread::sleep(Duration::from_millis(10));
}
Ok(None) => {
timed_out = true;
let _ = child.kill();
break;
}
Err(error) => {
return Err(RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot wait for `{program}`: {error}"),
))
}
}
}
let output = child.wait_with_output().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("cannot collect `{program}` output: {error}"),
)
})?;
if timed_out {
return Ok(process_error(
"process.timeout",
&format!("program `{program}` exceeded the 5 second limit"),
));
}
if output.stdout.len() > LIMIT || output.stderr.len() > LIMIT {
return Ok(process_error(
"process.output_too_large",
&format!("program `{program}` exceeded the {LIMIT} byte output limit"),
));
}
let stdout = String::from_utf8(output.stdout).map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("program `{program}` stdout is not valid UTF-8"),
)
})?;
let stderr = String::from_utf8(output.stderr).map_err(|_| {
RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("program `{program}` stderr is not valid UTF-8"),
)
})?;
let mut value = BTreeMap::new();
value.insert(
"status".to_string(),
Value::int(output.status.code().unwrap_or(-1) as i64),
);
value.insert("stdout".to_string(), Value::text(stdout));
value.insert("stderr".to_string(), Value::text(stderr));
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::Map(value));
Ok(Value::Map(map))
}
+292
View File
@@ -0,0 +1,292 @@
//! C ABI resource provider v1 (ADR-0036).
//!
//! The library is trusted native code. Loading it shares the host address space
//! and is explicitly not a sandbox; only explicitly trusted adapters may be
//! registered.
use std::collections::BTreeMap;
use std::ffi::{c_char, CString};
use std::path::{Path, PathBuf};
use libloading::Library;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::resource::{ResourceProvider, ResourceRead};
const ABI_VERSION: u32 = 1;
const ERROR_MAX: usize = 1024;
type AbiVersionFn = unsafe extern "C" fn() -> u32;
type OpenFn = unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *mut u64) -> i32;
type ReadFn = unsafe extern "C" fn(u64, *mut u8, u32, *mut u32, *mut i32) -> i32;
type WriteFn = unsafe extern "C" fn(u64, *const u8, u32, *mut u32) -> i32;
type CloseFn = unsafe extern "C" fn(u64) -> i32;
type LastErrorFn = unsafe extern "C" fn(*mut c_char, u32) -> i32;
#[derive(Debug, serde::Deserialize)]
struct ProviderPackage {
schema: String,
schema_version: u32,
name: String,
kinds: Vec<String>,
abi: String,
#[serde(default)]
library: BTreeMap<String, String>,
}
/// Load a C ABI provider from its package manifest (ADR-0037).
pub(crate) fn load_package(manifest_path: &Path) -> Result<CResourceProvider, RuntimeError> {
let bytes = std::fs::read(manifest_path).map_err(|error| {
RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"cannot read provider manifest {}: {error}",
manifest_path.display()
),
)
})?;
let package: ProviderPackage = serde_json::from_slice(&bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"invalid provider manifest {}: {error}",
manifest_path.display()
),
)
})?;
if package.schema != "marqdo.provider" || package.schema_version != 1 {
return Err(provider_error(
&package.name,
"manifest schema must be marqdo.provider version 1",
));
}
if package.abi != "c-abi-1" {
return Err(provider_error(
&package.name,
&format!(
"unsupported provider ABI `{}` (expected c-abi-1)",
package.abi
),
));
}
let platform = if cfg!(target_os = "linux") {
"linux"
} else if cfg!(target_os = "macos") {
"macos"
} else if cfg!(target_os = "windows") {
"windows"
} else {
"default"
};
let library_name = package
.library
.get(platform)
.or_else(|| package.library.get("default"))
.ok_or_else(|| {
provider_error(
&package.name,
&format!("manifest has no `{platform}` or `default` library entry"),
)
})?;
let base = manifest_path.parent().unwrap_or_else(|| Path::new("."));
let library = PathBuf::from(library_name);
let library = if library.is_absolute() {
library
} else {
base.join(library)
};
CResourceProvider::open(&package.name, &package.kinds, &library)
}
pub(crate) struct CResourceProvider {
name: String,
kinds: Vec<String>,
library: Library,
}
impl CResourceProvider {
pub(crate) fn open(name: &str, kinds: &[String], path: &Path) -> Result<Self, RuntimeError> {
let library = unsafe { Library::new(path) }.map_err(|error| {
RuntimeError::new(
ErrorCategory::KernelUnavailable,
None,
format!(
"cannot load C resource provider `{name}` ({}): {error}",
path.display()
),
)
})?;
let version = {
let symbol: libloading::Symbol<AbiVersionFn> = unsafe {
library
.get(b"marqdo_resource_provider_abi_version\0")
.map_err(|error| {
RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("C resource provider `{name}` is missing abi_version: {error}"),
)
})?
};
unsafe { symbol() }
};
if version != ABI_VERSION {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!(
"C resource provider `{name}` uses ABI version {version}; host requires {ABI_VERSION}"
),
));
}
Ok(Self {
name: name.to_string(),
kinds: kinds.to_vec(),
library,
})
}
fn open_fn(&self) -> Result<libloading::Symbol<'_, OpenFn>, RuntimeError> {
unsafe { self.library.get(b"marqdo_resource_open\0") }
.map_err(|error| provider_error(&self.name, &format!("missing open: {error}")))
}
fn read_fn(&self) -> Result<libloading::Symbol<'_, ReadFn>, RuntimeError> {
unsafe { self.library.get(b"marqdo_resource_read\0") }
.map_err(|error| provider_error(&self.name, &format!("missing read: {error}")))
}
fn write_fn(&self) -> Result<libloading::Symbol<'_, WriteFn>, RuntimeError> {
unsafe { self.library.get(b"marqdo_resource_write\0") }
.map_err(|error| provider_error(&self.name, &format!("missing write: {error}")))
}
fn close_fn(&self) -> Result<libloading::Symbol<'_, CloseFn>, RuntimeError> {
unsafe { self.library.get(b"marqdo_resource_close\0") }
.map_err(|error| provider_error(&self.name, &format!("missing close: {error}")))
}
fn last_error(&self) -> String {
let Ok(symbol) = (unsafe {
self.library
.get::<LastErrorFn>(b"marqdo_resource_last_error\0")
}) else {
return format!("C resource provider `{}` failed", self.name);
};
let mut buffer = vec![0i8; ERROR_MAX];
let code = unsafe { symbol(buffer.as_mut_ptr(), ERROR_MAX as u32) };
if code != 0 {
return format!("C resource provider `{}` failed", self.name);
}
let bytes = buffer
.iter()
.map(|value| *value as u8)
.take_while(|value| *value != 0)
.collect::<Vec<_>>();
String::from_utf8_lossy(&bytes).into_owned()
}
fn failure(&self, span: Option<Span>) -> RuntimeError {
let message = self.last_error();
RuntimeError::new(ErrorCategory::HostError, span, message)
}
}
impl ResourceProvider for CResourceProvider {
fn name(&self) -> &str {
&self.name
}
fn kinds(&self) -> &[&str] {
&[]
}
fn kind_strings(&self) -> Vec<String> {
self.kinds.clone()
}
fn open(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<u64, RuntimeError> {
let kind = CString::new(kind).map_err(|_| provider_error(&self.name, "kind has NUL"))?;
let descriptor = CString::new(descriptor)
.map_err(|_| provider_error(&self.name, "descriptor has NUL"))?;
let rights = CString::new(rights.join(","))
.map_err(|_| provider_error(&self.name, "rights have NUL"))?;
let mut token = 0u64;
let code = unsafe {
(self.open_fn()?)(
kind.as_ptr(),
descriptor.as_ptr(),
rights.as_ptr(),
&mut token,
)
};
if code != 0 {
return Err(self.failure(span));
}
Ok(token)
}
fn read(
&mut self,
token: u64,
max_bytes: usize,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError> {
let capacity = u32::try_from(max_bytes).unwrap_or(u32::MAX);
let mut buffer = vec![0u8; capacity as usize];
let mut read = 0u32;
let mut eof = 0i32;
let code =
unsafe { (self.read_fn()?)(token, buffer.as_mut_ptr(), capacity, &mut read, &mut eof) };
if code != 0 {
return Err(self.failure(span));
}
buffer.truncate(read as usize);
Ok(ResourceRead {
bytes: buffer,
eof: eof != 0,
})
}
fn write(
&mut self,
token: u64,
bytes: &[u8],
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let length = u32::try_from(bytes.len())
.map_err(|_| provider_error(&self.name, "write size exceeds the C ABI u32 limit"))?;
let mut written = 0u32;
let code = unsafe { (self.write_fn()?)(token, bytes.as_ptr(), length, &mut written) };
if code != 0 {
return Err(self.failure(span));
}
Ok(written as usize)
}
fn close(&mut self, token: u64, span: Option<Span>) -> Result<(), RuntimeError> {
let code = unsafe { (self.close_fn()?)(token) };
if code != 0 {
return Err(self.failure(span));
}
Ok(())
}
}
impl std::fmt::Debug for CResourceProvider {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CResourceProvider")
.field("name", &self.name)
.field("kinds", &self.kinds)
.finish()
}
}
fn provider_error(name: &str, message: &str) -> RuntimeError {
RuntimeError::new(
ErrorCategory::HostError,
None,
format!("C resource provider `{name}`: {message}"),
)
}
+210
View File
@@ -0,0 +1,210 @@
//! Host-managed worker resource provider (ADR-0035).
//!
//! This is a small, versioned framed-JSON transport for **trusted helper
//! processes**. It is not a C ABI binding and not an OS sandbox: the helper
//! runs as the host user. Registration is a host embedding API; language code
//! only sees the normal `resource.*` operations.
use std::io::{BufReader, Read, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use marqdo_span::Span;
use serde_json::{json, Value as Json};
use crate::resource::{ResourceProvider, ResourceRead};
use marqdo_value::{ErrorCategory, RuntimeError};
const MAX_FRAME_BYTES: usize = 1024 * 1024;
/// A `ResourceProvider` backed by a child process speaking framed JSON.
pub(crate) struct WorkerResourceProvider {
name: String,
kinds: Vec<String>,
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
impl WorkerResourceProvider {
pub(crate) fn spawn(
name: &str,
kinds: &[String],
program: &Path,
args: &[String],
) -> Result<Self, RuntimeError> {
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|error| {
RuntimeError::new(
ErrorCategory::KernelUnavailable,
None,
format!(
"cannot spawn worker resource provider `{name}` ({}): {error}",
program.display()
),
)
})?;
let stdin = child
.stdin
.take()
.ok_or_else(|| worker_error("missing stdin pipe"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| worker_error("missing stdout pipe"))?;
let mut provider = Self {
name: name.to_string(),
kinds: kinds.to_vec(),
child,
stdin,
stdout: BufReader::new(stdout),
};
// Handshake: the helper must answer a ping before it is trusted.
provider.request(json!({"op": "ping"}))?;
Ok(provider)
}
fn request(&mut self, request: Json) -> Result<Json, RuntimeError> {
let bytes = serde_json::to_vec(&request)
.map_err(|error| worker_error(&format!("cannot encode request: {error}")))?;
if bytes.len() > MAX_FRAME_BYTES {
return Err(worker_error("request frame is too large"));
}
self.stdin
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| self.stdin.write_all(&bytes))
.and_then(|()| self.stdin.flush())
.map_err(|error| worker_error(&format!("cannot write request frame: {error}")))?;
let mut header = [0u8; 4];
self.stdout
.read_exact(&mut header)
.map_err(|error| worker_error(&format!("cannot read response header: {error}")))?;
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(worker_error("invalid response frame length"));
}
let mut payload = vec![0u8; length];
self.stdout
.read_exact(&mut payload)
.map_err(|error| worker_error(&format!("cannot read response frame: {error}")))?;
let response: Json = serde_json::from_slice(&payload)
.map_err(|error| worker_error(&format!("invalid response JSON: {error}")))?;
if response.get("ok").and_then(Json::as_bool) != Some(true) {
let code = response
.get("code")
.and_then(Json::as_str)
.unwrap_or("host.error");
let message = response
.get("message")
.and_then(Json::as_str)
.unwrap_or("worker resource provider failed");
let category = match code {
"permission.denied" => ErrorCategory::PermissionDenied,
"resource.closed" => ErrorCategory::ResourceClosed,
"resource.exhausted" => ErrorCategory::ResourceExhausted,
"resource.unsupported" => ErrorCategory::ResourceUnsupported,
_ => ErrorCategory::HostError,
};
return Err(RuntimeError::new(category, None, message.to_string()));
}
Ok(response)
}
}
impl ResourceProvider for WorkerResourceProvider {
fn name(&self) -> &str {
&self.name
}
fn kinds(&self) -> &[&str] {
// Owned kinds are exposed through `kind_strings`; registration never
// calls this for the worker transport.
&[]
}
fn kind_strings(&self) -> Vec<String> {
self.kinds.clone()
}
fn open(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<u64, RuntimeError> {
let response = self
.request(json!({
"op": "open",
"kind": kind,
"descriptor": descriptor,
"rights": rights,
}))
.map_err(|error| with_span(error, span))?;
response
.get("token")
.and_then(Json::as_u64)
.ok_or_else(|| worker_error("open response has no token"))
}
fn read(
&mut self,
token: u64,
max_bytes: usize,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError> {
let response = self
.request(json!({"op": "read", "token": token, "max_bytes": max_bytes}))
.map_err(|error| with_span(error, span))?;
let bytes = response
.get("bytes")
.and_then(Json::as_array)
.ok_or_else(|| worker_error("read response has no bytes"))?
.iter()
.map(|value| value.as_u64().and_then(|v| u8::try_from(v).ok()))
.collect::<Option<Vec<u8>>>()
.ok_or_else(|| worker_error("read response contains a non-byte value"))?;
let eof = response.get("eof").and_then(Json::as_bool).unwrap_or(false);
Ok(ResourceRead { bytes, eof })
}
fn write(
&mut self,
token: u64,
bytes: &[u8],
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let response = self
.request(json!({"op": "write", "token": token, "bytes": bytes}))
.map_err(|error| with_span(error, span))?;
response
.get("count")
.and_then(Json::as_u64)
.and_then(|count| usize::try_from(count).ok())
.ok_or_else(|| worker_error("write response has no count"))
}
fn close(&mut self, token: u64, span: Option<Span>) -> Result<(), RuntimeError> {
self.request(json!({"op": "close", "token": token}))
.map_err(|error| with_span(error, span))?;
Ok(())
}
}
impl Drop for WorkerResourceProvider {
fn drop(&mut self) {
let _ = self.request(json!({"op": "shutdown"}));
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn with_span(mut error: RuntimeError, span: Option<Span>) -> RuntimeError {
if error.span.is_none() {
error.span = span;
}
error
}
fn worker_error(message: &str) -> RuntimeError {
RuntimeError::new(ErrorCategory::HostError, None, message.to_string())
}
+928
View File
@@ -0,0 +1,928 @@
//! Host-owned resource/stream table (ADR-0025).
//!
//! The stream table owns run-scoped stdio endpoints, bounded project-file
//! read/write streams, explicitly registered provider tokens and IP-literal TCP
//! streams. Handles are opaque and the table validates run identity, slot
//! identity and generation on every call. Bytes move only through `Memory`.
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, UdpSocket};
use rustls::{ClientConnection, StreamOwned};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1);
/// A versioned trusted provider of additional resource kinds (ADR-0033).
///
/// In-process providers share the host address space and are **not** a
/// sandbox; only explicitly trusted code may be registered.
pub trait ResourceProvider: Send {
/// Stable grant name.
fn name(&self) -> &str;
/// Protocol version; must be 1 in this build.
fn protocol_version(&self) -> u32 {
1
}
/// Resource kinds served by this provider.
fn kinds(&self) -> &[&str];
/// Owned kind list used by registration. Providers with dynamically owned
/// kind strings override this.
fn kind_strings(&self) -> Vec<String> {
self.kinds()
.iter()
.map(|kind| (*kind).to_string())
.collect()
}
/// Open one descriptor, returning a provider-private token.
fn open(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<u64, RuntimeError>;
/// Read up to `max_bytes` from a token.
fn read(
&mut self,
token: u64,
max_bytes: usize,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError>;
/// Write bytes to a token; return the accepted count.
fn write(
&mut self,
token: u64,
bytes: &[u8],
span: Option<Span>,
) -> Result<usize, RuntimeError>;
/// Close a token.
fn close(&mut self, token: u64, span: Option<Span>) -> Result<(), RuntimeError>;
}
/// Shared provider handle registered on the host.
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 {
bytes: Vec<u8>,
position: usize,
}
#[allow(clippy::large_enum_variant)]
enum Stream {
Stdin {
cursor: Arc<Mutex<StdinCursor>>,
closed: bool,
},
Stdout {
closed: bool,
},
Stderr {
closed: bool,
},
File {
relative: String,
bytes: Vec<u8>,
position: usize,
closed: bool,
},
FileWriter {
relative: String,
bytes: Vec<u8>,
closed: bool,
},
Provider {
kind: String,
provider: SharedResourceProvider,
token: u64,
closed: bool,
},
Tcp {
stream: TcpStream,
closed: bool,
},
Udp {
socket: UdpSocket,
closed: bool,
},
TcpListener {
listener: TcpListener,
closed: bool,
},
Tls {
stream: StreamOwned<ClientConnection, TcpStream>,
closed: bool,
},
}
struct Slot {
generation: u64,
stream: Stream,
}
impl Slot {
fn closed(&self) -> bool {
match &self.stream {
Stream::Stdin { closed, .. } => *closed,
Stream::Stdout { closed } => *closed,
Stream::Stderr { closed } => *closed,
Stream::File { closed, .. } => *closed,
Stream::FileWriter { closed, .. } => *closed,
Stream::Provider { closed, .. } => *closed,
Stream::Tcp { closed, .. } => *closed,
Stream::Udp { closed, .. } => *closed,
Stream::TcpListener { closed, .. } => *closed,
Stream::Tls { closed, .. } => *closed,
}
}
}
/// Host resource table for one run.
pub struct ResourceTable {
run_id: u64,
next_resource: u64,
slots: BTreeMap<u64, Slot>,
stdin: Arc<Mutex<StdinCursor>>,
}
impl Default for ResourceTable {
fn default() -> Self {
Self::new()
}
}
impl ResourceTable {
/// Create an empty table with a fresh run identity.
pub fn new() -> Self {
Self {
run_id: NEXT_RUN_ID.fetch_add(1, Ordering::Relaxed),
next_resource: 1,
slots: BTreeMap::new(),
stdin: Arc::new(Mutex::new(StdinCursor {
bytes: Vec::new(),
position: 0,
})),
}
}
/// Number of live (not necessarily open) slots.
pub fn slot_count(&self) -> usize {
self.slots.len()
}
/// Register the pre-opened stdout stream.
pub fn open_stdout(&mut self) -> ResourceHandle {
self.insert(Stream::Stdout { closed: false })
}
/// Register the pre-opened stderr stream.
pub fn open_stderr(&mut self) -> ResourceHandle {
self.insert(Stream::Stderr { closed: false })
}
/// Set the run-scoped stdin bytes at assembly time.
///
/// All `stdio/stdin` handles share this cursor so repeated console reads
/// continue through the input instead of restarting at byte zero.
pub fn set_stdin(&mut self, bytes: Vec<u8>) {
self.stdin = Arc::new(Mutex::new(StdinCursor { bytes, position: 0 }));
}
/// Register a read-only handle over the run-scoped stdin cursor.
pub fn open_stdin(&mut self) -> ResourceHandle {
self.insert(Stream::Stdin {
cursor: Arc::clone(&self.stdin),
closed: false,
})
}
/// Return the stdio descriptor name for a handle, if it is a stdio stream.
pub fn stdio_name(
&self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<Option<&'static str>, RuntimeError> {
let slot = self.slot(handle, span)?;
Ok(match &slot.stream {
Stream::Stdin { .. } => Some("stdin"),
Stream::Stdout { .. } => Some("stdout"),
Stream::Stderr { .. } => Some("stderr"),
Stream::File { .. } | Stream::FileWriter { .. } => None,
Stream::Provider { .. }
| Stream::Tcp { .. }
| Stream::Udp { .. }
| Stream::TcpListener { .. }
| Stream::Tls { .. } => None,
})
}
/// Register a project-file read stream opened from already-bounded bytes.
pub fn open_file(&mut self, relative: impl Into<String>, bytes: Vec<u8>) -> ResourceHandle {
self.insert(Stream::File {
relative: relative.into(),
bytes,
position: 0,
closed: false,
})
}
/// Register an empty buffered project-file write stream.
pub fn open_file_writer(&mut self, relative: impl Into<String>) -> ResourceHandle {
self.insert(Stream::FileWriter {
relative: relative.into(),
bytes: Vec::new(),
closed: false,
})
}
/// Register a connected TCP stream.
pub fn open_tcp(&mut self, stream: TcpStream) -> ResourceHandle {
self.insert(Stream::Tcp {
stream,
closed: false,
})
}
/// Register a connected UDP socket.
pub fn open_udp(&mut self, socket: UdpSocket) -> ResourceHandle {
self.insert(Stream::Udp {
socket,
closed: false,
})
}
/// Register a bound TCP listener.
pub fn open_tcp_listener(&mut self, listener: TcpListener) -> ResourceHandle {
self.insert(Stream::TcpListener {
listener,
closed: false,
})
}
/// Register a TLS client stream over a TCP socket.
pub fn open_tls(&mut self, stream: StreamOwned<ClientConnection, TcpStream>) -> ResourceHandle {
self.insert(Stream::Tls {
stream,
closed: false,
})
}
/// Accept one inbound TCP connection from a listener, with a 5 s deadline.
pub fn accept(
&mut self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<ResourceHandle, RuntimeError> {
let slot = self.slot_mut(handle, span)?;
if slot.closed() {
return Err(RuntimeError::new(
ErrorCategory::ResourceClosed,
span,
"Resource handle is closed",
));
}
let Stream::TcpListener { listener, .. } = &mut slot.stream else {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"resource.accept requires a tcp-listener handle",
));
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
match listener.accept() {
Ok((stream, _)) => {
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
return Ok(self.insert(Stream::Tcp {
stream,
closed: false,
}));
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
if std::time::Instant::now() >= deadline {
return Err(RuntimeError::new(
ErrorCategory::HostError,
span,
"tcp-listener accept timed out after 5 seconds",
));
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(error) => {
return Err(RuntimeError::new(
ErrorCategory::HostError,
span,
format!("tcp-listener accept failed: {error}"),
))
}
}
}
}
/// Open a provider token and wrap it in a host-issued handle.
pub fn open_provider(
&mut self,
provider: SharedResourceProvider,
kind: &str,
descriptor: &str,
rights: &[String],
span: Option<Span>,
) -> Result<ResourceHandle, RuntimeError> {
let token = {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.open(kind, descriptor, rights, span)?
};
Ok(self.insert(Stream::Provider {
kind: kind.to_string(),
provider,
token,
closed: false,
}))
}
fn insert(&mut self, stream: Stream) -> ResourceHandle {
let id = self.next_resource;
self.next_resource += 1;
self.slots.insert(
id,
Slot {
generation: 1,
stream,
},
);
ResourceHandle::from_host(self.run_id, id, 1)
}
fn slot(&self, handle: ResourceHandle, span: Option<Span>) -> Result<&Slot, RuntimeError> {
if handle.run_id() != self.run_id {
return Err(RuntimeError::new(
ErrorCategory::ResourceFault,
span,
"Resource handle belongs to a different host run",
));
}
let Some(slot) = self.slots.get(&handle.resource_id()) else {
return Err(RuntimeError::new(
ErrorCategory::ResourceFault,
span,
"unknown Resource handle",
));
};
if slot.generation != handle.generation() {
return Err(RuntimeError::new(
ErrorCategory::ResourceFault,
span,
"stale Resource handle",
));
}
Ok(slot)
}
fn slot_mut(
&mut self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<&mut Slot, RuntimeError> {
self.slot(handle, span)?;
self.slots
.get_mut(&handle.resource_id())
.ok_or_else(|| unknown_handle(span))
}
/// Read up to `max_bytes` from a file stream.
///
/// Reads at EOF return `count=0, eof=true`. A read on a closed stream is
/// `resource.closed`; stdout is not readable.
pub fn read(
&mut self,
handle: ResourceHandle,
max_bytes: usize,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError> {
let slot = self.slot_mut(handle, span)?;
if slot.closed() {
return Err(RuntimeError::new(
ErrorCategory::ResourceClosed,
span,
"Resource handle is closed",
));
}
match &mut slot.stream {
Stream::Stdin { cursor, .. } => {
let mut cursor = cursor.lock().map_err(|_| stdin_lock_error(span))?;
let start = cursor.position;
let end = start.saturating_add(max_bytes).min(cursor.bytes.len());
let chunk = cursor.bytes[start..end].to_vec();
cursor.position = end;
Ok(ResourceRead {
bytes: chunk,
eof: end >= cursor.bytes.len(),
})
}
Stream::File {
bytes, position, ..
} => {
let start = *position;
let end = start.saturating_add(max_bytes).min(bytes.len());
let chunk = bytes[start..end].to_vec();
*position = end;
Ok(ResourceRead {
bytes: chunk,
eof: end >= bytes.len(),
})
}
Stream::Stdout { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"stdout does not support resource.read",
)),
Stream::Stderr { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"stderr does not support resource.read",
)),
Stream::FileWriter { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"a file write stream does not support resource.read",
)),
Stream::Provider {
provider, token, ..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
let read = provider.read(*token, max_bytes, span)?;
if read.bytes.len() > max_bytes {
return Err(RuntimeError::new(
ErrorCategory::ResourceFault,
span,
format!(
"resource provider returned {} bytes for a {max_bytes}-byte read",
read.bytes.len()
),
));
}
Ok(read)
}
Stream::Tcp { stream, .. } => {
let mut buffer = vec![0u8; max_bytes];
let count = stream.read(&mut buffer).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("tcp read failed: {error}"),
)
})?;
buffer.truncate(count);
Ok(ResourceRead {
bytes: buffer,
eof: count == 0,
})
}
Stream::TcpListener { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"a tcp-listener does not support resource.read; use resource.accept",
)),
Stream::Tls { stream, .. } => {
let mut buffer = vec![0u8; max_bytes];
let count = stream.read(&mut buffer).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("tls read failed: {error}"),
)
})?;
buffer.truncate(count);
Ok(ResourceRead {
bytes: buffer,
eof: count == 0,
})
}
Stream::Udp { socket, .. } => {
let mut buffer = vec![0u8; max_bytes];
let count = socket.recv(&mut buffer).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("udp read failed: {error}"),
)
})?;
buffer.truncate(count);
Ok(ResourceRead {
bytes: buffer,
eof: false,
})
}
}
}
/// Validate a stdout write and return the accepted byte count.
///
/// The caller performs the output-budget accounting and buffer append; this
/// method only checks handle identity, closed state and stream kind.
pub fn write(
&mut self,
handle: ResourceHandle,
bytes: &[u8],
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let slot = self.slot_mut(handle, span)?;
if slot.closed() {
return Err(RuntimeError::new(
ErrorCategory::ResourceClosed,
span,
"Resource handle is closed",
));
}
match &mut slot.stream {
Stream::Stdout { .. } | Stream::Stderr { .. } => Ok(bytes.len()),
Stream::Stdin { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"stdin is a read-only resource stream",
)),
Stream::File { relative, .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
format!("project file `{relative}` was opened read-only"),
)),
Stream::FileWriter {
relative,
bytes: buffer,
..
} => {
let next = buffer.len().checked_add(bytes.len());
let Some(next) = next else {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
format!("file write buffer for `{relative}` overflows"),
));
};
if next > crate::fs::MAX_READ_BYTES as usize {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
format!(
"file write buffer for `{relative}` exceeds the {} byte limit",
crate::fs::MAX_READ_BYTES
),
));
}
buffer.extend_from_slice(bytes);
Ok(bytes.len())
}
Stream::Provider {
provider, token, ..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
let count = provider.write(*token, bytes, span)?;
if count > bytes.len() {
return Err(RuntimeError::new(
ErrorCategory::ResourceFault,
span,
format!(
"resource provider reported {count} bytes written for a {}-byte request",
bytes.len()
),
));
}
Ok(count)
}
Stream::Tcp { stream, .. } => stream.write(bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("tcp write failed: {error}"),
)
}),
Stream::TcpListener { .. } => Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
span,
"a tcp-listener does not support resource.write; use resource.accept",
)),
Stream::Tls { stream, .. } => stream.write(bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("tls write failed: {error}"),
)
}),
Stream::Udp { socket, .. } => socket.send(bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
span,
format!("udp write failed: {error}"),
)
}),
}
}
/// Close a stream. A second close is `resource.closed`.
pub fn close(
&mut self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<(), RuntimeError> {
let slot = self.slot_mut(handle, span)?;
if slot.closed() {
return Err(RuntimeError::new(
ErrorCategory::ResourceClosed,
span,
"Resource handle is already closed",
));
}
match &mut slot.stream {
Stream::Stdin { closed, .. } => *closed = true,
Stream::Stdout { closed } => *closed = true,
Stream::Stderr { closed } => *closed = true,
Stream::File { closed, .. } => *closed = true,
Stream::FileWriter { closed, .. } => *closed = true,
Stream::Provider {
provider,
token,
closed,
..
} => {
let mut provider = provider.lock().map_err(|_| provider_lock_error(span))?;
provider.close(*token, span)?;
*closed = true;
}
Stream::Tcp { stream, closed } => {
let _ = stream.shutdown(std::net::Shutdown::Both);
*closed = true;
}
Stream::Udp { closed, .. } => *closed = true,
Stream::TcpListener { closed, .. } => *closed = true,
Stream::Tls { closed, .. } => *closed = true,
}
Ok(())
}
/// Return the buffered bytes of a file write stream without closing it.
///
/// `None` means the handle is not a file writer (stdout or a reader). The
/// caller must call [`Self::close`] only after the flush succeeds, so a
/// failed flush leaves the writer open with its buffer intact.
pub fn pending_file_write(
&self,
handle: ResourceHandle,
span: Option<Span>,
) -> Result<Option<(String, Vec<u8>)>, RuntimeError> {
let slot = self.slot(handle, span)?;
if slot.closed() {
return Err(RuntimeError::new(
ErrorCategory::ResourceClosed,
span,
"Resource handle is closed",
));
}
match &slot.stream {
Stream::FileWriter {
relative, bytes, ..
} => Ok(Some((relative.clone(), bytes.clone()))),
_ => Ok(None),
}
}
/// Descriptor kind for diagnostics/trace, if the handle is valid.
pub fn kind(&self, handle: ResourceHandle, span: Option<Span>) -> Result<String, RuntimeError> {
let slot = self.slot(handle, span)?;
Ok(match &slot.stream {
Stream::Stdin { .. } | Stream::Stdout { .. } | Stream::Stderr { .. } => {
"stdio".to_string()
}
Stream::File { .. } | Stream::FileWriter { .. } => "file".to_string(),
Stream::Provider { kind, .. } => kind.clone(),
Stream::Tcp { .. } => "tcp".to_string(),
Stream::Udp { .. } => "udp".to_string(),
Stream::TcpListener { .. } => "tcp-listener".to_string(),
Stream::Tls { .. } => "tls".to_string(),
})
}
}
fn provider_lock_error(span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::HostError,
span,
"resource provider lock is poisoned",
)
}
fn stdin_lock_error(span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::HostError,
span,
"stdin cursor lock is poisoned",
)
}
fn unknown_handle(span: Option<Span>) -> RuntimeError {
RuntimeError::new(
ErrorCategory::ResourceFault,
span,
"unknown Resource handle",
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn file_reads_are_chunked_with_eof() {
let mut table = ResourceTable::new();
let handle = table.open_file("data.txt", b"abcdef".to_vec());
assert_eq!(
table.read(handle, 2, None).unwrap(),
ResourceRead {
bytes: b"ab".to_vec(),
eof: false
}
);
assert_eq!(
table.read(handle, 8, None).unwrap(),
ResourceRead {
bytes: b"cdef".to_vec(),
eof: true
}
);
assert_eq!(
table.read(handle, 1, None).unwrap(),
ResourceRead {
bytes: Vec::new(),
eof: true
}
);
}
#[test]
fn forged_and_closed_handles_are_rejected() {
let mut table = ResourceTable::new();
let handle = table.open_stdout();
let forged = ResourceHandle::from_host(handle.run_id() + 1, handle.resource_id(), 1);
assert_eq!(
table.write(forged, b"x", None).unwrap_err().code(),
"runtime.resource"
);
table.close(handle, None).unwrap();
assert_eq!(
table.write(handle, b"x", None).unwrap_err().code(),
"resource.closed"
);
assert_eq!(
table.close(handle, None).unwrap_err().code(),
"resource.closed"
);
}
#[test]
fn stdout_is_not_readable_and_file_is_not_writable() {
let mut table = ResourceTable::new();
let stdout = table.open_stdout();
assert_eq!(
table.read(stdout, 1, None).unwrap_err().code(),
"resource.unsupported"
);
let file = table.open_file("x.txt", Vec::new());
assert_eq!(
table.write(file, b"x", None).unwrap_err().code(),
"resource.unsupported"
);
}
#[test]
fn stdin_reads_are_chunked_and_end_at_eof() {
let mut table = ResourceTable::new();
table.set_stdin(b"ab".to_vec());
let stdin = table.open_stdin();
assert_eq!(
table.read(stdin, 1, None).unwrap(),
ResourceRead {
bytes: b"a".to_vec(),
eof: false
}
);
assert_eq!(
table.read(stdin, 8, None).unwrap(),
ResourceRead {
bytes: b"b".to_vec(),
eof: true
}
);
assert_eq!(
table.read(stdin, 1, None).unwrap(),
ResourceRead {
bytes: Vec::new(),
eof: true
}
);
assert_eq!(
table.write(stdin, b"x", None).unwrap_err().code(),
"resource.unsupported"
);
table.close(stdin, None).unwrap();
assert_eq!(
table.read(stdin, 1, None).unwrap_err().code(),
"resource.closed"
);
}
#[test]
fn stderr_is_write_only() {
let mut table = ResourceTable::new();
let stderr = table.open_stderr();
assert_eq!(table.write(stderr, b"diagnostic", None).unwrap(), 10);
assert_eq!(
table.read(stderr, 1, None).unwrap_err().code(),
"resource.unsupported"
);
assert_eq!(table.stdio_name(stderr, None).unwrap(), Some("stderr"));
table.close(stderr, None).unwrap();
assert_eq!(
table.write(stderr, b"x", None).unwrap_err().code(),
"resource.closed"
);
}
}
#[cfg(test)]
mod provider_tests {
use super::*;
struct OverReporting;
impl ResourceProvider for OverReporting {
fn name(&self) -> &str {
"over-reporting"
}
fn kinds(&self) -> &[&str] {
&["bad"]
}
fn open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
_span: Option<Span>,
) -> Result<u64, RuntimeError> {
Ok(1)
}
fn read(
&mut self,
_token: u64,
max_bytes: usize,
_span: Option<Span>,
) -> Result<ResourceRead, RuntimeError> {
Ok(ResourceRead {
bytes: vec![0; max_bytes + 1],
eof: false,
})
}
fn write(
&mut self,
_token: u64,
bytes: &[u8],
_span: Option<Span>,
) -> Result<usize, RuntimeError> {
Ok(bytes.len() + 1)
}
fn close(&mut self, _token: u64, _span: Option<Span>) -> Result<(), RuntimeError> {
Ok(())
}
}
#[test]
fn provider_counts_are_bounded_by_the_request() {
let mut table = ResourceTable::new();
let provider: SharedResourceProvider = Arc::new(Mutex::new(Box::new(OverReporting)));
let handle = table
.open_provider(provider, "bad", "descriptor", &["read".to_string()], None)
.unwrap();
assert_eq!(
table.read(handle, 2, None).unwrap_err().code(),
"runtime.resource"
);
assert_eq!(
table.write(handle, b"x", None).unwrap_err().code(),
"runtime.resource"
);
}
}
+241
View File
@@ -0,0 +1,241 @@
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
match value {
marqdo_value::Value::Resource(handle) => handle,
other => panic!("expected resource, got {other:?}"),
}
}
fn cc_available() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn build_provider_with_version(dir: &Path, version: u32) -> PathBuf {
let source = dir.join("provider.c");
std::fs::write(
&source,
r#"
#include <stdint.h>
#include <stddef.h>
#include <string.h>
static const char DATA[] = "c-abi";
static size_t position = 0;
static uint64_t next_token = 1;
#ifndef PROVIDER_VERSION
#define PROVIDER_VERSION 1u
#endif
uint32_t marqdo_resource_provider_abi_version(void) { return PROVIDER_VERSION; }
int32_t marqdo_resource_open(const char *kind, const char *descriptor,
const char *rights_csv, uint64_t *out_token) {
(void)kind; (void)descriptor; (void)rights_csv;
position = 0;
*out_token = next_token++;
return 0;
}
int32_t marqdo_resource_read(uint64_t token, uint8_t *buffer,
uint32_t capacity, uint32_t *out_read,
int32_t *out_eof) {
(void)token;
size_t remaining = sizeof(DATA) - 1 - position;
size_t count = remaining < capacity ? remaining : capacity;
memcpy(buffer, DATA + position, count);
position += count;
*out_read = (uint32_t)count;
*out_eof = position >= sizeof(DATA) - 1 ? 1 : 0;
return 0;
}
int32_t marqdo_resource_write(uint64_t token, const uint8_t *bytes,
uint32_t length, uint32_t *out_written) {
(void)token; (void)bytes;
*out_written = length;
return 0;
}
int32_t marqdo_resource_close(uint64_t token) { (void)token; return 0; }
int32_t marqdo_resource_last_error(char *buffer, uint32_t capacity) {
if (capacity > 0) buffer[0] = 0;
return 0;
}
"#,
)
.unwrap();
let extension = if cfg!(target_os = "macos") {
"dylib"
} else {
"so"
};
let library = dir.join(format!("libecho_provider.{extension}"));
let status = Command::new("cc")
.args([
"-shared",
"-fPIC",
"-O2",
&format!("-DPROVIDER_VERSION={version}"),
"-o",
])
.arg(&library)
.arg(&source)
.status()
.expect("run cc");
assert!(status.success(), "C provider build failed");
library
}
fn build_provider(dir: &Path) -> PathBuf {
build_provider_with_version(dir, 1)
}
#[test]
fn c_abi_provider_round_trips() {
if !cc_available() {
eprintln!("skipping C provider test: cc is unavailable");
return;
}
let dir = tempfile::tempdir().unwrap();
let library = build_provider(dir.path());
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("cabi"),
project.path(),
);
host.register_c_resource_provider("cabi", &["cabi.sensor"], &library)
.unwrap();
let ctx = context();
let handle = handle(
host.resource_open("cabi.sensor", "sensor-1", &["read".to_string()], &ctx)
.unwrap(),
);
let first = host.resource_read(handle, 2, &ctx).unwrap();
assert_eq!(first.bytes, b"c-");
assert!(!first.eof);
let rest = host.resource_read(handle, 16, &ctx).unwrap();
assert_eq!(rest.bytes, b"abi");
assert!(rest.eof);
assert_eq!(host.resource_write(handle, b"xyz", &ctx).unwrap(), 3);
host.resource_close(handle, &ctx).unwrap();
assert_eq!(
host.resource_close(handle, &ctx).unwrap_err().code(),
"resource.closed"
);
}
#[test]
fn c_abi_provider_loading_fails_closed() {
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("cabi"),
project.path(),
);
let error = host
.register_c_resource_provider(
"cabi",
&["cabi.sensor"],
Path::new("/definitely/missing/marqdo-provider.so"),
)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::KernelUnavailable);
}
#[test]
fn c_abi_version_mismatch_and_modes_fail_closed() {
if !cc_available() {
eprintln!("skipping C provider test: cc is unavailable");
return;
}
let dir = tempfile::tempdir().unwrap();
let wrong = build_provider_with_version(dir.path(), 2);
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("cabi"),
project.path(),
);
let error = host
.register_c_resource_provider("cabi", &["cabi.sensor"], &wrong)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::ResourceUnsupported);
let good = build_provider(dir.path());
for mode in [SandboxMode::Pure, SandboxMode::Strict] {
let mut host = StdHost::new(
mode,
Capabilities::project().allow_resource_provider("cabi"),
project.path(),
);
host.register_c_resource_provider("cabi", &["cabi.sensor"], &good)
.unwrap();
let error = host
.resource_open("cabi.sensor", "s", &["read".to_string()], &context())
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
}
}
#[test]
fn provider_package_manifest_installs_a_c_abi_library() {
if !cc_available() {
eprintln!("skipping C provider test: cc is unavailable");
return;
}
let dir = tempfile::tempdir().unwrap();
let library = build_provider(dir.path());
let manifest = dir.path().join("provider.json");
let platform = if cfg!(target_os = "linux") {
"linux"
} else if cfg!(target_os = "macos") {
"macos"
} else {
"default"
};
std::fs::write(
&manifest,
serde_json::json!({
"schema": "marqdo.provider",
"schema_version": 1,
"name": "cabi",
"kinds": ["cabi.sensor"],
"abi": "c-abi-1",
"library": { platform: library.file_name().unwrap().to_string_lossy() }
})
.to_string(),
)
.unwrap();
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("cabi"),
project.path(),
);
host.register_provider_package(&manifest).unwrap();
let ctx = context();
let handle = handle(
host.resource_open("cabi.sensor", "s", &["read".to_string()], &ctx)
.unwrap(),
);
let read = host.resource_read(handle, 2, &ctx).unwrap();
assert_eq!(read.bytes, b"c-");
}
@@ -0,0 +1,581 @@
//! Trusted capability-handler registry (RFC-EXT-0001 §7, ADR-0057).
//!
//! These are end-to-end tests over the public `marqdo-host` API. They cover the
//! CAP-01..CAP-12 checks listed in RFC-EXT-0001 §7.5: policy vs handler,
//! package binding, registration validation, real `fs.read` scope enforcement,
//! reply budgets, forged/replayed handles, audit hygiene, resource-stream
//! regression, project-vs-strict labeling and the "no handler is never a
//! silent OK" rule.
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use marqdo_host::{
contains_plugin_handle, Budget, Capabilities, CapabilityBroker, CapabilityHandler,
CapabilityRequest, PluginHandleTable, ProjectFs, ResourceTable, SandboxMode, StdHost,
CORE_CAPABILITIES,
};
use marqdo_plugin_abi::PluginError;
use marqdo_value::{RuntimeError, Value};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new() -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-capability-handlers-{}-{id}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A trusted test handler that returns canned bytes.
struct FixedHandler {
name: &'static str,
reply: Vec<u8>,
}
impl CapabilityHandler for FixedHandler {
fn name(&self) -> &str {
self.name
}
fn execute(
&mut self,
_request: &CapabilityRequest<'_>,
_capabilities: &Capabilities,
_budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
Ok(self.reply.clone())
}
}
/// A trusted test handler that proves the request identity and budget reach it.
struct EchoHandler {
name: &'static str,
fuel: u64,
}
impl CapabilityHandler for EchoHandler {
fn name(&self) -> &str {
self.name
}
fn execute(
&mut self,
request: &CapabilityRequest<'_>,
_capabilities: &Capabilities,
budget: &mut Budget,
) -> Result<Vec<u8>, PluginError> {
budget
.consume_fuel(self.fuel, None)
.map_err(map_runtime_error)?;
Ok(format!(
"{}|{}|{}",
request.package_instance, request.capability, request.trace_id
)
.into_bytes())
}
}
fn map_runtime_error(error: RuntimeError) -> PluginError {
PluginError::capability(error.code(), error.message)
}
fn audit_entries(broker: &CapabilityBroker) -> Vec<marqdo_host::CapabilityAudit> {
let audit = broker.audit();
let guard = audit.lock().expect("audit lock");
guard.clone()
}
/// CAP-01: a declared vendor capability without a trusted policy entry is
/// denied, even when a handler happens to be installed.
#[test]
fn cap_01_vendor_capability_without_policy_is_denied() {
let mut broker = CapabilityBroker::new(Capabilities::project());
broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"device".to_vec(),
})
.unwrap();
let error = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(error.code, "permission.denied", "{error:?}");
assert!(broker
.authorize("demo.solver", "vendor.device.read", b"{}")
.is_err());
let audit = audit_entries(&broker);
assert_eq!(audit.len(), 2);
assert!(audit.iter().all(|entry| entry.decision == "denied"));
assert!(audit
.iter()
.all(|entry| entry.capability == "vendor.device.read"));
}
/// CAP-02: authorized but no handler installed is `capability.unavailable`;
/// `authorize` alone does not execute and cannot fake an empty success.
#[test]
fn cap_02_authorized_capability_without_handler_is_unavailable() {
let mut broker = CapabilityBroker::new(Capabilities::project().allow_write("out/**"));
broker.allow_vendor("vendor.device.read");
let unavailable = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(
unavailable.code, "capability.unavailable",
"{unavailable:?}"
);
// Policy is a grant, not an executor: authorize() succeeds, execute() still
// refuses because no trusted handler was registered.
assert!(broker
.authorize(
"demo.solver",
"fs.write",
br#"{"path":"out/result.txt","contents":"x"}"#,
)
.is_ok());
let write = broker
.execute(
"demo.solver",
"fs.write",
br#"{"path":"out/result.txt","contents":"x"}"#,
)
.unwrap_err();
assert_eq!(write.code, "capability.unavailable", "{write:?}");
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "unavailable" && entry.capability == "fs.write"));
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.capability == "fs.write"));
}
/// CAP-03: a handler bound to one trusted package rejects cross-package
/// impersonation, while the bound package still executes and the request
/// identity/trace id reach the handler.
#[test]
fn cap_03_package_bound_handler_rejects_impersonation() {
let mut broker = CapabilityBroker::new(Capabilities::project()).with_trace_id("trace-9");
broker.allow_vendor("vendor.device.read");
broker
.register_package_handler(
"demo.solver",
EchoHandler {
name: "vendor.device.read",
fuel: 0,
},
)
.unwrap();
let spoofed = broker
.execute("attacker.solver", "vendor.device.read", b"{}")
.unwrap_err();
assert_eq!(spoofed.code, "permission.denied", "{spoofed:?}");
let reply = broker
.execute("demo.solver", "vendor.device.read", b"{}")
.unwrap();
assert_eq!(
String::from_utf8(reply).unwrap(),
"demo.solver|vendor.device.read|trace-9"
);
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "denied" && entry.package == "attacker.solver"));
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.package == "demo.solver"));
}
/// CAP-04: duplicate, reserved, empty and malformed handler names are rejected
/// and never installed.
#[test]
fn cap_04_registration_rejects_duplicate_reserved_and_empty_names() {
let mut broker = CapabilityBroker::new(Capabilities::project());
let rejected = |broker: &mut CapabilityBroker, name: &'static str, expected: &str| {
let error = broker
.register_handler(FixedHandler {
name,
reply: Vec::new(),
})
.unwrap_err();
assert_eq!(error.code, expected, "name `{name}`: {error:?}");
assert!(!broker.has_handler(name));
};
rejected(&mut broker, "", "capability.handler_invalid");
rejected(&mut broker, "host.terminal", "capability.handler_reserved");
rejected(
&mut broker,
"marqdo.internal.read",
"capability.handler_reserved",
);
rejected(
&mut broker,
"not a capability",
"capability.handler_invalid",
);
rejected(&mut broker, "vendor..read", "capability.handler_invalid");
broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"device".to_vec(),
})
.unwrap();
let duplicate = broker
.register_handler(FixedHandler {
name: "vendor.device.read",
reply: b"other".to_vec(),
})
.unwrap_err();
assert_eq!(
duplicate.code, "capability.handler_conflict",
"{duplicate:?}"
);
// The trusted built-in fs.read handler cannot be replaced either.
let dir = TempDir::new();
let mut with_fs =
CapabilityBroker::new(Capabilities::project()).with_fs(ProjectFs::new(dir.path()));
assert!(with_fs.has_handler("fs.read"));
let conflict = with_fs
.register_handler(FixedHandler {
name: "fs.read",
reply: Vec::new(),
})
.unwrap_err();
assert_eq!(conflict.code, "capability.handler_conflict", "{conflict:?}");
}
/// CAP-05: the real `fs.read` handler enforces ProjectFs root/scope limits; a
/// permissive glob grant cannot be used to read outside the project root or to
/// traverse with `..`.
#[test]
fn cap_05_fs_read_handler_enforces_scope() {
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/allowed.txt"), "allowed").unwrap();
std::fs::create_dir_all(dir.path().join("private")).unwrap();
std::fs::write(dir.path().join("private/secret.txt"), "secret").unwrap();
let mut broker = CapabilityBroker::new(Capabilities::project().allow_read("data/**"))
.with_fs(ProjectFs::new(dir.path()));
let allowed = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/allowed.txt"}"#)
.unwrap();
assert_eq!(String::from_utf8(allowed).unwrap(), "allowed");
for out_of_scope in [
br#"{"path":"private/secret.txt"}"#.as_slice(),
br#"{"path":"../escape.txt"}"#.as_slice(),
br#"{"path":"/etc/passwd"}"#.as_slice(),
] {
let error = broker
.execute("demo.solver", "fs.read", out_of_scope)
.unwrap_err();
assert_eq!(
error.code, "permission.denied",
"{out_of_scope:?}: {error:?}"
);
}
// Even a `**` grant only authorizes project-relative paths: traversal and
// absolute paths are rejected by ProjectFs::resolve at the handler.
let mut permissive = CapabilityBroker::new(Capabilities::project().allow_read("**"))
.with_fs(ProjectFs::new(dir.path()));
for rejected in [
br#"{"path":"data/../private/secret.txt"}"#.as_slice(),
br#"{"path":"/etc/passwd"}"#.as_slice(),
] {
let error = permissive
.execute("demo.solver", "fs.read", rejected)
.unwrap_err();
assert_eq!(error.code, "permission.denied", "{rejected:?}: {error:?}");
}
}
/// CAP-06: a handler reply over the broker budget is a resource limit, and the
/// handler receives (and charges) the broker budget.
#[test]
fn cap_06_handler_reply_over_budget_is_resource_limit() {
let mut broker = CapabilityBroker::new(Capabilities::project())
.with_reply_limit(64)
.with_budget(Budget {
fuel: 10,
..Budget::default()
});
broker.allow_vendor("vendor.device.big");
broker.allow_vendor("vendor.device.fuel");
broker
.register_handler(FixedHandler {
name: "vendor.device.big",
reply: vec![b'x'; 65],
})
.unwrap();
broker
.register_handler(EchoHandler {
name: "vendor.device.fuel",
fuel: 4,
})
.unwrap();
let oversized = broker
.execute("demo.solver", "vendor.device.big", b"{}")
.unwrap_err();
assert_eq!(oversized.code, "resource.exhausted", "{oversized:?}");
let reply = broker
.execute("demo.solver", "vendor.device.fuel", b"{}")
.unwrap();
assert_eq!(
String::from_utf8(reply).unwrap(),
"demo.solver|vendor.device.fuel|"
);
assert_eq!(broker.budget().remaining_fuel(), 6);
let audit = audit_entries(&broker);
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
assert!(audit
.iter()
.any(|entry| entry.capability == "vendor.device.big" && entry.decision == "denied"));
}
/// CAP-07: forged plugin handles are rejected by the host table, and a handle
/// hidden inside an untrusted extension value is detected.
#[test]
fn cap_07_forged_handles_are_rejected() {
let mut table = PluginHandleTable::default();
let handle = table.mint("demo.capability", "capability.read", "demo.capability", 1);
table
.validate(&handle, "demo.capability", 1)
.expect("host-minted handle is valid");
let mut forged = handle.clone();
forged.id = handle.id.wrapping_add(1000);
let error = table
.validate(&forged, "demo.capability", 1)
.expect_err("forged id must be rejected");
assert!(
error.message.contains("plugin_handle.untrusted"),
"{error:?}"
);
let wrong_owner = table
.validate(&handle, "other.package", 1)
.expect_err("cross-owner handle must be rejected");
assert!(
wrong_owner.message.contains("plugin_handle.untrusted"),
"{wrong_owner:?}"
);
let untrusted_value = Value::Map(
[("handle".to_string(), Value::PluginHandle(handle.clone()))]
.into_iter()
.collect(),
);
assert!(contains_plugin_handle(&untrusted_value));
}
/// CAP-08: a handle from an old run or a cleared (unloaded) run is rejected on
/// replay.
#[test]
fn cap_08_replayed_handle_after_run_end_is_rejected() {
let mut table = PluginHandleTable::default();
let handle = table.mint("demo.capability", "capability.read", "demo.capability", 7);
table
.validate(&handle, "demo.capability", 7)
.expect("current run accepts its own handle");
let new_run = table
.validate(&handle, "demo.capability", 8)
.expect_err("a new run must not accept the old handle");
assert!(
new_run.message.contains("plugin_handle.untrusted"),
"{new_run:?}"
);
table.clear_run(7);
assert!(table.is_empty());
let replayed = table
.validate(&handle, "demo.capability", 7)
.expect_err("a cleared run must reject the replayed handle");
assert!(
replayed.message.contains("plugin_handle.untrusted"),
"{replayed:?}"
);
}
/// CAP-09: the capability audit records decisions and durations but never file
/// contents or request secrets.
#[test]
fn cap_09_audit_contains_no_file_contents_or_secrets() {
const SECRET: &str = "TOP-SECRET-PAYLOAD";
const API_KEY: &str = "sk-live-not-audited";
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/secret.txt"), SECRET).unwrap();
let mut broker = CapabilityBroker::new(Capabilities::project().allow_read("data/**"))
.with_fs(ProjectFs::new(dir.path()));
let request = format!(r#"{{"path":"data/secret.txt","api_key":"{API_KEY}"}}"#);
let contents = broker
.execute("demo.solver", "fs.read", request.as_bytes())
.unwrap();
assert_eq!(String::from_utf8(contents).unwrap(), SECRET);
let denied = broker
.execute("demo.solver", "fs.read", br#"{"path":"private/key.txt"}"#)
.unwrap_err();
assert_eq!(denied.code, "permission.denied");
let audit_debug = format!("{:?}", audit_entries(&broker));
assert!(!audit_debug.contains(SECRET), "{audit_debug}");
assert!(!audit_debug.contains(API_KEY), "{audit_debug}");
let audit = audit_entries(&broker);
assert!(audit
.iter()
.any(|entry| entry.decision == "granted" && entry.capability == "fs.read"));
assert!(audit
.iter()
.any(|entry| entry.decision == "denied" && entry.capability == "fs.read"));
assert!(audit.iter().all(|entry| entry.duration_micros <= 5_000_000));
}
/// CAP-10: low-level resource open/read/write/close stays on a sane performance
/// path. This is a catastrophic-regression guard with a deliberately generous
/// bound, not a benchmark (CI timeouts remain authoritative).
#[test]
fn cap_10_resource_stream_operations_do_not_regress_catastrophically() {
const CHUNK: usize = 256 * 1024;
const ITERATIONS: usize = 32;
let payload = vec![b'x'; CHUNK];
let mut table = ResourceTable::default();
let started = Instant::now();
for _ in 0..ITERATIONS {
let reader = table.open_file("data/blob.bin", payload.clone());
let read = table.read(reader, payload.len(), None).unwrap();
assert_eq!(read.bytes.len(), CHUNK);
assert!(read.eof);
table.close(reader, None).unwrap();
let writer = table.open_file_writer("out/blob.bin");
assert_eq!(table.write(writer, &payload, None).unwrap(), CHUNK);
table.close(writer, None).unwrap();
}
let elapsed = started.elapsed();
// 32 x (256 KiB read + 256 KiB write) is ~16 MiB of in-memory copying.
assert!(
elapsed < Duration::from_secs(5),
"resource open/read/write/close took {elapsed:?} for {ITERATIONS} iterations"
);
}
/// CAP-11: the default `project` mode is not an OS-strict mode and grants
/// nothing beyond `pure` by default.
#[test]
fn cap_11_default_project_mode_is_not_os_strict() {
let dir = TempDir::new();
let host = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
assert_eq!(host.mode, SandboxMode::Project);
assert_ne!(host.mode, SandboxMode::Strict);
assert_eq!(host.mode.as_str(), "project");
// Project defaults equal pure defaults: no implicit fs/process/plugin grant.
assert!(host.capabilities.fs_read.is_empty());
assert!(host.capabilities.fs_write.is_empty());
assert!(!host.capabilities.process);
assert!(!host.capabilities.foreign);
assert!(host.capabilities.plugins.is_empty());
// Strict isolation availability is a property of `strict`; project mode is
// cooperative in-process checks, whether or not the platform could isolate.
assert_eq!(
SandboxMode::parse(host.mode.as_str()),
Some(SandboxMode::Project)
);
}
/// CAP-12: core capabilities without an executing handler are always
/// `capability.unavailable`, never a silent empty success.
#[test]
fn cap_12_core_capabilities_without_handler_are_unavailable() {
let dir = TempDir::new();
std::fs::create_dir_all(dir.path().join("data")).unwrap();
std::fs::write(dir.path().join("data/ok.txt"), "ok").unwrap();
let mut capabilities = Capabilities::project()
.allow_read("data/**")
.allow_write("data/**")
.allow_net("127.0.0.1")
.allow_process("/bin/true");
capabilities.process = true;
let mut broker = CapabilityBroker::new(capabilities).with_fs(ProjectFs::new(dir.path()));
// The one migrated capability has a real handler.
let read = broker
.execute("demo.solver", "fs.read", br#"{"path":"data/ok.txt"}"#)
.unwrap();
assert_eq!(String::from_utf8(read).unwrap(), "ok");
// Every other core capability is authorized by its grant but has no
// executor in this build.
for name in CORE_CAPABILITIES {
if name == "fs.read" {
continue;
}
let payload: &[u8] = match name {
"fs.write" => br#"{"path":"data/x","contents":"x"}"#,
"net.request" => br#"{"host":"127.0.0.1"}"#,
_ => b"{}",
};
let error = broker.execute("demo.solver", name, payload).unwrap_err();
assert_eq!(
error.code, "capability.unavailable",
"core capability `{name}` must not silently succeed: {error:?}"
);
assert!(!broker.has_handler(name));
}
let unknown = broker
.execute("demo.solver", "teleport", b"{}")
.unwrap_err();
assert_eq!(unknown.code, "capability.unknown", "{unknown:?}");
let audit = audit_entries(&broker);
assert!(
audit
.iter()
.filter(|entry| entry.decision == "unavailable")
.count()
>= CORE_CAPABILITIES.len() - 1,
"{audit:?}"
);
}
File diff suppressed because it is too large. Load diff
+162
View File
@@ -0,0 +1,162 @@
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
match value {
marqdo_value::Value::Resource(handle) => handle,
other => panic!("expected resource, got {other:?}"),
}
}
fn helper() -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let script = dir.path().join("provider.py");
std::fs::write(
&script,
r#"
import sys, json, struct
def read_frame():
header = sys.stdin.buffer.read(4)
if len(header) < 4:
return None
size = struct.unpack(">I", header)[0]
return json.loads(sys.stdin.buffer.read(size))
def write_frame(value):
payload = json.dumps(value).encode()
sys.stdout.buffer.write(struct.pack(">I", len(payload)) + payload)
sys.stdout.buffer.flush()
data = b"hello world"
position = 0
while True:
request = read_frame()
if request is None:
break
op = request["op"]
if op == "ping":
write_frame({"ok": True})
elif op == "open":
write_frame({"ok": True, "token": 7})
elif op == "read":
count = request["max_bytes"]
chunk = data[position:position + count]
position += len(chunk)
write_frame({"ok": True, "bytes": list(chunk), "eof": position >= len(data)})
elif op == "write":
write_frame({"ok": True, "count": len(request["bytes"])})
elif op == "close":
write_frame({"ok": True})
elif op == "shutdown":
break
else:
write_frame({"ok": False, "code": "resource.unsupported", "message": op})
"#,
)
.unwrap();
(dir, script)
}
#[test]
fn worker_provider_round_trips_through_framed_json() {
let (dir, script) = helper();
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker"),
project.path(),
);
host.register_worker_resource_provider(
"worker",
&["worker.sensor"],
&std::path::PathBuf::from("python3"),
&[script.to_string_lossy().to_string()],
)
.unwrap();
let ctx = context();
let handle = handle(
host.resource_open("worker.sensor", "sensor-1", &["read".to_string()], &ctx)
.unwrap(),
);
let first = host.resource_read(handle, 5, &ctx).unwrap();
assert_eq!(first.bytes, b"hello");
assert!(!first.eof);
let rest = host.resource_read(handle, 64, &ctx).unwrap();
assert_eq!(rest.bytes, b" world");
assert!(rest.eof);
assert_eq!(host.resource_write(handle, b"abc", &ctx).unwrap(), 3);
host.resource_close(handle, &ctx).unwrap();
assert_eq!(
host.resource_close(handle, &ctx).unwrap_err().code(),
"resource.closed"
);
drop(dir);
}
#[test]
fn worker_provider_registration_requires_a_grant_and_project_mode() {
let (_dir, script) = helper();
let project = tempfile::tempdir().unwrap();
let ctx = context();
let mut denied = StdHost::new(
SandboxMode::Project,
Capabilities::project(),
project.path(),
);
denied
.register_worker_resource_provider(
"worker",
&["worker.sensor"],
&std::path::PathBuf::from("python3"),
&[script.to_string_lossy().to_string()],
)
.unwrap();
let error = denied
.resource_open("worker.sensor", "s", &["read".to_string()], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
for mode in [SandboxMode::Pure, SandboxMode::Strict] {
let mut host = StdHost::new(
mode,
Capabilities::project().allow_resource_provider("worker"),
project.path(),
);
host.register_worker_resource_provider(
"worker",
&["worker.sensor"],
&std::path::PathBuf::from("python3"),
&[script.to_string_lossy().to_string()],
)
.unwrap();
let error = host
.resource_open("worker.sensor", "s", &["read".to_string()], &ctx)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::PermissionDenied);
}
}
#[test]
fn missing_worker_program_is_a_structured_error() {
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker"),
project.path(),
);
let error = host
.register_worker_resource_provider(
"worker",
&["worker.sensor"],
&std::path::PathBuf::from("/definitely/missing/marqdo-provider"),
&[],
)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::KernelUnavailable);
}
+173
View File
@@ -167,6 +167,158 @@ const FS_WRITE: Builtin = Builtin {
named_only: false,
effectful: true,
};
const MEMORY_NEW: Builtin = Builtin {
name: "memory.new",
aliases: &[],
params: &[req("initial_pages"), req("max_pages")],
named_only: false,
effectful: false,
};
const MEMORY_SIZE: Builtin = Builtin {
name: "memory.size",
aliases: &[],
params: &[req("memory")],
named_only: false,
effectful: false,
};
const MEMORY_GROW: Builtin = Builtin {
name: "memory.grow",
aliases: &[],
params: &[req("memory"), req("pages")],
named_only: false,
effectful: false,
};
const LIST_APPEND: Builtin = Builtin {
name: "list.append",
aliases: &[],
params: &[req("list"), req("value")],
named_only: false,
effectful: false,
};
const LIST_CONCAT: Builtin = Builtin {
name: "list.concat",
aliases: &[],
params: &[req("left"), req("right")],
named_only: false,
effectful: false,
};
const MAP_KEYS: Builtin = Builtin {
name: "map.keys",
aliases: &[],
params: &[req("map")],
named_only: false,
effectful: false,
};
const MAP_HAS: Builtin = Builtin {
name: "map.has",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const MAP_GET: Builtin = Builtin {
name: "map.get",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const MAP_SET: Builtin = Builtin {
name: "map.set",
aliases: &[],
params: &[req("map"), req("key"), req("value")],
named_only: false,
effectful: false,
};
const MAP_REMOVE: Builtin = Builtin {
name: "map.remove",
aliases: &[],
params: &[req("map"), req("key")],
named_only: false,
effectful: false,
};
const TEXT_CODEPOINTS: Builtin = Builtin {
name: "text.codepoints",
aliases: &[],
params: &[req("text")],
named_only: false,
effectful: false,
};
const TEXT_FROM_CODEPOINT: Builtin = Builtin {
name: "text.from_codepoint",
aliases: &[],
params: &[req("codepoint")],
named_only: false,
effectful: false,
};
const TABLE_COLUMNS: Builtin = Builtin {
name: "table.columns",
aliases: &[],
params: &[req("table")],
named_only: false,
effectful: false,
};
const TABLE_ROW: Builtin = Builtin {
name: "table.row",
aliases: &[],
params: &[req("table"), req("row")],
named_only: false,
effectful: false,
};
const RESOURCE_OPEN: Builtin = Builtin {
name: "resource.open",
aliases: &[],
params: &[req("kind"), req("descriptor"), req("rights")],
named_only: false,
effectful: true,
};
const RESOURCE_READ: Builtin = Builtin {
name: "resource.read",
aliases: &[],
params: &[
req("handle"),
req("memory"),
req("offset"),
req("max_bytes"),
],
named_only: false,
effectful: true,
};
const RESOURCE_WRITE: Builtin = Builtin {
name: "resource.write",
aliases: &[],
params: &[req("handle"), req("memory"), req("offset"), req("length")],
named_only: false,
effectful: true,
};
const RESOURCE_CLOSE: Builtin = Builtin {
name: "resource.close",
aliases: &[],
params: &[req("handle")],
named_only: false,
effectful: true,
};
const RESOURCE_REQUEST: Builtin = Builtin {
name: "resource.request",
aliases: &[],
params: &[req("operation"), req("arguments")],
named_only: false,
effectful: true,
};
const RESOURCE_ACCEPT: Builtin = Builtin {
name: "resource.accept",
aliases: &[],
params: &[req("handle")],
named_only: false,
effectful: true,
};
const TABLE_CELL: Builtin = Builtin {
name: "table.cell",
aliases: &[],
params: &[req("table"), req("row"), req("column")],
named_only: false,
effectful: false,
};
/// All builtins known to the language. Host availability is decided at call
/// time by the capability layer, not here.
@@ -188,6 +340,27 @@ pub const BUILTINS: &[Builtin] = &[
FOREIGN_CALL,
FS_READ,
FS_WRITE,
MEMORY_NEW,
MEMORY_SIZE,
MEMORY_GROW,
LIST_APPEND,
LIST_CONCAT,
MAP_KEYS,
MAP_HAS,
MAP_GET,
MAP_SET,
MAP_REMOVE,
TEXT_CODEPOINTS,
TEXT_FROM_CODEPOINT,
TABLE_COLUMNS,
TABLE_ROW,
TABLE_CELL,
RESOURCE_OPEN,
RESOURCE_READ,
RESOURCE_WRITE,
RESOURCE_CLOSE,
RESOURCE_REQUEST,
RESOURCE_ACCEPT,
];
/// Find a builtin by canonical name or alias.
+201
View File
@@ -0,0 +1,201 @@
//! Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
//!
//! The frontend resolves every statically visible call site exactly once and
//! 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
//! prefix. The table is internal IR (not part of Analysis/Trace v2 wire
//! contracts) and is deliberately skipped when a [`crate::Program`] is
//! serialized.
//!
//! Identity rules:
//!
//! * a [`CallSiteKey`] is `(module, function, byte span)` and is therefore
//! independent of disk paths, registration order and hash-map iteration;
//! * a bound target names the *resolved implementation*, including the plugin
//! package, complete export name and verified artifact digest for ABI calls;
//! * [`BoundTarget::DynamicValue`] is the only non-static path and may only
//! call language values (for example a `FunctionRef`); it is never a back
//! door to an unknown ABI export.
use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{FunctionId, ModuleId};
/// Stable identity of one static call site.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct CallSiteKey {
/// Module containing the call.
pub module: ModuleId,
/// Function containing the call.
pub function: FunctionId,
/// First byte offset of the call expression.
pub span_start: usize,
/// End byte offset (exclusive) of the call expression.
pub span_end: usize,
}
impl CallSiteKey {
/// Construct a key from a function identity and an expression span.
pub fn new(function: FunctionId, span: marqdo_span::Span) -> Self {
Self {
module: function.module.clone(),
function,
span_start: span.start,
span_end: span.end,
}
}
}
impl fmt::Display for CallSiteKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}@{}..{}",
self.function, self.span_start, self.span_end
)
}
}
/// Resolved implementation target for a call site.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BoundTarget {
/// A fixed language builtin, by canonical builtin name.
Builtin {
/// Canonical name (for example `math.eval`), not a user alias.
canonical_name: String,
},
/// A function defined by a Markdown heading.
Marqdo {
/// Exact function identity.
function: FunctionId,
},
/// A statically declared ABI plugin export.
AbiPlugin {
/// Plugin package that owns the export.
package: String,
/// Complete dotted export name.
export: String,
/// Verified artifact digest from the selected manifest artifact.
digest: String,
/// Declared parameter names in manifest order; used to normalise
/// positional arguments deterministically for the ABI v1 map wire.
param_names: Vec<String>,
},
/// The callee is a language value resolved at runtime (local variable or
/// an expression result). Only language callables such as `FunctionRef`
/// are valid; this path cannot invoke an ABI plugin.
DynamicValue,
}
impl BoundTarget {
/// Whether this binding names a statically known implementation.
pub fn is_static(&self) -> bool {
!matches!(self, BoundTarget::DynamicValue)
}
}
/// One deterministic binding table for a prepared program.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CallBindingTable {
sites: BTreeMap<CallSiteKey, BoundTarget>,
}
impl CallBindingTable {
/// Insert a binding. Returns `false` when the site was already bound to a
/// different target; re-binding the same target is idempotent.
pub fn insert(&mut self, key: CallSiteKey, target: BoundTarget) -> bool {
match self.sites.get(&key) {
Some(existing) => existing == &target,
None => {
self.sites.insert(key, target);
true
}
}
}
/// Look up the bound target for a call site.
pub fn get(&self, key: &CallSiteKey) -> Option<&BoundTarget> {
self.sites.get(key)
}
/// Number of bound call sites.
pub fn len(&self) -> usize {
self.sites.len()
}
/// Whether no call site is bound.
pub fn is_empty(&self) -> bool {
self.sites.is_empty()
}
/// Iterate bindings deterministically (call site order).
pub fn iter(&self) -> impl Iterator<Item = (&CallSiteKey, &BoundTarget)> {
self.sites.iter()
}
/// Number of statically bound (non-dynamic) call sites.
pub fn static_count(&self) -> usize {
self.sites
.values()
.filter(|target| target.is_static())
.count()
}
/// Number of dynamically resolved call sites.
pub fn dynamic_count(&self) -> usize {
self.sites.len() - self.static_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
use marqdo_span::Span;
fn function(name: &str) -> FunctionId {
FunctionId {
module: ModuleId::root_default("index.mq.md"),
name: name.to_string(),
}
}
fn key(name: &str, span: Span) -> CallSiteKey {
CallSiteKey::new(function(name), span)
}
#[test]
fn keys_are_deterministic_and_span_based() {
let left = key("f", Span::new(10, 20));
let right = key("f", Span::new(10, 20));
let other = key("f", Span::new(21, 30));
assert_eq!(left, right);
assert_ne!(left, other);
assert_eq!(left.to_string(), "root:default::index.mq.md::f@10..20");
}
#[test]
fn insert_is_idempotent_but_rejects_conflicting_targets() {
let mut table = CallBindingTable::default();
let site = key("f", Span::new(1, 2));
assert!(table.insert(
site.clone(),
BoundTarget::Builtin {
canonical_name: "长度".into()
}
));
assert!(table.insert(
site.clone(),
BoundTarget::Builtin {
canonical_name: "长度".into()
}
));
assert!(!table.insert(site, BoundTarget::DynamicValue));
assert_eq!(table.len(), 1);
assert_eq!(table.static_count(), 1);
assert_eq!(table.dynamic_count(), 0);
}
}
+148 -8
View File
@@ -10,7 +10,7 @@ use std::fmt;
use serde::{Deserialize, Serialize};
use crate::{builtins, Function, Module, ModuleId, Param, Program, SignatureKind};
use crate::{builtins, Function, FunctionId, Module, ModuleId, Param, Program, SignatureKind};
use marqdo_span::Span;
/// Globally unique callable identity.
@@ -138,6 +138,42 @@ pub struct CallableRegistry {
builtins: BTreeMap<String, CallableDescriptor>,
functions: BTreeMap<ModuleId, BTreeMap<String, CallableDescriptor>>,
external: BTreeMap<String, CallableDescriptor>,
/// Official stdlib public aliases (for example `打印`/`print`) mapped to
/// the bundled Markdown function that implements them. Only the verified
/// stdlib loader may populate this table; third-party packages cannot.
official_aliases: BTreeMap<String, FunctionId>,
}
/// One official bundled-stdlib public alias.
#[derive(Debug, Clone, PartialEq)]
pub struct OfficialAlias {
/// Public names that resolve to the same target (for example both
/// `打印` and `print`).
pub public_names: Vec<String>,
/// Bundled Marqdo function implementing the alias.
pub function: FunctionId,
/// Effective signature; the loader must have checked it against the
/// verified stdlib metadata before registration.
pub signature: CallableSignature,
/// Owner package instance (the verified stdlib instance).
pub owner_package: String,
/// Conservative effect request summary for Trace/Analysis.
pub effects_requested: Vec<String>,
}
/// A deterministic static-table conflict.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallableConflict {
/// Colliding public name.
pub public_name: String,
/// Human-readable reason; never used as a machine code.
pub reason: String,
}
impl fmt::Display for CallableConflict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`{}`: {}", self.public_name, self.reason)
}
}
impl CallableRegistry {
@@ -150,21 +186,46 @@ impl CallableRegistry {
}
/// Build a registry for all modules and declared external descriptors.
pub fn from_program(program: &Program) -> Self {
///
/// Duplicate external names are rejected rather than silently keeping the
/// first entry: a static table must never depend on registration order.
pub fn try_from_program(program: &Program) -> Result<Self, CallableConflict> {
let mut registry = Self::default();
registry.add_builtins();
for module in program.modules.values() {
registry.add_module(module);
}
for descriptor in &program.external_callables {
// Conflicting declarations are reported by the loader; keep the
// first deterministic entry here rather than overwriting silently.
registry
.external
.entry(descriptor.public_name.clone())
.or_insert_with(|| descriptor.clone());
.insert_external(descriptor.clone())
.map_err(|reason| CallableConflict {
public_name: descriptor.public_name.clone(),
reason,
})?;
}
registry
Ok(registry)
}
/// Build a registry for all modules and declared external descriptors.
///
/// Prefer [`CallableRegistry::try_from_program`] on the CLI composition
/// path; this compatibility wrapper keeps the first declaration for
/// already-validated callers (tests and embedders).
pub fn from_program(program: &Program) -> Self {
Self::try_from_program(program).unwrap_or_else(|_| {
let mut registry = Self::default();
registry.add_builtins();
for module in program.modules.values() {
registry.add_module(module);
}
for descriptor in &program.external_callables {
registry
.external
.entry(descriptor.public_name.clone())
.or_insert_with(|| descriptor.clone());
}
registry
})
}
/// Look up a builtin by canonical name or alias.
@@ -188,6 +249,85 @@ impl CallableRegistry {
self.external.values()
}
/// Register one official bundled-stdlib public alias.
///
/// The loader calls this only after verifying the bundled stdlib digest and
/// the metadata digest, so a third-party package can never claim `打印`,
/// `print` or any other official public name through this path.
pub fn insert_official_alias(&mut self, alias: OfficialAlias) -> Result<(), String> {
if alias.public_names.is_empty() {
return Err("official alias must declare at least one public name".to_string());
}
if alias.function.module.instance.is_empty() || alias.function.name.is_empty() {
return Err("official alias target function identity must not be empty".to_string());
}
for name in &alias.public_names {
if name.is_empty() {
return Err("official alias public name must not be empty".to_string());
}
if self.external.contains_key(name) {
return Err(format!(
"official alias `{name}` conflicts with a declared plugin export"
));
}
let descriptor = CallableDescriptor {
id: CallableId(format!("marqdo:{}", alias.function)),
public_name: name.clone(),
owner_package: alias.owner_package.clone(),
signature: alias.signature.clone(),
effects_requested: alias.effects_requested.clone(),
origin: CallableOrigin::Marqdo,
implementation_digest: None,
source_span: None,
};
// Official aliases intentionally replace the reserved placeholder
// builtin (for example `打印`); no third-party path can do this.
self.builtins.insert(name.clone(), descriptor);
self.official_aliases
.insert(name.clone(), alias.function.clone());
}
Ok(())
}
/// Target Marqdo function of an official alias, if `name` is one.
pub fn alias_target(&self, name: &str) -> Option<&FunctionId> {
self.official_aliases.get(name)
}
/// Iterate official aliases deterministically (public name, target).
pub fn official_aliases(&self) -> impl Iterator<Item = (&String, &FunctionId)> {
self.official_aliases.iter()
}
/// Whether a dotted builtin namespace starts with `prefix.`.
pub fn has_builtin_dotted_prefix(&self, prefix: &str) -> bool {
self.builtins.keys().any(|name| {
name.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('.'))
})
}
/// Whether a declared plugin export starts with `prefix.`.
pub fn has_external_dotted_prefix(&self, prefix: &str) -> bool {
self.external.keys().any(|name| {
name.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('.'))
})
}
/// Resolve a module function to its exact identity.
pub fn function_id(&self, module: &ModuleId, name: &str) -> Option<FunctionId> {
let descriptor = self.function(module, name)?;
if matches!(descriptor.origin, CallableOrigin::Marqdo) {
Some(FunctionId {
module: module.clone(),
name: descriptor.public_name.clone(),
})
} else {
None
}
}
/// Insert an external descriptor, rejecting duplicate public names.
pub fn insert_external(&mut self, descriptor: CallableDescriptor) -> Result<(), String> {
if self.builtins.contains_key(&descriptor.public_name) {
+71 -56
View File
@@ -12,11 +12,12 @@
use std::collections::BTreeMap;
use std::fmt;
use marqdo_expression::{Arg, Expr};
use marqdo_expression::Expr;
use marqdo_span::Span;
use serde::{Deserialize, Serialize};
pub mod builtins;
pub mod call_binding;
pub mod callable;
/// Canonical logical identity of a module: package instance plus a path
@@ -152,6 +153,8 @@ pub enum UnitKind {
Namespace,
/// Level-2 heading: function.
Function,
/// Level-2 heading in Knowledge mode: inert knowledge unit.
Knowledge,
/// Level-3+ heading inside a function: named section, not a callable unit.
Section,
}
@@ -224,16 +227,52 @@ pub struct Function {
pub body: Vec<Stmt>,
}
/// Writable place of an assignment (ADR-0022).
///
/// Both variants come from an executable payload whose text is
/// `target = expression` (any carrier: `Strong`, `Emph` or inline `Code`).
/// `Local` rebinds a frame slot;
/// `Index` writes one byte into an addressable runtime `Memory` region and is
/// rejected for every other base value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "place", rename_all = "snake_case")]
pub enum PlaceTarget {
/// Local slot rebinding.
Local {
/// Target name.
name: String,
/// Span of the target name.
name_span: Span,
},
/// `base[index] = value`; only a `Memory` base is writable.
Index {
/// Base expression, evaluated first.
base: Expr,
/// Index expression, evaluated second.
index: Expr,
/// Span from the base start through the closing `]`.
span: Span,
},
}
impl PlaceTarget {
/// Best known source span of the place.
pub fn span(&self) -> Span {
match self {
PlaceTarget::Local { name_span, .. } => *name_span,
PlaceTarget::Index { span, .. } => *span,
}
}
}
/// An executable statement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "stmt", rename_all = "snake_case")]
pub enum Stmt {
/// Local assignment (`strong` node with `name = expr`).
/// Assignment to a local slot or a `Memory` index.
Assign {
/// Target name.
name: String,
/// Span of the target name (approximated by the payload span).
name_span: Span,
/// Writable place.
target: PlaceTarget,
/// Value expression.
value: Expr,
/// Span of the whole statement.
@@ -246,21 +285,14 @@ pub enum Stmt {
/// Span of the whole statement.
span: Span,
},
/// Markdown-link call form from a block quote.
Call {
/// Resolved call site.
call: CallSite,
/// Span of the whole statement.
span: Span,
},
/// Ordered list: first matching condition wins.
/// `if`/`else` group: the first true arm wins.
Branch {
/// Arms in AST order.
arms: Vec<BranchArm>,
/// Span of the list node.
span: Span,
},
/// Bullet list item: a `while` loop.
/// `while`/`end` group.
Loop {
/// Loop condition.
condition: Expr,
@@ -268,10 +300,10 @@ pub enum Stmt {
condition_span: Span,
/// Loop body.
body: Vec<Stmt>,
/// Span of the list item.
/// Span of the whole `while` statement.
span: Span,
},
/// Return from the enclosing function (`emph` node).
/// Return from the enclosing function (`return` statement).
Return {
/// Returned expression.
value: Expr,
@@ -286,7 +318,6 @@ impl Stmt {
match self {
Stmt::Assign { span, .. }
| Stmt::Eval { span, .. }
| Stmt::Call { span, .. }
| Stmt::Branch { span, .. }
| Stmt::Loop { span, .. }
| Stmt::Return { span, .. } => *span,
@@ -294,12 +325,12 @@ impl Stmt {
}
}
/// One arm of a branch (ordered list item).
/// One arm of an `if`/`else` group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BranchArm {
/// Boolean condition expression.
pub condition: Expr,
/// Span of the condition code span.
/// Span of the condition payload.
pub condition_span: Span,
/// Statements executed when the condition is true.
pub body: Vec<Stmt>,
@@ -307,42 +338,6 @@ pub struct BranchArm {
pub span: Span,
}
/// Target of a call statement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "target", rename_all = "snake_case")]
pub enum CallTarget {
/// Unqualified function in the current module.
Function {
/// Canonical function name.
name: String,
},
/// Function reached through an imported module alias.
Qualified {
/// Local import alias.
module_alias: String,
/// Canonical function name.
function: String,
},
/// Function resolved from a Markdown link target.
Resolved {
/// Canonical module identity.
module: ModuleId,
/// Canonical function name.
function: String,
},
}
/// A call statement with evaluated arguments.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallSite {
/// Callee target.
pub target: CallTarget,
/// Arguments in source order.
pub args: Vec<Arg>,
/// Span of the call.
pub span: Span,
}
/// One explicit import declared in front matter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportDecl {
@@ -482,6 +477,13 @@ pub struct Program {
/// metadata only: `check` never loads a library.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub external_callables: Vec<callable::CallableDescriptor>,
/// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
///
/// Internal IR: deliberately skipped on the wire so Analysis/Trace v2
/// consumers are unaffected. A prepared program always carries a complete
/// table; the runtime never re-resolves names.
#[serde(skip)]
pub call_bindings: call_binding::CallBindingTable,
}
impl Program {
@@ -519,6 +521,19 @@ impl Program {
pub fn callable_registry(&self) -> callable::CallableRegistry {
callable::CallableRegistry::from_program(self)
}
/// Resolved static call binding for one call site, if any.
pub fn call_binding(
&self,
key: &call_binding::CallSiteKey,
) -> Option<&call_binding::BoundTarget> {
self.call_bindings.get(key)
}
/// Install the prepared binding table.
pub fn set_call_bindings(&mut self, bindings: call_binding::CallBindingTable) {
self.call_bindings = bindings;
}
}
#[cfg(test)]
+2 -2
View File
@@ -72,9 +72,9 @@ pub enum MdKind {
Paragraph,
/// Literal text.
Text,
/// Strong emphasis: an execution statement in executable position.
/// Strong emphasis: one payload carrier in an `@exec` scope.
Strong,
/// Emphasis: a return statement in executable position.
/// Emphasis: one payload carrier in an `@exec` scope.
Emph,
/// GFM strikethrough.
Strikethrough,
+25
View File
@@ -66,6 +66,19 @@ impl FrontMatter {
Ok(result)
}
/// Whether the top-level YAML mapping contains `key`.
///
/// Returns `false` for invalid YAML. Used to reject removed syntax
/// selectors such as `marqdo_semantics` or `syntax` without making the
/// frontend depend on a YAML crate.
pub fn has_key(&self, key: &str) -> bool {
let Ok(yaml) = &self.yaml else {
return false;
};
yaml.as_mapping()
.is_some_and(|mapping| mapping.contains_key(key))
}
/// The raw YAML parses successfully.
pub fn is_valid(&self) -> bool {
self.yaml.is_ok()
@@ -153,6 +166,18 @@ mod tests {
assert!(fm.imports().is_err());
}
#[test]
fn detects_removed_syntax_selector_keys() {
let literal = "---\nmarqdo_semantics: 2\nimport:\n x: \"@x\"\n---\n";
let fm = parse_literal(literal, Span::new(0, literal.len()));
assert!(fm.has_key("marqdo_semantics"));
assert!(!fm.has_key("syntax"));
assert!(fm.has_key("import"));
let invalid = parse_literal("---\nimport: [unclosed\n---", Span::new(0, 24));
assert!(!invalid.has_key("import"), "invalid YAML reports no key");
}
#[test]
fn import_shapes_are_validated() {
let literal = "---\nimport: geometry\n---\n";
+1
View File
@@ -13,6 +13,7 @@ serde = { workspace = true }
serde_yaml = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
semver = { workspace = true }
walkdir = { workspace = true }
hex = { workspace = true }
+2 -2
View File
@@ -273,7 +273,7 @@ mod tests {
fn excludes_git_and_marqdo_directories() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(&root.join("index.mq.md"), b"## main\n");
write(&root.join("index.mq.md"), b"## @exec main\n");
write(&root.join(".git/HEAD"), b"ref: main\n");
write(&root.join(".marqdo/env/env.json"), b"{}");
write(&root.join("nested/.marqdo/state"), b"x");
@@ -343,7 +343,7 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let source = dir.path().join("source");
let target = dir.path().join("target");
write(&source.join("index.mq.md"), b"## main\n");
write(&source.join("index.mq.md"), b"## @exec main\n");
write(&source.join("data/value.txt"), b"42");
write(&source.join(".git/HEAD"), b"ignored");
let digest = hash_tree(&source).unwrap();
+724 -20
View File
@@ -65,7 +65,10 @@ impl Dependency {
(None, Some(_)) if !is_full_commit(self.rev.as_deref().unwrap_or("")) => Err(format!(
"dependency `{name}` git rev must be a full lowercase 40- or 64-character commit hash"
)),
(Some(path), None) if path.is_absolute() => Err(format!(
// `has_root`, not `is_absolute`: on Windows a drive-less rooted
// path such as `/tmp/x` or `\tmp\x` is not `is_absolute()` but
// still escapes the project when joined. Reject every rooted path.
(Some(path), None) if path.has_root() => Err(format!(
"dependency `{name}` path must be project-relative"
)),
_ => Ok(()),
@@ -113,6 +116,233 @@ pub struct NetRequests {
pub hosts: Vec<String>,
}
/// Extension category explicitly selected by a project manifest
/// (RFC-EXT-0001 §6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExtensionKind {
/// Callable ABI plugin (`plugin.yaml`).
Plugin,
/// Foreign kernel descriptor (`kernel.json`).
Kernel,
/// Resource provider manifest (`provider.json`).
Provider,
}
impl ExtensionKind {
/// Stable lowercase name used in lock files and diagnostics.
pub const fn as_str(self) -> &'static str {
match self {
ExtensionKind::Plugin => "plugin",
ExtensionKind::Kernel => "kernel",
ExtensionKind::Provider => "provider",
}
}
/// Parse the stable lowercase name.
pub fn parse(value: &str) -> Option<Self> {
match value {
"plugin" => Some(ExtensionKind::Plugin),
"kernel" => Some(ExtensionKind::Kernel),
"provider" => Some(ExtensionKind::Provider),
_ => None,
}
}
}
impl std::fmt::Display for ExtensionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// One explicit extension activation source.
///
/// Allowed forms are deliberately narrow (RFC-EXT-0001 §6.3):
///
/// * `./relative/path` — a regular file inside the current project;
/// * `@alias/relative/path` — a regular file inside a locked dependency.
///
/// Absolute paths, `..` traversal, HTTP(S) URLs, globs and implicit searches
/// are rejected. A declaration is activation/visibility, never a grant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExtensionSource {
/// Declared source string.
pub from: String,
}
impl ExtensionSource {
/// Parse and validate the source form.
pub fn resolve(
&self,
dependencies: &BTreeMap<String, Dependency>,
) -> Result<ResolvedExtensionSource, String> {
let value = self.from.trim();
if value.is_empty() {
return Err("extension `from` must not be empty".to_string());
}
if let Some(rest) = value.strip_prefix("./") {
let relative = safe_relative(rest, "extension source")?;
return Ok(ResolvedExtensionSource::ProjectRelative(relative));
}
if let Some(rest) = value.strip_prefix('@') {
let (alias, relative) = rest.split_once('/').ok_or_else(|| {
format!("extension source `{value}` must be `@alias/relative/path`")
})?;
if alias.is_empty() {
return Err(format!("extension source `{value}` has an empty alias"));
}
if !dependencies.contains_key(alias) {
return Err(format!(
"extension source `{value}` uses `@{alias}`, which is not a declared dependency"
));
}
let relative = safe_relative(relative, "extension source")?;
return Ok(ResolvedExtensionSource::Dependency {
alias: alias.to_string(),
relative,
});
}
Err(format!(
"extension source `{value}` must be `./relative/path` or `@alias/relative/path`; absolute paths, URLs and implicit discovery are not allowed"
))
}
}
/// A resolved extension activation source (regular file inside a package).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedExtension {
/// Extension category declared by the manifest block.
pub kind: ExtensionKind,
/// Declared `from` string (identity key in the lock).
pub from: String,
/// Canonical manifest/descriptor file path.
pub path: PathBuf,
/// Logical owner package instance (`root:...` or a dependency instance id).
pub logical_owner: String,
/// Canonical package root that contains the file.
pub package_root: PathBuf,
}
/// A parsed extension source relative to a project or dependency.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedExtensionSource {
/// `./relative/path` below the project root.
ProjectRelative(PathBuf),
/// `@alias/relative/path` below a declared dependency.
Dependency {
/// Dependency alias.
alias: String,
/// Package-relative path.
relative: PathBuf,
},
}
fn resolve_extension_file(
package_root: &Path,
relative: &Path,
kind: ExtensionKind,
from: &str,
) -> Result<PathBuf, String> {
let candidate = package_root.join(relative);
let canonical = candidate.canonicalize().map_err(|error| {
format!(
"cannot open {kind} extension source `{from}` at `{}`: {error}",
candidate.display()
)
})?;
if !canonical.starts_with(package_root) {
return Err(format!(
"{kind} extension source `{from}` escapes its owning package"
));
}
let metadata = std::fs::metadata(&canonical)
.map_err(|error| format!("cannot stat {kind} extension source `{from}`: {error}"))?;
if !metadata.is_file() {
return Err(format!(
"{kind} extension source `{from}` must be a regular file"
));
}
Ok(canonical)
}
fn safe_relative(value: &str, what: &str) -> Result<PathBuf, String> {
if value.is_empty() {
return Err(format!("{what} path must not be empty"));
}
let mut normalised = PathBuf::new();
for component in Path::new(value).components() {
match component {
std::path::Component::Normal(part) => normalised.push(part),
std::path::Component::CurDir => {}
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_) => {
return Err(format!(
"{what} path `{value}` must stay inside its package (no `..`, absolute or rooted paths)"
))
}
}
}
if normalised.as_os_str().is_empty() {
return Err(format!("{what} path must not be empty"));
}
Ok(normalised)
}
/// The `extensions:` block of `marqdo.yaml` (explicit activation sources).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Extensions {
/// Callable plugin manifests.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub plugins: Vec<ExtensionSource>,
/// Foreign kernel descriptors.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kernels: Vec<ExtensionSource>,
/// Resource provider manifests.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub providers: Vec<ExtensionSource>,
}
impl Extensions {
/// Whether no extension is declared.
pub fn is_empty(&self) -> bool {
self.plugins.is_empty() && self.kernels.is_empty() && self.providers.is_empty()
}
/// Iterate `(kind, source)` in deterministic kind order.
pub fn iter(&self) -> impl Iterator<Item = (ExtensionKind, &ExtensionSource)> {
self.plugins
.iter()
.map(|source| (ExtensionKind::Plugin, source))
.chain(
self.kernels
.iter()
.map(|source| (ExtensionKind::Kernel, source)),
)
.chain(
self.providers
.iter()
.map(|source| (ExtensionKind::Provider, source)),
)
}
fn validate(&self, dependencies: &BTreeMap<String, Dependency>) -> Result<(), String> {
let mut seen: std::collections::BTreeSet<(ExtensionKind, String)> =
std::collections::BTreeSet::new();
for (kind, source) in self.iter() {
source.resolve(dependencies)?;
if !seen.insert((kind, source.from.clone())) {
return Err(format!(
"{kind} extension source `{}` is declared more than once",
source.from
));
}
}
Ok(())
}
}
/// The `marqdo.yaml` project manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
@@ -127,6 +357,9 @@ pub struct Manifest {
/// Capability requests.
#[serde(default, skip_serializing_if = "CapabilityRequests::is_empty")]
pub capabilities: CapabilityRequests,
/// Explicit extension activation sources (never authorization).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extensions: Option<Extensions>,
}
/// A requested plugin (installation is not authorization).
@@ -160,6 +393,9 @@ impl Manifest {
if self.project.version.trim().is_empty() {
return Err("project.version must not be empty".to_string());
}
if let Some(range) = &self.project.marqdo {
validate_core_range(range)?;
}
for (name, dependency) in &self.dependencies {
dependency.validate(name)?;
}
@@ -170,6 +406,9 @@ impl Manifest {
));
}
}
if let Some(extensions) = &self.extensions {
extensions.validate(&self.dependencies)?;
}
Ok(())
}
@@ -184,15 +423,41 @@ impl Manifest {
project: ProjectInfo {
name: project_name.to_string(),
version: "0.1.0".to_string(),
marqdo: Some(">=0.1,<1".to_string()),
marqdo: Some(">=3.0.0-beta.1,<4.0.0".to_string()),
},
dependencies: BTreeMap::new(),
plugins: BTreeMap::new(),
capabilities: CapabilityRequests::default(),
extensions: None,
}
}
}
/// Enforce the optional `project.marqdo` runtime range.
///
/// The field was informational before the 3.0 beta; a project that declares a
/// range the running core does not satisfy must fail closed with a clear
/// diagnostic instead of being silently ignored. SemVer prerelease semantics
/// apply: a stable-only range such as `>=3.0.0,<4.0.0` does not accept
/// `3.0.0-beta.1`, so prerelease users must opt in explicitly.
fn validate_core_range(range: &str) -> Result<(), String> {
let requirement = semver::VersionReq::parse(range).map_err(|error| {
format!(
"package.marqdo_range_invalid: project.marqdo `{range}` is not a valid SemVer requirement: {error}"
)
})?;
let core = semver::Version::parse(env!("CARGO_PKG_VERSION")).map_err(|error| {
format!("package.marqdo_range_invalid: core version is not valid SemVer: {error}")
})?;
if !requirement.matches(&core) {
return Err(format!(
"package.marqdo_incompatible: project requires marqdo `{range}`, this core is {}",
env!("CARGO_PKG_VERSION")
));
}
Ok(())
}
/// How a resolved package was obtained. Identity does not depend on this.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PackageOrigin {
@@ -389,6 +654,59 @@ impl PackageResolver {
&self.root
}
/// Resolve and validate every `marqdo.yaml.extensions` source to a real
/// regular file inside its owning package (RFC-EXT-0001 §6.3).
///
/// This is pure static path resolution: no extension binary is loaded, no
/// script is executed and no grant is implied. Resolution order is sorted by
/// `(kind, from)` so the resulting fact table never depends on YAML order.
pub fn resolve_extension_sources(&self) -> Result<Vec<ResolvedExtension>, String> {
let Some(manifest) = &self.manifest else {
return Ok(Vec::new());
};
let Some(extensions) = &manifest.extensions else {
return Ok(Vec::new());
};
let root = self
.root
.canonicalize()
.map_err(|error| format!("cannot resolve project root: {error}"))?;
let owner = root_instance(Some(manifest));
let mut resolved = Vec::new();
for (kind, source) in extensions.iter() {
match source.resolve(&manifest.dependencies)? {
ResolvedExtensionSource::ProjectRelative(relative) => {
let path = resolve_extension_file(&root, &relative, kind, &source.from)?;
resolved.push(ResolvedExtension {
kind,
from: source.from.clone(),
path,
logical_owner: owner.clone(),
package_root: root.clone(),
});
}
ResolvedExtensionSource::Dependency { alias, relative } => {
let module = self.resolve_alias(&alias)?;
let package_root =
module.package.module_root.canonicalize().map_err(|error| {
format!("cannot resolve package root for dependency `{alias}`: {error}")
})?;
let path =
resolve_extension_file(&package_root, &relative, kind, &source.from)?;
resolved.push(ResolvedExtension {
kind,
from: source.from.clone(),
path,
logical_owner: module.package.instance_id.clone(),
package_root,
});
}
}
}
resolved.sort_by(|left, right| (&left.kind, &left.from).cmp(&(&right.kind, &right.from)));
Ok(resolved)
}
/// The project manifest, if the entry is part of a project.
pub fn manifest(&self) -> Option<&Manifest> {
self.manifest.as_ref()
@@ -846,6 +1164,7 @@ impl PackageResolver {
},
packages,
root_dependencies,
extensions: Vec::new(),
};
lock.validate()?;
Ok(ResolvedLockGraph {
@@ -1112,7 +1431,7 @@ fn package_name_version(manifest: &Option<Manifest>, alias: &str) -> (String, St
}
/// Lock format version written by this build.
pub const LOCK_VERSION: u32 = 3;
pub const LOCK_VERSION: u32 = 4;
/// One package instance in `marqdo.lock` v3.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -1135,7 +1454,7 @@ pub struct LockedPackage {
pub dependencies: BTreeMap<String, String>,
}
/// A structured package source in lock v3.
/// A structured package source in lock v4.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum LockedSource {
@@ -1191,7 +1510,7 @@ impl LockedSource {
}
}
/// Root entry of a lock v3 graph.
/// Root entry of a lock v4 graph.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LockedRoot {
/// Logical root package instance (`root:<name>@<version>`).
@@ -1209,6 +1528,32 @@ impl Default for LockedRoot {
}
}
/// One locked extension identity (lock v4).
///
/// Records the exact selected extension source, manifest digest, artifact
/// digest and target so a later `run` can prove it uses the same bytes the
/// project locked. A lock is identity, not authorization: grants remain
/// separate CLI/operator decisions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LockedExtension {
/// Extension category.
pub kind: ExtensionKind,
/// Owner package instance (`root:...` or a dependency instance id).
pub logical_owner: String,
/// Stable declared name (plugin package, kernel provider id, provider name).
pub name: String,
/// Declared extension version.
pub version: String,
/// SHA-256 of the exact manifest file bytes (lowercase hex).
pub manifest_digest: String,
/// SHA-256 of the selected target artifact (lowercase hex).
pub artifact_digest: String,
/// Selected host target triple.
pub selected_target: String,
/// Source string as declared in `marqdo.yaml.extensions`.
pub source: String,
}
/// The `marqdo.lock` package-instance graph.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LockFile {
@@ -1224,6 +1569,9 @@ pub struct LockFile {
/// Root alias -> target package instance.
#[serde(default)]
pub root_dependencies: BTreeMap<String, String>,
/// Locked extension identities, sorted by `(kind, name, logical_owner)`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extensions: Vec<LockedExtension>,
}
impl Default for LockFile {
@@ -1234,6 +1582,7 @@ impl Default for LockFile {
root: LockedRoot::default(),
packages: Vec::new(),
root_dependencies: BTreeMap::new(),
extensions: Vec::new(),
}
}
}
@@ -1261,7 +1610,7 @@ pub fn manifest_digest(manifest: &Manifest) -> String {
}
impl LockFile {
/// Parse and validate a lockfile. Only lock v3 is accepted.
/// Parse and validate a lockfile. Only lock v4 is accepted.
pub fn from_yaml(yaml: &str) -> Result<Self, String> {
#[derive(Deserialize)]
struct VersionProbe {
@@ -1270,8 +1619,13 @@ impl LockFile {
let probe: VersionProbe =
serde_yaml::from_str(yaml).map_err(|error| format!("invalid {LOCK_FILE}: {error}"))?;
if probe.lock_version != LOCK_VERSION {
if probe.lock_version == LOCK_VERSION - 1 {
return Err(format!(
"lock v3 is superseded by lock v4 (extension identities); run `marqdo lock` to migrate explicitly. {LOCK_FILE} was not rewritten"
));
}
return Err(format!(
"unsupported lock_version {}; lock v3 is required. Run `marqdo lock` to regenerate the graph",
"unsupported lock_version {}; lock v{LOCK_VERSION} is required. Run `marqdo lock` to regenerate the graph",
probe.lock_version
));
}
@@ -1279,6 +1633,7 @@ impl LockFile {
serde_yaml::from_str(yaml).map_err(|error| format!("invalid {LOCK_FILE}: {error}"))?;
lock.packages
.sort_by(|a, b| a.instance_id.cmp(&b.instance_id));
lock.sort_extensions();
lock.validate()?;
Ok(lock)
}
@@ -1296,6 +1651,7 @@ impl LockFile {
sorted
.packages
.sort_by(|a, b| a.instance_id.cmp(&b.instance_id));
sorted.sort_extensions();
serde_yaml::to_string(&sorted).unwrap_or_default()
}
@@ -1306,6 +1662,115 @@ impl LockFile {
hex::encode(hasher.finalize())
}
fn sort_extensions(&mut self) {
self.extensions.sort_by(|left, right| {
(&left.kind, &left.name, &left.logical_owner).cmp(&(
&right.kind,
&right.name,
&right.logical_owner,
))
});
}
/// Look up one locked extension identity.
pub fn extension(
&self,
kind: ExtensionKind,
name: &str,
logical_owner: &str,
) -> Option<&LockedExtension> {
self.extensions.iter().find(|extension| {
extension.kind == kind
&& extension.name == name
&& extension.logical_owner == logical_owner
})
}
/// Compare an actual extension selection with the lock (RFC-EXT-0001 §6.4).
///
/// The same complete identity and digests are idempotent; any missing,
/// extra or changed identity is an error. The caller turns this into
/// `ext.extension_lock_mismatch`; this layer returns a descriptive string.
pub fn validate_extension_selection(&self, actual: &[LockedExtension]) -> Result<(), String> {
let mut seen: BTreeSet<(ExtensionKind, String, String)> = BTreeSet::new();
for extension in actual {
let key = (
extension.kind,
extension.name.clone(),
extension.logical_owner.clone(),
);
if !seen.insert(key.clone()) {
return Err(format!(
"extension {} `{}` for owner `{}` is selected more than once",
key.0, key.1, key.2
));
}
match self.extension(key.0, &key.1, &key.2) {
Some(locked) if locked == extension => {}
Some(locked) => {
return Err(format!(
"extension {} `{}` identity mismatch: lock has manifest {} artifact {} target {}, selection has manifest {} artifact {} target {}",
key.0,
key.1,
locked.manifest_digest,
locked.artifact_digest,
locked.selected_target,
extension.manifest_digest,
extension.artifact_digest,
extension.selected_target
))
}
None => {
return Err(format!(
"extension {} `{}` for owner `{}` is not present in {LOCK_FILE}; run `marqdo lock` and pass the selected manifest explicitly",
key.0, key.1, key.2
))
}
}
}
for locked in &self.extensions {
if !seen.contains(&(
locked.kind,
locked.name.clone(),
locked.logical_owner.clone(),
)) {
return Err(format!(
"locked extension {} `{}` for owner `{}` is not selected in this run",
locked.kind, locked.name, locked.logical_owner
));
}
}
Ok(())
}
/// Insert one exact extension identity; identical insertion is idempotent.
pub fn merge_extension(&mut self, extension: LockedExtension) -> Result<(), String> {
match self.extension(
extension.kind,
&extension.name,
&extension.logical_owner,
) {
Some(existing) if existing == &extension => Ok(()),
Some(existing) => Err(format!(
"extension {} `{}` for owner `{}` already has manifest {} artifact {} target {}; refusing to replace it with manifest {} artifact {} target {}",
extension.kind,
extension.name,
extension.logical_owner,
existing.manifest_digest,
existing.artifact_digest,
existing.selected_target,
extension.manifest_digest,
extension.artifact_digest,
extension.selected_target
)),
None => {
self.extensions.push(extension);
self.sort_extensions();
Ok(())
}
}
}
/// Find a locked package by instance id.
pub fn package(&self, instance_id: &str) -> Option<&LockedPackage> {
self.packages
@@ -1442,6 +1907,112 @@ impl LockFile {
));
}
}
let mut extension_keys = BTreeSet::new();
let mut extension_sources = BTreeSet::new();
for extension in &self.extensions {
if !extension_keys.insert((
extension.kind,
extension.name.clone(),
extension.logical_owner.clone(),
)) {
return Err(format!(
"duplicate extension {} `{}` for owner `{}` in {LOCK_FILE}",
extension.kind, extension.name, extension.logical_owner
));
}
if extension.name.trim().is_empty() {
return Err("lock extension name must not be empty".to_string());
}
if extension.version.trim().is_empty() {
return Err(format!(
"extension {} `{}` has an empty version",
extension.kind, extension.name
));
}
if extension.logical_owner.trim().is_empty() {
return Err(format!(
"extension {} `{}` has an empty logical_owner",
extension.kind, extension.name
));
}
if !is_hex_digest(&extension.manifest_digest) {
return Err(format!(
"extension {} `{}` manifest_digest is not a 64-character lowercase hex digest",
extension.kind, extension.name
));
}
if !is_hex_digest(&extension.artifact_digest) {
return Err(format!(
"extension {} `{}` artifact_digest is not a 64-character lowercase hex digest",
extension.kind, extension.name
));
}
if extension.selected_target.trim().is_empty() {
return Err(format!(
"extension {} `{}` has an empty selected_target",
extension.kind, extension.name
));
}
if extension.source.trim().is_empty() {
return Err(format!(
"extension {} `{}` has an empty source",
extension.kind, extension.name
));
}
if !extension_sources.insert((extension.kind, extension.source.clone())) {
return Err(format!(
"extension {} source `{}` is locked more than once",
extension.kind, extension.source
));
}
}
Ok(())
}
/// Validate that locked extensions match the manifest declarations.
///
/// Declaration is activation, not authorization; this only checks identity
/// bookkeeping. A manifest that declares an extension without a lock entry
/// (or vice versa) requires an explicit `marqdo lock`.
pub fn validate_extension_declarations(&self, manifest: &Manifest) -> Result<(), String> {
let declared: Vec<(ExtensionKind, String)> = manifest
.extensions
.as_ref()
.map(|extensions| {
extensions
.iter()
.map(|(kind, source)| (kind, source.from.trim().to_string()))
.collect()
})
.unwrap_or_default();
if declared.is_empty() && !self.extensions.is_empty() {
return Err(format!(
"{LOCK_FILE} records extension(s) but the manifest declares none; run `marqdo lock`"
));
}
for (kind, source) in &declared {
let found = self
.extensions
.iter()
.any(|extension| &extension.kind == kind && &extension.source == source);
if !found {
return Err(format!(
"extension {kind} source `{source}` is declared but not locked; run `marqdo lock`"
));
}
}
for extension in &self.extensions {
if !declared
.iter()
.any(|(kind, source)| kind == &extension.kind && source == &extension.source)
{
return Err(format!(
"locked extension {} source `{}` is not declared by the manifest; run `marqdo lock`",
extension.kind, extension.source
));
}
}
Ok(())
}
@@ -1514,6 +2085,36 @@ capabilities:
assert_eq!(manifest.capabilities.process, Some(false));
}
#[test]
fn project_marqdo_range_is_enforced_against_the_running_core() {
let core = env!("CARGO_PKG_VERSION");
assert!(
Manifest::template("template-project").validate().is_ok(),
"the init template must be runnable by the core that writes it"
);
let accepted =
format!("project:\n name: p\n version: 0.1.0\n marqdo: \">={core},<4.0.0\"\n");
Manifest::from_yaml(&accepted).expect("an explicit opt-in range must be accepted");
let stale = "project:\n name: p\n version: 0.1.0\n marqdo: \">=0.1,<1\"\n";
let error = Manifest::from_yaml(stale).unwrap_err();
assert!(
error.contains("package.marqdo_incompatible"),
"stale range must fail closed: {error}"
);
assert!(
error.contains(core),
"diagnostic must name the core: {error}"
);
let invalid = "project:\n name: p\n version: 0.1.0\n marqdo: \"not a range\"\n";
let error = Manifest::from_yaml(invalid).unwrap_err();
assert!(
error.contains("package.marqdo_range_invalid"),
"invalid range must be rejected: {error}"
);
}
#[test]
fn git_dependency_requires_rev() {
let yaml = "project:\n name: p\n version: 0.1.0\ndependencies:\n x:\n git: https://example/x\n";
@@ -1552,6 +2153,7 @@ capabilities:
dependencies: BTreeMap::new(),
},
],
extensions: Vec::new(),
root_dependencies: BTreeMap::from([
(
"a".to_string(),
@@ -1573,13 +2175,107 @@ capabilities:
}
#[test]
fn v1_and_v2_locks_are_rejected_with_a_relock_hint() {
fn old_locks_are_rejected_with_an_explicit_migration() {
for version in [1, 2] {
let yaml = format!("lock_version: {version}\npackages: []\n");
let error = LockFile::from_yaml(&yaml).unwrap_err();
assert!(error.contains("lock v3 is required"), "{error}");
assert!(error.contains("lock v4 is required"), "{error}");
assert!(error.contains("marqdo lock"), "{error}");
}
// v3 is the immediately previous public format: the error must say the
// migration is explicit, not silently reinterpret the document.
let error = LockFile::from_yaml("lock_version: 3\npackages: []\n").unwrap_err();
assert!(
error.contains("lock v3 is superseded by lock v4"),
"{error}"
);
assert!(error.contains("run `marqdo lock`"), "{error}");
}
#[test]
fn extensions_manifest_sources_are_narrow_and_validated() {
let yaml = "project:\n name: p\n version: 0.1.0\ndependencies:\n q:\n path: ./q\nextensions:\n plugins:\n - from: ./adapter/plugin.yaml\n kernels: []\n providers:\n - from: \"@q/adapter/provider.json\"\n";
let manifest = Manifest::from_yaml(yaml).unwrap();
let extensions = manifest.extensions.as_ref().unwrap();
assert_eq!(extensions.plugins.len(), 1);
assert_eq!(extensions.providers.len(), 1);
let resolved = extensions.plugins[0]
.resolve(&manifest.dependencies)
.unwrap();
assert_eq!(
resolved,
ResolvedExtensionSource::ProjectRelative(PathBuf::from("adapter/plugin.yaml"))
);
for bad in [
"extensions:\n plugins:\n - from: /abs/plugin.yaml\n",
"extensions:\n plugins:\n - from: https://example/plugin.yaml\n",
"extensions:\n plugins:\n - from: ../escape/plugin.yaml\n",
"extensions:\n plugins:\n - from: \"@missing/plugin.yaml\"\n",
"extensions:\n plugins:\n - from: \"@q/../../escape\"\n",
"extensions:\n plugins:\n - from: \"\"\n",
] {
let yaml = format!(
"project:\n name: p\n version: 0.1.0\ndependencies:\n q:\n path: ./q\n{bad}"
);
assert!(
Manifest::from_yaml(&yaml).is_err(),
"extension source must be rejected: {bad}"
);
}
}
fn sample_extension(name: &str, digest: char) -> LockedExtension {
LockedExtension {
kind: ExtensionKind::Plugin,
logical_owner: "root:p@0.1.0".into(),
name: name.into(),
version: "0.1.0".into(),
manifest_digest: digest.to_string().repeat(64),
artifact_digest: "b".repeat(64),
selected_target: "x86_64-unknown-linux-gnu".into(),
source: format!("./adapter/{name}/plugin.yaml"),
}
}
#[test]
fn lock_v4_extension_identity_is_deterministic_and_exact() {
let mut lock = LockFile::default();
lock.root.manifest_digest = "a".repeat(64);
lock.merge_extension(sample_extension("demo.ext", 'a'))
.unwrap();
lock.merge_extension(sample_extension("demo.ext", 'a'))
.unwrap();
assert_eq!(lock.extensions.len(), 1);
assert!(lock
.merge_extension(sample_extension("demo.ext", 'c'))
.is_err());
let second = sample_extension("other.ext", 'd');
lock.merge_extension(second.clone()).unwrap();
assert_eq!(lock.extensions[0].name, "demo.ext");
let yaml = lock.to_yaml();
let parsed = LockFile::from_yaml(&yaml).unwrap();
assert_eq!(parsed, lock);
assert!(parsed
.validate_extension_selection(&[
sample_extension("demo.ext", 'a'),
sample_extension("other.ext", 'd'),
])
.is_ok());
assert!(parsed
.validate_extension_selection(&[sample_extension("demo.ext", 'a')])
.is_err());
assert!(parsed
.validate_extension_selection(&[
sample_extension("demo.ext", 'a'),
sample_extension("other.ext", 'd'),
sample_extension("extra.ext", 'e'),
])
.is_err());
let mut changed = sample_extension("demo.ext", 'a');
changed.artifact_digest = "f".repeat(64);
assert!(parsed
.validate_extension_selection(&[changed, sample_extension("other.ext", 'd')])
.is_err());
}
#[test]
@@ -1599,7 +2295,7 @@ capabilities:
"project:\n name: geometry\n version: 0.1.0\n",
)
.unwrap();
std::fs::write(first.join("index.mq.md"), "## f\n\n*1*\n").unwrap();
std::fs::write(first.join("index.mq.md"), "## @exec f\n\n`return 1`\n").unwrap();
let manifest = Manifest::load(&root.join(MANIFEST_FILE)).unwrap();
let resolver =
PackageResolver::new(root.clone(), Some(manifest.clone()), None).with_unlocked(true);
@@ -1629,6 +2325,14 @@ capabilities:
fn rejects_absolute_dependency_paths() {
let yaml = "project:\n name: p\n version: 0.1.0\ndependencies:\n x:\n path: /tmp/x\n";
assert!(Manifest::from_yaml(yaml).is_err());
#[cfg(windows)]
{
// Rooted but drive-less: `is_absolute()` is false on Windows, yet
// joining it escapes the project root.
let rooted =
"project:\n name: p\n version: 0.1.0\ndependencies:\n x:\n path: \\tmp\\x\n";
assert!(Manifest::from_yaml(rooted).is_err());
}
}
fn have_git() -> bool {
@@ -1668,7 +2372,7 @@ capabilities:
"project:\n name: remote\n version: 0.2.0\n",
)
.unwrap();
std::fs::write(dep.join("index.mq.md"), "## hello\n\n*1*\n").unwrap();
std::fs::write(dep.join("index.mq.md"), "## @exec hello\n\n`return 1`\n").unwrap();
git(&dep, &["init", "-q"]);
git(&dep, &["add", "."]);
git(&dep, &["commit", "-q", "-m", "initial"]);
@@ -1721,7 +2425,7 @@ capabilities:
"project:\n name: geometry\n version: 0.1.0\n",
)
.unwrap();
std::fs::write(dep.join("index.mq.md"), "## area\n\n*1*\n").unwrap();
std::fs::write(dep.join("index.mq.md"), "## @exec area\n\n`return 1`\n").unwrap();
std::fs::write(
root.join(MANIFEST_FILE),
"project:\n name: p\n version: 0.1.0\ndependencies:\n geometry:\n path: ./deps/geometry\n",
@@ -1765,19 +2469,19 @@ capabilities:
"project:\n name: root\n version: 0.1.0\ndependencies:\n a:\n path: ./deps/a\n",
)
.unwrap();
std::fs::write(root.join("index.mq.md"), "## main\n\n*1*\n").unwrap();
std::fs::write(root.join("index.mq.md"), "## @exec main\n\n`return 1`\n").unwrap();
std::fs::write(
a.join(MANIFEST_FILE),
"project:\n name: a\n version: 0.1.0\ndependencies:\n b:\n path: ./b\n",
)
.unwrap();
std::fs::write(a.join("index.mq.md"), "## a\n\n*1*\n").unwrap();
std::fs::write(a.join("index.mq.md"), "## @exec a\n\n`return 1`\n").unwrap();
std::fs::write(
b.join(MANIFEST_FILE),
"project:\n name: b\n version: 0.1.0\n",
)
.unwrap();
std::fs::write(b.join("index.mq.md"), "## b\n\n*2*\n").unwrap();
std::fs::write(b.join("index.mq.md"), "## @exec b\n\n`return 2`\n").unwrap();
let manifest = Manifest::load(&root.join(MANIFEST_FILE)).unwrap();
let resolver = PackageResolver::new(root.clone(), Some(manifest), None).with_unlocked(true);
let graph = resolver.resolve_lock_graph().unwrap();
@@ -1813,7 +2517,7 @@ capabilities:
"project:\n name: geometry\n version: 0.1.0\n",
)
.unwrap();
std::fs::write(dep.join("index.mq.md"), "## area\n\n*1*\n").unwrap();
std::fs::write(dep.join("index.mq.md"), "## @exec area\n\n`return 1`\n").unwrap();
std::fs::write(
root.join(MANIFEST_FILE),
"project:\n name: p\n version: 0.1.0\ndependencies:\n geometry:\n path: ./deps/geometry\n",
@@ -1858,11 +2562,11 @@ capabilities:
"project:\n name: p\n version: 0.1.0\n",
)
.unwrap();
// macOS temp_dir is `/var/folders/...` while canonicalize resolves the
// `/var -> /private/var` symlink; compare canonical forms on both sides.
assert_eq!(
discover_root(&nested).unwrap(),
dir.path()
.canonicalize()
.unwrap_or_else(|_| dir.path().to_path_buf())
discover_root(&nested).unwrap().canonicalize().unwrap(),
dir.path().canonicalize().unwrap()
);
assert!(discover_root(Path::new("/")).is_none());
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "marqdo-provider-worker"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "marqdo-provider-worker"
path = "src/main.rs"
[dependencies]
libloading = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
marqdo-host = { path = "../marqdo-host" }
marqdo-sandbox = { path = "../marqdo-sandbox" }
marqdo-value = { path = "../marqdo-value" }
tempfile = { workspace = true }
+261
View File
@@ -0,0 +1,261 @@
//! Trusted C ABI provider worker (ADR-0038).
//!
//! This helper loads one trusted `c-abi-1` shared library and serves the
//! ADR-0035 framed-JSON resource protocol over stdin/stdout. It is a transport
//! boundary, not a sandbox: the library runs with the worker's privileges.
use std::ffi::{c_char, CString};
use std::io::{Read, Write};
use std::path::PathBuf;
use libloading::Library;
use serde_json::{json, Value as Json};
const ABI_VERSION: u32 = 1;
const MAX_FRAME_BYTES: usize = 1024 * 1024;
const ERROR_MAX: usize = 1024;
type AbiVersionFn = unsafe extern "C" fn() -> u32;
type OpenFn = unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *mut u64) -> i32;
type ReadFn = unsafe extern "C" fn(u64, *mut u8, u32, *mut u32, *mut i32) -> i32;
type WriteFn = unsafe extern "C" fn(u64, *const u8, u32, *mut u32) -> i32;
type CloseFn = unsafe extern "C" fn(u64) -> i32;
type LastErrorFn = unsafe extern "C" fn(*mut c_char, u32) -> i32;
struct Provider {
library: Library,
}
impl Provider {
fn load(path: &PathBuf) -> Result<Self, String> {
let library = unsafe { Library::new(path) }
.map_err(|error| format!("cannot load `{}`: {error}", path.display()))?;
let version: libloading::Symbol<AbiVersionFn> = unsafe {
library
.get(b"marqdo_resource_provider_abi_version\0")
.map_err(|error| format!("missing abi_version: {error}"))?
};
if unsafe { version() } != ABI_VERSION {
return Err(format!("provider ABI is not {ABI_VERSION}"));
}
Ok(Self { library })
}
fn last_error(&self) -> String {
let Ok(symbol) = (unsafe {
self.library
.get::<LastErrorFn>(b"marqdo_resource_last_error\0")
}) else {
return "C provider failed".to_string();
};
let mut buffer = vec![0i8; ERROR_MAX];
if unsafe { symbol(buffer.as_mut_ptr(), ERROR_MAX as u32) } != 0 {
return "C provider failed".to_string();
}
let bytes = buffer
.iter()
.map(|value| *value as u8)
.take_while(|value| *value != 0)
.collect::<Vec<_>>();
String::from_utf8_lossy(&bytes).into_owned()
}
fn open(&self, kind: &str, descriptor: &str, rights: &[String]) -> Result<u64, String> {
let kind = CString::new(kind).map_err(|_| "kind has NUL".to_string())?;
let descriptor = CString::new(descriptor).map_err(|_| "descriptor has NUL".to_string())?;
let rights = CString::new(rights.join(",")).map_err(|_| "rights have NUL".to_string())?;
let symbol: libloading::Symbol<OpenFn> = unsafe {
self.library
.get(b"marqdo_resource_open\0")
.map_err(|error| format!("missing open: {error}"))?
};
let mut token = 0u64;
if unsafe {
symbol(
kind.as_ptr(),
descriptor.as_ptr(),
rights.as_ptr(),
&mut token,
)
} != 0
{
return Err(self.last_error());
}
Ok(token)
}
fn read(&self, token: u64, max_bytes: usize) -> Result<(Vec<u8>, bool), String> {
let capacity = u32::try_from(max_bytes).unwrap_or(u32::MAX);
let mut buffer = vec![0u8; capacity as usize];
let mut read = 0u32;
let mut eof = 0i32;
let symbol: libloading::Symbol<ReadFn> = unsafe {
self.library
.get(b"marqdo_resource_read\0")
.map_err(|error| format!("missing read: {error}"))?
};
if unsafe { symbol(token, buffer.as_mut_ptr(), capacity, &mut read, &mut eof) } != 0 {
return Err(self.last_error());
}
buffer.truncate(read as usize);
Ok((buffer, eof != 0))
}
fn write(&self, token: u64, bytes: &[u8]) -> Result<usize, String> {
let length = u32::try_from(bytes.len()).map_err(|_| "write too large".to_string())?;
let mut written = 0u32;
let symbol: libloading::Symbol<WriteFn> = unsafe {
self.library
.get(b"marqdo_resource_write\0")
.map_err(|error| format!("missing write: {error}"))?
};
if unsafe { symbol(token, bytes.as_ptr(), length, &mut written) } != 0 {
return Err(self.last_error());
}
Ok(written as usize)
}
fn close(&self, token: u64) -> Result<(), String> {
let symbol: libloading::Symbol<CloseFn> = unsafe {
self.library
.get(b"marqdo_resource_close\0")
.map_err(|error| format!("missing close: {error}"))?
};
if unsafe { symbol(token) } != 0 {
return Err(self.last_error());
}
Ok(())
}
}
fn read_frame() -> Result<Option<Json>, String> {
let mut header = [0u8; 4];
let mut read = 0usize;
while read < header.len() {
match std::io::stdin().read(&mut header[read..]) {
Ok(0) if read == 0 => return Ok(None),
Ok(0) => return Err("stdin ended inside a frame header".to_string()),
Ok(count) => read += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(format!("stdin read failed: {error}")),
}
}
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(format!("invalid frame length {length}"));
}
let mut payload = vec![0u8; length];
std::io::stdin()
.read_exact(&mut payload)
.map_err(|error| format!("stdin read failed: {error}"))?;
serde_json::from_slice(&payload)
.map(Some)
.map_err(|error| format!("invalid JSON frame: {error}"))
}
fn write_frame(value: &Json) -> Result<(), String> {
let bytes = serde_json::to_vec(value).map_err(|error| format!("encode failed: {error}"))?;
if bytes.len() > MAX_FRAME_BYTES {
return Err("response frame is too large".to_string());
}
let mut stdout = std::io::stdout();
stdout
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| stdout.write_all(&bytes))
.and_then(|()| stdout.flush())
.map_err(|error| format!("stdout write failed: {error}"))
}
fn fail(message: &str) -> Json {
json!({"ok": false, "code": "host.error", "message": message})
}
fn main() {
let Some(path) = std::env::args_os().nth(1) else {
eprintln!("usage: marqdo-provider-worker <c-abi-library>");
std::process::exit(2);
};
let provider = match Provider::load(&PathBuf::from(path)) {
Ok(provider) => provider,
Err(error) => {
eprintln!("provider worker: {error}");
std::process::exit(2);
}
};
loop {
let request = match read_frame() {
Ok(Some(request)) => request,
Ok(None) => break,
Err(error) => {
eprintln!("provider worker: {error}");
std::process::exit(1);
}
};
let op = request.get("op").and_then(Json::as_str).unwrap_or("");
let response = match op {
"ping" => json!({"ok": true}),
"open" => {
let kind = request.get("kind").and_then(Json::as_str).unwrap_or("");
let descriptor = request
.get("descriptor")
.and_then(Json::as_str)
.unwrap_or("");
let rights = request
.get("rights")
.and_then(Json::as_array)
.map(|values| {
values
.iter()
.filter_map(Json::as_str)
.map(str::to_string)
.collect::<Vec<_>>()
})
.unwrap_or_default();
match provider.open(kind, descriptor, &rights) {
Ok(token) => json!({"ok": true, "token": token}),
Err(error) => fail(&error),
}
}
"read" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
let max_bytes =
request.get("max_bytes").and_then(Json::as_u64).unwrap_or(0) as usize;
match provider.read(token, max_bytes) {
Ok((bytes, eof)) => json!({"ok": true, "bytes": bytes, "eof": eof}),
Err(error) => fail(&error),
}
}
"write" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
let bytes = request
.get("bytes")
.and_then(Json::as_array)
.map(|values| {
values
.iter()
.filter_map(Json::as_u64)
.filter_map(|value| u8::try_from(value).ok())
.collect::<Vec<_>>()
})
.unwrap_or_default();
match provider.write(token, &bytes) {
Ok(count) => json!({"ok": true, "count": count}),
Err(error) => fail(&error),
}
}
"close" => {
let token = request.get("token").and_then(Json::as_u64).unwrap_or(0);
match provider.close(token) {
Ok(()) => json!({"ok": true}),
Err(error) => fail(&error),
}
}
"shutdown" => break,
_ => fail("unsupported worker operation"),
};
if let Err(error) = write_frame(&response) {
eprintln!("provider worker: {error}");
std::process::exit(1);
}
}
}
@@ -0,0 +1,136 @@
#![cfg(unix)]
use std::path::Path;
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: Value) -> marqdo_value::ResourceHandle {
match value {
Value::Resource(handle) => handle,
other => panic!("expected resource, got {other:?}"),
}
}
fn cc_available() -> bool {
Command::new("cc")
.arg("--version")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
fn build_provider(dir: &Path) -> std::path::PathBuf {
let source = dir.join("provider.c");
std::fs::write(
&source,
r#"
#include <stdint.h>
#include <stddef.h>
#include <string.h>
static const char DATA[] = "worker-abi";
static size_t position = 0;
uint32_t marqdo_resource_provider_abi_version(void) { return 1u; }
int32_t marqdo_resource_open(const char *kind, const char *descriptor,
const char *rights_csv, uint64_t *out_token) {
(void)kind; (void)descriptor; (void)rights_csv;
position = 0; *out_token = 42; return 0;
}
int32_t marqdo_resource_read(uint64_t token, uint8_t *buffer,
uint32_t capacity, uint32_t *out_read,
int32_t *out_eof) {
(void)token;
size_t remaining = sizeof(DATA) - 1 - position;
size_t count = remaining < capacity ? remaining : capacity;
memcpy(buffer, DATA + position, count);
position += count;
*out_read = (uint32_t)count;
*out_eof = position >= sizeof(DATA) - 1 ? 1 : 0;
return 0;
}
int32_t marqdo_resource_write(uint64_t token, const uint8_t *bytes,
uint32_t length, uint32_t *out_written) {
(void)token; (void)bytes; *out_written = length; return 0;
}
int32_t marqdo_resource_close(uint64_t token) { (void)token; return 0; }
int32_t marqdo_resource_last_error(char *buffer, uint32_t capacity) {
(void)capacity; buffer[0] = 0; return 0;
}
"#,
)
.unwrap();
let extension = if cfg!(target_os = "macos") {
"dylib"
} else {
"so"
};
let library = dir.join(format!("libworker_provider.{extension}"));
let status = Command::new("cc")
.args(["-shared", "-fPIC", "-O2", "-o"])
.arg(&library)
.arg(&source)
.status()
.expect("run cc");
assert!(status.success());
library
}
#[test]
fn c_abi_provider_runs_inside_the_worker_helper() {
if !cc_available() {
eprintln!("skipping worker binding test: cc is unavailable");
return;
}
let dir = tempfile::tempdir().unwrap();
let library = build_provider(dir.path());
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker-cabi"),
project.path(),
);
host.register_worker_resource_provider(
"worker-cabi",
&["worker.sensor"],
&std::path::PathBuf::from(env!("CARGO_BIN_EXE_marqdo-provider-worker")),
&[library.to_string_lossy().to_string()],
)
.unwrap();
let ctx = context();
let handle = handle(
host.resource_open("worker.sensor", "s", &["read".to_string()], &ctx)
.unwrap(),
);
let first = host.resource_read(handle, 6, &ctx).unwrap();
assert_eq!(first.bytes, b"worker");
let rest = host.resource_read(handle, 64, &ctx).unwrap();
assert_eq!(rest.bytes, b"-abi");
assert!(rest.eof);
assert_eq!(host.resource_write(handle, b"x", &ctx).unwrap(), 1);
host.resource_close(handle, &ctx).unwrap();
}
#[test]
fn worker_helper_without_c_provider_fails_closed() {
let project = tempfile::tempdir().unwrap();
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_resource_provider("worker-cabi"),
project.path(),
);
let error = host
.register_worker_resource_provider(
"worker-cabi",
&["worker.sensor"],
&std::path::PathBuf::from(env!("CARGO_BIN_EXE_marqdo-provider-worker")),
&["/definitely/missing/provider.so".to_string()],
)
.unwrap_err();
assert_eq!(error.category, ErrorCategory::HostError);
}
+535 -7
View File
@@ -6,13 +6,13 @@
use std::collections::BTreeMap;
use marqdo_host::HostOp;
use marqdo_host::{HostOp, ResourceRead};
use marqdo_ir::builtins::Builtin;
use marqdo_ir::Resource;
use marqdo_span::Span;
use marqdo_value::{
float_to_bigint, CodeValue, ErrorCategory, FormulaValue, FunctionRef, RuntimeError, Table,
Value,
float_to_bigint, CodeValue, ErrorCategory, FormulaValue, FunctionRef, ResourceHandle,
RuntimeError, Table, Value,
};
use crate::interpreter::Interpreter;
@@ -27,10 +27,15 @@ pub(crate) fn dispatch(
let module = frame.module().clone();
match builtin.name {
"打印" => {
let value = take(&bound, "值", builtin, span)?;
interpreter
.host_invoke(HostOp::Print, vec![value], span, &module)
.map(|_| Value::Unit)
// Compat-C (ADR-0031): the legacy HostOp::Print path is gone. On
// the official CLI the loader routes 打印/print to stdlib io.写值;
// reaching this builtin means the verified bundle was unavailable.
let _ = take(&bound, "值", builtin, span)?;
Err(RuntimeError::new(
ErrorCategory::KernelUnavailable,
span,
"打印 requires the bundled stdlib print module; install the official CLI bundle",
))
}
"长度" => {
let value = take(&bound, "值", builtin, span)?;
@@ -187,6 +192,307 @@ pub(crate) fn dispatch(
&module,
)
}
"memory.new" => {
let initial_pages = page_count(take(&bound, "initial_pages", builtin, span)?, span)?;
let max_pages = page_count(take(&bound, "max_pages", builtin, span)?, span)?;
let handle = interpreter
.memory_mut()
.create(initial_pages, max_pages, span)?;
interpreter.record_memory_event(
"memory.new",
&module,
span,
&format!("initial_pages={initial_pages} max_pages={max_pages}"),
);
Ok(Value::Memory(handle))
}
"memory.size" => {
let memory = take(&bound, "memory", builtin, span)?;
let memory_type = memory.type_name();
let Value::Memory(handle) = memory else {
return Err(RuntimeError::type_error(
span,
format!("memory.size expects a Memory value, got {memory_type}"),
));
};
let pages = interpreter.memory().size(handle, span)?;
Ok(pages_value(pages, span)?)
}
"memory.grow" => {
let memory = take(&bound, "memory", builtin, span)?;
let memory_type = memory.type_name();
let Value::Memory(handle) = memory else {
return Err(RuntimeError::type_error(
span,
format!("memory.grow expects a Memory value, got {memory_type}"),
));
};
let pages = page_count(take(&bound, "pages", builtin, span)?, span)?;
let old_pages = interpreter.memory_mut().grow(handle, pages, span)?;
interpreter.record_memory_event(
"memory.grow",
&module,
span,
&format!("pages={pages} old_pages={old_pages}"),
);
Ok(pages_value(old_pages, span)?)
}
"list.append" => {
let list = take(&bound, "list", builtin, span)?;
let value = take(&bound, "value", builtin, span)?;
let list_type = list.type_name();
let Value::List(mut items) = list else {
return Err(RuntimeError::type_error(
span,
format!("list.append expects a List, got {list_type}"),
));
};
items.push(value);
Ok(Value::List(items))
}
"list.concat" => {
let left = take(&bound, "left", builtin, span)?;
let right = take(&bound, "right", builtin, span)?;
let left_type = left.type_name();
let Value::List(mut items) = left else {
return Err(RuntimeError::type_error(
span,
format!("list.concat left operand must be a List, got {left_type}"),
));
};
let right_type = right.type_name();
let Value::List(other) = right else {
return Err(RuntimeError::type_error(
span,
format!("list.concat right operand must be a List, got {right_type}"),
));
};
items.extend(other);
Ok(Value::List(items))
}
"map.keys" => {
let value = take(&bound, "map", builtin, span)?;
let value_type = value.type_name();
let Value::Map(map) = value else {
return Err(RuntimeError::type_error(
span,
format!("map.keys expects a Map, got {value_type}"),
));
};
Ok(Value::List(
map.keys().cloned().map(Value::Text).collect::<Vec<_>>(),
))
}
"map.has" => {
let value = take(&bound, "map", builtin, span)?;
let key = map_key(take(&bound, "key", builtin, span)?, "map.has", span)?;
let value_type = value.type_name();
let Value::Map(map) = value else {
return Err(RuntimeError::type_error(
span,
format!("map.has expects a Map, got {value_type}"),
));
};
Ok(Value::Bool(map.contains_key(&key)))
}
"map.get" => {
let value = take(&bound, "map", builtin, span)?;
let key = map_key(take(&bound, "key", builtin, span)?, "map.get", span)?;
let value_type = value.type_name();
let Value::Map(map) = value else {
return Err(RuntimeError::type_error(
span,
format!("map.get expects a Map, got {value_type}"),
));
};
Ok(map.get(&key).cloned().unwrap_or(Value::None))
}
"map.set" => {
let value = take(&bound, "map", builtin, span)?;
let key = map_key(take(&bound, "key", builtin, span)?, "map.set", span)?;
let new_value = take(&bound, "value", builtin, span)?;
let value_type = value.type_name();
let Value::Map(mut map) = value else {
return Err(RuntimeError::type_error(
span,
format!("map.set expects a Map, got {value_type}"),
));
};
map.insert(key, new_value);
Ok(Value::Map(map))
}
"map.remove" => {
let value = take(&bound, "map", builtin, span)?;
let key = map_key(take(&bound, "key", builtin, span)?, "map.remove", span)?;
let value_type = value.type_name();
let Value::Map(mut map) = value else {
return Err(RuntimeError::type_error(
span,
format!("map.remove expects a Map, got {value_type}"),
));
};
map.remove(&key);
Ok(Value::Map(map))
}
"text.codepoints" => {
let value = take(&bound, "text", builtin, span)?;
let value_type = value.type_name();
let Value::Text(text) = value else {
return Err(RuntimeError::type_error(
span,
format!("text.codepoints expects Text, got {value_type}"),
));
};
Ok(Value::List(
text.chars()
.map(|character| Value::int(i64::from(character as u32)))
.collect(),
))
}
"text.from_codepoint" => {
let value = take(&bound, "codepoint", builtin, span)?;
let value_type = value.type_name();
let Value::Int(codepoint) = value else {
return Err(RuntimeError::type_error(
span,
format!("text.from_codepoint expects an Int, got {value_type}"),
));
};
let Some(codepoint) = num_traits::ToPrimitive::to_u32(&codepoint) else {
return Ok(Value::None);
};
Ok(match char::from_u32(codepoint) {
Some(character) => Value::Text(character.to_string()),
None => Value::None,
})
}
"table.columns" => {
let value = take(&bound, "table", builtin, span)?;
let value_type = value.type_name();
let Value::Table(table) = value else {
return Err(RuntimeError::type_error(
span,
format!("table.columns expects a Table, got {value_type}"),
));
};
Ok(Value::List(
table.header.into_iter().map(Value::Text).collect(),
))
}
"table.row" => {
let value = take(&bound, "table", builtin, span)?;
let row = take(&bound, "row", builtin, span)?;
let value_type = value.type_name();
let Value::Table(table) = value else {
return Err(RuntimeError::type_error(
span,
format!("table.row expects a Table, got {value_type}"),
));
};
let position = table_index(row, table.rows.len(), "row", span)?;
Ok(Value::List(table.rows[position].clone()))
}
"table.cell" => {
let value = take(&bound, "table", builtin, span)?;
let row = take(&bound, "row", builtin, span)?;
let column = take(&bound, "column", builtin, span)?;
let value_type = value.type_name();
let Value::Table(table) = value else {
return Err(RuntimeError::type_error(
span,
format!("table.cell expects a Table, got {value_type}"),
));
};
let row = table_index(row, table.rows.len(), "row", span)?;
let column = table_index(column, table.header.len(), "column", span)?;
Ok(table.rows[row][column].clone())
}
"resource.open" => {
let kind = expect_text_value(take(&bound, "kind", builtin, span)?, span)?;
let descriptor = expect_text_value(take(&bound, "descriptor", builtin, span)?, span)?;
let rights = rights_list(take(&bound, "rights", builtin, span)?, span)?;
interpreter.resource_open(&kind, &descriptor, &rights, &module, span)
}
"resource.read" => {
let handle = resource_handle(take(&bound, "handle", builtin, span)?, span)?;
let memory = memory_handle(
take(&bound, "memory", builtin, span)?,
"resource.read",
span,
)?;
let offset = take(&bound, "offset", builtin, span)?;
let offset_int = int_value(offset, "resource.read offset", span)?;
let offset_value = Value::Int(offset_int.clone());
let max_bytes = positive_count(
take(&bound, "max_bytes", builtin, span)?,
"resource.read max_bytes",
span,
)?;
let available = interpreter.memory().byte_len(memory, span)?;
let start = non_negative_usize(&offset_value, "resource.read offset", span)?;
if start >= available {
return Err(RuntimeError::new(
ErrorCategory::IndexOutOfBounds,
span,
format!("resource.read offset {start} is at or beyond the Memory length {available}"),
));
}
let limit = max_bytes.min(available - start);
let result = interpreter.resource_read(handle, limit, &module, span);
match result {
Ok(read) => {
interpreter
.memory_mut()
.write_bytes(memory, &offset_int, &read.bytes, span)?;
Ok(resource_ok(resource_read_payload(&read)))
}
Err(error) => resource_recoverable(error),
}
}
"resource.write" => {
let handle = resource_handle(take(&bound, "handle", builtin, span)?, span)?;
let memory = memory_handle(
take(&bound, "memory", builtin, span)?,
"resource.write",
span,
)?;
let offset = take(&bound, "offset", builtin, span)?;
let offset_int = int_value(offset, "resource.write offset", span)?;
let length = non_negative_usize(
&take(&bound, "length", builtin, span)?,
"resource.write length",
span,
)?;
let bytes = interpreter
.memory()
.read_bytes(memory, &offset_int, length, span)?;
match interpreter.resource_write(handle, &bytes, &module, span) {
Ok(count) => Ok(resource_ok(resource_write_payload(count))),
Err(error) => resource_recoverable(error),
}
}
"resource.close" => {
let handle = resource_handle(take(&bound, "handle", builtin, span)?, span)?;
match interpreter.resource_close(handle, &module, span) {
Ok(()) => Ok(resource_ok(Value::None)),
Err(error) => resource_recoverable(error),
}
}
"resource.accept" => {
let handle = resource_handle(take(&bound, "handle", builtin, span)?, span)?;
interpreter.resource_accept(handle, &module, span)
}
"resource.request" => {
let operation = expect_text_value(take(&bound, "operation", builtin, span)?, span)?;
let value_type = bound["arguments"].type_name();
let Value::List(arguments) = take(&bound, "arguments", builtin, span)? else {
return Err(RuntimeError::type_error(
span,
format!("resource.request arguments must be a List, got {value_type}"),
));
};
interpreter.resource_request(&operation, arguments, &module, span)
}
other => Err(RuntimeError::new(
ErrorCategory::KernelUnavailable,
span,
@@ -210,6 +516,228 @@ fn take(
})
}
/// Validate a page-count argument: an `Int` in the non-negative `u64` range.
fn page_count(value: Value, span: Option<Span>) -> Result<u64, RuntimeError> {
let value_type = value.type_name();
let Value::Int(count) = value else {
return Err(RuntimeError::type_error(
span,
format!("memory page count must be an Int, got {value_type}"),
));
};
num_traits::ToPrimitive::to_u64(&count).ok_or_else(|| {
RuntimeError::new(
ErrorCategory::MemoryFault,
span,
format!("memory page count {count} must be a non-negative integer"),
)
})
}
/// Convert a page count back to a language `Int`.
fn pages_value(pages: u64, span: Option<Span>) -> Result<Value, RuntimeError> {
i64::try_from(pages).map(Value::int).map_err(|_| {
RuntimeError::new(
ErrorCategory::MemoryFault,
span,
format!("page count {pages} does not fit an Int"),
)
})
}
/// Require a `Text` map key and return it.
fn map_key(value: Value, builtin: &str, span: Option<Span>) -> Result<String, RuntimeError> {
let value_type = value.type_name();
match value {
Value::Text(key) => Ok(key),
_ => Err(RuntimeError::type_error(
span,
format!("{builtin} key must be Text, got {value_type}"),
)),
}
}
/// Require a Text value.
fn expect_text_value(value: Value, span: Option<Span>) -> Result<String, RuntimeError> {
let value_type = value.type_name();
let Value::Text(text) = value else {
return Err(RuntimeError::type_error(
span,
format!("expected Text, got {value_type}"),
));
};
Ok(text)
}
/// Require a List of Text rights.
fn rights_list(value: Value, span: Option<Span>) -> Result<Vec<String>, RuntimeError> {
let value_type = value.type_name();
let Value::List(items) = value else {
return Err(RuntimeError::type_error(
span,
format!("resource rights must be a List, got {value_type}"),
));
};
let mut rights = Vec::with_capacity(items.len());
for item in items {
let item_type = item.type_name();
let Value::Text(right) = item else {
return Err(RuntimeError::type_error(
span,
format!("resource rights must contain Text, got {item_type}"),
));
};
rights.push(right);
}
Ok(rights)
}
/// Require an opaque resource handle.
fn resource_handle(value: Value, span: Option<Span>) -> Result<ResourceHandle, RuntimeError> {
let value_type = value.type_name();
let Value::Resource(handle) = value else {
return Err(RuntimeError::type_error(
span,
format!("expected a Resource handle, got {value_type}"),
));
};
Ok(handle)
}
/// Require an opaque Memory handle.
fn memory_handle(
value: Value,
builtin: &str,
span: Option<Span>,
) -> Result<marqdo_value::MemoryHandle, RuntimeError> {
let value_type = value.type_name();
let Value::Memory(handle) = value else {
return Err(RuntimeError::type_error(
span,
format!("{builtin} memory must be a Memory value, got {value_type}"),
));
};
Ok(handle)
}
/// Require an Int value.
fn int_value(
value: Value,
what: &str,
span: Option<Span>,
) -> Result<num_bigint::BigInt, RuntimeError> {
let value_type = value.type_name();
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
span,
format!("{what} must be an Int, got {value_type}"),
));
};
Ok(value)
}
/// Require a non-negative usize.
fn non_negative_usize(
value: &Value,
what: &str,
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let value_type = value.type_name();
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
span,
format!("{what} must be an Int, got {value_type}"),
));
};
num_traits::ToPrimitive::to_usize(value).ok_or_else(|| {
RuntimeError::new(
ErrorCategory::IndexOutOfBounds,
span,
format!("{what} {value} must be a non-negative integer in range"),
)
})
}
/// Require a strictly positive byte count.
fn positive_count(value: Value, what: &str, span: Option<Span>) -> Result<usize, RuntimeError> {
let count = non_negative_usize(&value, what, span)?;
if count == 0 {
return Err(RuntimeError::type_error(
span,
format!("{what} must be greater than zero"),
));
}
Ok(count)
}
fn resource_ok(value: Value) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), value);
Value::Map(map)
}
fn resource_err(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::Text(code.to_string()));
map.insert("message".to_string(), Value::Text(message.to_string()));
Value::Map(map)
}
fn resource_read_payload(read: &ResourceRead) -> Value {
let mut map = BTreeMap::new();
map.insert("count".to_string(), Value::int(read.bytes.len() as i64));
map.insert("eof".to_string(), Value::Bool(read.eof));
Value::Map(map)
}
fn resource_write_payload(count: usize) -> Value {
let mut map = BTreeMap::new();
map.insert("count".to_string(), Value::int(count as i64));
Value::Map(map)
}
/// Convert a closed-handle failure into a recoverable Result; other errors are
/// fatal (ADR-0025).
fn resource_recoverable(error: RuntimeError) -> Result<Value, RuntimeError> {
if error.category == ErrorCategory::ResourceClosed {
return Ok(resource_err("resource.closed", &error.message));
}
Err(error)
}
/// Validate a non-negative table row/column coordinate.
fn table_index(
value: Value,
len: usize,
what: &str,
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let value_type = value.type_name();
let Value::Int(index) = value else {
return Err(RuntimeError::type_error(
span,
format!("table {what} must be an Int, got {value_type}"),
));
};
let Some(position) = num_traits::ToPrimitive::to_usize(&index) else {
return Err(RuntimeError::new(
ErrorCategory::IndexOutOfBounds,
span,
format!("table {what} {index} is out of bounds for length {len}"),
));
};
if position >= len {
return Err(RuntimeError::new(
ErrorCategory::IndexOutOfBounds,
span,
format!("table {what} {position} is out of bounds for length {len}"),
));
}
Ok(position)
}
fn formula_text(value: Value, span: Option<Span>) -> Result<String, RuntimeError> {
match value {
Value::Formula(formula) => Ok(formula.latex),
+333 -143
View File
@@ -3,12 +3,13 @@
use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{ExecutionContext, Host, HostOp};
use marqdo_ir::{builtins, CallTarget, Function, FunctionId, ModuleId, Program, Stmt};
use marqdo_host::{ExecutionContext, Host, HostOp, ResourceRead};
use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value};
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use crate::builtins_impl::FrameView;
use crate::memory::{MemoryLimits, MemoryStore};
use crate::value_ops;
@@ -53,7 +54,6 @@ pub struct RunOutcome {
/// Execution frame for one function call.
struct Frame {
function: FunctionId,
namespace: Option<String>,
locals: BTreeMap<String, Value>,
}
@@ -68,6 +68,7 @@ pub struct Interpreter<'a> {
program: &'a Program,
host: &'a mut dyn Host,
depth: usize,
memory: MemoryStore,
}
/// Run a named function with already-evaluated arguments.
@@ -77,11 +78,31 @@ pub fn run(
module: &ModuleId,
function: &str,
args: Vec<EvaluatedArg>,
) -> Result<RunOutcome, RuntimeError> {
run_with_limits(
program,
host,
module,
function,
args,
MemoryLimits::default(),
)
}
/// Run with explicit addressable-memory limits (ADR-0022).
pub fn run_with_limits(
program: &Program,
host: &mut dyn Host,
module: &ModuleId,
function: &str,
args: Vec<EvaluatedArg>,
limits: MemoryLimits,
) -> Result<RunOutcome, RuntimeError> {
let mut interpreter = Interpreter {
program,
host,
depth: 0,
memory: MemoryStore::new(limits),
};
let value = interpreter.call_by_name(module, function, args, None)?;
Ok(RunOutcome { value })
@@ -157,7 +178,6 @@ impl<'a> Interpreter<'a> {
};
let mut frame = Frame {
function: function.id.clone(),
namespace: function.namespace.clone(),
locals,
};
self.depth += 1;
@@ -255,7 +275,6 @@ impl<'a> Interpreter<'a> {
// an empty frame so they cannot reach caller state.
let mut empty = Frame {
function: function.id.clone(),
namespace: function.namespace.clone(),
locals: BTreeMap::new(),
};
let value = self.eval_expr(default, &mut empty)?;
@@ -300,16 +319,28 @@ impl<'a> Interpreter<'a> {
self.host.consume_fuel(1, Some(stmt.span()))?;
self.host.check_deadline(Some(stmt.span()))?;
match stmt {
Stmt::Assign { name, value, .. } => {
let value = self.eval_expr(value, frame)?;
frame.locals.insert(name.clone(), value);
}
Stmt::Assign { target, value, .. } => match target {
PlaceTarget::Local { name, .. } => {
let value = self.eval_expr(value, frame)?;
frame.locals.insert(name.clone(), value);
}
PlaceTarget::Index { base, index, span } => {
// Frozen order (ADR-0022): base, index, then RHS.
let base_value = self.eval_expr(base, frame)?;
let index_value = self.eval_expr(index, frame)?;
let byte_value = self.eval_expr(value, frame)?;
self.assign_memory_index(
base_value,
index_value,
byte_value,
Some(*span),
frame,
)?;
}
},
Stmt::Eval { expr, .. } => {
self.eval_expr(expr, frame)?;
}
Stmt::Call { call, span } => {
self.exec_call_site(program, call, *span, frame)?;
}
Stmt::Return { value, span } => {
let value = self.eval_expr(value, frame)?;
let module = frame.function.module.canonical();
@@ -387,34 +418,60 @@ impl<'a> Interpreter<'a> {
Ok(Flow::Next)
}
fn exec_call_site(
/// Commit one byte into an addressable region after all operand checks.
///
/// The three operands are already evaluated, so a rejected value never
/// produces a partial write (ADR-0022 §3).
fn assign_memory_index(
&mut self,
program: &'a Program,
call: &'a marqdo_ir::CallSite,
span: Span,
frame: &mut Frame,
) -> Result<Value, RuntimeError> {
let args = self.eval_args(&call.args, frame)?;
let (module, name) = match &call.target {
CallTarget::Function { name } => (frame.function.module.clone(), name.clone()),
CallTarget::Qualified {
module_alias,
function,
} => {
let Some(target) = program.resolve_import(&frame.function.module, module_alias)
else {
return Err(RuntimeError::new(
ErrorCategory::UnknownSymbol,
Some(span),
format!("unknown imported module alias `{module_alias}`"),
));
};
(target.clone(), function.clone())
}
CallTarget::Resolved { module, function } => (module.clone(), function.clone()),
base: Value,
index: Value,
byte: Value,
span: Option<Span>,
frame: &Frame,
) -> Result<(), RuntimeError> {
let base_type = base.type_name();
let Value::Memory(handle) = base else {
return Err(RuntimeError::new(
ErrorCategory::Type,
span,
format!(
"index assignment requires a Memory base in v1, got {base_type}; List, Map \
and Table values keep their existing value semantics"
),
));
};
let caller = frame.function.module.clone();
self.call_by_name_from(&module, &name, args, Some(span), Some(&caller))
let index_type = index.type_name();
let Value::Int(offset) = index else {
return Err(RuntimeError::type_error(
span,
format!("Memory index must be an Int, got {index_type}"),
));
};
let byte_type = byte.type_name();
let byte_repr = byte.display();
let Value::Int(byte) = byte else {
return Err(RuntimeError::type_error(
span,
format!("Memory byte value must be an Int in 0..255, got {byte_type}"),
));
};
let Some(byte) = num_traits::ToPrimitive::to_u8(&byte) else {
return Err(RuntimeError::type_error(
span,
format!("Memory byte value {byte_repr} is outside 0..255"),
));
};
self.memory.write(handle, &offset, byte, span)?;
let module = frame.function.module.canonical();
self.host.record_semantic(
"memory.write",
Some(&frame.function.to_string()),
Some(&module),
span,
Some("byte"),
);
Ok(())
}
fn eval_args(
@@ -528,7 +585,22 @@ impl<'a> Interpreter<'a> {
Expr::Index { base, index, span } => {
let base_value = self.eval_expr(base, frame)?;
let index_value = self.eval_expr(index, frame)?;
index_value_of(base_value, index_value, Some(*span))
match base_value {
Value::Memory(handle) => {
let Value::Int(offset) = index_value else {
return Err(RuntimeError::type_error(
Some(*span),
format!(
"Memory index must be an Int, got {}",
index_value.type_name()
),
));
};
let byte = self.memory.read(handle, &offset, Some(*span))?;
Ok(Value::int(i64::from(byte)))
}
other => index_value_of(other, index_value, Some(*span)),
}
}
}
}
@@ -541,94 +613,96 @@ impl<'a> Interpreter<'a> {
span: Span,
frame: &mut Frame,
) -> Result<Value, RuntimeError> {
let caller_module = frame.function.module.clone();
match callee {
Expr::Ident(ident) => {
if let Some(value) = frame.locals.get(&ident.name).cloned() {
let args = self.eval_args(args, frame)?;
return self.call_value(program, value, args, Some(span), Some(&caller_module));
}
if let Some(builtin) = builtins::find(&ident.name) {
let args = self.eval_args(args, frame)?;
return self.call_builtin(builtin, args, Some(span), frame);
}
let args = self.eval_args(args, frame)?;
let (module, namespace) = (frame.function.module.clone(), frame.namespace.clone());
let Some(function) =
resolve_function(program, &module, namespace.as_deref(), &ident.name)
else {
// ADR-0054 / RFC-EXT-0001 §4: the frontend resolved this call site
// exactly once. Dispatch by the recorded identity; never re-resolve a
// name, never infer a plugin from a dotted prefix.
let key = marqdo_ir::call_binding::CallSiteKey::new(frame.function.clone(), span);
let Some(target) = program.call_bindings.get(&key).cloned() else {
return Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
format!(
"call site `{key}` has no static binding; run a prepared program (ADR-0054)"
),
));
};
match target {
marqdo_ir::call_binding::BoundTarget::Builtin { canonical_name } => {
let Some(builtin) = builtins::find(&canonical_name) else {
return Err(RuntimeError::new(
ErrorCategory::UnknownSymbol,
ErrorCategory::Internal,
Some(span),
format!("unknown function `{}`", ident.name),
format!("bound builtin `{canonical_name}` is not registered"),
));
};
self.call_function(program, function, args, Some(span), Some(&caller_module))
let args = self.eval_args(args, frame)?;
self.call_builtin(builtin, args, Some(span), frame)
}
Expr::Member { base, name, .. } => {
if let Expr::Ident(alias) = base.as_ref() {
if let Some(target_module) =
program.resolve_import(&frame.function.module, &alias.name)
{
let args = self.eval_args(args, frame)?;
let Some(function) = resolve_function(program, target_module, None, name)
else {
return Err(RuntimeError::new(
ErrorCategory::UnknownSymbol,
Some(span),
format!("unknown function `{name}` in module `{target_module}`"),
));
};
return self.call_function(
program,
function,
args,
Some(span),
Some(&caller_module),
);
}
let qualified = format!("{}.{name}", alias.name);
if let Some(builtin) = builtins::find(&qualified) {
let args = self.eval_args(args, frame)?;
return self.call_builtin(builtin, args, Some(span), frame);
}
if !frame.locals.contains_key(&alias.name) {
// A declared external descriptor is the only static
// source of plugin exports. Calls without a descriptor
// are still accepted for compatibility only when no
// plugin descriptors exist at all; this fallback is
// removed once the CLI always supplies descriptors.
let qualified = format!("{}.{}", alias.name, name);
let declared = program.external_callable(&qualified).is_some();
if !declared && !program.external_callables.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::UnknownSymbol,
Some(span),
format!("unknown plugin export `{qualified}`"),
));
}
// Plugin calls take named arguments only in this build.
let evaluated = self.eval_args(args, frame)?;
let mut named = std::collections::BTreeMap::new();
for argument in evaluated {
let Some(argument_name) = argument.name else {
marqdo_ir::call_binding::BoundTarget::Marqdo { function } => {
let Some(target_function) = program.function(&function) else {
return Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
format!("bound function `{function}` does not exist"),
));
};
let args = self.eval_args(args, frame)?;
self.call_function(
program,
target_function,
args,
Some(span),
Some(&frame.function.module.clone()),
)
}
marqdo_ir::call_binding::BoundTarget::AbiPlugin {
package: _,
export,
digest: _,
param_names,
} => {
// ABI v1 transports named arguments as a map. Normalise
// positional arguments deterministically against the static
// manifest order; static validation already rejected unknown,
// duplicate or missing arguments.
let evaluated = self.eval_args(args, frame)?;
let mut named = std::collections::BTreeMap::new();
let mut position = 0usize;
for argument in evaluated {
let name = match argument.name {
Some(name) => name,
None => {
let Some(name) = param_names.get(position).cloned() else {
return Err(RuntimeError::new(
ErrorCategory::Type,
Some(argument.span),
"plugin calls require named arguments",
ErrorCategory::Internal,
Some(span),
format!(
"positional argument {} was not normalised for `{export}`",
position + 1
),
));
};
named.insert(argument_name, argument.value);
position += 1;
name
}
let module = frame.function.module.clone();
return self.host_invoke(
HostOp::PluginInvoke,
vec![Value::Text(qualified), Value::Map(named)],
};
if named.insert(name.clone(), argument.value).is_some() {
return Err(RuntimeError::new(
ErrorCategory::Arity,
Some(span),
&module,
);
format!("duplicate argument `{name}` for `{export}`"),
));
}
}
let module = frame.function.module.clone();
self.host_invoke(
HostOp::PluginInvoke,
vec![Value::Text(export), Value::Map(named)],
Some(span),
&module,
)
}
marqdo_ir::call_binding::BoundTarget::DynamicValue => {
let callee_value = self.eval_expr(callee, frame)?;
let args = self.eval_args(args, frame)?;
self.call_value(
@@ -636,18 +710,7 @@ impl<'a> Interpreter<'a> {
callee_value,
args,
Some(span),
Some(&caller_module),
)
}
other => {
let callee_value = self.eval_expr(other, frame)?;
let args = self.eval_args(args, frame)?;
self.call_value(
program,
callee_value,
args,
Some(span),
Some(&caller_module),
Some(&frame.function.module.clone()),
)
}
}
@@ -701,6 +764,130 @@ impl<'a> Interpreter<'a> {
self.program
}
/// Addressable-memory store for builtins and place writes.
pub(crate) fn memory(&self) -> &MemoryStore {
&self.memory
}
/// Mutable addressable-memory store for `memory.new`/`memory.grow`.
pub(crate) fn memory_mut(&mut self) -> &mut MemoryStore {
&mut self.memory
}
/// Record a semantic event for a builtin that is not a host operation.
pub(crate) fn record_memory_event(
&mut self,
kind: &str,
module: &ModuleId,
span: Option<Span>,
detail: &str,
) {
let module = module.canonical();
self.host
.record_semantic(kind, None, Some(&module), span, Some(detail));
}
/// Open a resource/stream through the host boundary.
pub(crate) fn resource_open(
&mut self,
kind: &str,
descriptor: &str,
rights: &[String],
module: &ModuleId,
span: Option<Span>,
) -> Result<Value, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_open(kind, descriptor, rights, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Read from a resource stream.
pub(crate) fn resource_read(
&mut self,
handle: ResourceHandle,
max_bytes: usize,
module: &ModuleId,
span: Option<Span>,
) -> Result<ResourceRead, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_read(handle, max_bytes, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Write bytes to a resource stream.
pub(crate) fn resource_write(
&mut self,
handle: ResourceHandle,
bytes: &[u8],
module: &ModuleId,
span: Option<Span>,
) -> Result<usize, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_write(handle, bytes, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Accept one inbound TCP connection from a listener handle.
pub(crate) fn resource_accept(
&mut self,
handle: ResourceHandle,
module: &ModuleId,
span: Option<Span>,
) -> Result<Value, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_accept(handle, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Execute one non-streaming resource operation.
pub(crate) fn resource_request(
&mut self,
operation: &str,
args: Vec<Value>,
module: &ModuleId,
span: Option<Span>,
) -> Result<Value, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_request(operation, args, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Close a resource stream.
pub(crate) fn resource_close(
&mut self,
handle: ResourceHandle,
module: &ModuleId,
span: Option<Span>,
) -> Result<(), RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host
.resource_close(handle, &context)
.map_err(|mut error| {
error.mark_callsite();
error
})
}
/// Call a builtin-read host operation on behalf of a frame's module.
pub(crate) fn host_invoke(
&mut self,
@@ -717,21 +904,6 @@ impl<'a> Interpreter<'a> {
}
}
fn resolve_function<'p>(
program: &'p Program,
module: &ModuleId,
namespace: Option<&str>,
name: &str,
) -> Option<&'p Function> {
let module = program.module(module)?;
if let Some(namespace) = namespace {
if let Some(found) = module.namespaced_function(namespace, name) {
return Some(found);
}
}
module.function(name)
}
/// Bind already-evaluated arguments to a builtin parameter list.
fn bind_builtin_args(
builtin: &'static builtins::Builtin,
@@ -820,6 +992,24 @@ fn member_of(value: Value, name: &str, span: Option<Span>) -> Result<Value, Runt
format!("Code has no field `{name}`"),
)),
},
Value::FunctionRef(reference) => match name {
"module" => Ok(Value::Text(reference.module)),
"name" => Ok(Value::Text(reference.name)),
_ => Err(RuntimeError::new(
ErrorCategory::UnknownField,
span,
format!("FunctionRef has no field `{name}`"),
)),
},
Value::PluginHandle(handle) => match name {
"plugin" => Ok(Value::Text(handle.plugin)),
"export" => Ok(Value::Text(handle.export)),
_ => Err(RuntimeError::new(
ErrorCategory::UnknownField,
span,
format!("PluginHandle has no field `{name}`"),
)),
},
other => Err(RuntimeError::new(
ErrorCategory::UnknownField,
span,
+5 -1
View File
@@ -8,8 +8,12 @@
mod builtins_impl;
mod interpreter;
mod memory;
mod value_ops;
pub use interpreter::{run, EvaluatedArg, Interpreter, RunOutcome};
pub use interpreter::{run, run_with_limits, EvaluatedArg, Interpreter, RunOutcome};
pub use memory::{
MemoryLimits, MemoryStore, DEFAULT_MAX_REGION_BYTES, DEFAULT_MAX_TOTAL_BYTES, PAGE_SIZE,
};
pub use marqdo_value::{RuntimeError, Value};
Loaded 100 of 699 files, more files were not shown because too many files have changed in this diff. Show more