Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4af3829e6c | ||
|
|
3bc726790f | ||
|
|
0ded4e245d | ||
|
|
995f6026c9 | ||
|
|
099ff8ba02 | ||
|
|
d67f54c1f5 | ||
|
|
b9c41564ae | ||
|
|
a67f344b6b | ||
|
|
0fe5f42a62 | ||
|
|
1d3dca7c18 | ||
|
|
2d51f08340 | ||
|
|
e6e497e68b | ||
|
|
d78faaf8e4 | ||
|
|
d38736c0a0 | ||
|
|
eeea01d672 | ||
|
|
9e76635028 |
No files matched your search
@@ -183,9 +183,33 @@ jobs:
|
||||
assert document["code"] == "strict.probe_unavailable", document
|
||||
PY
|
||||
|
||||
frozen-extensions:
|
||||
name: frozen Linux archive and external extensions
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Build and check the frozen archive
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
version="$(cargo metadata --no-deps --format-version 1 --offline \
|
||||
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
|
||||
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
|
||||
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: frozen-extension-evidence-${{ github.sha }}
|
||||
path: dist/frozen-extension-evidence.json
|
||||
if-no-files-found: error
|
||||
|
||||
release-evidence:
|
||||
name: release evidence manifest
|
||||
needs: [test, schema, cross-platform]
|
||||
needs: [test, schema, cross-platform, frozen-extensions]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -197,6 +221,7 @@ jobs:
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
LINUX_RESULT: ${{ needs.test.result }}
|
||||
SCHEMA_RESULT: ${{ needs.schema.result }}
|
||||
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
|
||||
PORTABLE_RESULT: ${{ needs.cross-platform.result }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -209,7 +234,7 @@ jobs:
|
||||
}
|
||||
linux="$(state "$LINUX_RESULT")"
|
||||
portable="$(state "$PORTABLE_RESULT")"
|
||||
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ]; then
|
||||
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_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::"
|
||||
@@ -235,7 +260,7 @@ jobs:
|
||||
|
||||
release-candidate:
|
||||
name: release candidate artifact (${{ matrix.os }})
|
||||
needs: [test, schema, cross-platform]
|
||||
needs: [test, schema, cross-platform, frozen-extensions]
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
@@ -17,6 +17,7 @@ examples/plugin-multi-export/solver.so
|
||||
examples/plugin-demo/build/
|
||||
examples/plugin-multi-export/build/
|
||||
examples/provider-demo/build/
|
||||
examples/math-backend/build/
|
||||
|
||||
# Release artifacts
|
||||
dist/
|
||||
|
||||
@@ -10,7 +10,7 @@ steps:
|
||||
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
|
||||
- apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
|
||||
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
|
||||
- apt-get install -y --no-install-recommends nodejs
|
||||
- cargo fmt --all -- --check
|
||||
@@ -19,6 +19,10 @@ steps:
|
||||
# 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
|
||||
# Execution Events v1 black-box contract: a released-binary-shaped run
|
||||
# validated by the independent Python consumer and the public schema.
|
||||
- cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl
|
||||
- python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
|
||||
- cargo test -p marqdo-cli --test docs_consistency
|
||||
- cargo test -p marqdo-cli --test architecture_boundaries
|
||||
- python3 -m unittest discover -s tools/ci -p "test_*.py"
|
||||
@@ -32,6 +36,8 @@ steps:
|
||||
image: rust:1.100-bookworm
|
||||
depends_on: [test]
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 build-essential
|
||||
# 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
|
||||
@@ -44,3 +50,5 @@ steps:
|
||||
| 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
|
||||
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
|
||||
cat dist/frozen-extension-evidence.json
|
||||
+93
-1
@@ -1,12 +1,104 @@
|
||||
# Changelog
|
||||
|
||||
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
|
||||
`3.0.0-beta.1` was tagged on 2026-11-22 at source
|
||||
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`
|
||||
([release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1));
|
||||
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 (post `3.0.0-beta.1`)
|
||||
|
||||
### Core/extension boundary — RFC-EXT-0003 (issue #3)
|
||||
|
||||
Executed evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
|
||||
Frozen decisions: ADR-0060 (heading modes/annotations), ADR-0061 (math
|
||||
detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
|
||||
(foreign F-A transition).
|
||||
|
||||
#### Breaking changes (beta line; migrate before the next beta/stable)
|
||||
|
||||
- **`math.*` core builtins removed.** `math.parse`, `math.eval`,
|
||||
`math.substitute`, `math.simplify` and `math.differentiate` no longer exist in
|
||||
`BUILTINS`, `HostOp`, the runtime or the host. A document that calls one now
|
||||
fails statically with `symbol.unknown`; there is no `math.unsupported` runtime
|
||||
fallback and no old-name compatibility parser. `crates/marqdo-math` is removed
|
||||
from the workspace and host dependency graph. `Int`/`Float` arithmetic and the
|
||||
inert Markdown `Formula` value stay. Math algorithms move to pure `.mq.md`
|
||||
packages (`examples/math-library/`) or an explicitly selected ABI backend with
|
||||
the `math.compute` capability (`examples/math-backend/`). The historical
|
||||
`math` import namespace is released, so `import: { math: ... }` is accepted
|
||||
again. Migration: [`spec/math.md`](spec/math.md).
|
||||
- **Sibling heading inheritance bug fixed (H-06).** `build_units` now removes the
|
||||
current and same-or-higher-level headings from the ancestor stack *before*
|
||||
deriving the inherited mode. An unmarked heading can no longer inherit the
|
||||
previous sibling's mode: under `# @knowledge` a `## @exec` sibling followed by an
|
||||
unmarked `##` leaves the latter Knowledge/inert; under `# @exec` a `## @knowledge`
|
||||
sibling followed by an unmarked `##` makes the latter Exec/callable. This is a
|
||||
correctness fix with new conformance/black-box/`check --emit` coverage.
|
||||
- **Release archive now ships the verified `stdlib/`.** The archive contains
|
||||
`stdlib.json` and every `.mq.md` module; `RELEASE_INFO.json` records name,
|
||||
version, tree digest, alias digest, count and file list. `package.py` recomputes
|
||||
both digests and refuses a mismatch; `smoke.py` re-verifies them and fails
|
||||
closed when the bundle is removed. Release builds no longer fall back to the
|
||||
compile-time source tree (debug builds keep a development-only fallback). An
|
||||
independent `ubuntu:24.04` cold-install container check is recorded in the
|
||||
evidence.
|
||||
- **Core resource kinds are one registry (H-04).** `marqdo_host::CORE_RESOURCE_KINDS`
|
||||
(`stdio`, `file`, `tcp`, `tls`, `udp`, `tcp-listener`) is now used by both the
|
||||
CLI provider-manifest validator and every trusted host registration path; a provider
|
||||
name or declared kind equal to a core kind is rejected before registration.
|
||||
- `resource_request` operation ownership is reviewed and enforced by an
|
||||
architecture gate. New domain operations are forbidden in the core; see
|
||||
[`docs/architecture/resource-operations.md`](docs/architecture/resource-operations.md)
|
||||
and ADR-0062.
|
||||
|
||||
#### Proposed, not implemented
|
||||
|
||||
- **Heading Annotations v1 (H-05/H-07/H-13).** `@exec`/`@knowledge` are frozen
|
||||
as the only Core Modes and alone decide execution; a declarative,
|
||||
metadata-only `@namespace.identifier` annotation layer is specified as
|
||||
**Proposed** with target `3.1.x`. The current parser still rejects any other
|
||||
leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code,
|
||||
manifest loader, Analysis v3 or sidecar exists in this build. Contracts:
|
||||
ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md).
|
||||
- **Foreign F-B removal is deferred (H-02).** The permission-gated one-shot
|
||||
`foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled
|
||||
OS-boundary primitive (F-A); removal needs a versioned generic process/worker
|
||||
capability and the existing security negatives. ADR-0063 and
|
||||
[`spec/foreign.md`](spec/foreign.md) §8.
|
||||
|
||||
### Runtime observability — Execution Events v1 (RFC-OBS-0001, ADR-0059)
|
||||
|
||||
- `marqdo run` and `marqdo call` accept `--event-stream jsonl`: the CLI stdout
|
||||
becomes a pure NDJSON `marqdo.execution-events` v1 channel. Program
|
||||
stdout/stderr are carried as byte-exact base64 chunk events emitted at the
|
||||
Host commit point, not by splitting the final buffer.
|
||||
- Lifecycle and terminal events (`stream.opened`, `run.started`,
|
||||
`run.completed`, `run.failed`, `run.rejected`) have defined ordering and exit
|
||||
codes. `--event-stream` is mutually exclusive with `--json`, is rejected by
|
||||
static commands and by `--mode strict`, and may be combined with
|
||||
`--trace-file`; the two writers share one run id and Analysis digest.
|
||||
- Call instances get run-unique `frame_id`/`parent_frame_id`; `call.enter`,
|
||||
`call.exit`, `return`, `branch.eval`, `loop.iteration`, `effect` and
|
||||
`variable.assigned` events are bounded by a structural budget with a single
|
||||
`observation.truncated` marker.
|
||||
- Values are off by default. `--observe-variable` / `--observe-parameter` are
|
||||
exact-name selections; `Int`/`Float`/`Bool` are bounded and `Text` requires
|
||||
the separate `--observe-text-values` consent. Unselected, redacted,
|
||||
truncated and unsupported states are distinct.
|
||||
- New public contract
|
||||
[`spec/execution-events-v1.md`](spec/execution-events-v1.md) and
|
||||
[`spec/schemas/execution-events-v1.schema.json`](spec/schemas/execution-events-v1.schema.json),
|
||||
with fixtures and an independent Python consumer. Analysis v2 and Trace v2
|
||||
schemas/versions are unchanged.
|
||||
- Limitations: memory metadata events (OBS-06/P2), a bidirectional debug
|
||||
protocol and SSE/HTTP remain out of scope; strict mode refuses event mode
|
||||
explicitly.
|
||||
|
||||
## 3.0.0-beta.1 (2026-11-22)
|
||||
|
||||
First public prerelease of the independent Marqdo toolchain. This is a
|
||||
|
||||
+26
-5
@@ -1,7 +1,7 @@
|
||||
# Compatibility and support matrix
|
||||
|
||||
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
|
||||
tagged `v3.0.0-beta.1` at source SHA `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. 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
|
||||
@@ -44,6 +44,22 @@ Consequences for compatibility:
|
||||
[`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).
|
||||
|
||||
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
|
||||
|
||||
These land after the beta tag and **before any next beta/stable tag**; they are
|
||||
intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed
|
||||
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
|
||||
|
||||
| Change | Compatibility rule |
|
||||
|---|---|
|
||||
| `math.parse/eval/substitute/simplify/differentiate` removed from the core | **Breaking.** A call is a static `symbol.unknown`; there is no old-name parser, no `math.unsupported` runtime fallback and no ABI/Builtin shim. `Formula` stays an inert Markdown resource. Migrate to a pure `.mq.md` package or an explicitly selected ABI backend; `spec/math.md`. The `math` import namespace is released (no builtin conflict). |
|
||||
| Sibling heading mode inheritance corrected (H-06) | **Behaviour fix.** Unmarked headings inherit the nearest ancestor, never the previous sibling. Documents that relied on the buggy sibling leak change: a former accidental Exec sibling can become inert Knowledge (or vice versa). Covered by conformance/black-box/`check --emit` tests; no syntax/version change. |
|
||||
| Release archive must ship the verified `stdlib/` | **Delivery requirement.** Archive contains `stdlib.json` + all modules and `RELEASE_INFO.json` carries its name/version/tree/alias digests/count/files. Removing or tampering with it fails closed; release builds do not fall back to the build-machine source path. |
|
||||
| Core resource kinds enforced on every registration path (H-04) | Provider name or declared kind equal to `stdio/file/tcp/tls/udp/tcp-listener` is rejected with `ext.manifest_invalid` (CLI) / `ResourceUnsupported` (host) before registration. No provider may shadow a core kind. |
|
||||
| `resource_request` operation ownership (H-03) | New domain/business operations are forbidden in the core: ship a pure `.mq.md` package, ABI export or Provider. The exact reviewed allowlist is pinned by `architecture_boundaries.rs`; see `docs/architecture/resource-operations.md`. |
|
||||
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`, Analysis v3 or sidecar exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
|
||||
| Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. |
|
||||
|
||||
## Public protocol versions
|
||||
|
||||
| Surface | Version | Compatibility rule |
|
||||
@@ -53,10 +69,11 @@ Consequences for compatibility:
|
||||
| `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. |
|
||||
| Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). |
|
||||
| CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. |
|
||||
| Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. |
|
||||
| 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. |
|
||||
| Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). |
|
||||
| Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). |
|
||||
| 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. |
|
||||
@@ -82,6 +99,7 @@ portable/tested locally but the native platform lane has not run here;
|
||||
| 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 |
|
||||
| Execution Events v1 (`--event-stream jsonl`, P0/P1) | PASS locally (14 CLI contract tests + 8 host + 4 runtime; independent Python schema consumer); post-beta, not in the tagged archive | UNVERIFIED | UNVERIFIED |
|
||||
| Tool Protocol v1 + 3 independent consumers | PASS | UNVERIFIED | UNVERIFIED |
|
||||
| Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** |
|
||||
| Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) |
|
||||
@@ -163,5 +181,8 @@ 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.
|
||||
[`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
||||
(`BETA_RELEASE_CANDIDATE`). Release:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. Beta status
|
||||
does not imply stable `3.0.0` or LTS; the stable gate remains stricter and
|
||||
separate.
|
||||
Generated
-13
@@ -422,7 +422,6 @@ dependencies = [
|
||||
"marqdo-host",
|
||||
"marqdo-ir",
|
||||
"marqdo-markdown",
|
||||
"marqdo-math",
|
||||
"marqdo-package",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-runtime",
|
||||
@@ -488,7 +487,6 @@ dependencies = [
|
||||
"glob",
|
||||
"libloading",
|
||||
"marqdo-foreign",
|
||||
"marqdo-math",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-span",
|
||||
@@ -525,17 +523,6 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-math"
|
||||
version = "3.0.0-beta.1"
|
||||
dependencies = [
|
||||
"marqdo-value",
|
||||
"num-bigint",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-package"
|
||||
version = "3.0.0-beta.1"
|
||||
|
||||
@@ -7,7 +7,6 @@ members = [
|
||||
"crates/marqdo-markdown",
|
||||
"crates/marqdo-ir",
|
||||
"crates/marqdo-frontend",
|
||||
"crates/marqdo-math",
|
||||
"crates/marqdo-foreign",
|
||||
"crates/marqdo-plugin-abi",
|
||||
"crates/marqdo-provider-worker",
|
||||
@@ -34,7 +33,6 @@ marqdo-expression = { path = "crates/marqdo-expression" }
|
||||
marqdo-markdown = { path = "crates/marqdo-markdown" }
|
||||
marqdo-ir = { path = "crates/marqdo-ir" }
|
||||
marqdo-frontend = { path = "crates/marqdo-frontend" }
|
||||
marqdo-math = { path = "crates/marqdo-math" }
|
||||
marqdo-foreign = { path = "crates/marqdo-foreign" }
|
||||
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
|
||||
marqdo-host = { path = "crates/marqdo-host" }
|
||||
|
||||
@@ -27,8 +27,9 @@ release policy.
|
||||
> [`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
|
||||
> **Status: `3.0.0-beta.1` prerelease** —
|
||||
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1),
|
||||
> source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the
|
||||
> 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
|
||||
@@ -66,6 +67,7 @@ marqdo init demo
|
||||
cd demo
|
||||
marqdo check index.mq.md
|
||||
marqdo run index.mq.md # executes ## @exec main
|
||||
marqdo run index.mq.md --event-stream jsonl # live Execution Events v1 NDJSON
|
||||
marqdo inspect index.mq.md --ast
|
||||
marqdo inspect index.mq.md --signature
|
||||
marqdo call index.mq.md main
|
||||
@@ -217,11 +219,13 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
|
||||
capability dropping, rlimits, a wall-clock supervisor and child
|
||||
self-verification (ADR-0021). It is probe-gated and verified in a disposable
|
||||
Ubuntu VM; unsupported hosts fail closed.
|
||||
* **P5 Math/Foreign** — native `Formula` value from `$$...$$`; `math.parse/
|
||||
eval/substitute` over a documented exact-rational subset; one-shot Python/
|
||||
Node kernels via `foreign.run/call` with typed wire protocol, timeout and
|
||||
output limits; pinned provider/environment digests and ADR-0020 environment
|
||||
binding.
|
||||
* **P5 Math/Foreign** — native inert `Formula` value from `$$...$$`; the host
|
||||
`math.*` builtin API was removed after `3.0.0-beta.1` (ADR-0061) and math
|
||||
algorithms now live in pure `.mq.md` packages or an explicitly selected ABI
|
||||
backend with the `math.compute` capability; one-shot Python/Node kernels via
|
||||
`foreign.run/call` (controlled F-A OS boundary, ADR-0063) with typed wire
|
||||
protocol, timeout and output limits; pinned provider/environment digests and
|
||||
ADR-0020 environment binding.
|
||||
* **P6 plugin ABI** — frozen C ABI v1 header (`include/marqdo_plugin_abi_v1.h`),
|
||||
host bindings, Rust SDK (`mq_plugin_entry!`), `plugin.yaml` validation,
|
||||
target-triple + sha256 artifact verification, native and isolated worker
|
||||
@@ -229,7 +233,9 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
|
||||
(`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox.
|
||||
* **Public protocols** — Analysis v2 and Trace v2 with JSON Schemas and
|
||||
independent Python consumers; Tool Protocol v1 with arbitrary command names,
|
||||
SemVer negotiation and whole-bundle digest verification.
|
||||
SemVer negotiation and whole-bundle digest verification; **Execution Events
|
||||
v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and
|
||||
explicitly selected, bounded values (post-beta addition, ADR-0059).
|
||||
|
||||
Run everything:
|
||||
|
||||
@@ -244,7 +250,7 @@ cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
* **Strict is Linux-only and L1-only.** `--mode strict` enables the
|
||||
Bubblewrap supervisor only when its runtime probe passes; otherwise it exits
|
||||
1. It supports pure Marqdo + Math and rejects Foreign, plugins, kernels,
|
||||
1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels,
|
||||
external grants and trace files (exit 2). Worker plugins provide
|
||||
crash/address-space isolation, not an OS sandbox, and are not allowed in
|
||||
strict.
|
||||
@@ -264,8 +270,10 @@ cargo clippy --workspace --all-targets -- -D warnings
|
||||
the first.
|
||||
* **`fmt` is minimal** (line endings/trailing newlines), not AST-preserving
|
||||
reformatting.
|
||||
* **Math is a limited calculator**, not a CAS/prover: no `simplify`/
|
||||
`differentiate`/matrices/series; equation solving is affine-only.
|
||||
* **Math is not a core API.** `math.*` builtins were removed after
|
||||
`3.0.0-beta.1` (ADR-0061); `Formula` Markdown stays inert, and math
|
||||
algorithms come from explicit pure `.mq.md` imports or a trusted ABI backend.
|
||||
The core promises no CAS/prover, solver or evaluator.
|
||||
* **Foreign kernels are unsandboxed one-shot child processes** (no sessions,
|
||||
no state bridge); they run with the host user's filesystem/network access.
|
||||
* Finite floats are IEEE-754 binary64; the typed wire round-trip is exact
|
||||
@@ -281,12 +289,11 @@ crates/marqdo-expression strict expression/statement parser
|
||||
crates/marqdo-markdown frozen comrak profile, canonical AST, front matter
|
||||
crates/marqdo-ir module/unit/function/statement IR, builtin table
|
||||
crates/marqdo-frontend heading scopes, mapping, inference, static calls
|
||||
crates/marqdo-math exact-rational Formula subset
|
||||
crates/marqdo-foreign Python/Node one-shot kernel supervisor
|
||||
crates/marqdo-sandbox mode parsing + platform isolation detection
|
||||
crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader
|
||||
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro
|
||||
crates/marqdo-host CapabilityHost, budgets, FS, math/foreign/plugin adapters
|
||||
crates/marqdo-host CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
|
||||
crates/marqdo-runtime tree-walk interpreter
|
||||
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
|
||||
crates/cli CLI composition root (binary `marqdo`)
|
||||
@@ -442,7 +449,9 @@ details in [`spec/callable-resolution.md`](spec/callable-resolution.md)):
|
||||
`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
|
||||
`resource`) is rejected with `ext.import_namespace_conflict`; rename it. The
|
||||
historical `math` namespace was released when the `math.*` builtins were removed
|
||||
(ADR-0061), so a `math:` import alias is now accepted. 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.
|
||||
|
||||
@@ -15,7 +15,6 @@ marqdo-expression = { workspace = true }
|
||||
marqdo-markdown = { workspace = true }
|
||||
marqdo-ir = { workspace = true }
|
||||
marqdo-frontend = { workspace = true }
|
||||
marqdo-math = { workspace = true }
|
||||
marqdo-foreign = { workspace = true }
|
||||
marqdo-plugin-abi = { workspace = true }
|
||||
marqdo-host = { workspace = true }
|
||||
|
||||
+281
-52
@@ -4,6 +4,7 @@
|
||||
//! runtime helpers, but keeps the run session out of the command table.
|
||||
|
||||
use super::*;
|
||||
use crate::execution_events::{EventStream, ObservationOptions};
|
||||
use crate::provider_manifest;
|
||||
use marqdo_sandbox::StrictChildState;
|
||||
|
||||
@@ -14,16 +15,55 @@ pub fn execute(
|
||||
settings: &SandboxSettings,
|
||||
json: bool,
|
||||
trace: bool,
|
||||
observation: Option<&ObservationOptions>,
|
||||
) -> 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,
|
||||
// Open the dedicated protocol channel before any project work so prepare
|
||||
// and authorization failures can still produce `run.rejected`.
|
||||
let events = match observation {
|
||||
Some(options) => match EventStream::open(options) {
|
||||
Ok(stream) => Some(stream),
|
||||
Err(error) => {
|
||||
eprintln!("error[observe.transport_failed]: {error}");
|
||||
return 1;
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let stream = events.as_ref();
|
||||
let prepared = if stream.is_some() {
|
||||
let options = PrepareOptions {
|
||||
plugins: settings.plugins.clone(),
|
||||
};
|
||||
match project_prepare::prepare(file, &options) {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return fail_prepare(stream, json, command_name, "prepare", &error),
|
||||
}
|
||||
} else {
|
||||
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 let Some(stream) = stream {
|
||||
let code = project
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|item| item.diagnostic.is_error())
|
||||
.map(|item| item.diagnostic.code.clone())
|
||||
.unwrap_or_else(|| "cli.compile_error".to_string());
|
||||
if let Err(error) = stream.rejected(
|
||||
"compile",
|
||||
&code,
|
||||
"refusing to run a project with compile errors",
|
||||
) {
|
||||
return transport_failure(&error);
|
||||
}
|
||||
}
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"command": command_name,
|
||||
@@ -48,8 +88,15 @@ pub fn execute(
|
||||
let mode = match settings.sandbox_mode() {
|
||||
Ok(mode) => mode,
|
||||
Err(error) => {
|
||||
emit_error(json, command_name, "cli.invalid_mode", &error);
|
||||
return 2;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"cli.invalid_mode",
|
||||
&error,
|
||||
2,
|
||||
);
|
||||
}
|
||||
};
|
||||
// A project-declared extension is activation, not authorization, but it is
|
||||
@@ -68,8 +115,15 @@ pub fn execute(
|
||||
marqdo_package::MANIFEST_FILE,
|
||||
settings.mode
|
||||
);
|
||||
emit_error(json, command_name, code, &message);
|
||||
return 2;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
code,
|
||||
&message,
|
||||
2,
|
||||
);
|
||||
}
|
||||
let mut kernel_paths = settings.kernels.clone();
|
||||
kernel_paths.extend(
|
||||
@@ -90,9 +144,28 @@ pub fn execute(
|
||||
provider_paths.sort();
|
||||
provider_paths.dedup();
|
||||
if mode == SandboxMode::Strict {
|
||||
if stream.is_some() {
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"strict",
|
||||
"strict.unsupported_grant",
|
||||
"--event-stream jsonl is not supported under --mode strict; strict refuses \
|
||||
trace/event artifacts and never downgrades to project mode",
|
||||
2,
|
||||
);
|
||||
}
|
||||
if let Err(error) = settings.strict_preflight() {
|
||||
emit_error(json, command_name, "strict.unsupported_grant", &error);
|
||||
return 2;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"strict",
|
||||
"strict.unsupported_grant",
|
||||
&error,
|
||||
2,
|
||||
);
|
||||
}
|
||||
match marqdo_sandbox::inspect_strict_child() {
|
||||
// A verified supervisor child may run project code.
|
||||
@@ -101,8 +174,15 @@ pub fn execute(
|
||||
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 fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"strict",
|
||||
error.code(),
|
||||
&error.to_string(),
|
||||
1,
|
||||
);
|
||||
}
|
||||
return launch_strict_process(&project.root, file, settings, json, command_name);
|
||||
}
|
||||
@@ -111,30 +191,49 @@ pub fn execute(
|
||||
// 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;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"strict",
|
||||
"strict.identity_invalid",
|
||||
&message,
|
||||
1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let platform = PlatformCapabilities::detect();
|
||||
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
|
||||
emit_error(
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"sandbox.unavailable",
|
||||
&error.to_string(),
|
||||
1,
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let capabilities = match settings.capabilities() {
|
||||
Ok(capabilities) => capabilities,
|
||||
Err(error) => {
|
||||
emit_error(json, command_name, "cli.invalid_grants", &error);
|
||||
return 2;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"cli.invalid_grants",
|
||||
&error,
|
||||
2,
|
||||
);
|
||||
}
|
||||
};
|
||||
let stdin = read_stdin();
|
||||
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
|
||||
if let Some(stream) = stream {
|
||||
host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
|
||||
}
|
||||
if trace || json || settings.trace_file.is_some() {
|
||||
host = host
|
||||
.with_trace()
|
||||
@@ -161,12 +260,15 @@ pub fn execute(
|
||||
}
|
||||
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;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"prepare",
|
||||
"ext.kernel_load_failed",
|
||||
&error,
|
||||
2,
|
||||
);
|
||||
}
|
||||
}
|
||||
// T6: verify every selected artifact/path/hash before starting a worker or
|
||||
@@ -180,8 +282,7 @@ pub fn execute(
|
||||
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;
|
||||
return fail_prepare(stream, json, command_name, "prepare", &error);
|
||||
}
|
||||
};
|
||||
// `--provider` alone never authorizes; the exact `--allow-provider NAME`
|
||||
@@ -201,8 +302,7 @@ pub fn execute(
|
||||
provider.name, provider.name
|
||||
),
|
||||
);
|
||||
emit_prepare_error(json, command_name, &error);
|
||||
return error.exit_code;
|
||||
return fail_prepare(stream, json, command_name, "authorization", &error);
|
||||
}
|
||||
}
|
||||
// A grant that matches no selected provider is a deterministic option
|
||||
@@ -217,8 +317,7 @@ pub fn execute(
|
||||
providers are never discovered automatically"
|
||||
),
|
||||
);
|
||||
emit_prepare_error(json, command_name, &error);
|
||||
return error.exit_code;
|
||||
return fail_prepare(stream, json, command_name, "authorization", &error);
|
||||
}
|
||||
}
|
||||
for plugin in &static_plugins.plugins {
|
||||
@@ -226,16 +325,34 @@ pub fn execute(
|
||||
&plugin.base_dir,
|
||||
&plugin.artifact_relative,
|
||||
) {
|
||||
emit_prepare_error(json, command_name, &error);
|
||||
return error.exit_code;
|
||||
return fail_prepare(stream, json, command_name, "authorization", &error);
|
||||
}
|
||||
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;
|
||||
return fail_prepare(stream, json, command_name, "authorization", &error);
|
||||
}
|
||||
}
|
||||
// A native plugin shares this process and can write fd 1 directly, so it
|
||||
// can pollute the JSONL channel. Fail closed rather than presenting
|
||||
// untrusted raw bytes as program stdout (RFC-OBS-0001 §4.4/§9.2, T26).
|
||||
if stream.is_some()
|
||||
&& static_plugins
|
||||
.plugins
|
||||
.iter()
|
||||
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native)
|
||||
{
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"ext.event_stream_unsupported_native_plugin",
|
||||
"--event-stream jsonl cannot guarantee a clean channel with an in-process native \
|
||||
plugin; use a worker plugin or disable event mode",
|
||||
2,
|
||||
);
|
||||
}
|
||||
// T7: start only selected, granted and verified extensions.
|
||||
for plugin in &static_plugins.plugins {
|
||||
if let Err(message) = load_plugin_into_host(
|
||||
@@ -243,19 +360,29 @@ pub fn execute(
|
||||
&plugin.manifest_path,
|
||||
settings.trust_native_plugin,
|
||||
) {
|
||||
if json {
|
||||
output::print_json(&json!({"success": false, "error": message}));
|
||||
} else {
|
||||
eprintln!("error: {message}");
|
||||
}
|
||||
return 1;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"ext.plugin_load_failed",
|
||||
&message,
|
||||
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;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"authorization",
|
||||
"ext.plugin_binding_mismatch",
|
||||
&message,
|
||||
1,
|
||||
);
|
||||
}
|
||||
// T7b: start only granted and verified provider helpers. Every manifest,
|
||||
// artifact, target, grant and duplicate-kind check above already passed, so
|
||||
@@ -266,8 +393,7 @@ pub fn execute(
|
||||
provider,
|
||||
&settings.allow_provider,
|
||||
) {
|
||||
emit_prepare_error(json, command_name, &error);
|
||||
return error.exit_code;
|
||||
return fail_prepare(stream, json, command_name, "prepare", &error);
|
||||
}
|
||||
}
|
||||
let function_name = function.unwrap_or("main").to_string();
|
||||
@@ -285,12 +411,15 @@ pub fn execute(
|
||||
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;
|
||||
return fail(
|
||||
stream,
|
||||
json,
|
||||
command_name,
|
||||
"compile",
|
||||
"sem.no_entry_function",
|
||||
&message,
|
||||
1,
|
||||
);
|
||||
}
|
||||
let runtime_args: Vec<EvaluatedArg> = named_args
|
||||
.iter()
|
||||
@@ -304,7 +433,19 @@ pub fn execute(
|
||||
.max_region_memory
|
||||
.unwrap_or(marqdo_runtime::DEFAULT_MAX_REGION_BYTES),
|
||||
};
|
||||
let result = run_with_limits(
|
||||
if let Some(stream) = stream {
|
||||
let entry = format!("{}::{}", project.entry, function_name);
|
||||
let analysis_digest = format!("sha256:{}", crate::analysis::digest(&project));
|
||||
if let Err(error) = stream.started(
|
||||
&entry,
|
||||
mode.as_str(),
|
||||
&project.identity.root_id(),
|
||||
&analysis_digest,
|
||||
) {
|
||||
return transport_failure(&error);
|
||||
}
|
||||
}
|
||||
let mut result = run_with_limits(
|
||||
&project.program,
|
||||
&mut host,
|
||||
&project.entry,
|
||||
@@ -312,17 +453,58 @@ pub fn execute(
|
||||
runtime_args,
|
||||
memory_limits,
|
||||
);
|
||||
// A dead event pipe is a run failure even if the program itself returned.
|
||||
if result.is_ok() {
|
||||
if let Some(message) = host.observation_failure() {
|
||||
result = Err(RuntimeError::new(
|
||||
marqdo_value::ErrorCategory::Observation,
|
||||
None,
|
||||
format!("observe.transport_failed: {message}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
let trace_run_id = stream.map(EventStream::run_id);
|
||||
if let Some(path) = &settings.trace_file {
|
||||
let status = match &result {
|
||||
Ok(_) => "ok",
|
||||
Err(error) => error.code(),
|
||||
};
|
||||
let entry = format!("{}::{}", project.entry, function_name);
|
||||
if let Err(error) = crate::trace::write(&project, &host, &entry, status, path) {
|
||||
emit_error(json, command_name, "cli.trace_failed", &error);
|
||||
if let Err(error) = crate::trace::write(
|
||||
&project,
|
||||
&host,
|
||||
&entry,
|
||||
status,
|
||||
path,
|
||||
trace_run_id.as_deref(),
|
||||
) {
|
||||
if let Some(stream) = stream {
|
||||
let _ = stream.failed_error("cli.trace_failed", &error);
|
||||
} else {
|
||||
emit_error(json, command_name, "cli.trace_failed", &error);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if let Some(stream) = stream {
|
||||
// The program's stdout/stderr were already emitted as chunk events at
|
||||
// their real host commit points; never replay them on this channel.
|
||||
match &result {
|
||||
Ok(outcome) => {
|
||||
if let Err(error) = stream.completed(&outcome.value) {
|
||||
return transport_failure(&error);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
if let Err(write_error) = stream.failed(error) {
|
||||
eprintln!("error[observe.transport_failed]: {write_error}");
|
||||
}
|
||||
eprint!("{}", render_runtime_error(error, &project));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
let stdout = host.take_output();
|
||||
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
|
||||
let stderr = host.take_error();
|
||||
@@ -383,6 +565,53 @@ pub fn execute(
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_failure(error: &str) -> i32 {
|
||||
eprintln!("error[observe.transport_failed]: {error}");
|
||||
1
|
||||
}
|
||||
|
||||
/// Emit one pre-execution rejection (or the legacy non-event error form).
|
||||
fn fail(
|
||||
stream: Option<&EventStream>,
|
||||
json: bool,
|
||||
command_name: &str,
|
||||
phase: &str,
|
||||
code: &str,
|
||||
message: &str,
|
||||
exit: i32,
|
||||
) -> i32 {
|
||||
if let Some(stream) = stream {
|
||||
if let Err(error) = stream.rejected(phase, code, message) {
|
||||
return transport_failure(&error);
|
||||
}
|
||||
}
|
||||
if json && stream.is_none() {
|
||||
emit_error(json, command_name, code, message);
|
||||
} else {
|
||||
eprintln!("error[{code}]: {message}");
|
||||
}
|
||||
exit
|
||||
}
|
||||
|
||||
/// Emit one prepare/authorization rejection using a `PrepareError`.
|
||||
fn fail_prepare(
|
||||
stream: Option<&EventStream>,
|
||||
json: bool,
|
||||
command_name: &str,
|
||||
phase: &str,
|
||||
error: &crate::extension_descriptors::PrepareError,
|
||||
) -> i32 {
|
||||
if let Some(stream) = stream {
|
||||
if let Err(write_error) = stream.rejected(phase, &error.code, &error.message) {
|
||||
return transport_failure(&write_error);
|
||||
}
|
||||
eprintln!("error[{}]: {}", error.code, error.message);
|
||||
} else {
|
||||
emit_prepare_error(json, command_name, error);
|
||||
}
|
||||
error.exit_code
|
||||
}
|
||||
|
||||
fn emit_prepare_error(
|
||||
json: bool,
|
||||
command_name: &str,
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
//! Execution Events v1 JSONL writer and public envelope.
|
||||
//!
|
||||
//! Normative contract: `spec/execution-events-v1.md`; decision record:
|
||||
//! ADR-0059. The host owns the typed events; this module only assigns the
|
||||
//! public envelope/sequence, encodes bytes as base64 and writes one flushed
|
||||
//! line per event to the CLI protocol stdout.
|
||||
//!
|
||||
//! There is no HTTP, SSE, WebSocket, View or Agent branch here.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeSet;
|
||||
use std::io::{self, Write};
|
||||
use std::rc::Rc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use marqdo_host::{
|
||||
FrameId, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
|
||||
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
DEFAULT_MAX_VALUE_BYTES,
|
||||
};
|
||||
use marqdo_value::{RuntimeError, Value};
|
||||
use serde_json::{json, Value as Json};
|
||||
|
||||
/// Public schema name.
|
||||
pub const SCHEMA: &str = "marqdo.execution-events";
|
||||
/// Public schema major version.
|
||||
pub const SCHEMA_VERSION: u32 = 1;
|
||||
/// The only accepted `--event-stream` format in v1.
|
||||
pub const FORMAT_JSONL: &str = "jsonl";
|
||||
|
||||
/// CLI observation options.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObservationOptions {
|
||||
/// Exact local-variable names selected with `--observe-variable`.
|
||||
pub variables: Vec<String>,
|
||||
/// Exact parameter names selected with `--observe-parameter`.
|
||||
pub parameters: Vec<String>,
|
||||
/// Second explicit consent for `Text` bytes.
|
||||
pub allow_text_values: bool,
|
||||
/// Maximum encoded source bytes for one value (`0` = unlimited).
|
||||
pub max_value_bytes: usize,
|
||||
/// Structural/value event budget (`0` = unlimited).
|
||||
pub max_events: u64,
|
||||
/// Approximate structural/value byte budget (`0` = unlimited).
|
||||
pub max_bytes: u64,
|
||||
}
|
||||
|
||||
impl Default for ObservationOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
variables: Vec::new(),
|
||||
parameters: Vec::new(),
|
||||
allow_text_values: false,
|
||||
max_value_bytes: DEFAULT_MAX_VALUE_BYTES,
|
||||
max_events: DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
max_bytes: DEFAULT_MAX_OBSERVATION_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObservationOptions {
|
||||
/// Typed host policy for this run.
|
||||
pub fn config(&self) -> ObservationConfig {
|
||||
ObservationConfig {
|
||||
structural: true,
|
||||
selected_variables: self.variables.iter().cloned().collect::<BTreeSet<_>>(),
|
||||
selected_parameters: self.parameters.iter().cloned().collect::<BTreeSet<_>>(),
|
||||
allow_text_values: self.allow_text_values,
|
||||
max_observation_events: self.max_events,
|
||||
max_observation_bytes: self.max_bytes,
|
||||
max_value_bytes: self.max_value_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One run's JSONL writer, shared with the host sink.
|
||||
#[derive(Clone)]
|
||||
pub struct EventStream {
|
||||
inner: Rc<RefCell<JsonlWriter>>,
|
||||
config: ObservationConfig,
|
||||
}
|
||||
|
||||
impl EventStream {
|
||||
/// Open the protocol channel and write `stream.opened` as `seq: 0`.
|
||||
pub fn open(options: &ObservationOptions) -> Result<Self, String> {
|
||||
let run_id = new_run_id();
|
||||
let config = options.config();
|
||||
let opened = json!({
|
||||
"producer": {
|
||||
"name": "marqdo",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
},
|
||||
"protocol": {
|
||||
"name": SCHEMA,
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
},
|
||||
"observation": {
|
||||
"level": config.level(),
|
||||
"values": config.values_enabled(),
|
||||
"selected_variables": config.selected_variables.iter().cloned().collect::<Vec<_>>(),
|
||||
"selected_parameters": config.selected_parameters.iter().cloned().collect::<Vec<_>>(),
|
||||
"allow_text_values": config.allow_text_values,
|
||||
},
|
||||
"limits": {
|
||||
"max_observation_events": config.max_observation_events,
|
||||
"max_observation_bytes": config.max_observation_bytes,
|
||||
"max_value_bytes": config.max_value_bytes,
|
||||
},
|
||||
});
|
||||
let mut writer = JsonlWriter {
|
||||
out: Box::new(io::stdout()),
|
||||
run_id: run_id.clone(),
|
||||
seq: 0,
|
||||
};
|
||||
writer.emit("stream.opened", opened)?;
|
||||
Ok(Self {
|
||||
inner: Rc::new(RefCell::new(writer)),
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
/// Opaque run identity shared with Trace v2 when both are requested.
|
||||
pub fn run_id(&self) -> String {
|
||||
self.inner.borrow().run_id.clone()
|
||||
}
|
||||
|
||||
/// Typed policy (used to install the host sink).
|
||||
pub fn config(&self) -> ObservationConfig {
|
||||
self.config.clone()
|
||||
}
|
||||
|
||||
/// Installable host sink handle.
|
||||
pub fn host_sink(&self) -> HostEventSink {
|
||||
HostEventSink {
|
||||
stream: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write one raw public event. Used for lifecycle and terminal events.
|
||||
pub fn emit(&self, kind: &str, payload: Json) -> Result<(), String> {
|
||||
self.inner.borrow_mut().emit(kind, payload)
|
||||
}
|
||||
|
||||
/// Write `run.started`.
|
||||
pub fn started(
|
||||
&self,
|
||||
entry: &str,
|
||||
mode: &str,
|
||||
root_id: &str,
|
||||
analysis_digest: &str,
|
||||
) -> Result<(), String> {
|
||||
self.emit(
|
||||
"run.started",
|
||||
json!({
|
||||
"entry": entry,
|
||||
"mode": mode,
|
||||
"source": {
|
||||
"root_id": root_id,
|
||||
"analysis_digest": analysis_digest,
|
||||
},
|
||||
"started_unix_ms": unix_millis(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Write the successful terminal event.
|
||||
pub fn completed(&self, value: &Value) -> Result<(), String> {
|
||||
self.emit(
|
||||
"run.completed",
|
||||
json!({"status": "ok", "value": marqdo_value::to_wire(value)}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Write the failed terminal event.
|
||||
pub fn failed(&self, error: &RuntimeError) -> Result<(), String> {
|
||||
self.emit(
|
||||
"run.failed",
|
||||
json!({
|
||||
"status": "error",
|
||||
"error": {
|
||||
"code": error.code(),
|
||||
"message": error.message,
|
||||
"module_id": error.module_id.as_deref(),
|
||||
"span": error.span.map(span_json),
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Write a failed terminal event for a CLI-level failure that still has a
|
||||
/// stable code (for example `cli.trace_failed`).
|
||||
pub fn failed_error(&self, code: &str, message: &str) -> Result<(), String> {
|
||||
self.emit(
|
||||
"run.failed",
|
||||
json!({
|
||||
"status": "error",
|
||||
"error": {"code": code, "message": message},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Write the pre-execution rejection terminal event.
|
||||
pub fn rejected(&self, phase: &str, code: &str, message: &str) -> Result<(), String> {
|
||||
self.emit(
|
||||
"run.rejected",
|
||||
json!({
|
||||
"status": "rejected",
|
||||
"phase": phase,
|
||||
"error": {"code": code, "message": message},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Encode and write one typed host/runtime observation event.
|
||||
pub fn emit_observation(&self, event: ObservationEvent<'_>) -> Result<(), String> {
|
||||
let (kind, payload) = observation_payload(event);
|
||||
self.emit(kind, payload)
|
||||
}
|
||||
}
|
||||
|
||||
/// `ObservationSink` adapter installed into `StdHost`.
|
||||
pub struct HostEventSink {
|
||||
stream: EventStream,
|
||||
}
|
||||
|
||||
impl ObservationSink for HostEventSink {
|
||||
fn emit(&mut self, event: ObservationEvent<'_>) -> Result<(), ObservationError> {
|
||||
self.stream
|
||||
.emit_observation(event)
|
||||
.map_err(ObservationError::new)
|
||||
}
|
||||
}
|
||||
|
||||
struct JsonlWriter {
|
||||
out: Box<dyn Write>,
|
||||
run_id: String,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
impl JsonlWriter {
|
||||
fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> {
|
||||
let event = json!({
|
||||
"schema": SCHEMA,
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"run_id": self.run_id,
|
||||
"seq": self.seq,
|
||||
"kind": kind,
|
||||
"payload": payload,
|
||||
});
|
||||
let mut line = serde_json::to_vec(&event)
|
||||
.map_err(|error| format!("cannot encode execution event: {error}"))?;
|
||||
line.push(b'\n');
|
||||
// Flush each line: line-buffered batching would hide real-time output
|
||||
// behind the run duration (RFC-OBS-0001 §5.2).
|
||||
self.out
|
||||
.write_all(&line)
|
||||
.and_then(|()| self.out.flush())
|
||||
.map_err(|error| format!("cannot write execution event stream: {error}"))?;
|
||||
self.seq += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
|
||||
match event {
|
||||
ObservationEvent::StdoutChunk { data } => (
|
||||
"stdout.chunk",
|
||||
json!({
|
||||
"encoding": "base64",
|
||||
"data_base64": base64_encode(data),
|
||||
"byte_count": data.len(),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::StderrChunk { data } => (
|
||||
"stderr.chunk",
|
||||
json!({
|
||||
"encoding": "base64",
|
||||
"data_base64": base64_encode(data),
|
||||
"byte_count": data.len(),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::CallEnter {
|
||||
frame_id,
|
||||
parent_frame_id,
|
||||
function_id,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"call.enter",
|
||||
json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"parent_frame_id": parent_frame_id.map(FrameId::as_wire),
|
||||
"function_id": function_id,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::CallExit {
|
||||
frame_id,
|
||||
status,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"call.exit",
|
||||
json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"status": status,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"return",
|
||||
json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"value_type": value_type,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::BranchEval {
|
||||
frame_id,
|
||||
result,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"branch.eval",
|
||||
json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"result": result,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::LoopIteration {
|
||||
frame_id,
|
||||
decision,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"loop.iteration",
|
||||
json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"decision": decision,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::Effect {
|
||||
operation,
|
||||
result_code,
|
||||
module_id,
|
||||
span,
|
||||
} => (
|
||||
"effect",
|
||||
json!({
|
||||
"operation": operation,
|
||||
"result_code": result_code,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
}),
|
||||
),
|
||||
ObservationEvent::VariableAssigned {
|
||||
frame_id,
|
||||
name,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value,
|
||||
} => (
|
||||
"variable.assigned",
|
||||
value_event_payload(
|
||||
frame_id,
|
||||
name,
|
||||
None,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value,
|
||||
),
|
||||
),
|
||||
ObservationEvent::ParameterObserved {
|
||||
frame_id,
|
||||
name,
|
||||
source,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value,
|
||||
} => (
|
||||
"parameter.observed",
|
||||
value_event_payload(
|
||||
frame_id,
|
||||
name,
|
||||
Some(source),
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value,
|
||||
),
|
||||
),
|
||||
ObservationEvent::ObservationTruncated {
|
||||
reason,
|
||||
limit,
|
||||
written,
|
||||
dropped,
|
||||
} => (
|
||||
"observation.truncated",
|
||||
json!({
|
||||
"reason": reason,
|
||||
"limit": limit,
|
||||
"written": written,
|
||||
"dropped": dropped,
|
||||
}),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn value_event_payload(
|
||||
frame_id: FrameId,
|
||||
name: &str,
|
||||
source: Option<ParameterSource>,
|
||||
value_type: &str,
|
||||
module_id: &str,
|
||||
span: Option<marqdo_span::Span>,
|
||||
value_state: ValueState,
|
||||
value: Option<marqdo_host::ObservedValue>,
|
||||
) -> Json {
|
||||
let mut payload = json!({
|
||||
"frame_id": frame_id.as_wire(),
|
||||
"name": name,
|
||||
"value_type": value_type,
|
||||
"module_id": module_id,
|
||||
"span": span.map(span_json),
|
||||
"value_state": value_state.as_str(),
|
||||
});
|
||||
if let Some(source) = source {
|
||||
payload["source"] = Json::String(source.as_str().to_string());
|
||||
}
|
||||
if let Some(value) = value {
|
||||
payload["value"] = value.wire;
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
fn span_json(span: marqdo_span::Span) -> Json {
|
||||
json!({"start": span.start, "end": span.end})
|
||||
}
|
||||
|
||||
fn new_run_id() -> String {
|
||||
format!("{}-{}", std::process::id(), unix_nanos())
|
||||
}
|
||||
|
||||
fn unix_nanos() -> u128 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn unix_millis() -> u128 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_millis())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Standard padded base64 (no external dependency; the protocol only needs
|
||||
/// one canonical encoding).
|
||||
pub fn base64_encode(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||
for chunk in bytes.chunks(3) {
|
||||
let b0 = chunk[0] as u32;
|
||||
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
|
||||
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
|
||||
let triple = (b0 << 16) | (b1 << 8) | b2;
|
||||
out.push(ALPHABET[((triple >> 18) & 0x3f) as usize] as char);
|
||||
out.push(ALPHABET[((triple >> 12) & 0x3f) as usize] as char);
|
||||
out.push(if chunk.len() > 1 {
|
||||
ALPHABET[((triple >> 6) & 0x3f) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
out.push(if chunk.len() > 2 {
|
||||
ALPHABET[(triple & 0x3f) as usize] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base64_matches_known_vectors() {
|
||||
assert_eq!(base64_encode(b""), "");
|
||||
assert_eq!(base64_encode(b"f"), "Zg==");
|
||||
assert_eq!(base64_encode(b"fo"), "Zm8=");
|
||||
assert_eq!(base64_encode(b"foo"), "Zm9v");
|
||||
assert_eq!(
|
||||
base64_encode("开始文本\n".as_bytes()),
|
||||
"5byA5aeL5paH5pysCg=="
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_unselected_value_is_encoded() {
|
||||
let options = ObservationOptions {
|
||||
variables: vec!["visible".to_string()],
|
||||
..ObservationOptions::default()
|
||||
};
|
||||
let config = options.config();
|
||||
assert_eq!(config.level(), "values");
|
||||
assert!(config.selected_variables.contains("visible"));
|
||||
assert!(!config.allow_text_values);
|
||||
let empty = ObservationOptions::default().config();
|
||||
assert_eq!(empty.level(), "structural");
|
||||
assert!(!empty.values_enabled());
|
||||
}
|
||||
}
|
||||
+136
-14
@@ -7,6 +7,7 @@
|
||||
mod analysis;
|
||||
mod args;
|
||||
mod commands;
|
||||
mod execution_events;
|
||||
mod extension_descriptors;
|
||||
mod extension_selection;
|
||||
mod loader;
|
||||
@@ -34,6 +35,83 @@ struct Cli {
|
||||
command: Command,
|
||||
}
|
||||
|
||||
/// Execution Events v1 options (RFC-OBS-0001).
|
||||
///
|
||||
/// `--event-stream jsonl` makes the CLI stdout a dedicated NDJSON channel;
|
||||
/// program stdout/stderr become events. It is mutually exclusive with
|
||||
/// `--json` and is not accepted by static commands.
|
||||
#[derive(Args, Clone)]
|
||||
struct ObserveArgs {
|
||||
/// Stream Execution Events v1 as JSON Lines on stdout (only `jsonl`).
|
||||
#[arg(
|
||||
long = "event-stream",
|
||||
value_name = "FORMAT",
|
||||
value_parser = [execution_events::FORMAT_JSONL],
|
||||
conflicts_with = "json"
|
||||
)]
|
||||
event_stream: Option<String>,
|
||||
/// Publish the value of one exactly named local variable (repeatable).
|
||||
#[arg(
|
||||
long = "observe-variable",
|
||||
value_name = "NAME",
|
||||
requires = "event_stream"
|
||||
)]
|
||||
observe_variable: Vec<String>,
|
||||
/// Publish the value of one exactly named parameter (repeatable).
|
||||
#[arg(
|
||||
long = "observe-parameter",
|
||||
value_name = "NAME",
|
||||
requires = "event_stream"
|
||||
)]
|
||||
observe_parameter: Vec<String>,
|
||||
/// Allow selected Text values to be published (second explicit consent).
|
||||
#[arg(long = "observe-text-values", requires = "event_stream")]
|
||||
observe_text_values: bool,
|
||||
/// Maximum encoded source bytes for one observed value (0 = unlimited).
|
||||
#[arg(
|
||||
long = "observe-max-value-bytes",
|
||||
value_name = "BYTES",
|
||||
requires = "event_stream"
|
||||
)]
|
||||
observe_max_value_bytes: Option<usize>,
|
||||
/// Override the structural/value event budget (0 = unlimited).
|
||||
#[arg(
|
||||
long = "observe-max-events",
|
||||
value_name = "COUNT",
|
||||
requires = "event_stream"
|
||||
)]
|
||||
observe_max_events: Option<u64>,
|
||||
/// Override the approximate structural/value byte budget (0 = unlimited).
|
||||
#[arg(
|
||||
long = "observe-max-bytes",
|
||||
value_name = "BYTES",
|
||||
requires = "event_stream"
|
||||
)]
|
||||
observe_max_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl ObserveArgs {
|
||||
fn options(&self) -> Option<execution_events::ObservationOptions> {
|
||||
self.event_stream.as_ref()?;
|
||||
let mut options = execution_events::ObservationOptions {
|
||||
variables: self.observe_variable.clone(),
|
||||
parameters: self.observe_parameter.clone(),
|
||||
allow_text_values: self.observe_text_values,
|
||||
..execution_events::ObservationOptions::default()
|
||||
};
|
||||
if let Some(bytes) = self.observe_max_value_bytes {
|
||||
options.max_value_bytes = bytes;
|
||||
}
|
||||
if let Some(events) = self.observe_max_events {
|
||||
options.max_events = events;
|
||||
}
|
||||
if let Some(bytes) = self.observe_max_bytes {
|
||||
options.max_bytes = bytes;
|
||||
}
|
||||
Some(options)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Initialise a new Marqdo project.
|
||||
@@ -201,6 +279,8 @@ struct RunArgs {
|
||||
/// Include the host effect trace.
|
||||
#[arg(long)]
|
||||
trace: bool,
|
||||
#[command(flatten)]
|
||||
observe: ObserveArgs,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -220,6 +300,8 @@ struct CallArgs {
|
||||
/// Include the host effect trace.
|
||||
#[arg(long)]
|
||||
trace: bool,
|
||||
#[command(flatten)]
|
||||
observe: ObserveArgs,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -432,23 +514,31 @@ fn dispatch() -> i32 {
|
||||
};
|
||||
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
|
||||
}
|
||||
Command::Run(args) => commands::execute(
|
||||
args.file.as_deref(),
|
||||
None,
|
||||
&[],
|
||||
&args.sandbox.settings(),
|
||||
args.json,
|
||||
args.trace,
|
||||
),
|
||||
Command::Call(args) => match commands::parse_named_args(&args.args) {
|
||||
Ok(named) => commands::execute(
|
||||
Some(&args.file),
|
||||
Some(&args.function),
|
||||
&named,
|
||||
Command::Run(args) => {
|
||||
let observation = args.observe.options();
|
||||
commands::execute(
|
||||
args.file.as_deref(),
|
||||
None,
|
||||
&[],
|
||||
&args.sandbox.settings(),
|
||||
args.json,
|
||||
args.trace,
|
||||
),
|
||||
observation.as_ref(),
|
||||
)
|
||||
}
|
||||
Command::Call(args) => match commands::parse_named_args(&args.args) {
|
||||
Ok(named) => {
|
||||
let observation = args.observe.options();
|
||||
commands::execute(
|
||||
Some(&args.file),
|
||||
Some(&args.function),
|
||||
&named,
|
||||
&args.sandbox.settings(),
|
||||
args.json,
|
||||
args.trace,
|
||||
observation.as_ref(),
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
2
|
||||
@@ -479,3 +569,35 @@ fn dispatch() -> i32 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn top_level_commands_are_reviewed() {
|
||||
use clap::CommandFactory;
|
||||
|
||||
let cli = Cli::command();
|
||||
let mut names: Vec<_> = cli
|
||||
.get_subcommands()
|
||||
.map(|command| command.get_name())
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"__plugin-worker",
|
||||
"add",
|
||||
"call",
|
||||
"check",
|
||||
"fmt",
|
||||
"init",
|
||||
"inspect",
|
||||
"lock",
|
||||
"plugin",
|
||||
"remove",
|
||||
"run",
|
||||
"sync",
|
||||
"tool"
|
||||
],
|
||||
"review changes under ADR-0064"
|
||||
);
|
||||
}
|
||||
@@ -49,11 +49,10 @@ 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"];
|
||||
/// Core resource kinds are owned by the host and may never be overridden by a
|
||||
/// provider (RFC-EXT-0001 §5.3.1, ADR-0062). The single source of truth is
|
||||
/// [`marqdo_host::CORE_RESOURCE_KINDS`]; this alias keeps the CLI wording.
|
||||
pub const RESERVED_RESOURCE_KINDS: &[&str] = marqdo_host::CORE_RESOURCE_KINDS;
|
||||
|
||||
/// Raw `provider.json` schema version 2 document.
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -835,13 +834,26 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_kind_is_rejected() {
|
||||
fn every_core_kind_is_rejected_as_name_and_as_kind() {
|
||||
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);
|
||||
for core_kind in marqdo_host::CORE_RESOURCE_KINDS {
|
||||
let as_kind = write_manifest(
|
||||
&dir,
|
||||
&manifest_text("demo.sensor", &[core_kind], &path, &sha),
|
||||
);
|
||||
let error = read_provider_manifests(&[as_kind]).unwrap_err();
|
||||
assert_eq!(error.code, "ext.manifest_invalid");
|
||||
assert!(error.message.contains("reserved"), "{}", error.message);
|
||||
|
||||
let as_name = write_manifest(
|
||||
&dir,
|
||||
&manifest_text(core_kind, &["demo.sensor"], &path, &sha),
|
||||
);
|
||||
let error = read_provider_manifests(&[as_name]).unwrap_err();
|
||||
assert_eq!(error.code, "ext.manifest_invalid");
|
||||
assert!(error.message.contains("reserved"), "{}", error.message);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
+60
-13
@@ -46,25 +46,39 @@ impl StdlibBundle {
|
||||
/// Discover the bundle.
|
||||
///
|
||||
/// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid), a `stdlib`
|
||||
/// directory next to the executable, then the development tree.
|
||||
/// directory next to the executable, and finally — **debug builds only** — the
|
||||
/// compile-time source tree. A release binary never falls back to a build
|
||||
/// machine path: the release archive must ship a verified `stdlib/` next to
|
||||
/// the binary (RFC-EXT-0003 H-08, ADR).
|
||||
pub fn discover() -> Result<Option<Self>, String> {
|
||||
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
|
||||
return Self::load(PathBuf::from(dir)).map(Some);
|
||||
}
|
||||
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);
|
||||
}
|
||||
Self::discover_from_exe_dir(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(Path::to_path_buf)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Discover from the directory that holds the executable, without the explicit
|
||||
/// environment override. Release builds do not read the source tree.
|
||||
fn discover_from_exe_dir(exe_dir: Option<PathBuf>) -> Result<Option<Self>, String> {
|
||||
if let Some(parent) = exe_dir {
|
||||
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);
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("..")
|
||||
.join("..")
|
||||
.join("stdlib");
|
||||
if dev.is_dir() {
|
||||
return Self::load(dev).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
@@ -457,6 +471,39 @@ mod tests {
|
||||
assert!(bundle.resolve("../escape").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_stdlib_is_found_without_environment_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bundle = dir.path().join("stdlib");
|
||||
std::fs::create_dir_all(&bundle).unwrap();
|
||||
for entry in std::fs::read_dir(dev_bundle()).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let target = bundle.join(entry.file_name());
|
||||
if entry.path().is_dir() {
|
||||
copy_dir(&entry.path(), &target);
|
||||
} else {
|
||||
std::fs::copy(entry.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
|
||||
.unwrap()
|
||||
.expect("sibling stdlib");
|
||||
assert_eq!(found.root, bundle.canonicalize().unwrap());
|
||||
}
|
||||
|
||||
fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
|
||||
std::fs::create_dir_all(target).unwrap();
|
||||
for entry in std::fs::read_dir(source).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let destination = target.join(entry.file_name());
|
||||
if entry.path().is_dir() {
|
||||
copy_dir(&entry.path(), &destination);
|
||||
} else {
|
||||
std::fs::copy(entry.path(), destination).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_tamper_is_rejected() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+13
-8
@@ -21,15 +21,20 @@ pub fn write(
|
||||
entry: &str,
|
||||
status: &str,
|
||||
path: &Path,
|
||||
run_id: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let run_id = format!(
|
||||
"{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
);
|
||||
// A combined `--event-stream` run shares the CLI-generated opaque run id
|
||||
// with Execution Events v1; Trace v2 keeps its schema and field types.
|
||||
let run_id = run_id.map(str::to_string).unwrap_or_else(|| {
|
||||
format!(
|
||||
"{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0)
|
||||
)
|
||||
});
|
||||
let analysis_digest = crate::analysis::digest(project);
|
||||
let root_id = project.identity.root_id();
|
||||
let state = host.trace_state();
|
||||
|
||||
@@ -30,7 +30,6 @@ const WORKSPACE_CRATES: &[&str] = &[
|
||||
"marqdo-markdown",
|
||||
"marqdo-ir",
|
||||
"marqdo-frontend",
|
||||
"marqdo-math",
|
||||
"marqdo-foreign",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-provider-worker",
|
||||
@@ -315,26 +314,90 @@ fn callable_binding_is_the_only_static_resolution_path() {
|
||||
);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// ADR-0064 freezes the core catalogue until a new language primitive is reviewed.
|
||||
#[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"
|
||||
fn builtin_names_and_aliases_are_reviewed() {
|
||||
let builtins = marqdo_ir::builtins::BUILTINS;
|
||||
let mut names: Vec<_> = builtins
|
||||
.iter()
|
||||
.flat_map(|builtin| std::iter::once(builtin.name).chain(builtin.aliases.iter().copied()))
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"float",
|
||||
"foreign.call",
|
||||
"foreign.run",
|
||||
"fs.read",
|
||||
"fs.write",
|
||||
"int",
|
||||
"len",
|
||||
"list.append",
|
||||
"list.concat",
|
||||
"map.get",
|
||||
"map.has",
|
||||
"map.keys",
|
||||
"map.remove",
|
||||
"map.set",
|
||||
"memory.grow",
|
||||
"memory.new",
|
||||
"memory.size",
|
||||
"print",
|
||||
"ref",
|
||||
"resource.accept",
|
||||
"resource.close",
|
||||
"resource.open",
|
||||
"resource.read",
|
||||
"resource.request",
|
||||
"resource.write",
|
||||
"str",
|
||||
"table",
|
||||
"table.cell",
|
||||
"table.columns",
|
||||
"table.row",
|
||||
"text.codepoints",
|
||||
"text.from_codepoint",
|
||||
"type",
|
||||
"小数",
|
||||
"打印",
|
||||
"整数",
|
||||
"文本",
|
||||
"类型",
|
||||
"表",
|
||||
"长度",
|
||||
],
|
||||
"review changes under ADR-0064"
|
||||
);
|
||||
}
|
||||
|
||||
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
|
||||
const _: fn(marqdo_host::HostOp) = |operation| match operation {
|
||||
marqdo_host::HostOp::ForeignRun
|
||||
| marqdo_host::HostOp::ForeignCall
|
||||
| marqdo_host::HostOp::FsRead
|
||||
| marqdo_host::HostOp::FsWrite
|
||||
| marqdo_host::HostOp::PluginInvoke => (),
|
||||
};
|
||||
|
||||
const _: fn(marqdo_value::Value) = |value| match value {
|
||||
marqdo_value::Value::Unit
|
||||
| marqdo_value::Value::None
|
||||
| marqdo_value::Value::Bool(_)
|
||||
| marqdo_value::Value::Int(_)
|
||||
| marqdo_value::Value::Float(_)
|
||||
| marqdo_value::Value::Text(_)
|
||||
| marqdo_value::Value::List(_)
|
||||
| marqdo_value::Value::Map(_)
|
||||
| marqdo_value::Value::Table(_)
|
||||
| marqdo_value::Value::Formula(_)
|
||||
| marqdo_value::Value::Code(_)
|
||||
| marqdo_value::Value::FunctionRef(_)
|
||||
| marqdo_value::Value::PluginHandle(_)
|
||||
| marqdo_value::Value::Memory(_)
|
||||
| marqdo_value::Value::Resource(_) => (),
|
||||
};
|
||||
|
||||
/// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not
|
||||
/// hard-coded runtime names. Recompute the canonical metadata digest.
|
||||
#[test]
|
||||
@@ -387,6 +450,84 @@ fn official_stdlib_public_aliases_are_verified_metadata() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outer match in the compatibility dispatcher is the operation catalogue.
|
||||
#[test]
|
||||
fn resource_request_operation_allowlist_is_reviewed() {
|
||||
let source = read(&repo_root().join("crates/marqdo-host/src/host/resource_requests.rs"));
|
||||
let dispatch = source
|
||||
.split_once(" match operation {\n")
|
||||
.expect("closed operation dispatch")
|
||||
.1
|
||||
.split_once("\n _ =>")
|
||||
.expect("unknown operations must reach a rejection arm")
|
||||
.0;
|
||||
let mut names: Vec<_> = dispatch
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" "))
|
||||
.filter(|line| line.starts_with('"') || line.starts_with('|'))
|
||||
.flat_map(|line| line.split('"').skip(1).step_by(2))
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"clock.now",
|
||||
"compress.gunzip",
|
||||
"compress.gzip",
|
||||
"env.get",
|
||||
"fs.append",
|
||||
"fs.exists",
|
||||
"fs.list",
|
||||
"fs.metadata",
|
||||
"fs.mkdir",
|
||||
"fs.read_at",
|
||||
"fs.remove",
|
||||
"fs.rename",
|
||||
"fs.walk",
|
||||
"process.run",
|
||||
"random.bytes",
|
||||
"regex.captures",
|
||||
"regex.match",
|
||||
],
|
||||
"review changes under ADR-0062 and ADR-0064"
|
||||
);
|
||||
}
|
||||
|
||||
/// RFC-EXT-0003 H-01: the CLI/host must not link the removed domain math
|
||||
/// kernel and `resource_request` must not dispatch a math.* domain operation.
|
||||
#[test]
|
||||
fn domain_math_kernel_is_not_part_of_the_core() {
|
||||
let root = repo_root();
|
||||
for manifest in [
|
||||
"Cargo.toml",
|
||||
"crates/marqdo-host/Cargo.toml",
|
||||
"crates/cli/Cargo.toml",
|
||||
] {
|
||||
let text = read(&root.join(manifest));
|
||||
assert!(
|
||||
!text.contains("marqdo-math"),
|
||||
"{manifest} must not depend on the removed domain math kernel"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!root.join("crates/marqdo-math").exists(),
|
||||
"crates/marqdo-math was removed from the core repository"
|
||||
);
|
||||
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
|
||||
for removed in [
|
||||
"MathEval",
|
||||
"MathParse",
|
||||
"MathSubstitute",
|
||||
"MathSimplify",
|
||||
"MathDifferentiate",
|
||||
] {
|
||||
assert!(
|
||||
!host.contains(removed),
|
||||
"host.rs still dispatches {removed}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
|
||||
@@ -140,12 +140,12 @@ fn stdout(output: &Output) -> String {
|
||||
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",
|
||||
&dir.path().join("resource.mq.md"),
|
||||
"## @exec select\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",
|
||||
"---\nimport:\n resource: \"./resource.mq.md\"\n---\n\n## @exec main\n\n`return resource.select(a=1)`\n",
|
||||
);
|
||||
let check = cli(&["check", "index.mq.md"], dir.path());
|
||||
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
|
||||
|
||||
@@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() {
|
||||
|
||||
#[test]
|
||||
fn public_schemas_are_valid_json_and_versioned() {
|
||||
for name in ["analysis-v1", "trace-v1", "tool-v1"] {
|
||||
for name in ["analysis-v1", "trace-v1", "tool-v1", "execution-events-v1"] {
|
||||
let path = repo()
|
||||
.join("spec/schemas")
|
||||
.join(format!("{name}.schema.json"));
|
||||
|
||||
@@ -0,0 +1,767 @@
|
||||
//! Black-box Execution Events v1 contract tests (RFC-OBS-0001).
|
||||
//!
|
||||
//! These drive the real `marqdo` binary (`CARGO_BIN_EXE_marqdo`) and parse the
|
||||
//! stdout line stream exactly like an external consumer. They cover the P0
|
||||
//! envelope/lifecycle/byte-fidelity contract and the P1 frame/value policy,
|
||||
//! plus trace coexistence, truncation, live delivery and a broken pipe.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const BASIC: &str =
|
||||
"## @exec main\n\n`打印(\"START\")`\n\n`n = 10`\n\n`打印(\"DONE\")`\n\n`return n`\n";
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"marqdo-execution-events-{tag}-{}-{nanos}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, source: &str) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
fs::write(&path, source).unwrap();
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli(dir: &Path, args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.expect("run marqdo")
|
||||
}
|
||||
|
||||
fn parse_events(stdout: &[u8]) -> Vec<Value> {
|
||||
String::from_utf8_lossy(stdout)
|
||||
.lines()
|
||||
.map(|line| {
|
||||
serde_json::from_str(line)
|
||||
.unwrap_or_else(|error| panic!("invalid JSONL line {line:?}: {error}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn events_of<'a>(events: &'a [Value], kind: &str) -> Vec<&'a Value> {
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| event["kind"] == kind)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn chunk_bytes(events: &[Value], kind: &str) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for event in events_of(events, kind) {
|
||||
let payload = &event["payload"];
|
||||
assert_eq!(payload["encoding"], "base64");
|
||||
let data = base64_decode(payload["data_base64"].as_str().unwrap());
|
||||
assert_eq!(
|
||||
payload["byte_count"].as_u64().unwrap() as usize,
|
||||
data.len(),
|
||||
"byte_count must equal decoded length"
|
||||
);
|
||||
out.extend(data);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn base64_decode(text: &str) -> Vec<u8> {
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = Vec::new();
|
||||
let bytes: Vec<u8> = text
|
||||
.bytes()
|
||||
.filter(|byte| *byte != b'=')
|
||||
.map(|byte| {
|
||||
ALPHABET
|
||||
.iter()
|
||||
.position(|item| *item == byte)
|
||||
.unwrap_or_else(|| panic!("invalid base64 byte {byte}")) as u8
|
||||
})
|
||||
.collect();
|
||||
for chunk in bytes.chunks(4) {
|
||||
let mut triple = 0u32;
|
||||
for (index, byte) in chunk.iter().enumerate() {
|
||||
triple |= u32::from(*byte) << (18 - 6 * index);
|
||||
}
|
||||
out.push((triple >> 16) as u8);
|
||||
if chunk.len() > 2 {
|
||||
out.push((triple >> 8) as u8);
|
||||
}
|
||||
if chunk.len() > 3 {
|
||||
out.push(triple as u8);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_envelope(events: &[Value]) {
|
||||
assert!(!events.is_empty());
|
||||
let first = &events[0];
|
||||
assert_eq!(first["kind"], "stream.opened");
|
||||
assert_eq!(first["schema"], "marqdo.execution-events");
|
||||
assert_eq!(first["schema_version"], 1);
|
||||
assert_eq!(first["seq"], 0);
|
||||
let run_id = first["run_id"].as_str().unwrap().to_string();
|
||||
for (index, event) in events.iter().enumerate() {
|
||||
assert_eq!(event["seq"].as_u64().unwrap(), index as u64);
|
||||
assert_eq!(event["run_id"], run_id);
|
||||
assert_eq!(event["schema_version"], 1);
|
||||
assert!(event["payload"].is_object());
|
||||
}
|
||||
let terminals: Vec<&str> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event["kind"].as_str().unwrap() {
|
||||
"run.completed" | "run.failed" | "run.rejected" => {
|
||||
Some(event["kind"].as_str().unwrap())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(terminals.len(), 1, "exactly one terminal event");
|
||||
assert_eq!(events.last().unwrap()["kind"], terminals[0]);
|
||||
assert_eq!(events_of(events, "stream.opened").len(), 1);
|
||||
assert!(events_of(events, "run.started").len() <= 1);
|
||||
}
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn python_consumer_available() -> bool {
|
||||
Command::new("python3")
|
||||
.args(["-c", "import jsonschema"])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_in_fixtures_validate_against_the_public_schema() {
|
||||
if !python_consumer_available() {
|
||||
eprintln!("python3 + jsonschema unavailable; schema consumer skipped");
|
||||
return;
|
||||
}
|
||||
let fixtures = repo_root().join("tests/consumers/fixtures/execution-events");
|
||||
let consumer = repo_root().join("tests/consumers/execution_events_consumer.py");
|
||||
for name in ["minimal.jsonl", "full.jsonl"] {
|
||||
let path = fixtures.join("valid").join(name);
|
||||
let output = Command::new("python3")
|
||||
.arg(&consumer)
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("run execution events consumer");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"valid fixture {name} rejected: {}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
}
|
||||
for entry in fs::read_dir(fixtures.join("invalid")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let output = Command::new("python3")
|
||||
.arg(&consumer)
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("run execution events consumer");
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"invalid fixture {} was accepted",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_fixture_attributes_repeated_recursive_frames() {
|
||||
let dir = TempDir::new("structure");
|
||||
let source = fs::read_to_string(
|
||||
repo_root().join("tests/consumers/fixtures/execution-events/structure.mq.md"),
|
||||
)
|
||||
.unwrap();
|
||||
dir.write("index.mq.md", &source);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-max-events",
|
||||
"1000",
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
assert_eq!(events.last().unwrap()["payload"]["value"]["decimal"], "3");
|
||||
|
||||
let enters = events_of(&events, "call.enter");
|
||||
assert_eq!(enters.len(), 4, "main + f(2) + g(2) + f(0)");
|
||||
let frames: Vec<&str> = enters
|
||||
.iter()
|
||||
.map(|event| event["payload"]["frame_id"].as_str().unwrap())
|
||||
.collect();
|
||||
let unique: std::collections::BTreeSet<&str> = frames.iter().copied().collect();
|
||||
assert_eq!(unique.len(), 4, "frame identities are run-unique");
|
||||
let main = enters[0]["payload"]["frame_id"].as_str().unwrap();
|
||||
assert!(enters[0]["payload"]["parent_frame_id"].is_null());
|
||||
let f2 = enters[1]["payload"]["frame_id"].as_str().unwrap();
|
||||
let g2 = enters[2]["payload"]["frame_id"].as_str().unwrap();
|
||||
let f0 = enters[3]["payload"]["frame_id"].as_str().unwrap();
|
||||
assert_eq!(enters[1]["payload"]["parent_frame_id"], main);
|
||||
assert_eq!(enters[2]["payload"]["parent_frame_id"], f2);
|
||||
assert_eq!(enters[3]["payload"]["parent_frame_id"], main);
|
||||
let exit_frames: Vec<&str> = events_of(&events, "call.exit")
|
||||
.iter()
|
||||
.map(|event| event["payload"]["frame_id"].as_str().unwrap())
|
||||
.collect();
|
||||
for frame in [main, f2, g2, f0] {
|
||||
assert!(exit_frames.contains(&frame), "frame {frame} must close");
|
||||
}
|
||||
assert_eq!(events_of(&events, "branch.eval").len(), 2);
|
||||
assert_eq!(
|
||||
events_of(&events, "loop.iteration")
|
||||
.iter()
|
||||
.map(|event| event["payload"]["decision"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["continue", "continue", "exit"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_plugin_is_fail_closed_in_event_mode() {
|
||||
use sha2::Digest;
|
||||
let dir = TempDir::new("native-plugin");
|
||||
dir.write("index.mq.md", "## @exec main\n\n`return 1`\n");
|
||||
let plugin_dir = dir.path().join("plugin");
|
||||
fs::create_dir_all(&plugin_dir).unwrap();
|
||||
let artifact = plugin_dir.join("solver.so");
|
||||
fs::write(&artifact, b"not-a-real-library").unwrap();
|
||||
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
|
||||
let manifest = format!(
|
||||
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
|
||||
marqdo_plugin_abi::HostTarget::current().triple(),
|
||||
digest
|
||||
);
|
||||
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--plugin",
|
||||
plugin_dir.join("plugin.yaml").to_str().unwrap(),
|
||||
"--allow-plugin",
|
||||
"demo.solver",
|
||||
],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
let terminal = events.last().unwrap();
|
||||
assert_eq!(terminal["kind"], "run.rejected");
|
||||
assert_eq!(
|
||||
terminal["payload"]["error"]["code"],
|
||||
"ext.event_stream_unsupported_native_plugin"
|
||||
);
|
||||
assert!(
|
||||
events_of(&events, "run.started").is_empty(),
|
||||
"the native plugin is rejected before execution"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_values_never_enter_trace_v2() {
|
||||
let dir = TempDir::new("trace-redaction");
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
|
||||
);
|
||||
let trace_path = dir.path().join("trace.json");
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-variable",
|
||||
"secret_token",
|
||||
"--observe-text-values",
|
||||
"--trace-file",
|
||||
trace_path.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stdout).contains("DO_NOT_LEAK_SENTINEL_1"),
|
||||
"the explicit event consent publishes the selected value in the stream"
|
||||
);
|
||||
let trace = fs::read(&trace_path).unwrap();
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&trace).contains("DO_NOT_LEAK_SENTINEL_1"),
|
||||
"Trace v2 must not gain observed values"
|
||||
);
|
||||
let trace: Value = serde_json::from_slice(&trace).unwrap();
|
||||
assert_eq!(trace["schema"], "marqdo.trace");
|
||||
assert_eq!(trace["schema_version"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() {
|
||||
let dir = TempDir::new("basic");
|
||||
dir.write("index.mq.md", BASIC);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&["run", "index.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
assert_eq!(events_of(&events, "run.started").len(), 1);
|
||||
assert_eq!(chunk_bytes(&events, "stdout.chunk"), b"START\nDONE\n");
|
||||
let terminal = events.last().unwrap();
|
||||
assert_eq!(terminal["kind"], "run.completed");
|
||||
assert_eq!(terminal["payload"]["status"], "ok");
|
||||
assert_eq!(terminal["payload"]["value"]["decimal"], "10");
|
||||
// Terminal sequence is after all chunk sequences.
|
||||
let terminal_seq = terminal["seq"].as_u64().unwrap();
|
||||
for event in events_of(&events, "stdout.chunk") {
|
||||
assert!(event["seq"].as_u64().unwrap() < terminal_seq);
|
||||
}
|
||||
|
||||
// The normal (non-event) run writes the same bytes and return value.
|
||||
let normal = cli(dir.path(), &["run", "index.mq.md"]);
|
||||
assert_eq!(normal.status.code(), Some(0));
|
||||
assert_eq!(normal.stdout, b"START\nDONE\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_stream_rejects_mixed_json_and_static_commands() {
|
||||
let dir = TempDir::new("reject");
|
||||
dir.write("index.mq.md", BASIC);
|
||||
let mixed = cli(
|
||||
dir.path(),
|
||||
&["run", "index.mq.md", "--event-stream", "jsonl", "--json"],
|
||||
);
|
||||
assert_eq!(mixed.status.code(), Some(2));
|
||||
assert!(mixed.stdout.is_empty(), "no mixed stdout");
|
||||
assert!(String::from_utf8_lossy(&mixed.stderr).contains("--json"));
|
||||
|
||||
for command in ["check", "inspect"] {
|
||||
let rejected = cli(
|
||||
dir.path(),
|
||||
&[command, "index.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(
|
||||
rejected.status.code(),
|
||||
Some(2),
|
||||
"{command} must reject the option"
|
||||
);
|
||||
assert!(rejected.stdout.is_empty(), "{command} must not execute");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_and_runtime_failures_have_defined_terminals() {
|
||||
let dir = TempDir::new("failures");
|
||||
dir.write("broken.mq.md", "## @exec main\n\n`if true`\n\n`return 1`\n");
|
||||
let rejected = cli(
|
||||
dir.path(),
|
||||
&["run", "broken.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(rejected.status.code(), Some(1));
|
||||
let events = parse_events(&rejected.stdout);
|
||||
assert_envelope(&events);
|
||||
assert_eq!(events.last().unwrap()["kind"], "run.rejected");
|
||||
assert_eq!(events.last().unwrap()["payload"]["phase"], "compile");
|
||||
assert!(
|
||||
events_of(&events, "run.started").is_empty(),
|
||||
"a rejected run never starts"
|
||||
);
|
||||
|
||||
dir.write(
|
||||
"runtime.mq.md",
|
||||
"## @exec main\n\n`x = 1 / 0`\n\n`return x`\n",
|
||||
);
|
||||
let failed = cli(
|
||||
dir.path(),
|
||||
&["run", "runtime.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(failed.status.code(), Some(1));
|
||||
let events = parse_events(&failed.stdout);
|
||||
assert_envelope(&events);
|
||||
assert_eq!(events.last().unwrap()["kind"], "run.failed");
|
||||
assert_eq!(
|
||||
events.last().unwrap()["payload"]["error"]["code"],
|
||||
"runtime.division_by_zero"
|
||||
);
|
||||
assert!(events_of(&events, "run.completed").is_empty());
|
||||
let exit = events_of(&events, "call.exit");
|
||||
assert_eq!(exit.len(), 1, "failure still closes the entered frame");
|
||||
assert_eq!(exit[0]["payload"]["status"], "runtime.division_by_zero");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_observation_is_exact_and_requires_text_consent() {
|
||||
let dir = TempDir::new("values");
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
|
||||
);
|
||||
// Default: metadata only; no value, no sentinel anywhere.
|
||||
let default = cli(
|
||||
dir.path(),
|
||||
&["run", "index.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(default.status.code(), Some(0));
|
||||
assert!(!String::from_utf8_lossy(&default.stdout).contains("DO_NOT_LEAK_SENTINEL_1"));
|
||||
for event in events_of(&parse_events(&default.stdout), "variable.assigned") {
|
||||
assert_eq!(event["payload"]["value_state"], "not_requested");
|
||||
assert!(event["payload"].get("value").is_none());
|
||||
}
|
||||
|
||||
let selected = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-variable",
|
||||
"visible_count",
|
||||
],
|
||||
);
|
||||
let events = parse_events(&selected.stdout);
|
||||
let visible = events_of(&events, "variable.assigned")
|
||||
.into_iter()
|
||||
.find(|event| event["payload"]["name"] == "visible_count")
|
||||
.expect("visible_count event");
|
||||
assert_eq!(visible["payload"]["value_state"], "observed");
|
||||
assert_eq!(visible["payload"]["value"]["decimal"], "42");
|
||||
// The unselected variable must never carry a value.
|
||||
for event in events_of(&events, "variable.assigned") {
|
||||
if event["payload"]["name"] == "secret_token" {
|
||||
assert_eq!(event["payload"]["value_state"], "not_requested");
|
||||
assert!(event["payload"].get("value").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
// Selecting the text variable is not enough: the bytes stay redacted.
|
||||
let redacted = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-variable",
|
||||
"secret_token",
|
||||
],
|
||||
);
|
||||
assert!(!String::from_utf8_lossy(&redacted.stdout).contains("DO_NOT_LEAK_SENTINEL_1"));
|
||||
let events = parse_events(&redacted.stdout);
|
||||
let secret = events_of(&events, "variable.assigned")
|
||||
.into_iter()
|
||||
.find(|event| event["payload"]["name"] == "secret_token")
|
||||
.expect("secret_token event");
|
||||
assert_eq!(secret["payload"]["value_state"], "redacted");
|
||||
assert!(secret["payload"].get("value").is_none());
|
||||
|
||||
// A second explicit consent publishes only the selected value.
|
||||
let consented = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-variable",
|
||||
"secret_token",
|
||||
"--observe-text-values",
|
||||
],
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&consented.stdout);
|
||||
assert!(stdout.contains("DO_NOT_LEAK_SENTINEL_1"));
|
||||
let events = parse_events(&consented.stdout);
|
||||
let secret = events_of(&events, "variable.assigned")
|
||||
.into_iter()
|
||||
.find(|event| event["payload"]["name"] == "secret_token")
|
||||
.unwrap();
|
||||
assert_eq!(secret["payload"]["value_state"], "observed");
|
||||
assert_eq!(
|
||||
secret["payload"]["value"]["value"],
|
||||
"DO_NOT_LEAK_SENTINEL_1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_and_multibyte_output_is_byte_exact() {
|
||||
let dir = TempDir::new("bytes");
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
"## @exec main\n\n`打印(\"开始文本\")`\n\n`流 = resource.open(\"stdio\", \"stdout\", [\"write\"])`\n\n`内存 = memory.new(1, 1)`\n\n`内存[0] = 255`\n\n`内存[1] = 0`\n\n`内存[2] = 128`\n\n`写入 = resource.write(流, 内存, 0, 3)`\n\n`关闭 = resource.close(流)`\n\n`return 写入`\n",
|
||||
);
|
||||
let normal = cli(dir.path(), &["run", "index.mq.md"]);
|
||||
assert_eq!(
|
||||
normal.status.code(),
|
||||
Some(0),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&normal.stderr)
|
||||
);
|
||||
let streamed = cli(
|
||||
dir.path(),
|
||||
&["run", "index.mq.md", "--event-stream", "jsonl"],
|
||||
);
|
||||
assert_eq!(streamed.status.code(), Some(0));
|
||||
let events = parse_events(&streamed.stdout);
|
||||
let chunks = chunk_bytes(&events, "stdout.chunk");
|
||||
assert_eq!(
|
||||
chunks, normal.stdout,
|
||||
"error text may not go to stdout; concatenated chunks must equal the program bytes"
|
||||
);
|
||||
assert!(chunks.starts_with("开始文本".as_bytes()));
|
||||
assert_eq!(&chunks[chunks.len() - 3..], &[0xff, 0x00, 0x80]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_file_coexists_and_shares_the_run_identity() {
|
||||
let dir = TempDir::new("trace");
|
||||
dir.write("index.mq.md", BASIC);
|
||||
let trace_path = dir.path().join("trace.json");
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--trace-file",
|
||||
trace_path.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
let trace: Value = serde_json::from_slice(&fs::read(&trace_path).unwrap()).unwrap();
|
||||
assert_eq!(trace["schema"], "marqdo.trace");
|
||||
assert_eq!(trace["schema_version"], 2);
|
||||
assert_eq!(trace["run"]["id"], events[0]["run_id"]);
|
||||
let started = events_of(&events, "run.started")[0];
|
||||
assert_eq!(
|
||||
started["payload"]["source"]["analysis_digest"],
|
||||
trace["source"]["analysis_digest"]
|
||||
);
|
||||
assert!(
|
||||
events_of(&events, "run.completed").len() == 1,
|
||||
"trace writing does not suppress the terminal event"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_budget_truncates_without_losing_critical_events() {
|
||||
let dir = TempDir::new("budget");
|
||||
dir.write("index.mq.md", BASIC);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-max-events",
|
||||
"5",
|
||||
],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
let markers = events_of(&events, "observation.truncated");
|
||||
assert_eq!(markers.len(), 1);
|
||||
assert_eq!(markers[0]["payload"]["reason"], "event_budget");
|
||||
assert_eq!(chunk_bytes(&events, "stdout.chunk"), b"START\nDONE\n");
|
||||
assert_eq!(events.last().unwrap()["kind"], "run.completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_budget_still_fails_the_run_and_emits_no_chunk() {
|
||||
let dir = TempDir::new("output-budget");
|
||||
dir.write("index.mq.md", BASIC);
|
||||
let output = cli(
|
||||
dir.path(),
|
||||
&[
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--max-output",
|
||||
"3",
|
||||
],
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
let events = parse_events(&output.stdout);
|
||||
assert_envelope(&events);
|
||||
assert!(chunk_bytes(&events, "stdout.chunk").is_empty());
|
||||
assert_eq!(events.last().unwrap()["kind"], "run.failed");
|
||||
assert_eq!(
|
||||
events.last().unwrap()["payload"]["error"]["code"],
|
||||
"resource.exhausted"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_chunks_arrive_while_the_program_is_still_running() {
|
||||
let dir = TempDir::new("live");
|
||||
let source = "## @exec main\n\n`打印(\"READY\")`\n\n`i = 0`\n\n`while i < 2000000`\n\n`i = i + 1`\n\n`end`\n\n`打印(\"FINISH\")`\n\n`return i`\n";
|
||||
dir.write("index.mq.md", source);
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args([
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-max-events",
|
||||
"20",
|
||||
"--fuel",
|
||||
"100000000",
|
||||
])
|
||||
.current_dir(dir.path())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn marqdo");
|
||||
let mut reader = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut events = Vec::new();
|
||||
let mut ready_seen_alive = false;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
let read = reader.read_line(&mut line).expect("read event line");
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
let event: Value = serde_json::from_str(line.trim_end()).expect("event JSON");
|
||||
if event["kind"] == "stdout.chunk" {
|
||||
let data = base64_decode(event["payload"]["data_base64"].as_str().unwrap());
|
||||
if data == b"READY\n" || data == b"READY" {
|
||||
assert!(
|
||||
child.try_wait().expect("try_wait").is_none(),
|
||||
"READY was only readable after the process exited; this is not live output"
|
||||
);
|
||||
ready_seen_alive = true;
|
||||
}
|
||||
}
|
||||
events.push(event);
|
||||
}
|
||||
let status = child.wait().expect("wait");
|
||||
assert_eq!(status.code(), Some(0));
|
||||
assert!(
|
||||
ready_seen_alive,
|
||||
"the READY chunk must be readable before the process exits"
|
||||
);
|
||||
assert_eq!(chunk_bytes(&events, "stdout.chunk"), b"READY\nFINISH\n");
|
||||
assert_eq!(events.last().unwrap()["kind"], "run.completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
|
||||
let dir = TempDir::new("pipe");
|
||||
let source = "## @exec main\n\n`打印(\"START\")`\n\n`i = 0`\n\n`while i < 5000000`\n\n`i = i + 1`\n\n`end`\n\n`return i`\n";
|
||||
dir.write("index.mq.md", source);
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args([
|
||||
"run",
|
||||
"index.mq.md",
|
||||
"--event-stream",
|
||||
"jsonl",
|
||||
"--observe-max-events",
|
||||
"10",
|
||||
"--fuel",
|
||||
"100000000",
|
||||
])
|
||||
.current_dir(dir.path())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn marqdo");
|
||||
{
|
||||
let mut reader = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("read one line");
|
||||
assert!(line.contains("stream.opened"));
|
||||
// Dropping the reader closes the pipe; the next write must fail.
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
loop {
|
||||
match child.try_wait().expect("try_wait") {
|
||||
Some(status) => {
|
||||
assert_ne!(
|
||||
status.code(),
|
||||
Some(0),
|
||||
"a broken event pipe must fail the run"
|
||||
);
|
||||
break;
|
||||
}
|
||||
None if Instant::now() > deadline => {
|
||||
let _ = child.kill();
|
||||
panic!("the run kept executing after its event pipe was closed");
|
||||
}
|
||||
None => std::thread::sleep(Duration::from_millis(20)),
|
||||
}
|
||||
}
|
||||
let mut stderr = String::new();
|
||||
child
|
||||
.stderr
|
||||
.take()
|
||||
.unwrap()
|
||||
.read_to_string(&mut stderr)
|
||||
.unwrap();
|
||||
assert!(
|
||||
stderr.contains("observe.transport_failed"),
|
||||
"expected a transport diagnostic on stderr: {stderr}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Black-box regression tests for RFC-EXT-0003 H-06 sibling heading modes.
|
||||
//!
|
||||
//! A heading that does not declare `@exec`/`@knowledge` inherits its nearest
|
||||
//! *ancestor*, never the previous sibling. These tests drive the real `marqdo`
|
||||
//! binary and assert that `check --emit`, `run` and `call` agree.
|
||||
|
||||
#![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-heading-test-{}-{id}-{tag}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, text: &str) {
|
||||
std::fs::write(self.0.join(name), text).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
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 units(document: &serde_json::Value) -> Vec<&serde_json::Value> {
|
||||
document["modules"][0]["units"]
|
||||
.as_array()
|
||||
.expect("units array")
|
||||
.iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn unit<'a>(document: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
|
||||
units(document)
|
||||
.into_iter()
|
||||
.find(|unit| unit["name"] == name)
|
||||
.unwrap_or_else(|| panic!("missing unit {name}"))
|
||||
}
|
||||
|
||||
fn exec_document() -> &'static str {
|
||||
"# @knowledge 数学\n\n## @exec main\n\n`return 1`\n\n## 普通说明\n\n这段是知识叙述。\n"
|
||||
}
|
||||
|
||||
fn knowledge_document() -> &'static str {
|
||||
"# @exec 项目\n\n## @knowledge 解释\n\n背景。\n\n## main\n\n`return 2`\n"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_emit_marks_unmarked_sibling_knowledge() {
|
||||
let dir = TempDir::new("emit-knowledge");
|
||||
dir.write("index.mq.md", exec_document());
|
||||
let analysis = dir.path().join("analysis.json");
|
||||
let check = cli(
|
||||
&["check", "index.mq.md", "--emit", analysis.to_str().unwrap()],
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(&analysis).unwrap()).unwrap();
|
||||
assert_eq!(unit(&document, "数学")["kind"], "namespace");
|
||||
assert_eq!(unit(&document, "main")["kind"], "function");
|
||||
assert_eq!(unit(&document, "普通说明")["kind"], "knowledge");
|
||||
assert!(unit(&document, "普通说明")["function"].is_null());
|
||||
// The analysis exposes exactly one function and it is the Exec sibling.
|
||||
let functions = document["modules"][0]["functions"].as_array().unwrap();
|
||||
assert_eq!(functions.len(), 1);
|
||||
assert_eq!(functions[0]["local_name"], "main");
|
||||
assert_eq!(functions[0]["namespace"], "数学");
|
||||
assert_eq!(functions[0]["unit_id"], unit(&document, "main")["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_emit_marks_unmarked_sibling_exec() {
|
||||
let dir = TempDir::new("emit-exec");
|
||||
dir.write("index.mq.md", knowledge_document());
|
||||
let analysis = dir.path().join("analysis.json");
|
||||
let check = cli(
|
||||
&["check", "index.mq.md", "--emit", analysis.to_str().unwrap()],
|
||||
dir.path(),
|
||||
);
|
||||
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
|
||||
let document: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(analysis).unwrap()).unwrap();
|
||||
assert_eq!(unit(&document, "解释")["kind"], "knowledge");
|
||||
assert_eq!(unit(&document, "main")["kind"], "function");
|
||||
let functions = document["modules"][0]["functions"].as_array().unwrap();
|
||||
assert_eq!(functions.len(), 1);
|
||||
assert_eq!(functions[0]["local_name"], "main");
|
||||
assert_eq!(functions[0]["namespace"], "项目");
|
||||
assert_eq!(functions[0]["unit_id"], unit(&document, "main")["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_and_call_not_callable_knowledge_sibling() {
|
||||
let dir = TempDir::new("call");
|
||||
dir.write("index.mq.md", exec_document());
|
||||
let run = cli(&["run", "index.mq.md"], dir.path());
|
||||
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
|
||||
// `run` streams program stdout only; the returned value is reported by
|
||||
// `call`, whose output is asserted below and must agree.
|
||||
assert!(stdout(&run).is_empty());
|
||||
|
||||
let call = cli(&["call", "index.mq.md", "数学.main"], dir.path());
|
||||
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
|
||||
assert_eq!(stdout(&call), "1\n");
|
||||
|
||||
let knowledge_sibling = cli(&["call", "index.mq.md", "数学.普通说明"], dir.path());
|
||||
assert_eq!(knowledge_sibling.status.code(), Some(1));
|
||||
assert!(
|
||||
stderr(&knowledge_sibling).contains("sem.no_entry_function"),
|
||||
"{}",
|
||||
stderr(&knowledge_sibling)
|
||||
);
|
||||
assert!(stdout(&knowledge_sibling).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_function_run_and_call_agree() {
|
||||
let dir = TempDir::new("exec");
|
||||
dir.write("index.mq.md", knowledge_document());
|
||||
let run = cli(&["run", "index.mq.md"], dir.path());
|
||||
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
|
||||
assert!(stdout(&run).is_empty());
|
||||
|
||||
let call = cli(&["call", "index.mq.md", "项目.main"], dir.path());
|
||||
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
|
||||
assert_eq!(stdout(&call), "2\n");
|
||||
|
||||
let knowledge = cli(&["call", "index.mq.md", "项目.解释"], dir.path());
|
||||
assert_eq!(knowledge.status.code(), Some(1));
|
||||
assert!(stderr(&knowledge).contains("sem.no_entry_function"));
|
||||
}
|
||||
@@ -653,7 +653,7 @@ fn multi_module_imports_and_cycles() {
|
||||
let dir = TempDir::new("modules");
|
||||
dir.write(
|
||||
"geometry.mq.md",
|
||||
"## @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",
|
||||
"## @exec 圆面积\n\n`params(r: Number)`\n\n`return 3.141592653589793 * r * r`\n\n### @knowledge 公式\n\n$$\nA = \\pi r^2\n$$\n",
|
||||
);
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! RFC-EXT-0003 H-01 / T-MATH-01..06: the core has no `math.*` domain
|
||||
//! builtins; algorithms live in pure `.mq.md` packages and optionally in an
|
||||
//! explicitly selected ABI backend. This test drives the real CLI binary and the
|
||||
//! checked-in examples.
|
||||
|
||||
#![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-math-test-{}-{id}-{tag}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
fn write(&self, name: &str, text: &str) {
|
||||
std::fs::write(self.0.join(name), text).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pure_math_library_checks_calls_and_runs_without_math_builtins() {
|
||||
let repo = repo();
|
||||
let check = cli(&["check", "examples/math-library-demo.mq.md"], &repo);
|
||||
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
|
||||
|
||||
let call = cli(&["call", "examples/math-library-demo.mq.md", "main"], &repo);
|
||||
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
|
||||
assert_eq!(stdout(&call), "6\n");
|
||||
|
||||
let run = cli(&["call", "examples/math.mq.md", "计算圆面积"], &repo);
|
||||
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_math_builtins_are_static_symbol_errors() {
|
||||
let dir = TempDir::new("removed");
|
||||
dir.write(
|
||||
"index.mq.md",
|
||||
"# @knowledge 公式\n\n$$\nA = r + 1\n$$\n\n## @exec main\n\n`return math.eval(ref(\"#公式\"), {\"r\": 2}, target=\"A\")`\n",
|
||||
);
|
||||
let check = cli(&["check", "index.mq.md"], dir.path());
|
||||
assert_eq!(check.status.code(), Some(1));
|
||||
let error = stderr(&check);
|
||||
assert!(error.contains("symbol.unknown"), "{error}");
|
||||
// No fallback execution and no removed `math.unsupported` runtime path.
|
||||
let run = cli(&["run", "index.mq.md"], dir.path());
|
||||
assert_eq!(run.status.code(), Some(1));
|
||||
assert!(run.stdout.is_empty());
|
||||
assert!(stderr(&run).contains("symbol.unknown"), "{}", stderr(&run));
|
||||
}
|
||||
@@ -65,7 +65,7 @@ const BASES: &[Base] = &[
|
||||
|
||||
半径叙述。
|
||||
|
||||
`return math.eval(ref("#公式"), {"r": r}, target="A")`
|
||||
`return 3.141592653589793 * r * r`
|
||||
|
||||
### @knowledge 公式
|
||||
|
||||
|
||||
@@ -789,11 +789,11 @@ mod tests {
|
||||
"main",
|
||||
&[],
|
||||
SignatureKind::Explicit,
|
||||
vec![return_call("math.eval(x=1)")],
|
||||
vec![return_call("resource.request(x=1)")],
|
||||
)],
|
||||
imports: vec![marqdo_ir::ImportDecl {
|
||||
alias: "math".into(),
|
||||
target: "./math.mq.md".into(),
|
||||
alias: "resource".into(),
|
||||
target: "./resource.mq.md".into(),
|
||||
span: Span::new(0, 1),
|
||||
}],
|
||||
resources: vec![],
|
||||
|
||||
@@ -140,7 +140,7 @@ impl<'a> Analyzer<'a> {
|
||||
}
|
||||
Expr::Call { callee, args, .. } => {
|
||||
// A callee identifier names a function; a `ns.name` callee is a
|
||||
// builtin namespace (math.eval) or an imported module alias.
|
||||
// builtin namespace (resource.request) or an imported module alias.
|
||||
// Neither is a variable read.
|
||||
match callee.as_ref() {
|
||||
Expr::Ident(_) => {}
|
||||
|
||||
@@ -221,6 +221,16 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Resolve the ancestor scope before deriving the mode: remove every
|
||||
// same-or-higher-level heading first so a heading can only inherit from
|
||||
// its nearest *ancestor*, never from the previous sibling.
|
||||
while let Some((parent_level, _, _)) = stack.last() {
|
||||
if *parent_level >= level {
|
||||
stack.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let inherited = stack
|
||||
.last()
|
||||
.map(|(_, _, mode)| *mode)
|
||||
@@ -242,13 +252,6 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
||||
continue;
|
||||
};
|
||||
|
||||
while let Some((parent_level, _, _)) = stack.last() {
|
||||
if *parent_level >= level {
|
||||
stack.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let parent_path = stack
|
||||
.last()
|
||||
.map(|(_, path, _)| path.clone())
|
||||
@@ -551,4 +554,88 @@ mod tests {
|
||||
assert!(index.diagnostics.is_empty());
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmarked_sibling_inherits_ancestor_not_previous_exec_sibling() {
|
||||
// Regression for RFC-EXT-0003 H-06: the previous sibling is Exec but the
|
||||
// nearest ancestor is Knowledge, so 普通说明 must stay Knowledge.
|
||||
let index =
|
||||
index_of("# @knowledge 数学\n\n## @exec 运行\n\n`return 1`\n\n## 普通说明\n\n叙述。\n");
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
assert_eq!(index.functions[0].id.name, "数学.运行");
|
||||
let sibling = index
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| heading.name == "普通说明")
|
||||
.expect("sibling heading");
|
||||
assert_eq!(sibling.kind, UnitKind::Knowledge);
|
||||
assert_eq!(sibling.mode, SemanticMode::Knowledge);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmarked_sibling_inherits_exec_ancestor_not_previous_knowledge_sibling() {
|
||||
let index =
|
||||
index_of("# @exec 项目\n\n## @knowledge 解释\n\n叙述。\n\n## 计算\n\n`return 1`\n");
|
||||
assert_eq!(index.diagnostics.len(), 0, "{:?}", index.diagnostics);
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
assert_eq!(index.functions[0].id.name, "项目.计算");
|
||||
let sibling = index
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| heading.name == "计算")
|
||||
.expect("sibling heading");
|
||||
assert_eq!(sibling.mode, SemanticMode::Exec);
|
||||
assert_eq!(sibling.kind, UnitKind::Function);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_sections_follow_their_own_ancestors() {
|
||||
// H3 under an Exec H2 is an Exec section; H3 under a Knowledge H2 is not
|
||||
// polluted by the earlier Exec chain.
|
||||
let index = index_of(
|
||||
"# @knowledge 数学\n\n## @exec 计算\n\n### 细节\n\n`return 1`\n\n## 说明\n\n### 例子\n\n叙述。\n",
|
||||
);
|
||||
let depth = |name: &str| {
|
||||
index
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| heading.name == name)
|
||||
.unwrap_or_else(|| panic!("missing heading {name}"))
|
||||
.mode
|
||||
};
|
||||
assert_eq!(depth("细节"), SemanticMode::Exec);
|
||||
assert_eq!(depth("说明"), SemanticMode::Knowledge);
|
||||
assert_eq!(index.functions.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_marker_does_not_corrupt_later_siblings() {
|
||||
let index = index_of("# @knowledge 数学\n\n## @Exec 坏标记\n\n## 正常\n\n`return 1`\n");
|
||||
assert!(index
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.code == "sem.invalid_mode_marker"));
|
||||
let normal = index
|
||||
.headings
|
||||
.iter()
|
||||
.find(|heading| heading.name == "正常")
|
||||
.expect("valid sibling heading");
|
||||
assert_eq!(normal.mode, SemanticMode::Knowledge);
|
||||
assert_eq!(normal.kind, UnitKind::Knowledge);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knowledge_scope_payloads_and_sections_stay_inert() {
|
||||
let index = index_of(
|
||||
"# @knowledge 数学\n\n$$\nA = \\pi r^2\n$$\n\n`数学表达式`\n\n## @knowledge 公式\n\n**不是函数**\n",
|
||||
);
|
||||
assert!(index.functions.is_empty(), "{:?}", index.functions);
|
||||
for heading in &index.headings {
|
||||
assert_eq!(heading.mode, SemanticMode::Knowledge);
|
||||
}
|
||||
assert!(index
|
||||
.units
|
||||
.iter()
|
||||
.all(|unit| !matches!(unit.kind, UnitKind::Function)));
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ regex = { workspace = true }
|
||||
glob = { workspace = true }
|
||||
marqdo-span = { workspace = true }
|
||||
marqdo-value = { workspace = true }
|
||||
marqdo-math = { workspace = true }
|
||||
marqdo-foreign = { workspace = true }
|
||||
marqdo-sandbox = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
+342
-629
File diff suppressed because it is too large.
Load diff
@@ -72,11 +72,6 @@ pub(crate) fn dispatch(
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -37,5 +37,8 @@ impl StdHost {
|
||||
started.elapsed(),
|
||||
summary.to_string(),
|
||||
);
|
||||
// Executed regardless of Trace v2 being enabled: the two writers are
|
||||
// independent observation outputs (RFC-OBS-0001 §4.6).
|
||||
self.observe_effect(op, summary, ctx);
|
||||
}
|
||||
}
|
||||
@@ -84,11 +84,18 @@ impl StdHost {
|
||||
));
|
||||
}
|
||||
let name = provider.name().to_string();
|
||||
if name.is_empty() || name == "stdio" || name == "file" {
|
||||
if name.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
None,
|
||||
format!("resource provider name `{name}` is reserved or empty"),
|
||||
"resource provider name is empty".to_string(),
|
||||
));
|
||||
}
|
||||
if is_core_resource_kind(&name) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
None,
|
||||
format!("resource provider name `{name}` is a reserved core resource kind"),
|
||||
));
|
||||
}
|
||||
let kinds = provider.kind_strings();
|
||||
@@ -100,11 +107,18 @@ impl StdHost {
|
||||
));
|
||||
}
|
||||
for kind in &kinds {
|
||||
if kind.is_empty() || kind == "stdio" || kind == "file" {
|
||||
if kind.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
None,
|
||||
format!("resource provider `{name}` declares reserved kind `{kind}`"),
|
||||
format!("resource provider `{name}` declares an empty kind"),
|
||||
));
|
||||
}
|
||||
if is_core_resource_kind(kind) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
None,
|
||||
format!("resource provider `{name}` declares reserved core kind `{kind}`"),
|
||||
));
|
||||
}
|
||||
if let Some((existing, _)) = self.resource_providers.get(kind) {
|
||||
|
||||
@@ -0,0 +1,626 @@
|
||||
//! Closed compatibility catalogue for non-streaming resource operations (ADR-0062).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value};
|
||||
|
||||
impl StdHost {
|
||||
pub(super) fn request_compatibility_operation(
|
||||
&mut self,
|
||||
operation: &str,
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"resource operations are available only in project mode",
|
||||
));
|
||||
}
|
||||
if args.iter().any(Value::contains_memory) || args.iter().any(Value::contains_resource) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"resource operations accept only Text path arguments",
|
||||
));
|
||||
}
|
||||
match operation {
|
||||
"process.run" => {
|
||||
if args.len() != 2 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `process.run` expects 2 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let program_type = args[0].type_name();
|
||||
let Value::Text(program) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `process.run` expects a Text program, got {program_type}"
|
||||
),
|
||||
));
|
||||
};
|
||||
let args_type = args[1].type_name();
|
||||
let Value::List(values) = args[1].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `process.run` expects a List of Text arguments, got {args_type}"
|
||||
),
|
||||
));
|
||||
};
|
||||
let mut program_args = Vec::with_capacity(values.len());
|
||||
for value in values {
|
||||
let value_type = value.type_name();
|
||||
let Value::Text(value) = value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("process arguments must be Text, got {value_type}"),
|
||||
));
|
||||
};
|
||||
program_args.push(value);
|
||||
}
|
||||
self.capabilities.check_process(&program, ctx.span)?;
|
||||
let result =
|
||||
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=process.run"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "process.run");
|
||||
Ok(result)
|
||||
}
|
||||
"regex.match" | "regex.captures" => {
|
||||
if args.len() != 2 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `{operation}` expects 2 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let pattern_type = args[0].type_name();
|
||||
let Value::Text(pattern) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("{operation} pattern must be Text, got {pattern_type}"),
|
||||
));
|
||||
};
|
||||
let text_type = args[1].type_name();
|
||||
let Value::Text(text) = args[1].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("{operation} text must be Text, got {text_type}"),
|
||||
));
|
||||
};
|
||||
let regex = match regex::Regex::new(&pattern) {
|
||||
Ok(regex) => regex,
|
||||
Err(error) => {
|
||||
return Ok(result_error(
|
||||
"regex.invalid",
|
||||
&format!("invalid regular expression: {error}"),
|
||||
))
|
||||
}
|
||||
};
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(operation),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, operation);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
if operation == "regex.match" {
|
||||
map.insert("value".to_string(), Value::Bool(regex.is_match(&text)));
|
||||
} else {
|
||||
let mut payload = BTreeMap::new();
|
||||
let captures = regex.captures(&text);
|
||||
payload.insert("matched".to_string(), Value::Bool(captures.is_some()));
|
||||
let groups = match captures {
|
||||
Some(captures) => captures
|
||||
.iter()
|
||||
.map(|group| match group {
|
||||
Some(group) => Value::text(group.as_str()),
|
||||
None => Value::None,
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
payload.insert("groups".to_string(), Value::List(groups));
|
||||
map.insert("value".to_string(), Value::Map(payload));
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"compress.gzip" => {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `compress.gzip` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let text_type = args[0].type_name();
|
||||
let Value::Text(text) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("compress.gzip expects Text, got {text_type}"),
|
||||
));
|
||||
};
|
||||
if text.len() > 8 * 1024 * 1024 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
ctx.span,
|
||||
"compress.gzip input exceeds 8 MiB",
|
||||
));
|
||||
}
|
||||
let mut encoder =
|
||||
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
encoder.write_all(text.as_bytes()).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("gzip failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
let bytes = encoder.finish().map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("gzip failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
let values = bytes
|
||||
.into_iter()
|
||||
.map(|byte| Value::int(byte as i64))
|
||||
.collect();
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=compress.gzip"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::List(values));
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"compress.gunzip" => {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `compress.gunzip` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let list_type = args[0].type_name();
|
||||
let Value::List(values) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("compress.gunzip expects List<Int>, got {list_type}"),
|
||||
));
|
||||
};
|
||||
if values.len() > 8 * 1024 * 1024 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
ctx.span,
|
||||
"compress.gunzip input exceeds 8 MiB",
|
||||
));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(values.len());
|
||||
for value in values {
|
||||
let Value::Int(value) = value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
"compress.gunzip bytes must be Int",
|
||||
));
|
||||
};
|
||||
let Some(byte) = value.to_string().parse::<u8>().ok() else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!("`{value}` is not a byte in 0..=255"),
|
||||
));
|
||||
};
|
||||
bytes.push(byte);
|
||||
}
|
||||
let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
|
||||
let mut output = Vec::new();
|
||||
if let Err(error) = decoder
|
||||
.by_ref()
|
||||
.take(8 * 1024 * 1024 + 1)
|
||||
.read_to_end(&mut output)
|
||||
{
|
||||
return Ok(result_error(
|
||||
"compress.invalid",
|
||||
&format!("gunzip failed: {error}"),
|
||||
));
|
||||
}
|
||||
if output.len() > 8 * 1024 * 1024 {
|
||||
return Ok(result_error(
|
||||
"compress.too_large",
|
||||
"gunzip output exceeds 8 MiB",
|
||||
));
|
||||
}
|
||||
let text = match String::from_utf8(output) {
|
||||
Ok(text) => text,
|
||||
Err(_) => {
|
||||
return Ok(result_error(
|
||||
"compress.not_utf8",
|
||||
"gunzip output is not UTF-8",
|
||||
))
|
||||
}
|
||||
};
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=compress.gunzip"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::text(text));
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"random.bytes" => {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `random.bytes` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let count = match &args[0] {
|
||||
Value::Int(value) => value
|
||||
.to_string()
|
||||
.parse::<usize>()
|
||||
.ok()
|
||||
.filter(|count| (1..=65536).contains(count)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(count) = count else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
"random.bytes requires an Int in 1..=65536",
|
||||
));
|
||||
};
|
||||
self.capabilities.check_random(ctx.span)?;
|
||||
let mut bytes = vec![0u8; count];
|
||||
getrandom::fill(&mut bytes).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("OS entropy is unavailable: {error}"),
|
||||
)
|
||||
})?;
|
||||
let values = bytes
|
||||
.into_iter()
|
||||
.map(|byte| Value::int(byte as i64))
|
||||
.collect();
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=random.bytes"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::List(values));
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"env.get" => {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `env.get` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let value_type = args[0].type_name();
|
||||
let Value::Text(name) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `env.get` expects a Text name, got {value_type}"
|
||||
),
|
||||
));
|
||||
};
|
||||
self.capabilities.check_env(&name, ctx.span)?;
|
||||
let mut map = BTreeMap::new();
|
||||
match std::env::var(&name) {
|
||||
Ok(value) => {
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::text(value));
|
||||
}
|
||||
Err(std::env::VarError::NotPresent) => {
|
||||
map.insert("ok".to_string(), Value::Bool(false));
|
||||
map.insert("code".to_string(), Value::text("env.not_found"));
|
||||
map.insert(
|
||||
"message".to_string(),
|
||||
Value::text(format!("environment variable `{name}` is not set")),
|
||||
);
|
||||
}
|
||||
Err(std::env::VarError::NotUnicode(_)) => {
|
||||
map.insert("ok".to_string(), Value::Bool(false));
|
||||
map.insert("code".to_string(), Value::text("env.not_unicode"));
|
||||
map.insert(
|
||||
"message".to_string(),
|
||||
Value::text(format!(
|
||||
"environment variable `{name}` is not valid UTF-8"
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=env.get"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "env.get");
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"clock.now" => {
|
||||
if !args.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `clock.now` expects 0 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("system clock is before the Unix epoch: {error}"),
|
||||
)
|
||||
})?
|
||||
.as_millis()
|
||||
.min(i64::MAX as u128) as i64;
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::int(millis));
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=clock.now"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "clock.now");
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"fs.read_at" => {
|
||||
if args.len() != 3 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `fs.read_at` expects 3 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let path_type = args[0].type_name();
|
||||
let Value::Text(path) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.read_at path must be Text, got {path_type}"),
|
||||
));
|
||||
};
|
||||
let offset = match &args[1] {
|
||||
Value::Int(value) => value.to_string(),
|
||||
other => {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.read_at offset must be Int, got {}", other.type_name()),
|
||||
))
|
||||
}
|
||||
};
|
||||
let length = match &args[2] {
|
||||
Value::Int(value) => value.to_string(),
|
||||
other => {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.read_at length must be Int, got {}", other.type_name()),
|
||||
))
|
||||
}
|
||||
};
|
||||
self.capabilities.check_read(&path, ctx.span)?;
|
||||
let result = self
|
||||
.fs
|
||||
.request("read_at", &[path, offset, length], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.read_at"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
|
||||
Ok(result)
|
||||
}
|
||||
"fs.append" => {
|
||||
if args.len() != 2 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `fs.append` expects 2 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let path_type = args[0].type_name();
|
||||
let Value::Text(path) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.append path must be Text, got {path_type}"),
|
||||
));
|
||||
};
|
||||
let text_type = args[1].type_name();
|
||||
let Value::Text(text) = args[1].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.append text must be Text, got {text_type}"),
|
||||
));
|
||||
};
|
||||
self.capabilities.check_write(&path, ctx.span)?;
|
||||
let result = self.fs.request("append", &[path, text], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.append"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.append");
|
||||
Ok(result)
|
||||
}
|
||||
"fs.walk" => {
|
||||
if args.len() != 1 {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `fs.walk` expects 1 argument, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let path_type = args[0].type_name();
|
||||
let Value::Text(path) = args[0].clone() else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!("fs.walk path must be Text, got {path_type}"),
|
||||
));
|
||||
};
|
||||
self.capabilities.check_read(&path, ctx.span)?;
|
||||
let result = self.fs.request("walk", &[path], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.walk"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
|
||||
Ok(result)
|
||||
}
|
||||
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
|
||||
let name = &operation["fs.".len()..];
|
||||
let expected = if name == "rename" { 2 } else { 1 };
|
||||
if args.len() != expected {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `{operation}` expects {expected} argument(s), got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut paths = Vec::with_capacity(args.len());
|
||||
for value in args {
|
||||
let value_type = value.type_name();
|
||||
let Value::Text(path) = value else {
|
||||
return Err(RuntimeError::type_error(
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `{operation}` expects Text paths, got {value_type}"
|
||||
),
|
||||
));
|
||||
};
|
||||
paths.push(path);
|
||||
}
|
||||
match name {
|
||||
"exists" | "metadata" | "list" => {
|
||||
self.capabilities.check_read(&paths[0], ctx.span)?;
|
||||
}
|
||||
"mkdir" | "remove" => {
|
||||
self.capabilities.check_write(&paths[0], ctx.span)?;
|
||||
}
|
||||
"rename" => {
|
||||
self.capabilities.check_write(&paths[0], ctx.span)?;
|
||||
self.capabilities.check_write(&paths[1], ctx.span)?;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let result = self.fs.request(name, &paths, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("op=fs.{name}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.request",
|
||||
ctx,
|
||||
started,
|
||||
&format!("fs.{name}"),
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
let message = match operation.strip_prefix("fs.") {
|
||||
Some(name) => format!("unsupported filesystem operation `{name}`"),
|
||||
None => format!("unsupported resource operation `{operation}`"),
|
||||
};
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
message,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn result_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)
|
||||
}
|
||||
@@ -1,147 +1,18 @@
|
||||
//! Math and foreign kernel adapters.
|
||||
//! Foreign-kernel adapters.
|
||||
//!
|
||||
//! These functions are the only bridge between the capability host and the
|
||||
//! native math / foreign crates. Every operation is capability-checked before
|
||||
//! the kernel is touched; kernel failures are converted to structured runtime
|
||||
//! errors, never panics.
|
||||
//! This module is the bridge between the capability host and the native foreign
|
||||
//! kernel crate. Every operation is capability-checked before the kernel is
|
||||
//! touched; kernel failures are converted to structured runtime errors, never
|
||||
//! panics. Domain math is not a host kernel (ADR-0061): it belongs to a pure
|
||||
//! `.mq.md` package or an explicitly selected ABI backend.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_value::{to_wire, ErrorCategory, FormulaValue, RuntimeError, Value};
|
||||
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
|
||||
|
||||
use crate::context::ExecutionContext;
|
||||
use crate::host::{arity, expect_text, HostOp, StdHost};
|
||||
|
||||
pub(crate) fn math(
|
||||
host: &mut StdHost,
|
||||
op: HostOp,
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
if !host.capabilities.math {
|
||||
return Err(denied(ctx, "the math capability was not granted"));
|
||||
}
|
||||
let span = ctx.span;
|
||||
match op {
|
||||
HostOp::MathParse => {
|
||||
let source = expect_text(&args, 0, "math.parse source", span)?;
|
||||
let formula = marqdo_math::parse(&source).map_err(|error| math_error(error, span))?;
|
||||
Ok(Value::Formula(FormulaValue {
|
||||
latex: formula.source,
|
||||
unit: None,
|
||||
display: false,
|
||||
span,
|
||||
}))
|
||||
}
|
||||
HostOp::MathEval => {
|
||||
if args.len() < 2 {
|
||||
return Err(arity(span, "math.eval", 2, args.len()));
|
||||
}
|
||||
let formula = formula_source(&args[0], span)?;
|
||||
let bindings = math_bindings(&args[1], span)?;
|
||||
let target = match args.get(2) {
|
||||
Some(Value::Text(target)) => Some(target.clone()),
|
||||
Some(Value::None) | None => None,
|
||||
Some(other) => {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("math.eval target must be Text, got {}", other.type_name()),
|
||||
))
|
||||
}
|
||||
};
|
||||
let parsed = marqdo_math::parse(&formula).map_err(|error| math_error(error, span))?;
|
||||
marqdo_math::evaluate(&parsed, &bindings, target.as_deref())
|
||||
.map_err(|error| math_error(error, span))
|
||||
}
|
||||
HostOp::MathSubstitute => {
|
||||
if args.len() < 2 {
|
||||
return Err(arity(span, "math.substitute", 2, args.len()));
|
||||
}
|
||||
let source = formula_source(&args[0], span)?;
|
||||
let bindings = math_bindings(&args[1], span)?;
|
||||
let parsed = marqdo_math::parse(&source).map_err(|error| math_error(error, span))?;
|
||||
let substituted = marqdo_math::substitute(&parsed, &bindings)
|
||||
.map_err(|error| math_error(error, span))?;
|
||||
Ok(Value::Formula(FormulaValue {
|
||||
latex: substituted.source,
|
||||
unit: None,
|
||||
display: false,
|
||||
span,
|
||||
}))
|
||||
}
|
||||
HostOp::MathSimplify | HostOp::MathDifferentiate => Err(RuntimeError::new(
|
||||
ErrorCategory::MathUnsupported,
|
||||
span,
|
||||
format!(
|
||||
"`{}` is not part of the supported math subset in this build",
|
||||
op.name()
|
||||
),
|
||||
)),
|
||||
_ => Err(RuntimeError::new(
|
||||
ErrorCategory::Internal,
|
||||
span,
|
||||
"unexpected math operation",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn formula_source(value: &Value, span: Option<marqdo_span::Span>) -> Result<String, RuntimeError> {
|
||||
match value {
|
||||
Value::Formula(formula) => Ok(formula.latex.clone()),
|
||||
Value::Text(text) => Ok(text.clone()),
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("expected Formula or Text, got {}", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn math_bindings(
|
||||
value: &Value,
|
||||
span: Option<marqdo_span::Span>,
|
||||
) -> Result<BTreeMap<String, Value>, RuntimeError> {
|
||||
match value {
|
||||
Value::Map(map) => {
|
||||
let mut bindings = BTreeMap::new();
|
||||
for (name, value) in map {
|
||||
match value {
|
||||
Value::Int(_) | Value::Float(_) => {
|
||||
bindings.insert(name.clone(), value.clone());
|
||||
}
|
||||
other => {
|
||||
return Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!(
|
||||
"math binding `{name}` must be Int or Float, got {}",
|
||||
other.type_name()
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(bindings)
|
||||
}
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("math bindings must be a Map, got {}", other.type_name()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn math_error(error: marqdo_math::MathError, span: Option<marqdo_span::Span>) -> RuntimeError {
|
||||
use marqdo_math::MathErrorKind;
|
||||
let category = match error.kind {
|
||||
MathErrorKind::Parse | MathErrorKind::Unsupported => ErrorCategory::MathUnsupported,
|
||||
MathErrorKind::UndefinedVariable => ErrorCategory::UnknownSymbol,
|
||||
MathErrorKind::Type => ErrorCategory::Type,
|
||||
};
|
||||
let mut message = error.message;
|
||||
if let Some(position) = error.position {
|
||||
message = format!("{message} (at byte {position} of the formula)");
|
||||
}
|
||||
RuntimeError::new(category, span, message)
|
||||
}
|
||||
use crate::host::{HostOp, StdHost};
|
||||
|
||||
pub(crate) fn foreign(
|
||||
host: &mut StdHost,
|
||||
@@ -296,9 +167,5 @@ fn foreign_error(
|
||||
RuntimeError::new(category, span, message)
|
||||
}
|
||||
|
||||
fn denied(ctx: &ExecutionContext, message: impl Into<String>) -> RuntimeError {
|
||||
RuntimeError::new(ErrorCategory::PermissionDenied, ctx.span, message)
|
||||
}
|
||||
|
||||
/// Default per-call foreign timeout used by the CLI.
|
||||
pub const DEFAULT_FOREIGN_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
@@ -11,6 +11,7 @@ pub mod fs;
|
||||
pub mod handles;
|
||||
pub mod host;
|
||||
pub mod kernels;
|
||||
pub mod observe;
|
||||
mod plugin_worker;
|
||||
mod process;
|
||||
mod provider_c;
|
||||
@@ -28,5 +29,14 @@ 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 observe::{
|
||||
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
|
||||
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
|
||||
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
|
||||
};
|
||||
pub use resource::{
|
||||
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
|
||||
CORE_RESOURCE_KINDS,
|
||||
};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Typed runtime observation facade (RFC-OBS-0001, ADR-0059).
|
||||
//!
|
||||
//! This module is internal to the workspace. It defines the typed events the
|
||||
//! interpreter and host emit at real commit points, the optional sink the CLI
|
||||
//! installs, the run-scoped frame identity and the bounded observation budget.
|
||||
//! It does **not** know JSONL, HTTP, SSE, View, agents or the public envelope;
|
||||
//! the CLI composes the public Execution Events v1 protocol from these events.
|
||||
//!
|
||||
//! Defaults are deliberately inert: no sink means no allocation and no
|
||||
//! serialization. The facade never exposes `Frame.locals`, the whole
|
||||
//! `MemoryStore`, raw OS pointers or host handles.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
|
||||
/// Default maximum number of structural/value observation events per run.
|
||||
pub const DEFAULT_MAX_OBSERVATION_EVENTS: u64 = 100_000;
|
||||
/// Default approximate maximum encoded bytes for structural/value events.
|
||||
pub const DEFAULT_MAX_OBSERVATION_BYTES: u64 = 16 * 1024 * 1024;
|
||||
/// Default maximum encoded bytes for one selected value.
|
||||
pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
|
||||
/// Maximum committed stdio bytes carried by one chunk event.
|
||||
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Opaque run-scoped call-instance identity.
|
||||
///
|
||||
/// Not a function identity, not a source location and never a memory pointer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct FrameId(pub u64);
|
||||
|
||||
impl FrameId {
|
||||
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
|
||||
pub fn as_wire(self) -> String {
|
||||
format!("f{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a bound parameter's value came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ParameterSource {
|
||||
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
|
||||
Provided,
|
||||
/// Evaluated from the declared default expression.
|
||||
Default,
|
||||
}
|
||||
|
||||
impl ParameterSource {
|
||||
/// Stable wire name.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ParameterSource::Provided => "provided",
|
||||
ParameterSource::Default => "default",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observation policy for one run.
|
||||
///
|
||||
/// `structural` always implies frame identity; value events only exist for
|
||||
/// exact names in `selected_variables`/`selected_parameters`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObservationConfig {
|
||||
/// Publish lifecycle/frame/branch/loop/effect events.
|
||||
pub structural: bool,
|
||||
/// Exact local-variable names allowed to publish a value.
|
||||
pub selected_variables: BTreeSet<String>,
|
||||
/// Exact parameter names allowed to publish a value.
|
||||
pub selected_parameters: BTreeSet<String>,
|
||||
/// Second explicit consent required to publish `Text` bytes.
|
||||
pub allow_text_values: bool,
|
||||
/// Structural/value event budget (`0` = unlimited).
|
||||
pub max_observation_events: u64,
|
||||
/// Approximate structural/value byte budget (`0` = unlimited).
|
||||
pub max_observation_bytes: u64,
|
||||
/// Maximum source bytes encoded for one value (`0` = unlimited).
|
||||
pub max_value_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for ObservationConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
structural: true,
|
||||
selected_variables: BTreeSet::new(),
|
||||
selected_parameters: BTreeSet::new(),
|
||||
allow_text_values: false,
|
||||
max_observation_events: DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
max_observation_bytes: DEFAULT_MAX_OBSERVATION_BYTES,
|
||||
max_value_bytes: DEFAULT_MAX_VALUE_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObservationConfig {
|
||||
/// Whether any value can ever be published.
|
||||
pub fn values_enabled(&self) -> bool {
|
||||
!self.selected_variables.is_empty() || !self.selected_parameters.is_empty()
|
||||
}
|
||||
|
||||
/// Negotiated observation level (`base`, `structural` or `values`).
|
||||
pub fn level(&self) -> &'static str {
|
||||
if self.values_enabled() {
|
||||
"values"
|
||||
} else if self.structural {
|
||||
"structural"
|
||||
} else {
|
||||
"base"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a value has (or has not) a wire encoding.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueState {
|
||||
/// Name not selected; no value encoded.
|
||||
NotRequested,
|
||||
/// Name selected but policy hides the value.
|
||||
Redacted,
|
||||
/// Encoded but truncated to the configured maximum.
|
||||
Truncated,
|
||||
/// Type not supported by the v1 scalar policy.
|
||||
Unsupported,
|
||||
/// Encoded normally.
|
||||
Observed,
|
||||
}
|
||||
|
||||
impl ValueState {
|
||||
/// Stable wire name.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ValueState::NotRequested => "not_requested",
|
||||
ValueState::Redacted => "redacted",
|
||||
ValueState::Truncated => "truncated",
|
||||
ValueState::Unsupported => "unsupported",
|
||||
ValueState::Observed => "observed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded, policy-filtered value encoding (the `marqdo.value.v1` wire
|
||||
/// object plus optional truncation metadata).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ObservedValue {
|
||||
/// JSON object safe to publish.
|
||||
pub wire: serde_json::Value,
|
||||
}
|
||||
|
||||
/// One typed internal observation event.
|
||||
///
|
||||
/// Borrows strings and stdio bytes so the default disabled path never clones a
|
||||
/// frame, argument list or whole `Value`. The sink must consume it
|
||||
/// synchronously before returning.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ObservationEvent<'a> {
|
||||
/// Bytes committed to the program's stdout by the host.
|
||||
StdoutChunk { data: &'a [u8] },
|
||||
/// Bytes committed to the program's stderr by the host.
|
||||
StderrChunk { data: &'a [u8] },
|
||||
/// A new frame exists (arguments already bound).
|
||||
CallEnter {
|
||||
frame_id: FrameId,
|
||||
parent_frame_id: Option<FrameId>,
|
||||
function_id: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A frame finished, including failure paths.
|
||||
CallExit {
|
||||
frame_id: FrameId,
|
||||
status: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A `return` statement committed its value.
|
||||
Return {
|
||||
frame_id: FrameId,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A branch condition was evaluated.
|
||||
BranchEval {
|
||||
frame_id: FrameId,
|
||||
result: bool,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A loop condition was evaluated.
|
||||
LoopIteration {
|
||||
frame_id: FrameId,
|
||||
decision: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// The host completed a controlled effect attempt.
|
||||
Effect {
|
||||
operation: &'a str,
|
||||
result_code: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A local assignment was committed.
|
||||
VariableAssigned {
|
||||
frame_id: FrameId,
|
||||
name: &'a str,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
value_state: ValueState,
|
||||
value: Option<ObservedValue>,
|
||||
},
|
||||
/// A function parameter was bound.
|
||||
ParameterObserved {
|
||||
frame_id: FrameId,
|
||||
name: &'a str,
|
||||
source: ParameterSource,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
value_state: ValueState,
|
||||
value: Option<ObservedValue>,
|
||||
},
|
||||
/// The structural/value observation budget was exhausted.
|
||||
ObservationTruncated {
|
||||
reason: &'a str,
|
||||
limit: u64,
|
||||
written: u64,
|
||||
dropped: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
|
||||
///
|
||||
/// Every variant carries an `Option<FrameId>`; observation of values and
|
||||
/// structural events only happens while a frame identity exists.
|
||||
#[derive(Debug)]
|
||||
pub enum RuntimeObservation<'a> {
|
||||
/// A `return` statement committed (before the call exits).
|
||||
Return {
|
||||
frame_id: Option<FrameId>,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A branch condition evaluated.
|
||||
BranchEval {
|
||||
frame_id: Option<FrameId>,
|
||||
result: bool,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A loop condition evaluated.
|
||||
LoopIteration {
|
||||
frame_id: Option<FrameId>,
|
||||
decision: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A local variable assignment committed.
|
||||
VariableAssigned {
|
||||
frame_id: Option<FrameId>,
|
||||
name: &'a str,
|
||||
value: &'a Value,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A parameter was bound.
|
||||
ParameterBound {
|
||||
frame_id: Option<FrameId>,
|
||||
name: &'a str,
|
||||
source: ParameterSource,
|
||||
value: &'a Value,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Sink installed by the composition root (the CLI JSONL writer in product
|
||||
/// builds, an in-memory recorder in tests).
|
||||
pub trait ObservationSink {
|
||||
/// Consume one event synchronously.
|
||||
fn emit(&mut self, event: ObservationEvent<'_>) -> Result<(), ObservationError>;
|
||||
}
|
||||
|
||||
/// A sink failed to accept an event (usually a closed/broken output pipe).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObservationError {
|
||||
/// Human-readable transport reason (safe to print to OS stderr).
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ObservationError {
|
||||
/// Construct an observation transport error.
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert into the stable runtime failure used to abort the run.
|
||||
pub fn into_runtime_error(self) -> RuntimeError {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::Observation,
|
||||
None,
|
||||
format!("observe.transport_failed: {}", self.message),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ObservationError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ObservationError {}
|
||||
|
||||
/// Mutable per-run observation state owned by `StdHost`.
|
||||
pub(crate) struct ObservationState {
|
||||
pub(crate) config: ObservationConfig,
|
||||
pub(crate) sink: Box<dyn ObservationSink>,
|
||||
next_frame: u64,
|
||||
frames: Vec<FrameId>,
|
||||
written: u64,
|
||||
bytes: u64,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
impl ObservationState {
|
||||
pub(crate) fn new(config: ObservationConfig, sink: Box<dyn ObservationSink>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
sink,
|
||||
next_frame: 0,
|
||||
frames: Vec::new(),
|
||||
written: 0,
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_frame(&mut self) -> FrameId {
|
||||
self.next_frame += 1;
|
||||
FrameId(self.next_frame)
|
||||
}
|
||||
|
||||
pub(crate) fn parent_frame(&self) -> Option<FrameId> {
|
||||
self.frames.last().copied()
|
||||
}
|
||||
|
||||
pub(crate) fn push_frame(&mut self, frame: FrameId) {
|
||||
self.frames.push(frame);
|
||||
}
|
||||
|
||||
/// Pop the frame if it is on the stack. A mismatch is a runtime bug, not a
|
||||
/// consumer-visible event, so it is repaired defensively rather than
|
||||
/// panicking inside the host.
|
||||
pub(crate) fn pop_frame(&mut self, frame: FrameId) {
|
||||
if self.frames.last().copied() == Some(frame) {
|
||||
self.frames.pop();
|
||||
} else if let Some(position) = self.frames.iter().rposition(|item| *item == frame) {
|
||||
self.frames.truncate(position);
|
||||
}
|
||||
}
|
||||
|
||||
/// Estimate one encoded event and accept it if the budget allows.
|
||||
///
|
||||
/// Returns `Ok(true)` when the event was admitted, `Ok(false)` when the
|
||||
/// budget was already exhausted, and writes the single truncation marker
|
||||
/// through `emit_truncated` on the transition.
|
||||
pub(crate) fn admit(&mut self, estimate: u64) -> bool {
|
||||
if self.truncated {
|
||||
return false;
|
||||
}
|
||||
let event_limit = self.config.max_observation_events;
|
||||
let byte_limit = self.config.max_observation_bytes;
|
||||
if (event_limit > 0 && self.written >= event_limit)
|
||||
|| (byte_limit > 0 && self.bytes.saturating_add(estimate) > byte_limit)
|
||||
{
|
||||
self.truncated = true;
|
||||
return false;
|
||||
}
|
||||
self.written += 1;
|
||||
self.bytes = self.bytes.saturating_add(estimate);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn truncation_reason(&self, estimate: u64) -> &'static str {
|
||||
let event_limit = self.config.max_observation_events;
|
||||
if event_limit > 0 && self.written >= event_limit {
|
||||
"event_budget"
|
||||
} else if self.config.max_observation_bytes > 0
|
||||
&& self.bytes.saturating_add(estimate) > self.config.max_observation_bytes
|
||||
{
|
||||
"byte_budget"
|
||||
} else {
|
||||
"event_budget"
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_truncated(&self) -> bool {
|
||||
self.truncated
|
||||
}
|
||||
|
||||
pub(crate) fn written(&self) -> u64 {
|
||||
self.written
|
||||
}
|
||||
|
||||
pub(crate) fn limit_for(&self, reason: &str) -> u64 {
|
||||
if reason == "byte_budget" {
|
||||
self.config.max_observation_bytes
|
||||
} else {
|
||||
self.config.max_observation_events
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a selected value under the v1 scalar policy.
|
||||
///
|
||||
/// No `Debug`, no recursive container expansion and no handle serialization.
|
||||
pub fn encode_value(
|
||||
config: &ObservationConfig,
|
||||
selected: bool,
|
||||
value: &Value,
|
||||
) -> (ValueState, Option<ObservedValue>) {
|
||||
if !selected {
|
||||
return (ValueState::NotRequested, None);
|
||||
}
|
||||
match value {
|
||||
Value::Int(_) | Value::Float(_) | Value::Bool(_) => (
|
||||
ValueState::Observed,
|
||||
Some(ObservedValue {
|
||||
wire: marqdo_value::to_wire(value),
|
||||
}),
|
||||
),
|
||||
Value::Text(text) => {
|
||||
if !config.allow_text_values {
|
||||
return (ValueState::Redacted, None);
|
||||
}
|
||||
let limit = config.max_value_bytes;
|
||||
if limit == 0 || text.len() <= limit {
|
||||
return (
|
||||
ValueState::Observed,
|
||||
Some(ObservedValue {
|
||||
wire: marqdo_value::to_wire(value),
|
||||
}),
|
||||
);
|
||||
}
|
||||
let mut cut = limit.min(text.len());
|
||||
while cut > 0 && !text.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
let prefix = Value::Text(text[..cut].to_string());
|
||||
let mut wire = marqdo_value::to_wire(&prefix);
|
||||
if let serde_json::Value::Object(map) = &mut wire {
|
||||
map.insert("truncated".to_string(), serde_json::Value::Bool(true));
|
||||
map.insert(
|
||||
"original_byte_count".to_string(),
|
||||
serde_json::Value::from(text.len() as u64),
|
||||
);
|
||||
}
|
||||
(ValueState::Truncated, Some(ObservedValue { wire }))
|
||||
}
|
||||
_ => (ValueState::Unsupported, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Approximate encoded size, used only for the observation byte budget.
|
||||
pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
|
||||
let mut total: u64 = 160;
|
||||
let mut add_text = |text: &str| total = total.saturating_add(text.len() as u64);
|
||||
match event {
|
||||
ObservationEvent::StdoutChunk { data } | ObservationEvent::StderrChunk { data } => {
|
||||
total = total.saturating_add((data.len() as u64).saturating_mul(4) / 3);
|
||||
}
|
||||
ObservationEvent::CallEnter {
|
||||
function_id,
|
||||
module_id,
|
||||
..
|
||||
} => {
|
||||
add_text(function_id);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::CallExit {
|
||||
status, module_id, ..
|
||||
} => {
|
||||
add_text(status);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::Return {
|
||||
value_type,
|
||||
module_id,
|
||||
..
|
||||
} => {
|
||||
add_text(value_type);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::BranchEval { module_id, .. }
|
||||
| ObservationEvent::LoopIteration { module_id, .. }
|
||||
| ObservationEvent::Effect { module_id, .. } => {
|
||||
add_text(module_id);
|
||||
if let ObservationEvent::LoopIteration { decision, .. } = event {
|
||||
add_text(decision);
|
||||
}
|
||||
if let ObservationEvent::Effect { operation, .. } = event {
|
||||
add_text(operation);
|
||||
}
|
||||
}
|
||||
ObservationEvent::VariableAssigned {
|
||||
name,
|
||||
value_type,
|
||||
module_id,
|
||||
value,
|
||||
..
|
||||
}
|
||||
| ObservationEvent::ParameterObserved {
|
||||
name,
|
||||
value_type,
|
||||
module_id,
|
||||
value,
|
||||
..
|
||||
} => {
|
||||
add_text(name);
|
||||
add_text(value_type);
|
||||
add_text(module_id);
|
||||
if let Some(value) = value {
|
||||
total = total.saturating_add(encoded_len(&value.wire));
|
||||
}
|
||||
}
|
||||
ObservationEvent::ObservationTruncated { reason, .. } => add_text(reason),
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn encoded_len(value: &serde_json::Value) -> u64 {
|
||||
serde_json::to_vec(value)
|
||||
.map(|bytes| bytes.len() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
@@ -18,6 +18,20 @@ use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
|
||||
|
||||
static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Core resource kinds owned by the host itself.
|
||||
///
|
||||
/// A third-party [`ResourceProvider`] may neither use one of these names as its
|
||||
/// provider name nor declare one of them as a served kind: the host dispatches
|
||||
/// these kinds before consulting the provider table. This is the single source of
|
||||
/// truth used by both host registration and the CLI provider-manifest validator
|
||||
/// ([`spec/resource-provider-v2.md`], ADR-0033/0062).
|
||||
pub const CORE_RESOURCE_KINDS: &[&str] = &["stdio", "file", "tcp", "tls", "udp", "tcp-listener"];
|
||||
|
||||
/// Whether `name` is a host-owned core resource kind.
|
||||
pub fn is_core_resource_kind(name: &str) -> bool {
|
||||
CORE_RESOURCE_KINDS.contains(&name)
|
||||
}
|
||||
|
||||
/// A versioned trusted provider of additional resource kinds (ADR-0033).
|
||||
///
|
||||
/// In-process providers share the host address space and are **not** a
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Host observation facade tests (RFC-OBS-0001 / ADR-0059).
|
||||
//!
|
||||
//! These pin the internal contract: stdio chunks come from the real host
|
||||
//! commit point, the default path is inert, frames are paired, budgets
|
||||
//! truncate only non-critical events and a broken sink aborts the run.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use marqdo_host::{
|
||||
encode_value, Capabilities, ExecutionContext, FrameId, Host, ObservationConfig,
|
||||
ObservationError, ObservationEvent, ObservationSink, ParameterSource, RuntimeObservation,
|
||||
StdHost, ValueState,
|
||||
};
|
||||
use marqdo_sandbox::SandboxMode;
|
||||
use marqdo_value::{ErrorCategory, Value};
|
||||
|
||||
fn context() -> ExecutionContext {
|
||||
ExecutionContext::new("index.mq.md".to_string(), None)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Recorded {
|
||||
Stdout(Vec<u8>),
|
||||
Stderr(Vec<u8>),
|
||||
Enter {
|
||||
frame: FrameId,
|
||||
parent: Option<FrameId>,
|
||||
function: String,
|
||||
},
|
||||
Exit {
|
||||
frame: FrameId,
|
||||
status: String,
|
||||
},
|
||||
Return {
|
||||
frame: FrameId,
|
||||
value_type: String,
|
||||
},
|
||||
Branch {
|
||||
frame: FrameId,
|
||||
result: bool,
|
||||
},
|
||||
Loop {
|
||||
frame: FrameId,
|
||||
decision: String,
|
||||
},
|
||||
Variable {
|
||||
frame: FrameId,
|
||||
name: String,
|
||||
value_type: String,
|
||||
state: ValueState,
|
||||
value: Option<serde_json::Value>,
|
||||
},
|
||||
Parameter {
|
||||
frame: FrameId,
|
||||
name: String,
|
||||
source: ParameterSource,
|
||||
state: ValueState,
|
||||
value: Option<serde_json::Value>,
|
||||
},
|
||||
Effect {
|
||||
operation: String,
|
||||
result_code: String,
|
||||
},
|
||||
Truncated {
|
||||
reason: String,
|
||||
limit: u64,
|
||||
written: u64,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ObservationEvent<'_>> for Recorded {
|
||||
fn from(event: ObservationEvent<'_>) -> Self {
|
||||
match event {
|
||||
ObservationEvent::StdoutChunk { data } => Recorded::Stdout(data.to_vec()),
|
||||
ObservationEvent::StderrChunk { data } => Recorded::Stderr(data.to_vec()),
|
||||
ObservationEvent::CallEnter {
|
||||
frame_id,
|
||||
parent_frame_id,
|
||||
function_id,
|
||||
..
|
||||
} => Recorded::Enter {
|
||||
frame: frame_id,
|
||||
parent: parent_frame_id,
|
||||
function: function_id.to_string(),
|
||||
},
|
||||
ObservationEvent::CallExit {
|
||||
frame_id, status, ..
|
||||
} => Recorded::Exit {
|
||||
frame: frame_id,
|
||||
status: status.to_string(),
|
||||
},
|
||||
ObservationEvent::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
..
|
||||
} => Recorded::Return {
|
||||
frame: frame_id,
|
||||
value_type: value_type.to_string(),
|
||||
},
|
||||
ObservationEvent::BranchEval {
|
||||
frame_id, result, ..
|
||||
} => Recorded::Branch {
|
||||
frame: frame_id,
|
||||
result,
|
||||
},
|
||||
ObservationEvent::LoopIteration {
|
||||
frame_id, decision, ..
|
||||
} => Recorded::Loop {
|
||||
frame: frame_id,
|
||||
decision: decision.to_string(),
|
||||
},
|
||||
ObservationEvent::Effect {
|
||||
operation,
|
||||
result_code,
|
||||
..
|
||||
} => Recorded::Effect {
|
||||
operation: operation.to_string(),
|
||||
result_code: result_code.to_string(),
|
||||
},
|
||||
ObservationEvent::VariableAssigned {
|
||||
frame_id,
|
||||
name,
|
||||
value_type,
|
||||
value_state,
|
||||
value,
|
||||
..
|
||||
} => Recorded::Variable {
|
||||
frame: frame_id,
|
||||
name: name.to_string(),
|
||||
value_type: value_type.to_string(),
|
||||
state: value_state,
|
||||
value: value.map(|value| value.wire),
|
||||
},
|
||||
ObservationEvent::ParameterObserved {
|
||||
frame_id,
|
||||
name,
|
||||
source,
|
||||
value_state,
|
||||
value,
|
||||
..
|
||||
} => Recorded::Parameter {
|
||||
frame: frame_id,
|
||||
name: name.to_string(),
|
||||
source,
|
||||
state: value_state,
|
||||
value: value.map(|value| value.wire),
|
||||
},
|
||||
ObservationEvent::ObservationTruncated {
|
||||
reason,
|
||||
limit,
|
||||
written,
|
||||
..
|
||||
} => Recorded::Truncated {
|
||||
reason: reason.to_string(),
|
||||
limit,
|
||||
written,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Recorder {
|
||||
events: Rc<RefCell<Vec<Recorded>>>,
|
||||
fail: bool,
|
||||
}
|
||||
|
||||
impl ObservationSink for Recorder {
|
||||
fn emit(&mut self, event: ObservationEvent<'_>) -> Result<(), ObservationError> {
|
||||
if self.fail {
|
||||
return Err(ObservationError::new("synthetic broken pipe"));
|
||||
}
|
||||
self.events.borrow_mut().push(event.into());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn observed_host(config: ObservationConfig) -> (StdHost, Rc<RefCell<Vec<Recorded>>>) {
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
.with_observation(
|
||||
config,
|
||||
Box::new(Recorder {
|
||||
events: Rc::clone(&events),
|
||||
fail: false,
|
||||
}),
|
||||
);
|
||||
(host, events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_and_stderr_chunks_are_emitted_at_the_commit_point() {
|
||||
let (mut host, events) = observed_host(ObservationConfig::default());
|
||||
let ctx = context();
|
||||
let stdout = match host
|
||||
.resource_open("stdio", "stdout", &["write".to_string()], &ctx)
|
||||
.unwrap()
|
||||
{
|
||||
Value::Resource(handle) => handle,
|
||||
other => panic!("expected a resource handle, got {other:?}"),
|
||||
};
|
||||
let stderr = match host
|
||||
.resource_open("stdio", "stderr", &["write".to_string()], &ctx)
|
||||
.unwrap()
|
||||
{
|
||||
Value::Resource(handle) => handle,
|
||||
other => panic!("expected a resource handle, got {other:?}"),
|
||||
};
|
||||
host.resource_write(stdout, b"START\n", &ctx).unwrap();
|
||||
host.resource_write(stderr, &[0xff, 0x00, 0xfe], &ctx)
|
||||
.unwrap();
|
||||
host.resource_write(stdout, b"DONE\n", &ctx).unwrap();
|
||||
let events = events.borrow();
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Recorded::Stdout(bytes) => Some(bytes.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
vec![b"START\n".to_vec(), b"DONE\n".to_vec()],
|
||||
"each committed stdout write must produce its own chunk event"
|
||||
);
|
||||
assert!(events.contains(&Recorded::Stderr(vec![0xff, 0x00, 0xfe])));
|
||||
assert_eq!(host.take_output(), b"START\nDONE\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_output_write_emits_no_chunk() {
|
||||
let (mut host, events) = observed_host(ObservationConfig::default());
|
||||
host.budget.max_output_bytes = 3;
|
||||
let ctx = context();
|
||||
let stdout = match host
|
||||
.resource_open("stdio", "stdout", &["write".to_string()], &ctx)
|
||||
.unwrap()
|
||||
{
|
||||
Value::Resource(handle) => handle,
|
||||
other => panic!("expected a resource handle, got {other:?}"),
|
||||
};
|
||||
let error = host.resource_write(stdout, b"hello", &ctx).unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::ResourceExhausted);
|
||||
assert!(
|
||||
events
|
||||
.borrow()
|
||||
.iter()
|
||||
.all(|event| !matches!(event, Recorded::Stdout(_))),
|
||||
"an output write rejected by the host budget must not be observed"
|
||||
);
|
||||
assert!(host.take_output().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_writes_are_split_into_bounded_chunks() {
|
||||
let (mut host, events) = observed_host(ObservationConfig::default());
|
||||
let ctx = context();
|
||||
let stdout = match host
|
||||
.resource_open("stdio", "stdout", &["write".to_string()], &ctx)
|
||||
.unwrap()
|
||||
{
|
||||
Value::Resource(handle) => handle,
|
||||
other => panic!("expected a resource handle, got {other:?}"),
|
||||
};
|
||||
let data = vec![b'x'; 150_000];
|
||||
host.resource_write(stdout, &data, &ctx).unwrap();
|
||||
let chunks: Vec<Vec<u8>> = events
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Recorded::Stdout(bytes) => Some(bytes.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(chunks.len(), 3);
|
||||
assert!(chunks.iter().all(|chunk| chunk.len() <= 64 * 1024));
|
||||
assert_eq!(chunks.concat(), data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_are_unique_paired_and_parented() {
|
||||
let (mut host, events) = observed_host(ObservationConfig::default());
|
||||
let main = host
|
||||
.observation_begin_frame("root::main", "root::index.mq.md", None)
|
||||
.unwrap()
|
||||
.expect("observation enabled must allocate a frame");
|
||||
let child = host
|
||||
.observation_begin_frame("root::f", "root::index.mq.md", None)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let grandchild = host
|
||||
.observation_begin_frame("root::g", "root::index.mq.md", None)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
host.observe_runtime(RuntimeObservation::Return {
|
||||
frame_id: Some(grandchild),
|
||||
value_type: "Int",
|
||||
module_id: "root::index.mq.md",
|
||||
span: None,
|
||||
})
|
||||
.unwrap();
|
||||
host.observation_end_frame(Some(grandchild), "return", "root::index.mq.md", None)
|
||||
.unwrap();
|
||||
host.observation_end_frame(Some(child), "ok", "root::index.mq.md", None)
|
||||
.unwrap();
|
||||
host.observation_end_frame(Some(main), "ok", "root::index.mq.md", None)
|
||||
.unwrap();
|
||||
|
||||
let events = events.borrow();
|
||||
let enters: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Recorded::Enter { frame, parent, .. } => Some((*frame, *parent)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(enters.len(), 3);
|
||||
assert_eq!(enters[0].1, None);
|
||||
assert_eq!(enters[1].1, Some(main));
|
||||
assert_eq!(enters[2].1, Some(child));
|
||||
let exits = events
|
||||
.iter()
|
||||
.filter(|event| matches!(event, Recorded::Exit { .. }))
|
||||
.count();
|
||||
assert_eq!(exits, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_budget_truncates_with_one_marker_and_keeps_critical_events() {
|
||||
let config = ObservationConfig {
|
||||
max_observation_events: 2,
|
||||
..ObservationConfig::default()
|
||||
};
|
||||
let (mut host, events) = observed_host(config);
|
||||
let ctx = context();
|
||||
let stdout = match host
|
||||
.resource_open("stdio", "stdout", &["write".to_string()], &ctx)
|
||||
.unwrap()
|
||||
{
|
||||
Value::Resource(handle) => handle,
|
||||
other => panic!("expected a resource handle, got {other:?}"),
|
||||
};
|
||||
let first = host
|
||||
.observation_begin_frame("f1", "m", None)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
host.observation_end_frame(Some(first), "ok", "m", None)
|
||||
.unwrap();
|
||||
// Third structural event exceeds the two-event budget.
|
||||
host.observation_begin_frame("f2", "m", None).unwrap();
|
||||
host.resource_write(stdout, b"still-visible", &ctx).unwrap();
|
||||
|
||||
let events = events.borrow();
|
||||
let markers = events
|
||||
.iter()
|
||||
.filter(|event| matches!(event, Recorded::Truncated { .. }))
|
||||
.count();
|
||||
assert_eq!(markers, 1, "exactly one truncation marker");
|
||||
assert!(
|
||||
events.contains(&Recorded::Stdout(b"still-visible".to_vec())),
|
||||
"stdout chunks are critical and survive the structural budget"
|
||||
);
|
||||
assert!(events.iter().any(|event| matches!(
|
||||
event,
|
||||
Recorded::Truncated { reason, limit, written }
|
||||
if reason == "event_budget" && *limit == 2 && *written == 2
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_sink_aborts_and_is_saved_for_the_next_boundary() {
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
.with_observation(
|
||||
ObservationConfig::default(),
|
||||
Box::new(Recorder {
|
||||
events: Rc::clone(&events),
|
||||
fail: true,
|
||||
}),
|
||||
);
|
||||
let error = host
|
||||
.observation_begin_frame("f", "m", None)
|
||||
.expect_err("a broken sink must propagate");
|
||||
assert_eq!(error.category, ErrorCategory::Observation);
|
||||
assert_eq!(error.code(), "observe.transport_failed");
|
||||
assert_eq!(host.observation_failure(), Some("synthetic broken pipe"));
|
||||
let boundary = host.consume_fuel(1, None).expect_err("next boundary fails");
|
||||
assert_eq!(boundary.category, ErrorCategory::Observation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_host_has_no_observation_state() {
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
);
|
||||
assert!(!host.observation_enabled());
|
||||
assert!(host.observation_config().is_none());
|
||||
assert_eq!(host.observation_begin_frame("f", "m", None).unwrap(), None);
|
||||
host.observation_end_frame(None, "ok", "m", None).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_encoding_is_selected_bounded_and_handle_safe() {
|
||||
let mut config = ObservationConfig {
|
||||
max_value_bytes: 8,
|
||||
..ObservationConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
encode_value(&config, false, &Value::int(42)),
|
||||
(ValueState::NotRequested, None)
|
||||
);
|
||||
let (state, value) = encode_value(&config, true, &Value::int(42));
|
||||
assert_eq!(state, ValueState::Observed);
|
||||
assert_eq!(value.unwrap().wire["decimal"], "42");
|
||||
|
||||
const SENTINEL: &str = "DO_NOT_LEAK_SENTINEL_1";
|
||||
let (state, value) = encode_value(&config, true, &Value::text(SENTINEL));
|
||||
assert_eq!(state, ValueState::Redacted);
|
||||
assert!(value.is_none(), "text requires explicit consent");
|
||||
|
||||
config.allow_text_values = true;
|
||||
let (state, value) = encode_value(&config, true, &Value::text(SENTINEL));
|
||||
assert_eq!(state, ValueState::Truncated);
|
||||
let wire = value.unwrap().wire;
|
||||
assert_eq!(wire["truncated"], true);
|
||||
assert!(wire["value"].as_str().unwrap().len() <= 8);
|
||||
assert!(!wire.to_string().contains(SENTINEL));
|
||||
|
||||
config.allow_text_values = true;
|
||||
let text = "开始文本\n";
|
||||
let (state, value) = encode_value(&config, true, &Value::text(text));
|
||||
assert_eq!(state, ValueState::Truncated);
|
||||
let wire = value.unwrap().wire;
|
||||
assert!(
|
||||
text.starts_with(wire["value"].as_str().unwrap()),
|
||||
"truncation must keep a UTF-8 scalar prefix"
|
||||
);
|
||||
|
||||
let handle_value = Value::None;
|
||||
let (state, _) = encode_value(&config, true, &handle_value);
|
||||
assert_eq!(state, ValueState::Unsupported);
|
||||
let (state, value) = encode_value(&config, true, &Value::List(vec![Value::int(1)]));
|
||||
assert_eq!(state, ValueState::Unsupported);
|
||||
assert!(value.is_none());
|
||||
}
|
||||
@@ -279,6 +279,7 @@ struct MockProvider {
|
||||
written: Vec<u8>,
|
||||
version: u32,
|
||||
kinds: Vec<&'static str>,
|
||||
provider_name: &'static str,
|
||||
}
|
||||
|
||||
impl MockProvider {
|
||||
@@ -289,13 +290,19 @@ impl MockProvider {
|
||||
written: Vec::new(),
|
||||
version,
|
||||
kinds,
|
||||
provider_name: "mock",
|
||||
}
|
||||
}
|
||||
|
||||
fn with_name(mut self, name: &'static str) -> Self {
|
||||
self.provider_name = name;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl marqdo_host::ResourceProvider for MockProvider {
|
||||
fn name(&self) -> &str {
|
||||
"mock"
|
||||
self.provider_name
|
||||
}
|
||||
fn protocol_version(&self) -> u32 {
|
||||
self.version
|
||||
@@ -421,10 +428,30 @@ fn provider_registration_rejects_versions_reserved_names_and_conflicts() {
|
||||
.register_resource_provider(Box::new(MockProvider::new(b"x", 2, vec!["mock.sensor"])))
|
||||
.unwrap_err();
|
||||
assert_eq!(bad_version.category, ErrorCategory::ResourceUnsupported);
|
||||
let reserved = host
|
||||
.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["stdio"])))
|
||||
.unwrap_err();
|
||||
assert_eq!(reserved.category, ErrorCategory::ResourceUnsupported);
|
||||
for core_kind in marqdo_host::CORE_RESOURCE_KINDS {
|
||||
let reserved_kind = host
|
||||
.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec![core_kind])))
|
||||
.unwrap_err();
|
||||
assert_eq!(reserved_kind.category, ErrorCategory::ResourceUnsupported);
|
||||
assert!(
|
||||
reserved_kind.message.contains("reserved core kind"),
|
||||
"{core_kind}: {}",
|
||||
reserved_kind.message
|
||||
);
|
||||
let reserved_name = host
|
||||
.register_resource_provider(Box::new(
|
||||
MockProvider::new(b"x", 1, vec!["mock.sensor"]).with_name(core_kind),
|
||||
))
|
||||
.unwrap_err();
|
||||
assert_eq!(reserved_name.category, ErrorCategory::ResourceUnsupported);
|
||||
assert!(
|
||||
reserved_name
|
||||
.message
|
||||
.contains("reserved core resource kind"),
|
||||
"{core_kind}: {}",
|
||||
reserved_name.message
|
||||
);
|
||||
}
|
||||
host.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"])))
|
||||
.unwrap();
|
||||
let conflict = host
|
||||
|
||||
@@ -28,7 +28,7 @@ const fn opt(name: &'static str) -> BuiltinParam {
|
||||
/// A builtin function or host operation.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Builtin {
|
||||
/// Canonical call name (may be namespaced, e.g. `math.eval`).
|
||||
/// Canonical call name (may be namespaced, e.g. `foreign.run`).
|
||||
pub name: &'static str,
|
||||
/// Alternative names (Chinese/English aliases).
|
||||
pub aliases: &'static [&'static str],
|
||||
@@ -104,41 +104,6 @@ const REF: Builtin = Builtin {
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const MATH_PARSE: Builtin = Builtin {
|
||||
name: "math.parse",
|
||||
aliases: &[],
|
||||
params: &[req("formula")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const MATH_EVAL: Builtin = Builtin {
|
||||
name: "math.eval",
|
||||
aliases: &[],
|
||||
params: &[req("formula"), req("bindings"), opt("target")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const MATH_SUBSTITUTE: Builtin = Builtin {
|
||||
name: "math.substitute",
|
||||
aliases: &[],
|
||||
params: &[req("formula"), req("bindings")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const MATH_SIMPLIFY: Builtin = Builtin {
|
||||
name: "math.simplify",
|
||||
aliases: &[],
|
||||
params: &[req("formula")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const MATH_DIFFERENTIATE: Builtin = Builtin {
|
||||
name: "math.differentiate",
|
||||
aliases: &[],
|
||||
params: &[req("formula"), req("变量")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const FOREIGN_RUN: Builtin = Builtin {
|
||||
name: "foreign.run",
|
||||
aliases: &[],
|
||||
@@ -331,11 +296,6 @@ pub const BUILTINS: &[Builtin] = &[
|
||||
FLOAT,
|
||||
TABLE,
|
||||
REF,
|
||||
MATH_PARSE,
|
||||
MATH_EVAL,
|
||||
MATH_SUBSTITUTE,
|
||||
MATH_SIMPLIFY,
|
||||
MATH_DIFFERENTIATE,
|
||||
FOREIGN_RUN,
|
||||
FOREIGN_CALL,
|
||||
FS_READ,
|
||||
@@ -427,7 +387,8 @@ mod tests {
|
||||
fn lookup_aliases() {
|
||||
assert_eq!(find("print").unwrap().name, "打印");
|
||||
assert_eq!(find("打印").unwrap().name, "打印");
|
||||
assert!(!find("math.eval").unwrap().named_only);
|
||||
assert!(find("table").is_some());
|
||||
assert!(find("math.eval").is_none());
|
||||
assert!(find("nope").is_none());
|
||||
}
|
||||
|
||||
@@ -437,15 +398,11 @@ mod tests {
|
||||
let print = find("打印").unwrap();
|
||||
assert!(validate_args(print, &parse_arguments("(1)").unwrap()).is_ok());
|
||||
assert!(validate_args(print, &parse_arguments("()").unwrap()).is_err());
|
||||
let eval = find("math.eval").unwrap();
|
||||
assert!(validate_args(
|
||||
eval,
|
||||
&parse_arguments("(formula=ref(\"#x\"), bindings={}, target=\"A\")").unwrap()
|
||||
)
|
||||
.is_ok());
|
||||
// math.eval accepts positional arguments followed by named ones.
|
||||
assert!(validate_args(eval, &parse_arguments("(ref(\"#x\"), {})").unwrap()).is_ok());
|
||||
assert!(validate_args(eval, &parse_arguments("(formula=1, nope=2)").unwrap()).is_err());
|
||||
assert!(validate_args(eval, &parse_arguments("(1, 2, 3, 4)").unwrap()).is_err());
|
||||
let table = find("table").unwrap();
|
||||
assert!(validate_args(table, &parse_arguments("(表头=[1], 行=[])").unwrap()).is_ok());
|
||||
// Builtins accept positional arguments followed by named ones.
|
||||
assert!(validate_args(table, &parse_arguments("([1], [])").unwrap()).is_ok());
|
||||
assert!(validate_args(table, &parse_arguments("(表头=[1], nope=[])").unwrap()).is_err());
|
||||
assert!(validate_args(table, &parse_arguments("(1, 2, 3)").unwrap()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ impl fmt::Display for CallSiteKey {
|
||||
pub enum BoundTarget {
|
||||
/// A fixed language builtin, by canonical builtin name.
|
||||
Builtin {
|
||||
/// Canonical name (for example `math.eval`), not a user alias.
|
||||
/// Canonical name (for example `foreign.run`), not a user alias.
|
||||
canonical_name: String,
|
||||
},
|
||||
/// A function defined by a Markdown heading.
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
[package]
|
||||
name = "marqdo-math"
|
||||
description = "Native Math/Formula kernel: parse, substitute and evaluate a defined subset"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
marqdo-value = { workspace = true }
|
||||
num-bigint = { workspace = true }
|
||||
num-rational = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -1,394 +0,0 @@
|
||||
//! Formula AST, exact-number representation and deterministic rendering.
|
||||
//!
|
||||
//! The AST is public so that `math.inspect` and tests can observe the parsed
|
||||
//! structure instead of re-parsing the source string. [`Formula::source`] keeps
|
||||
//! the original LaTeX exactly as supplied to [`crate::parse`]; rendering is only
|
||||
//! used when an operation (currently [`crate::substitute`]) produces a new
|
||||
//! formula.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use num_bigint::BigInt;
|
||||
use num_rational::Ratio;
|
||||
use num_traits::{One, Signed, Zero};
|
||||
|
||||
/// Exact rational number used internally by the kernel.
|
||||
///
|
||||
/// This is `num-rational`'s generic `Ratio` instantiated over the same
|
||||
/// `num-bigint` `BigInt` type used by [`marqdo_value::Value::Int`], so values can
|
||||
/// cross the kernel boundary without a lossy or string round-trip.
|
||||
pub type Rational = Ratio<BigInt>;
|
||||
|
||||
/// Named mathematical constants supported by the subset.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Constant {
|
||||
/// The circle ratio, written `\pi` or `pi`.
|
||||
Pi,
|
||||
/// Euler's number, written `\e` or `e`.
|
||||
E,
|
||||
}
|
||||
|
||||
impl Constant {
|
||||
/// The approximate `f64` value of this constant.
|
||||
pub fn value(self) -> f64 {
|
||||
match self {
|
||||
Constant::Pi => std::f64::consts::PI,
|
||||
Constant::E => std::f64::consts::E,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A node of the supported expression grammar.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Expr {
|
||||
/// An exact numeric literal. Decimal literals are reduced to exact
|
||||
/// rationals (for example `0.25` becomes `1/4`).
|
||||
Number(Rational),
|
||||
/// A free variable resolved from the binding map at evaluation time.
|
||||
Variable(String),
|
||||
/// A named constant (`\pi`, `pi`, `\e`, `e`).
|
||||
Constant(Constant),
|
||||
/// Unary negation.
|
||||
Neg(Box<Expr>),
|
||||
/// Addition.
|
||||
Add(Box<Expr>, Box<Expr>),
|
||||
/// Subtraction.
|
||||
Sub(Box<Expr>, Box<Expr>),
|
||||
/// Multiplication.
|
||||
Mul(Box<Expr>, Box<Expr>),
|
||||
/// Division. `\frac{a}{b}` is parsed as `Div(a, b)`.
|
||||
Div(Box<Expr>, Box<Expr>),
|
||||
/// Exponentiation. The exponent must evaluate to an integer.
|
||||
Pow(Box<Expr>, Box<Expr>),
|
||||
/// Square root. `\sqrt{x}` is a dedicated node so that perfect squares can
|
||||
/// stay exact.
|
||||
Sqrt(Box<Expr>),
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
/// Collect every free variable name (constants are not variables).
|
||||
pub fn variables(&self) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
self.collect_variables(&mut names);
|
||||
names
|
||||
}
|
||||
|
||||
fn collect_variables(&self, names: &mut BTreeSet<String>) {
|
||||
match self {
|
||||
Expr::Number(_) | Expr::Constant(_) => {}
|
||||
Expr::Variable(name) => {
|
||||
names.insert(name.clone());
|
||||
}
|
||||
Expr::Neg(inner) | Expr::Sqrt(inner) => inner.collect_variables(names),
|
||||
Expr::Add(left, right)
|
||||
| Expr::Sub(left, right)
|
||||
| Expr::Mul(left, right)
|
||||
| Expr::Div(left, right)
|
||||
| Expr::Pow(left, right) => {
|
||||
left.collect_variables(names);
|
||||
right.collect_variables(names);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of syntactic occurrences of `name`.
|
||||
pub fn occurrences(&self, name: &str) -> usize {
|
||||
match self {
|
||||
Expr::Number(_) | Expr::Constant(_) => 0,
|
||||
Expr::Variable(variable) => usize::from(variable == name),
|
||||
Expr::Neg(inner) | Expr::Sqrt(inner) => inner.occurrences(name),
|
||||
Expr::Add(left, right)
|
||||
| Expr::Sub(left, right)
|
||||
| Expr::Mul(left, right)
|
||||
| Expr::Div(left, right)
|
||||
| Expr::Pow(left, right) => left.occurrences(name) + right.occurrences(name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Top level shape of a parsed formula: an expression or a single equation.
|
||||
///
|
||||
/// A formula with one `=` is an [`FormulaKind::Equation`]; it is never an
|
||||
/// assignment. More than one `=` is a parse error.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum FormulaKind {
|
||||
/// A standalone arithmetic expression.
|
||||
Expression(Expr),
|
||||
/// `left = right`.
|
||||
Equation {
|
||||
/// Left-hand side.
|
||||
left: Expr,
|
||||
/// Right-hand side.
|
||||
right: Expr,
|
||||
},
|
||||
}
|
||||
|
||||
/// A parsed formula plus the original source text.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Formula {
|
||||
/// Original LaTeX source exactly as supplied to [`crate::parse`], or the
|
||||
/// canonical rendering produced by [`crate::substitute`].
|
||||
pub source: String,
|
||||
/// Parsed structure.
|
||||
pub kind: FormulaKind,
|
||||
}
|
||||
|
||||
impl Formula {
|
||||
/// Whether this formula is an equation.
|
||||
pub fn is_equation(&self) -> bool {
|
||||
matches!(self.kind, FormulaKind::Equation { .. })
|
||||
}
|
||||
|
||||
/// Borrow the expression when this formula is not an equation.
|
||||
pub fn expression(&self) -> Option<&Expr> {
|
||||
match &self.kind {
|
||||
FormulaKind::Expression(expr) => Some(expr),
|
||||
FormulaKind::Equation { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrow both sides when this formula is an equation.
|
||||
pub fn equation(&self) -> Option<(&Expr, &Expr)> {
|
||||
match &self.kind {
|
||||
FormulaKind::Expression(_) => None,
|
||||
FormulaKind::Equation { left, right } => Some((left, right)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every free variable appearing in the formula, in sorted order.
|
||||
pub fn variables(&self) -> BTreeSet<String> {
|
||||
match &self.kind {
|
||||
FormulaKind::Expression(expr) => expr.variables(),
|
||||
FormulaKind::Equation { left, right } => {
|
||||
let mut names = left.variables();
|
||||
names.extend(right.variables());
|
||||
names
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render this formula back to the supported LaTeX subset deterministically.
|
||||
///
|
||||
/// The result is always re-parseable by [`crate::parse`]. This is used by
|
||||
/// [`crate::substitute`] to build the new [`Formula::source`].
|
||||
pub fn render(&self) -> String {
|
||||
match &self.kind {
|
||||
FormulaKind::Expression(expr) => render_expr(expr),
|
||||
FormulaKind::Equation { left, right } => {
|
||||
format!("{} = {}", render_expr(left), render_expr(right))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rendering precedence levels, from loosest to tightest.
|
||||
const PREC_ADD: u8 = 1;
|
||||
const PREC_MUL: u8 = 2;
|
||||
const PREC_UNARY: u8 = 3;
|
||||
const PREC_POW: u8 = 4;
|
||||
const PREC_ATOM: u8 = 5;
|
||||
|
||||
/// Fractional digits beyond which a terminating rational is rendered as
|
||||
/// `\frac{..}{..}` instead of a long decimal. Chosen so that substituted
|
||||
/// `f64` values that are exactly representable in a short decimal stay readable,
|
||||
/// while binary-exact values with long expansions use a compact fraction.
|
||||
const MAX_RENDERED_DECIMAL_DIGITS: u32 = 32;
|
||||
|
||||
/// Render an expression without surrounding parentheses.
|
||||
pub fn render_expr(expr: &Expr) -> String {
|
||||
render(expr, 0)
|
||||
}
|
||||
|
||||
fn render(expr: &Expr, parent_precedence: u8) -> String {
|
||||
match expr {
|
||||
Expr::Number(value) => {
|
||||
let (text, precedence) = render_rational(value);
|
||||
parenthesize(text, precedence, parent_precedence)
|
||||
}
|
||||
Expr::Variable(name) => name.clone(),
|
||||
Expr::Constant(constant) => match constant {
|
||||
Constant::Pi => "\\pi".to_string(),
|
||||
Constant::E => "\\e".to_string(),
|
||||
},
|
||||
Expr::Neg(inner) => {
|
||||
let text = format!("-{}", render(inner, PREC_UNARY));
|
||||
parenthesize(text, PREC_UNARY, parent_precedence)
|
||||
}
|
||||
Expr::Add(left, right) => {
|
||||
let text = format!(
|
||||
"{} + {}",
|
||||
render(left, PREC_ADD),
|
||||
render(right, PREC_ADD + 1)
|
||||
);
|
||||
parenthesize(text, PREC_ADD, parent_precedence)
|
||||
}
|
||||
Expr::Sub(left, right) => {
|
||||
let text = format!(
|
||||
"{} - {}",
|
||||
render(left, PREC_ADD),
|
||||
render(right, PREC_ADD + 1)
|
||||
);
|
||||
parenthesize(text, PREC_ADD, parent_precedence)
|
||||
}
|
||||
Expr::Mul(left, right) => {
|
||||
let text = format!(
|
||||
"{} * {}",
|
||||
render(left, PREC_MUL),
|
||||
render(right, PREC_MUL + 1)
|
||||
);
|
||||
parenthesize(text, PREC_MUL, parent_precedence)
|
||||
}
|
||||
Expr::Div(left, right) => {
|
||||
let text = format!(
|
||||
"{} / {}",
|
||||
render(left, PREC_MUL),
|
||||
render(right, PREC_MUL + 1)
|
||||
);
|
||||
parenthesize(text, PREC_MUL, parent_precedence)
|
||||
}
|
||||
Expr::Pow(base, exponent) => {
|
||||
let text = format!(
|
||||
"{} ^ {}",
|
||||
render(base, PREC_POW + 1),
|
||||
render(exponent, PREC_POW)
|
||||
);
|
||||
parenthesize(text, PREC_POW, parent_precedence)
|
||||
}
|
||||
Expr::Sqrt(inner) => format!("\\sqrt{{{}}}", render(inner, 0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parenthesize(text: String, precedence: u8, parent_precedence: u8) -> String {
|
||||
if precedence < parent_precedence {
|
||||
format!("({text})")
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Render an exact rational, returning the text and its rendering precedence.
|
||||
///
|
||||
/// Integral values render as integers. Values with a terminating decimal
|
||||
/// expansion of at most [`MAX_RENDERED_DECIMAL_DIGITS`] digits render as
|
||||
/// decimals; everything else renders as `\frac{numerator}{denominator}`.
|
||||
fn render_rational(value: &Rational) -> (String, u8) {
|
||||
if value.is_integer() {
|
||||
let integer = value.to_integer();
|
||||
let negative = integer.sign() == num_bigint::Sign::Minus;
|
||||
let precedence = if negative { PREC_UNARY } else { PREC_ATOM };
|
||||
return (integer.to_string(), precedence);
|
||||
}
|
||||
|
||||
if let Some(places) = decimal_places(value.denom()) {
|
||||
if places <= MAX_RENDERED_DECIMAL_DIGITS {
|
||||
let scale = BigInt::from(10_u32).pow(places);
|
||||
let scaled = value.numer() * &scale / value.denom();
|
||||
let negative = scaled.sign() == num_bigint::Sign::Minus;
|
||||
let digits = scaled.abs().to_string();
|
||||
let places = places as usize;
|
||||
let decimal = if digits.len() <= places {
|
||||
format!("0.{}{digits}", "0".repeat(places - digits.len()))
|
||||
} else {
|
||||
let split = digits.len() - places;
|
||||
format!("{}.{}", &digits[..split], &digits[split..])
|
||||
};
|
||||
let precedence = if negative { PREC_UNARY } else { PREC_ATOM };
|
||||
let text = if negative {
|
||||
format!("-{decimal}")
|
||||
} else {
|
||||
decimal
|
||||
};
|
||||
return (text, precedence);
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
format!("\\frac{{{}}}{{{}}}", value.numer(), value.denom()),
|
||||
PREC_ATOM,
|
||||
)
|
||||
}
|
||||
|
||||
/// Number of fractional digits needed for the terminating decimal expansion of
|
||||
/// `denominator`, or `None` when the expansion does not terminate or is longer
|
||||
/// than [`MAX_RENDERED_DECIMAL_DIGITS`].
|
||||
fn decimal_places(denominator: &BigInt) -> Option<u32> {
|
||||
let mut reduced = denominator.clone();
|
||||
let two = BigInt::from(2_u32);
|
||||
let five = BigInt::from(5_u32);
|
||||
let mut twos = 0_u32;
|
||||
while reduced.is_positive() && (&reduced % &two).is_zero() {
|
||||
reduced /= &two;
|
||||
twos += 1;
|
||||
if twos > MAX_RENDERED_DECIMAL_DIGITS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut fives = 0_u32;
|
||||
while reduced.is_positive() && (&reduced % &five).is_zero() {
|
||||
reduced /= &five;
|
||||
fives += 1;
|
||||
if fives > MAX_RENDERED_DECIMAL_DIGITS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if reduced.is_one() {
|
||||
Some(twos.max(fives))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn number(numerator: i64, denominator: i64) -> Expr {
|
||||
Expr::Number(Ratio::new(
|
||||
BigInt::from(numerator),
|
||||
BigInt::from(denominator),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_round_trips_through_parse() {
|
||||
// The renderer must always emit text the parser accepts.
|
||||
for source in [
|
||||
"1 + 2 * 3",
|
||||
"(1 + 2) * 3",
|
||||
"2 ^ (3 + 1)",
|
||||
"\\frac{1}{3}",
|
||||
"-4 ^ 2",
|
||||
"2 ^ (-3)",
|
||||
"\\sqrt{2}",
|
||||
"a = 2 * b + 1",
|
||||
"(2 ^ 3) ^ 2",
|
||||
"1 - (2 - 3)",
|
||||
"a / (b * c)",
|
||||
] {
|
||||
let formula = crate::parse(source).expect("fixture parses");
|
||||
let rendered = formula.render();
|
||||
let reparsed = crate::parse(&rendered)
|
||||
.unwrap_or_else(|err| panic!("rendered {rendered:?} does not parse: {err}"));
|
||||
assert_eq!(reparsed.kind, formula.kind, "source {source:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_and_fraction_rendering_is_deterministic() {
|
||||
assert_eq!(render_expr(&number(5, 2)), "2.5");
|
||||
assert_eq!(render_expr(&number(-5, 2)), "-2.5");
|
||||
assert_eq!(render_expr(&number(1, 8)), "0.125");
|
||||
assert_eq!(render_expr(&number(1, 3)), "\\frac{1}{3}");
|
||||
assert_eq!(render_expr(&number(0, 1)), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_are_collected_without_constants() {
|
||||
let formula = crate::parse("2 * x + y * \\pi").unwrap();
|
||||
assert_eq!(
|
||||
formula.variables().into_iter().collect::<Vec<_>>(),
|
||||
vec!["x".to_string(), "y".to_string()]
|
||||
);
|
||||
assert_eq!(formula.expression().unwrap().occurrences("x"), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
//! Structured errors returned by the native math kernel.
|
||||
//!
|
||||
//! The kernel never panics on untrusted LaTeX. Every failure is reported as a
|
||||
//! [`MathError`] with a stable [`MathErrorKind`], a human readable message and
|
||||
//! (for parse failures) the byte offset into the original LaTeX source. The
|
||||
//! host layer is expected to map [`MathErrorKind::Unsupported`] to the
|
||||
//! `math.unsupported` diagnostic code and the remaining kinds to the matching
|
||||
//! expression diagnostics.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
/// Broad category of a math kernel failure.
|
||||
///
|
||||
/// The enum is deliberately small: the kernel only distinguishes "the input is
|
||||
/// not in the supported grammar", "the input is in the grammar but outside the
|
||||
/// supported subset", "a name is unbound" and "a value has the wrong type".
|
||||
/// Resource-bound violations (exponent/result size) are reported as
|
||||
/// [`MathErrorKind::Unsupported`] because they are a documented limitation of
|
||||
/// the subset rather than a parse or type problem.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MathErrorKind {
|
||||
/// The input is malformed LaTeX for the supported subset.
|
||||
Parse,
|
||||
/// The input is well-formed but outside the deliberately limited subset, or
|
||||
/// the requested operation/equation shape is not supported.
|
||||
Unsupported,
|
||||
/// A variable used by the formula has no binding.
|
||||
UndefinedVariable,
|
||||
/// A binding or operand has an incompatible type, or an operation is
|
||||
/// undefined for the supplied values (for example division by zero).
|
||||
Type,
|
||||
}
|
||||
|
||||
impl MathErrorKind {
|
||||
/// Stable lowercase label used by diagnostics and tests.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
MathErrorKind::Parse => "parse",
|
||||
MathErrorKind::Unsupported => "unsupported",
|
||||
MathErrorKind::UndefinedVariable => "undefined-variable",
|
||||
MathErrorKind::Type => "type",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MathErrorKind {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// A structured error produced by [`crate::parse`], [`crate::evaluate`] or
|
||||
/// [`crate::substitute`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct MathError {
|
||||
/// Failure category.
|
||||
pub kind: MathErrorKind,
|
||||
/// Human readable explanation. Messages are diagnostic text; callers should
|
||||
/// branch on [`MathError::kind`] rather than on the wording.
|
||||
pub message: String,
|
||||
/// Byte offset into the original LaTeX source, when the failure is tied to
|
||||
/// a specific token.
|
||||
pub position: Option<usize>,
|
||||
}
|
||||
|
||||
impl MathError {
|
||||
/// Construct an error with an explicit kind and optional byte position.
|
||||
pub fn new(kind: MathErrorKind, message: impl Into<String>, position: Option<usize>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
position,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a [`MathErrorKind::Parse`] error.
|
||||
pub fn parse(message: impl Into<String>, position: Option<usize>) -> Self {
|
||||
Self::new(MathErrorKind::Parse, message, position)
|
||||
}
|
||||
|
||||
/// Construct a [`MathErrorKind::Unsupported`] error.
|
||||
pub fn unsupported(message: impl Into<String>, position: Option<usize>) -> Self {
|
||||
Self::new(MathErrorKind::Unsupported, message, position)
|
||||
}
|
||||
|
||||
/// Construct a [`MathErrorKind::UndefinedVariable`] error.
|
||||
pub fn undefined_variable(message: impl Into<String>, position: Option<usize>) -> Self {
|
||||
Self::new(MathErrorKind::UndefinedVariable, message, position)
|
||||
}
|
||||
|
||||
/// Construct a [`MathErrorKind::Type`] error.
|
||||
pub fn type_error(message: impl Into<String>, position: Option<usize>) -> Self {
|
||||
Self::new(MathErrorKind::Type, message, position)
|
||||
}
|
||||
|
||||
/// The documented result-size guard was hit. Reported as `Unsupported` so
|
||||
/// callers can surface a stable `math.unsupported` diagnostic instead of a
|
||||
/// crash or an out-of-memory abort.
|
||||
pub fn size_bound(message: impl Into<String>) -> Self {
|
||||
Self::unsupported(message, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MathError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.kind)?;
|
||||
if let Some(position) = self.position {
|
||||
write!(f, " at byte {position}")?;
|
||||
}
|
||||
write!(f, ": {}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MathError {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn display_includes_kind_and_position() {
|
||||
let err = MathError::parse("expected an expression", Some(3));
|
||||
assert_eq!(err.to_string(), "parse at byte 3: expected an expression");
|
||||
assert_eq!(err.kind.as_str(), "parse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constructors_use_stable_kinds() {
|
||||
assert_eq!(
|
||||
MathError::unsupported("x", None).kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
MathError::undefined_variable("x", None).kind,
|
||||
MathErrorKind::UndefinedVariable
|
||||
);
|
||||
assert_eq!(MathError::type_error("x", None).kind, MathErrorKind::Type);
|
||||
assert_eq!(MathError::size_bound("x").kind, MathErrorKind::Unsupported);
|
||||
assert_eq!(
|
||||
MathErrorKind::UndefinedVariable.to_string(),
|
||||
"undefined-variable"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,695 +0,0 @@
|
||||
//! Exact evaluation, equation solving and substitution.
|
||||
//!
|
||||
//! Numeric semantics are documented on the crate root. In short: literals,
|
||||
//! integer/float bindings and the operators `+ - * / ^` are evaluated as exact
|
||||
//! rationals; `\pi`, `\e` and non-perfect square roots introduce an `f64`
|
||||
//! approximation. The final value is [`Value::Int`] exactly when the exact
|
||||
//! result is an integer and [`Value::Float`] otherwise.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use num_bigint::{BigInt, Sign};
|
||||
use num_rational::Ratio;
|
||||
use num_traits::{One, Signed, ToPrimitive, Zero};
|
||||
|
||||
use marqdo_value::Value;
|
||||
|
||||
use crate::ast::{Expr, Formula, FormulaKind, Rational};
|
||||
use crate::error::MathError;
|
||||
|
||||
/// Maximum magnitude of an integer exponent accepted by `^`.
|
||||
pub const MAX_EXPONENT: u64 = 10_000;
|
||||
|
||||
/// Maximum number of bits (binary digits) allowed for the numerator and for the
|
||||
/// denominator of an exact intermediate or result. This bounds memory and CPU
|
||||
/// for hostile formulas such as `(2^10000)^10000`.
|
||||
pub const MAX_RESULT_BITS: u64 = 1_000_000;
|
||||
|
||||
/// A number during evaluation: either exact or an explicit `f64`
|
||||
/// approximation produced by an irrational operation.
|
||||
#[derive(Debug, Clone)]
|
||||
enum Numeric {
|
||||
Exact(Rational),
|
||||
Approx(f64),
|
||||
}
|
||||
|
||||
impl Numeric {
|
||||
fn exact_zero() -> Self {
|
||||
Numeric::Exact(Ratio::from_integer(BigInt::zero()))
|
||||
}
|
||||
|
||||
fn exact_one() -> Self {
|
||||
Numeric::Exact(Ratio::from_integer(BigInt::one()))
|
||||
}
|
||||
|
||||
fn is_zero(&self) -> bool {
|
||||
match self {
|
||||
Numeric::Exact(value) => value.is_zero(),
|
||||
Numeric::Approx(value) => *value == 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn neg(self) -> Result<Self, MathError> {
|
||||
match self {
|
||||
Numeric::Exact(value) => Ok(Numeric::Exact(-value)),
|
||||
Numeric::Approx(value) => Ok(Numeric::Approx(-value)),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_approx(&self) -> Result<f64, MathError> {
|
||||
match self {
|
||||
Numeric::Approx(value) => Ok(*value),
|
||||
Numeric::Exact(value) => ratio_to_f64(value).ok_or_else(|| {
|
||||
MathError::size_bound(
|
||||
"an exact intermediate result is too large to represent as a Float",
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn add(self, other: Numeric) -> Result<Self, MathError> {
|
||||
match (self, other) {
|
||||
(Numeric::Exact(left), Numeric::Exact(right)) => {
|
||||
Ok(Numeric::Exact(checked_ratio(left + right)?))
|
||||
}
|
||||
(left, right) => Ok(Numeric::Approx(left.to_approx()? + right.to_approx()?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn sub(self, other: Numeric) -> Result<Self, MathError> {
|
||||
match (self, other) {
|
||||
(Numeric::Exact(left), Numeric::Exact(right)) => {
|
||||
Ok(Numeric::Exact(checked_ratio(left - right)?))
|
||||
}
|
||||
(left, right) => Ok(Numeric::Approx(left.to_approx()? - right.to_approx()?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn mul(self, other: Numeric) -> Result<Self, MathError> {
|
||||
match (self, other) {
|
||||
(Numeric::Exact(left), Numeric::Exact(right)) => {
|
||||
Ok(Numeric::Exact(exact_mul(&left, &right)?))
|
||||
}
|
||||
(left, right) => Ok(Numeric::Approx(left.to_approx()? * right.to_approx()?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn div(self, other: Numeric) -> Result<Self, MathError> {
|
||||
if other.is_zero() {
|
||||
return Err(division_by_zero());
|
||||
}
|
||||
match (self, other) {
|
||||
(Numeric::Exact(left), Numeric::Exact(right)) => {
|
||||
Ok(Numeric::Exact(checked_ratio(left / right)?))
|
||||
}
|
||||
(left, right) => Ok(Numeric::Approx(left.to_approx()? / right.to_approx()?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn sqrt(self) -> Result<Self, MathError> {
|
||||
match self {
|
||||
Numeric::Exact(value) => {
|
||||
if value.is_negative() {
|
||||
return Err(MathError::type_error(
|
||||
"square root of a negative number is not supported by the real-valued subset",
|
||||
None,
|
||||
));
|
||||
}
|
||||
let numerator_root = integer_sqrt(value.numer());
|
||||
let denominator_root = integer_sqrt(value.denom());
|
||||
if &(&numerator_root * &numerator_root) == value.numer()
|
||||
&& &(&denominator_root * &denominator_root) == value.denom()
|
||||
{
|
||||
Ok(Numeric::Exact(Ratio::new(numerator_root, denominator_root)))
|
||||
} else {
|
||||
let approximate = ratio_to_f64(&value).ok_or_else(|| {
|
||||
MathError::size_bound(
|
||||
"square root operands are outside the representable Float range",
|
||||
)
|
||||
})?;
|
||||
Ok(Numeric::Approx(approximate.sqrt()))
|
||||
}
|
||||
}
|
||||
Numeric::Approx(value) => {
|
||||
if value < 0.0 {
|
||||
return Err(MathError::type_error(
|
||||
"square root of a negative number is not supported by the real-valued subset",
|
||||
None,
|
||||
));
|
||||
}
|
||||
Ok(Numeric::Approx(value.sqrt()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pow(self, exponent: BigInt) -> Result<Self, MathError> {
|
||||
let negative_exponent = exponent.sign() == Sign::Minus;
|
||||
let magnitude = exponent.magnitude();
|
||||
let bound = num_bigint::BigUint::from(MAX_EXPONENT);
|
||||
if *magnitude > bound {
|
||||
return Err(MathError::size_bound(format!(
|
||||
"exponent magnitude exceeds the supported bound of {MAX_EXPONENT}"
|
||||
)));
|
||||
}
|
||||
let exponent_u32 = magnitude
|
||||
.to_u32()
|
||||
.ok_or_else(|| MathError::size_bound("exponent is outside the supported bound"))?;
|
||||
|
||||
match self {
|
||||
Numeric::Exact(base) => {
|
||||
if exponent_u32 == 0 {
|
||||
if base.is_zero() {
|
||||
return Err(MathError::type_error(
|
||||
"0 ^ 0 is undefined in the native math subset",
|
||||
None,
|
||||
));
|
||||
}
|
||||
return Ok(Numeric::Exact(Ratio::from_integer(BigInt::one())));
|
||||
}
|
||||
if base.is_zero() && negative_exponent {
|
||||
return Err(division_by_zero());
|
||||
}
|
||||
let max_bits = base.numer().bits().max(base.denom().bits());
|
||||
let estimated_bits = max_bits.saturating_mul(u64::from(exponent_u32));
|
||||
if estimated_bits > MAX_RESULT_BITS {
|
||||
return Err(MathError::size_bound(format!(
|
||||
"exponentiation result would exceed the supported size bound of {MAX_RESULT_BITS} bits"
|
||||
)));
|
||||
}
|
||||
let numerator = base.numer().pow(exponent_u32);
|
||||
let denominator = base.denom().pow(exponent_u32);
|
||||
let result = if negative_exponent {
|
||||
Ratio::new(denominator, numerator)
|
||||
} else {
|
||||
Ratio::new(numerator, denominator)
|
||||
};
|
||||
Ok(Numeric::Exact(checked_ratio(result)?))
|
||||
}
|
||||
Numeric::Approx(base) => {
|
||||
if base == 0.0 && negative_exponent {
|
||||
return Err(division_by_zero());
|
||||
}
|
||||
let exponent = exponent_u32 as i32;
|
||||
Ok(Numeric::Approx(base.powi(exponent)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_value(self) -> Result<Value, MathError> {
|
||||
match self {
|
||||
Numeric::Exact(value) => {
|
||||
if value.is_integer() {
|
||||
Ok(Value::Int(value.to_integer()))
|
||||
} else {
|
||||
Ok(Value::Float(ratio_to_f64(&value).ok_or_else(|| {
|
||||
MathError::size_bound("exact result is too large to represent as a Float")
|
||||
})?))
|
||||
}
|
||||
}
|
||||
Numeric::Approx(value) => Ok(Value::Float(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn division_by_zero() -> MathError {
|
||||
MathError::type_error(
|
||||
"division by zero is not defined in the native math subset",
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn checked_ratio(value: Rational) -> Result<Rational, MathError> {
|
||||
if value.numer().bits() > MAX_RESULT_BITS || value.denom().bits() > MAX_RESULT_BITS {
|
||||
return Err(MathError::size_bound(format!(
|
||||
"intermediate result exceeds the supported size bound of {MAX_RESULT_BITS} bits"
|
||||
)));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Convert an exact rational to `f64` without going through `Ratio`'s
|
||||
/// `ToPrimitive` impl (which is bound to a different `num-bigint` version in
|
||||
/// `num-rational` 0.4). Returns `None` when the value is outside the finite
|
||||
/// `f64` range or would lose everything to underflow.
|
||||
fn ratio_to_f64(value: &Rational) -> Option<f64> {
|
||||
if value.is_zero() {
|
||||
return Some(0.0);
|
||||
}
|
||||
let negative = value.numer().sign() == Sign::Minus;
|
||||
let (numerator_mantissa, numerator_exponent) = scaled_f64_mantissa(&value.numer().abs());
|
||||
let (denominator_mantissa, denominator_exponent) = scaled_f64_mantissa(value.denom());
|
||||
let exponent = numerator_exponent - denominator_exponent;
|
||||
if exponent > 1023 {
|
||||
return None;
|
||||
}
|
||||
if exponent < -1075 {
|
||||
return Some(if negative { -0.0 } else { 0.0 });
|
||||
}
|
||||
let mut result = numerator_mantissa / denominator_mantissa;
|
||||
result *= 2_f64.powi(exponent as i32);
|
||||
if !result.is_finite() {
|
||||
return None;
|
||||
}
|
||||
Some(if negative { -result } else { result })
|
||||
}
|
||||
|
||||
/// Decompose a non-negative integer into `(mantissa, exponent)` such that the
|
||||
/// value is approximately `mantissa * 2^exponent` and `mantissa` fits in `f64`.
|
||||
fn scaled_f64_mantissa(value: &BigInt) -> (f64, i64) {
|
||||
debug_assert!(!value.is_negative());
|
||||
let bits = value.bits();
|
||||
if bits == 0 {
|
||||
return (0.0, 0);
|
||||
}
|
||||
// Keep the most significant 64 bits; the low bits only affect the last
|
||||
// ~11 bits of the f64 mantissa, which is below the documented precision.
|
||||
let shift = bits.saturating_sub(64);
|
||||
let top = (value >> shift).to_u64().unwrap_or(u64::MAX);
|
||||
(top as f64, shift as i64)
|
||||
}
|
||||
|
||||
fn exact_mul(left: &Rational, right: &Rational) -> Result<Rational, MathError> {
|
||||
// Pre-check before allocating so that multiplying two large operands cannot
|
||||
// allocate an out-of-bound intermediate.
|
||||
let numerator_bits = left.numer().bits().saturating_add(right.numer().bits());
|
||||
let denominator_bits = left.denom().bits().saturating_add(right.denom().bits());
|
||||
if numerator_bits > MAX_RESULT_BITS || denominator_bits > MAX_RESULT_BITS {
|
||||
return Err(MathError::size_bound(format!(
|
||||
"multiplication result would exceed the supported size bound of {MAX_RESULT_BITS} bits"
|
||||
)));
|
||||
}
|
||||
checked_ratio(left * right)
|
||||
}
|
||||
|
||||
/// Integer square root of a non-negative integer (Newton iteration).
|
||||
fn integer_sqrt(value: &BigInt) -> BigInt {
|
||||
debug_assert!(!value.is_negative());
|
||||
if value.is_zero() {
|
||||
return BigInt::zero();
|
||||
}
|
||||
let mut estimate = BigInt::one() << value.bits().div_ceil(2) as usize;
|
||||
loop {
|
||||
let next = (&estimate + value / &estimate) >> 1;
|
||||
if next >= estimate {
|
||||
return estimate;
|
||||
}
|
||||
estimate = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a finite `f64` into the exact binary rational it represents.
|
||||
fn float_to_ratio(value: f64) -> Option<Rational> {
|
||||
if !value.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if value == 0.0 {
|
||||
return Some(Ratio::from_integer(BigInt::zero()));
|
||||
}
|
||||
let bits = value.to_bits();
|
||||
let negative = (bits >> 63) == 1;
|
||||
let exponent_bits = ((bits >> 52) & 0x7ff) as i32;
|
||||
let fraction = bits & ((1_u64 << 52) - 1);
|
||||
let (mantissa, exponent) = if exponent_bits == 0 {
|
||||
(fraction, -1074_i32)
|
||||
} else {
|
||||
(fraction | (1_u64 << 52), exponent_bits - 1075)
|
||||
};
|
||||
let mut numerator = BigInt::from(mantissa);
|
||||
let mut denominator = BigInt::one();
|
||||
if exponent >= 0 {
|
||||
numerator <<= exponent as usize;
|
||||
} else {
|
||||
denominator <<= (-exponent) as usize;
|
||||
}
|
||||
if negative {
|
||||
numerator = -numerator;
|
||||
}
|
||||
Some(Ratio::new(numerator, denominator))
|
||||
}
|
||||
|
||||
/// Convert a [`Value`] binding into a kernel number.
|
||||
fn binding_numeric(name: &str, bindings: &BTreeMap<String, Value>) -> Result<Numeric, MathError> {
|
||||
match bindings.get(name) {
|
||||
None => Err(MathError::undefined_variable(
|
||||
format!("variable `{name}` is not bound"),
|
||||
None,
|
||||
)),
|
||||
Some(Value::Int(value)) => Ok(Numeric::Exact(Ratio::from_integer(value.clone()))),
|
||||
Some(Value::Float(value)) => float_to_ratio(*value).map(Numeric::Exact).ok_or_else(|| {
|
||||
MathError::type_error(
|
||||
format!(
|
||||
"binding `{name}` is a non-finite Float; the math kernel only accepts finite numeric bindings"
|
||||
),
|
||||
None,
|
||||
)
|
||||
}),
|
||||
Some(other) => Err(MathError::type_error(
|
||||
format!(
|
||||
"binding `{name}` has type {} but the math kernel requires Int or Float",
|
||||
other.type_name()
|
||||
),
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_expr(expr: &Expr, bindings: &BTreeMap<String, Value>) -> Result<Numeric, MathError> {
|
||||
match expr {
|
||||
Expr::Number(value) => Ok(Numeric::Exact(value.clone())),
|
||||
Expr::Variable(name) => binding_numeric(name, bindings),
|
||||
Expr::Constant(constant) => Ok(Numeric::Approx(constant.value())),
|
||||
Expr::Neg(inner) => eval_expr(inner, bindings)?.neg(),
|
||||
Expr::Add(left, right) => eval_expr(left, bindings)?.add(eval_expr(right, bindings)?),
|
||||
Expr::Sub(left, right) => eval_expr(left, bindings)?.sub(eval_expr(right, bindings)?),
|
||||
Expr::Mul(left, right) => eval_expr(left, bindings)?.mul(eval_expr(right, bindings)?),
|
||||
Expr::Div(left, right) => eval_expr(left, bindings)?.div(eval_expr(right, bindings)?),
|
||||
Expr::Pow(base, exponent) => {
|
||||
let base = eval_expr(base, bindings)?;
|
||||
base.pow(integer_exponent(&eval_expr(exponent, bindings)?)?)
|
||||
}
|
||||
Expr::Sqrt(inner) => eval_expr(inner, bindings)?.sqrt(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Require a numeric value to be an integer and return it.
|
||||
fn integer_exponent(value: &Numeric) -> Result<BigInt, MathError> {
|
||||
match value {
|
||||
Numeric::Exact(value) if value.is_integer() => Ok(value.to_integer()),
|
||||
_ => Err(MathError::type_error(
|
||||
"exponent must be an integer in the native math subset",
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A linear/affine form `coefficient * target + constant`.
|
||||
struct Affine {
|
||||
coefficient: Numeric,
|
||||
constant: Numeric,
|
||||
}
|
||||
|
||||
impl Affine {
|
||||
fn constant(value: Numeric) -> Self {
|
||||
Self {
|
||||
coefficient: Numeric::exact_zero(),
|
||||
constant: value,
|
||||
}
|
||||
}
|
||||
|
||||
fn target() -> Self {
|
||||
Self {
|
||||
coefficient: Numeric::exact_one(),
|
||||
constant: Numeric::exact_zero(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_target_free(&self) -> bool {
|
||||
self.coefficient.is_zero()
|
||||
}
|
||||
|
||||
fn neg(self) -> Result<Self, MathError> {
|
||||
Ok(Self {
|
||||
coefficient: self.coefficient.neg()?,
|
||||
constant: self.constant.neg()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn add(self, other: Self) -> Result<Self, MathError> {
|
||||
Ok(Self {
|
||||
coefficient: self.coefficient.add(other.coefficient)?,
|
||||
constant: self.constant.add(other.constant)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn sub(self, other: Self) -> Result<Self, MathError> {
|
||||
Ok(Self {
|
||||
coefficient: self.coefficient.sub(other.coefficient)?,
|
||||
constant: self.constant.sub(other.constant)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn scale(self, factor: Numeric) -> Result<Self, MathError> {
|
||||
let coefficient = self.coefficient.mul(factor.clone())?;
|
||||
let constant = self.constant.mul(factor)?;
|
||||
Ok(Self {
|
||||
coefficient,
|
||||
constant,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the affine form of `expr` with respect to `target`.
|
||||
///
|
||||
/// Variables other than `target` are resolved from `bindings`. Operations that
|
||||
/// are not affine in `target` are rejected as unsupported instead of being
|
||||
/// approximated or reported as a solution.
|
||||
fn to_affine(
|
||||
expr: &Expr,
|
||||
target: &str,
|
||||
bindings: &BTreeMap<String, Value>,
|
||||
) -> Result<Affine, MathError> {
|
||||
match expr {
|
||||
Expr::Number(value) => Ok(Affine::constant(Numeric::Exact(value.clone()))),
|
||||
Expr::Constant(constant) => Ok(Affine::constant(Numeric::Approx(constant.value()))),
|
||||
Expr::Variable(name) if name == target => Ok(Affine::target()),
|
||||
Expr::Variable(name) => Ok(Affine::constant(binding_numeric(name, bindings)?)),
|
||||
Expr::Neg(inner) => to_affine(inner, target, bindings)?.neg(),
|
||||
Expr::Add(left, right) => {
|
||||
let left = to_affine(left, target, bindings)?;
|
||||
let right = to_affine(right, target, bindings)?;
|
||||
left.add(right)
|
||||
}
|
||||
Expr::Sub(left, right) => {
|
||||
let left = to_affine(left, target, bindings)?;
|
||||
let right = to_affine(right, target, bindings)?;
|
||||
left.sub(right)
|
||||
}
|
||||
Expr::Mul(left, right) => {
|
||||
let left = to_affine(left, target, bindings)?;
|
||||
let right = to_affine(right, target, bindings)?;
|
||||
match (left.is_target_free(), right.is_target_free()) {
|
||||
(true, true) => Ok(Affine::constant(
|
||||
left.constant.mul(right.constant)?,
|
||||
)),
|
||||
(true, false) => right.scale(left.constant),
|
||||
(false, true) => left.scale(right.constant),
|
||||
(false, false) => Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the equation is not linear in the target (it appears in both factors of a product)"
|
||||
),
|
||||
None,
|
||||
)),
|
||||
}
|
||||
}
|
||||
Expr::Div(left, right) => {
|
||||
let left = to_affine(left, target, bindings)?;
|
||||
let right = to_affine(right, target, bindings)?;
|
||||
if !right.is_target_free() {
|
||||
return Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the target appears in a denominator, which is outside the supported linear forms"
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
if right.constant.is_zero() {
|
||||
return Err(division_by_zero());
|
||||
}
|
||||
let inverse = Numeric::exact_one().div(right.constant)?;
|
||||
left.scale(inverse)
|
||||
}
|
||||
Expr::Pow(base, exponent) => {
|
||||
if exponent.occurrences(target) > 0 {
|
||||
return Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the target appears in an exponent, which is not an affine form"
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let exponent_value = eval_expr(exponent, bindings)?;
|
||||
let exponent = integer_exponent(&exponent_value)?;
|
||||
let base = to_affine(base, target, bindings)?;
|
||||
if base.is_target_free() {
|
||||
let value = base.constant.pow(exponent)?;
|
||||
return Ok(Affine::constant(value));
|
||||
}
|
||||
if exponent.is_zero() {
|
||||
return Ok(Affine::constant(Numeric::exact_one()));
|
||||
}
|
||||
if exponent.is_one() {
|
||||
return Ok(base);
|
||||
}
|
||||
Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the target appears in a power with exponent {exponent}, which is not an affine form"
|
||||
),
|
||||
None,
|
||||
))
|
||||
}
|
||||
Expr::Sqrt(inner) => {
|
||||
if inner.occurrences(target) > 0 {
|
||||
return Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the target appears under a square root, which is not an affine form"
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
Ok(Affine::constant(eval_expr(inner, bindings)?.sqrt()?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate `formula` with `bindings`.
|
||||
///
|
||||
/// For an expression the result is the exact value (or a [`Value::Float`] when
|
||||
/// the exact value is not integral or an irrational operation was involved).
|
||||
/// For an equation `target` selects the variable to solve for; it must occur
|
||||
/// exactly once and the equation must be linear in it.
|
||||
pub fn evaluate(
|
||||
formula: &Formula,
|
||||
bindings: &BTreeMap<String, Value>,
|
||||
target: Option<&str>,
|
||||
) -> Result<Value, MathError> {
|
||||
match (&formula.kind, target) {
|
||||
(FormulaKind::Expression(expr), None) => eval_expr(expr, bindings)?.into_value(),
|
||||
(FormulaKind::Expression(_), Some(_)) => Err(MathError::unsupported(
|
||||
"a target variable is only meaningful for an equation; the formula is a plain expression",
|
||||
None,
|
||||
)),
|
||||
(FormulaKind::Equation { .. }, None) => Err(MathError::unsupported(
|
||||
"evaluating an equation requires a target variable to solve for",
|
||||
None,
|
||||
)),
|
||||
(FormulaKind::Equation { left, right }, Some(target)) => {
|
||||
solve_equation(left, right, target, bindings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn solve_equation(
|
||||
left: &Expr,
|
||||
right: &Expr,
|
||||
target: &str,
|
||||
bindings: &BTreeMap<String, Value>,
|
||||
) -> Result<Value, MathError> {
|
||||
if target.is_empty() {
|
||||
return Err(MathError::unsupported(
|
||||
"target variable name must not be empty",
|
||||
None,
|
||||
));
|
||||
}
|
||||
if target == "pi" || target == "e" {
|
||||
return Err(MathError::unsupported(
|
||||
format!("`{target}` is a reserved constant, not a solvable variable"),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let occurrences = left.occurrences(target) + right.occurrences(target);
|
||||
match occurrences {
|
||||
0 => {
|
||||
return Err(MathError::unsupported(
|
||||
format!("cannot solve for `{target}`: the variable does not occur in the equation"),
|
||||
None,
|
||||
));
|
||||
}
|
||||
1 => {}
|
||||
count => {
|
||||
return Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the variable occurs {count} times, but only a single occurrence in an affine equation is supported"
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let left = to_affine(left, target, bindings)?;
|
||||
let right = to_affine(right, target, bindings)?;
|
||||
let coefficient = left.coefficient.sub(right.coefficient)?;
|
||||
let constant = left.constant.sub(right.constant)?;
|
||||
if coefficient.is_zero() {
|
||||
return Err(MathError::unsupported(
|
||||
format!(
|
||||
"cannot solve for `{target}`: the equation does not uniquely determine the variable"
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
constant.neg()?.div(coefficient)?.into_value()
|
||||
}
|
||||
|
||||
/// Replace every bound variable in `formula` with its exact value.
|
||||
///
|
||||
/// Unbound variables stay symbolic. The returned formula gets a deterministic,
|
||||
/// re-parseable [`Formula::source`] rendering; `Float` bindings are inserted as
|
||||
/// the exact rational value of the `f64` (never as a rounded or lossy decimal).
|
||||
pub fn substitute(
|
||||
formula: &Formula,
|
||||
bindings: &BTreeMap<String, Value>,
|
||||
) -> Result<Formula, MathError> {
|
||||
let kind = match &formula.kind {
|
||||
FormulaKind::Expression(expr) => FormulaKind::Expression(substitute_expr(expr, bindings)?),
|
||||
FormulaKind::Equation { left, right } => FormulaKind::Equation {
|
||||
left: substitute_expr(left, bindings)?,
|
||||
right: substitute_expr(right, bindings)?,
|
||||
},
|
||||
};
|
||||
let substituted = Formula {
|
||||
source: String::new(),
|
||||
kind,
|
||||
};
|
||||
Ok(Formula {
|
||||
source: substituted.render(),
|
||||
kind: substituted.kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn substitute_expr(expr: &Expr, bindings: &BTreeMap<String, Value>) -> Result<Expr, MathError> {
|
||||
match expr {
|
||||
Expr::Number(_) | Expr::Constant(_) => Ok(expr.clone()),
|
||||
Expr::Variable(name) => match bindings.get(name) {
|
||||
None => Ok(expr.clone()),
|
||||
Some(Value::Int(value)) => Ok(Expr::Number(Ratio::from_integer(value.clone()))),
|
||||
Some(Value::Float(value)) => match float_to_ratio(*value) {
|
||||
Some(value) => Ok(Expr::Number(value)),
|
||||
None => Err(MathError::type_error(
|
||||
format!(
|
||||
"binding `{name}` is a non-finite Float; the math kernel only accepts finite numeric bindings"
|
||||
),
|
||||
None,
|
||||
)),
|
||||
},
|
||||
Some(other) => Err(MathError::type_error(
|
||||
format!(
|
||||
"binding `{name}` has type {} but the math kernel requires Int or Float",
|
||||
other.type_name()
|
||||
),
|
||||
None,
|
||||
)),
|
||||
},
|
||||
Expr::Neg(inner) => Ok(Expr::Neg(Box::new(substitute_expr(inner, bindings)?))),
|
||||
Expr::Add(left, right) => Ok(Expr::Add(
|
||||
Box::new(substitute_expr(left, bindings)?),
|
||||
Box::new(substitute_expr(right, bindings)?),
|
||||
)),
|
||||
Expr::Sub(left, right) => Ok(Expr::Sub(
|
||||
Box::new(substitute_expr(left, bindings)?),
|
||||
Box::new(substitute_expr(right, bindings)?),
|
||||
)),
|
||||
Expr::Mul(left, right) => Ok(Expr::Mul(
|
||||
Box::new(substitute_expr(left, bindings)?),
|
||||
Box::new(substitute_expr(right, bindings)?),
|
||||
)),
|
||||
Expr::Div(left, right) => Ok(Expr::Div(
|
||||
Box::new(substitute_expr(left, bindings)?),
|
||||
Box::new(substitute_expr(right, bindings)?),
|
||||
)),
|
||||
Expr::Pow(base, exponent) => Ok(Expr::Pow(
|
||||
Box::new(substitute_expr(base, bindings)?),
|
||||
Box::new(substitute_expr(exponent, bindings)?),
|
||||
)),
|
||||
Expr::Sqrt(inner) => Ok(Expr::Sqrt(Box::new(substitute_expr(inner, bindings)?))),
|
||||
}
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
//! Native Formula kernel for a deliberately limited, documented math subset.
|
||||
//!
|
||||
//! This crate is the native math kernel of the Marqdo toolchain. A Markdown math
|
||||
//! node becomes an inert [`marqdo_value::FormulaValue`]; nothing is evaluated
|
||||
//! implicitly. The host layer calls [`parse`], [`substitute`] and [`evaluate`]
|
||||
//! explicitly, and evaluation is gated by the `math.*` capabilities.
|
||||
//!
|
||||
//! **The kernel never proves anything.** It computes exact or floating values
|
||||
//! and solves a restricted affine equation. It does not establish a theorem,
|
||||
//! does not simplify a formula into a proof obligation and must not be presented
|
||||
//! as a formal verifier. See the blueprint section 5 ("原生 Math") and
|
||||
//! `spec/evaluation.md`.
|
||||
//!
|
||||
//! # Guarantees
|
||||
//!
|
||||
//! * No panics on untrusted LaTeX. Malformed input, unsupported constructs,
|
||||
//! unbounded work and wrong value types all become a structured [`MathError`].
|
||||
//! * Exact rational arithmetic (`num-rational` `Ratio` over `num-bigint`) is used
|
||||
//! wherever possible; integers are arbitrary precision.
|
||||
//! * A formula is never silently simplified, guessed or partially accepted:
|
||||
//! anything outside the grammar below is an error.
|
||||
//!
|
||||
//! # Supported grammar
|
||||
//!
|
||||
//! The parser accepts exactly the following LaTeX subset (whitespace is
|
||||
//! insignificant; byte offsets are reported on parse errors):
|
||||
//!
|
||||
//! ```text
|
||||
//! formula = expr [ "=" expr ] ; single '=' only, never assignment
|
||||
//! expr = term { ("+" | "-") term } ;
|
||||
//! term = unary { ("*" | "/" | "·" | "×" | implicit) unary } ;
|
||||
//! unary = ("+" | "-") unary | power ;
|
||||
//! power = primary [ "^" unary ] ; right associative
|
||||
//! primary = number
|
||||
//! | identifier Unicode letter (plus digits/underscore)
|
||||
//! | "\pi" | "pi" | "\e" | "e" constants
|
||||
//! | "(" expr ")" | "\left(" expr "\right)"
|
||||
//! | "{" expr "}" grouping
|
||||
//! | "\frac{" expr "}{" expr "}" exact division
|
||||
//! | "\sqrt{" expr "}" real square root
|
||||
//! ;
|
||||
//! number = digits [ "." digits ] | "." digits ; decimal, no exponent form
|
||||
//! ```
|
||||
//!
|
||||
//! Notes on the grammar:
|
||||
//!
|
||||
//! * `\cdot` and `\times` are accepted as synonyms for `*`.
|
||||
//! * Implicit multiplication is accepted between adjacent factors where the
|
||||
//! meaning is unambiguous: `2x`, `\pi r^2`, `(a)(b)` and `m a`. Concatenated
|
||||
//! letters form one identifier (`ma` is the variable `ma`; write `m a` or
|
||||
//! `m * a` for a product). Two adjacent number literals are a parse error.
|
||||
//! * Unicode identifiers are supported (for example `面积`, `r`, `速度`). Plain
|
||||
//! multi-letter identifiers are allowed as variables, but the names of common
|
||||
//! elementary functions (`sin`, `cos`, `log`, `exp`, …) are reserved and
|
||||
//! rejected as unsupported so that `sin(x)` is not silently read as a product.
|
||||
//! * A single top-level `=` creates an equation (`F = m a`). It is **not**
|
||||
//! assignment and never writes a binding. A second `=` is a parse error.
|
||||
//!
|
||||
//! # Unsupported constructs
|
||||
//!
|
||||
//! Everything outside the grammar is a structured [`MathErrorKind::Unsupported`]
|
||||
//! or [`MathErrorKind::Parse`] error: matrices, sums/integrals, function calls
|
||||
//! (`\sin`, `\cos`, …), multi-letter commands, `\left[`/`\right]`, mismatched or
|
||||
//! missing braces, scientific notation (`1e3`), commas, arrays, subscripts,
|
||||
//! superscript commands other than the `^` operator, `\frac`/`\sqrt` without
|
||||
//! braced arguments, and so on. Labels, alignment characters and line breaks are
|
||||
//! likewise unsupported. Underscores are ordinary identifier characters rather
|
||||
//! than subscripts: `x_1` is the variable named `x_1`, not `x` subscript `1`.
|
||||
//!
|
||||
//! # Constants and ambiguity handling
|
||||
//!
|
||||
//! * `\pi` and `pi` denote the circle ratio; `\e` and `e` denote Euler's number.
|
||||
//! * These spellings are **reserved**: a binding with the key `pi` or `e` never
|
||||
//! overrides the constant, and they cannot be used as a solve target. Use a
|
||||
//! different variable name (for example `E`, `x`, `r`).
|
||||
//! * `2e` is parsed as `2 * e` (number times the constant); `2e3` is rejected as
|
||||
//! scientific notation rather than silently reinterpreted.
|
||||
//!
|
||||
//! # Numeric semantics
|
||||
//!
|
||||
//! * Decimal literals are exact rationals: `0.25` is `1/4`, not a binary float.
|
||||
//! * `Int` bindings become exact integers. `Float` bindings are interpreted as
|
||||
//! the exact binary rational value of the `f64` (no rounding is introduced);
|
||||
//! non-finite `Float` bindings are a [`MathErrorKind::Type`] error.
|
||||
//! * `+ - * / ^` are exact when both operands are exact. Division keeps a
|
||||
//! rational, so `\frac{1}{3} * 3` evaluates exactly to `1`.
|
||||
//! * The final value is [`marqdo_value::Value::Int`] exactly when the exact result is an
|
||||
//! integer, and [`marqdo_value::Value::Float`] otherwise. Consequently `1.5 + 2.5` returns
|
||||
//! `Int(4)`, while `1 / 2` returns `Float(0.5)`.
|
||||
//! * `\pi`, `\e` and a `\sqrt` of a non-perfect square introduce an `f64`
|
||||
//! approximation; any result derived from one of them is a [`marqdo_value::Value::Float`].
|
||||
//! Precision caveats: approximations follow IEEE-754 binary64, so only about
|
||||
//! 15–17 significant decimal digits are reliable and repeated operations may
|
||||
//! accumulate error. The kernel never claims an approximate result is exact.
|
||||
//! * `\sqrt` of a perfect square of an exact rational stays exact (`\sqrt{4}` is
|
||||
//! `Int(2)`, `\sqrt{1/4}` is `Float(0.5)`); a negative radicand is a type
|
||||
//! error because the subset is real-valued.
|
||||
//! * The exponent of `^` must evaluate to an integer. Its magnitude is bounded by
|
||||
//! [`MAX_EXPONENT`]. Integer powers with a negative exponent are exact
|
||||
//! reciprocals. `0 ^ 0` is a type error.
|
||||
//! * Exact intermediate/result numerators and denominators are bounded by
|
||||
//! [`MAX_RESULT_BITS`]; exceeding the bound returns a structured
|
||||
//! `Unsupported` error instead of hanging or exhausting memory.
|
||||
//! * Parsing is bounded by [`MAX_SOURCE_BYTES`], [`MAX_PARSE_DEPTH`] and
|
||||
//! [`MAX_AST_NODES`]. The node bound also bounds later recursion depth for
|
||||
//! long operator chains, so hostile input cannot overflow the stack during
|
||||
//! evaluation, rendering or substitution.
|
||||
//! * Division by zero, `0 ^ 0` and other undefined real operations are
|
||||
//! [`MathErrorKind::Type`] errors (the kernel has no dedicated division error
|
||||
//! kind, so the host maps the message/kind to `runtime.division_by_zero`).
|
||||
//!
|
||||
//! # Equations
|
||||
//!
|
||||
//! [`evaluate`] of an equation requires `target`. The target must occur exactly
|
||||
//! once and the equation must be affine in it. The kernel supports `+`, `-`,
|
||||
//! multiplication by a target-free side, division where the target is in the
|
||||
//! numerator, and inversion of those operations in either direction (`2x = 4`,
|
||||
//! `4 = 2x`, `x / 2 = 3`, `3 = x / 2`). Other variables are substituted from
|
||||
//! `bindings` first; missing bindings are [`MathErrorKind::UndefinedVariable`].
|
||||
//!
|
||||
//! Solving a target that occurs zero times or more than once, that appears in a
|
||||
//! denominator, under a root, in an exponent or in a non-affine product is a
|
||||
//! structured [`MathErrorKind::Unsupported`] error. A target passed for a plain
|
||||
//! expression, or an equation without a target, is likewise `Unsupported`.
|
||||
//!
|
||||
//! # Substitution
|
||||
//!
|
||||
//! [`substitute`] replaces bound variables with exact numeric literals and keeps
|
||||
//! unbound variables symbolic. The returned [`Formula::source`] is a
|
||||
//! deterministic canonical rendering that [`parse`] accepts again. Because the
|
||||
//! rendering is canonical, it is not byte-identical to the original formatting.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod ast;
|
||||
mod error;
|
||||
mod eval;
|
||||
mod parse;
|
||||
|
||||
pub use ast::{render_expr, Constant, Expr, Formula, FormulaKind, Rational};
|
||||
pub use error::{MathError, MathErrorKind};
|
||||
pub use eval::{evaluate, substitute, MAX_EXPONENT, MAX_RESULT_BITS};
|
||||
pub use parse::{parse, MAX_AST_NODES, MAX_PARSE_DEPTH, MAX_SOURCE_BYTES};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use marqdo_value::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// End-to-end smoke test for the API shape documented on the crate root.
|
||||
#[test]
|
||||
fn public_api_round_trip() {
|
||||
let formula = parse("A = \\pi r^2").unwrap();
|
||||
assert!(formula.is_equation());
|
||||
assert_eq!(formula.source, "A = \\pi r^2");
|
||||
|
||||
let mut bindings = BTreeMap::new();
|
||||
bindings.insert("r".to_string(), Value::int(2));
|
||||
let area = evaluate(&formula, &bindings, Some("A")).unwrap();
|
||||
let Value::Float(area) = area else {
|
||||
panic!("area should be an approximate Float");
|
||||
};
|
||||
assert!((area - std::f64::consts::PI * 4.0).abs() < 1e-12);
|
||||
|
||||
let substituted = substitute(&formula, &bindings).unwrap();
|
||||
assert_eq!(substituted.source, "A = \\pi * 2 ^ 2");
|
||||
assert!(substituted.is_equation());
|
||||
assert_eq!(substituted.kind, parse("A = \\pi * 2 ^ 2").unwrap().kind);
|
||||
}
|
||||
}
|
||||
@@ -1,837 +0,0 @@
|
||||
//! Lexer and recursive-descent parser for the documented math subset.
|
||||
//!
|
||||
//! The parser is intentionally strict: anything outside the subset becomes a
|
||||
//! structured [`MathError`] instead of being skipped, guessed or silently
|
||||
//! simplified. It never panics on untrusted input: recursion depth, source size
|
||||
//! and numeric literal size are all bounded before the corresponding work
|
||||
//! happens.
|
||||
|
||||
use std::iter::Peekable;
|
||||
use std::str::CharIndices;
|
||||
|
||||
use num_bigint::BigInt;
|
||||
use num_rational::Ratio;
|
||||
|
||||
use crate::ast::{Constant, Expr, Formula, FormulaKind, Rational};
|
||||
use crate::error::MathError;
|
||||
|
||||
/// Maximum accepted source length in bytes. Longer inputs are rejected before
|
||||
/// tokenization so that a hostile formula cannot consume unbounded memory.
|
||||
pub const MAX_SOURCE_BYTES: usize = 1_000_000;
|
||||
|
||||
/// Maximum parser recursion depth (parentheses, groups, unary chains, fractions
|
||||
/// and roots all consume one level). Deeper input is a parse error instead of a
|
||||
/// stack overflow.
|
||||
pub const MAX_PARSE_DEPTH: usize = 256;
|
||||
|
||||
/// Maximum number of AST nodes in one formula. This bounds evaluation,
|
||||
/// substitution and rendering recursion depth: a long left-associative chain
|
||||
/// such as `1 + 1 + ...` would otherwise build a very deep tree even though the
|
||||
/// parser loop itself is iterative. Deeper formulas are rejected with a parse
|
||||
/// error instead of risking a stack overflow later.
|
||||
pub const MAX_AST_NODES: usize = 512;
|
||||
|
||||
/// Maximum number of digits in one numeric literal.
|
||||
const MAX_LITERAL_DIGITS: usize = 100_000;
|
||||
|
||||
/// Plain identifiers that name elementary functions in ordinary LaTeX. They are
|
||||
/// reported as unsupported instead of being silently reinterpreted as variables
|
||||
/// or implicit multiplication.
|
||||
const FUNCTION_NAMES: &[&str] = &[
|
||||
"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh",
|
||||
"log", "ln", "lg", "exp", "abs", "min", "max", "floor", "ceil", "round", "det", "dim", "gcd",
|
||||
"lcm", "lim", "sup", "inf", "arg", "Re", "Im",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum TokenKind {
|
||||
Number(Rational),
|
||||
Ident(String),
|
||||
Constant(Constant),
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
Slash,
|
||||
Caret,
|
||||
LParen,
|
||||
RParen,
|
||||
LBrace,
|
||||
RBrace,
|
||||
Equals,
|
||||
Frac,
|
||||
Sqrt,
|
||||
Eof,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Token {
|
||||
kind: TokenKind,
|
||||
/// Byte offset of the first byte of the token.
|
||||
start: usize,
|
||||
}
|
||||
|
||||
impl Token {
|
||||
fn describe(&self) -> String {
|
||||
match &self.kind {
|
||||
TokenKind::Number(_) => "a number".to_string(),
|
||||
TokenKind::Ident(name) => format!("identifier `{name}`"),
|
||||
TokenKind::Constant(constant) => match constant {
|
||||
Constant::Pi => "`\\pi`".to_string(),
|
||||
Constant::E => "`\\e`".to_string(),
|
||||
},
|
||||
TokenKind::Plus => "`+`".to_string(),
|
||||
TokenKind::Minus => "`-`".to_string(),
|
||||
TokenKind::Star => "`*`".to_string(),
|
||||
TokenKind::Slash => "`/`".to_string(),
|
||||
TokenKind::Caret => "`^`".to_string(),
|
||||
TokenKind::LParen => "`(`".to_string(),
|
||||
TokenKind::RParen => "`)`".to_string(),
|
||||
TokenKind::LBrace => "`{`".to_string(),
|
||||
TokenKind::RBrace => "`}`".to_string(),
|
||||
TokenKind::Equals => "`=`".to_string(),
|
||||
TokenKind::Frac => "`\\frac`".to_string(),
|
||||
TokenKind::Sqrt => "`\\sqrt`".to_string(),
|
||||
TokenKind::Eof => "the end of the formula".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `latex` into a [`Formula`].
|
||||
///
|
||||
/// The supported grammar is documented on the crate root. The returned formula
|
||||
/// keeps the original source in [`Formula::source`] and exposes the parsed
|
||||
/// [`FormulaKind`] for inspection.
|
||||
pub fn parse(latex: &str) -> Result<Formula, MathError> {
|
||||
if latex.len() > MAX_SOURCE_BYTES {
|
||||
return Err(MathError::parse(
|
||||
format!(
|
||||
"formula source is {} bytes; the supported limit is {MAX_SOURCE_BYTES} bytes",
|
||||
latex.len()
|
||||
),
|
||||
Some(0),
|
||||
));
|
||||
}
|
||||
let tokens = lex(latex)?;
|
||||
Parser {
|
||||
tokens,
|
||||
position: 0,
|
||||
depth: 0,
|
||||
nodes: 0,
|
||||
}
|
||||
.parse_formula(latex)
|
||||
}
|
||||
|
||||
fn lex(source: &str) -> Result<Vec<Token>, MathError> {
|
||||
Lexer {
|
||||
source,
|
||||
chars: source.char_indices().peekable(),
|
||||
tokens: Vec::new(),
|
||||
}
|
||||
.run()
|
||||
}
|
||||
|
||||
struct Lexer<'a> {
|
||||
source: &'a str,
|
||||
chars: Peekable<CharIndices<'a>>,
|
||||
tokens: Vec<Token>,
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
fn run(mut self) -> Result<Vec<Token>, MathError> {
|
||||
while let Some(&(start, ch)) = self.chars.peek() {
|
||||
if ch.is_whitespace() {
|
||||
self.chars.next();
|
||||
continue;
|
||||
}
|
||||
let kind = match ch {
|
||||
'+' => {
|
||||
self.chars.next();
|
||||
TokenKind::Plus
|
||||
}
|
||||
'-' => {
|
||||
self.chars.next();
|
||||
TokenKind::Minus
|
||||
}
|
||||
'*' => {
|
||||
self.chars.next();
|
||||
TokenKind::Star
|
||||
}
|
||||
'/' => {
|
||||
self.chars.next();
|
||||
TokenKind::Slash
|
||||
}
|
||||
'^' => {
|
||||
self.chars.next();
|
||||
TokenKind::Caret
|
||||
}
|
||||
'(' => {
|
||||
self.chars.next();
|
||||
TokenKind::LParen
|
||||
}
|
||||
')' => {
|
||||
self.chars.next();
|
||||
TokenKind::RParen
|
||||
}
|
||||
'{' => {
|
||||
self.chars.next();
|
||||
TokenKind::LBrace
|
||||
}
|
||||
'}' => {
|
||||
self.chars.next();
|
||||
TokenKind::RBrace
|
||||
}
|
||||
'=' => {
|
||||
self.chars.next();
|
||||
TokenKind::Equals
|
||||
}
|
||||
'\\' => self.lex_command()?,
|
||||
ch if ch.is_ascii_digit() || ch == '.' => self.lex_number()?,
|
||||
ch if is_ident_start(ch) => self.lex_identifier()?,
|
||||
other => {
|
||||
return Err(MathError::unsupported(
|
||||
format!("unsupported character `{other}` in a formula"),
|
||||
Some(start),
|
||||
));
|
||||
}
|
||||
};
|
||||
self.tokens.push(Token { kind, start });
|
||||
}
|
||||
self.tokens.push(Token {
|
||||
kind: TokenKind::Eof,
|
||||
start: self.source.len(),
|
||||
});
|
||||
Ok(self.tokens)
|
||||
}
|
||||
|
||||
fn lex_identifier(&mut self) -> Result<TokenKind, MathError> {
|
||||
let start = self.current_offset();
|
||||
let mut text = String::new();
|
||||
while let Some(&(_, ch)) = self.chars.peek() {
|
||||
if is_ident_continue(ch) {
|
||||
text.push(ch);
|
||||
self.chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match text.as_str() {
|
||||
"pi" => Ok(TokenKind::Constant(Constant::Pi)),
|
||||
"e" => Ok(TokenKind::Constant(Constant::E)),
|
||||
_ if FUNCTION_NAMES.contains(&text.as_str()) => Err(MathError::unsupported(
|
||||
format!(
|
||||
"function `{text}` is not supported; the native math subset has no function calls"
|
||||
),
|
||||
Some(start),
|
||||
)),
|
||||
_ => Ok(TokenKind::Ident(text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte offset of the next unconsumed character (or the source end).
|
||||
fn current_offset(&mut self) -> usize {
|
||||
match self.chars.peek() {
|
||||
Some(&(offset, _)) => offset,
|
||||
None => self.source.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lex_number(&mut self) -> Result<TokenKind, MathError> {
|
||||
let start = self.current_offset();
|
||||
let mut integer_digits = String::new();
|
||||
while let Some(&(_, ch)) = self.chars.peek() {
|
||||
if ch.is_ascii_digit() {
|
||||
integer_digits.push(ch);
|
||||
self.chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut fraction_digits = String::new();
|
||||
if matches!(self.chars.peek(), Some(&(_, '.'))) {
|
||||
self.chars.next();
|
||||
while let Some(&(_, ch)) = self.chars.peek() {
|
||||
if ch.is_ascii_digit() {
|
||||
fraction_digits.push(ch);
|
||||
self.chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if fraction_digits.is_empty() {
|
||||
return Err(MathError::parse(
|
||||
"malformed decimal literal: expected digits after `.`",
|
||||
Some(start),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if integer_digits.is_empty() && fraction_digits.is_empty() {
|
||||
return Err(MathError::parse("malformed numeric literal", Some(start)));
|
||||
}
|
||||
if integer_digits.len() + fraction_digits.len() > MAX_LITERAL_DIGITS {
|
||||
return Err(MathError::parse(
|
||||
format!(
|
||||
"numeric literal has more than {MAX_LITERAL_DIGITS} digits, which is outside the supported resource bound"
|
||||
),
|
||||
Some(start),
|
||||
));
|
||||
}
|
||||
|
||||
// Reject scientific notation (`1e3`) explicitly: it is outside the
|
||||
// subset and would otherwise parse as `1 * e3`.
|
||||
if matches!(self.chars.peek(), Some(&(_, 'e' | 'E')))
|
||||
&& self.number_is_followed_by_exponent()
|
||||
{
|
||||
return Err(MathError::parse(
|
||||
"scientific notation is not supported; write an explicit product such as `2 * 10 ^ 3`",
|
||||
Some(start),
|
||||
));
|
||||
}
|
||||
|
||||
let integer_text = if integer_digits.is_empty() {
|
||||
"0"
|
||||
} else {
|
||||
&integer_digits
|
||||
};
|
||||
let numerator = parse_bigint(integer_text, start)?;
|
||||
if fraction_digits.is_empty() {
|
||||
return Ok(TokenKind::Number(Ratio::from_integer(numerator)));
|
||||
}
|
||||
let mut all_digits = String::with_capacity(integer_digits.len() + fraction_digits.len());
|
||||
all_digits.push_str(if integer_digits.is_empty() {
|
||||
"0"
|
||||
} else {
|
||||
&integer_digits
|
||||
});
|
||||
all_digits.push_str(&fraction_digits);
|
||||
let numerator = parse_bigint(&all_digits, start)?;
|
||||
let denominator = BigInt::from(10_u32).pow(fraction_digits.len() as u32);
|
||||
Ok(TokenKind::Number(Ratio::new(numerator, denominator)))
|
||||
}
|
||||
|
||||
/// Look past the current `e`/`E` to decide whether it introduces an
|
||||
/// exponent (`1e3`, `1e-3`) rather than the Euler constant (`2e`).
|
||||
fn number_is_followed_by_exponent(&self) -> bool {
|
||||
let mut chars = self.chars.clone();
|
||||
let _ = chars.next(); // the 'e' / 'E'
|
||||
match chars.next().map(|(_, ch)| ch) {
|
||||
Some(ch) if ch.is_ascii_digit() => true,
|
||||
Some('+' | '-') => {
|
||||
matches!(chars.next().map(|(_, ch)| ch), Some(ch) if ch.is_ascii_digit())
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn lex_command(&mut self) -> Result<TokenKind, MathError> {
|
||||
let start = self.current_offset();
|
||||
self.chars.next(); // consume the backslash
|
||||
let mut name = String::new();
|
||||
while let Some(&(_, ch)) = self.chars.peek() {
|
||||
if ch.is_ascii_alphabetic() {
|
||||
name.push(ch);
|
||||
self.chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match name.as_str() {
|
||||
"pi" => Ok(TokenKind::Constant(Constant::Pi)),
|
||||
"e" => Ok(TokenKind::Constant(Constant::E)),
|
||||
"cdot" | "times" => Ok(TokenKind::Star),
|
||||
"frac" => Ok(TokenKind::Frac),
|
||||
"sqrt" => Ok(TokenKind::Sqrt),
|
||||
"left" => self.lex_left_right(start, '('),
|
||||
"right" => self.lex_left_right(start, ')'),
|
||||
"" => Err(MathError::unsupported(
|
||||
"unsupported LaTeX control symbol; only alphabetic commands such as `\\pi` are supported",
|
||||
Some(start),
|
||||
)),
|
||||
other => Err(MathError::unsupported(
|
||||
format!(
|
||||
"unsupported LaTeX command `\\{other}`; the native math subset only supports `\\frac`, `\\sqrt`, `\\cdot`, `\\times`, `\\left(`, `\\right)`, `\\pi` and `\\e`"
|
||||
),
|
||||
Some(start),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn lex_left_right(&mut self, start: usize, expected: char) -> Result<TokenKind, MathError> {
|
||||
while let Some(&(_, ch)) = self.chars.peek() {
|
||||
if ch.is_whitespace() {
|
||||
self.chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match self.chars.next() {
|
||||
Some((_, ch)) if ch == expected => Ok(if expected == '(' {
|
||||
TokenKind::LParen
|
||||
} else {
|
||||
TokenKind::RParen
|
||||
}),
|
||||
_ => Err(MathError::unsupported(
|
||||
format!(
|
||||
"only the parenthesis forms `\\left(` and `\\right)` are supported, not `\\{}` followed by another delimiter",
|
||||
if expected == '(' { "left" } else { "right" }
|
||||
),
|
||||
Some(start),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bigint(digits: &str, position: usize) -> Result<BigInt, MathError> {
|
||||
digits
|
||||
.parse::<BigInt>()
|
||||
.map_err(|_| MathError::parse("numeric literal is too large to represent", Some(position)))
|
||||
}
|
||||
|
||||
fn is_ident_start(ch: char) -> bool {
|
||||
ch.is_alphabetic() || ch == '_'
|
||||
}
|
||||
|
||||
fn is_ident_continue(ch: char) -> bool {
|
||||
ch.is_alphanumeric() || ch == '_'
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
position: usize,
|
||||
depth: usize,
|
||||
nodes: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn peek(&self) -> &Token {
|
||||
// The lexer always appends an Eof token, so indexing is in bounds.
|
||||
&self.tokens[self.position.min(self.tokens.len() - 1)]
|
||||
}
|
||||
|
||||
fn advance(&mut self) -> Token {
|
||||
let token = self.peek().clone();
|
||||
if self.position < self.tokens.len() - 1 {
|
||||
self.position += 1;
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
/// Record one constructed AST node, enforcing [`MAX_AST_NODES`].
|
||||
fn node(&mut self, expr: Expr) -> Result<Expr, MathError> {
|
||||
self.nodes += 1;
|
||||
if self.nodes > MAX_AST_NODES {
|
||||
return Err(MathError::parse(
|
||||
format!(
|
||||
"formula contains more than the supported limit of {MAX_AST_NODES} syntax nodes"
|
||||
),
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
Ok(expr)
|
||||
}
|
||||
|
||||
fn enter_depth(&mut self) -> Result<(), MathError> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_PARSE_DEPTH {
|
||||
return Err(MathError::parse(
|
||||
format!("formula nesting exceeds the supported limit of {MAX_PARSE_DEPTH} levels"),
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_formula(mut self, source: &str) -> Result<Formula, MathError> {
|
||||
if matches!(self.peek().kind, TokenKind::Eof) {
|
||||
return Err(MathError::parse("empty formula", Some(0)));
|
||||
}
|
||||
let left = self.parse_expr()?;
|
||||
let kind = if matches!(self.peek().kind, TokenKind::Equals) {
|
||||
let equals = self.advance();
|
||||
if matches!(self.peek().kind, TokenKind::Eof) {
|
||||
return Err(MathError::parse(
|
||||
"expected a right-hand side after `=`",
|
||||
Some(equals.start + 1),
|
||||
));
|
||||
}
|
||||
let right = self.parse_expr()?;
|
||||
if matches!(self.peek().kind, TokenKind::Equals) {
|
||||
return Err(MathError::parse(
|
||||
"more than one `=` in a formula; at most one equation is supported and `=` is never assignment",
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
FormulaKind::Equation { left, right }
|
||||
} else {
|
||||
FormulaKind::Expression(left)
|
||||
};
|
||||
if !matches!(self.peek().kind, TokenKind::Eof) {
|
||||
return Err(MathError::parse(
|
||||
format!("unexpected {} after the formula", self.peek().describe()),
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
Ok(Formula {
|
||||
source: source.to_string(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_expr(&mut self) -> Result<Expr, MathError> {
|
||||
let mut left = self.parse_term()?;
|
||||
loop {
|
||||
match self.peek().kind {
|
||||
TokenKind::Plus => {
|
||||
self.advance();
|
||||
let right = self.parse_term()?;
|
||||
left = self.node(Expr::Add(Box::new(left), Box::new(right)))?;
|
||||
}
|
||||
TokenKind::Minus => {
|
||||
self.advance();
|
||||
let right = self.parse_term()?;
|
||||
left = self.node(Expr::Sub(Box::new(left), Box::new(right)))?;
|
||||
}
|
||||
_ => return Ok(left),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_term(&mut self) -> Result<Expr, MathError> {
|
||||
let mut left = self.parse_unary()?;
|
||||
loop {
|
||||
if matches!(self.peek().kind, TokenKind::Star) {
|
||||
self.advance();
|
||||
let right = self.parse_unary()?;
|
||||
left = self.node(Expr::Mul(Box::new(left), Box::new(right)))?;
|
||||
} else if matches!(self.peek().kind, TokenKind::Slash) {
|
||||
self.advance();
|
||||
let right = self.parse_unary()?;
|
||||
left = self.node(Expr::Div(Box::new(left), Box::new(right)))?;
|
||||
} else if can_start_primary(&self.peek().kind) {
|
||||
if matches!(left, Expr::Number(_))
|
||||
&& matches!(self.peek().kind, TokenKind::Number(_))
|
||||
{
|
||||
return Err(MathError::parse(
|
||||
"two adjacent number literals are ambiguous; insert an operator",
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
// Implicit multiplication: `2x`, `\pi r^2`, `m a`.
|
||||
let right = self.parse_unary()?;
|
||||
left = self.node(Expr::Mul(Box::new(left), Box::new(right)))?;
|
||||
} else {
|
||||
return Ok(left);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_unary(&mut self) -> Result<Expr, MathError> {
|
||||
self.enter_depth()?;
|
||||
let result = self.parse_unary_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn parse_unary_inner(&mut self) -> Result<Expr, MathError> {
|
||||
match self.peek().kind {
|
||||
TokenKind::Minus => {
|
||||
self.advance();
|
||||
let inner = self.parse_unary()?;
|
||||
self.node(Expr::Neg(Box::new(inner)))
|
||||
}
|
||||
TokenKind::Plus => {
|
||||
self.advance();
|
||||
self.parse_unary()
|
||||
}
|
||||
_ => self.parse_power(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_power(&mut self) -> Result<Expr, MathError> {
|
||||
let base = self.parse_primary()?;
|
||||
if matches!(self.peek().kind, TokenKind::Caret) {
|
||||
self.advance();
|
||||
let exponent = self.parse_unary()?;
|
||||
return self.node(Expr::Pow(Box::new(base), Box::new(exponent)));
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<Expr, MathError> {
|
||||
self.enter_depth()?;
|
||||
let result = self.parse_primary_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn parse_primary_inner(&mut self) -> Result<Expr, MathError> {
|
||||
let token = self.peek().clone();
|
||||
match token.kind {
|
||||
TokenKind::Number(value) => {
|
||||
self.advance();
|
||||
self.node(Expr::Number(value))
|
||||
}
|
||||
TokenKind::Ident(name) => {
|
||||
self.advance();
|
||||
self.node(Expr::Variable(name))
|
||||
}
|
||||
TokenKind::Constant(constant) => {
|
||||
self.advance();
|
||||
self.node(Expr::Constant(constant))
|
||||
}
|
||||
TokenKind::LParen => {
|
||||
self.advance();
|
||||
let inner = self.parse_expr()?;
|
||||
self.expect_closing(TokenKind::RParen, "`)`", token.start)?;
|
||||
Ok(inner)
|
||||
}
|
||||
TokenKind::LBrace => {
|
||||
self.advance();
|
||||
let inner = self.parse_expr()?;
|
||||
self.expect_closing(TokenKind::RBrace, "`}`", token.start)?;
|
||||
Ok(inner)
|
||||
}
|
||||
TokenKind::Frac => {
|
||||
self.advance();
|
||||
let numerator = self.parse_braced_argument("\\frac")?;
|
||||
let denominator = self.parse_braced_argument("\\frac")?;
|
||||
self.node(Expr::Div(Box::new(numerator), Box::new(denominator)))
|
||||
}
|
||||
TokenKind::Sqrt => {
|
||||
self.advance();
|
||||
let inner = self.parse_braced_argument("\\sqrt")?;
|
||||
self.node(Expr::Sqrt(Box::new(inner)))
|
||||
}
|
||||
TokenKind::Eof => Err(MathError::parse(
|
||||
"expected an expression, found the end of the formula",
|
||||
Some(token.start),
|
||||
)),
|
||||
other => Err(MathError::parse(
|
||||
format!(
|
||||
"expected an expression, found {}",
|
||||
Token {
|
||||
kind: other,
|
||||
start: token.start
|
||||
}
|
||||
.describe()
|
||||
),
|
||||
Some(token.start),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_braced_argument(&mut self, command: &str) -> Result<Expr, MathError> {
|
||||
if !matches!(self.peek().kind, TokenKind::LBrace) {
|
||||
return Err(MathError::parse(
|
||||
format!("`{command}` requires a braced argument such as `{command}{{x}}`"),
|
||||
Some(self.peek().start),
|
||||
));
|
||||
}
|
||||
let open = self.advance();
|
||||
let inner = self.parse_expr()?;
|
||||
self.expect_closing(TokenKind::RBrace, "`}`", open.start)?;
|
||||
Ok(inner)
|
||||
}
|
||||
|
||||
fn expect_closing(
|
||||
&mut self,
|
||||
expected: TokenKind,
|
||||
description: &str,
|
||||
open_position: usize,
|
||||
) -> Result<(), MathError> {
|
||||
if std::mem::discriminant(&self.peek().kind) == std::mem::discriminant(&expected) {
|
||||
self.advance();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MathError::parse(
|
||||
format!(
|
||||
"expected {description} to close the group opened at byte {open_position}, found {}",
|
||||
self.peek().describe()
|
||||
),
|
||||
Some(self.peek().start),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_start_primary(kind: &TokenKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
TokenKind::Number(_)
|
||||
| TokenKind::Ident(_)
|
||||
| TokenKind::Constant(_)
|
||||
| TokenKind::LParen
|
||||
| TokenKind::LBrace
|
||||
| TokenKind::Frac
|
||||
| TokenKind::Sqrt
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_ok(source: &str) -> Formula {
|
||||
parse(source).unwrap_or_else(|err| panic!("expected {source:?} to parse: {err}"))
|
||||
}
|
||||
|
||||
fn parse_err(source: &str) -> MathError {
|
||||
parse(source).unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precedence_matches_standard_arithmetic() {
|
||||
let formula = parse_ok("1 + 2 * 3");
|
||||
assert_eq!(
|
||||
formula.kind,
|
||||
FormulaKind::Expression(Expr::Add(
|
||||
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(1)))),
|
||||
Box::new(Expr::Mul(
|
||||
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(2)))),
|
||||
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(3)))),
|
||||
)),
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unary_minus_binds_looser_than_power() {
|
||||
// -2^2 is -(2^2), not (-2)^2.
|
||||
let formula = parse_ok("-2^2");
|
||||
assert!(matches!(
|
||||
formula.kind,
|
||||
FormulaKind::Expression(Expr::Neg(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_is_right_associative() {
|
||||
let formula = parse_ok("2^3^2");
|
||||
let FormulaKind::Expression(Expr::Pow(_, exponent)) = formula.kind else {
|
||||
panic!("expected a power");
|
||||
};
|
||||
assert!(matches!(*exponent, Expr::Pow(_, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_multiplication_joins_adjacent_factors() {
|
||||
let formula = parse_ok("\\pi r^2");
|
||||
let FormulaKind::Expression(Expr::Mul(left, right)) = formula.kind else {
|
||||
panic!("expected multiplication");
|
||||
};
|
||||
assert!(matches!(*left, Expr::Constant(Constant::Pi)));
|
||||
assert!(matches!(*right, Expr::Pow(_, _)));
|
||||
|
||||
// `F = m a` is an equation whose right side is a product.
|
||||
let formula = parse_ok("F = m a");
|
||||
let FormulaKind::Equation { right, .. } = formula.kind else {
|
||||
panic!("expected an equation");
|
||||
};
|
||||
assert!(matches!(right, Expr::Mul(_, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_right_parentheses_are_accepted() {
|
||||
assert_eq!(
|
||||
parse_ok("\\left(1 + 2\\right) * 3").kind,
|
||||
parse_ok("(1 + 2) * 3").kind
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frac_and_sqrt_become_dedicated_nodes() {
|
||||
let formula = parse_ok("\\frac{1}{2} + \\sqrt{4}");
|
||||
let FormulaKind::Expression(Expr::Add(left, right)) = formula.kind else {
|
||||
panic!("expected addition");
|
||||
};
|
||||
assert!(matches!(*left, Expr::Div(_, _)));
|
||||
assert!(matches!(*right, Expr::Sqrt(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_equals_is_an_equation() {
|
||||
let formula = parse_ok("A = \\pi r^2");
|
||||
assert!(formula.is_equation());
|
||||
assert_eq!(formula.variables().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_one_equals_is_a_parse_error() {
|
||||
let err = parse_err("a = b = c");
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
|
||||
assert!(err.message.contains("more than one"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_malformed_input_is_a_parse_error() {
|
||||
assert_eq!(parse_err("").kind, crate::error::MathErrorKind::Parse);
|
||||
for source in ["1 +", "(1 + 2", "\\frac{1}{2", "{1 + 2", "1 + 2)", "= 3"] {
|
||||
let err = parse_err(source);
|
||||
assert_eq!(
|
||||
err.kind,
|
||||
crate::error::MathErrorKind::Parse,
|
||||
"source {source:?}"
|
||||
);
|
||||
assert!(err.position.is_some(), "source {source:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_commands_are_structured() {
|
||||
for source in [
|
||||
"\\begin{matrix}1&2\\end{matrix}",
|
||||
"\\int_0^1 x dx",
|
||||
"\\sin(x)",
|
||||
"\\sum_{i=1}^n i",
|
||||
"sin(1)",
|
||||
] {
|
||||
let err = parse_err(source);
|
||||
assert_eq!(
|
||||
err.kind,
|
||||
crate::error::MathErrorKind::Unsupported,
|
||||
"source {source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_characters_are_structured() {
|
||||
let err = parse_err("1, 2");
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Unsupported);
|
||||
assert!(err.message.contains("unsupported character"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_is_rejected_without_stack_overflow() {
|
||||
let source = format!("{}1{}", "(".repeat(10_000), ")".repeat(10_000));
|
||||
let err = parse_err(&source);
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
|
||||
assert!(err.message.contains("nesting"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excessive_node_count_is_rejected() {
|
||||
// A long left-associative chain is cheap to parse iteratively but would
|
||||
// build a very deep tree; the node budget rejects it first.
|
||||
let source = format!("{}1", "1 + ".repeat(MAX_AST_NODES));
|
||||
let err = parse_err(&source);
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
|
||||
assert!(err.message.contains("syntax nodes"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn very_long_chain_is_rejected_without_stack_overflow() {
|
||||
let source = format!("{}1", "1 + ".repeat(200_000));
|
||||
let err = parse_err(&source);
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_literal_bounds_are_enforced() {
|
||||
let source = "9".repeat(MAX_LITERAL_DIGITS + 1);
|
||||
let err = parse_err(&source);
|
||||
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
|
||||
assert!(err.message.contains("digits"));
|
||||
}
|
||||
}
|
||||
@@ -1,596 +0,0 @@
|
||||
//! End-to-end tests for the native Formula kernel.
|
||||
//!
|
||||
//! These tests exercise the public contract used by the host layer:
|
||||
//! `parse`, `evaluate` and `substitute`. They cover the documented grammar,
|
||||
//! exact numeric semantics, equation solving, structured errors and resource
|
||||
//! bounds.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_math::{evaluate, parse, substitute, MathError, MathErrorKind, MAX_EXPONENT};
|
||||
use marqdo_value::Value;
|
||||
use num_bigint::BigInt;
|
||||
|
||||
fn empty() -> BTreeMap<String, Value> {
|
||||
BTreeMap::new()
|
||||
}
|
||||
|
||||
fn bindings(entries: &[(&str, Value)]) -> BTreeMap<String, Value> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(name, value)| ((*name).to_string(), value.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn eval(source: &str, bindings: &BTreeMap<String, Value>) -> Result<Value, MathError> {
|
||||
evaluate(&parse(source).expect("fixture must parse"), bindings, None)
|
||||
}
|
||||
|
||||
fn solve(
|
||||
source: &str,
|
||||
bindings: &BTreeMap<String, Value>,
|
||||
target: &str,
|
||||
) -> Result<Value, MathError> {
|
||||
evaluate(
|
||||
&parse(source).expect("fixture must parse"),
|
||||
bindings,
|
||||
Some(target),
|
||||
)
|
||||
}
|
||||
|
||||
fn assert_int(value: &Value, expected: i64) {
|
||||
assert_eq!(value, &Value::int(expected), "value was {value:?}");
|
||||
}
|
||||
|
||||
fn assert_float_close(value: &Value, expected: f64) {
|
||||
let Value::Float(actual) = value else {
|
||||
panic!("expected a Float, got {value:?}");
|
||||
};
|
||||
assert!(
|
||||
(actual - expected).abs() <= 1e-12 * expected.abs().max(1.0),
|
||||
"expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precedence_and_parentheses() {
|
||||
assert_int(&eval("1 + 2 * 3", &empty()).unwrap(), 7);
|
||||
assert_int(&eval("(1 + 2) * 3", &empty()).unwrap(), 9);
|
||||
assert_int(&eval("10 - 3 - 2", &empty()).unwrap(), 5);
|
||||
assert_int(&eval("8 / 4 / 2", &empty()).unwrap(), 1);
|
||||
assert_int(&eval("2 + 3 * 4 ^ 2", &empty()).unwrap(), 50);
|
||||
// Power is right associative, unary minus binds looser than power.
|
||||
assert_int(&eval("2 ^ 3 ^ 2", &empty()).unwrap(), 512);
|
||||
assert_int(&eval("-2 ^ 2", &empty()).unwrap(), -4);
|
||||
assert_int(&eval("(-2) ^ 2", &empty()).unwrap(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_big_integer_arithmetic() {
|
||||
let Value::Int(power) = eval("2 ^ 100", &empty()).unwrap() else {
|
||||
panic!("expected an Int");
|
||||
};
|
||||
assert_eq!(power.to_string(), "1267650600228229401496703205376");
|
||||
|
||||
let Value::Int(product) = eval(
|
||||
"123456789012345678901234567890 * 987654321098765432109876543210",
|
||||
&empty(),
|
||||
)
|
||||
.unwrap() else {
|
||||
panic!("expected an Int");
|
||||
};
|
||||
assert_eq!(
|
||||
product.to_string(),
|
||||
"121932631137021795226185032733622923332237463801111263526900"
|
||||
);
|
||||
|
||||
let Value::Int(sum) = eval("2 ^ 200 + 1", &empty()).unwrap() else {
|
||||
panic!("expected an Int");
|
||||
};
|
||||
assert_eq!(
|
||||
sum.to_string(),
|
||||
"1606938044258990275541962092341162602522202993782792835301377"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn division_stays_exact_when_it_reduces_to_an_integer() {
|
||||
// 1/3 alone is a Float approximation, but three of them are exactly 1.
|
||||
assert_int(&eval("(1 / 3) * 3", &empty()).unwrap(), 1);
|
||||
assert_int(&eval("(2 / 7) * 7", &empty()).unwrap(), 2);
|
||||
assert_int(&eval("100 / 4", &empty()).unwrap(), 25);
|
||||
|
||||
assert_float_close(&eval("10 / 4", &empty()).unwrap(), 2.5);
|
||||
assert_float_close(&eval("1 / 3", &empty()).unwrap(), 1.0 / 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_literals_are_exact_rationals() {
|
||||
// 1.5 + 2.5 is exactly 4, which is integral, so the result is an Int.
|
||||
assert_int(&eval("1.5 + 2.5", &empty()).unwrap(), 4);
|
||||
assert_int(&eval("0.25 * 4", &empty()).unwrap(), 1);
|
||||
assert_float_close(&eval("0.1 + 0.2", &empty()).unwrap(), 0.3);
|
||||
assert_float_close(&eval(".5 + 1", &empty()).unwrap(), 1.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pi_r_squared_area() {
|
||||
let mut bindings = empty();
|
||||
bindings.insert("r".to_string(), Value::int(2));
|
||||
let value = solve("A = \\pi r^2", &bindings, "A").unwrap();
|
||||
assert_float_close(&value, std::f64::consts::PI * 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perfect_and_non_perfect_square_roots() {
|
||||
assert_int(&eval("\\sqrt{16}", &empty()).unwrap(), 4);
|
||||
assert_int(&eval("\\sqrt{0}", &empty()).unwrap(), 0);
|
||||
// \sqrt{1/4} = 1/2: exact but not integral, so it is a Float value.
|
||||
assert_float_close(&eval("\\sqrt{\\frac{1}{4}}", &empty()).unwrap(), 0.5);
|
||||
// Non-perfect squares are explicitly approximate Floats.
|
||||
assert_float_close(
|
||||
&eval("\\sqrt{2}", &empty()).unwrap(),
|
||||
std::f64::consts::SQRT_2,
|
||||
);
|
||||
assert_float_close(&eval("\\sqrt{2} * \\sqrt{2}", &empty()).unwrap(), 2.0);
|
||||
let err = eval("\\sqrt{-4}", &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frac_is_exact_division() {
|
||||
assert_int(&eval("\\frac{6}{2}", &empty()).unwrap(), 3);
|
||||
assert_float_close(&eval("\\frac{6}{4}", &empty()).unwrap(), 1.5);
|
||||
assert_float_close(
|
||||
&eval("\\frac{\\frac{1}{2}}{\\frac{3}{4}}", &empty()).unwrap(),
|
||||
2.0 / 3.0,
|
||||
);
|
||||
assert_int(&eval("\\frac{1}{3} + \\frac{2}{3}", &empty()).unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_right_parentheses_and_nesting() {
|
||||
assert_int(
|
||||
&eval(
|
||||
"\\left(\\left(1 + 2\\right) * \\left(3 + 4\\right)\\right)",
|
||||
&empty(),
|
||||
)
|
||||
.unwrap(),
|
||||
21,
|
||||
);
|
||||
assert_int(&eval("\\left(1 + 2\\right) * 3", &empty()).unwrap(), 9);
|
||||
assert_int(&eval("((((1 + 2)))) * 3", &empty()).unwrap(), 9);
|
||||
assert_int(&eval("2 * {3 + 4}", &empty()).unwrap(), 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_identifiers() {
|
||||
let bindings = bindings(&[("半径", Value::int(3))]);
|
||||
assert_float_close(
|
||||
&solve("面积 = \\pi 半径^2", &bindings, "面积").unwrap(),
|
||||
std::f64::consts::PI * 9.0,
|
||||
);
|
||||
let substituted = substitute(&parse("半径 + 1").unwrap(), &bindings).unwrap();
|
||||
assert_eq!(substituted.source, "3 + 1");
|
||||
assert_int(&eval(&substituted.source, &empty()).unwrap(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constants_and_their_ambiguity_rules() {
|
||||
assert_float_close(&eval("\\pi", &empty()).unwrap(), std::f64::consts::PI);
|
||||
assert_float_close(&eval("pi", &empty()).unwrap(), std::f64::consts::PI);
|
||||
assert_float_close(&eval("\\e", &empty()).unwrap(), std::f64::consts::E);
|
||||
assert_float_close(&eval("e", &empty()).unwrap(), std::f64::consts::E);
|
||||
// `2e` is 2 times the constant, not scientific notation.
|
||||
assert_float_close(&eval("2e", &empty()).unwrap(), 2.0 * std::f64::consts::E);
|
||||
// `pi` and `e` are reserved: bindings do not shadow the constants.
|
||||
let bindings = bindings(&[("pi", Value::int(3)), ("e", Value::int(3))]);
|
||||
assert_float_close(&eval("pi", &bindings).unwrap(), std::f64::consts::PI);
|
||||
assert_float_close(&eval("e", &bindings).unwrap(), std::f64::consts::E);
|
||||
assert_eq!(
|
||||
solve("pi = 3", &empty(), "pi").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f_equals_m_a_solved_for_m() {
|
||||
let bindings = bindings(&[("F", Value::int(12)), ("a", Value::int(3))]);
|
||||
assert_int(&solve("F = m a", &bindings, "m").unwrap(), 4);
|
||||
// F = m a is an equation, not assignment: solving for m never rebinds F.
|
||||
assert_eq!(bindings.get("F"), Some(&Value::int(12)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f_equals_m_a_solved_for_a() {
|
||||
let bindings = bindings(&[("F", Value::int(12)), ("m", Value::int(3))]);
|
||||
assert_int(&solve("F = m a", &bindings, "a").unwrap(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f_equals_m_a_solved_for_f() {
|
||||
let bindings = bindings(&[("m", Value::int(3)), ("a", Value::int(4))]);
|
||||
assert_int(&solve("F = m a", &bindings, "F").unwrap(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_equation_solving_both_directions() {
|
||||
// Target on the left and on the right; multiplication and division by a
|
||||
// target-free side are both inverted.
|
||||
assert_int(&solve("2 x = 4", &empty(), "x").unwrap(), 2);
|
||||
assert_int(&solve("4 = 2 x", &empty(), "x").unwrap(), 2);
|
||||
assert_int(&solve("x / 2 = 3", &empty(), "x").unwrap(), 6);
|
||||
assert_int(&solve("3 = x / 2", &empty(), "x").unwrap(), 6);
|
||||
assert_int(&solve("x + 2 = 5", &empty(), "x").unwrap(), 3);
|
||||
assert_int(&solve("2 + x = 5", &empty(), "x").unwrap(), 3);
|
||||
assert_int(&solve("2 x + 1 = 7", &empty(), "x").unwrap(), 3);
|
||||
assert_int(&solve("x = 4", &empty(), "x").unwrap(), 4);
|
||||
assert_int(&solve("x / 4 = 1 / 2", &empty(), "x").unwrap(), 2);
|
||||
assert_int(&solve("(x + 1) * 2 = 8", &empty(), "x").unwrap(), 3);
|
||||
|
||||
// Other variables are substituted first.
|
||||
let bindings = bindings(&[("y", Value::int(3))]);
|
||||
assert_int(&solve("x = 2 y + 1", &bindings, "x").unwrap(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equation_solving_requires_exactly_one_affine_occurrence() {
|
||||
assert_eq!(
|
||||
solve("x + x = 4", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("x * x = 4", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("x ^ 2 = 4", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("1 / x = 2", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("\\sqrt{x} = 2", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("2 = 4", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
solve("x * 0 = 1", &empty(), "x").unwrap_err().kind,
|
||||
MathErrorKind::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_errors_are_structured() {
|
||||
let err = evaluate(&parse("A = 2").unwrap(), &empty(), None).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
assert!(err.message.contains("target"));
|
||||
|
||||
let err = evaluate(&parse("1 + 2").unwrap(), &empty(), Some("x")).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
|
||||
let err = solve("A = 2", &empty(), "B").unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
assert!(err.message.contains("does not occur"));
|
||||
|
||||
let err = solve("A = 2", &empty(), "").unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_constructs_are_structured() {
|
||||
for source in [
|
||||
"\\begin{matrix} 1 & 2 \\\\ 3 & 4 \\end{matrix}",
|
||||
"\\int_0^1 x dx",
|
||||
"\\sin(x)",
|
||||
"\\cos(x) + 1",
|
||||
"\\sum_{i=1}^{n} i",
|
||||
"\\alpha + 1",
|
||||
"\\frac12",
|
||||
"1e3",
|
||||
"\\left[ 1, 2 \\right]",
|
||||
] {
|
||||
let err = parse(source).unwrap_err();
|
||||
assert!(
|
||||
matches!(err.kind, MathErrorKind::Unsupported | MathErrorKind::Parse),
|
||||
"source {source:?} produced {err:?}"
|
||||
);
|
||||
assert!(
|
||||
err.position.is_some(),
|
||||
"source {source:?} lost its position"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_latex_is_a_parse_error_with_position() {
|
||||
for source in [
|
||||
"",
|
||||
"1 +",
|
||||
"(1 + 2",
|
||||
"\\frac{1}{2",
|
||||
"\\frac{1}",
|
||||
"\\sqrt 2",
|
||||
"{1 + 2",
|
||||
"1 + 2}",
|
||||
"1 + 2)",
|
||||
"1.2.3",
|
||||
"1 2",
|
||||
"a = b = c",
|
||||
] {
|
||||
let err = parse(source).unwrap_err();
|
||||
assert_eq!(
|
||||
err.kind,
|
||||
MathErrorKind::Parse,
|
||||
"source {source:?} produced {err:?}"
|
||||
);
|
||||
assert!(err.position.is_some(), "source {source:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undefined_variables_are_reported() {
|
||||
let err = eval("1 + x", &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::UndefinedVariable);
|
||||
assert!(err.message.contains('x'));
|
||||
|
||||
let err = solve("A = x + 1", &empty(), "A").unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::UndefinedVariable);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_numeric_bindings_are_type_errors() {
|
||||
for value in [
|
||||
Value::Bool(true),
|
||||
Value::text("two"),
|
||||
Value::List(vec![Value::int(2)]),
|
||||
Value::None,
|
||||
Value::Float(f64::NAN),
|
||||
Value::Float(f64::INFINITY),
|
||||
] {
|
||||
let err = eval("x + 1", &bindings(&[("x", value)])).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type);
|
||||
}
|
||||
// Unused bindings of other types are irrelevant.
|
||||
assert_int(
|
||||
&eval("1 + 1", &bindings(&[("x", Value::text("unused"))])).unwrap(),
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_bindings_are_exact_numeric_values() {
|
||||
let bindings = bindings(&[("x", Value::Float(2.5))]);
|
||||
assert_float_close(&eval("x", &bindings).unwrap(), 2.5);
|
||||
// 2.5 + 0.5 is exactly 3, so the exact-result rule yields an Int.
|
||||
assert_int(&eval("x + 0.5", &bindings).unwrap(), 3);
|
||||
assert_float_close(&eval("x / 2", &bindings).unwrap(), 1.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn division_by_zero_is_a_structured_error() {
|
||||
for source in ["1 / 0", "\\frac{1}{0}", "1 / (2 - 2)"] {
|
||||
let err = eval(source, &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type, "source {source:?}");
|
||||
assert!(
|
||||
err.message.contains("division by zero"),
|
||||
"source {source:?} produced {err:?}"
|
||||
);
|
||||
}
|
||||
let err = solve("x / 0 = 1", &empty(), "x").unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exponent_must_be_an_integer() {
|
||||
for source in ["2 ^ 0.5", "2 ^ \\frac{1}{2}", "2 ^ \\pi"] {
|
||||
let err = eval(source, &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type, "source {source:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_integer_exponents_are_exact_reciprocals() {
|
||||
assert_float_close(&eval("2 ^ -3", &empty()).unwrap(), 0.125);
|
||||
assert_int(&eval("(1 / 2) ^ -2", &empty()).unwrap(), 4);
|
||||
let err = eval("0 ^ -1", &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_exponents_are_bounded_not_hung() {
|
||||
let err = eval(&format!("2 ^ {}", MAX_EXPONENT + 1), &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
assert!(err.message.contains("exponent"));
|
||||
|
||||
let err = eval("2 ^ 1000000", &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
|
||||
// Each factor is under the exponent bound, but the product size is not.
|
||||
let err = eval("(2 ^ 10000) ^ 10000", &empty()).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Unsupported);
|
||||
|
||||
// At the documented exponent bound the result is still computed exactly.
|
||||
let Value::Int(bounded) = eval("2 ^ 10000", &empty()).unwrap() else {
|
||||
panic!("expected an Int");
|
||||
};
|
||||
assert_eq!(bounded.bits(), 10001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitute_replaces_bindings_deterministically() {
|
||||
let formula = parse("A = \\pi r^2").unwrap();
|
||||
let bindings = bindings(&[("r", Value::int(2))]);
|
||||
let substituted = substitute(&formula, &bindings).unwrap();
|
||||
|
||||
// The rendering is canonical, re-parseable and deterministic.
|
||||
assert_eq!(substituted.source, "A = \\pi * 2 ^ 2");
|
||||
assert_eq!(substituted.render(), substituted.source);
|
||||
assert_eq!(parse(&substituted.source).unwrap().kind, substituted.kind);
|
||||
|
||||
let direct = evaluate(&formula, &bindings, Some("A")).unwrap();
|
||||
let via_substitution = evaluate(&substituted, &empty(), Some("A")).unwrap();
|
||||
assert_eq!(direct, via_substitution);
|
||||
|
||||
let second = substitute(&formula, &bindings).unwrap();
|
||||
assert_eq!(substituted.source, second.source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitute_leaves_unbound_variables_symbolic() {
|
||||
let formula = parse("x + y * 2").unwrap();
|
||||
let substituted = substitute(&formula, &bindings(&[("x", Value::int(3))])).unwrap();
|
||||
assert_eq!(substituted.source, "3 + y * 2");
|
||||
assert!(substituted.variables().contains("y"));
|
||||
assert!(!substituted.variables().contains("x"));
|
||||
|
||||
let value = evaluate(&substituted, &bindings(&[("y", Value::int(4))]), None).unwrap();
|
||||
assert_int(&value, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitute_rejects_unsupported_binding_types() {
|
||||
let formula = parse("x + 1").unwrap();
|
||||
let err = substitute(&formula, &bindings(&[("x", Value::text("two"))])).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Type);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scientific_notation_and_adjacent_numbers_are_rejected() {
|
||||
assert_eq!(parse("1e3").unwrap_err().kind, MathErrorKind::Parse);
|
||||
assert_eq!(parse("1E3").unwrap_err().kind, MathErrorKind::Parse);
|
||||
assert_eq!(parse("1e-3").unwrap_err().kind, MathErrorKind::Parse);
|
||||
assert_eq!(parse("1 2").unwrap_err().kind, MathErrorKind::Parse);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_display_includes_kind_and_position() {
|
||||
let err = parse("\\frac{1}{2").unwrap_err();
|
||||
let rendered = err.to_string();
|
||||
assert!(rendered.starts_with("parse at byte "), "{rendered}");
|
||||
assert!(rendered.contains("expected `}`"), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_inputs_never_panic() {
|
||||
// A small corpus of adversarial inputs: all must produce a structured error
|
||||
// (or a value), never a panic or an unbounded computation.
|
||||
let sources = [
|
||||
"\\",
|
||||
"\\\\",
|
||||
"\\\\\\\\",
|
||||
"\\frac",
|
||||
"\\frac{}{}",
|
||||
"\\sqrt{}",
|
||||
"{}",
|
||||
"((((",
|
||||
"))))",
|
||||
"^^^^",
|
||||
"----------------x",
|
||||
"1 + + + +",
|
||||
"1 // 2",
|
||||
"\\left(1",
|
||||
"\\right)",
|
||||
"\\left[1\\right]",
|
||||
"1..2",
|
||||
"..",
|
||||
"∞",
|
||||
"1 × 2",
|
||||
"1 · 2",
|
||||
"2 ^ 2 ^ 2 ^ 2",
|
||||
"\\pi 2 3",
|
||||
"x = ",
|
||||
"= x",
|
||||
"x = = y",
|
||||
"\\frac{1}{2} \\frac{3}{4}",
|
||||
];
|
||||
for source in sources {
|
||||
match parse(source) {
|
||||
Ok(formula) => {
|
||||
// If it parses, evaluation must be structured as well.
|
||||
let _ = evaluate(&formula, &empty(), None);
|
||||
}
|
||||
Err(err) => {
|
||||
assert!(
|
||||
!err.message.is_empty(),
|
||||
"structured error must have a message for {source:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_and_times_are_multiplication_operators() {
|
||||
assert_int(&eval("2 \\cdot 3", &empty()).unwrap(), 6);
|
||||
assert_int(&eval("2 \\times 3", &empty()).unwrap(), 6);
|
||||
assert_int(&eval("2 \\cdot 3 \\times 4", &empty()).unwrap(), 24);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solve_target_on_the_left_of_a_product() {
|
||||
let bindings = bindings(&[("F", Value::int(20)), ("a", Value::int(5))]);
|
||||
assert_int(&solve("m a = F", &bindings, "m").unwrap(), 4);
|
||||
assert_int(&solve("(m + 1) a = F", &bindings, "m").unwrap(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitution_with_float_and_negative_bindings_reparses() {
|
||||
// A Float binding is substituted as its exact numeric value, and the
|
||||
// canonical rendering must evaluate to the same value as the direct form.
|
||||
let formula = parse("x * 2").unwrap();
|
||||
let x_is_float = bindings(&[("x", Value::Float(2.5))]);
|
||||
let substituted = substitute(&formula, &x_is_float).unwrap();
|
||||
let direct = evaluate(&formula, &x_is_float, None).unwrap();
|
||||
let re_evaluated = evaluate(&parse(&substituted.source).unwrap(), &empty(), None).unwrap();
|
||||
assert_eq!(direct, re_evaluated);
|
||||
assert_int(&direct, 5);
|
||||
|
||||
// Negative substituted literals keep a parseable rendering.
|
||||
let formula = parse("x + 1").unwrap();
|
||||
let x_is_negative = bindings(&[("x", Value::int(-3))]);
|
||||
let substituted = substitute(&formula, &x_is_negative).unwrap();
|
||||
let value = evaluate(&parse(&substituted.source).unwrap(), &empty(), None).unwrap();
|
||||
assert_int(&value, -2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_exact_results_are_returned_as_integers() {
|
||||
let Value::Int(value) = eval("2 ^ 10000", &empty()).unwrap() else {
|
||||
panic!("expected an Int");
|
||||
};
|
||||
assert_eq!(value.bits(), 10001);
|
||||
// A non-perfect square of the same order remains representable as Float.
|
||||
assert!(matches!(
|
||||
eval("\\sqrt{2}", &empty()).unwrap(),
|
||||
Value::Float(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_operator_chains_within_the_node_budget_still_evaluate() {
|
||||
// Each `+`/`*` needs two leaf nodes plus one operator node, so 200
|
||||
// operators stay inside the documented 512-node budget.
|
||||
let source = format!("{}1", "1 + ".repeat(200));
|
||||
assert_int(&eval(&source, &empty()).unwrap(), 201);
|
||||
|
||||
let source = format!("{}1", "2 * ".repeat(200));
|
||||
assert_eq!(
|
||||
eval(&source, &empty()).unwrap(),
|
||||
Value::Int(BigInt::from(2).pow(200))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_formulas_are_rejected_with_a_structured_error() {
|
||||
// Well over the documented node budget, but not deep enough to be caught by
|
||||
// the nesting guard: this must be a parse error, not a stack overflow.
|
||||
let source = format!("{}1", "1 + ".repeat(200_000));
|
||||
let err = parse(&source).unwrap_err();
|
||||
assert_eq!(err.kind, MathErrorKind::Parse);
|
||||
}
|
||||
@@ -121,44 +121,6 @@ pub(crate) fn dispatch(
|
||||
};
|
||||
resolve_ref(interpreter, &module, &target, span)
|
||||
}
|
||||
"math.parse" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let text = formula_text(formula, span)?;
|
||||
interpreter.host_invoke(HostOp::MathParse, vec![Value::Text(text)], span, &module)
|
||||
}
|
||||
"math.eval" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let bindings = take(&bound, "bindings", builtin, span)?;
|
||||
let mut args = vec![formula, bindings];
|
||||
if let Some(target) = bound.get("target") {
|
||||
args.push(target.clone());
|
||||
}
|
||||
interpreter.host_invoke(HostOp::MathEval, args, span, &module)
|
||||
}
|
||||
"math.substitute" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let bindings = take(&bound, "bindings", builtin, span)?;
|
||||
interpreter.host_invoke(
|
||||
HostOp::MathSubstitute,
|
||||
vec![formula, bindings],
|
||||
span,
|
||||
&module,
|
||||
)
|
||||
}
|
||||
"math.simplify" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
interpreter.host_invoke(HostOp::MathSimplify, vec![formula], span, &module)
|
||||
}
|
||||
"math.differentiate" => {
|
||||
let formula = take(&bound, "formula", builtin, span)?;
|
||||
let variable = take(&bound, "变量", builtin, span)?;
|
||||
interpreter.host_invoke(
|
||||
HostOp::MathDifferentiate,
|
||||
vec![formula, variable],
|
||||
span,
|
||||
&module,
|
||||
)
|
||||
}
|
||||
"foreign.run" => {
|
||||
let code = take(&bound, "ref", builtin, span)?;
|
||||
let mut args = vec![code];
|
||||
@@ -738,20 +700,6 @@ fn table_index(
|
||||
Ok(position)
|
||||
}
|
||||
|
||||
fn formula_text(value: Value, span: Option<Span>) -> Result<String, RuntimeError> {
|
||||
match value {
|
||||
Value::Formula(formula) => Ok(formula.latex),
|
||||
Value::Text(text) => Ok(text),
|
||||
other => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!(
|
||||
"formula argument must be Formula or Text, got {}",
|
||||
other.type_name()
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn table(header: Value, rows: Value, span: Option<Span>) -> Result<Value, RuntimeError> {
|
||||
let Value::List(header_values) = header else {
|
||||
return Err(RuntimeError::type_error(
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
|
||||
use marqdo_host::{ExecutionContext, Host, HostOp, ResourceRead};
|
||||
use marqdo_host::{
|
||||
ExecutionContext, FrameId, Host, HostOp, ParameterSource, ResourceRead, RuntimeObservation,
|
||||
};
|
||||
use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
||||
@@ -55,6 +57,14 @@ pub struct RunOutcome {
|
||||
struct Frame {
|
||||
function: FunctionId,
|
||||
locals: BTreeMap<String, Value>,
|
||||
/// Run-unique call-instance identity; `None` when observation is off.
|
||||
id: Option<FrameId>,
|
||||
}
|
||||
|
||||
/// Locals plus where each parameter's value came from.
|
||||
struct BoundArgs {
|
||||
locals: BTreeMap<String, Value>,
|
||||
provenance: BTreeMap<String, (ParameterSource, Span)>,
|
||||
}
|
||||
|
||||
/// Flow of one statement list.
|
||||
@@ -69,6 +79,9 @@ pub struct Interpreter<'a> {
|
||||
host: &'a mut dyn Host,
|
||||
depth: usize,
|
||||
memory: MemoryStore,
|
||||
/// Cached `Host::observation_enabled()`: the default path skips building
|
||||
/// observation events entirely.
|
||||
observe: bool,
|
||||
}
|
||||
|
||||
/// Run a named function with already-evaluated arguments.
|
||||
@@ -98,11 +111,13 @@ pub fn run_with_limits(
|
||||
args: Vec<EvaluatedArg>,
|
||||
limits: MemoryLimits,
|
||||
) -> Result<RunOutcome, RuntimeError> {
|
||||
let observe = host.observation_enabled();
|
||||
let mut interpreter = Interpreter {
|
||||
program,
|
||||
host,
|
||||
depth: 0,
|
||||
memory: MemoryStore::new(limits),
|
||||
observe,
|
||||
};
|
||||
let value = interpreter.call_by_name(module, function, args, None)?;
|
||||
Ok(RunOutcome { value })
|
||||
@@ -167,8 +182,8 @@ impl<'a> Interpreter<'a> {
|
||||
call_span,
|
||||
None,
|
||||
);
|
||||
let locals = match self.bind_args(function, args, call_span) {
|
||||
Ok(locals) => locals,
|
||||
let bound = match self.bind_args(function, args, call_span) {
|
||||
Ok(bound) => bound,
|
||||
Err(mut error) => {
|
||||
if let Some(module) = caller_module {
|
||||
error.attribute_module(module.canonical());
|
||||
@@ -176,9 +191,38 @@ impl<'a> Interpreter<'a> {
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// A frame is announced only after argument binding succeeded, so a
|
||||
// binding failure can never leave a dangling call frame.
|
||||
let frame_id = if self.observe {
|
||||
self.host
|
||||
.observation_begin_frame(&trace_id, &trace_module, call_span)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(frame_id) = frame_id {
|
||||
let parameter_module = function.id.module.canonical();
|
||||
for param in &function.params {
|
||||
let Some((source, span)) = bound.provenance.get(¶m.name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let Some(value) = bound.locals.get(¶m.name) else {
|
||||
continue;
|
||||
};
|
||||
self.host
|
||||
.observe_runtime(RuntimeObservation::ParameterBound {
|
||||
frame_id: Some(frame_id),
|
||||
name: ¶m.name,
|
||||
source,
|
||||
value,
|
||||
module_id: ¶meter_module,
|
||||
span: Some(span),
|
||||
})?;
|
||||
}
|
||||
}
|
||||
let mut frame = Frame {
|
||||
function: function.id.clone(),
|
||||
locals,
|
||||
locals: bound.locals,
|
||||
id: frame_id,
|
||||
};
|
||||
self.depth += 1;
|
||||
let result = self.exec_stmts(program, &function.body, &mut frame);
|
||||
@@ -195,6 +239,12 @@ impl<'a> Interpreter<'a> {
|
||||
call_span,
|
||||
Some(status),
|
||||
);
|
||||
let close = self
|
||||
.host
|
||||
.observation_end_frame(frame_id, status, &trace_module, call_span);
|
||||
if result.is_ok() {
|
||||
close?;
|
||||
}
|
||||
match result {
|
||||
Ok(Flow::Next) => Ok(Value::Unit),
|
||||
Ok(Flow::Return(value)) => Ok(value),
|
||||
@@ -215,7 +265,7 @@ impl<'a> Interpreter<'a> {
|
||||
function: &Function,
|
||||
args: Vec<EvaluatedArg>,
|
||||
call_span: Option<Span>,
|
||||
) -> Result<BTreeMap<String, Value>, RuntimeError> {
|
||||
) -> Result<BoundArgs, RuntimeError> {
|
||||
let mut provided: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut positional = 0usize;
|
||||
for arg in args {
|
||||
@@ -264,11 +314,10 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
}
|
||||
let mut locals = BTreeMap::new();
|
||||
let mut provenance = BTreeMap::new();
|
||||
for param in &function.params {
|
||||
match provided.remove(¶m.name) {
|
||||
Some(value) => {
|
||||
locals.insert(param.name.clone(), value);
|
||||
}
|
||||
let (value, source) = match provided.remove(¶m.name) {
|
||||
Some(value) => (value, ParameterSource::Provided),
|
||||
None => {
|
||||
if let Some(default) = ¶m.default {
|
||||
// Defaults are compile-time constants; evaluate them in
|
||||
@@ -276,9 +325,10 @@ impl<'a> Interpreter<'a> {
|
||||
let mut empty = Frame {
|
||||
function: function.id.clone(),
|
||||
locals: BTreeMap::new(),
|
||||
id: None,
|
||||
};
|
||||
let value = self.eval_expr(default, &mut empty)?;
|
||||
locals.insert(param.name.clone(), value);
|
||||
(value, ParameterSource::Default)
|
||||
} else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
@@ -290,9 +340,13 @@ impl<'a> Interpreter<'a> {
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
if self.observe {
|
||||
provenance.insert(param.name.clone(), (source, param.span));
|
||||
}
|
||||
locals.insert(param.name.clone(), value);
|
||||
}
|
||||
Ok(locals)
|
||||
Ok(BoundArgs { locals, provenance })
|
||||
}
|
||||
|
||||
fn exec_stmts(
|
||||
@@ -323,6 +377,20 @@ impl<'a> Interpreter<'a> {
|
||||
PlaceTarget::Local { name, .. } => {
|
||||
let value = self.eval_expr(value, frame)?;
|
||||
frame.locals.insert(name.clone(), value);
|
||||
if self.observe {
|
||||
if let Some(committed) = frame.locals.get(name) {
|
||||
let module = frame.function.module.canonical();
|
||||
self.host.observe_runtime(
|
||||
RuntimeObservation::VariableAssigned {
|
||||
frame_id: frame.id,
|
||||
name,
|
||||
value: committed,
|
||||
module_id: &module,
|
||||
span: Some(stmt.span()),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
PlaceTarget::Index { base, index, span } => {
|
||||
// Frozen order (ADR-0022): base, index, then RHS.
|
||||
@@ -351,6 +419,14 @@ impl<'a> Interpreter<'a> {
|
||||
Some(*span),
|
||||
Some(value.type_name()),
|
||||
);
|
||||
if self.observe {
|
||||
self.host.observe_runtime(RuntimeObservation::Return {
|
||||
frame_id: frame.id,
|
||||
value_type: value.type_name(),
|
||||
module_id: &module,
|
||||
span: Some(*span),
|
||||
})?;
|
||||
}
|
||||
return Ok(Flow::Return(value));
|
||||
}
|
||||
Stmt::Branch { arms, .. } => {
|
||||
@@ -374,6 +450,14 @@ impl<'a> Interpreter<'a> {
|
||||
Some(arm.condition_span),
|
||||
Some(if condition { "true" } else { "false" }),
|
||||
);
|
||||
if self.observe {
|
||||
self.host.observe_runtime(RuntimeObservation::BranchEval {
|
||||
frame_id: frame.id,
|
||||
result: condition,
|
||||
module_id: &module,
|
||||
span: Some(arm.condition_span),
|
||||
})?;
|
||||
}
|
||||
if condition {
|
||||
match self.exec_stmts(program, &arm.body, frame)? {
|
||||
Flow::Next => break,
|
||||
@@ -405,6 +489,15 @@ impl<'a> Interpreter<'a> {
|
||||
Some(*condition_span),
|
||||
Some(if value { "continue" } else { "exit" }),
|
||||
);
|
||||
if self.observe {
|
||||
self.host
|
||||
.observe_runtime(RuntimeObservation::LoopIteration {
|
||||
frame_id: frame.id,
|
||||
decision: if value { "continue" } else { "exit" },
|
||||
module_id: &module,
|
||||
span: Some(*condition_span),
|
||||
})?;
|
||||
}
|
||||
if !value {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! Runtime observation integration tests (RFC-OBS-0001 / ADR-0059).
|
||||
//!
|
||||
//! The real frontend/IR/runtime path is exercised with an in-memory sink:
|
||||
//! frame identity, branch/loop/return attribution, committed assignment
|
||||
//! events, exact parameter selection and redaction of unselected values.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use marqdo_host::{
|
||||
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
|
||||
ParameterSource, StdHost, ValueState,
|
||||
};
|
||||
use marqdo_ir::{ModuleId, Program};
|
||||
use marqdo_runtime::run;
|
||||
use marqdo_sandbox::SandboxMode;
|
||||
use marqdo_value::Value;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Seen {
|
||||
kind: &'static str,
|
||||
frame: Option<u64>,
|
||||
name: String,
|
||||
value_type: String,
|
||||
state: Option<ValueState>,
|
||||
wire: Option<serde_json::Value>,
|
||||
source: Option<ParameterSource>,
|
||||
decision: String,
|
||||
}
|
||||
|
||||
struct Recorder(Rc<RefCell<Vec<Seen>>>);
|
||||
|
||||
impl ObservationSink for Recorder {
|
||||
fn emit(&mut self, event: ObservationEvent<'_>) -> Result<(), ObservationError> {
|
||||
let seen = match event {
|
||||
ObservationEvent::CallEnter { frame_id, .. } => Seen {
|
||||
kind: "enter",
|
||||
frame: Some(frame_id.0),
|
||||
name: String::new(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::CallExit {
|
||||
frame_id, status, ..
|
||||
} => Seen {
|
||||
kind: "exit",
|
||||
frame: Some(frame_id.0),
|
||||
name: status.to_string(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
..
|
||||
} => Seen {
|
||||
kind: "return",
|
||||
frame: Some(frame_id.0),
|
||||
name: String::new(),
|
||||
value_type: value_type.to_string(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::BranchEval {
|
||||
frame_id, result, ..
|
||||
} => Seen {
|
||||
kind: "branch",
|
||||
frame: Some(frame_id.0),
|
||||
name: result.to_string(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::LoopIteration {
|
||||
frame_id, decision, ..
|
||||
} => Seen {
|
||||
kind: "loop",
|
||||
frame: Some(frame_id.0),
|
||||
name: String::new(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: decision.to_string(),
|
||||
},
|
||||
ObservationEvent::VariableAssigned {
|
||||
frame_id,
|
||||
name,
|
||||
value_type,
|
||||
value_state,
|
||||
value,
|
||||
..
|
||||
} => Seen {
|
||||
kind: "variable",
|
||||
frame: Some(frame_id.0),
|
||||
name: name.to_string(),
|
||||
value_type: value_type.to_string(),
|
||||
state: Some(value_state),
|
||||
wire: value.map(|value| value.wire),
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::ParameterObserved {
|
||||
frame_id,
|
||||
name,
|
||||
source,
|
||||
value_type,
|
||||
value_state,
|
||||
value,
|
||||
..
|
||||
} => Seen {
|
||||
kind: "parameter",
|
||||
frame: Some(frame_id.0),
|
||||
name: name.to_string(),
|
||||
value_type: value_type.to_string(),
|
||||
state: Some(value_state),
|
||||
wire: value.map(|value| value.wire),
|
||||
source: Some(source),
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::Effect { operation, .. } => Seen {
|
||||
kind: "effect",
|
||||
frame: None,
|
||||
name: operation.to_string(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::ObservationTruncated { reason, .. } => Seen {
|
||||
kind: "truncated",
|
||||
frame: None,
|
||||
name: reason.to_string(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
ObservationEvent::StdoutChunk { .. } | ObservationEvent::StderrChunk { .. } => Seen {
|
||||
kind: "chunk",
|
||||
frame: None,
|
||||
name: String::new(),
|
||||
value_type: String::new(),
|
||||
state: None,
|
||||
wire: None,
|
||||
source: None,
|
||||
decision: String::new(),
|
||||
},
|
||||
};
|
||||
self.0.borrow_mut().push(seen);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn build(source: &str) -> Program {
|
||||
let result = marqdo_frontend::analyze_source("index.mq.md", source);
|
||||
assert!(!result.has_errors(), "{:#?}", result.diagnostics);
|
||||
let module_id = ModuleId::from("index.mq.md");
|
||||
let mut program = Program {
|
||||
main_module: Some(module_id.clone()),
|
||||
..Program::default()
|
||||
};
|
||||
program.insert(result.module);
|
||||
let registry = program.callable_registry();
|
||||
let bound = marqdo_frontend::calls::bind_program_calls(&program, ®istry);
|
||||
assert!(bound.diagnostics.is_empty(), "{:#?}", bound.diagnostics);
|
||||
program.set_call_bindings(bound.bindings);
|
||||
program
|
||||
}
|
||||
|
||||
fn source() -> &'static str {
|
||||
"## @exec f\n\n`params(n: Int)`\n\n`if n <= 0`\n\n`return 0`\n\n`end`\n\n`x = n`\n\n`return x + f(n=n-1)`\n\n## @exec main\n\n`i = 0`\n\n`while i < 2`\n\n`i = i + 1`\n\n`end`\n\n`visible = 42`\n\n`secret = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`return f(n=2)`\n"
|
||||
}
|
||||
|
||||
fn run_observed(config: ObservationConfig) -> (Value, Vec<Seen>) {
|
||||
let program = build(source());
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
.with_observation(config, Box::new(Recorder(Rc::clone(&seen))));
|
||||
let outcome = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
"main",
|
||||
Vec::new(),
|
||||
);
|
||||
let value = outcome.map(|outcome| outcome.value).unwrap();
|
||||
let seen = seen.borrow().clone();
|
||||
(value, seen)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_calls_get_unique_frames_and_correct_parents() {
|
||||
let (value, seen) = run_observed(ObservationConfig::default());
|
||||
assert_eq!(value, Value::int(3));
|
||||
|
||||
let enters: Vec<_> = seen.iter().filter(|event| event.kind == "enter").collect();
|
||||
assert_eq!(enters.len(), 4, "main + f(2) + f(1) + f(0)");
|
||||
let mut ids: Vec<u64> = enters.iter().filter_map(|event| event.frame).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 4, "frame ids must be run-unique");
|
||||
assert_eq!(
|
||||
enters[0].frame,
|
||||
Some(1),
|
||||
"the entry frame is the first frame"
|
||||
);
|
||||
// Nested calls are announced in call order; each later frame has a parent.
|
||||
for pair in enters.windows(2).skip(1).take(2) {
|
||||
assert!(pair[1].frame.unwrap() > pair[0].frame.unwrap());
|
||||
}
|
||||
let exits = seen.iter().filter(|event| event.kind == "exit").count();
|
||||
assert_eq!(exits, 4, "every entered frame closes, including recursion");
|
||||
let returns = seen.iter().filter(|event| event.kind == "return").count();
|
||||
assert_eq!(returns, 4);
|
||||
assert!(
|
||||
seen.iter().all(|event| event.wire.is_none()),
|
||||
"default observation publishes no value payloads"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_loop_and_assignments_are_attributed_and_default_hides_values() {
|
||||
let (_value, seen) = run_observed(ObservationConfig::default());
|
||||
let branches: Vec<_> = seen.iter().filter(|event| event.kind == "branch").collect();
|
||||
assert_eq!(
|
||||
branches.len(),
|
||||
3,
|
||||
"one condition per call: f(2), f(1), f(0)"
|
||||
);
|
||||
assert_eq!(
|
||||
branches.iter().filter(|event| event.name == "true").count(),
|
||||
1,
|
||||
"only the n <= 0 branch is true"
|
||||
);
|
||||
let loops: Vec<_> = seen.iter().filter(|event| event.kind == "loop").collect();
|
||||
assert_eq!(
|
||||
loops
|
||||
.iter()
|
||||
.map(|event| event.decision.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["continue", "continue", "exit"]
|
||||
);
|
||||
|
||||
let mut variables: Vec<(&str, &str)> = seen
|
||||
.iter()
|
||||
.filter(|event| event.kind == "variable")
|
||||
.map(|event| (event.name.as_str(), event.value_type.as_str()))
|
||||
.collect();
|
||||
variables.sort();
|
||||
assert!(variables.contains(&("i", "Int")));
|
||||
assert!(variables.contains(&("visible", "Int")));
|
||||
assert!(variables.contains(&("secret", "Text")));
|
||||
assert!(variables.contains(&("x", "Int")));
|
||||
for event in seen.iter().filter(|event| event.kind == "variable") {
|
||||
assert_eq!(event.state, Some(ValueState::NotRequested));
|
||||
assert!(
|
||||
event.wire.is_none(),
|
||||
"default event mode publishes no values"
|
||||
);
|
||||
}
|
||||
assert!(!serde_json::to_string(
|
||||
&seen
|
||||
.iter()
|
||||
.filter_map(|event| event.wire.clone())
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
.unwrap()
|
||||
.contains("DO_NOT_LEAK_SENTINEL_1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_selection_publishes_only_selected_scalars_and_redacts_text() {
|
||||
let mut config = ObservationConfig::default();
|
||||
config.selected_variables.insert("visible".to_string());
|
||||
config.selected_variables.insert("secret".to_string());
|
||||
config.selected_parameters.insert("n".to_string());
|
||||
let (_value, seen) = run_observed(config);
|
||||
|
||||
let visible = seen
|
||||
.iter()
|
||||
.find(|event| event.kind == "variable" && event.name == "visible")
|
||||
.expect("visible assignment event");
|
||||
assert_eq!(visible.state, Some(ValueState::Observed));
|
||||
assert_eq!(
|
||||
visible.wire.as_ref().unwrap()["decimal"],
|
||||
serde_json::Value::from("42")
|
||||
);
|
||||
|
||||
let secret = seen
|
||||
.iter()
|
||||
.filter(|event| event.kind == "variable" && event.name == "secret")
|
||||
.collect::<Vec<_>>();
|
||||
assert!(!secret.is_empty());
|
||||
for event in secret {
|
||||
assert_eq!(event.state, Some(ValueState::Redacted));
|
||||
assert!(event.wire.is_none(), "text needs a second explicit consent");
|
||||
}
|
||||
|
||||
let unselected: Vec<_> = seen
|
||||
.iter()
|
||||
.filter(|event| event.kind == "variable" && (event.name == "x" || event.name == "i"))
|
||||
.collect();
|
||||
assert!(!unselected.is_empty());
|
||||
for event in unselected {
|
||||
assert_eq!(event.state, Some(ValueState::NotRequested));
|
||||
assert!(event.wire.is_none(), "unselected names never carry values");
|
||||
}
|
||||
|
||||
let parameters: Vec<_> = seen
|
||||
.iter()
|
||||
.filter(|event| event.kind == "parameter" && event.name == "n")
|
||||
.collect();
|
||||
assert_eq!(parameters.len(), 3, "f(2), f(1), f(0)");
|
||||
assert_eq!(
|
||||
parameters
|
||||
.iter()
|
||||
.map(|event| event.wire.as_ref().unwrap()["decimal"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["2", "1", "0"]
|
||||
);
|
||||
assert!(parameters
|
||||
.iter()
|
||||
.all(|event| event.source == Some(ParameterSource::Provided)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argument_binding_failure_creates_no_frame() {
|
||||
let program = build(source());
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut host = StdHost::new(
|
||||
SandboxMode::Project,
|
||||
Capabilities::pure(),
|
||||
std::env::temp_dir(),
|
||||
)
|
||||
.with_observation(
|
||||
ObservationConfig::default(),
|
||||
Box::new(Recorder(Rc::clone(&seen))),
|
||||
);
|
||||
let result = run(
|
||||
&program,
|
||||
&mut host,
|
||||
&ModuleId::from("index.mq.md"),
|
||||
"f",
|
||||
vec![],
|
||||
);
|
||||
assert!(result.is_err(), "f requires n");
|
||||
assert!(
|
||||
seen.borrow().iter().all(|event| event.kind != "enter"),
|
||||
"a frame is announced only after successful binding"
|
||||
);
|
||||
}
|
||||
@@ -55,6 +55,11 @@ pub enum ErrorCategory {
|
||||
ForeignFailure,
|
||||
/// A host operation failed for an environmental reason.
|
||||
HostError,
|
||||
/// The observation event transport failed (broken pipe/write error).
|
||||
///
|
||||
/// This aborts the run rather than letting a program with side effects
|
||||
/// continue after its event channel died (RFC-OBS-0001 §5.3).
|
||||
Observation,
|
||||
/// Internal invariant violation.
|
||||
Internal,
|
||||
}
|
||||
@@ -84,6 +89,7 @@ impl ErrorCategory {
|
||||
ErrorCategory::PluginFailure => "plugin.failure",
|
||||
ErrorCategory::ForeignFailure => "foreign.failure",
|
||||
ErrorCategory::HostError => "host.error",
|
||||
ErrorCategory::Observation => "observe.transport_failed",
|
||||
ErrorCategory::Internal => codes::INTERNAL,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# RFC-REL-0001 — Marqdo 3.0 预发布路线、发布门禁与 LTS 策略(建议草案)
|
||||
|
||||
> 状态:**Adopted as the release policy for `3.0.0-beta.1`**(2026-11-22)。REL-01~REL-05 已按本文实施;实际门禁结果记录在 `docs/STATUS.md`、`docs/evidence/` 和 `docs/evidence/ci/<release-sha>/manifest.json`。
|
||||
> 状态:**Adopted as the release policy for `3.0.0-beta.1`**(2026-11-22,源码 `2c7c4f31e7a388d3fcfa717a77067e696ed13854`,[release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1))。REL-01~REL-05 已按本文实施;实际门禁结果记录在 `docs/STATUS.md`、`docs/evidence/` 和 `docs/evidence/ci/<release-sha>/manifest.json`。
|
||||
> 代码核对基线(提议时):`cflmy/marqdo-cli@56189b176c612bf399ff965c3b642077f6b04617`,2026-11-22;§2 的“剩余门禁”表是迁移前快照,当前事实以 `docs/STATUS.md` 为准。
|
||||
> 现有发布依据:`docs/releasing.md`、`docs/STATUS.md`、`COMPATIBILITY.md`、`spec/extension-selection.md`、`spec/callable-resolution.md`。
|
||||
> 本文是策略与门禁定义;**tag 只能在该 SHA 的全部门禁通过后创建**,本文本身不构成任意 SHA 的发布批准。
|
||||
|
||||
+187
-17
@@ -1,10 +1,13 @@
|
||||
# Marqdo Implementation Status
|
||||
|
||||
Snapshot: **2026-11-22**, product version **`3.0.0-beta.1`** (prerelease, tag
|
||||
`v3.0.0-beta.1`). Released platform: **Linux x86_64 (glibc)**. The exact tagged
|
||||
source SHA, CI pipeline URL and binary hashes are recorded in
|
||||
[`evidence/ci/`](evidence/ci/README.md) and in the archive's
|
||||
`RELEASE_INFO.json`; do not copy a SHA from a plan.
|
||||
`v3.0.0-beta.1`). Released platform: **Linux x86_64 (glibc)**. Tagged source
|
||||
SHA: **`2c7c4f31e7a388d3fcfa717a77067e696ed13854`**; release:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. The
|
||||
same-SHA evidence aggregate is
|
||||
[`evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
||||
(decision `BETA_RELEASE_CANDIDATE`); binary hashes are in the archive's
|
||||
`RELEASE_INFO.json`. Do not copy a SHA from a plan.
|
||||
|
||||
Current architecture overview:
|
||||
[`architecture/CURRENT.md`](architecture/CURRENT.md).
|
||||
@@ -47,21 +50,26 @@ SHA-mismatched gate is `DO_NOT_RELEASE`.
|
||||
| Gate | Beta requirement | Evidence |
|
||||
|---|---|---|
|
||||
| Source hygiene | clean tree, committed `Cargo.lock`, `--locked` builds | release commit; `RELEASE_INFO.json` |
|
||||
| Static/tests | `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace --locked` PASS | release evidence document + Woodpecker pipeline |
|
||||
| Release build | `cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker` PASS | archive contains both binaries, same target |
|
||||
| Linux CI | same-SHA Woodpecker pipeline PASS | pipeline URL in `evidence/ci/<sha>/manifest.json` |
|
||||
| Frozen-binary conformance | external `marqdo-extension-conformance` suite PASS with unchanged CLI hash | `evidence/extension/<sha>/manifest.json` |
|
||||
| Clean-install smoke | archive-only smoke PASS (incl. provider worker positive/negative, tools, plugins, kernel, Analysis/Trace) | release evidence document |
|
||||
| Version compatibility | prerelease Tool/project SemVer tests PASS; `project.marqdo` fail-closed tests PASS | `cargo test` logs/pipeline |
|
||||
| Strict policy | same-SHA disposable-VM G3 PASS for Linux strict L1 (or a tested fail-closed `strict: unsupported` policy) | `evidence/*strict*` document |
|
||||
| Performance | correctness-verified `MEASURED` on fixed Woodpecker agent; Beta-only `WARN` approved with environment/limits | G4 evidence document |
|
||||
| Static/tests | `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace --locked` PASS | [pipeline #37](https://ci.cflmy.cn/repos/1/pipeline/37); [gate record](evidence/2026-11-22-beta-release-gates.md) |
|
||||
| Release build | `cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker` PASS | archive contains both binaries, same target (`RELEASE_INFO.json`) |
|
||||
| Linux CI | same-SHA Woodpecker pipeline PASS | [pipeline #37](https://ci.cflmy.cn/repos/1/pipeline/37), commit `2c7c4f31e7a388d3fcfa717a77067e696ed13854` |
|
||||
| Frozen-binary conformance | external `marqdo-extension-conformance` suite PASS with unchanged CLI hash | [`evidence/extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json) (7/7; fixture `e22ec95…`) |
|
||||
| Clean-install smoke | archive-only smoke PASS (incl. provider worker positive/negative, tools, plugins, kernel, Analysis/Trace) | [gate record](evidence/2026-11-22-beta-release-gates.md) |
|
||||
| Version compatibility | prerelease Tool/project SemVer tests PASS; `project.marqdo` fail-closed tests PASS | pipeline #37 test step; local `cargo test` |
|
||||
| Strict policy | same-SHA disposable-VM G3 PASS for Linux strict L1 (or a tested fail-closed `strict: unsupported` policy) | [strict G3 evidence](evidence/2026-11-22-strict-gc-2c7c4f31.md) (`outcome: PASS`, uid 1000, container none) |
|
||||
| Performance | correctness-verified `MEASURED` on fixed Woodpecker agent; Beta-only `WARN` approved with environment/limits | [G4 evidence](evidence/2026-11-22-perf-woodpecker-agent-1-run38.md), [pipeline #38](https://ci.cflmy.cn/repos/1/pipeline/38) |
|
||||
| Support matrix | Linux x86_64 supported; macOS/Windows explicitly unsupported/experimental | [`../COMPATIBILITY.md`](../COMPATIBILITY.md) |
|
||||
| Third-party guide | every handbook command executed against the released archive | [guide validation](evidence/2026-11-22-beta-guide-validation.md) |
|
||||
|
||||
Release decision: **BETA_RELEASE_CANDIDATE**. The `v3.0.0-beta.1` tag is cut
|
||||
only from a SHA with all gates green; the SHA-bound manifests are committed in
|
||||
the post-release evidence commit. This is a prerelease: it does **not** imply
|
||||
stable `3.0.0`, does not promise LTS, and does not claim macOS/Windows
|
||||
artifacts, strict L2, Wasm, or a package registry.
|
||||
Release decision: **BETA_RELEASE_CANDIDATE** on
|
||||
[`evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json). Tag
|
||||
`v3.0.0-beta.1` was created only from `2c7c4f31e7a388d3fcfa717a77067e696ed13854` after every row above was green;
|
||||
the archive is
|
||||
`marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz` with sha256
|
||||
`507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317`, published
|
||||
as a Gitea prerelease. This is a prerelease: it does **not** imply stable
|
||||
`3.0.0`, does not promise LTS, and does not claim macOS/Windows artifacts,
|
||||
strict L2, Wasm, or a package registry.
|
||||
|
||||
### 0.3 Strict and performance policy for this beta
|
||||
|
||||
@@ -86,6 +94,168 @@ exports reconcile exactly with the static manifest. The independent
|
||||
frozen-binary suite is the beta gate above; the older `6a7bb98` manifest is
|
||||
historical and superseded by the release-SHA manifest.
|
||||
|
||||
## 0.5 Post-beta addition — Execution Events v1 (unreleased)
|
||||
|
||||
This section records work **after** the `v3.0.0-beta.1` tag. It is not part of
|
||||
the tagged beta archive and no new release tag has been created. The design
|
||||
input is RFC-OBS-0001 (issue `#1`), the frozen decision is ADR-0059 and the
|
||||
normative contract is [`spec/execution-events-v1.md`](../spec/execution-events-v1.md).
|
||||
Executed evidence for this section is
|
||||
[`evidence/2026-11-22-execution-events-v1.md`](evidence/2026-11-22-execution-events-v1.md).
|
||||
|
||||
- **Implemented (P0/P1):** `run/call --event-stream jsonl` writes a pure NDJSON
|
||||
`marqdo.execution-events` v1 stream; lifecycle/terminal events; byte-exact
|
||||
base64 stdout/stderr chunks emitted at the Host commit point; run-unique
|
||||
`frame_id`/`parent_frame_id`; `return`/`branch.eval`/`loop.iteration`/`effect`
|
||||
attribution; exact-name, bounded value observation with a separate
|
||||
`--observe-text-values` consent; structural/value budget with one
|
||||
`observation.truncated`; broken-pipe failure via `observe.transport_failed`;
|
||||
Trace v2 coexistence with a shared run id and unchanged Trace schema.
|
||||
- **Unchanged:** Analysis v2 and Trace v2 schemas/versions, `--json` envelope,
|
||||
default stdout/stderr/exit codes, language semantics and capability
|
||||
authorization.
|
||||
- **Deferred:** OBS-06 memory metadata (P2), debugger/stepping/time travel,
|
||||
bidirectional debug protocol, SSE/HTTP in the CLI (View implements that).
|
||||
- **Explicitly unsupported combination:** `--mode strict` rejects
|
||||
`--event-stream` with a structured `run.rejected`; there is no downgrade.
|
||||
|
||||
Executed local gate on this tree (Linux x86_64, Rust 1.100.0):
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS: 630 passed, 0 failed, 2 ignored
|
||||
cargo test -p marqdo-cli --test execution_events PASS: 14 passed
|
||||
cargo test -p marqdo-host --test observation PASS: 8 passed
|
||||
cargo test -p marqdo-runtime --test observation PASS: 4 passed
|
||||
python3 tests/consumers/execution_events_consumer.py PASS on a live real-binary stream (schema, seq, terminal, byte_count)
|
||||
```
|
||||
|
||||
The Python consumer is an independent black-box parser using only the checked-in
|
||||
JSON Schema; it was run against the local binary's stream and the checked-in
|
||||
valid/invalid fixtures. This is local evidence, not a frozen release-archive or
|
||||
same-SHA CI gate. `cargo test --workspace --locked` includes the new schema
|
||||
fixture test when `python3` + `jsonschema` are available (the Woodpecker test
|
||||
lane installs `python3-jsonschema` and also runs the consumer against a real
|
||||
`--event-stream jsonl` invocation).
|
||||
|
||||
## 0.6 Post-beta core/extension boundary — RFC-EXT-0003 (unreleased)
|
||||
|
||||
This section records work **after** the `v3.0.0-beta.1` tag. It is not part of the
|
||||
tagged beta archive and no new tag or stable release has been created. Design
|
||||
input: issue `#3` (RFC-EXT-0003). Frozen decisions: ADR-0060 (Core Modes /
|
||||
Heading Annotations), ADR-0061 (math detach), ADR-0062 (`resource_request`
|
||||
ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence:
|
||||
[`evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
|
||||
|
||||
### 0.6.1 Implemented / fixed
|
||||
|
||||
- **H-06 sibling heading inheritance:** `build_units` now removes the current and
|
||||
all same-or-higher-level headings from the ancestor stack before deriving the
|
||||
inherited mode. An unmarked heading inherits the nearest **ancestor**, never the
|
||||
previous sibling. Reproduced with the two audit documents first, then covered by
|
||||
the `units` matrix, conformance fixtures 22/23 and black-box
|
||||
`heading_inheritance` (`check --emit`, `run`, `call`).
|
||||
- **H-08 release archive stdlib:** the deterministic archive now contains the
|
||||
complete `stdlib/` tree; `RELEASE_INFO.json.stdlib` records name, version,
|
||||
tree/alias digests, file count and file list. `package.py` and `smoke.py`
|
||||
recompute both digests with the runtime algorithm and fail on mismatch; smoke
|
||||
removes the bundle and requires a fail-closed run (no source fallback). Release
|
||||
discovery only falls back to the compile-time source tree in debug builds.
|
||||
- **H-04 core resource kinds:** `marqdo_host::CORE_RESOURCE_KINDS` is the single
|
||||
registry used by the CLI manifest validator and every trusted host registration
|
||||
path; all six core kinds are rejected as a provider name and as a declared kind
|
||||
before registration.
|
||||
- **H-01 math domain API removed (breaking):** the five `math.*` builtins,
|
||||
`HostOp` variants, runtime arms and `crates/marqdo-math` are deleted. A call is a
|
||||
static `symbol.unknown`; `Formula` stays inert. Math algorithms are a pure
|
||||
`.mq.md` package (`examples/math-library/`) and an optional explicitly selected
|
||||
ABI backend that requests the `math.compute` capability
|
||||
(`examples/math-backend/`). The historical `math` import namespace is released.
|
||||
`math.compute` stays a capability category, not a core solver.
|
||||
- **H-03 `resource_request` ownership:** the reviewed operation table and policy
|
||||
are in [`architecture/resource-operations.md`](architecture/resource-operations.md);
|
||||
`architecture_boundaries::resource_request_operation_allowlist_is_reviewed` extracts
|
||||
the literals and fails on an unreviewed operation. New domain operations are
|
||||
forbidden in the core.
|
||||
|
||||
### 0.6.2 Proposed / deferred (not implemented, not claimed)
|
||||
|
||||
- **H-05/H-07/H-13 Heading Annotations v1:** `@exec`/`@knowledge` are frozen as
|
||||
the only Core Modes and alone decide execution. A declarative, metadata-only
|
||||
heading annotation layer is **Proposed** (ADR-0060,
|
||||
[`spec/heading-annotations-v1.md`](../spec/heading-annotations-v1.md), target
|
||||
`3.1.x`). This build still rejects an unknown `@foo` with
|
||||
`sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`,
|
||||
Analysis v3 or sidecar exists yet. Not advertised as available.
|
||||
- **H-02/F-B foreign:** the one-shot permission-gated `foreign.run/call` and the
|
||||
dynamic `KernelRegistry` remain the controlled OS-boundary primitive (F-A);
|
||||
removal (F-B) needs a versioned generic process/worker capability and the same
|
||||
security negatives. ADR-0063, [`spec/foreign.md`](../spec/foreign.md) §8.
|
||||
- Still deferred: full Math CAS/solver, persistent Foreign sessions, notebook
|
||||
execution, Analysis v3/sidecar, Windows/macOS native gates, strict L2.
|
||||
|
||||
### 0.6.3 Executed gate (Linux x86_64, Rust 1.100.0)
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS: 586 passed, 0 failed, 2 ignored
|
||||
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS: 28 passed
|
||||
cargo test -p marqdo-cli --test heading_inheritance PASS: 4 passed
|
||||
cargo test -p marqdo-cli --test math_library PASS: 2 passed
|
||||
cargo test -p marqdo-host --test resource_streams PASS: 34 passed
|
||||
cargo test -p marqdo-cli provider_manifest PASS: 9 passed
|
||||
cargo test -p marqdo-cli --test conformance_semantics PASS: 22/23/74/75 goldens
|
||||
```
|
||||
|
||||
The archive/stdlib digests, cold-install smoke, independent `ubuntu:24.04`
|
||||
container and external frozen-binary conformance are executed on the implementation
|
||||
commit and recorded with exact hashes in
|
||||
[`evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md)
|
||||
§5–§7; the external frozen-binary manifest is
|
||||
[`evidence/extension/b9c41564aeeadd2b7b202256b866bc13f995cb36/manifest.json`](evidence/extension/b9c41564aeeadd2b7b202256b866bc13f995cb36/manifest.json)
|
||||
(7/7 PASS, CLI sha256 `e684ed26…` matching the archive). This is local evidence,
|
||||
not a same-SHA CI pipeline or a tagged release; platform claim remains Linux x86_64.
|
||||
|
||||
## 0.7 Post-beta stable core review — RFC-GPL-0004 (unreleased)
|
||||
|
||||
- [ADR-0064](adr/0064-stable-core-extension-boundary.md) requires an accepted ADR,
|
||||
spec updates, evidence from three unrelated use cases and positive and negative
|
||||
cases for a core surface change. Tests check the current Builtin names and
|
||||
aliases, HostOp and Value variants, top-level CLI commands and the exact
|
||||
`resource.request` catalogue.
|
||||
- The compatibility dispatcher lives in
|
||||
`crates/marqdo-host/src/host/resource_requests.rs`. The Host still checks
|
||||
project mode, operation grants and argument shapes. Existing names and
|
||||
protocol versions apply. Math and Foreign follow ADR-0061 and ADR-0063.
|
||||
- The Linux jobs in Woodpecker and GitHub run
|
||||
`tools/ci/run_frozen_extensions.sh` against the release archive. The fixed
|
||||
cross-repository fixture covers pure package, Callable Worker, Foreign
|
||||
Kernel, Provider Worker and Tool. It also includes
|
||||
[`marqdo-net`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance/src/commit/cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec/marqdo-net)
|
||||
for bounded HTTP(S) and live SSE and
|
||||
[`marqdo-agent`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance/src/commit/cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec/marqdo-agent)
|
||||
for a sequential conversation with caller-authorized local tools. The gate
|
||||
checks the CLI (including its embedded plugin Worker) and the sibling
|
||||
Provider Worker digests against the archive and after the fixture run.
|
||||
- The Resource Control and Task milestones start with proposed
|
||||
[ADR-0065](adr/0065-resource-control-vnext.md) and
|
||||
[ADR-0066](adr/0066-structured-tasks-v1.md). Provider control, readiness,
|
||||
in-flight cancellation, parallel Agent, DB/QPU examples and Buffer
|
||||
Exchange remain follow-up work. Buffer Exchange first needs measurements
|
||||
of repeated container updates, resource I/O and Worker wire copies.
|
||||
The post-beta work does not qualify a new tag or stable release.
|
||||
|
||||
Local Linux x86_64 evidence for implementation commit `3bc7267` passed
|
||||
formatting, Clippy with warnings denied, the workspace (587 passed, 2 ignored),
|
||||
the CLI suite (215 passed), and the CI tool tests (30 passed). The release archive
|
||||
passed its installation smoke test. The [frozen archive manifest](evidence/extension/3bc726790fdcee3694fc0b56adbcfd0c6c645275/manifest.json)
|
||||
records 7/7 conformance groups and 6/6 reference cases with both executable
|
||||
digests. The external lane ran from a temporary fixture checkout with Cargo
|
||||
absent from PATH. Archive SHA-256 is
|
||||
`8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`.
|
||||
|
||||
## 1. Historical: pre-beta remote baseline and evidence
|
||||
|
||||
> **Historical record.** Everything in §1 onward was executed before the
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# ADR-0059: Runtime observability and Execution Events v1
|
||||
|
||||
- **Status:** Accepted
|
||||
- **Date:** 2026-11-22
|
||||
- **Decision owners:** CLI, runtime and host maintainers
|
||||
- **Inputs:** [RFC-OBS-0001](../architecture/RFC-OBS-0001-runtime-observability.md)
|
||||
(issue `#1` of `cflmy/marqdo-cli`), [Trace v2](../../spec/trace-v2.md),
|
||||
[Analysis v2](../../spec/analysis-v2.md), [Tool Protocol v1](../../spec/tool-v1.md)
|
||||
|
||||
## Context
|
||||
|
||||
Marqdo has two public, versioned machine-readable artifacts: Analysis v2
|
||||
(static, never executes) and Trace v2 (one complete document published
|
||||
atomically after a run). Neither can stream program stdout/stderr while a task
|
||||
is still running, and Trace v2 deliberately has no argument or local-variable
|
||||
values.
|
||||
|
||||
External tools (`marqdo-view`, agents, IDEs, Knowledge/Prove) therefore had two
|
||||
bad options: parse human terminal output, or embed/link private runtime types
|
||||
and build a second execution path. Both break the repository boundary this
|
||||
project exists to maintain: **the CLI is the only runtime**.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **A third, independent public protocol exists: Execution Events v1.**
|
||||
* `schema = "marqdo.execution-events"`, `schema_version = 1`.
|
||||
* It is a one-way NDJSON (JSON Lines) stream over the CLI's protocol stdout.
|
||||
* It is **not** Trace v2, not Analysis v2 and not Tool Protocol v1. Each has
|
||||
its own version axis. Adding optional events/fields is allowed in v1;
|
||||
changing required field meaning, ordering, redaction promises or the
|
||||
source-digest definition requires a new major.
|
||||
* The CLI implements no HTTP, SSE, WebSocket, browser session or
|
||||
View/Agent/IDE-specific branch. Consumers convert the stream themselves.
|
||||
|
||||
2. **The stream is opt-in and never changes semantics.**
|
||||
`marqdo run/call --event-stream jsonl` turns the CLI stdout into a pure
|
||||
JSONL channel. Without the option, stdout, stderr, exit codes, Trace and
|
||||
Analysis behavior are byte-for-byte unchanged. Observation is not a
|
||||
capability grant and cannot widen `pure/project/strict` authorization.
|
||||
|
||||
3. **`--event-stream jsonl` and `--json` are mutually exclusive.**
|
||||
`--trace-file` may be combined; Trace v2 keeps its atomic, post-run,
|
||||
low-sensitivity contract. Program stdout/stderr are encapsulated as
|
||||
`stdout.chunk`/`stderr.chunk` events and are never written raw to the
|
||||
protocol stdout.
|
||||
|
||||
4. **Events are emitted at real commit points, not from final buffers.**
|
||||
Stdout/stderr chunks originate in `StdHost::resource_write` immediately
|
||||
after the host accepts and commits bytes, inside the same budget path. The
|
||||
final `take_output()` buffer is never split into fake "live" chunks.
|
||||
Selected local-variable events originate after the assignment has been
|
||||
committed to `Frame.locals`; a rejected memory write never produces a
|
||||
success event.
|
||||
|
||||
5. **The host owns the observation facade.**
|
||||
`marqdo-host::observe` defines typed internal events (`ObservationEvent`),
|
||||
the `ObservationSink` trait, `ObservationConfig`, frame identity
|
||||
(`FrameId`) and the observation budget. The runtime emits borrowed events
|
||||
through default `Host` methods; it never hands the sink `Frame.locals`,
|
||||
the whole `MemoryStore`, or raw OS handles. The CLI owns only JSONL
|
||||
encoding and the public envelope. No new crate is introduced.
|
||||
|
||||
6. **Call instances get an opaque identity.**
|
||||
Each entered frame gets a run-unique `frame_id` (`f1`, `f2`, ...) and a
|
||||
`parent_frame_id` (`null` at the top level). Frame IDs exist only in
|
||||
Execution Events v1; Trace v2 is not given a new field. Argument binding
|
||||
happens before a frame is announced, so a failed binding never produces a
|
||||
dangling frame.
|
||||
|
||||
7. **Values are selected, bounded and off by default.**
|
||||
* Default event mode publishes types/status only (`value_state:
|
||||
not_requested`).
|
||||
* `--observe-variable NAME` / `--observe-parameter NAME` are exact-name,
|
||||
repeatable selections. There is no wildcard, regex, path expression or
|
||||
`--dump-all-locals`.
|
||||
* Supported value types are the scalars `Int`, `Float`, `Bool`; `Text`
|
||||
additionally requires `--observe-text-values`. Lists, maps, tables,
|
||||
formulas, code, memory, resources and plugin handles report
|
||||
`unsupported` and are never expanded or serialized by `Debug`.
|
||||
* Every value is capped by `--observe-max-value-bytes` (default 256) and
|
||||
reports `not_requested`, `redacted`, `truncated`, `unsupported` or
|
||||
`observed` distinctly. A text truncation never splits a UTF-8 scalar.
|
||||
* Observation lowers confidentiality: it is an explicit developer action.
|
||||
It is never enabled from a project manifest, never recorded in Trace v2
|
||||
or Analysis v2, and never automatically enabled by View.
|
||||
|
||||
8. **Budgets, ordering and failure are defined.**
|
||||
* One dispatcher assigns `seq` from 0; stdout/stderr, structural and value
|
||||
events share the observable order of admission.
|
||||
* Structural/value events have a bounded budget (default 100 000 events /
|
||||
16 MiB). Exhaustion emits one `observation.truncated` and stops only
|
||||
non-critical events; stdout/stderr and the terminal event still flow.
|
||||
* `stream.opened` (seq 0), `run.started`, stdout/stderr and the terminal
|
||||
`run.completed`/`run.failed`/`run.rejected` are not dropped by the
|
||||
structural budget.
|
||||
* Writes are bounded and synchronous: a slow consumer applies IO
|
||||
backpressure instead of growing an unbounded queue. A write failure
|
||||
aborts the run with `observe.transport_failed`; the CLI must not keep
|
||||
executing a program with side effects after its event pipe broke, and it
|
||||
must not write a half JSON line.
|
||||
* A killed/crashed process may have no terminal event. Consumers must
|
||||
report `incomplete`, never synthesize success.
|
||||
|
||||
9. **`run.rejected` covers pre-execution failure in event mode.**
|
||||
After the writer is open, prepare/authorization/compile failures produce a
|
||||
structured terminal `run.rejected` with the existing stable error code and
|
||||
phase, a non-zero exit, and no `run.started`. CLI option parsing errors
|
||||
still use the ordinary clap stderr path before the protocol exists.
|
||||
|
||||
10. **The source binding is the Analysis digest.**
|
||||
`run.started.payload.source` carries `root_id` and
|
||||
`analysis_digest` = `sha256:` plus the SHA-256 of the exact Analysis v2
|
||||
bytes for the same project/projection configuration. A changed source
|
||||
makes old events stale; consumers must not render them onto new source.
|
||||
|
||||
11. **The Trace v2 run identity is shared, without changing Trace v2.**
|
||||
In a combined run the CLI composition root creates one opaque `run_id` and
|
||||
passes it to both writers, so `trace.run.id == execution stream run_id`.
|
||||
Trace v2 keeps `schema_version: 2` and gains no frame/value fields.
|
||||
|
||||
## Consequences
|
||||
|
||||
- External tools can consume live output with a released binary and a
|
||||
documented schema; they still need no private Rust crate.
|
||||
- The runtime gains observation hooks at existing commit points. The default
|
||||
(no option) path installs no sink and does not clone `Value`s or serialize
|
||||
observation data.
|
||||
- The value policy is intentionally smaller than a debugger. Breakpoints,
|
||||
stepping, time travel, raw memory snapshots, memory-byte events and a
|
||||
bidirectional Debug Protocol remain a separate future RFC.
|
||||
- Memory metadata events (`memory.region.*`, `memory.budget`) are P2 in
|
||||
RFC-OBS-0001 and are **not** part of this decision's implemented scope; no
|
||||
raw memory content or handle is ever exposed.
|
||||
|
||||
## Rejected alternatives
|
||||
|
||||
- **Stream Trace v2 while running.** Breaks existing complete-file consumers
|
||||
and cannot naturally carry live stdout/stderr or reject-before-run events.
|
||||
- **Make events a flag of `--json`.** Mixes a complete result envelope with a
|
||||
line stream on one channel and violates the clean-stdout guarantee.
|
||||
- **Emit stdout by splitting the final buffer.** It is not real-time and
|
||||
defeats the purpose; the RFC explicitly forbids it.
|
||||
- **Put JSONL/SSE/HTTP in the CLI.** Adds transport and product concerns to
|
||||
the composition root; View's SSE belongs to the View repository.
|
||||
- **Publish all locals as a default debugging dump.** Unbounded
|
||||
confidentiality loss and no stable value encoding; rejected in favour of
|
||||
exact, bounded selections.
|
||||
@@ -0,0 +1,74 @@
|
||||
# ADR-0060: Heading modes are core; heading annotations are declarative metadata
|
||||
|
||||
Status: Accepted (RFC-EXT-0003 H-05/H-07/H-13, post-`3.0.0-beta.1`).
|
||||
Implementation status: **core-mode classification is implemented and tested;
|
||||
Heading Annotations v1 is Proposed and not implemented in this build** (targeted
|
||||
at `3.1.x`). This ADR does not itself make annotations available.
|
||||
Related: RFC-LANG-0002, ADR-0052, [`spec/mapping.md`](../../spec/mapping.md),
|
||||
[`spec/heading-annotations-v1.md`](../../spec/heading-annotations-v1.md).
|
||||
|
||||
## Context
|
||||
|
||||
`@exec`/`@knowledge` look like decorators, which invites the idea that a plugin
|
||||
could redefine them, or add `@agent`/`@test` decorators that change whether a
|
||||
section executes. That would make the same document executable in one installation
|
||||
and inert in another, break `check` ↔ `run` binding equality, and let third-party
|
||||
code affect capability and safety. At the same time, tools genuinely need
|
||||
non-executable heading metadata (test selection, View folding, proof
|
||||
obligations).
|
||||
|
||||
The current parser (`crates/marqdo-frontend/src/units.rs::heading_declaration`)
|
||||
already treats a heading's first plain `Text` prefix as a closed mode token and
|
||||
rejects any other leading `@foo` with `sem.invalid_mode_marker`
|
||||
(`tests/negative/01-invalid-mode-marker-case.expected.json`). Analysis v2
|
||||
`units[]` projects only `id/kind/name/level/span/function`; a `section`,
|
||||
`knowledge` or `namespace` unit does not carry its effective mode or annotation
|
||||
source.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Two layers, one executor.**
|
||||
- **Core Mode** is the closed set `{@exec, @knowledge}`. It alone decides
|
||||
whether a heading is callable/executable. Unmarked headings inherit the
|
||||
nearest ancestor mode (see `spec/mapping.md` §1.2, including the H-06
|
||||
bugfix). There is no third executable mode and no plugin-defined mode.
|
||||
- **Heading Annotations** are an open, declarative, metadata-only extension
|
||||
layer. They never decide execution.
|
||||
2. **Annotation syntax v1** (Proposed): an ATX heading's first plain `Text` prefix
|
||||
may contain at most one core mode followed by zero or more
|
||||
`@namespace.identifier` annotations, then the semantic title. No parameters in
|
||||
v1; annotations do not inherit; `semantic_name`/`FunctionId`/anchors are derived
|
||||
only from the core mode + normalized title. A malformed/unknown annotation is a
|
||||
static error (`annotation.unknown` or `annotation.malformed`), not silently
|
||||
plain prose; ordinary body text may discuss `@foo`, and a heading-only spelling
|
||||
escape is part of the proposal.
|
||||
3. **No authority.** An annotation may not add/remove callability, rewrite the AST
|
||||
or IR, reorder statements, change budgets, grant a capability, load native code
|
||||
or change an already-bound CallBinding. The runtime ignores annotations.
|
||||
4. **Registration is data, not parse-time code.** Allowed annotations come from
|
||||
explicitly declared, version-pinned project/dependency resources (a static
|
||||
manifest referenced from `marqdo.yaml`), bound to project/lock identity and
|
||||
digest. Duplicate ownership, conflicting names, unknown versions and digest
|
||||
mismatches fail at `check` without executing anything.
|
||||
5. **Analysis projection is versioned.** Do **not** silently add
|
||||
`effective_mode`, `mode_origin` or `annotations` to Analysis v2 `units[]`.
|
||||
Use a new Analysis v3 or a separate `heading-annotations.v1` sidecar carrying
|
||||
unit id, effective core mode, explicit/inherited origin, annotations, source
|
||||
module/span, function/unit id, and manifest owner/digest. Existing
|
||||
Analysis v2 consumers continue to validate unchanged.
|
||||
6. **Step split.** Step A (accepted here) is this contract + parser test design +
|
||||
identity/schema prototype; Step B (3.1) implements descriptor loading, index,
|
||||
conflict checks, the sidecar/v3 projection and independent consumers. Until Step B
|
||||
ships, docs/STATUS must say Proposed/not implemented.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Core-mode behaviour (`@exec`/`@knowledge` + ancestor inheritance) is stable and
|
||||
cannot be overridden by installed tools; the H-06 fix changes only the buggy
|
||||
sibling case.
|
||||
- Tool authors get a safe metadata channel without a plugin parse hook; the runtime
|
||||
never needs to know tool names.
|
||||
- Analysis v2 stays byte-compatible; new metadata needs a versioned sidecar/v3 and an
|
||||
independent black-box consumer before it can be claimed.
|
||||
- `check` and `run` still agree on every call site regardless of which tools are
|
||||
installed.
|
||||
@@ -0,0 +1,64 @@
|
||||
# ADR-0061: Detach the domain math kernel from the core
|
||||
|
||||
Status: Accepted (post-`3.0.0-beta.1`, RFC-EXT-0003 H-01/H-10/H-11).
|
||||
Related: RFC-LANG-0002, ADR-0025, ADR-0032, ADR-0052, ADR-0062.
|
||||
This ADR is an intentional **prerelease incompatibility**; it does not promise
|
||||
zero-cost migration for `3.0.0-beta.1` users.
|
||||
|
||||
## Context
|
||||
|
||||
The core exposed five domain functions as first-class builtins:
|
||||
|
||||
- `math.parse`, `math.eval`, `math.substitute` over an exact-rational subset;
|
||||
- `math.simplify`, `math.differentiate` declared but returning
|
||||
`math.unsupported`.
|
||||
|
||||
They required a core crate (`crates/marqdo-math`) in the host dependency graph,
|
||||
reserved the `math` import namespace forever, made the `HostOp` enum grow with a
|
||||
domain, and were not a complete CAS. Every new math algorithm would either grow
|
||||
the core or be blocked by the reserved namespace. The beta audit (H-01, T-MATH-05/06)
|
||||
recorded this as unintended domain ownership.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Remove the API from the core surface.** Delete the five `Builtin` entries,
|
||||
the five `HostOp` variants, their dispatch/runtime arms, the reserved
|
||||
`math` namespace as a builtin, and the `marqdo-math` workspace crate. A call
|
||||
to `math.parse/eval/substitute/simplify/differentiate` is a static
|
||||
`symbol.unknown`; there is no `math.unsupported` runtime fallback and no old
|
||||
compatibility parser.
|
||||
2. **Keep only language primitives.** `Int`/`Float` literals, ordinary
|
||||
arithmetic/comparison/control flow, and the inert Markdown `Formula` value
|
||||
(a `$$...$$` block referenced with `ref("#anchor")`) stay in the core. The
|
||||
core never evaluates a `Formula`.
|
||||
3. **Algorithms move out.**
|
||||
- Preferred: a pure `.mq.md` package exposing ordinary Exec H2 functions
|
||||
(`examples/math-library/` shows gcd + a consumer importing it as `math` now
|
||||
that the namespace is released).
|
||||
- Hot path / external data: an explicitly selected Plugin ABI v1 backend that
|
||||
requests the `math.compute` capability (`examples/math-backend/`). Selection
|
||||
is not authorization: native needs `--trust-native-plugin` and every plugin
|
||||
needs `--allow-plugin NAME`; without the grant it is `permission.denied`.
|
||||
4. **`math.compute` stays.** `CORE_CAPABILITIES` may continue to name
|
||||
`math.compute` as a capability **category** requested by an ABI compute
|
||||
backend. It is not a promise that the core ships a solver, parser or evaluator,
|
||||
and pure language arithmetic never requires it.
|
||||
5. **One binding, no fallback.** `check`, `run` and `call` see the same static
|
||||
result for a removed name. New math functions require neither `BUILTINS`,
|
||||
`HostOp`, `Host`, `Value`, `resource_request` nor a CLI rebuild.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Beta users of `math.*` must migrate; `CHANGELOG`/`spec/math.md` carry the
|
||||
removed-name list, the `symbol.unknown` behaviour and a pure-package example.
|
||||
- A `math` import alias is accepted again because no builtin namespace reserves it;
|
||||
`ext.import_namespace_conflict` no longer fires for `math`.
|
||||
- The host no longer links `marqdo-math`; `cargo tree -p marqdo-host`/`-p marqdo-cli`
|
||||
contain no math crate. An architecture gate
|
||||
(`architecture_boundaries.rs`) fails if the crate or `HostOp::Math*` returns.
|
||||
- The exact-rational engine is deleted rather than kept as dead core code. External
|
||||
libraries own their numeric contracts; API and precision are their responsibility.
|
||||
- No Analysis v2, Trace v2, Value wire or capability wire version changes: only a
|
||||
builtin/HostOp surface and one crate are removed, and the static error code is
|
||||
the existing `symbol.unknown`.
|
||||
- No OS sandbox, performance or CAS claim is made.
|
||||
@@ -0,0 +1,62 @@
|
||||
# ADR-0062: Resource-operation ownership and core resource kinds
|
||||
|
||||
Status: Accepted (post-`3.0.0-beta.1`, RFC-EXT-0003 H-03 / H-04).
|
||||
Supersedes nothing; refines ADR-0025, ADR-0033, ADR-0041–0050 and
|
||||
[`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md).
|
||||
|
||||
## Context
|
||||
|
||||
`Host::resource_request` had grown a mixed catalogue: operating-system
|
||||
primitives (`process.run`, `fs.*`, `env.get`, `clock.now`, `random.bytes`) next to
|
||||
convenience services implemented inside the host (`regex.*`, `compress.*`).
|
||||
Nothing recorded which entries were intentional core surface and which were domain
|
||||
convenience that should become external extensions. Separately, six resource kinds
|
||||
were reserved by `spec/resource-provider-v2.md`, but the trusted host registration
|
||||
path only rejected `stdio` and `file`; only the CLI manifest validator had the full
|
||||
list. A host caller (`register_resource_provider`, `register_c_resource_provider`,
|
||||
`register_worker_resource_provider`, `register_provider_package`) could therefore
|
||||
register a provider named `tcp` or declaring `tls` and shadow core dispatch.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. One core resource-kind registry
|
||||
|
||||
`marqdo_host::CORE_RESOURCE_KINDS` is the single source of truth:
|
||||
`stdio`, `file`, `tcp`, `tls`, `udp`, `tcp-listener`. Both the CLI provider
|
||||
manifest validator and every host registration path use it. A provider whose `name`
|
||||
is a core kind, or which declares a core kind, is rejected before it enters the
|
||||
resource table with `ResourceUnsupported` (CLI: `ext.manifest_invalid`). A change
|
||||
to the list requires this ADR and the spec to change with it.
|
||||
|
||||
### 2. Two operation classes
|
||||
|
||||
`resource_request` is closed over the following reviewed operations:
|
||||
|
||||
| Class | Operations | Owner |
|
||||
|---|---|---|
|
||||
| Core OS primitive | `process.run`, `env.get`, `clock.now`, `random.bytes`, `fs.read_at`, `fs.append`, `fs.walk`, `fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`, `fs.rename` | host / OS |
|
||||
| Host-held built-in service | `regex.match`, `regex.captures`, `compress.gzip`, `compress.gunzip` | host library, existing grants |
|
||||
|
||||
`regex.*` and `compress.*` are existing host-held services with their own
|
||||
ADRs; they are not a precedent for adding more domain functions to the host.
|
||||
Project mode and the corresponding capability grant are required for every entry.
|
||||
|
||||
### 3. Extension boundary rule
|
||||
|
||||
New business or domain operations **must not** be added to `resource_request`.
|
||||
A domain function belongs in a pure `.mq.md` package, a Callable Plugin ABI
|
||||
backend, or a Resource Provider — selected and authorized through the normal
|
||||
extension path. Adding an operation to the core table requires a new accepted ADR and
|
||||
an update to [`docs/architecture/resource-operations.md`](../architecture/resource-operations.md),
|
||||
`spec/resource-provider-v2.md` and the architecture gate
|
||||
`crates/cli/tests/architecture_boundaries.rs`.
|
||||
|
||||
## Consequences
|
||||
|
||||
- A host-side provider can no longer shadow a core kind even when it did not pass
|
||||
through the CLI validator; the CLI and host fail with consistent wording.
|
||||
- The reviewed operation list is executable evidence: the architecture test extracts
|
||||
the literals from `resource_request` and fails on unrecorded additions.
|
||||
- `regex.*` / `compress.*` keep working unchanged; moving them out is a separate
|
||||
ADR and is not implied by this one.
|
||||
- No CLI flag, language keyword, wire version or Analysis/Trace schema changes.
|
||||
@@ -0,0 +1,56 @@
|
||||
# ADR-0063: Foreign kernel transition — retain F-A, defer F-B
|
||||
|
||||
Status: Accepted (RFC-EXT-0003 H-02/H-12, post-`3.0.0-beta.1`).
|
||||
Related: ADR-0020, ADR-0044, ADR-0062, [`spec/foreign.md`](../../spec/foreign.md).
|
||||
|
||||
## Context
|
||||
|
||||
The core exposes permission-gated one-shot `foreign.run`/`foreign.call` plus a
|
||||
`KernelRegistry` whose default descriptors are Python/Node but which already
|
||||
accepts dynamically registered languages. The audit (H-02) observed that:
|
||||
`foreign.*` is a controlled **OS process boundary**, not a domain function; the
|
||||
high-level batching/validation/orchestration around it should be a `.mq.md` package;
|
||||
and removing the primitive before a generic process/stream capability exists would
|
||||
push OS behaviour into an unregulated worker without improving safety.
|
||||
|
||||
Two legitimate but conflicting goals: "the frontend/runtime should not know each
|
||||
external language API" (already true — registration is dynamic) versus "Foreign must
|
||||
disappear from the core to count as decoupled" (not automatically true — some layer
|
||||
must own the real OS process/IO boundary).
|
||||
|
||||
## Decision
|
||||
|
||||
**F-A (current, retained):** keep the existing permission-gated one-shot
|
||||
`foreign.run`/`foreign.call` and the dynamic `KernelRegistry` as the controlled
|
||||
OS-boundary primitive.
|
||||
|
||||
- No new language-specific `Builtin`, `HostOp` or runtime branch may be added.
|
||||
New languages register through `KernelRegistry::register`; Python/Node are only
|
||||
default descriptors, not the only extension channel.
|
||||
- High-level orchestration (sequencing, batching, validation, error normalization)
|
||||
belongs in `.mq.md` packages, not in the host.
|
||||
- Grants, digest/target checks, timeout, output caps, typed wire and environment
|
||||
binding stay exactly as `spec/foreign.md` specifies; the security negatives are
|
||||
not weakened by this ADR. Without `--allow-foreign` the call is
|
||||
`permission.denied`; `pure`/`strict` fail closed.
|
||||
|
||||
**F-B (deferred, needs its own ADR + release):** removing `foreign.*` from the
|
||||
core requires first a versioned generic Process/Worker capability contract with at
|
||||
least: program/argv, controlled stdio, isolation level, timeout and process-tree
|
||||
reaping, output budget, environment identity, lifecycle and cancellation
|
||||
semantics. It must demonstrate frozen-binary behavioural equivalence and keep the
|
||||
same permission, digest, timeout, wire and output-limit negatives. Until then the
|
||||
core keeps the primitive and we do not claim it was removed.
|
||||
|
||||
**Forbidden in both phases:** persistent Python/Node sessions, Notebook-cell
|
||||
execution, `@python`-style heading auto-execution, and a second foreign runtime
|
||||
inside View; streaming stays in Execution Events, not a second network protocol.
|
||||
|
||||
## Consequences
|
||||
|
||||
- The core is honest: it owns a controlled foreign primitive and documents it.
|
||||
- Adding a new language needs zero Rust/core changes (T-FOREIGN-01 remains the
|
||||
acceptance test); the default descriptor table may later become a verified static
|
||||
config, but that is not required to decouple domains.
|
||||
- F-B stays open and tracked; docs/STATUS records it as deferred rather than as
|
||||
implemented.
|
||||
@@ -0,0 +1,42 @@
|
||||
# ADR-0064 — Stable core and extension boundary
|
||||
|
||||
Status: Accepted for the post-beta development line. Input is [RFC-GPL-0004,
|
||||
issue #4](https://git.cflmy.cn/cflmy/marqdo-cli/issues/4).
|
||||
|
||||
## Decision
|
||||
|
||||
The frontend owns the single Markdown-to-IR mapping and static callable binding.
|
||||
The runtime owns evaluation and run-local state. The Capability Host owns
|
||||
authority, resource identity, budgets and observable effects. Tool v1 dispatches
|
||||
independent processes. Domain code goes in a Marqdo package, a Callable Plugin,
|
||||
a Resource Provider, a Foreign Kernel, or a Tool, according to which existing
|
||||
interface it needs.
|
||||
|
||||
Keep the core surface inventory under review. A change to the builtin catalogue,
|
||||
HostOp, Value or top-level command set requires a new accepted ADR, the relevant
|
||||
specification changes, and evidence from at least three unrelated use cases
|
||||
that need the same primitive. Include a working composition example or explain
|
||||
why the existing interfaces cannot express one. Describe authority, ownership,
|
||||
cleanup, performance, compatibility, and positive and negative tests.
|
||||
The reviewed resource operations remain governed by ADR-0062 and Foreign F-A
|
||||
by ADR-0063.
|
||||
|
||||
The Linux check builds the release CLI and its shipped provider worker, installs
|
||||
the archive, and runs a pinned external conformance repository against it.
|
||||
The evidence identifies the core and fixture commits and the executable
|
||||
digests. New extension use cases should enter that repository first. The
|
||||
stock package, Worker Callable, Foreign Kernel, Resource Provider, and
|
||||
registered Tool cases continue to exercise the same prebuilt CLI.
|
||||
|
||||
Feature work that depends on new runtime primitives follows
|
||||
[Resource Control](0065-resource-control-vnext.md) and
|
||||
[Task v1](0066-structured-tasks-v1.md) as independent milestones. Each proposal
|
||||
has its own adoption and acceptance criteria. HTTP and model-specific behavior
|
||||
belongs to independent reference packages using the published interfaces.
|
||||
|
||||
## Consequences
|
||||
|
||||
Extension packages depend on public contracts. The source and ABI for those
|
||||
contracts keep their existing release policy. The inventory gate covers changes
|
||||
to the named surfaces and the external tests cover composition at runtime.
|
||||
Review still checks changes inside an existing dispatch branch.
|
||||
@@ -0,0 +1,51 @@
|
||||
# ADR-0065 — Declarative Resource Control
|
||||
|
||||
Status: Proposed. Follow-up to RFC-GPL-0004 §4 and ADR-0062.
|
||||
|
||||
## First milestone
|
||||
|
||||
Introduce a versioned provider contract for control on a live resource. Keep
|
||||
Provider v2 stream transport and its schema supported. Select control-capable
|
||||
providers explicitly through the manifest and lock, pinning both descriptor
|
||||
content and the platform artifact. The check/inspect path reads declarations
|
||||
without starting a worker. Dynamic action names and argument values also need
|
||||
full validation at dispatch.
|
||||
|
||||
A manifest declares actions by resource kind. Each action has a unique name,
|
||||
ordered argument shapes, a required right and a result kind. The result is
|
||||
either a bounded Value Wire value or a child kind declared by the same provider.
|
||||
Begin with positional arguments and a closed set of wire shapes. A handle always
|
||||
selects the provider and kind that issued it. The caller cannot override either.
|
||||
The dispatcher checks the live run-owned handle, provider grant, handle rights,
|
||||
registered action, arity and shapes before sending a worker request. Both the
|
||||
request and validated response are auditable without recording arguments.
|
||||
|
||||
Child creation returns an opaque provider token over the transport. The Host
|
||||
validates the result envelope, kind, freshness and quota before minting a
|
||||
run-owned Resource. Child rights are bounded by the action declaration and the
|
||||
operator's grant. Validation and handle publication form one transaction. If
|
||||
the Host cannot adopt a freshly allocated token, it releases the token or
|
||||
tears down the faulted worker. It invalidates worker-owned handles on transport
|
||||
failure and reaps them on run teardown. Raw host handles are excluded from all
|
||||
wire values. Timeout, malformed frames and worker exit have bounded cleanup.
|
||||
|
||||
## Later milestone
|
||||
|
||||
Specify `resource.wait` separately after the control path works. Readiness
|
||||
needs a monotonic deadline, a cancellation source and a bounded batch of
|
||||
run-owned handles. Unsupported interests return a defined error. The
|
||||
implementation must state how it interrupts each supported transport and what
|
||||
happens to outstanding control requests on cancellation. A synchronous Worker
|
||||
continues to provide process isolation from faults and needs a separate policy
|
||||
for OS containment.
|
||||
|
||||
## Before acceptance
|
||||
|
||||
Use a counter for bounded state mutations, a queue for acknowledgments, and a
|
||||
listener for child adoption. Test authorization before worker effects, unknown
|
||||
actions, wrong shapes, untrusted or closed handles, repeated or mismatched
|
||||
tokens, artifact substitution, malformed and oversized messages, worker loss
|
||||
and teardown. Run the same stream-only Provider v2 suite on the new binary.
|
||||
The initial implementation should register the three test kinds as external
|
||||
fixtures. The host's closed `resource.request` catalogue remains governed by
|
||||
ADR-0062.
|
||||
@@ -0,0 +1,56 @@
|
||||
# ADR-0066 — Structured Tasks and bounded Channels
|
||||
|
||||
Status: Proposed. Follow-up to RFC-GPL-0004 §§5, 7 and 10.
|
||||
|
||||
## Execution and authority
|
||||
|
||||
Use a shared immutable prepared program and the existing callable resolution.
|
||||
Spawn initially accepts a prepared FunctionRef with positional input. Each task
|
||||
has its own interpreter frames, MemoryStore and Host resources. All spawned
|
||||
tasks belong to the run. Task identities are opaque and scoped to that run.
|
||||
Only an owning task may join or cancel its child. Supervisors finish by
|
||||
reaping all children, including when the parent itself fails.
|
||||
|
||||
A child gets the intersection of its parent's effective grants and a requested
|
||||
subset. If the subset is omitted, the child starts with no optional effect
|
||||
grants. Charge every task, including descendants, to shared run quotas for
|
||||
live tasks, queued work, fuel, memory, messages and output. A child deadline
|
||||
cannot exceed its parent's. Bound scheduling admission before starting any
|
||||
effect. The scheduler needs a defined strategy for joins and blocking sends
|
||||
with a saturated worker pool. Prove progress for nested spawn with a two-worker
|
||||
limit before freezing the design.
|
||||
|
||||
Transfer bounded snapshots of ordinary values. At every nesting level reject
|
||||
Memory, Resource, PluginHandle, task handles and channel endpoints unless a
|
||||
separate typed endpoint-transfer rule is specified. FunctionRef is resolved
|
||||
against the same immutable prepared program. Table, Code and Formula transfers
|
||||
need size and depth accounting. Channel queues are bounded by count and bytes.
|
||||
Send is initially nonblocking with a full or closed result. Receive waits
|
||||
until a value, closure, deadline or cancellation. Specify channel endpoint
|
||||
ownership during the prototype before choosing any public syntax.
|
||||
|
||||
## Join, cancellation and observations
|
||||
|
||||
Join returns a structured outcome for completion, ordinary child failure and
|
||||
cancellation. A join wait timeout leaves the child joinable. Explicit cancel
|
||||
propagates to descendants and wakes waits. Capability denials and budget
|
||||
violations terminate the offending task and remain distinguishable from
|
||||
ordinary application failures. No task can use Join to resume an unauthorized
|
||||
effect.
|
||||
|
||||
Cancellation is cooperative at interpreter safe points. Bound or exclude Host
|
||||
operations that cannot honor run teardown, including uncancellable native
|
||||
calls. Where a worker can be interrupted, termination and reap have separate
|
||||
deadlines and must account for descendants. Task and parent IDs belong to a
|
||||
versioned observability contract. Ordering is defined per task, with explicit
|
||||
causal links across spawn, message delivery and join.
|
||||
|
||||
## Before acceptance
|
||||
|
||||
Exercise CPU recursion, concurrent mock network calls and batch orchestration
|
||||
with an independent failure, deadline and success. Test nested joins under
|
||||
pool saturation, queue and budget exhaustion, resource cleanup on parent exit,
|
||||
permission attenuation and rejection of nested live handles. Compare the
|
||||
existing single-task behavior and performance on the same workloads. Freeze
|
||||
public names, Value/Handle representation and schema versions only after this
|
||||
prototype. Shared memory and async syntax need separate decisions.
|
||||
+22
-1
@@ -43,4 +43,25 @@ Files: `0001`–`0050`, plus:
|
||||
* `0057-capability-handler-registration.md` — declared capability vs installed
|
||||
handler vs audit;
|
||||
* `0058-stdlib-public-alias.md` — verified stdlib `public_aliases` replace
|
||||
print magic.
|
||||
print magic;
|
||||
* `0059-runtime-observability-and-execution-events.md` — typed host
|
||||
observation facade, Execution Events v1 JSONL boundary, frame identity and
|
||||
selected-value policy;
|
||||
* `0060-heading-modes-and-extensible-annotations.md` — `@exec`/`@knowledge`
|
||||
are the closed Core Modes; metadata-only Heading Annotations v1 is Proposed
|
||||
(target 3.1), Analysis v2 unchanged;
|
||||
* `0061-detach-domain-math-kernel-from-core.md` — remove `math.*` builtins,
|
||||
`HostOp` variants and `marqdo-math`; pure package + optional ABI backend take
|
||||
over; `Formula`/`math.compute` boundaries;
|
||||
* `0062-resource-operation-ownership-and-core-kinds.md` — single
|
||||
`CORE_RESOURCE_KINDS` registry, two `resource_request` operation classes and
|
||||
the reviewed architecture gate;
|
||||
* `0063-foreign-kernel-transition-fa.md` — retain the permission-gated one-shot
|
||||
foreign primitive as F-A; F-B removal requires a versioned generic
|
||||
process/worker capability.
|
||||
* [0064](0064-stable-core-extension-boundary.md) — core surface review and
|
||||
frozen external conformance;
|
||||
* [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful
|
||||
operations and child resources;
|
||||
* [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded
|
||||
communication and cancellation.
|
||||
@@ -4,7 +4,7 @@ Status: **current architecture overview**. This file summarises the tree as it
|
||||
is today. It is not a release promise, does not reopen a frozen ADR, and does not
|
||||
replace `spec/` or a recorded test log.
|
||||
|
||||
- Baseline: `56189b176c612bf399ff965c3b642077f6b04617` (2026-11-22, RFC-EXT-0001 tree; the tagged `v3.0.0-beta.1` release SHA and its evidence are recorded in `../STATUS.md`).
|
||||
- Baseline: `2c7c4f31e7a388d3fcfa717a77067e696ed13854` (2026-11-22, tagged `v3.0.0-beta.1`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`).
|
||||
- Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`.
|
||||
- This is the **single current overview**. Do not add a second running "current state" file;
|
||||
update this file, `docs/STATUS.md` and an evidence file together.
|
||||
@@ -26,6 +26,34 @@ replace `spec/` or a recorded test log.
|
||||
> Normative boundaries: [`spec/callable-resolution.md`](../../spec/callable-resolution.md),
|
||||
> [`spec/extension-selection.md`](../../spec/extension-selection.md),
|
||||
> [`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md).
|
||||
>
|
||||
> **Post-baseline observability (ADR-0059, RFC-OBS-0001).** After the tagged
|
||||
> baseline the tree adds Execution Events v1: a typed host observation facade,
|
||||
> real-commit stdout/stderr chunks, run-unique call frames and explicitly
|
||||
> selected bounded values over `run/call --event-stream jsonl`. Analysis v2 and
|
||||
> Trace v2 are unchanged. This is locally tested on the post-baseline tree
|
||||
> ([`../STATUS.md`](../STATUS.md) §0.5) and is not part of the tagged beta
|
||||
> archive or its same-SHA evidence.
|
||||
>
|
||||
> **Post-baseline core/extension boundary (RFC-EXT-0003, ADR-0060–0063).** The
|
||||
> core call surface no longer owns the domain math kernel (`math.*` removed;
|
||||
> `crates/marqdo-math` deleted; ADR-0061), sibling heading mode inheritance is
|
||||
> fixed (H-06), the release archive must ship the verified `stdlib/` (H-08), one
|
||||
> `CORE_RESOURCE_KINDS` registry guards every provider registration path
|
||||
> (H-04), `resource_request` operation ownership is enforced by an architecture
|
||||
> gate (H-03), and the foreign one-shot primitive is explicitly retained as F-A
|
||||
> (ADR-0063). Heading Annotations v1 is **Proposed/not implemented** (ADR-0060,
|
||||
> target `3.1.x`) and must not be documented as available. Executed evidence:
|
||||
> [`../STATUS.md`](../STATUS.md) §0.6 and
|
||||
> [`../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
|
||||
|
||||
> **Stable core review (RFC-GPL-0004).** [ADR-0064](../adr/0064-stable-core-extension-boundary.md)
|
||||
> sets the review rule for builtins, HostOp, Value and top-level commands.
|
||||
> Linux CI builds a release archive and exercises its installed executables
|
||||
> against a fixed commit in the external conformance repository. The
|
||||
> [Resource Control](../adr/0065-resource-control-vnext.md) and
|
||||
> [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed.
|
||||
> See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased).
|
||||
|
||||
## 1. Four state dimensions
|
||||
|
||||
@@ -35,8 +63,8 @@ platform".
|
||||
|
||||
| Dimension | Current state | Source |
|
||||
|---|---|---|
|
||||
| Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root | `Cargo.toml`, `crates/`, `stdlib/` |
|
||||
| Tested locally | `cargo test --workspace --locked`: **599 passed, 0 failed** across 67 targets on Linux x86_64 in the RFC-EXT-0001 tree; fmt and clippy clean. Historical baseline: 507 passed at `9c1723d`. | `docs/STATUS.md`, `docs/evidence/2026-11-22-ext-implementation.md` |
|
||||
| Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; post-baseline Execution Events v1 (ADR-0059), core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` |
|
||||
| Tested locally | `cargo test --workspace --locked`, `cargo fmt --all -- --check`, `clippy -D warnings`, release archive smoke and an independent `ubuntu:24.04` cold-install run on the RFC-EXT-0003 tree (Linux x86_64); exact counts and logs are in `docs/STATUS.md` §0.6 and the RFC-EXT-0003 evidence file. Historical baselines stay in earlier sections. | `docs/STATUS.md` §0.6, `docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md` |
|
||||
| Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` |
|
||||
| Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 |
|
||||
|
||||
@@ -46,9 +74,10 @@ platform".
|
||||
user .mq.md programs / agents / research workflows
|
||||
|
|
||||
stdlib/*.mq.md (versioned and digest-checked in this repository)
|
||||
core / collections / text / encoding / data / math
|
||||
core / collections / text / encoding / data
|
||||
io / console / stream / fs / net / process
|
||||
memory / alloc + portable pure algorithms
|
||||
(math algorithms are external: examples/math-library + ABI backend)
|
||||
|
|
||||
language semantics: Markdown -> AST -> frontend -> IR
|
||||
|
|
||||
@@ -99,7 +128,7 @@ Current Rust dependency edges (documented, not proposed):
|
||||
marqdo-cli -> marqdo-runtime -> marqdo-host
|
||||
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ...
|
||||
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
|
||||
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-math
|
||||
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox
|
||||
```
|
||||
|
||||
`marqdo-runtime -> marqdo-host` is the current direction. Do not add a second
|
||||
@@ -110,12 +139,17 @@ review RFC, not a new crate per provider.
|
||||
| Public contract | API (`.mq.md`) | State | Tests |
|
||||
|---|---|---|---|
|
||||
| stdio stdin | `resource.open("stdio","stdin",["read"])`, `resource.read`, `resource.close`; one run-scoped cursor | implemented, read-only | `resource_streams`, `p2_closure`, `tests/conformance` |
|
||||
| Execution Events v1 | `run/call --event-stream jsonl`; `--observe-variable`, `--observe-parameter`, `--observe-text-values` | implemented P0/P1 (post-beta); P2 memory metadata deferred; strict refuses the option | `execution_events` CLI, `observation` host/runtime, `execution_events_consumer.py` |
|
||||
| stdio stdout | `resource.open("stdio","stdout",["write"])`, `resource.write`, `resource.close`; separate output budget | implemented | `stdlib_bundle`, `print_routing`, `resource_streams` |
|
||||
| stdio stderr | `resource.open("stdio","stderr",["write"])`; separate from stdout and CLI diagnostics | implemented | `resource_streams`, `stdlib_product` |
|
||||
| project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` |
|
||||
| project file write | `resource.open("file", path, ["write"])`; buffers until `close`, never flush-on-drop | implemented, project mode | `resource_streams`, `stdlib_product` |
|
||||
| `std:fs/file` | `读文本/写文本/复制文件/存在/元数据/列出目录/创建目录/删除/重命名/追加文本/读取片段/遍历` over `resource.*`; bounded at 8 MiB | implemented; no watch/binary offset read | `stdlib_product` |
|
||||
| `resource.request` | `resource.request("fs.exists|metadata|list|mkdir|remove|rename", paths)`; project mode, grant-checked, recoverable fs Result | implemented `fs.*`; no seek/append/watch | `resource_streams`, `stdlib_product` |
|
||||
| `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` |
|
||||
| core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
|
||||
| `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
|
||||
| Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); third-party heading annotations are **Proposed** metadata only, Analysis v2 unchanged (H-05/H-07) | core mode: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` |
|
||||
| Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` |
|
||||
| `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` |
|
||||
| `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` |
|
||||
| `std:path` | `path.连接/文件名/目录名/扩展名/规范/是否绝对`; lexical only | implemented (no I/O) | `stdlib_product` |
|
||||
|
||||
@@ -21,8 +21,11 @@ input and evidence. It is not a second running-status page.
|
||||
|---|---|---|
|
||||
| [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. |
|
||||
| [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002. |
|
||||
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Adopted and implemented (P0/P1)** | Typed host observation, Execution Events v1 NDJSON, frame identity, selected bounded values; P2 memory metadata remains deferred. |
|
||||
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
|
||||
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
|
||||
| RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. |
|
||||
| [RFC-GPL-0004 stable core review](https://git.cflmy.cn/cflmy/marqdo-cli/issues/4) | **Boundary adopted; protocol proposals open** | ADR-0064 records core review and a mandatory external gate. ADR-0065 and ADR-0066 propose independent Resource Control and Task work. |
|
||||
|
||||
The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
||||
`../STATUS.md`; the RFC text itself never proves that code exists.
|
||||
@@ -65,6 +68,14 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
||||
| gzip compression operations | [0049](../adr/0049-compression-resource-operations.md) | Accepted (bounded byte-list gzip) |
|
||||
| Host regex extension | [0050](../adr/0050-host-regex-extension.md) | Accepted (project-mode groups/alternation/captures) |
|
||||
| Byte-exact HTTP framing | [0051](../adr/0051-byte-exact-http-framing.md) | Accepted (byte-list HTTP/1.1) |
|
||||
| Runtime observability / Execution Events v1 | [0059](../adr/0059-runtime-observability-and-execution-events.md) | Accepted and implemented (P0/P1); memory metadata P2 deferred |
|
||||
| Core modes and heading annotations | [0060](../adr/0060-heading-modes-and-extensible-annotations.md) | Core modes implemented; Heading Annotations v1 **Proposed/not implemented** (target 3.1) |
|
||||
| Detach domain math kernel | [0061](../adr/0061-detach-domain-math-kernel-from-core.md) | Accepted and implemented; `math.*` removed, pure package + ABI backend |
|
||||
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
|
||||
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
|
||||
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
|
||||
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
|
||||
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
|
||||
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
||||
|
||||
## Evidence and status
|
||||
|
||||
@@ -0,0 +1,814 @@
|
||||
# RFC-OBS-0001: Runtime observability and real-time execution events
|
||||
|
||||
> **Status:** Accepted and implemented at the level recorded in
|
||||
> [`docs/STATUS.md`](../STATUS.md); this file is the frozen design input.
|
||||
> The normative protocol contract is
|
||||
> [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md).
|
||||
>
|
||||
> **Source:** issue `#1` of `cflmy/marqdo-cli`, filed 2026-11-22 against
|
||||
> `master@eeea01d672c07b6be7d6444031d1619309dc88ab`. It is reproduced here so
|
||||
> the design is reviewable without the issue tracker. Where this document and
|
||||
> `spec/execution-events-v1.md` disagree on the wire format, the spec is
|
||||
> normative.
|
||||
|
||||
---
|
||||
|
||||
# RFC-OBS-0001:Marqdo 3.x 运行时可观测性与实时执行事件协议
|
||||
|
||||
> **建议 Issue 标题**:`[RFC][P0/P1] Runtime Observability & Execution Events v1:实时输出、调用帧、可选变量观测和外部工具解耦`
|
||||
>
|
||||
> **状态**:历史设计输入;实现范围与证据以 [`docs/STATUS.md`](../STATUS.md)
|
||||
> 和 [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md) 为准。
|
||||
> 本文中的 `PROPOSED` 命名保留为设计决策记录,不再表示“未实现”。
|
||||
>
|
||||
> **目标仓库**:[`cflmy/marqdo-cli`](https://github.com/cflmy/marqdo-cli);旧产品 [`cflmy/marqdo`](https://github.com/cflmy/marqdo) 只用作历史参照,不能作为 3.x 的语义或 API 依据。
|
||||
>
|
||||
> **源码审查基线**:`master@eeea01d672c07b6be7d6444031d1619309dc88ab`(2026-11-22)。已发布基线:`v3.0.0-beta.1@2c7c4f31e7a388d3fcfa717a77067e696ed13854`。
|
||||
>
|
||||
> **读者**:CLI、Runtime、Host、View、Agent、Knowledge、Prove、IDE、第三方扩展库开发者。**本文自足;无需阅读任何历史对话**。文中明确标出的 `spec/` 和 `docs/` 是实际开发时必须共同更新的仓库文件,而非理解本文的前置条件。
|
||||
>
|
||||
> **核心目标**:使外部仓库仅使用**发布版 `marqdo` 二进制 + 公开版本化协议**即可实时获取计算输出和经授权的运行观测信息,不重编译 CLI、不链接其私有 crate、不实现第二套解释器。
|
||||
|
||||
---
|
||||
|
||||
## 0. 决策摘要(先读此节即可确定工作范围)
|
||||
|
||||
本 RFC 作出以下架构决策:
|
||||
|
||||
1. **需要修改 CLI 的通用观测基础设施**,不是为 `marqdo-view` 加专用 API。`run/call` 可选输出 **Execution Events v1**;`check`、`inspect` 等静态命令仍绝不执行。
|
||||
2. **CLI → 外部工具用单向 NDJSON/JSON Lines 流**;`marqdo-view` 后端接收 JSONL 并转换为浏览器 **SSE**。CLI 不实现 HTTP、SSE、WebSocket、浏览器会话或 Token/Agent 专用协议。
|
||||
3. **Trace v2 保持兼容**:不改变 `marqdo.trace` `schema_version:2` 的既有字段语义,不在默认 Trace 中添加参数、变量值、内存字节。实时协议具有独立 Schema、独立版本与独立预算。
|
||||
4. **优先实现实时 stdout/stderr 和任务生命周期**;紧接着实现可靠的调用实例标识、分支/循环事件;之后才实现**显式授权、精确选择且有界**的变量/参数值观测。
|
||||
5. **内存统计与写入元数据可以增量实现**,但本 RFC 不引入原始内存读取、任意地址快照、断点、单步、时间旅行和 Jupyter 式持久内核。它们属于以后独立的 Debug Protocol RFC。
|
||||
6. **观测默认关闭且不改变语言含义、执行结果、权限判定与预算**;除了有定义的输出背压/观测开销外,不允许将“启用观测”变成改变分支或修复运行错误的行为。
|
||||
7. 外部开发者的主验证方式是**冻结 CLI 二进制后的黑盒消费者测试**。View、Agent 和第三方消费者使用相同协议,不得出现 `if consumer == view` 一类特殊分支。
|
||||
|
||||
### 0.1 优先级定义
|
||||
|
||||
| 优先级 | 内容 | 对发布的影响 |
|
||||
|---|---|---|
|
||||
| **P0 / OBS-01~03** | 协议、观测边界、实时 stdout/stderr、终态、`run/call` JSONL 模式、黑盒验证 | 建议在下一个 3.x Beta 实施;对交互 View/Agent 的价值最高 |
|
||||
| **P1 / OBS-04~05** | 调用实例及父子关系、变量写入元数据、**显式**参数/变量值观测、源位置关联 | 建议稳定 3.x 前完成并验证;可拆分提交 |
|
||||
| **P2 / OBS-06** | 内存区域/预算统计及变更元数据、采样、性能优化 | 可以放到后续 3.x;禁止牵连 P0 |
|
||||
| **非目标** | 通用调试器、内存转储、逐指令暂停、SSE server、UI、AI Token 专用协议 | 不得为了本 Issue 一并开发 |
|
||||
|
||||
`P0/P1/P2` 代表项目规划优先级,不等同于当前仓库已有的 CI 门禁编号。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景:为什么现在必须补齐观测边界
|
||||
|
||||
Marqdo 3.x 把 Markdown 源、语言映射、IR、独立解释执行、Capability Host 及第三方工具协议分开了。`.mq.md` 的 H2 `@exec` 函数可以由 `marqdo run/call` 执行;外部 `marqdo-view`、`marqdo-knowledge`、`marqdo-prove`、Agent、IDE 则应当通过公开协议消费静态/动态信息。
|
||||
|
||||
已公开的两类机器可读信息是:
|
||||
|
||||
- **Analysis v2**:`marqdo check index.mq.md --emit analysis.json`。它描述模块、函数、语句结构、引用、代码资源、UTF-8 源码区间及静态诊断;**不执行**。
|
||||
- **Trace v2**:`marqdo run/call ... --trace-file trace.json`。它记录 `call.enter`、`call.exit`、`return`、`branch.eval`、`loop.iteration`、`effect` 及可能的截断事件;在运行结束时原子写入,**不包含调用实参、秘密、句柄或文件内容**。
|
||||
|
||||
CLI 还提供 `run/call --json`,但它在执行结束后一次性打印返回值、捕获的 stdout/stderr、错误等 JSON。以上能力能支持静态阅读及事后执行展示,却无法让外部工具在一个长时间运行的任务中即时看到输出,也不足以恢复多次/递归调用的完整调用实例与局部变量变化。
|
||||
|
||||
### 1.1 具体用户场景
|
||||
|
||||
- **View**:用户在文档旁点击“调用函数”,希望实时看到正常程序输出,并在完成后把调用、分支和返回结果关联至原文;不希望 View 内置第二个 Marqdo 解释器。
|
||||
- **Agent/SKILL**:需要以低延迟消费长任务的阶段性输出,得知任务是否仍执行,并能中止已无必要的工作。
|
||||
- **科研/计算工具**:需要计算进度与调用轨迹,之后依据源版本比对结果,不能等数分钟后才一次性获得日志。
|
||||
- **IDE**:需要知道某次函数调用、某个赋值事件属于哪个运行帧;当前仅有函数标识、没有稳定的“调用实例”身份。
|
||||
- **Knowledge/Prove**:可能用运行事实生成经验记录或反例,但必须区分“运行中观察到”和“通用证明成立”。**不为这两类工具把推理/证明逻辑塞进 CLI。**
|
||||
|
||||
### 1.2 仅把 Trace 文件边写边读为什么不够
|
||||
|
||||
现有 Trace v2 是**完整记录文件协议**,由 CLI 在运行结束时原子发布;其协议承诺了安全摘要和容量规则。把它改成一边执行一边追加 JSON,不但会破坏现有消费者对完整文件的假设,还不能自然支持实时 stdout/stderr、执行前错误、管道背压和“主动订阅但不保存文件”的工具。因此需要一个**并存而非取代**的事件传输协议。
|
||||
|
||||
### 1.3 不实现这些能力会造成什么长期成本
|
||||
|
||||
不增加公共观测协议,独立工具将被迫采取以下错误方案:解析面向人的终端日志、读取私有 Host 结构、在 View 中重写解释器、从 Trace 中猜测变量值、为了一个工具额外改一条 CLI 私有接口。它们都会使 3.0 的仓库解耦退化。因此本 Issue 的成功不是“View 看起来会动”,而是“任意消费者使用一个稳定的观测接口都能做同类工作”。
|
||||
|
||||
---
|
||||
|
||||
## 2. 已核实的现状与缺口(EXISTING,不是提案)
|
||||
|
||||
| 当前源码/规范 | 已有行为 | 缺口/注意事项 |
|
||||
|---|---|---|
|
||||
| `crates/marqdo-runtime/src/interpreter.rs` `call_function` / `bind_args` | 调用期间有带 `locals` 的 `Frame`;`call.enter` / `call.exit` 已记录 | 事件只有函数身份、尚无每次调用的 `frame_id`/`parent_frame_id`;值留在内部 |
|
||||
| 同文件 `exec_stmts_inner` | 成功赋值写入 `frame.locals`;记录返回类型、分支真假、循环 continue/exit | 不发布每次赋值事件/值;不能用最终变量值倒填历史语句 |
|
||||
| `crates/marqdo-runtime/src/memory.rs` `MemoryStore` | 持有区域和提交字节统计;`MemoryHandle` 非原始主机指针 | 不存在公开的通用运行时内存观测协议;不应导出原始字节 |
|
||||
| `crates/marqdo-host/src/host.rs` `Host`、`StdHost` | Host 处理副作用;`output`、`stderr` 为缓冲字节数组;`resource_write` 对 stdio 写入缓冲 | 想获得**真实的**增量 stdout/stderr 必须在 Host 输出路径上挂钩,而不是事后拆分 |
|
||||
| `crates/marqdo-host/src/trace.rs` | `SemanticEvent` 含 `seq/kind/function_id/module_id/span/detail`;Host 有 `TraceBudget` | 没有公共调用实例 ID;现有安全摘要协议有意不提供参数值 |
|
||||
| `crates/cli/src/commands/run.rs` | `run/call --json` 完成后组合 stdout/stderr/返回值;`--trace-file` 结束时调用写入 | 不提供实时事件通道;`--json` 不可和流式协议混作同一 stdout |
|
||||
| `crates/cli/src/trace.rs` | Trace v2 原子写完整文档,并与 Analysis digest 关联 | 修改已有 v2 的隐私/完整性含义是破坏性行为 |
|
||||
| `spec/analysis-v2.md`、`spec/trace-v2.md` | 公共版本化静态/动态合同 | 新增协议必须独立命名/版本,说明如何与其对齐 |
|
||||
| `spec/tool-v1.md`、`docs/developers/tools.md` | 独立工具通过 `MARQDO_BIN` 调用已发布 CLI,不依赖私有 Rust 类型 | 新协议需要按工具协议方式向外公开与声明兼容性 |
|
||||
|
||||
**证据基线**:上述结论仅依据已检查的 SHA;后续实现前必须重新确认 HEAD,不能假定未检查的后续提交仍维持同样行为。文中设计决策均标记为 **PROPOSED**。当前发布版**没有** `--event-stream`、`--observe-values` 或 `marqdo.execution-events`。
|
||||
|
||||
### 2.1 必须保留的既有保证
|
||||
|
||||
1. `check`/`inspect` 不执行;`run`/`call` 通过统一预备流程和能力 Host 执行。
|
||||
2. `--json` 仍是**完整、非混杂**的单次执行结果;不能把 JSONL 事件插入其 stdout。
|
||||
3. `--trace-file` 仍在完成后形成符合 Trace v2 的完整 JSON,含合法的 `source.analysis_digest`。
|
||||
4. `pure/project/strict` 及插件、Foreign、Provider 的授权规则保持原样;观测开关不是额外 capability grant,也不是绕过安全策略的方法。
|
||||
5. 默认 Trace 继续不包含参数值、原始内存、敏感数据。即使 Events v1 未来可显式输出选定值,也不意味着 Trace v2 变成高敏快照。
|
||||
6. 语言 `.mq.md` 的 `@exec/@knowledge`、语句载体和控制流映射**不修改**。这是运行时观测项目,不是 RFC-LANG 重构。
|
||||
|
||||
---
|
||||
|
||||
## 3. 最终架构与职责边界(PROPOSED)
|
||||
|
||||
```text
|
||||
marqdo-cli (唯一运行时)
|
||||
.mq.md ──> Frontend / PreparedProgram ──> Runtime Interpreter
|
||||
│ │
|
||||
│ 运行中事件(借用数据)
|
||||
│ ▼
|
||||
│ Observation Facade
|
||||
│ ┌─────────┴──────────┐
|
||||
│ Metadata/Frame Value Policy
|
||||
│ └─────────┬──────────┘
|
||||
│ ▼
|
||||
│ Event Dispatcher
|
||||
│ ┌──────────┼───────────┐
|
||||
▼ ▼ ▼ ▼
|
||||
Analysis v2 JSONL Sink Trace v2 Null Sink
|
||||
(静态文件) (实时stdout) (已有完整文件) (默认无开销)
|
||||
│
|
||||
┌─────────────────┼──────────────────┐
|
||||
▼ ▼ ▼
|
||||
marqdo-view Agent / SKILL 其他 CLI Tool
|
||||
│
|
||||
转换为 HTTP SSE
|
||||
│
|
||||
浏览器
|
||||
```
|
||||
|
||||
### 3.1 模块划分:哪里能增加代码、哪里不该增加
|
||||
|
||||
**Runtime (`crates/marqdo-runtime`)**
|
||||
- 仍是计算、函数调用、局部变量赋值、内存读写的**唯一语义来源**。
|
||||
- 在已经成功完成的状态变化边界提供可选观测钩子;不能仅为输出“赋值事件”再次执行表达式。
|
||||
- 函数调用实例 ID 在进入帧时生成;递归/异常退出也必须配对和归属正确。
|
||||
- 不认识 View、HTTP、SSE、JSONL、HTML,也不负责隐藏/展示参数输入框。
|
||||
|
||||
**Host (`crates/marqdo-host`)**
|
||||
- 继续作为所有被支持的 stdout/stderr 和副作用的汇聚位置。
|
||||
- 定义**内部 typed observation interface**、可选 `EventSink` 和受预算约束的分发;Host 接收 Runtime 提交的纯语义事件,再根据策略编码成对外数据。
|
||||
- 不为了观测对插件/Foreign/Provider 放宽权限,也不自动把外部子进程的 stdout 当成 Marqdo 程序的受控 stdout。
|
||||
- 编码/写出时禁止在全局锁下等待一个不可信外部消费者;先解决锁与背压的线程安全边界。
|
||||
|
||||
**CLI (`crates/cli`)**
|
||||
- 只负责选项解析、协议版本协商、观测配置、JSONL writer、稳定错误映射、退出状态和原有 Trace 文件写入。
|
||||
- `--event-stream jsonl` 使用**专有机器输出通道(CLI stdout)**;程序 stdout/stderr 是事件,不能再原样写到同一个 stdout。
|
||||
- CLI 没有 HTTP 监听、浏览器 session、SSE 编码、View 专用功能分支。
|
||||
|
||||
**独立 `marqdo-view`**
|
||||
- 使用 Tool Protocol v1 的 `MARQDO_BIN` 启动 CLI 子进程,消费 JSONL。
|
||||
- View Server 负责 `POST` 发起、通过 SSE 转发并支持取消;不改变事件语义,不补造内部变量值,不读取 CLI 私有数据。
|
||||
- View 仍默认只读;只有用户显式确认才执行。View 的 SSE 和 CLI 的 JSONL **属于不同传输层**。
|
||||
|
||||
### 3.2 是否需要新 Rust crate?
|
||||
|
||||
**首选不新增**只为观测而存在的多层框架或十几个 crate。将类型定义放在 `marqdo-host` 的有界模块(例如 `observe/{mod.rs,event.rs,policy.rs,sink.rs}`),在 `marqdo-runtime` 以轻量 Host 方法或明确 trait 传入只读事件,在 CLI 内维护 `execution_events.rs`(公共 JSONL 序列化)。
|
||||
|
||||
如果编译期依赖图迫使 Host↔Runtime 环依赖,则可建立**一个**只含 `Event`/`Policy`/`Span`、无 IO/CLI 的 `marqdo-observe` 内部基础 crate;必须附 ADR 说明为什么现有边界不足。**不得因为“未来也许要 IDE”先创建通用插件总线、会话管理器或所有业务通用 EventBus。**
|
||||
|
||||
### 3.3 三种不同对象,不能混淆
|
||||
|
||||
- `RuntimeEvent`:内部 typed 事件,允许只读借用 `Value`、`Span` 等,以便延迟序列化。不是公共协议。
|
||||
- `ExecutionEventV1`:经过过滤/预算/转码后写到 stdout 的**公开**单行 JSON 对象。是第三方消费者所依赖的协议。
|
||||
- `TraceV2`:事后落盘、独立的公共证据对象。运行时可复用部分事件来源,但**不承诺每一种 RuntimeEvent 都写进 Trace v2**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 外部协议:Execution Events v1(PROPOSED)
|
||||
|
||||
### 4.1 命名和传输
|
||||
|
||||
建议协议 ID:`schema = "marqdo.execution-events"`;主版本:`schema_version = 1`;媒体类型文档可记为 `application/x-ndjson`。每行是一个完整 UTF-8 JSON 对象,以 `\n` 终止;一条事件内不得出现未转义换行;事件超过大小限额必须拒绝/裁剪并明确标记。
|
||||
|
||||
提议 CLI 使用:
|
||||
|
||||
```bash
|
||||
# 下列命令是提议 API,当前 3.0.0-beta.1 不支持
|
||||
marqdo run index.mq.md --event-stream jsonl
|
||||
marqdo call index.mq.md main --arg n=5 --event-stream jsonl
|
||||
marqdo call index.mq.md main --arg n=5 \
|
||||
--event-stream jsonl --trace-file trace.json
|
||||
```
|
||||
|
||||
选项决策:
|
||||
- `--event-stream jsonl` **仅** `run/call` 可用,表示整个 stdout 都属于 JSONL;普通程序输出必须封装成事件。
|
||||
- `--event-stream` 与已有 `--json` **互斥**,不混合两种 JSON 输出;`--trace-file` 可共存(保留 Trace v2 原子语义)。
|
||||
- 普通人类可读 `run/call` 不启用事件、行为和 stdout 字节保持不变。
|
||||
- `check`、`inspect`、`fmt`、`tool` 等命令不接收该选项;不将静态检查伪装成运行。
|
||||
- CLI 选项错误(clap 在命令分发前拒绝)仍走普通 stderr 与非零退出;一旦进入事件模式且成功初始化 writer,预备/授权错误须使用结构化 `run.rejected` 终态,**不输出半行 JSON 或人类可读文字到 stdout**。
|
||||
|
||||
### 4.2 公共事件信封(提议)
|
||||
|
||||
所有正常输出的事件必须包含:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "marqdo.execution-events",
|
||||
"schema_version": 1,
|
||||
"run_id": "run-opaque-01",
|
||||
"seq": 2,
|
||||
"kind": "call.enter",
|
||||
"payload": {}
|
||||
}
|
||||
```
|
||||
|
||||
- `run_id`:CLI 生成的**本次运行**不透明字符串;不是 OS PID,不得被误用作跨机器持久身份。
|
||||
- `seq`:从 0 开始的全局、严格递增整数;一个运行内不重复、不倒退;由统一分发者赋值。语义事件与 stdout/stderr 的**可观察**顺序按进入该分发者的顺序定义,不能保证其他操作系统子进程内独立流的真实物理先后顺序。
|
||||
- `kind`:稳定、带命名空间的事件名;未来新事件种类是**加法扩展**。消费者可以忽略未知 `kind`,但必须拒绝未知 `schema_version` major。
|
||||
- `payload`:与 kind 对应的有界对象。每类的 required 字段由 JSON Schema 约束;未知可选字段可以忽略。
|
||||
- 为避免无关冗余,不强制每条事件重复完整 `project` 元信息;建立时通过 `stream.opened` 提供协议、生产者和观测配置;**成功准备项目后**,由 `run.started` 提供 `source` 身份和摘要;后续事件可带 `module_id`、`span`。预备失败时 `run.rejected` 可没有 `source`。
|
||||
|
||||
### 4.3 最小公共事件表
|
||||
|
||||
| 事件 | 何时发出 | 必需信息 | 观测级别 |
|
||||
|---|---|---|---|
|
||||
| `stream.opened` | JSONL writer 成功初始化,**第 0 条** | `producer`、`protocol`、预算、观测范围(无须已有 `source`) | base |
|
||||
| `run.started` | 校验、授权通过,解释器准备真正执行 | `entry`、`mode`、`source`(`root_id` / `analysis_digest`)、`started`(仅诊断用途) | base |
|
||||
| `stdout.chunk` | Host 真正接受一段程序 stdout | `encoding`、`data_base64`、`byte_count` | base |
|
||||
| `stderr.chunk` | Host 真正接受一段程序 stderr | 同上 | base |
|
||||
| `call.enter` | 参数已成功绑定、创建本次函数帧 | `frame_id`、`parent_frame_id`、`function_id`、`module_id`、`span` | structural |
|
||||
| `call.exit` | 某次已进入的函数帧结束(含失败) | `frame_id`、`status`、`module_id`、`span` | structural |
|
||||
| `return` | return 语句实际执行完 | `frame_id`、`value_type`、`module_id`、`span` | structural |
|
||||
| `branch.eval` | 实际求值某条条件 | `frame_id`、`result`、`module_id`、`span` | structural |
|
||||
| `loop.iteration` | 条件实际求值完成 | `frame_id`、`decision`、`module_id`、`span` | structural |
|
||||
| `effect` | Host 已完成受控副作用尝试 | `operation`、`result_code`、`module_id`、`span` | structural |
|
||||
| `variable.assigned` | 成功提交局部变量赋值 | `frame_id`、`name`、`value_type`、`module_id`、`span` | selected values / metadata |
|
||||
| `observation.truncated` | 仅观察事件达预算 | `reason`、`limit`、`written`、`dropped`(若已知) | any |
|
||||
| `run.completed` | 正常成功退出 | `status:ok`、`value`(公开 wire 值,遵循既有返回规则) | base;终态 |
|
||||
| `run.failed` | 已开始执行但运行失败 | `status:error`、稳定 `error.code`、安全消息 | base;终态 |
|
||||
| `run.rejected` | 进入 event mode 后、运行前校验/授权拒绝 | 结构化错误及阶段 | base;终态 |
|
||||
|
||||
**状态一致性**:进入 event mode 且 writer 存活时,协议应有恰好一条 `stream.opened`、最多一条 `run.started`,以及恰好一条终态 `run.completed/failed/rejected`。对于 OS 强制终止、进程崩溃、SIGKILL、断管,此保证不成立;消费者必须按“未收到终态 + 进程非正常退出/EOF”标记为 **incomplete / unknown**,不能补造成功事件。
|
||||
|
||||
### 4.4 输出数据的字节安全
|
||||
|
||||
stdout/stderr 可能包含无效 UTF-8、跨写操作分裂的多字节字符、NUL 和二进制数据。**规范载荷统一使用 `data_base64`,按字节保真;不把 `String::from_utf8_lossy` 当作协议原始数据。** UI 需要人类文本时自行使用增量 UTF-8 解码,并定义无效字节替换或十六进制展示策略。
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "marqdo.execution-events",
|
||||
"schema_version": 1,
|
||||
"run_id": "r1",
|
||||
"seq": 2,
|
||||
"kind": "stdout.chunk",
|
||||
"payload": {"encoding":"base64","data_base64":"5byA5aeL5paH5pysCg==","byte_count":13}
|
||||
}
|
||||
```
|
||||
|
||||
上面的 `data_base64` 对应 UTF-8 字符串 `开始文本\n`(13 字节);实现时必须逐字节回读验证,`byte_count` 必须与解码后长度一致。`stderr.chunk` 同理。
|
||||
|
||||
`stdout.chunk`/`stderr.chunk` 是 **Marqdo Host 接受的程序流**;第三方插件或外语内核若绕过 Host 直接写 OS fd,其输出可能逃逸或与事件流混杂,属于安全/完整性风险,必须在 OBS-03 中测试并禁止。对无法截获的外部 stdout/stderr,**要么隔离/重定向并单独标注来源,要么禁止该组合使用 event mode**,不能默默将其解释为可信程序 stdout。
|
||||
|
||||
### 4.5 完整的最小示例
|
||||
|
||||
```jsonl
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.x"},"observation":{"level":"structural","values":false}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"pure","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:<digest>"}}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","data_base64":"T0sK","byte_count":3}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":null}}
|
||||
{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":5,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","value":"10"}}}
|
||||
```
|
||||
|
||||
示例中的源版本、`source` 内容、`value` wire 格式应以最终协议 Schema 与实际 `marqdo_value::to_wire` 的一致性测试为准;占位的 `<digest>` 不是有效 SHA-256,**不能直接作为 JSON Schema 测试 fixture**。
|
||||
|
||||
### 4.6 与 Analysis v2 和 Trace v2 的一致性
|
||||
|
||||
`run.started.payload.source` 至少包含:`root_id`、`analysis_digest`;若需要还可包含锁文件 digest、入口 module id。`stream.opened` 在预备之前发出,因此**不得要求它携带尚未计算的 source**;预备失败时的 `run.rejected` 同样不要求携带 source。`analysis_digest` **必须等于与当前执行相同 prepare/projection 配置下 Analysis v2 文件原始字节**的 SHA-256,而不是随手重新序列化 JSON 后的摘要。源变化后必须标记旧事件为 stale。
|
||||
|
||||
- 建议在现有 Trace v2 的 `run.id` 字符串字段中重用本次 CLI 生成的 `run_id`;**不新增字段、不改变其类型**。如果现有内部生成路径不同,应在 CLI composition root 统一创建 run ID,再分别交给两种 writer。
|
||||
- Trace v2 仍在执行完成后原子生成;JSONL 可以在运行中消费。两者只共享运行身份、来源摘要与可信事件来源,**不要求事件逐条同构**。
|
||||
- 需要识别调用实例的是 Events v1;不能宣称 Trace v2 已经具有 frame_id。
|
||||
- 消费者拒绝未知 Schema major、来源不匹配、非法 span 和无终态事件,不能误把旧事件渲染到新源码上。
|
||||
|
||||
### 4.7 版本与兼容规则
|
||||
|
||||
采用独立协议主版本 **v1**,不与 CLI 产品版本或 Trace v2 混淆。增加可选事件、可选字段可在 v1 允许;改变必填字段含义、事件排序语义、脱敏承诺、源摘要定义或将私密数据改为默认公开,必须发新 major。`--help` 和 `docs/developers/compatibility.md` 应列出该协议、支持范围和 feature flags;Tool Protocol v1 的 `tool.json` 目前只协商 Analysis/Trace,**不能悄悄加入一个未经 Tool v1 规范确认的 `events` 字段并当作自动协商**。初期工具通过调用 `MARQDO_BIN` 的已定义 `--event-stream jsonl` 并核对 `stream.opened` 协商协议;若将来扩展 `tool.json.compatibility`,需单独更新 Tool Protocol 的 Schema、实现和测试。
|
||||
|
||||
---
|
||||
|
||||
## 5. 内部事件机制:既要实时,又不能重建 EventBus
|
||||
|
||||
### 5.1 最小类型和调用方向
|
||||
|
||||
建议实现可替换的内部接口(伪 Rust,具体命名可在 PR 中调整,但语义不可改变):
|
||||
|
||||
```rust
|
||||
// 内部接口;不是公共 SDK。借用 Value 以避免无谓 clone/序列化。
|
||||
trait ObservationSink {
|
||||
fn emit(&mut self, event: RuntimeEventRef<'_>) -> Result<(), ObservationError>;
|
||||
}
|
||||
|
||||
struct ObservationConfig {
|
||||
enabled: bool,
|
||||
structural: bool,
|
||||
selected_variables: Vec<String>, // 精确名称选择,不自动全量输出
|
||||
selected_parameters: Vec<String>,
|
||||
allow_text_values: bool,
|
||||
max_observation_events: u64,
|
||||
max_observation_bytes: u64,
|
||||
max_value_bytes: usize,
|
||||
}
|
||||
|
||||
// RuntimeEventRef 包含 typed 事件、源身份及可选 &Value,
|
||||
// 绝不将所有 Frame.locals 或整个 MemoryStore 交给 sink。
|
||||
```
|
||||
|
||||
运行正常流程:
|
||||
|
||||
1. CLI 根据选项创建 `ObservationConfig`;无观测选项时使用 **Null/None sink**。
|
||||
2. Runtime/Host 在已有状态提交点发出轻量 typed 通知;**先完成原始语义**,再形成不会影响业务结果的只读观测资料。
|
||||
3. 分发层先执行级别、变量名精确选择、数据敏感度、事件/字节预算判断。
|
||||
4. 通过的事件才做序列化并同步写入 CLI 所持有的**独立协议 stdout writer**。
|
||||
5. `--trace-file` 仍走现有 Trace Writer;内部可以共享事件创建,但不能因为打开 JSONL 就自动在 Trace v2 输出变量值。
|
||||
|
||||
如果已有 `Host::record_semantic(...)` 不返回错误,不能据此把 IO 异常吞掉。开发者必须采取以下两者之一:① 新增明确可传播的 fallible emission 方法并在解释器安全点传播错误;② 在 sink 保存错误,解释器的下一次预算/控制边界与最终返回路径强制检查。**不得让 JSONL 管道已损坏而 CLI 继续无限执行有副作用的程序。**
|
||||
|
||||
### 5.2 输出产生点与正确的实时性
|
||||
|
||||
真正的实时流必须在 `StdHost::resource_write` 记录 stdout/stderr 的同一条授权/预算路径上送出 `stdout.chunk` / `stderr.chunk`。**严禁**把 `take_output()` 得到的最终字符串按行切碎,再声称“实时”。
|
||||
|
||||
行为要求:
|
||||
|
||||
- 写出的字节恰好等于 Host 已接受的字节;如果 Host 的输出预算拒绝一次写入,则不能先推送该未提交字节。
|
||||
- 原有 `--max-output` 语义仍有效;stream 不能绕开 Budget。
|
||||
- 行缓冲只能影响吞吐,不能把短小增量积累到运行结束;每次成功的 Host 程序输出写入应在合理有界延迟内可读取(见验收)。
|
||||
- 输出事件不必等待 Trace/Analysis 文件,也不要求所有扩展原生支持流。Foreign/Plugin 调用若本身阻塞直到结果返回,不得宣称内核可以神奇地实现中间 Token 流。
|
||||
- 允许有界 chunk 合并,但顺序和字节精确性必须保持;不同设备返回的字节不能冒充主程序 stdout。
|
||||
|
||||
### 5.3 预算、背压与失败策略
|
||||
|
||||
**需要分别管理三类资源**:
|
||||
|
||||
1. **原有执行预算**:`--fuel`、`--timeout`、`--max-output` 等。观测不得扩权或改变其含义。
|
||||
2. **可丢弃的结构化观测预算**:例如建议 `100_000` 条、`16 MiB`,达到上限后只停止**非关键结构事件**,发一条 `observation.truncated`,继续运行和真实 stdout/stderr。值大小默认限制(例如 `256 B`),未观察的值不序列化;常规执行不分配大量事件缓冲。
|
||||
3. **不可静默丢弃的关键事件**:`stream.opened`、`run.started`、stdout/stderr、最终终态。它们不受“结构事件条数”预算截断;stdout/stderr 仍受原有输出预算。若其传输不可继续,必须明确导致**观测传输失败**,不能伪造完整成功流。
|
||||
|
||||
背压策略:**首版优先使用有界、同步写入**;下游不读时可使执行等待,属于可解释的 IO 背压,而不是无界增加内存。避免新建全局异步队列和大量线程。若后续引入专用有界队列,必须分别定义关键输出阻塞与非关键结构事件截断的策略;不能静默丢失 stdout 字节。
|
||||
|
||||
断管/写失败:JSONL sink 写失败需使 `run/call` 返回非零;在可以恢复的条件下打印仅到 OS stderr 的 `observe.transport_failed` 诊断,不得向坏掉的 stdout 再写半条 JSON。**对于此前已经发生的副作用不能声称回滚**,消费者记录为“观察失败、运行状态可能不完整”;强制取消或 SIGKILL 同样不能凭空补完终态。
|
||||
|
||||
### 5.4 输出顺序和线程安全
|
||||
|
||||
- 同一运行使用一个分发序号源,EventSink 写入过程对外形成全序。
|
||||
- 调用帧栈、局部变量数据仅在正确的解释器安全点采样;禁止后台线程无同步地遍历 `Frame.locals`。
|
||||
- 插件/外语进程如果同时写流,必须使用经验证的 Host 接口或一个区分来源的受控转发器;不能让第三方 fd 原始输出污染 JSONL。
|
||||
- 不在持有 MemoryStore 内部互斥锁/全局运行状态锁时等待阻塞 IO;先形成有界摘要再执行发送。
|
||||
|
||||
---
|
||||
|
||||
## 6. 调用帧身份与结构化执行事件(P1)
|
||||
|
||||
### 6.1 需要 `frame_id` 的理由
|
||||
|
||||
同一个函数可以多次被调用、递归调用,两个分支/循环的源位置也可能相同。现有 `function_id` 只能说明**哪个函数**,不能说明**哪一次调用**。没有调用实例身份,外部 View 即使知道某条赋值发生过,也无法可靠附着到具体调用。
|
||||
|
||||
### 6.2 Frame identity 规则
|
||||
|
||||
- `frame_id`:本次运行内唯一、不透明、不可复用。建议 `f1, f2, ...` 或整型字符串;只用于展示和事件关联,不暴露内存指针。
|
||||
- `parent_frame_id`:顶层 `null`,其余指向进入当前函数时的直接调用者;必须存在或有明确表示“外部入口”的规则。
|
||||
- `function_id`:复用现有全限定函数标识和 module identity。
|
||||
- 在 `bind_args` 成功后进入新帧、发 `call.enter`;一旦进入帧,即使提前 return 或异常,也必须发对应 `call.exit`(若事件传输未截断/中断)。
|
||||
- 参数绑定失败时尚未进入函数帧:可以发 `call.bind_failed` 非终态摘要或由 `run.failed` 报告;**不能生成一个永远不会退出的虚假 frame**。
|
||||
- 每次 `return`、`branch.eval`、`loop.iteration`、`variable.assigned` 都带当前 `frame_id`,且源码区间属于声明的 module。
|
||||
- 调用序号与事件序号不同;不能拿 `seq` 代替 `frame_id`(一个帧有许多事件)。
|
||||
- 建议为实际循环增加 `iteration_index` 或唯一 loop occurrence 标识,但需要先明确是循环条件求值次数还是 body 执行次数,不能用模糊的次数误导 UI。第一阶段可维持逐次 `loop.iteration` 事件,不保证完整 iteration frame。
|
||||
|
||||
### 6.3 例子:递归与重复调用
|
||||
|
||||
`main -> f(2) -> f(1)`,然后 `main -> f(3)`,应产生三个不同的 f 调用实例。消费者能够由 `frame_id,parent_frame_id` 构造树;无论函数名是否重复、源位置是否相同,都不发生归属混淆。
|
||||
|
||||
### 6.4 同一函数遇到错误和提前 return
|
||||
|
||||
- 显式 `return` 时先形成 return 事件,再形成 `call.exit(status=return)`。
|
||||
- 抛运行错误时形成 `call.exit(status=<error-code>)`,再最终 `run.failed`;必要时沿栈逐帧退出,顺序和错误归属一致。
|
||||
- 观察项达到上限时可缺少结构化事件,消费者明确显示“部分调用轨迹”,不得重建不存在的调用帧。
|
||||
|
||||
---
|
||||
|
||||
## 7. 变量与参数值:必须“可选择且有界”,不是默认调试转储(P1)
|
||||
|
||||
### 7.1 先做元数据,后做具体值
|
||||
|
||||
变量赋值应在**实际成功提交**后发布元数据事件:变量名、类型、帧身份、准确源位置、是否发生写入等。不得重新计算 RHS,不得使用最终局部变量值填充历史赋值,更不能在失败的内存写入后伪造“已成功”。
|
||||
|
||||
```json
|
||||
{
|
||||
"schema":"marqdo.execution-events",
|
||||
"schema_version":1,
|
||||
"run_id":"r1",
|
||||
"seq":15,
|
||||
"kind":"variable.assigned",
|
||||
"payload":{
|
||||
"frame_id":"f2","name":"result","value_type":"int",
|
||||
"module_id":"root:demo@0.1.0::index.mq.md",
|
||||
"span":{"start":120,"end":141},
|
||||
"value_state":"not_requested"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 7.2 值观测授权模型
|
||||
|
||||
本 RFC **不**接受 `--dump-all-locals` 作为默认开发接口。建议提供下列显式参数(命名为拟议):
|
||||
|
||||
```bash
|
||||
# 都是拟议命令;首版可先只实现结构事件,再实现选定值
|
||||
marqdo call index.mq.md main --arg n=5 \
|
||||
--event-stream jsonl \
|
||||
--observe-variable result \
|
||||
--observe-parameter n \
|
||||
--observe-max-value-bytes 256
|
||||
```
|
||||
|
||||
具体契约:
|
||||
|
||||
1. 默认 `--event-stream` **只允许类型/状态**,不含任何实参或局部变量原始值。
|
||||
2. 用户必须显式列出允许观察的参数名/变量名;首版只接受**精确名称匹配**,不支持 `*`、正则、路径表达式或“全部变量”,以免范围失控。
|
||||
3. 可观测值类型在第一阶段仅允许简单标量:整数、浮点、布尔;**字符串 Text 默认不输出**,需要另一个明确的 `--observe-text-values` 同意选项。列表/Map/Table/Formula/Code、Memory、Resource、PluginHandle 默认仅记录类型与安全摘要,不自动递归展开。
|
||||
4. 观测值由同一个 `Value` 安全编码策略处理,不得使用 Rust `Debug`、随意序列化嵌套引用或打印 MemoryHandle 内部字段。
|
||||
5. 每个值有 `max_value_bytes`、截断和失败状态;将“值未请求”“被规则遮蔽”“超过限额”“类型不支持”分别表示为 `not_requested/redacted/truncated/unsupported`,不能都显示空字符串。
|
||||
6. 即使是 Int、Float、Bool 也可能表示敏感数据。观测值的权限意味着**由用户显式同意写入该输出通道**,协议不能承诺凭变量名自动正确识别秘密。
|
||||
7. 文档中明确指出:值观测降低数据机密性;CLI 允许的是开发者主动的调试泄露,View 不可默认勾选,更不能从项目 manifest 自动开启。
|
||||
8. 不在普通 Trace v2、普通 `--json` 的 effect trace 或 Analysis v2 中偷偷新增这些值。
|
||||
|
||||
### 7.3 `call.enter` 上的参数值
|
||||
|
||||
- 默认仅有 `function_id/frame_id` 等身份和可公开的参数签名;实际参数值不出现。
|
||||
- 通过 `--observe-parameter` 选择后,可单独附加 `parameter.observed` 事件,按相同脱敏/值类型/预算策略处理。
|
||||
- 函数绑定默认值也视为真实运行参数,但事件必须注明来源为 `provided/default`,不能把源码默认表达式误当做用户传参;不允许将第三方插件收到的所有原始请求自动拷贝到观测流。
|
||||
|
||||
### 7.4 对 View 的呈现原则
|
||||
|
||||
- 默认显示“变量 `result` 已赋值(Int)”,不显示 `result = ...` 的猜测值。
|
||||
- 获得明确观测值时显示“本次调用 f2 在源位置 x/y 写入 42”,并能切换 f1/f2。
|
||||
- 缺少值时显示“未请求/受保护”,而不是误导性的 `null/0/None`。
|
||||
- 不能把运行时观测值称为形式证明。
|
||||
|
||||
---
|
||||
|
||||
## 8. 内存观测:只做元数据,保留未来的 Debug Protocol(P2)
|
||||
|
||||
当前 `MemoryStore` 的页、容量、已提交字节及区域概念适合提供**非内容型指标**。建议以后允许以下只读事件:
|
||||
|
||||
| 事件 | 允许的内容 | 禁止内容 |
|
||||
|---|---|---|
|
||||
| `memory.region.created` | 本次运行内不透明区域 ID、逻辑大小、容量限制 | 操作系统地址、裸指针、初始内存字节 |
|
||||
| `memory.region.grown` | 旧/新提交字节数,是否成功 | 原始内存数据 |
|
||||
| `memory.region.written` | 区域 ID、偏移/长度、来源 span、操作结果 | 写入字节的内容 |
|
||||
| `memory.budget` | 总已提交字节数、区域数量、预算 | 进程地址空间映射 |
|
||||
|
||||
`MemoryHandle` 当前是带运行生命周期的内部能力,不应被事件流序列化为可在下一次调用使用的句柄。区域 ID 仅供同一次运行内展示,与 CLI 用户可操作的资源句柄无关。
|
||||
|
||||
**明确不开发**:随时从外部读取 MemoryStore、逐字节 dump、任意读写、设置断点、暂停线程、时间旅行。这些需要安全模型、快照一致性、会话协议与可重放语义,应另立 Debug Protocol RFC。
|
||||
|
||||
---
|
||||
|
||||
## 9. 安全、隐私与可信边界
|
||||
|
||||
### 9.1 威胁模型
|
||||
|
||||
至少考虑:不可信 `.mq.md`、不可信 Plugin/Provider/Foreign 子进程、恶意或慢速 JSONL 消费者、意外重定向到日志服务器、循环大量打印/写变量值、内存中的 Token/密码、跨源浏览器请求、源码变更产生的错位展示。
|
||||
|
||||
**本 RFC 不提供 OS 沙箱**。现有 `pure/project/strict` 能力与隔离承诺按照当前产品文档执行;Worker 是进程故障隔离,不等于对所有敌意扩展的 OS 级安全边界。观测模式不能改变安全级别、临时扩大权限或强制载入 Plugin。
|
||||
|
||||
### 9.2 强制约束
|
||||
|
||||
- 观测开关只改变**允许输出的信息**,不能授权网络、文件、进程、Foreign、Provider 或插件。
|
||||
- 观测输出与普通程序 stdout **严格分离**;stderr 中的诊断也不得偷偷泄露被隐藏的变量/密钥。
|
||||
- 用户有意识地打印的内容属于程序 stdout;该内容可能包含秘密,事件协议对此只保证字节保真、**不自动替用户脱敏 stdout**。
|
||||
- `Value` 观测默认关闭;不输出资源句柄、内存字节及未经明确允许的文本值。
|
||||
- 禁止将变量值记录到 CI artifacts、Issue、公开诊断中作为测试失败的默认附带信息。测试使用合成哨兵并断言其不出现。
|
||||
- 与外部扩展组合使用时,应确保其原始 fd 不污染 JSONL;不能保证该点时明确标记组合不支持并 fail-closed。
|
||||
- 不向浏览器直接暴露 CLI 机器管道:View Server 仅在用户明确运行后启动子进程并将受限事件转换为 SSE;其 HTTP 授权与 CSRF 防护属于 View 仓库,不要求 CLI 实现。
|
||||
|
||||
### 9.3 特殊模式与流输出边界
|
||||
|
||||
- 即使 `--mode pure`,读取 stdout 流/传事件的行为属于调用者对 CLI 进程 stdout 的消费,**不得扩大 Marqdo 程序本身的 capability grants**。
|
||||
- `strict` 模式依赖平台/隔离环境;若已支持进程 stdout 管道,事件流应经过同样的隔离 preflight 验证,不能绕过 strict;不支持时显式拒绝。
|
||||
- 若项目声明插件而 `pure/strict` 拒绝激活,则 event mode 也必须以相同原因拒绝,不能为了 UI 可观测性自动退回 project。
|
||||
|
||||
---
|
||||
|
||||
## 10. 执行生命周期与故障处理
|
||||
|
||||
```text
|
||||
CLI 参数解析
|
||||
│ ├─ 无效参数 → stderr + 非零(尚未进入事件协议)
|
||||
▼
|
||||
初始化 JSONL Writer → stream.opened(seq=0)
|
||||
▼
|
||||
准备项目 / 静态诊断 / 安全预检
|
||||
├─ 失败 → run.rejected + EOF + 非零
|
||||
▼
|
||||
run.started
|
||||
▼
|
||||
Runtime 真实执行
|
||||
├─ stdout/stderr → *.chunk(已提交输出)
|
||||
├─ call/branch/loop → structural(有界)
|
||||
├─ selected Value → observed(显式授权、有界)
|
||||
├─ Runtime 失败 → run.failed + EOF + 非零
|
||||
├─ 成功 → run.completed + EOF + 0
|
||||
└─ OS 强杀/断管/崩溃 → 可能无终态;消费者标 incomplete
|
||||
```
|
||||
|
||||
### 10.1 正确的终态和退出码
|
||||
|
||||
- `run.completed(status=ok)` 只表示解释器实际成功返回,不代表所有 stdout 已被浏览器消费;必须在关键输出**成功写入**协议通道后发出。
|
||||
- `run.failed` 的 `error.code` 应尽量复用现有稳定错误族,不在新协议中另创造一套语言错误分类。
|
||||
- `run.rejected` 区分 preflight/compilation/authorization;不提供不存在的返回值。
|
||||
- 观测流断开后不能继续写半条 JSON;若产生副作用后出错,禁止伪称事务回滚。
|
||||
- 取消由外部 Tool 管理 OS 子进程(或未来明确的 CLI 取消机制),SIGTERM/SIGKILL 后无终态是合法边界;外部消费者必须以 EOF、退出状态和超时综合判断。
|
||||
- 多次运行具有不同 `run_id`;不能跨运行复用 `frame_id` 或将 A 的 `source_digest` 绑定给 B。
|
||||
|
||||
### 10.2 stdout 完整性与任务终态次序
|
||||
|
||||
成功运行必须满足:先观察到全部已接受的 `stdout.chunk` 和 `stderr.chunk`,之后才可以出现 `run.completed`。拼接 base64 解码字节应与同一个 fixture 在普通运行模式下的原始输出一致(前提是相同参数与能力配置)。不得因为 UTF-8 chunk 边界将中文变乱码,也不得因为换行将一条事件误拆成多条。
|
||||
|
||||
### 10.3 复杂外部扩展的输出
|
||||
|
||||
Host 管辖的 `resource.write("stdio")`、`打印` 正常路径必须覆盖;Foreign/Plugin/Provider 若在自己的子进程 stdout 打印,输出默认视作**外部进程数据**,必须由受控 transport 收集或拒绝该组合,不能透传到 CLI 协议 stdout。提议为可归属外部进程的输出保留未来 `external.stdout.chunk` 事件,但**不在本 Issue 假定所有第三方扩展已经具备该能力**。
|
||||
|
||||
---
|
||||
|
||||
## 11. 对既有公开协议和外部仓库的影响
|
||||
|
||||
### 11.1 各协议边界
|
||||
|
||||
| 接口 | 当前/建议 | 需要承担的职责 |
|
||||
|---|---|---|
|
||||
| Analysis v2 | **保持** | 静态结构、模块/函数身份、源码位置和 digest |
|
||||
| Trace v2 | **保持** | 一次执行结束后的低敏、完整的受限轨迹文件 |
|
||||
| Execution Events v1 | **新增** | 在线 stdout/stderr、生命周期、调用帧身份、选定可观测值 |
|
||||
| CLI Tool Protocol v1 | **保持**,必要时另立兼容性扩展 | 启动独立工具、定位 `MARQDO_BIN`,不得硬编码 View |
|
||||
| View SSE | **View 仓库实现** | POST 执行、GET SSE 推送、取消、页面状态与结果呈现 |
|
||||
| Debug Protocol | **以后另议** | 断点、单步、状态快照、内存字节等高风险双向操作 |
|
||||
|
||||
### 11.2 View 无需重新实现执行引擎
|
||||
|
||||
`marqdo-view` 先按 RFC-VIEW-0002 已公开 `--json`/Trace v2 完成独立安装、默认不执行、显式运行和 SSE 生命周期。一旦新 Events v1 发布,**只替换一个 CLI output adapter**:
|
||||
|
||||
```text
|
||||
现有:CLI --json 结束结果 + Trace v2 → View Execution Controller → SSE
|
||||
新增:CLI --event-stream jsonl(增量)+ 可选 Trace v2 → 同一 Controller → SSE
|
||||
```
|
||||
|
||||
不调整文档渲染核心、不生成 HTML 的第二条路径、不引入 Host 私有依赖,也不在 CLI 里判断“是不是 View 进程”。View 应对没有新协议的旧版 Beta CLI 采用明确降级/提示,不假装实时 stdout。
|
||||
|
||||
### 11.3 Agent、Prove、Knowledge 的边界
|
||||
|
||||
- Agent 能消费 stdout.chunk、状态与终态,但是否有 LLM Token 流仍取决于模型扩展是否**实际**增量输出;事件协议不生产 AI 内容。
|
||||
- Prove 可消费实验观测/反例;不能把 `variable.assigned` 作为通用证明证书。
|
||||
- Knowledge 可记录来源一致的执行观测;必须显式区分动态观察、人工确认与形式证明。
|
||||
- 任何第三方仓库都只能依赖公开 CLI、Schema、Release Artifact,不得通过 Cargo path 依赖 Runtime 内部类型。
|
||||
|
||||
---
|
||||
|
||||
## 12. 分阶段开发任务(可直接拆分 PR)
|
||||
|
||||
### OBS-00:基线、ADR 与 Protocol Skeleton(P0)
|
||||
|
||||
**为什么**:不在不确定的源码/规范之上新增互不兼容的事件格式。
|
||||
|
||||
**要开发**:在 `docs/architecture/` 或 Issue 留存此 RFC;新增架构 ADR(建议下一可用编号),固定现有 `--json`、Trace v2、Host 输出语义;新增 `spec/execution-events-v1.md` 和 `spec/schemas/execution-events-v1.schema.json` 初始合同;建立 `tests/consumers/execution_events_consumer.py` 或等价独立消费者骨架。
|
||||
|
||||
**验收**:代码尚未实现也能针对 Schema 校验正反向 fixtures;独立文档明确 `CURRENT/PROPOSED`;不修改旧 Trace v2 Schema 的私密字段保证。
|
||||
|
||||
### OBS-01:Host 与 Runtime 的观测挂钩(P0)
|
||||
|
||||
**可能修改**:`crates/marqdo-host/src/host.rs`、`crates/marqdo-host/src/host/effects.rs`、`crates/marqdo-host/src/trace.rs`、`crates/marqdo-runtime/src/interpreter.rs`(仅观测钩子)、可能新增 `crates/marqdo-host/src/observe/`。
|
||||
|
||||
**要开发**:Null/Enabled Sink;Run 生命周期事件的内部表示;统一序号与安全来源身份;在 stdio 真实写入路径上发出只读字节事件;预算/IO 错误传播;兼容既有 Trace 收集。
|
||||
|
||||
**验收**:默认未启用时不序列化、不为每次变量赋值 clone `Value`;已有普通运行的返回、stdout、stderr、Trace/错误/权限测试全部不变;内部可对写入时刻的事件进行测试(不能事后分片)。
|
||||
|
||||
### OBS-02:JSONL CLI 参数与真实实时流(P0)
|
||||
|
||||
**可能修改**:`crates/cli/src/main.rs`、`crates/cli/src/commands/run.rs`、`crates/cli/src/output.rs`,新增 `crates/cli/src/execution_events.rs`;`spec/` + 开发者文档。
|
||||
|
||||
**要开发**:`--event-stream jsonl`;writer;`stream.opened`/`run.started`/`stdout.chunk`/`stderr.chunk`/`run.completed|failed|rejected`;与 `--json` 互斥、`--trace-file` 并存;严格的 stdout 纯净性和失败退出。
|
||||
|
||||
**验收**:长任务在结束前可读到前置输出;二进制字节可重组;不同渠道无 JSON 污染;事件行逐条合法;故障/超时/拒绝均有明确定义;无需改 View 或核心语言语法。
|
||||
|
||||
### OBS-03:独立消费者与发布验证(P0)
|
||||
|
||||
**要开发**:Linux x86_64 release 构建的已发布二进制,冻结 SHA-256;在独立 Python/Rust/Go fixture 项目读取 stdout JSONL,解析、验证 schema、重组字节,确认与终态;一个最小 View adapter JSONL→SSE 的端到端演示(属于 `marqdo-view` 仓库,不移入 CLI)。
|
||||
|
||||
**验收**:二进制不重新编译、不变化;独立消费者在正常/失败/断开情形均按规范完成;`marqdo --help`、README、CHANGLEOG、COMPATIBILITY、STATUS、Release Notes 明确声明新协议及适用版本。
|
||||
|
||||
### OBS-04:调用实例 ID 与结构事件(P1)
|
||||
|
||||
**可能修改**:`crates/marqdo-runtime/src/interpreter.rs`、Host 观测类型、Schema;现有 Trace v2 仅能做不破坏的内部身份对齐。
|
||||
|
||||
**要开发**:`frame_id`/`parent_frame_id`、enter/exit 配对、递归/多次调用归属;return/branch/loop/Host effect 与调用帧关联;`run.failed` 异常路径收束。
|
||||
|
||||
**验收**:递归/多调用 fixture 100% 正确归属;不存在相同帧 ID 的重复进入;传输未截断时帧完整闭合;嵌套调用与错误回卷不悬空。
|
||||
|
||||
### OBS-05:受控值观测(P1)
|
||||
|
||||
**可能修改**:Runtime 的 `bind_args`、局部写入、Host 观测过滤器、CLI 参数和 Schema。
|
||||
|
||||
**要开发**:精确的 `--observe-variable`、`--observe-parameter` 选择;类型摘要;标量有界序列化、文字的二次 opt-in;有据可查的 `redacted/truncated/unsupported`;**不读 MemoryStore 原始内容**。
|
||||
|
||||
**验收**:默认运行和只开启结构事件都不会泄露哨兵值;未选择变量绝不输出;中文字符串跨字节/超长值正确截断;无效选择和不支持的嵌套类型有明确定义;启用后每个值的帧和源码坐标正确;关闭观测时基准性能满足门禁。
|
||||
|
||||
### OBS-06:内存元数据(P2,可延期)
|
||||
|
||||
**可能修改**:`crates/marqdo-runtime/src/memory.rs` 和 Host 事件类型。
|
||||
|
||||
**要开发**:创建、增长、成功写入和预算统计;不透明区域标识;禁用裸指针与字节读取。
|
||||
|
||||
**验收**:内存区域/总提交量与真实 Store 一致;扩容失败不能产生“成功增长”;权限、类型和 budget 均不受观测影响。
|
||||
|
||||
### OBS-07:正式门禁、文档治理与跨平台(P0/P1)
|
||||
|
||||
**要开发**:在原有 Linux 主通道以及平台声明范围内运行 CI;Perf 追加 disabled/metadata/values 三档;严格隔离的组合测试,不用本次改动推断未验证平台已经受支持;更新协议版本矩阵和源码状态文档。
|
||||
|
||||
**验收**:见第 13/14 节。对于稳定 3.x,性能和安全门禁不能因 Beta 阶段允许 WARN 而永久免检。
|
||||
|
||||
---
|
||||
|
||||
## 13. 最小测试项目与验收矩阵
|
||||
|
||||
### 13.1 可执行 fixture A:真实输出与返回
|
||||
|
||||
```markdown
|
||||
# @knowledge Stream protocol example
|
||||
|
||||
## @exec main
|
||||
|
||||
`打印("START")`
|
||||
|
||||
`n = 10`
|
||||
|
||||
`打印("DONE")`
|
||||
|
||||
`return n`
|
||||
```
|
||||
|
||||
**验收**:普通 `marqdo run` 与 `--event-stream jsonl` 两条运行结果一致;JSONL 前置输出发生于 run.completed 之前;输出 chunk 重组为相同字节;返回值保持官方 wire 编码;运行结果不混入原始输出文本行。此 fixture 只测试输出事件的时间顺序,不能充当“有时间延迟”测试;延迟由下面的独立 fixture 测量。
|
||||
|
||||
### 13.2 实时性 fixture B:长任务中段输出
|
||||
|
||||
选取**当前语言已经支持**的确定性长任务:程序先打印 `READY`,再进行可测量的大量计算/循环,最后打印 `FINISH`。测试进程在读取到 `READY` 时必须仍处于运行中;如果本机任务太快,则使用受控、可重复且经授权的 `process.run` fixture 或测试用 Host 延迟,避免依赖未被正式支持的 `sleep` 关键字。**严禁仅靠 run.completed 之后 replay 的字符串伪造 PASS。**
|
||||
|
||||
验收标准(建议 CI):在固定测试机上,`READY` 事件的可观察到达时间必须明显早于最终退出(例如与后续受控延迟 ≥ 300ms 之间至少有 100ms 可辨窗口),在负载波动时保留 timing 诊断,不把共享 CI 的单次偶然卡顿视为核心失败证据。可用同步闸门 fixture 做确定性测试:子进程收到 READY 后测试方才释放后续计算。
|
||||
|
||||
### 13.3 结构 fixture C:递归、重复调用、嵌套循环
|
||||
|
||||
编写合法 3.0 RFC-LANG-0002 的 `main`、`f`、`g`,至少有 `main→f→g`、两次 `f`、一次递归调用、一条真假分支和循环两次。测试断言:不同 `frame_id`、正确 `parent_frame_id`、`function_id`、源位置、事件排序和真实循环次数;提前返回与深层异常均能形成可归属的失败事件。
|
||||
|
||||
### 13.4 变量 fixture D:默认不泄露 / 精确启用
|
||||
|
||||
```markdown
|
||||
## @exec main
|
||||
|
||||
`secret_token = "DO_NOT_LEAK_SENTINEL_1"`
|
||||
|
||||
`visible_count = 42`
|
||||
|
||||
`return visible_count`
|
||||
```
|
||||
|
||||
注意:这是测试值泄露策略的 fixture,**不要同时打印 secret_token**,否则 stdout 按程序意图包含它,不能拿来证明观察系统泄露。
|
||||
|
||||
- 默认普通运行/默认 event mode / metadata mode / Trace v2:均不应包含 `DO_NOT_LEAK_SENTINEL_1`。
|
||||
- `--observe-variable visible_count`:在该事件收到 42(若整数值被允许)。
|
||||
- `--observe-variable secret_token` **但未显式开启文本值选项**:仅显示 `redacted`,不出现哨兵。
|
||||
- 即使允许文本,也只输出被精确选择且未超预算的值;不得连带输出其他变量。
|
||||
|
||||
### 13.5 负面与边界验收表(每项都须可自动测试)
|
||||
|
||||
| 编号 | 测试 | 预期结果 |
|
||||
|---|---|---|
|
||||
| T01 | 不加 `--event-stream` | stdout、错误、退出码、Trace v2 与当前版本一致 |
|
||||
| T02 | `--event-stream jsonl --json` | usage 错误,无混合输出 |
|
||||
| T03 | `check`/`inspect` 请求 event mode | 拒绝;不执行 |
|
||||
| T04 | 每条 JSONL 行 Schema v1 验证 | 全部通过;seq 从 0 单调递增 |
|
||||
| T05 | 未知 Schema major 的独立消费者 | 明确拒绝、不静默当 v1 |
|
||||
| T06 | stdout 中文多字节跨 chunk | base64 重组原始字节完全一致 |
|
||||
| T07 | stderr 非 UTF-8 / NUL | 无数据损坏、无输出混杂 |
|
||||
| T08 | 长任务中段输出 | 可在执行仍未退出时观测到 |
|
||||
| T09 | `run --trace-file` 同时使用 JSONL | Trace v2 正常原子写入,digest 对应 |
|
||||
| T10 | 预备失败、语义错误、授权拒绝 | event mode 有 `run.rejected`,非零退出,无 `run.started` |
|
||||
| T11 | 运行错误 | `run.failed`,无 `run.completed` |
|
||||
| T12 | SIGKILL / 进程崩溃 | 消费者判 incomplete,不凭空补成功 |
|
||||
| T13 | 断管 / JSONL writer IO 错误 | 非零退出或已终止,不能继续无限副作用 |
|
||||
| T14 | 慢消费者 | 背压有界、内存不无限增长、无静默输出丢失 |
|
||||
| T15 | 结构事件预算耗尽 | 有 `observation.truncated`,后续 stdout/终态仍可传输 |
|
||||
| T16 | stdout 执行预算耗尽 | 与旧 Budget 一致,不绕过限制 |
|
||||
| T17 | 重复/递归调用 | `frame_id` 唯一、parent 正确、来源正确 |
|
||||
| T18 | 参数绑定失败 | 不出现悬空的假调用帧 |
|
||||
| T19 | return / error | enter/exit 正确配对(未截断前提下) |
|
||||
| T20 | `variable.assigned` | 只在真实提交后发,源 span 精确 |
|
||||
| T21 | 默认观测 | 不包含未选择的局部变量/参数值 |
|
||||
| T22 | 显式选中整数变量 | 值可用且有预算限制 |
|
||||
| T23 | 文本值未二次授权 | 哨兵字节不存在 |
|
||||
| T24 | 不支持的复杂类型/MemoryHandle | 仅安全类型/遮蔽状态,不序列化句柄 |
|
||||
| T25 | 观测打开/关闭同一程序 | 原业务结果与权限判定一致 |
|
||||
| T26 | 不可信插件原生 stdout | 不污染 JSONL,必要时 fail-closed |
|
||||
| T27 | `pure/project/strict` 模式 | 授权、拒绝和已声明的支持矩阵不变 |
|
||||
| T28 | 源文档更改后回放旧事件 | digest 失效提示,不贴到新源码 |
|
||||
| T29 | 多次运行 | 不共享 run/frame 身份 |
|
||||
| T30 | 冻结发布 CLI 二进制的外部 Python/Go/Rust 消费者 | 不改 CLI 源码、不重编译、成功消费新协议 |
|
||||
| T31 | 旧 Analysis v2/Trace v2 消费者回归 | 无行为/Schema 回归 |
|
||||
| T32 | CI 性能对照:关闭、metadata、values | 记录可重复 p50/p95、分配和内存,异常回归阻止发布 |
|
||||
| T33 | 值观测写入现有 `--json`/Trace v2 | 不允许出现新增秘密字段 |
|
||||
| T34 | 错误的 `module_id/span` | 独立消费者拒绝/明确告警,不能装饰错误源码 |
|
||||
| T35 | `stdout.chunk` 与 run.completed 顺序 | 全部已提交输出先于终态;逐字节保真 |
|
||||
| T36 | 外部工具按 `MARQDO_BIN` 调用发布版 | 不需要私有 Cargo crate 或 Rust Host 嵌入 |
|
||||
|
||||
### 13.6 性能与容量验收原则
|
||||
|
||||
不要不经测量地宣称“零开销”。至少固定三个等级:`disabled`、`structural`、`selected values`,在相同 SHA、同工具链、同硬件节点上对循环、递归、输出密集、内存密集和 Foreign/Plugin 典型负载记录时间分布、峰值 RSS、输出字节、事件字节与丢弃计数。**未启用时不应发生 Value 序列化、长驻事件队列或全帧 clone**。任何目标百分比阈值须先通过基线验证后写入正式 release gate,不能用主观“无明显影响”代替数据。
|
||||
|
||||
---
|
||||
|
||||
## 14. 文档、CI、版本与发布完成标准
|
||||
|
||||
实现过程中必须同步更新:
|
||||
|
||||
- `spec/execution-events-v1.md`:**规范真相**,包含每类事件 required 字段、序号、终态、版本/未知字段、值策略与错误边界。
|
||||
- `spec/schemas/execution-events-v1.schema.json`:Draft 2020-12;配套正负 fixture。
|
||||
- `docs/developers/analysis-trace.md`:加入 Execution Events v1 的精确 CLI 使用示例、Analysis/Trace 绑定规则和禁用边界。
|
||||
- `docs/developers/tools.md`、第三方手册:新增外部消费者指南;若 Tool 协商改变,必须升级对应协议规范和测试。
|
||||
- `docs/developers/compatibility.md`、`COMPATIBILITY.md`:明确该协议与 Marqdo 产品/Analysis/Trace/Tool 各自独立的版本轴。
|
||||
- `README.md`、`CHANGELOG.md`、`docs/STATUS.md`、`docs/architecture/CURRENT.md`、`docs/releases/`:明确已实现、已验证、已发布和限制,**不能将本 Issue 的 Proposed 描述当成已实现**。
|
||||
- `crates/cli/tests/`、`crates/marqdo-host/tests/`、`crates/marqdo-runtime/tests/`、`tests/consumers/`:增加上述测试。
|
||||
- 适用平台的 CI:`cargo fmt --check`、clippy、workspace tests、JSON schema 正负验证、独立 frozen-binary contract、必要的 strict/安全与性能 lane;发布结论以同 SHA 证据为准。
|
||||
|
||||
### 14.1 Definition of Done(完全完成的判定)
|
||||
|
||||
必须同时满足:
|
||||
|
||||
- [ ] `marqdo run/call` 真实增量输出 Events v1,至少具备 P0 事件、严格 NDJSON 和终态/错误行为。
|
||||
- [ ] 事件来自**实际的 Host 输出提交点**,不是最终缓冲拆包;持续运行时消费者能读到先发出的 stdout/stderr。
|
||||
- [ ] 现行 `--json`、Trace v2、Analysis v2、授权模式、语言语义及普通 CLI stdout 保持原样。
|
||||
- [ ] P1 若作为本 Issue 完成范围:正确 frame identity 和变量/参数观测,默认不泄露值且显式选择严格生效;否则在发布记录明确 `OBS-04/05 pending`,不对外宣称已支持。
|
||||
- [ ] 禁止原始句柄/内存、未获同意的文本值和外部插件 fd 污染 JSONL。
|
||||
- [ ] 慢消费者、终端断开、预算截断、取消/崩溃、严格模式均有负面测试;无伪造成功或无限缓冲。
|
||||
- [ ] 使用发布版二进制与独立第三方消费者完成黑盒验证,二进制 SHA-256 测试前后不变。
|
||||
- [ ] 文档、Schema、fixtures、版本矩阵和同 SHA 的 CI/性能/安全证据一起提交并更新,避免文档与代码脱节。
|
||||
|
||||
---
|
||||
|
||||
## 15. 反模式与禁止事项(适用于所有 PR)
|
||||
|
||||
**禁止**:
|
||||
|
||||
1. 在 CLI 增加 `view` 专用命令/模块或只在 View 进程启动时才启用的私有路径。
|
||||
2. 在核心引入 HTTP server、SSE、WebSocket、前端、Notebook、Agent 会话、Knowledge/Prove 业务逻辑。
|
||||
3. 把普通 stdout 和 JSONL 事件写到同一物理 stdout;把最终字符串拆成“实时”chunk。
|
||||
4. 将 `Frame.locals`、整个 MemoryStore、原始 C ABI/OS 指针或任意 `Value` 的 Rust `Debug` 输出给外部消费者。
|
||||
5. 修改 Trace v2 的“不包含敏感值”承诺而仍维持 `schema_version:2`。
|
||||
6. 以强行重写 JSONL 或自定义解析 Markdown 语义方式绕过原来的 Analysis digest。
|
||||
7. 允许消费者拖慢时分配无界 Vec、队列或后台线程;静默丢 stdout 或伪造已完成。
|
||||
8. 观测失败后继续无限运行带副作用任务而不回报错误。
|
||||
9. 依赖私有 `inspect --ir`、`marqdo-ir` Cargo path 或宿主内存布局来实现第三方工具。
|
||||
10. 将多次运行的某个值当作通用定理的证明,或把“本次未观察到”当作“本次没有发生”。
|
||||
|
||||
---
|
||||
|
||||
## 16. Issue 可以直接拆出的执行清单
|
||||
|
||||
- [ ] **OBS-00**:确认最新 SHA / 审批 RFC / ADR / 公共 Schema / fixtures。
|
||||
- [ ] **OBS-01**:实现内部 typed sink、Null/Enabled 配置、Host stdout/stderr 原位事件与可传播 IO 故障。
|
||||
- [ ] **OBS-02**:`run/call --event-stream jsonl`、Lifecycle、base64 Chunk、预算与既有 `--json` 兼容。
|
||||
- [ ] **OBS-03**:真正独立的 frozen-binary 消费者和 live-output gate;更新 CLI 版本文档。
|
||||
- [ ] **OBS-04**:Frame ID / Parent ID / 递归调用及分支、循环事件正确归属。
|
||||
- [ ] **OBS-05**:显式选择、预算受限的参数/局部变量值观测;默认隐私 gate。
|
||||
- [ ] **OBS-06(可后移)**:Memory metadata(仅大小、区域、写入范围)。
|
||||
- [ ] **OBS-07**:覆盖所有负面测试、安全、性能、同 SHA 证据和 Release Notes。
|
||||
|
||||
**建议合并策略**:先交付 P0,可供 View/Agent 消费;再交付 P1 的帧身份与值观测;P2 不阻塞。P0 结束后,即使 P1 未完成,也应能真实改善实时输出体验。任何实施中发现的语言语义缺口要记录为**独立 issue**,不能把本项扩展成全能调试器。
|
||||
|
||||
---
|
||||
|
||||
## 17. 参考源码与权威文档(便于接手开发者逐文件定位)
|
||||
|
||||
**当前 CLI(审查 SHA `eeea01d`)**:
|
||||
|
||||
- [`crates/cli/src/main.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/cli/src/main.rs) — 参数定义与 `run/call` 分发。
|
||||
- [`crates/cli/src/commands/run.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/cli/src/commands/run.rs) — 预备、授权、Host 配置、执行、完成后 JSON/Trace。
|
||||
- [`crates/cli/src/trace.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/cli/src/trace.rs) — Trace v2 完整文件 Writer。
|
||||
- [`crates/cli/src/analysis.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/cli/src/analysis.rs) — Analysis v2 / digest。
|
||||
- [`crates/cli/src/output.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/cli/src/output.rs) — 当前 `--json` 诊断与最终 envelope。
|
||||
- [`crates/marqdo-runtime/src/interpreter.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/marqdo-runtime/src/interpreter.rs) — 调用帧、参数绑定、赋值/分支/循环及来源。
|
||||
- [`crates/marqdo-runtime/src/memory.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/marqdo-runtime/src/memory.rs) — MemoryStore 的区域和预算边界。
|
||||
- [`crates/marqdo-host/src/host.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/marqdo-host/src/host.rs) — Host Trait、StdHost、stdio 缓冲与 resource 写入。
|
||||
- [`crates/marqdo-host/src/host/effects.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/marqdo-host/src/host/effects.rs) — 现有 Host effect/sequence 记录。
|
||||
- [`crates/marqdo-host/src/trace.rs`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/crates/marqdo-host/src/trace.rs) — 现有语义事件/预算类型。
|
||||
- [`spec/analysis-v2.md`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/spec/analysis-v2.md);[`spec/trace-v2.md`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/spec/trace-v2.md);[`spec/tool-v1.md`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/spec/tool-v1.md) — 现行公共协议边界。
|
||||
- [`docs/developers/analysis-trace.md`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/docs/developers/analysis-trace.md)、[`docs/developers/tools.md`](https://github.com/cflmy/marqdo-cli/blob/eeea01d672c07b6be7d6444031d1619309dc88ab/docs/developers/tools.md) — 第三方消费接口。
|
||||
|
||||
**关联产品需求(不是 CLI 接口真相)**:`marqdo-view` 的 RFC-VIEW-0002 定义“默认静态、显式执行、SSE 实时任务状态、交互只通过 CLI 子进程”,但本 Issue **不依赖**该文件才能实现;CLI 只需提供以上通用 JSONL 流。旧 `cflmy/marqdo` 的 View 功能和源码仅能辅助回归 UI 体验,不得迁移旧私有 Host/Notebook API。
|
||||
|
||||
---
|
||||
|
||||
### 结语:应从“View 要变量面板”转为“语言提供可信可观测性”
|
||||
|
||||
这次改动的价值不在于让某个旧页面复活,而在于:**Marqdo 的执行语义由 CLI 唯一负责,所有外部工具获得同一份可验证、可限制、可授权、可版本化的运行事件。** 默认运行不泄密、不改变既有程序;需要更深观测时用户明确选择且能看到风险;每条可见结果都有来源、身份和失败语义。这样才能在后续开发 `marqdo-view`、`marqdo-knowledge`、`marqdo-prove`、Agent 和扩展库时继续保持真正的仓库解耦。
|
||||
@@ -0,0 +1,56 @@
|
||||
# Core resource-operation ownership
|
||||
|
||||
Status: **reviewed and enforced** (ADR-0062, RFC-EXT-0003 H-03/H-04).
|
||||
This page is the ownership record for every operation reachable through
|
||||
`Host::resource_request`. Adding an entry here is a product decision, not an
|
||||
implementation detail; the architecture gate
|
||||
`crates/cli/tests/architecture_boundaries.rs::resource_request_operation_allowlist_is_reviewed`
|
||||
extracts the literals from the host source and fails on any unreviewed change.
|
||||
|
||||
## Dispatch rules
|
||||
|
||||
- Every operation requires `SandboxMode::Project`; `pure` and `strict` refuse all
|
||||
resource operations with `PermissionDenied`.
|
||||
- `Memory`/resource handles never cross this API; path arguments are `Text`.
|
||||
- Operation-level grants are checked before any host action (`check_process`,
|
||||
`check_read`, `check_write`, `check_entropy`, `check_env`, network grants).
|
||||
- The compatibility dispatcher matches exact names in
|
||||
`crates/marqdo-host/src/host/resource_requests.rs`. The `fs.` prefix only
|
||||
distinguishes unknown-operation diagnostics.
|
||||
|
||||
## Reviewed operation table
|
||||
|
||||
| Operation | Class | Owner / implementation | Authorization | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| `process.run` | Core OS primitive | `crate::process::run_process` | exact program grant (`--allow-program`) | ADR-0044; `crates/marqdo-host/tests/resource_streams.rs` |
|
||||
| `env.get` | Core OS primitive | host environment | exact-name env grant | ADR-0043 |
|
||||
| `clock.now` | Core OS primitive | `SystemTime` | project mode | ADR-0042 |
|
||||
| `random.bytes` | Core OS primitive | OS entropy | explicit entropy grant (`--allow-random`) | ADR-0046 |
|
||||
| `fs.read_at` | Core OS primitive | `ProjectFs::request("read_at")` | read grant | ADR-0045 |
|
||||
| `fs.append` | Core OS primitive | `ProjectFs::request("append")` | write grant | ADR-0045 |
|
||||
| `fs.walk` | Core OS primitive | `ProjectFs::request("walk")` | read grant | ADR-0045 |
|
||||
| `fs.exists` | Core OS primitive | `ProjectFs::request("exists")` | read grant | ADR-0041 |
|
||||
| `fs.metadata` | Core OS primitive | `ProjectFs::request("metadata")` | read grant | ADR-0041 |
|
||||
| `fs.list` | Core OS primitive | `ProjectFs::request("list")` | read grant | ADR-0041 |
|
||||
| `fs.mkdir` | Core OS primitive | `ProjectFs::request("mkdir")` | write grant | ADR-0041 |
|
||||
| `fs.remove` | Core OS primitive | `ProjectFs::request("remove")` | write grant | ADR-0041 |
|
||||
| `fs.rename` | Core OS primitive | `ProjectFs::request("rename")` | write grant on both paths | ADR-0041 |
|
||||
| `regex.match` | Host-held built-in service | host regex library | project mode | ADR-0050 |
|
||||
| `regex.captures` | Host-held built-in service | host regex library | project mode | ADR-0050 |
|
||||
| `compress.gzip` | Host-held built-in service | host gzip library | project mode | ADR-0049 |
|
||||
| `compress.gunzip` | Host-held built-in service | host gzip library | project mode | ADR-0049 |
|
||||
|
||||
`regex.*` and `compress.*` are existing host-held convenience services. They
|
||||
do not create a general extension mechanism: no new domain operation may follow
|
||||
them into the core.
|
||||
|
||||
## Forbidden additions
|
||||
|
||||
- No domain/business operation (math, text, graphics, networking protocol,
|
||||
database, …) may be added to `resource_request`. Ship it as a pure `.mq.md`
|
||||
package, a Callable Plugin ABI export, or a Resource Provider.
|
||||
- No new language keyword, builtin name or CLI flag is added by this table.
|
||||
- No provider may use or declare a core kind: the single list lives in
|
||||
`marqdo_host::CORE_RESOURCE_KINDS` and is enforced by both the CLI validator
|
||||
and trusted host registration.
|
||||
- The removed `math.*` builtins (ADR-0061) are not coming back through this API.
|
||||
+13
-2
@@ -16,14 +16,25 @@ The default Docker pipeline runs on push and pull request:
|
||||
```text
|
||||
test:
|
||||
rustup component add clippy rustfmt
|
||||
apt install curl/ca-certificates/python3 + Node.js 22
|
||||
apt install curl/ca-certificates/python3/python3-jsonschema + Node.js 22
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo build --locked -p marqdo-provider-worker
|
||||
cargo test --workspace --locked
|
||||
cargo run --locked -p marqdo-cli -- run \
|
||||
tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl \
|
||||
> /tmp/execution-events.jsonl
|
||||
python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
|
||||
cargo test -p marqdo-cli --test docs_consistency
|
||||
cargo test -p marqdo-cli --test architecture_boundaries
|
||||
cargo test -p marqdo-cli --test stdlib_product
|
||||
python3 -m unittest discover -s tools/ci -p "test_*.py"
|
||||
rustup target add x86_64-pc-windows-gnu
|
||||
cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
|
||||
|
||||
build (depends on test):
|
||||
cargo build --release --locked -p marqdo-cli
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
package + cold-install smoke (which now validates live Execution Events v1)
|
||||
```
|
||||
|
||||
Node.js 22 is required because the optional foreign-kernel tests use ES-module
|
||||
|
||||
@@ -45,7 +45,7 @@ marqdo-cli/
|
||||
│ ├── security.md modes, capabilities, budgets, trust
|
||||
│ ├── package-format.md marqdo.yaml / marqdo.lock / init
|
||||
│ ├── plugin-abi.md C ABI v1, SDK, host lifecycle
|
||||
│ ├── math.md Formula subset and math.* semantics
|
||||
│ ├── math.md removed core math outlook + migration (ADR-0061)
|
||||
│ ├── foreign.md Python/Node kernel protocol
|
||||
│ ├── tool-v1.md generic external Tool Protocol v1
|
||||
│ ├── analysis-v2.md public Analysis v2 projection (v1 historical)
|
||||
@@ -58,12 +58,11 @@ marqdo-cli/
|
||||
│ ├── marqdo-markdown/ comrak profile, canonical AST, front matter
|
||||
│ ├── marqdo-ir/ Module/Unit/Function/Stmt IR, builtin table
|
||||
│ ├── marqdo-frontend/ units/modes, map, payloads, signature, infer, calls
|
||||
│ ├── marqdo-math/ Formula parser/evaluator (exact rationals)
|
||||
│ ├── marqdo-foreign/ Python/Node one-shot kernel supervisor
|
||||
│ ├── marqdo-sandbox/ modes + platform capability detection
|
||||
│ ├── marqdo-plugin-abi/ C ABI mirrors, manifest, artifact, loader, wire
|
||||
│ ├── marqdo-plugin-sdk/ Rust plugin SDK and `mq_plugin_entry!`
|
||||
│ ├── marqdo-host/ CapabilityHost, budgets, FS, math/foreign/plugin adapters
|
||||
│ ├── marqdo-host/ CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
|
||||
│ ├── marqdo-runtime/ tree-walk interpreter, value ops, builtins
|
||||
│ ├── marqdo-package/ marqdo.yaml / marqdo.lock types + discovery
|
||||
│ └── cli/ composition root: flags, commands, loader, output
|
||||
@@ -88,9 +87,8 @@ expression -> span
|
||||
markdown -> span, comrak (no semantic crate!)
|
||||
ir -> span, expression
|
||||
frontend -> markdown, expression, ir, value
|
||||
host -> value, math, foreign, sandbox
|
||||
host -> value, foreign, sandbox
|
||||
runtime -> ir, value, host, expression
|
||||
math -> value
|
||||
foreign -> value
|
||||
plugin-abi -> value
|
||||
plugin-sdk -> plugin-abi
|
||||
@@ -209,8 +207,8 @@ counts, harness responsibilities and known observations.
|
||||
|
||||
## 5. Coding conventions
|
||||
|
||||
* Rust edition 2021, `rust-version = 1.82`, workspace version `0.1.0`.
|
||||
* `unsafe` is forbidden in pure crates (`marqdo-math`, `marqdo-expression` use
|
||||
* Rust edition 2021, `rust-version = 1.82`, workspace version `3.0.0-beta.1`.
|
||||
* `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses
|
||||
`#![forbid(unsafe_code)]`); the ABI/loader crates contain the only
|
||||
`unsafe` code and every block has a SAFETY comment explaining the contract.
|
||||
* No panics on untrusted input: Markdown, expressions, LaTeX, wire data,
|
||||
@@ -261,7 +259,6 @@ Harness map (`crates/cli/tests/`):
|
||||
Crate-level tests worth knowing:
|
||||
|
||||
* `marqdo-expression` — grammar/priority/nesting/limit tests;
|
||||
* `marqdo-math/tests/kernel.rs` — exact arithmetic, bounds, equations, unsupported constructs;
|
||||
* `marqdo-foreign/tests/kernels.rs` — real python3/node (skips if absent), timeout, output caps, env, wire protocol;
|
||||
* `marqdo-plugin-abi/tests/loader_unix.rs` — compiles the C demo with `cc`, loads it, ABI-mismatch/negative cases (skips without `cc`);
|
||||
* `marqdo-runtime/tests/interpreter.rs` — recursion, loops, returns, budgets, ambiguity;
|
||||
@@ -281,8 +278,8 @@ $B call examples/factorial.mq.md 数学.阶乘 --arg n=5 # prints 120
|
||||
$B check examples/references.mq.md
|
||||
$B inspect examples/references.mq.md --refs
|
||||
$B inspect examples/hello.mq.md --ast --json
|
||||
$B run examples/math.mq.md # has no main: use call
|
||||
$B call examples/math.mq.md 数学.计算圆面积
|
||||
$B call examples/math.mq.md 数学.计算圆面积 # pure arithmetic, no math.* builtin
|
||||
$B call examples/math-library-demo.mq.md main # imports a pure math library
|
||||
$B run examples/python-foreign.mq.md --allow-foreign # needs python3
|
||||
$B run examples/multi-module/index.mq.md
|
||||
(cd examples/multi-module && ../../$B lock && ../../$B sync --locked)
|
||||
|
||||
@@ -7,9 +7,9 @@ core checkout, or host memory layout. Adding a new domain function must not
|
||||
require a core commit.
|
||||
|
||||
Product version for these docs: **`3.0.0-beta.1`** (Linux x86_64 beta).
|
||||
Protocol versions are independent: Analysis v2, Trace v2, Tool v1, Plugin ABI
|
||||
v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile
|
||||
`marqdo.md.v1`.
|
||||
Protocol versions are independent: Analysis v2, Trace v2, Execution Events v1,
|
||||
Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4,
|
||||
markdown profile `marqdo.md.v1`.
|
||||
|
||||
## Pick your entry point
|
||||
|
||||
@@ -33,7 +33,7 @@ v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile
|
||||
4. [extensions.md](extensions.md) — plugins, foreign kernels, resource
|
||||
providers, extension selection and lock v4.
|
||||
5. [analysis-trace.md](analysis-trace.md) — the public static/dynamic data
|
||||
contracts and digest binding.
|
||||
contracts, Execution Events v1 and digest binding.
|
||||
6. [compatibility.md](compatibility.md) — version axes, platform matrix and the
|
||||
prerelease policy.
|
||||
7. [release-limits.md](release-limits.md) — the honest beta limitations (this
|
||||
|
||||
@@ -60,6 +60,51 @@ marqdo run index.mq.md --trace-file ./trace.json
|
||||
`spec/schemas/trace-v2.schema.json`; consumer:
|
||||
`tests/consumers/trace_consumer.py`.
|
||||
|
||||
## Execution Events v1 (live)
|
||||
|
||||
```bash
|
||||
marqdo run index.mq.md --event-stream jsonl
|
||||
marqdo call index.mq.md main --arg n=5 --event-stream jsonl
|
||||
marqdo run index.mq.md --event-stream jsonl --trace-file ./trace.json
|
||||
```
|
||||
|
||||
- `schema: "marqdo.execution-events"`, `schema_version: 1`. This is a separate
|
||||
protocol from Analysis/Trace and has its own version axis.
|
||||
- While active, the CLI stdout is a **pure NDJSON channel**: one JSON object per
|
||||
line, `seq` starts at 0 and is strictly increasing. Program stdout/stderr are
|
||||
only `stdout.chunk`/`stderr.chunk` events with `encoding: "base64"`,
|
||||
`data_base64` and a matching `byte_count`. Concatenated decoded bytes equal a
|
||||
normal run's output; invalid UTF-8/NUL/binary bytes are preserved.
|
||||
- `stream.opened` is always seq 0. A run then has at most one `run.started` and
|
||||
exactly one terminal event (`run.completed`, `run.failed`, `run.rejected`) on
|
||||
a complete stream. An EOF without a terminal event is `incomplete`
|
||||
(SIGKILL/crash/broken pipe); never synthesize success.
|
||||
- `run.started.source` contains `root_id` and the `sha256:` digest of the exact
|
||||
Analysis v2 bytes. `--trace-file` may be combined; both writers share one
|
||||
opaque run id, and Trace v2 remains atomic and value-free.
|
||||
- Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`),
|
||||
`return`, `branch.eval`, `loop.iteration`, `effect`. Frames identify call
|
||||
instances, not functions; a failed argument binding creates no frame.
|
||||
- Values are off by default (`value_state: not_requested`).
|
||||
`--observe-variable NAME` and `--observe-parameter NAME` are exact-name
|
||||
selections. `Int`/`Float`/`Bool` are bounded by
|
||||
`--observe-max-value-bytes` (default 256); selected `Text` is `redacted` until
|
||||
`--observe-text-values` is also passed. Containers, `Memory`, resources and
|
||||
plugin handles are `unsupported`; handles are never serialized.
|
||||
- Structural/value events have a separate budget
|
||||
(`--observe-max-events`, `--observe-max-bytes`; defaults 100 000 / 16 MiB).
|
||||
Exhaustion emits one `observation.truncated` and still delivers stdout/stderr
|
||||
and the terminal event. A broken output pipe fails the run with
|
||||
`observe.transport_failed`; it never keeps executing side effects silently.
|
||||
- `--event-stream` is mutually exclusive with `--json`, rejected by
|
||||
`check`/`inspect`/`fmt`/`tool`, and currently rejected by `--mode strict`
|
||||
(fail-closed, no downgrade). It is not a capability grant.
|
||||
- Contract: [`../../spec/execution-events-v1.md`](../../spec/execution-events-v1.md);
|
||||
schema: `spec/schemas/execution-events-v1.schema.json`; consumer:
|
||||
`tests/consumers/execution_events_consumer.py`; fixtures and Rust gate:
|
||||
`tests/consumers/fixtures/execution-events/` and
|
||||
`crates/cli/tests/execution_events.rs`.
|
||||
|
||||
## Consumer rules
|
||||
|
||||
1. Reject unknown schema majors; there is no silent "use latest" fallback.
|
||||
|
||||
@@ -11,6 +11,7 @@ This page summarizes the public support policy. The authoritative matrix is
|
||||
| Product / CLI | `3.0.0-beta.1` | SemVer prerelease; breaking changes inside the 3.0 beta line are allowed and appear in `CHANGELOG.md`. |
|
||||
| Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. |
|
||||
| Trace | v2 | New major for incompatible changes; binds to exact Analysis bytes. |
|
||||
| Execution Events | v1 | One-line NDJSON stream; new major for incompatible required-field/ordering/redaction changes. Consumers reject unknown majors. |
|
||||
| CLI Tool | v1 | Frozen manifest/negotiation/bundle contract for v1. |
|
||||
| Plugin ABI | v1 (`1.0`) | Frozen C layout and version negotiation. |
|
||||
| Foreign wire | v1 | One-shot request envelope. |
|
||||
@@ -35,6 +36,9 @@ ranges**. Beta cores require a prerelease range such as
|
||||
|
||||
Strict is Linux-only and probe-gated. Plugin/provider worker transports are not
|
||||
OS sandboxes. `pure`/`project` are execution modes, not security boundaries.
|
||||
Execution Events v1 is a live observation protocol: it is not a capability
|
||||
grant, values are off by default, and `--mode strict` currently refuses
|
||||
`--event-stream` explicitly (no downgrade).
|
||||
|
||||
## Language compatibility
|
||||
|
||||
|
||||
@@ -163,3 +163,32 @@ Your external repository must pass with an unchanged CLI binary:
|
||||
The reference suite is
|
||||
[`marqdo-extension-conformance`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance);
|
||||
the core's evidence generator is `tools/ci/verify_extension_contracts.py`.
|
||||
|
||||
## 6. Optional math ABI backend (post core math removal)
|
||||
|
||||
After the `math.*` builtins were removed (ADR-0061) an accelerated math function
|
||||
is just an ordinary callable plugin export. `examples/math-backend/` exports
|
||||
`math_backend.add` through the same frozen ABI v1 and requests the
|
||||
`math.compute` **capability category**; `math.compute` does not promise any
|
||||
core solver. Selection is not authorization:
|
||||
|
||||
```bash
|
||||
./examples/math-backend/build.sh
|
||||
marqdo check examples/math-backend/demo.mq.md --plugin examples/math-backend/build
|
||||
marqdo run examples/math-backend/demo.mq.md \
|
||||
--plugin examples/math-backend/build --trust-native-plugin --allow-plugin math.backend
|
||||
# 42 ; without the grant: permission.denied
|
||||
```
|
||||
|
||||
A pure package is still preferred; see
|
||||
[`libraries.md`](libraries.md) §6. Domain operations must not be added to the
|
||||
core `resource_request` table (ADR-0062).
|
||||
|
||||
## 7. Heading annotations are Proposed, not implemented
|
||||
|
||||
`@exec`/`@knowledge` are the closed Core Modes and alone decide execution;
|
||||
third-party heading annotations are a **Proposed** metadata-only contract
|
||||
(ADR-0060, target `3.1.x`). This build still rejects an unknown leading `@foo`
|
||||
with `sem.invalid_mode_marker`; there is no annotation manifest,
|
||||
`annotation.unknown`, Analysis v3 or sidecar yet. Do not document annotations as
|
||||
available until Step B ships: [`../../spec/heading-annotations-v1.md`](../../spec/heading-annotations-v1.md).
|
||||
@@ -126,3 +126,23 @@ diagnostics. For negative cases expect hard errors, never prose fallback:
|
||||
- State that the package is pure `.mq.md` and needs no plugin/provider/kernel.
|
||||
- Version the package independently of the CLI (`0.1.0` here is the package
|
||||
version, not the product version).
|
||||
|
||||
## 6. Math libraries after the core math removal
|
||||
|
||||
The core `math.*` builtins (`math.parse/eval/substitute/simplify/differentiate`)
|
||||
were removed after `3.0.0-beta.1` by
|
||||
[ADR-0061](../adr/0061-detach-domain-math-kernel-from-core.md); a call is now
|
||||
a static `symbol.unknown` and `crates/marqdo-math` is gone. Pure `.mq.md` is the
|
||||
preferred replacement and the historical `math` import alias is available again:
|
||||
|
||||
```bash
|
||||
# examples/math-library/index.mq.md + ../math-library-demo.mq.md
|
||||
marqdo call examples/math-library-demo.mq.md main # 6
|
||||
```
|
||||
|
||||
Keep signatures/behaviour in your own library contract; the core promises no
|
||||
arithmetic beyond `Int`/`Float`, comparison and control flow, and no formula
|
||||
evaluator (`Formula` Markdown stays inert). For a hot path, an explicitly selected
|
||||
Plugin ABI export may request the `math.compute` capability
|
||||
(`examples/math-backend/`); grants and trust flags are unchanged
|
||||
(`docs/developers/extensions.md`). Migration: [`../../spec/math.md`](../../spec/math.md).
|
||||
@@ -61,8 +61,10 @@ Even when available:
|
||||
* `3.0.0-beta.1` is a **prerelease**, not stable and not LTS. Breaking changes
|
||||
inside the 3.0 beta series are allowed and announced in the changelog.
|
||||
* The product version is independent of protocol versions: Analysis v2, Trace
|
||||
v2, Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4
|
||||
keep their own major numbers. Do not infer them from `3.0.0-beta.1`.
|
||||
v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider
|
||||
manifest v2 and lock v4 keep their own major numbers. Do not infer them from
|
||||
`3.0.0-beta.1`. Execution Events v1 is a post-beta addition and is not in the
|
||||
tagged beta archive.
|
||||
* The official bundled stdlib keeps its independent package version `0.1.0`.
|
||||
A plugin `.mq.md` package version such as `0.1.0` is also independent.
|
||||
* `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer
|
||||
@@ -80,6 +82,23 @@ Archives are accompanied by SHA256 checksums and `RELEASE_INFO.json`
|
||||
integrity only; they are **not** a publisher signature. A digest obtained from
|
||||
an untrusted Git URL does not make the code trustworthy.
|
||||
|
||||
## Execution Events v1 (post-beta addition)
|
||||
|
||||
* Implemented: live stdout/stderr chunks, lifecycle/terminal events, call
|
||||
instance ids, branch/loop/effect events, explicit bounded value observation.
|
||||
* Not implemented: memory region/budget metadata (OBS-06/P2), raw memory
|
||||
content, breakpoints/stepping/time travel, and a bidirectional debug
|
||||
protocol. Do not infer a debugger from this protocol.
|
||||
* `--mode strict` currently rejects `--event-stream` explicitly; there is no
|
||||
silent fallback to `project`.
|
||||
* The live lane is tested on Linux x86_64; macOS/Windows are unverified for
|
||||
this option like the rest of the beta CLI.
|
||||
* In-process native plugins are rejected in event mode
|
||||
(`ext.event_stream_unsupported_native_plugin`) because they share the process
|
||||
and can write the protocol fd directly; worker plugins remain usable.
|
||||
* Observation lowers confidentiality when values are explicitly enabled. Text
|
||||
needs a second opt-in; View/agents must not enable these flags by default.
|
||||
|
||||
## Deliberately deferred
|
||||
|
||||
strict L2, Wasm plugins, macOS/Windows provider worker, automatic uv/npm
|
||||
|
||||
@@ -91,6 +91,20 @@ Dynamic input:
|
||||
"$MARQDO_BIN" run index.mq.md --trace-file ./trace.json
|
||||
```
|
||||
|
||||
Live dynamic input (Execution Events v1):
|
||||
|
||||
```bash
|
||||
"$MARQDO_BIN" run index.mq.md --event-stream jsonl
|
||||
"$MARQDO_BIN" call index.mq.md main --arg n=5 --event-stream jsonl
|
||||
```
|
||||
|
||||
Consume the stdout line stream as NDJSON; do not pass `--json` in the same
|
||||
invocation. Negotiate by reading `stream.opened` (`marqdo.execution-events`,
|
||||
`schema_version: 1`) and reject unknown majors. A tool server may convert the
|
||||
stream to its own SSE/websocket transport; the CLI never implements HTTP/SSE.
|
||||
This option is unavailable under `--mode strict` in the current tree and the
|
||||
tool must surface that refusal instead of pretending real-time support.
|
||||
|
||||
See [analysis-trace.md](analysis-trace.md) for fields and digest rules. Do not
|
||||
depend on `inspect --ir`: that JSON is not a frozen cross-repository protocol.
|
||||
The `view` tool renders the **original Markdown**, not the Analysis JSON; the
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Same-SHA CI evidence — `3.0.0-beta.1`
|
||||
|
||||
Date: 2026-11-22. Source SHA:
|
||||
`2c7c4f31e7a388d3fcfa717a77067e696ed13854` (branch `master`).
|
||||
|
||||
The authoritative CI for this repository is Gitea
|
||||
(`https://git.cflmy.cn/cflmy/marqdo-cli`) + Woodpecker
|
||||
(`https://ci.cflmy.cn`). A GitHub mirror is not the authoritative beta lane and
|
||||
was not available from the release host; this is stated in `COMPATIBILITY.md`
|
||||
and the release notes rather than claimed as a GitHub PASS.
|
||||
|
||||
## Linux pipeline #37 — PASS
|
||||
|
||||
URL: https://ci.cflmy.cn/repos/1/pipeline/37
|
||||
|
||||
```text
|
||||
pipeline 37
|
||||
commit 2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||
event push
|
||||
status success
|
||||
steps clone=success, test=success, build=success
|
||||
```
|
||||
|
||||
The `test` step ran `cargo fmt --all -- --check`, `cargo clippy --workspace
|
||||
--all-targets -- -D warnings`, `cargo test --workspace --locked`, the docs and
|
||||
architecture gates, the CI evidence-tool unit tests, the stdlib product tests
|
||||
and the Windows cross-target compile check.
|
||||
|
||||
The `build` step ran:
|
||||
|
||||
```text
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
test -x target/release/marqdo-provider-worker
|
||||
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
|
||||
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
|
||||
```
|
||||
|
||||
and reported a cold-install smoke PASS for its own CI-built archive:
|
||||
`archive version 3.0.0-beta.1, source 2c7c4f31...`, provider/tool/plugin/kernel
|
||||
positive and negative cases PASS, and strict fail-closed on the Docker host
|
||||
(`bubblewrap is not installed` → `strict` refused, never downgraded). The
|
||||
CI-built archive hash differs from the published archive because the C plugin
|
||||
artifacts and binary build environment differ; both are built from the same
|
||||
source SHA. The **published** archive and its exact binary hash are the ones
|
||||
bound in the extension evidence manifest and the release notes.
|
||||
|
||||
## Manual G4 pipeline #38 — PASS (WARN classification)
|
||||
|
||||
URL: https://ci.cflmy.cn/repos/1/pipeline/38
|
||||
|
||||
`performance`, manual, success, same source SHA; 5 warmups + 20 samples per
|
||||
workload on fixed agent 1, 9/9 workloads correctness-verified. See
|
||||
[`2026-11-22-perf-woodpecker-agent-1-run38.md`](2026-11-22-perf-woodpecker-agent-1-run38.md).
|
||||
The release-evidence manifest records this as a Beta-only `WARN` with the
|
||||
shared/powersave environment recorded, per the approved beta policy.
|
||||
|
||||
## Local gates on the same SHA (Linux x86_64, Rust 1.100.0)
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS
|
||||
cargo build --release --locked -p marqdo-cli \\
|
||||
-p marqdo-provider-worker PASS
|
||||
python3 tools/ci/verify_extension_contracts.py ... PASS (7/7 categories)
|
||||
python3 tools/release/smoke.py --archive ... PASS
|
||||
```
|
||||
|
||||
The extension evidence manifest is
|
||||
[`extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
||||
(tested SHA, CLI binary SHA-256 and fixture repo SHA bound; validated with
|
||||
`--validate`).
|
||||
@@ -0,0 +1,98 @@
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo --version
|
||||
marqdo 3.0.0-beta.1
|
||||
exit=0
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo --help
|
||||
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.
|
||||
|
||||
Usage: marqdo <COMMAND>
|
||||
|
||||
Commands:
|
||||
init Initialise a new Marqdo project
|
||||
run Run the entry function (`main` by default) of a document
|
||||
call Call a named function with typed arguments
|
||||
check Statically check a document without executing it
|
||||
inspect Inspect AST, units, signatures, IR, references or platform support
|
||||
fmt Conservative formatting: normalises line endings and trailing newlines
|
||||
plugin Plugin artifact inspection (never loads plugin code)
|
||||
add Add a dependency to marqdo.yaml
|
||||
remove Remove a dependency from marqdo.yaml
|
||||
lock Generate a deterministic marqdo.lock for the current project
|
||||
sync Verify that path dependencies match the lockfile
|
||||
tool Manage and dispatch generic external CLI tools
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
-h, --help
|
||||
Print help (see a summary with '-h')
|
||||
|
||||
-V, --version
|
||||
Print version
|
||||
exit=0
|
||||
### pure library flow
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo lock
|
||||
locked 1 package(s) in /tmp/guide-lib-v2/consumer/marqdo.lock
|
||||
exit=0
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo sync --locked
|
||||
synchronized 1 package(s) (locked) into /tmp/guide-lib-v2/consumer/.marqdo/env
|
||||
exit=0
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo check index.mq.md --refs
|
||||
checked 2 module(s): ok
|
||||
exit=0
|
||||
### /tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo call index.mq.md main
|
||||
42
|
||||
exit=0
|
||||
### project.marqdo mismatch
|
||||
error[project.load]: package.marqdo_incompatible: project requires marqdo `>=0.1,<1`, this core is 3.0.0-beta.1
|
||||
### project.marqdo mismatch
|
||||
error[project.load]: package.marqdo_incompatible: project requires marqdo `>=0.1,<1`, this core is 3.0.0-beta.1
|
||||
exit=2
|
||||
### tool install/dispatch
|
||||
installed tool `view` version 0.1.0 (marqdo-view)
|
||||
install exit=0
|
||||
view 0.1.0 (marqdo-view)
|
||||
list exit=0
|
||||
bin=/tmp/guide-release/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo
|
||||
tool=1 analysis=2 trace=2
|
||||
arg=index.mq.md
|
||||
arg=--json
|
||||
view exit=7
|
||||
removed tool `view`
|
||||
remove exit=0
|
||||
### plugin flows
|
||||
inspect exit=0
|
||||
checked 1 module(s): ok
|
||||
check-static exit=0
|
||||
42
|
||||
native-trust run exit=0
|
||||
error: loading `demo.solver` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation
|
||||
native-no-trust exit=1
|
||||
### provider flows
|
||||
provider run exit=0
|
||||
provider success= True read= ['kind=demo.sensor count=5']
|
||||
error[permission.denied]: resource provider `demo.sensor` was selected with --provider but is not granted; add --allow-provider demo.sensor
|
||||
provider-no-grant exit=1
|
||||
### kernel flows
|
||||
42
|
||||
kernel exit=0
|
||||
error: cannot open kernel provider: No such file or directory (os error 2)
|
||||
kernel-bad-digest exit=2
|
||||
### analysis/trace
|
||||
checked 2 module(s): ok
|
||||
12.566370614359172
|
||||
analysis+trace exit=0
|
||||
analysis sha256 1a2b894f4592861e063b40947da1c6f5fc5ee5d2cfdf623beb0bbc0434db5af7
|
||||
trace digest match True
|
||||
trace schema marqdo.trace 2 events 182
|
||||
### extension selection lock v4
|
||||
locked 0 package(s) in /tmp/guide-ext/marqdo.lock
|
||||
42
|
||||
extension run exit=0
|
||||
extension identity plugin demo.solver locked x86_64-unknown-linux-gnu
|
||||
### strict policy
|
||||
platform exit=0
|
||||
strict state {'mechanism': 'bubblewrap 0.11.1 (user/mount/PID/net/UTS/IPC namespaces + no-new-privs + rlimits)', 'state': 'available'}
|
||||
你好,Marqdo
|
||||
strict run exit=0
|
||||
error: 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.
|
||||
strict trace refusal exit=2
|
||||
guide validation done
|
||||
@@ -0,0 +1,72 @@
|
||||
# Third-party integration guide validation — `3.0.0-beta.1`
|
||||
|
||||
Date: 2026-11-22. Product: `3.0.0-beta.1`. Source SHA:
|
||||
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`.
|
||||
|
||||
Goal: every command/snippet in
|
||||
[`MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md)
|
||||
and [`developers/`](../developers/README.md) must work from the released
|
||||
archive without reading the core source or rebuilding the CLI.
|
||||
|
||||
## Binary and archive
|
||||
|
||||
```text
|
||||
archive dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
sha256 507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317
|
||||
marqdo sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f
|
||||
worker sha256 7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2
|
||||
```
|
||||
|
||||
The archive was extracted into a fresh directory outside the source tree; all
|
||||
commands below used only the extracted `marqdo` (and its sibling
|
||||
`marqdo-provider-worker`). The recorded console log is
|
||||
[`2026-11-22-beta-guide-validation.log`](2026-11-22-beta-guide-validation.log).
|
||||
|
||||
## Executed matrix
|
||||
|
||||
| Guide section | Command / flow | Result |
|
||||
|---|---|---|
|
||||
| §1 install | `sha256sum -c`, extract, `marqdo --version`, `--help` | PASS: `marqdo 3.0.0-beta.1` |
|
||||
| §2 pure library | local Git repo with `index.mq.md` + `params`; consumer with pinned `rev`, front-matter `import: quantum: "@quantum"`; `lock`, `sync --locked`, `check --refs`, `call main` | PASS: `lock` writes lock v4; call returns `42` |
|
||||
| §1.3 `project.marqdo` | project with `marqdo: ">=0.1,<1"` then `check` | PASS (fail-closed): exit 2, `package.marqdo_incompatible` names the running core |
|
||||
| §3 Tool v1 | independent tool package, `tool install`, `tool list`, dispatch `view index.mq.md --json`, `tool remove` | PASS: install/list/remove 0; dispatch preserves argv/stdout/exit code and receives `MARQDO_BIN` + protocol env vars; tool's exit code 7 propagated |
|
||||
| §3.1 Analysis v2 | `check --emit`, parse schema/version, producer version | PASS: `marqdo.analysis` v2, `producer.version = 3.0.0-beta.1` |
|
||||
| §3.2 Trace v2 | `run --trace-file`, compare `source.analysis_digest` with SHA-256 of the Analysis file bytes | PASS: digest matched byte-for-byte; `marqdo.trace` v2, 182 events on the example |
|
||||
| §4 Plugin ABI | `plugin inspect` static; `check --plugin` without loading; native run with `--trust-native-plugin`; native without trust | PASS: inspect/check/run 0; untrusted native refused with the documented `--trust-native-plugin` error |
|
||||
| §5 Provider v2 | `run --provider … --allow-provider demo.sensor`, read trace effects; no-grant run; missing helper (smoke) | PASS: provider reads `count=5`; no grant is `permission.denied`; missing sibling helper is `ext.worker_unavailable` with no PATH fallback |
|
||||
| §6 Foreign kernel | `run --kernel … --allow-foreign`; tampered `digest` | PASS: `42`; tampered digest fails with `kernel.unavailable` integrity error before execution |
|
||||
| §7 Extensions / lock v4 | project with `extensions.plugins.from=./adapter/plugin.yaml`; `lock`, `inspect --extensions --json`, `run --allow-plugin` | PASS: identity `plugin demo.solver locked x86_64-unknown-linux-gnu`; worker run returns `42`; undeclared grant is unnecessary but a grant is still required |
|
||||
| §1.4 strict | `inspect --platform --json`; `run --mode strict`; strict with `--trace-file` | PASS on this Linux host: probe reports Bubblewrap available, strict run succeeds; `--trace-file` refused with exit 2 |
|
||||
| §3 Tool compatibility | stable-only range `>=3.0.0,<4.0.0` on the beta core | PASS (expected rejection): `requires marqdo … this core is 3.0.0-beta.1` |
|
||||
|
||||
## Facts verified against the implementation
|
||||
|
||||
- Tool install is whole-bundle hashed and re-verified before dispatch; a
|
||||
tampered bundle, traversal entrypoint and reserved command are rejected.
|
||||
- `check --emit` writes Analysis v2 only after a successful check; `--refs` is
|
||||
an independent link validation and can delete a previous emit target on
|
||||
failure. The guide tells consumers to read the artifact only after exit 0.
|
||||
- Plugin calls are named-argument only; `--allow-plugin` matches the manifest
|
||||
`plugin.name`; artifact target triple must equal the host triple.
|
||||
- The provider helper is a CLI release artifact resolved only as a sibling; the
|
||||
provider package supplies `provider.json` + the C ABI library.
|
||||
- Extension selection records manifest/artifact identity in lock v4 and never
|
||||
grants execution by itself.
|
||||
- Analysis `producer.version` follows the product version; stdlib/package
|
||||
versions stay independent (`0.1.0`).
|
||||
|
||||
## Not executed / explicitly unverified
|
||||
|
||||
- HTTPS Git clone/fetch: the pure-library flow used a local repository; network
|
||||
authentication was not exercised. The 40/64-character lowercase rev rule and
|
||||
lock behaviour are code-tested.
|
||||
- macOS/Windows plugin, provider worker and strict paths: not executed; the
|
||||
release claims Linux x86_64 only and `COMPATIBILITY.md` marks them
|
||||
unsupported/experimental.
|
||||
- Provider wrong-target and kernel timeout/abnormal-exit variants: covered by
|
||||
the external conformance suite's digests/schema negatives and the spec, not
|
||||
by this specific manual run.
|
||||
|
||||
Verdict: the handbook and the developer pages are executable as written for the
|
||||
`3.0.0-beta.1` Linux x86_64 release; no unresolved BLOCKER/MAJOR guide defect
|
||||
remains from the independent audit.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Beta release gates — `3.0.0-beta.1`
|
||||
|
||||
Date: 2026-11-22. Product: `3.0.0-beta.1`. Release SHA:
|
||||
`2c7c4f31e7a388d3fcfa717a77067e696ed13854` (tag `v3.0.0-beta.1`). Platform: Linux x86_64 (glibc).
|
||||
Profile: **beta** (`tools/ci/release_evidence.py --profile beta`).
|
||||
|
||||
This document records the exact beta gate evidence for the tagged SHA. The
|
||||
machine-readable aggregate is
|
||||
[`ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
|
||||
(decision `BETA_RELEASE_CANDIDATE`). The stable profile is stricter and is not
|
||||
applied here.
|
||||
|
||||
## Release artifacts
|
||||
|
||||
```text
|
||||
source SHA 2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||
archive marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
archive sha256 507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317
|
||||
archive size 4701997 bytes
|
||||
marqdo sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f
|
||||
worker sha256 7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2
|
||||
target x86_64-unknown-linux-gnu
|
||||
toolchain rustc/cargo 1.100.0 (Cargo.lock committed, --locked)
|
||||
```
|
||||
|
||||
The archive contains `marqdo` and `marqdo-provider-worker` in the same
|
||||
directory, `RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`,
|
||||
licenses, README/CHANGELOG/COMPATIBILITY, `spec/`, `docs/developers/`,
|
||||
`examples/` (with host-built plugin/provider artifacts) and
|
||||
`tests/consumers/`.
|
||||
|
||||
## Gate results
|
||||
|
||||
| Gate | Result | Evidence |
|
||||
|---|---|---|
|
||||
| Source hygiene | PASS | clean tree at tagged SHA; `Cargo.lock` committed; `--locked` build |
|
||||
| fmt / clippy / tests | PASS | same-SHA Woodpecker pipeline #37 (test step); local gate log |
|
||||
| Release build (CLI + worker) | PASS | both binaries in archive, same target; `RELEASE_INFO.json` |
|
||||
| Same-SHA Linux CI | PASS | https://ci.cflmy.cn/repos/1/pipeline/37 (commit `2c7c4f31e7a388d3fcfa717a77067e696ed13854`) |
|
||||
| Frozen-binary external conformance | PASS | [`extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json), 7/7 categories, CLI hash unchanged, fixture repo `e22ec95b097477ae9c19d3bfe19048af5337b806` |
|
||||
| Clean-install smoke | PASS | `tools/release/smoke.py` from the archive only; see below |
|
||||
| Version compatibility | PASS | prerelease Tool/project SemVer tests + `project.marqdo` fail-closed tests in pipeline #37 and local `cargo test` |
|
||||
| Strict policy (G3) | PASS | same-SHA disposable-VM lane: [`2026-11-22-strict-gc-2c7c4f31.md`](2026-11-22-strict-gc-2c7c4f31.md), `outcome: PASS`, uid 1000, `container: none` |
|
||||
| Performance (G4) | WARN (Beta-approved) | 9/9 correctness-verified on fixed Woodpecker agent 1, shared powersave host: [`2026-11-22-perf-woodpecker-agent-1-run38.md`](2026-11-22-perf-woodpecker-agent-1-run38.md) |
|
||||
| Support matrix | PASS | Linux x86_64 supported; macOS/Windows explicitly experimental/unsupported: [`../../COMPATIBILITY.md`](../../COMPATIBILITY.md) |
|
||||
| Third-party guide validation | PASS | [`2026-11-22-beta-guide-validation.md`](2026-11-22-beta-guide-validation.md) and its log |
|
||||
|
||||
## Clean-install smoke (archive only)
|
||||
|
||||
Executed outside the source tree on the extracted archive:
|
||||
|
||||
```text
|
||||
smoke: archive version 3.0.0-beta.1, source 2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||
smoke: strict available (bubblewrap 0.11.1 ...) and exercised
|
||||
smoke: PASS
|
||||
```
|
||||
|
||||
Covered: `.sha256` verification; `RELEASE_INFO.json`/`SOURCE_SHA` and binary
|
||||
hashes; offline `--version`/`--help`; check/run/call; Analysis v2 + Trace v2
|
||||
consumers (with schema validation when `jsonschema` is installed); Tool
|
||||
install/dispatch; native and worker plugin transports; foreign kernel; Provider
|
||||
v2 through the shipped worker (positive read, unauthorized denial, missing
|
||||
helper `ext.worker_unavailable`); pure mode; strict when the host supports it
|
||||
(otherwise the tested fail-closed refusal). The CI pipeline also builds and
|
||||
smoke-tests its own archive in the build step, so the packaging procedure is
|
||||
reproduced by CI, while the **published** archive is the locally built one whose
|
||||
hashes are bound above.
|
||||
|
||||
## Explicit gaps (allowed for beta)
|
||||
|
||||
- macOS/Windows release artifacts, native plugin/provider ABI and provider
|
||||
worker: not claimed and not built; the Windows lane is a compile gate only.
|
||||
- Strict L2, Wasm, uv/npm auto-environments, package registry, JIT, built-in
|
||||
Knowledge/Proof/View: unsupported/deferred (see `KNOWN_LIMITATIONS.md`).
|
||||
- G4 is a Beta-only WARN on a shared powersave agent, not a stable performance
|
||||
guarantee.
|
||||
- No LTS or stable `3.0.0` claim; beta breakage is allowed with changelog notes.
|
||||
|
||||
## Approval
|
||||
|
||||
The owner directed execution of the `3.0.0-beta.1` prerelease per
|
||||
[`MARQDO_3_0_PRERELEASE_PLAN.md`](../MARQDO_3_0_PRERELEASE_PLAN.md) in this
|
||||
session (2026-11-22). The tag is created only from the SHA above after every
|
||||
gate in this table is recorded; the G4 Beta-only WARN and the Linux-only beta
|
||||
support scope are explicitly approved as prerelease exceptions, not stable
|
||||
exceptions. Rollback and withdrawal rules are in
|
||||
[`releasing.md`](../releasing.md) §7.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Execution Events v1 — local implementation evidence
|
||||
|
||||
- **Date:** 2026-11-22
|
||||
- **Scope:** RFC-OBS-0001 P0 (OBS-00..03) and P1 (OBS-04..05); OBS-06/P2
|
||||
memory metadata deliberately deferred.
|
||||
- **Source SHA:** `1d3dca7c1832eb9468e96384d9805a3812a303e4` (post-beta tree;
|
||||
the tagged beta is `2c7c4f31e7a388d3fcfa717a77067e696ed13854` and does **not**
|
||||
contain this feature).
|
||||
- **Normative contract:** [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md),
|
||||
schema `spec/schemas/execution-events-v1.schema.json`, decision
|
||||
[ADR-0059](../adr/0059-runtime-observability-and-execution-events.md).
|
||||
|
||||
This file records commands actually executed on Linux x86_64 with Rust
|
||||
1.100.0. It is local evidence, not a same-SHA CI or published-release claim.
|
||||
|
||||
## Static and test gate
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS: 630 passed, 0 failed, 2 ignored
|
||||
cargo test -p marqdo-cli --test execution_events PASS: 14 passed
|
||||
cargo test -p marqdo-host --test observation PASS: 8 passed
|
||||
cargo test -p marqdo-runtime --test observation PASS: 4 passed
|
||||
cargo test -p marqdo-cli --test docs_consistency PASS
|
||||
cargo test -p marqdo-cli --test architecture_boundaries PASS
|
||||
```
|
||||
|
||||
The `execution_events` suite covers: pure JSONL envelope, contiguous `seq`,
|
||||
terminal ordering, byte-exact base64 reconstruction (including invalid UTF-8
|
||||
and multi-byte text), live `READY` delivery while the child is still running,
|
||||
prepare/runtime terminals, exact value selection and text redaction, Trace v2
|
||||
coexistence/shared run id, structural-budget truncation, output-budget
|
||||
fail-closed, the checked-in JSON Schema fixtures, the structure fixture, and
|
||||
broken-pipe failure (`observe.transport_failed`, non-zero exit), native-plugin
|
||||
fail-closed, and observed values never entering Trace v2.
|
||||
|
||||
## Frozen-binary black-box consumer
|
||||
|
||||
A local release archive was built from the source SHA and the independent
|
||||
Python consumer was run against the extracted binary's live stream:
|
||||
|
||||
```text
|
||||
archive: dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
archive sha256: d55dd4b3cc3be6d2fec394e870af07fac0dd30bf5eb29f91a73a565ea6381088
|
||||
extracted marqdo sha256 before: ce0da79024b5677edb04328e56e9d873732b870fd0c3cbd74340c5de6efb073d
|
||||
extracted marqdo sha256 after: ce0da79024b5677edb04328e56e9d873732b870fd0c3cbd74340c5de6efb073d (unchanged)
|
||||
run: marqdo run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl
|
||||
run exit: 0
|
||||
consumer: execution events consumer: ok: 297 events, terminal=run.completed, stdout+stderr bytes=11
|
||||
```
|
||||
|
||||
The stream began with `stream.opened` (`seq 0`), contained exactly one
|
||||
`run.started`, emitted the two committed stdout chunks before the terminal
|
||||
event, and ended with `run.completed` (`{"type":"int","decimal":"10"}`).
|
||||
Concatenated chunk bytes were `START\nDONE\n`, equal to a normal run.
|
||||
|
||||
`tools/release/smoke.py --archive ... --skip-strict` on the same archive:
|
||||
`smoke: PASS` (includes the new live-stream consumer step and `run --help`
|
||||
protocol option check). The disposable-VM strict lane was not run because this
|
||||
environment is not a disposable VM; in any case `--mode strict` explicitly
|
||||
refuses `--event-stream` (structured `run.rejected`, no downgrade).
|
||||
|
||||
## Non-claims
|
||||
|
||||
- Not included in the `v3.0.0-beta.1` archive and no new release tag was
|
||||
created.
|
||||
- No macOS/Windows native verification for this option.
|
||||
- No memory metadata/value of containers/handles, no debugger, stepping,
|
||||
breakpoints, time travel, raw memory read or bidirectional debug protocol.
|
||||
- No performance gate; observation is off by default and the disabled path does
|
||||
not build observation events, but this file makes no percentage claim.
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"schema": "marqdo.perf.v2",
|
||||
"source_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"platform_id": "woodpecker-agent-1",
|
||||
"environment_approved": true,
|
||||
"binary": {
|
||||
"path": "target/release/marqdo",
|
||||
"sha256": "sha256:c6ea645ff13e594aa290a1816534351ee25f351962740a3fe5acfddd380ef160",
|
||||
"profile": "release",
|
||||
"cargo_lock_sha256": "sha256:eb9f58c3091c8e95907d7e9ef6d18915c83791826ef00307e818b8ee82f1bb1b",
|
||||
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09)\nbinary: rustc\ncommit-hash: 0ef1bc386059596dada8fb65b50425aab2ea637a\ncommit-date: 2026-11-09\nhost: x86_64-unknown-linux-gnu\nrelease: 1.100.0\nLLVM version: 23.1.5",
|
||||
"cargo": "cargo 1.100.0 (3acc79c0c 2026-11-05)"
|
||||
},
|
||||
"environment": {
|
||||
"uname": "Linux-7.0.0-31-generic-x86_64-with-glibc2.36",
|
||||
"kernel": "7.0.0-31-generic",
|
||||
"machine": "x86_64",
|
||||
"cpu_model": "12th Gen Intel(R) Core(TM) i7-12700H",
|
||||
"governor": "powersave",
|
||||
"loadavg_start": "5.90 2.76 1.36 1/2879 2894",
|
||||
"cpu_list": "0",
|
||||
"python": "3.11.2",
|
||||
"loadavg_end": "5.90 2.76 1.36 1/2879 2894"
|
||||
},
|
||||
"recipe": {
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"timeout_seconds": 120.0
|
||||
},
|
||||
"workloads": [
|
||||
{
|
||||
"name": "hello-check",
|
||||
"kind": "check",
|
||||
"source": "examples/hello.mq.md",
|
||||
"argv": [
|
||||
"check",
|
||||
"examples/hello.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 4.8196,
|
||||
"p95_ms": 4.9531,
|
||||
"mad_ms": 0.1178,
|
||||
"min_ms": 4.5112,
|
||||
"max_ms": 4.9564,
|
||||
"cpu_user_ms_median": 2.425,
|
||||
"cpu_sys_ms_median": 1.935,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "http-parser",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/71-http-parser.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/71-http-parser.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 4.7873,
|
||||
"p95_ms": 4.9299,
|
||||
"mad_ms": 0.1333,
|
||||
"min_ms": 4.4691,
|
||||
"max_ms": 4.9565,
|
||||
"cpu_user_ms_median": 3.262,
|
||||
"cpu_sys_ms_median": 1.073,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "table-sort",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/65-table-sort-stdlib.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/65-table-sort-stdlib.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 2.3621,
|
||||
"p95_ms": 2.4414,
|
||||
"mad_ms": 0.0289,
|
||||
"min_ms": 2.2494,
|
||||
"max_ms": 2.4731,
|
||||
"cpu_user_ms_median": 0.499,
|
||||
"cpu_sys_ms_median": 1.4755,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "factorial-run",
|
||||
"kind": "call",
|
||||
"source": "examples/factorial.mq.md",
|
||||
"argv": [
|
||||
"call",
|
||||
"examples/factorial.mq.md",
|
||||
"\u6570\u5b66.\u9636\u4e58",
|
||||
"--arg",
|
||||
"n=5",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 2.4061,
|
||||
"p95_ms": 2.4723,
|
||||
"mad_ms": 0.0379,
|
||||
"min_ms": 2.3286,
|
||||
"max_ms": 2.4763,
|
||||
"cpu_user_ms_median": 0.0,
|
||||
"cpu_sys_ms_median": 1.794,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "allocator-free-list",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 4.501,
|
||||
"p95_ms": 4.5861,
|
||||
"mad_ms": 0.0213,
|
||||
"min_ms": 4.435,
|
||||
"max_ms": 4.5908,
|
||||
"cpu_user_ms_median": 2.7075,
|
||||
"cpu_sys_ms_median": 1.5475,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "json-parser",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/62-json-array-parser.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/62-json-array-parser.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 6.6775,
|
||||
"p95_ms": 6.7354,
|
||||
"mad_ms": 0.0408,
|
||||
"min_ms": 6.5194,
|
||||
"max_ms": 6.7537,
|
||||
"cpu_user_ms_median": 4.5265,
|
||||
"cpu_sys_ms_median": 1.8105,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "stdlib-print-demo",
|
||||
"kind": "run",
|
||||
"source": "stdlib/demo.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"stdlib/demo.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 12.4718,
|
||||
"p95_ms": 13.6205,
|
||||
"mad_ms": 0.3838,
|
||||
"min_ms": 12.0072,
|
||||
"max_ms": 14.0983,
|
||||
"cpu_user_ms_median": 9.503,
|
||||
"cpu_sys_ms_median": 2.5135,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "matrix-multiply",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/70-matrix-multiply.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/70-matrix-multiply.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 2.3975,
|
||||
"p95_ms": 2.7386,
|
||||
"mad_ms": 0.0313,
|
||||
"min_ms": 2.3166,
|
||||
"max_ms": 2.8032,
|
||||
"cpu_user_ms_median": 1.002,
|
||||
"cpu_sys_ms_median": 1.0185,
|
||||
"max_rss_kb_median": 17232
|
||||
},
|
||||
{
|
||||
"name": "bytecode-vm",
|
||||
"kind": "run",
|
||||
"source": "tests/conformance/semantics/63-memory-bytecode-vm.mq.md",
|
||||
"argv": [
|
||||
"run",
|
||||
"tests/conformance/semantics/63-memory-bytecode-vm.mq.md",
|
||||
"--json"
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"warmups": 5,
|
||||
"samples": 20,
|
||||
"order_seed": "62bd903ba89d915a",
|
||||
"median_ms": 2.4187,
|
||||
"p95_ms": 3.4758,
|
||||
"mad_ms": 0.0627,
|
||||
"min_ms": 2.3327,
|
||||
"max_ms": 3.4983,
|
||||
"cpu_user_ms_median": 1.1695,
|
||||
"cpu_sys_ms_median": 1.141,
|
||||
"max_rss_kb_median": 17232
|
||||
}
|
||||
],
|
||||
"correctness": "VERIFIED",
|
||||
"status": "MEASURED",
|
||||
"baseline_comparison": []
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# G4 performance evidence — `3.0.0-beta.1`
|
||||
|
||||
Date: 2026-11-22. Source SHA: `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. Product: `3.0.0-beta.1`.
|
||||
Pipeline: Woodpecker manual pipeline #38
|
||||
(https://ci.cflmy.cn/repos/1/pipeline/38), successful. Report:
|
||||
[`2026-11-22-perf-woodpecker-agent-1-run38.json`](2026-11-22-perf-woodpecker-agent-1-run38.json)
|
||||
(schema `marqdo.perf.v2`).
|
||||
|
||||
## Environment (fixed node)
|
||||
|
||||
```text
|
||||
platform_id woodpecker-agent-1
|
||||
runner_kind Woodpecker Docker agent (agent_id 1)
|
||||
kernel 7.0.0-31-generic
|
||||
arch x86_64
|
||||
CPU 12th Gen Intel(R) Core(TM) i7-12700H
|
||||
cpuset / pinned CPU see report / 0
|
||||
governor powersave
|
||||
loadavg start 5.90 2.76 1.36 1/2879 2894
|
||||
source_sha 2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||
CI-built binary sha256:c6ea645ff13e594aa290a1816534351ee25f351962740a3fe5acfddd380ef160
|
||||
Cargo.lock sha256:eb9f58c3091c8e95907d7e9ef6d18915c83791826ef00307e818b8ee82f1bb1b
|
||||
rustc rustc 1.100.0 (0ef1bc386 2026-11-09)
|
||||
recipe {'warmups': 5, 'samples': 20, 'order_seed': '62bd903ba89d915a', 'timeout_seconds': 120.0}
|
||||
status MEASURED
|
||||
correctness VERIFIED
|
||||
```
|
||||
|
||||
## Results (p50 / p95 ms, MAD, RSS median KiB)
|
||||
|
||||
| Workload | p50 | p95 | MAD | RSS | Correctness |
|
||||
|---|---:|---:|---:|---:|---|
|
||||
| `hello-check` | 4.8196 | 4.9531 | 0.1178 | 17232 | VERIFIED |
|
||||
| `http-parser` | 4.7873 | 4.9299 | 0.1333 | 17232 | VERIFIED |
|
||||
| `table-sort` | 2.3621 | 2.4414 | 0.0289 | 17232 | VERIFIED |
|
||||
| `factorial-run` | 2.4061 | 2.4723 | 0.0379 | 17232 | VERIFIED |
|
||||
| `allocator-free-list` | 4.5010 | 4.5861 | 0.0213 | 17232 | VERIFIED |
|
||||
| `json-parser` | 6.6775 | 6.7354 | 0.0408 | 17232 | VERIFIED |
|
||||
| `stdlib-print-demo` | 12.4718 | 13.6205 | 0.3838 | 17232 | VERIFIED |
|
||||
| `matrix-multiply` | 2.3975 | 2.7386 | 0.0313 | 17232 | VERIFIED |
|
||||
| `bytecode-vm` | 2.4187 | 3.4758 | 0.0627 | 17232 | VERIFIED |
|
||||
|
||||
All 9 workloads reported `MEASURED` with `VERIFIED` correctness (immutable
|
||||
expected wire digests checked before timing). `baseline_comparison` is empty:
|
||||
this is the first fixed-node baseline for the beta release, so there is no
|
||||
regression comparison to claim.
|
||||
|
||||
## Gate classification
|
||||
|
||||
`tools/ci/release_evidence.py --profile beta` records `performance=WARN` for this
|
||||
release, not `PASS`: the node is a shared Docker container on a powersave host
|
||||
(loadavg ~5.9), not a dedicated performance machine, and this is a first
|
||||
baseline. The maintainer-approved Beta-only WARN policy and its limits are in
|
||||
[`MARQDO_3_0_PRERELEASE_PLAN.md`](../MARQDO_3_0_PRERELEASE_PLAN.md) §3.1 gate 6.
|
||||
The numbers are valid only for same-`platform_id` regression tracking; they must
|
||||
not be compared with another machine, container or QEMU/TCG run.
|
||||
@@ -0,0 +1,198 @@
|
||||
# RFC-EXT-0003 (issue #3) — core/extension boundary evidence
|
||||
|
||||
Status: **executed evidence, post-`3.0.0-beta.1` tree.**
|
||||
Audit baseline: `eeea01d672c07b6be7d6444031d1619309dc88ab` (issue #3).
|
||||
Frozen decisions: ADR-0060, ADR-0061, ADR-0062, ADR-0063.
|
||||
This file is the executed companion to `docs/STATUS.md` §0.6 and the ADRs; the
|
||||
plan text in the issue never counts as evidence.
|
||||
|
||||
## 1. Status matrix (audit item → implementation → evidence)
|
||||
|
||||
| Item | Status | Implementation | Executed evidence |
|
||||
|---|---|---|---|
|
||||
| H-06 sibling heading inheritance | **FIXED** | `build_units` pops `level >= current` before deriving the inherited mode (`crates/marqdo-frontend/src/units.rs`) | `units` matrix (12 tests), `conformance_semantics` fixtures 22/23, black-box `heading_inheritance` (check --emit/run/call) |
|
||||
| H-08 stdlib in the release archive | **FIXED** | `package.py` stages and digest-verifies `stdlib/`; `RELEASE_INFO.json.stdlib`; release discovery no longer falls back to the compile-time tree; `smoke.py` re-verifies and fails closed | `tools/ci/test_release_archive.py` (5 tests), archive + smoke + independent `ubuntu:24.04` container runs in §5–§6 |
|
||||
| H-04 provider reserved core kinds | **FIXED** | single `marqdo_host::CORE_RESOURCE_KINDS` used by CLI manifest validation and all trusted host registration paths | `resource_streams` (34 tests incl. all six names/kinds), `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
|
||||
| H-01 math domain API removed | **REMOVED (breaking, announced)** | five builtins/HostOps/runtime arms/`marqdo-math` deleted; pure package + optional ABI backend; `Formula` inert; `math.compute` stays a capability category | `math_library` black-box (pure package call = 6, ABI backend = 42, no grant = `permission.denied`, removed `math.eval` = `symbol.unknown`), `conformance_semantics` 74/75, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
|
||||
| H-03 `resource_request` ownership | **REVIEWED + GATED** | full owner/classification table in `docs/architecture/resource-operations.md`; exact reviewed allowlist pinned in `architecture_boundaries::resource_request_operation_allowlist_is_reviewed`; new domain ops forbidden (ADR-0062) | `architecture_boundaries` gate test passes on the SQL-free allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) |
|
||||
| H-05/H-07/H-13 heading annotations | **PROPOSED, NOT IMPLEMENTED** | closed Core Modes classified; metadata-only Heading Annotations v1 contract + sidecar/Analysis-v3 decision in ADR-0060 and `spec/heading-annotations-v1.md`; parser still rejects `@foo` with `sem.invalid_mode_marker` | `tests/negative/01-invalid-mode-marker-case.expected.json`; no annotation code exists to test — future T-ANNO rows are explicitly FUTURE |
|
||||
| H-02 foreign boundary | **F-A RETAINED, F-B DEFERRED** | one-shot permission-gated `foreign.run/call` + dynamic `KernelRegistry` kept, no new language-specific builtin/HostOp; ADR-0063 and `spec/foreign.md` §8 | existing `marqdo-foreign/tests/kernels.rs`, CLI kernel/foreign tests and `smoke.py` foreign case unchanged |
|
||||
| H-11 `math.compute` | **KEPT AS CAPABILITY CATEGORY** | still in `CORE_CAPABILITIES`/`Capabilities::math`; no core solver behind it; ABI backend example requests it | `math_library` ABI backend run (42), no-grant negative (`permission.denied`), capability tests |
|
||||
|
||||
## 2. Code-path recheck versus the audit SHA
|
||||
|
||||
- `crates/marqdo-frontend/src/units.rs`: the audit's `inherited`-before-pop order is
|
||||
gone; pop happens first. Covered by the sibling cases and the three entry points.
|
||||
- `crates/cli/src/stdlib.rs::discover`: the compile-time source fallback is now
|
||||
behind `#[cfg(debug_assertions)]`; a release build only loads an explicit
|
||||
`MARQDO_STDLIB_DIR` or the executable-sibling `stdlib/`; the new
|
||||
`sibling_stdlib_is_found_without_environment_override` test covers discovery.
|
||||
- `tools/release/package.py::stage`: `copy_tree(STDLIB, stage_dir / "stdlib")`,
|
||||
`verify_stdlib()` and `RELEASE_INFO.stdlib` are present; both digests are computed
|
||||
identically to the runtime.
|
||||
- `crates/marqdo-host/src/host/providers.rs`: both the provider name and every
|
||||
declared kind are checked against the shared six-kind registry before the table is
|
||||
mutated (previously only `""`/`stdio`/`file`).
|
||||
- `crates/marqdo-host/src/host.rs::resource_request`: reviewed allowlist from the
|
||||
audit is `process.run`, `regex.match`, `regex.captures`, `compress.gzip`,
|
||||
`compress.gunzip`, `random.bytes`, `env.get`, `clock.now`, `fs.{read_at,append,walk,exists,metadata,list,mkdir,remove,rename}`.
|
||||
- `crates/marqdo-ir/src/builtins.rs`, `marqdo-runtime`, `marqdo-host`: no `math.*`
|
||||
remaining; `crates/marqdo-math` directory is deleted and absent from the workspace.
|
||||
|
||||
## 3. Targeted tests (executed)
|
||||
|
||||
```text
|
||||
cargo test -p marqdo-frontend PASS (47)
|
||||
cargo test -p marqdo-frontend units PASS (12; new sibling matrix)
|
||||
cargo test -p marqdo-cli --test heading_inheritance PASS (4)
|
||||
cargo test -p marqdo-cli --test conformance_semantics PASS (1; 22/23/74/75 goldens)
|
||||
cargo test -p marqdo-cli --test math_library PASS (2)
|
||||
cargo test -p marqdo-cli --test callable_resolution PASS (14)
|
||||
cargo test -p marqdo-cli --test properties PASS (2)
|
||||
cargo test -p marqdo-cli --test integration_cli PASS (23)
|
||||
cargo test -p marqdo-cli --test negative PASS (3)
|
||||
cargo test -p marqdo-host PASS (all suites; resource_streams 34)
|
||||
cargo test -p marqdo-cli provider_manifest PASS (9)
|
||||
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS (28)
|
||||
```
|
||||
|
||||
`test result: FAILED` was observed only for the `docs_consistency` link
|
||||
check before this file existed; the full gate in §4 was rerun after creating it.
|
||||
|
||||
## 4. Full gate (executed, rerun after this evidence file exists)
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS (counts below)
|
||||
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS (28)
|
||||
```
|
||||
|
||||
Counts: **586 passed, 0 failed, 2 ignored** across the workspace; Python
|
||||
`tools/ci` suite: **28 passed**.
|
||||
|
||||
### 4.1 Final full-gate counts
|
||||
|
||||
```text
|
||||
cargo test --workspace --locked PASS: 586 passed, 0 failed, 2 ignored
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS: 28 passed
|
||||
```
|
||||
|
||||
## 5. Release archive (executed after the implementation commit)
|
||||
|
||||
```text
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
python3 tools/release/package.py --source-sha <SHA> --version 3.0.0-beta.1
|
||||
python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
```
|
||||
|
||||
`RELEASE_INFO.json` records:
|
||||
|
||||
```text
|
||||
source_sha a67f344b6b022ad2c4caefbc62258fa49e7af105
|
||||
binaries.marqdo.sha256 e684ed266494ec15db9163aaecbc88e02b4dd5002bf340fbf1ad91ecfc197e18
|
||||
binaries.marqdo-provider-worker.sha256 7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2
|
||||
stdlib.name / version marqdo-stdlib / 0.1.0
|
||||
stdlib.tree_digest sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713
|
||||
stdlib.aliases_digest sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb
|
||||
stdlib.file_count 42
|
||||
archive sha256 f52ace5463b90c9ce32462239bfc20aec282968ee3007a9fd5099610df204d88
|
||||
```
|
||||
|
||||
Smoke stdout (executed from the workspace tooling after the archive was built):
|
||||
|
||||
```text
|
||||
smoke: verified stdlib 0.1.0 tree=sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713 aliases=sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb files=42
|
||||
smoke: archive version 3.0.0-beta.1, source a67f344b6b022ad2c4caefbc62258fa49e7af105
|
||||
smoke: bundled stdlib missing -> fail-closed OK
|
||||
smoke: strict unsupported on this host; fail-closed refused
|
||||
smoke: PASS
|
||||
```
|
||||
|
||||
The missing-stdlib negative intentionally moves `stdlib/` aside; the run exits 1
|
||||
with `打印 requires the bundled stdlib print module` and never falls back to the
|
||||
source tree. Math library call printed `6`, ABI backend printed `42` with the grant
|
||||
and `permission.denied` without it, and removed `math.eval` was `symbol.unknown`.
|
||||
|
||||
## 6. Independent runtime container (executed)
|
||||
|
||||
`docker run --rm -v dist:/dist:ro ubuntu:24.04` extracts **only the archive** into
|
||||
a fresh directory (no source tree, no `/build`, no Cargo; Ubuntu 24.04, glibc 2.39)
|
||||
and runs:
|
||||
|
||||
```text
|
||||
./marqdo --version
|
||||
./marqdo --help
|
||||
./marqdo run examples/hello.mq.md
|
||||
./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json
|
||||
./marqdo call examples/math-library-demo.mq.md main
|
||||
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
|
||||
```
|
||||
|
||||
Result: **PASS**. Output:
|
||||
|
||||
```text
|
||||
marqdo 3.0.0-beta.1
|
||||
你好,Marqdo
|
||||
checked 2 module(s): ok
|
||||
6 # examples/math-library-demo.mq.md main (pure package)
|
||||
120 # examples/factorial.mq.md 阶乘 --arg n=5
|
||||
checked 1 module(s): ok # examples/stdlib-bundle.mq.md (std:io)
|
||||
sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713 # project.stdlib.digest in Analysis
|
||||
no-build-dir
|
||||
```
|
||||
|
||||
Warnings in that run were the pre-existing `sem.inferred_signature` warnings
|
||||
for examples without `params(...)`; they are not stdlib errors. The container has
|
||||
no Python, Cargo, C compiler, source checkout or `/build` directory and the archive
|
||||
binary (GLIBC symbols ≤ 2.39) ran on Ubuntu 24.04 / glibc 2.39, so this is a real
|
||||
archive-only stdlib test, not a dynamic-linker artefact.
|
||||
|
||||
## 7. External frozen-binary conformance (executed)
|
||||
|
||||
`marqdo-extension-conformance` (separate repository) is run with the
|
||||
unchanged release binary:
|
||||
|
||||
```bash
|
||||
python3 tools/ci/verify_extension_contracts.py --cli <release-marqdo> \
|
||||
--fixtures /root/work/marqdo-extension-conformance \
|
||||
--tested-sha <SHA> --out docs/evidence/extension/<SHA>/manifest.json
|
||||
```
|
||||
|
||||
Result: **PASS 7/7 categories, zero failures, zero unverified.**
|
||||
Manifest: [`extension/b9c41564aeeadd2b7b202256b866bc13f995cb36/manifest.json`](extension/b9c41564aeeadd2b7b202256b866bc13f995cb36/manifest.json).
|
||||
|
||||
```text
|
||||
tested_sha b9c41564aeeadd2b7b202256b866bc13f995cb36
|
||||
cli_binary_sha256 e684ed266494ec15db9163aaecbc88e02b4dd5002bf340fbf1ad91ecfc197e18
|
||||
fixture_repo_sha e22ec95b097477ae9c19d3bfe19048af5337b806
|
||||
results callable_registry, plugin_worker, foreign_kernel,
|
||||
resource_provider_cli, package_pinned_git,
|
||||
tool_analysis_consumer, negative_security = PASS
|
||||
failures []
|
||||
unverified []
|
||||
```
|
||||
|
||||
The CLI binary hash equals `RELEASE_INFO.json.binaries.marqdo.sha256` from the
|
||||
release archive (§5), i.e. the frozen binary exercised by the independent
|
||||
repository is the shipped one; the verifier also hashes it before and after the
|
||||
suite and fails if it changes. `tested_sha` is the evidence/tooling commit after the
|
||||
implementation commit `a67f344`; the two commits differ only in smoke-tooling and
|
||||
documentation files, not in any Rust crate or example that contributes to the
|
||||
binary/archive. The suite's own source tree was clean and the fixture repository
|
||||
was at `e22ec95…`; generated fixture artifacts were restored after the run.
|
||||
|
||||
## 8. Explicit deferrals / not claimed
|
||||
|
||||
- Heading annotations are **Proposed only**; no manifest loader, sidecar, Analysis
|
||||
v3, `annotation.unknown`, or parser change has shipped (target `3.1.x`).
|
||||
- Foreign F-B removal is deferred; `foreign.*` remains the controlled F-A primitive.
|
||||
- No compatibility parser for `math.*`, no second Markdown→IR mapping, no built-in
|
||||
View/Notebook, no AI/Quantum/Math `HostOp` was added.
|
||||
- `math.compute` promises no solver; regex/compress remain host-held services, not a
|
||||
general extension mechanism.
|
||||
- No stable tag/release was created by this work; platform claim stays Linux x86_64.
|
||||
- Not claimed/missing: full Math API/CAS, persistent Foreign sessions, Windows/macOS
|
||||
native gates, strict L2, performance improvement.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"schema": "marqdo.strict-evidence.v1",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"tested_sha_source": "operator-env",
|
||||
"tested_sha_verified": false,
|
||||
"source_archive_sha256": "sha256:d5b8219dd83666777eeba12c38df23c96f38487ba1cdd387e920cca31f61597e",
|
||||
"run": {
|
||||
"command": "./tests/security/run-lane.sh",
|
||||
"outcome": "PASS",
|
||||
"runner_kind": "disposable-vm",
|
||||
"run_url": "",
|
||||
"runner_image_sha256": "sha256:7b90593f5532b49b7e3fe3d2743f0d1f0d822e5b07cebcd8e00c0df8069ecab9",
|
||||
"lane_log": "/home/dev/evidence-2c7c4f31e7a388d3fcfa717a77067e696ed13854-b/gc-lane.log",
|
||||
"started_utc": "2026-11-21T18:49:02Z",
|
||||
"finished_utc": "2026-11-21T18:49:23Z"
|
||||
},
|
||||
"environment": {
|
||||
"uname": "Linux-7.0.0-43-generic-x86_64-with-glibc2.43",
|
||||
"kernel": "7.0.0-43-generic",
|
||||
"machine": "x86_64",
|
||||
"cgroup2": "cgroup2 cgroup2 rw,nsdelegate,memory_recursiveprot,memory_hugetlb_accounting",
|
||||
"container": "none",
|
||||
"uid": 1000,
|
||||
"user": "dev",
|
||||
"root": false,
|
||||
"bwrap_version": "bubblewrap 0.11.1",
|
||||
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09)",
|
||||
"cargo": "cargo 1.100.0 (3acc79c0c 2026-11-05)",
|
||||
"python": "3.14.4",
|
||||
"cc": [
|
||||
"cc (Ubuntu 15.2.0-16ubuntu1) 15.2.0"
|
||||
],
|
||||
"source_archive_sha256_matches": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# G-C strict-isolation evidence — `3.0.0-beta.1`
|
||||
|
||||
Date: 2026-11-22. Product: `3.0.0-beta.1`. Tested SHA:
|
||||
`2c7c4f31e7a388d3fcfa717a77067e696ed13854` (source archive
|
||||
`sha256:d5b8219dd83666777eeba12c38df23c96f38487ba1cdd387e920cca31f61597e`).
|
||||
Machine-readable report:
|
||||
[`2026-11-22-strict-evidence-2c7c4f31e7a388d3fcfa717a77067e696ed13854.json`](2026-11-22-strict-evidence-2c7c4f31e7a388d3fcfa717a77067e696ed13854.json);
|
||||
lane log:
|
||||
[`2026-11-22-strict-gc-2c7c4f31e7a388d3fcfa717a77067e696ed13854.log`](2026-11-22-strict-gc-2c7c4f31e7a388d3fcfa717a77067e696ed13854.log).
|
||||
|
||||
This is **local disposable-VM evidence**, not a remote self-hosted security-lane
|
||||
URL. It is the same-SHA G3 evidence the beta gate requires; the release notes
|
||||
must not call it a remote CI PASS.
|
||||
|
||||
## Environment
|
||||
|
||||
```text
|
||||
runner disposable QEMU/TCG VM (no KVM), fresh qcow2 overlay
|
||||
base image ubuntu-26.04 cloud image sha256:7b90593f5532b49b7e3fe3d2743f0d1f0d822e5b07cebcd8e00c0df8069ecab9
|
||||
guest Ubuntu 26.04.1, kernel 7.0.0-43-generic x86_64
|
||||
container none (systemd-detect-virt --container)
|
||||
user dev, uid 1000, root=false
|
||||
cgroup2 rw,nsdelegate,memory_recursiveprot,memory_hugetlb_accounting
|
||||
bubblewrap 0.11.1 (packaged bwrap-userns-restrict AppArmor profile)
|
||||
rustc/cargo 1.100.0 / 1.100.0
|
||||
source verification archive sha256 checked in the guest before extraction
|
||||
```
|
||||
|
||||
The guest was booted from a pinned base image with a read-only build-cache
|
||||
backing disk and a **fresh writable overlay per SHA**; the prior test source was
|
||||
removed and the release source archive was verified and extracted under
|
||||
`~/marqdo-<sha>`. The lane never ran as root.
|
||||
|
||||
## Result
|
||||
|
||||
```text
|
||||
./tests/security/run-lane.sh
|
||||
adversarial helper matrix: 7 passed; 0 failed
|
||||
strict mechanism probe: available (bubblewrap 0.11.1 ...)
|
||||
positive CLI: run / call / multi-module / strict --json PASS
|
||||
strict resource boundary (file/tcp refused) PASS
|
||||
all external-execution flags refused (exit 2) PASS
|
||||
@knowledge payloads stay inert PASS
|
||||
forged MARQDO_STRICT_ACTIVE marker rejected (text + JSON) PASS
|
||||
G-C security lane: PASS
|
||||
```
|
||||
|
||||
The seven adversarial cases are the `marqdo-sandbox` security tests:
|
||||
unprivileged/namespaced child identity, host read denied while the project is
|
||||
readable, writes denied outside/into the read-only project, proc/privilege
|
||||
escape denied, network denied, fd/process rlimits, memory/cpu/output limits.
|
||||
A skipped test fails the lane (`MARQDO_REQUIRE_STRICT_SECURITY=1`).
|
||||
|
||||
## Scope and limits
|
||||
|
||||
- Evidence is for the exact tested SHA and this disposable VM only. A root,
|
||||
container-only or TCG timing run is never promoted to a security or
|
||||
performance claim.
|
||||
- strict is Linux L1 only (pure language + native Math). strict L2
|
||||
(Worker/Foreign/Provider) is unsupported and the flags are refused.
|
||||
- rlimits are used instead of cgroup-v2 accounting; the network is denied by a
|
||||
network namespace rather than a seccomp allowlist; filesystem TOCTOU is
|
||||
reduced by read-only mounts but not formally proven against a racing host
|
||||
user.
|
||||
- The VM is not a performance node; do not read these timings as G4.
|
||||
- The release support claim remains Linux x86_64; macOS/Windows strict is
|
||||
fail-closed and unclaimed.
|
||||
@@ -0,0 +1,32 @@
|
||||
== adversarial helper matrix ==
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.35s
|
||||
Running tests/security_linux.rs (target/debug/build/marqdo-sandbox/b77b1d79feca4316/out/security_linux-b77b1d79feca4316)
|
||||
|
||||
running 7 tests
|
||||
test strict_child_cannot_escape_via_proc_or_privileges ... ok
|
||||
test strict_child_cannot_reach_the_network ... ok
|
||||
test strict_child_cannot_read_host_files_but_reads_the_project ... ok
|
||||
test strict_child_cannot_write_outside_or_into_the_project ... ok
|
||||
test strict_child_identity_is_unprivileged_and_namespaced ... ok
|
||||
test strict_supervisor_enforces_fd_and_process_limits ... ok
|
||||
test strict_supervisor_enforces_memory_cpu_and_output_limits ... ok
|
||||
|
||||
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 7.65s
|
||||
|
||||
== build CLI ==
|
||||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.54s
|
||||
strict mechanism: bubblewrap 0.11.1 (user/mount/PID/net/UTS/IPC namespaces + no-new-privs + rlimits)
|
||||
== positive CLI contract ==
|
||||
warning[sem.inferred_signature]: /home/dev/marqdo-2c7c4f31e7a388d3fcfa717a77067e696ed13854/examples/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
|
||||
## @exec 阶乘
|
||||
^
|
||||
warning[sem.inferred_signature]: /project/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
|
||||
## @exec 阶乘
|
||||
^
|
||||
== strict language resources are console-only ==
|
||||
== external-execution surfaces are refused ==
|
||||
== @knowledge payloads stay inert under strict ==
|
||||
== forged active marker is rejected ==
|
||||
G-C security lane: PASS
|
||||
strict evidence: /home/dev/evidence-2c7c4f31e7a388d3fcfa717a77067e696ed13854-b/strict-evidence.json
|
||||
strict evidence: /home/dev/evidence-2c7c4f31e7a388d3fcfa717a77067e696ed13854-b/strict-evidence.json
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"schema": "marqdo.release-gates.v1",
|
||||
"profile": "beta",
|
||||
"target_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z",
|
||||
"gates": {
|
||||
"linux": {
|
||||
"state": "PASS",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/37",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"strict_vm": {
|
||||
"state": "PASS",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "docs/evidence/2026-11-22-strict-gc-2c7c4f31.md",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"extension": {
|
||||
"state": "PASS",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "docs/evidence/extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"clean_install": {
|
||||
"state": "PASS",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "docs/evidence/2026-11-22-beta-release-gates.md",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"version_compat": {
|
||||
"state": "PASS",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/37",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"windows": {
|
||||
"state": "UNSUPPORTED",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "linux-only-beta-support-matrix",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"macos": {
|
||||
"state": "UNSUPPORTED",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "linux-only-beta-support-matrix",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
},
|
||||
"performance": {
|
||||
"state": "WARN",
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"run_url": "docs/evidence/2026-11-22-perf-woodpecker-agent-1-run38.md",
|
||||
"recorded_utc": "2026-11-21T18:52:29Z"
|
||||
}
|
||||
},
|
||||
"release_decision": "BETA_RELEASE_CANDIDATE",
|
||||
"reasons": []
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"schema": "marqdo.extension-evidence",
|
||||
"schema_version": 1,
|
||||
"tested_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||
"cli_binary_sha256": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||
"fixture_repo_sha": "e22ec95b097477ae9c19d3bfe19048af5337b806",
|
||||
"os": "linux",
|
||||
"arch": "x86_64",
|
||||
"results": {
|
||||
"callable_registry": "PASS",
|
||||
"plugin_worker": "PASS",
|
||||
"foreign_kernel": "PASS",
|
||||
"resource_provider_cli": "PASS",
|
||||
"package_pinned_git": "PASS",
|
||||
"tool_analysis_consumer": "PASS",
|
||||
"negative_security": "PASS"
|
||||
},
|
||||
"commands": [
|
||||
"python3 /root/work/marqdo-extension-conformance/tests/run_all.py (cwd=/root/work/marqdo-extension-conformance)"
|
||||
],
|
||||
"failures": [],
|
||||
"unverified": []
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"schema": "marqdo.extension-evidence",
|
||||
"schema_version": 1,
|
||||
"tested_sha": "3bc726790fdcee3694fc0b56adbcfd0c6c645275",
|
||||
"cli_binary_sha256": "c2b085ccb143292084d2202becc4927cff635fac7369cade2e125aa2537a5111",
|
||||
"fixture_repo_sha": "cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec",
|
||||
"os": "linux",
|
||||
"arch": "x86_64",
|
||||
"results": {
|
||||
"callable_registry": "PASS",
|
||||
"plugin_worker": "PASS",
|
||||
"foreign_kernel": "PASS",
|
||||
"resource_provider_cli": "PASS",
|
||||
"package_pinned_git": "PASS",
|
||||
"tool_analysis_consumer": "PASS",
|
||||
"negative_security": "PASS"
|
||||
},
|
||||
"commands": [
|
||||
"python3 /tmp/tmp.iuUoU6thoZ/fixtures/tests/run_all.py (cwd=/tmp/tmp.iuUoU6thoZ/fixtures)"
|
||||
],
|
||||
"failures": [],
|
||||
"unverified": [],
|
||||
"provider_worker_sha256": "7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2",
|
||||
"reference_applications": {
|
||||
"HTTP status, POST and bounded framing": "PASS",
|
||||
"URL validation and denial before connect": "PASS",
|
||||
"TLS with an explicit local trust root": "PASS",
|
||||
"live SSE visibility and caller close": "PASS",
|
||||
"socket read timeout and teardown": "PASS",
|
||||
"agent tool authority and two-turn provenance": "PASS"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"schema": "marqdo.extension-evidence",
|
||||
"schema_version": 1,
|
||||
"tested_sha": "b9c41564aeeadd2b7b202256b866bc13f995cb36",
|
||||
"cli_binary_sha256": "e684ed266494ec15db9163aaecbc88e02b4dd5002bf340fbf1ad91ecfc197e18",
|
||||
"fixture_repo_sha": "e22ec95b097477ae9c19d3bfe19048af5337b806",
|
||||
"os": "linux",
|
||||
"arch": "x86_64",
|
||||
"results": {
|
||||
"callable_registry": "PASS",
|
||||
"plugin_worker": "PASS",
|
||||
"foreign_kernel": "PASS",
|
||||
"resource_provider_cli": "PASS",
|
||||
"package_pinned_git": "PASS",
|
||||
"tool_analysis_consumer": "PASS",
|
||||
"negative_security": "PASS"
|
||||
},
|
||||
"commands": [
|
||||
"python3 /root/work/marqdo-extension-conformance/tests/run_all.py (cwd=/root/work/marqdo-extension-conformance)"
|
||||
],
|
||||
"failures": [],
|
||||
"unverified": []
|
||||
}
|
||||
@@ -30,6 +30,15 @@
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
},
|
||||
"provider_worker_sha256": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
},
|
||||
"reference_applications": {
|
||||
"type": "object",
|
||||
"minProperties": 1,
|
||||
"additionalProperties": { "const": "PASS" }
|
||||
},
|
||||
"fixture_repo_sha": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{40}$"
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# Marqdo CLI 3.0.0-beta.1
|
||||
|
||||
**Prerelease — not stable, not LTS.** This is the first public beta of the
|
||||
independent Marqdo toolchain. It claims **Linux x86_64 (glibc)** only.
|
||||
|
||||
- Source SHA: `2c7c4f31e7a388d3fcfa717a77067e696ed13854`
|
||||
- Tag: `v3.0.0-beta.1`
|
||||
- Archive: `marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz`
|
||||
- SHA256: `507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317`
|
||||
- `marqdo` SHA256: `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||
- `marqdo-provider-worker` SHA256: `7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2`
|
||||
- Toolchain: rustc/cargo 1.100.0; `Cargo.lock` committed, `--locked` build
|
||||
|
||||
## What this beta is
|
||||
|
||||
A Markdown-native language with its own Rust interpreter: `.mq.md` headings
|
||||
declare `@exec`/`@knowledge`, Strong/Emph/inline-`Code` carry one statement,
|
||||
keywords (`if`/`else`/`while`/`end`/`params`/`return`) decide control flow. A
|
||||
single static callable binding feeds `check`/`run`/`call`/`inspect`/Analysis.
|
||||
|
||||
Implemented and covered on the released source: RFC-LANG-0002, lock v4 and
|
||||
pinned Git packages, Analysis v2 / Trace v2, Tool Protocol v1, Plugin ABI v1
|
||||
(native + worker), Foreign kernels, Resource Provider v2 through the shipped
|
||||
worker, official stdlib aliases, and extension selection/lock identity.
|
||||
|
||||
## Breaking change
|
||||
|
||||
The source language is **not** compatible with pre-RFC Marqdo syntax
|
||||
(Strong=execute / Emph=return / list=branch/loop / quote=call). Old `.mq.md`
|
||||
sources are not executable; there is no `--legacy`, syntax switch or downgrade
|
||||
path. The normative contract is `spec/mapping.md` +
|
||||
`spec/expression.ebnf`; migration is a rewrite documented in
|
||||
`docs/migration/README.md`. The earlier `cflmy/marqdo` product line is a
|
||||
different architecture and is not compatible.
|
||||
|
||||
## Independent version axes
|
||||
|
||||
Product `3.0.0-beta.1` is independent from: Analysis v2, Trace v2, Tool v1,
|
||||
Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile
|
||||
`marqdo.md.v1`, the bundled stdlib package (`0.1.0`) and third-party package
|
||||
versions. `project.marqdo` and Tool `compatibility.marqdo` are enforced: beta
|
||||
cores require an explicit prerelease range such as
|
||||
`>=3.0.0-beta.1,<4.0.0`.
|
||||
|
||||
## Platform and security policy
|
||||
|
||||
- Supported: Linux x86_64 (glibc). The archive ships `marqdo` and
|
||||
`marqdo-provider-worker` together; the helper is resolved only as a sibling.
|
||||
- macOS/Windows: experimental, **not claimed**; the Windows lane is a
|
||||
cross-compile check only, and the C ABI plugin/provider/worker paths are not
|
||||
claimed there.
|
||||
- `strict`: Linux-only, Bubblewrap probe-gated L1 (pure language + Math), with
|
||||
same-SHA disposable-VM isolation evidence. Unsupported hosts fail closed;
|
||||
strict L2 (Worker/Foreign/Provider) is unsupported and refused. `project`
|
||||
mode and worker transports are not OS sandboxes.
|
||||
- Beta-only G4 `WARN`: 9/9 correctness-verified workloads on the fixed
|
||||
Woodpecker agent (shared/powersave host, recorded environment). Not a general
|
||||
performance guarantee.
|
||||
- Wasm, macOS/Windows provider worker, uv/npm auto-environments, a package
|
||||
registry, JIT, built-in Knowledge/Proof/View and platform installers are
|
||||
deliberately deferred.
|
||||
|
||||
## Install and verify
|
||||
|
||||
```bash
|
||||
sha256sum -c marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz.sha256
|
||||
tar -xzf marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
cd marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu
|
||||
./marqdo --version
|
||||
./marqdo run examples/hello.mq.md
|
||||
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
|
||||
```
|
||||
|
||||
The archive includes `RELEASE_INFO.json`, `SOURCE_SHA`,
|
||||
`KNOWN_LIMITATIONS.md`, specs, developer docs, runnable examples and public
|
||||
Analysis/Trace consumers. Checksums prove content integrity only; they are not
|
||||
a publisher signature.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Beta gates and exact same-SHA evidence:
|
||||
`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`
|
||||
- External frozen-binary conformance (7/7 categories):
|
||||
`docs/evidence/extension/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`
|
||||
- Strict isolation: `docs/evidence/2026-11-22-strict-gc-2c7c4f31.md`
|
||||
- Performance: `docs/evidence/2026-11-22-perf-woodpecker-agent-1-run38.md`
|
||||
- CI: https://ci.cflmy.cn/repos/1/pipeline/37 (same source SHA)
|
||||
- Third-party guide validation:
|
||||
`docs/evidence/2026-11-22-beta-guide-validation.md`
|
||||
|
||||
## Next
|
||||
|
||||
`3.0.0-beta.N` may break behavior with changelog notes. Stable `3.0.0` and any
|
||||
LTS are later, evidence-based gates; they are not promised by this beta. Report
|
||||
beta issues with `marqdo --version`, the platform, the exact commands and
|
||||
`--json` output where applicable.
|
||||
|
||||
## Documentation and entry points
|
||||
|
||||
- Third-party integration handbook:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md
|
||||
- Developer entry page:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/docs/developers/README.md
|
||||
- Support matrix:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/COMPATIBILITY.md
|
||||
- Status and same-SHA evidence:
|
||||
https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/docs/STATUS.md
|
||||
- The archive itself contains `spec/`, `docs/developers/`, `examples/` and
|
||||
`tests/consumers/`; repository-only pages (STATUS, evidence, the full
|
||||
prerelease policy) are linked above and are not duplicated into the archive.
|
||||
+44
-6
@@ -91,10 +91,18 @@ python3 tools/release/package.py --version "$version" --source-sha "$sha"
|
||||
```
|
||||
|
||||
Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory,
|
||||
`LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
|
||||
the **complete verified `stdlib/` bundle** (`stdlib.json`, every `.mq.md` module
|
||||
and self-test), `LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
|
||||
`RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`,
|
||||
`docs/developers/`, `examples/` (with host-built plugin/provider artifacts so
|
||||
the examples run without a compiler) and `tests/consumers/`.
|
||||
`docs/developers/`, `examples/` (with host-built plugin/provider/math-backend
|
||||
artifacts so the examples run without a compiler) and `tests/consumers/`.
|
||||
|
||||
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
|
||||
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
|
||||
with the same canonical algorithm as the runtime and refuses to package a mismatch
|
||||
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04). The bundled stdlib is a
|
||||
runtime requirement, not a build-machine side effect: a release binary must never
|
||||
fall back to the compile-time source path.
|
||||
|
||||
Do not publish an archive with only the CLI, with a mismatched worker target, or
|
||||
with a checksum that does not match the bytes.
|
||||
@@ -109,12 +117,42 @@ python3 tools/release/smoke.py \
|
||||
--archive dist/marqdo-*.tar.gz
|
||||
```
|
||||
|
||||
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, offline
|
||||
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib
|
||||
digests against `stdlib/stdlib.json` and the staged tree, offline
|
||||
`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2 and Trace v2
|
||||
consumers, Tool install/dispatch, native + worker plugin transports, a foreign
|
||||
kernel, Resource Provider v2 through the shipped worker (positive,
|
||||
unauthorized and missing-helper fail-closed), and strict mode when the host
|
||||
actually supports it. A failure is a release blocker.
|
||||
unauthorized and missing-helper fail-closed), the pure math package and optional
|
||||
math ABI backend, the removed `math.*` → `symbol.unknown` path, and strict mode
|
||||
when the host actually supports it.
|
||||
|
||||
It also moves the bundled `stdlib/` aside and requires `run examples/hello.mq.md`
|
||||
to fail closed with an explicit stdlib/print/symbol diagnostic: passing with a
|
||||
compile-machine source fallback is a release blocker (T-PKG-03).
|
||||
|
||||
### Independent runtime container (required, T-PKG-01/02)
|
||||
|
||||
The cold-install gate must run in a container that receives **only the archive
|
||||
bytes** — no source directory, no `/build`, no Cargo — and extracts them itself:
|
||||
|
||||
```bash
|
||||
docker run --rm -v "$PWD/dist:/dist:ro" ubuntu:24.04 sh -c '
|
||||
set -eu
|
||||
mkdir -p /opt/marqdo
|
||||
tar -xzf /dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz -C /opt/marqdo
|
||||
cd /opt/marqdo/marqdo-<version>-x86_64-unknown-linux-gnu
|
||||
./marqdo --version
|
||||
./marqdo --help >/dev/null
|
||||
./marqdo run examples/hello.mq.md
|
||||
./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json
|
||||
./marqdo call examples/math-library-demo.mq.md main
|
||||
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
|
||||
'
|
||||
```
|
||||
|
||||
Run this on the same Linux x86_64 glibc baseline as the release support
|
||||
matrix. If the binary needs a newer GLIBC than the runtime image, that is a real
|
||||
release defect, not a stdlib failure; do not report the ABI error as a stdlib PASS.
|
||||
|
||||
## 5. Release evidence manifest
|
||||
|
||||
|
||||
@@ -9,7 +9,11 @@ ordinary user `dev` (uid 1000), QEMU/TCG guest, 7/7 adversarial tests plus the
|
||||
strict `--json` and inert-`@knowledge` contracts — see
|
||||
[`evidence/2026-11-21-strict-gc-5fcc111.md`](evidence/2026-11-21-strict-gc-5fcc111.md).
|
||||
The older `8af7262` and `b6fc182` runs are retained below as history.
|
||||
Snapshot: product `3.0.0-beta.1`, 2026-11-22. See ADR-0021 and ADR-0053.
|
||||
Snapshot: product `3.0.0-beta.1`, source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`, 2026-11-22. See ADR-0021
|
||||
and ADR-0053. The same-SHA beta G3 run is
|
||||
[`evidence/2026-11-22-strict-gc-2c7c4f31.md`](evidence/2026-11-22-strict-gc-2c7c4f31.md)
|
||||
(local disposable VM, `outcome: PASS`, uid 1000, container none); it is not a
|
||||
remote self-hosted security-lane URL.
|
||||
|
||||
> **Language-syntax status.** The lane was re-run on the RFC-LANG-0002 tree
|
||||
> ([`architecture/RFC-LANG-0002-unified-semantics.md`](architecture/RFC-LANG-0002-unified-semantics.md))
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Example optional math ABI backend
|
||||
|
||||
This native plugin shows how a hot-path math algorithm can be supplied by an
|
||||
explicitly selected and trusted ABI backend after the core `math.*` call surface was
|
||||
removed (ADR-0061). It is optional: the pure `../math-library/` package works
|
||||
without it.
|
||||
|
||||
```bash
|
||||
./build.sh
|
||||
marqdo check demo.mq.md --plugin build
|
||||
marqdo run demo.mq.md --plugin build --trust-native-plugin --allow-plugin math.backend
|
||||
# 42
|
||||
marqdo run demo.mq.md --plugin build # permission.denied (no grant)
|
||||
```
|
||||
|
||||
`math.compute` is the capability category the backend requests; the core does not
|
||||
ship any math solver or evaluator.
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the example C plugin and generate a host-specific manifest.
|
||||
#
|
||||
# The artifact and generated manifest go to `build/`, which is gitignored. The
|
||||
# tracked `plugin.yaml` is never rewritten by a test or build: it documents the
|
||||
# manifest shape, while the generated one matches the machine that built it.
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
repo="$(cd "$here/../.." && pwd)"
|
||||
cd "$repo"
|
||||
|
||||
out="$here/build"
|
||||
mkdir -p "$out"
|
||||
host="$(rustc -vV | sed -n 's/^host: //p')"
|
||||
case "$host" in
|
||||
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
|
||||
*windows*) ext="dll"; flags=(-shared) ;;
|
||||
*) ext="so"; flags=(-shared -fPIC) ;;
|
||||
esac
|
||||
artifact="math_backend.$ext"
|
||||
cc -std=c11 -O2 "${flags[@]}" -I include -o "$out/$artifact" "$here/math_backend.c"
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
hash="$(sha256sum "$out/$artifact" | cut -d' ' -f1)"
|
||||
else
|
||||
hash="$(shasum -a 256 "$out/$artifact" | cut -d' ' -f1)"
|
||||
fi
|
||||
cat > "$out/plugin.yaml" <<YAML
|
||||
plugin:
|
||||
name: math.backend
|
||||
version: 0.1.0
|
||||
abi: "^1.0"
|
||||
kind: native
|
||||
exports:
|
||||
- name: math_backend.add
|
||||
signature: "(\$a: Int, \$b: Int) -> Int"
|
||||
requires:
|
||||
- math.compute
|
||||
artifacts:
|
||||
- target: $host
|
||||
file: $artifact
|
||||
sha256: "$hash"
|
||||
YAML
|
||||
echo "built $out/$artifact for $host (sha256 $hash)"
|
||||
echo "now run: marqdo plugin inspect $out"
|
||||
@@ -0,0 +1,5 @@
|
||||
## @exec main
|
||||
|
||||
`结果 = math_backend.add(a=20, b=22)`
|
||||
|
||||
> **打印(结果)**
|
||||
@@ -0,0 +1,318 @@
|
||||
/*
|
||||
* Marqdo plugin ABI v1 example plugin in C.
|
||||
*
|
||||
* Exports `math_backend.add` through `mq_plugin_entry_v1`, using the wire_version 1
|
||||
* JSON envelope. It deliberately has no external dependencies: the tiny JSON
|
||||
* scanning below is a demo aid, not a general-purpose JSON parser.
|
||||
*
|
||||
* Build:
|
||||
* cc -std=c11 -O2 -shared -fPIC -I include examples/math-backend/math_backend.c \
|
||||
* -o examples/math-backend/math_backend.so
|
||||
*
|
||||
* Test-only compile switches (used by the host-side conformance tests):
|
||||
* -DMQ_SOLVER_REPORT_ABI_MAJOR=2 report a wrong ABI major on purpose
|
||||
*/
|
||||
|
||||
#include "marqdo_plugin_abi_v1.h"
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef MQ_SOLVER_REPORT_ABI_MAJOR
|
||||
#define MQ_SOLVER_REPORT_ABI_MAJOR MQ_ABI_MAJOR
|
||||
#endif
|
||||
|
||||
static const char PLUGIN_METADATA[] =
|
||||
"{\"name\":\"math.backend\",\"version\":\"0.1.0\"}";
|
||||
|
||||
static const char SIGNATURE_ADD[] = "{\"signature\":\"($a: Int, $b: Int) -> Int\"}";
|
||||
|
||||
/* Single-threaded ABI: the host table is captured once at entry. */
|
||||
static const MqHostApi *g_host = NULL;
|
||||
|
||||
/* Return the pointer just past `"key"` + optional whitespace + ':' inside
|
||||
* `json`. Returns NULL when the key is absent. This is a demo scanner. */
|
||||
static const char *find_key(const char *json, const char *key) {
|
||||
size_t key_len = strlen(key);
|
||||
const char *cursor = json;
|
||||
while ((cursor = strchr(cursor, '"')) != NULL) {
|
||||
const char *name_start = cursor + 1;
|
||||
const char *name_end = strchr(name_start, '"');
|
||||
if (name_end == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
if ((size_t)(name_end - name_start) == key_len &&
|
||||
memcmp(name_start, key, key_len) == 0) {
|
||||
const char *after = name_end + 1;
|
||||
while (*after == ' ' || *after == '\t' || *after == '\n' ||
|
||||
*after == '\r') {
|
||||
after++;
|
||||
}
|
||||
if (*after != ':') {
|
||||
return NULL;
|
||||
}
|
||||
after++;
|
||||
while (*after == ' ' || *after == '\t' || *after == '\n' ||
|
||||
*after == '\r') {
|
||||
after++;
|
||||
}
|
||||
return after;
|
||||
}
|
||||
cursor = name_end + 1;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Find the object that is the value of key `name` and return a pointer to its
|
||||
* opening '{'. */
|
||||
static const char *find_object_value(const char *json, const char *name) {
|
||||
const char *value = find_key(json, name);
|
||||
if (value == NULL || *value != '{') {
|
||||
return NULL;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/* Extract a quoted JSON string value for `key`, copying at most `out_len - 1`
|
||||
* bytes into `out` (NUL terminated). Rejects escapes for simplicity. */
|
||||
static int read_string_value(const char *object, const char *key, char *out,
|
||||
size_t out_len) {
|
||||
const char *value = find_key(object, key);
|
||||
if (value == NULL || *value != '"') {
|
||||
return -1;
|
||||
}
|
||||
const char *start = value + 1;
|
||||
const char *end = strchr(start, '"');
|
||||
if (end == NULL) {
|
||||
return -1;
|
||||
}
|
||||
size_t len = (size_t)(end - start);
|
||||
if (len + 1 > out_len || memchr(start, '\\', len) != NULL) {
|
||||
return -1;
|
||||
}
|
||||
memcpy(out, start, len);
|
||||
out[len] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Extract the integer argument `name` from the request's `args` object. */
|
||||
static int read_int_argument(const char *json, const char *name,
|
||||
long long *out_value) {
|
||||
const char *args = find_object_value(json, "args");
|
||||
if (args == NULL) {
|
||||
return -1;
|
||||
}
|
||||
const char *argument = find_object_value(args, name);
|
||||
if (argument == NULL) {
|
||||
return -1;
|
||||
}
|
||||
char decimal[32];
|
||||
if (read_string_value(argument, "decimal", decimal, sizeof(decimal)) != 0) {
|
||||
return -1;
|
||||
}
|
||||
char *end = NULL;
|
||||
long long value = strtoll(decimal, &end, 10);
|
||||
if (end == NULL || *end != '\0' || end == decimal) {
|
||||
return -1;
|
||||
}
|
||||
*out_value = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Allocate an output buffer through the host allocator and copy `len` bytes.
|
||||
* The host frees it after copying; the plugin never frees output buffers. */
|
||||
static int32_t emit(const char *json, size_t len, MqOwnedBytes *out) {
|
||||
uint8_t *buffer;
|
||||
if (g_host == NULL || out == NULL) {
|
||||
return MQ_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
buffer = (uint8_t *)g_host->alloc(g_host->host_data, len);
|
||||
if (buffer == NULL) {
|
||||
return MQ_ERR_OUT_OF_MEMORY;
|
||||
}
|
||||
memcpy(buffer, json, len);
|
||||
out->data = buffer;
|
||||
out->len = len;
|
||||
return MQ_OK;
|
||||
}
|
||||
|
||||
static int32_t emit_error(const char *code, const char *message,
|
||||
MqOwnedBytes *out, int32_t failure_code) {
|
||||
char json[512];
|
||||
int written = snprintf(
|
||||
json, sizeof(json),
|
||||
"{\"wire_version\":1,\"kind\":\"response\",\"error\":"
|
||||
"{\"kind\":\"invoke\",\"code\":\"%s\",\"message\":\"%s\"}}",
|
||||
code, message);
|
||||
if (written < 0 || (size_t)written >= sizeof(json)) {
|
||||
return MQ_ERR_INTERNAL;
|
||||
}
|
||||
if (emit(json, (size_t)written, out) != MQ_OK) {
|
||||
return MQ_ERR_OUT_OF_MEMORY;
|
||||
}
|
||||
/* Non-zero: the invocation failed even though an error envelope was
|
||||
* written. The host reads the envelope for the structured error. */
|
||||
return failure_code;
|
||||
}
|
||||
|
||||
/* Optional hot-path ABI backend for pure math algorithms. */
|
||||
static int32_t math_backend_add(MqCallContext *ctx, MqBytes args_wire,
|
||||
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
|
||||
char *json;
|
||||
long long a = 0;
|
||||
long long b = 0;
|
||||
long long sum;
|
||||
char response[160];
|
||||
int written;
|
||||
|
||||
(void)ctx;
|
||||
if (result_wire == NULL || error_wire == NULL) {
|
||||
return MQ_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
*result_wire = (MqOwnedBytes){NULL, 0};
|
||||
*error_wire = (MqOwnedBytes){NULL, 0};
|
||||
if (args_wire.data == NULL || args_wire.len == 0) {
|
||||
return emit_error("bad_arguments", "request wire is empty", error_wire,
|
||||
MQ_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
if (args_wire.len > MQ_MAX_REQUEST_WIRE_BYTES) {
|
||||
return emit_error("request_too_large", "request wire is too large",
|
||||
error_wire, MQ_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
json = (char *)malloc(args_wire.len + 1);
|
||||
if (json == NULL) {
|
||||
return emit_error("out_of_memory", "plugin could not copy request",
|
||||
error_wire, MQ_ERR_OUT_OF_MEMORY);
|
||||
}
|
||||
memcpy(json, args_wire.data, args_wire.len);
|
||||
json[args_wire.len] = '\0';
|
||||
|
||||
if (read_int_argument(json, "a", &a) != 0 ||
|
||||
read_int_argument(json, "b", &b) != 0) {
|
||||
free(json);
|
||||
return emit_error("bad_arguments",
|
||||
"math_backend.add requires Int arguments `a` and `b`",
|
||||
error_wire, MQ_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
free(json);
|
||||
|
||||
#ifdef MQ_SOLVER_CRASH
|
||||
/* Test-only crash injection for isolated-worker crash tests. */
|
||||
abort();
|
||||
#endif
|
||||
|
||||
if (__builtin_add_overflow(a, b, &sum)) {
|
||||
return emit_error("integer_overflow", "math_backend.add overflowed i64",
|
||||
error_wire, MQ_ERR_INTERNAL);
|
||||
}
|
||||
written = snprintf(
|
||||
response, sizeof(response),
|
||||
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
|
||||
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
|
||||
sum);
|
||||
if (written < 0 || (size_t)written >= sizeof(response)) {
|
||||
return MQ_ERR_INTERNAL;
|
||||
}
|
||||
return emit(response, (size_t)written, result_wire);
|
||||
}
|
||||
|
||||
#ifdef MQ_SOLVER_MULTI_EXPORT
|
||||
/* Test-only second export: `math_backend.neg`, used to prove complete-name routing
|
||||
* (ADR-0010). It is not part of the default demo manifest. */
|
||||
static int32_t math_backend_neg(MqCallContext *ctx, MqBytes args_wire,
|
||||
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
|
||||
char *json;
|
||||
long long a = 0;
|
||||
char response[160];
|
||||
int written;
|
||||
|
||||
(void)ctx;
|
||||
if (result_wire == NULL || error_wire == NULL) {
|
||||
return MQ_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
*result_wire = (MqOwnedBytes){NULL, 0};
|
||||
*error_wire = (MqOwnedBytes){NULL, 0};
|
||||
if (args_wire.data == NULL || args_wire.len == 0) {
|
||||
return emit_error("bad_arguments", "request wire is empty", error_wire,
|
||||
MQ_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
json = (char *)malloc(args_wire.len + 1);
|
||||
if (json == NULL) {
|
||||
return emit_error("out_of_memory", "plugin could not copy request",
|
||||
error_wire, MQ_ERR_OUT_OF_MEMORY);
|
||||
}
|
||||
memcpy(json, args_wire.data, args_wire.len);
|
||||
json[args_wire.len] = '\0';
|
||||
if (read_int_argument(json, "a", &a) != 0) {
|
||||
free(json);
|
||||
return emit_error("bad_arguments", "math_backend.neg requires Int `a`",
|
||||
error_wire, MQ_ERR_INVALID_ARGUMENT);
|
||||
}
|
||||
free(json);
|
||||
written = snprintf(
|
||||
response, sizeof(response),
|
||||
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
|
||||
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
|
||||
-a);
|
||||
if (written < 0 || (size_t)written >= sizeof(response)) {
|
||||
return MQ_ERR_INTERNAL;
|
||||
}
|
||||
return emit(response, (size_t)written, result_wire);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Required ABI v1 entry point. */
|
||||
int32_t mq_plugin_entry_v1(const MqHostApi *host, MqPluginApi *plugin) {
|
||||
MqBytes export_name;
|
||||
MqBytes signature_wire;
|
||||
int32_t code;
|
||||
|
||||
if (host == NULL || plugin == NULL) {
|
||||
return MQ_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (host->struct_size < sizeof(MqHostApi)) {
|
||||
return MQ_ERR_ABI_MISMATCH;
|
||||
}
|
||||
if (host->abi_major != MQ_ABI_MAJOR) {
|
||||
return MQ_ERR_ABI_MISMATCH;
|
||||
}
|
||||
if (host->alloc == NULL || host->free == NULL ||
|
||||
host->register_function == NULL || host->request_capability == NULL) {
|
||||
return MQ_ERR_ABI_MISMATCH;
|
||||
}
|
||||
|
||||
g_host = host;
|
||||
|
||||
/* The host pre-fills struct_size; keep it and report our ABI version. */
|
||||
plugin->struct_size = (uint32_t)sizeof(MqPluginApi);
|
||||
plugin->abi_major = MQ_SOLVER_REPORT_ABI_MAJOR;
|
||||
plugin->abi_minor = MQ_ABI_MINOR;
|
||||
plugin->plugin_metadata_wire.data = (const uint8_t *)PLUGIN_METADATA;
|
||||
plugin->plugin_metadata_wire.len = sizeof(PLUGIN_METADATA) - 1;
|
||||
|
||||
export_name.data = (const uint8_t *)"math_backend.add";
|
||||
export_name.len = sizeof("math_backend.add") - 1;
|
||||
signature_wire.data = (const uint8_t *)SIGNATURE_ADD;
|
||||
signature_wire.len = sizeof(SIGNATURE_ADD) - 1;
|
||||
|
||||
code = host->register_function(host->host_data, export_name, signature_wire,
|
||||
math_backend_add);
|
||||
if (code != MQ_OK) {
|
||||
return code;
|
||||
}
|
||||
|
||||
#ifdef MQ_SOLVER_MULTI_EXPORT
|
||||
export_name.data = (const uint8_t *)"math_backend.neg";
|
||||
export_name.len = sizeof("math_backend.neg") - 1;
|
||||
signature_wire.data = (const uint8_t *)"{\"signature\":\"($a: Int) -> Int\"}";
|
||||
signature_wire.len = sizeof("{\"signature\":\"($a: Int) -> Int\"}") - 1;
|
||||
code = host->register_function(host->host_data, export_name, signature_wire,
|
||||
math_backend_neg);
|
||||
if (code != MQ_OK) {
|
||||
return code;
|
||||
}
|
||||
#endif
|
||||
return MQ_OK;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
# Example optional ABI math backend (plugin ABI v1).
|
||||
#
|
||||
# Installing this package never grants permissions. `math.compute` is a capability
|
||||
# category for a compute backend, not a promise that the core ships a solver.
|
||||
# Replace target/sha256 with the host-built artifact values (build.sh writes the
|
||||
# generated manifest into build/plugin.yaml).
|
||||
plugin:
|
||||
name: math.backend
|
||||
version: 0.1.0
|
||||
abi: "^1.0"
|
||||
kind: native
|
||||
exports:
|
||||
- name: math_backend.add
|
||||
signature: "($a: Int, $b: Int) -> Int"
|
||||
requires:
|
||||
- math.compute
|
||||
artifacts:
|
||||
- target: x86_64-unknown-linux-gnu
|
||||
file: math_backend.so
|
||||
sha256: "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
import:
|
||||
math: "./math-library/index.mq.md"
|
||||
---
|
||||
|
||||
# @knowledge 数学消费者
|
||||
|
||||
## @exec main
|
||||
|
||||
`return math.最大公约数(甲=48, 乙=18)`
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user