Author SHA1 Message Date
cflmy 452e9a32bd docs: define RC shared-node policy and downstream Analysis integration
ci/woodpecker/push/main Pipeline was successful
RC candidates may use a maintainer-approved shared node with a recorded WARN;
stable/LTS still requires a dedicated fixed node. Add the migration guide for
marqdo-view and marqdo-lint covering exact source/AST consumption, the changed
unit span meaning, the stateful reference contract and the rejection of old
same-revision artifacts.
2026-11-25 13:19:41 +08:00
cflmy 63f62d5728 Merge issue #10: close the public Analysis boundary
ci/woodpecker/push/main Pipeline was successful
Replace the program-only Analysis v3 shape in place with the ADR-0069 boundary:
exact source and document AST, complete heading scope, entry/snapshot identity,
one shared document-link resolver, typed call/reference facts, semantic
validation and owner-only atomic emit. All code/CI/archive/conformance gates pass;
rc.4 publication is withheld (DO_NOT_RELEASE) pending the strict-VM and approved
G4 gates.
2026-11-25 11:55:36 +08:00
cflmy 4a4ca63b45 evidence: record the green follow-up CI tree
ci/woodpecker/push/main Pipeline was successful
Pipeline 91 is fully green for the CI-helper follow-up commit b1fc211; the
shipped-code candidate remains e0645f3 and the release decision remains
DO_NOT_RELEASE because strict VM and the approved G4 result are unavailable.
2026-11-25 11:55:21 +08:00
cflmy b1fc211916 ci: move the stale-Analysis assertion into a checked-in script
ci/woodpecker/push/main Pipeline was successful
The runner does not preserve shell quoting inside multiline YAML commands, so a
single-quoted Python -c kept aborting the contract lane. Use a small checked-in
tool instead; it appends one byte, runs the independent Observation consumer and
fails the lane unless the stale artifact is rejected.
2026-11-25 11:51:56 +08:00
cflmy 8473ac9827 evidence: record the rc.4 same-SHA CI, archive and conformance gates
ci/woodpecker/push/main Pipeline failed
Record pipeline #89 (all four lanes PASS) for e0645f3, the CI and local archive
hashes, archive smoke, Ubuntu 24.04 cold install and frozen extension 7/7.
The SHA-bound gate aggregate is DO_NOT_RELEASE: strict VM is UNVERIFIED and no
approved G4 node result exists, so rc.4 is not tagged or published.
2026-11-25 11:47:55 +08:00
cflmy e0645f376b schema: allow legal path characters and reject only real traversal
ci/woodpecker/push/main Pipeline was successful
Accept a double dot inside a file name and '::' in a module path; reject only an
absolute, drive, UNC or backslash path, duplicate separators, and '.'/'..'
path segments. This matches the loader and avoids over-rejecting legal files.
2026-11-25 11:40:22 +08:00
cflmy 7064c5f22c analysis: keep function and module identities injective
ci/woodpecker/push/main Pipeline was successful
Escape the module/function delimiter when a function name contains '::', so a
path segment containing the delimiter cannot make two FunctionId renderings
collide. Drop the temporary path restriction that rejected a legal '::' in a
module path; the structured path and name fields remain authoritative. Add an
identity regression test and revalidate the schema.
2026-11-25 11:37:39 +08:00
cflmy 31ccfe15f8 ci: make the stale-Analysis rejection step shell-safe
ci/woodpecker/push/main Pipeline was canceled
The multiline if/printf block was truncated by the runner shell, so the
contract lane aborted with a syntax error after all protocol consumers had
already passed. Replace it with a single Python byte-append and an && guard;
the assertion still requires the stale artifact to be rejected.
2026-11-25 11:34:14 +08:00
cflmy 1543d33c8a evidence: record rc.4 archive smoke and cold-install gates
The packaged 3.0.0-rc.4 archive passes the archive-only smoke (stdlib digests,
Analysis/Observation consumers, Tool dispatch, workers, strict refusal) and the
container-only cold install on Ubuntu 24.04 with no Cargo and no network.
2026-11-25 11:22:13 +08:00
cflmy 8737e093d6 release: prepare 3.0.0-rc.4 and record the Analysis boundary
ci/woodpecker/push/main Pipeline failed
Bump the workspace product version, document the in-place Analysis contract
replacement, update the current-facing guides and architecture overview, and
record the local gate plus the 101-module/rc.3 performance comparison. The
candidate is not a release: same-SHA CI, archive cold install, frozen external
conformance and the strict VM gate are still required before tagging.
2026-11-25 11:18:31 +08:00
cflmy 0b7f238fd8 refs: keep plain-file fragments unverified and cover missing targets
A fragment on a verified non-program file is coverage the loaded catalog does
not have; report not_loaded instead of a file success. Add explicit-refs tests
for verified plain files, symlink refusal, encoded traversal, missing
unimported programs and lock snapshot digests.
2026-11-25 11:04:52 +08:00
cflmy 93e125e921 analysis: verify resource digests against the projected AST payload
Reject a resource whose content_digest does not match the AST node at its
span, so a tampered formula/code digest cannot pass the semantic validator.
2026-11-25 11:01:45 +08:00
cflmy 6d4209bf32 tests: verify the closed Analysis boundary with independent consumers
Add black-box tests for exact source/AST projection, complete heading scopes,
explicit reference states, output safety (input/symlink/hardlink/directory and
owner-only bytes), Observation digest binding, multi-entry snapshot context and
the protocol mutation gate. Upgrade the Python consumer into a full independent
semantic validator, add view/lint/knowledge consumer fixtures driven by the
real CLI, and run schema plus semantic mutation checks from validate_protocols.
2026-11-25 11:01:24 +08:00
cflmy 99789616a4 analysis: project document and program facts through one typed encoder
Replace the program-only projection with ADR-0069's typed model: exact source
and digest, the public document AST, complete heading scopes with parent/mode
origin/range, anchors, functions, imports, references, calls and resources.
Project identity now carries the entry, captured manifest/lock digests, stdlib
and the static extension identities that participated in preparation. Run and
call bind Observation to the same canonical bytes, inspect reuses the same AST,
unit and reference projectors, and the retired duplicate link resolver is
deleted. Emit refuses to overwrite inputs, directories, symlinks or hard links
and publishes through an owner-only exclusive temporary file.
2026-11-25 10:12:07 +08:00
cflmy 1b214d48da refs: converge Markdown link resolution on one scoped catalog
Add the single pure document-link resolver: it resolves exact anchors first,
collects all canonical-name fallback candidates, decodes percent escapes once,
and distinguishes resolved/not_loaded/missing/ambiguous/external/outside_scope/
invalid without network access or caller-entry fallback. The loaded catalog
never opens a link target; the explicit --refs catalog may verify directly
referenced files once, inside the package root, with symlink refusal and read
limits. Add unit-range ownership helpers to the heading index and focused
resolver tests.
2026-11-25 09:55:58 +08:00
cflmy d8212aaa01 loader: bind Analysis to the captured manifest and lock bytes
Read marqdo.yaml and marqdo.lock exactly once while loading, parse those bytes,
and record sha256 digests on LoadedProject. This removes the post-preparation
lock re-read (and its silent empty digest on IO failure) and lets Analysis name
the exact static snapshot that selected the program. Add a regression test that
editing the manifest after load cannot change the captured digest.
2026-11-25 09:46:04 +08:00
cflmy 629fb9834d frontend: expose heading scope facts for the public boundary
Keep the one heading index but record the effective mode origin and source
unit, the nearest ancestor unit, the complete section span and the heading
span separately, and cover the whole source with the root unit. Reject a dot
inside a function/namespace component as an ambiguous public identity, and
escape the structural separators in UnitId display so a segment containing
'/', '#' or '%' cannot collide with a deeper path. Add focused tests for the
new invariants and diagnostics.
2026-11-25 09:44:16 +08:00
cflmy 88d7cd3414 docs: define the closed public Analysis boundary
Add ADR-0069 and replace the program-only Analysis v3 shape in place with the
one public projection consumed by independent static tools: project entry and
snapshot identity, exact source, document AST, heading scope facts, anchors,
functions, calls, resources and stateful references. Update the Markdown
profile, reference and observation specs to point at the single resolver and
the same encoder/digest rule.
2026-11-25 09:39:26 +08:00
cflmy e6066e6ba9 evidence: record the published 3.0.0-rc.3 release
ci/woodpecker/push/main Pipeline was successful
- docs/evidence/2026-11-24-rc.3-release.md: per-gate record for the tagged SHA
  (same-SHA Linux CI pipeline #80, archive smoke, clean install, frozen
  extensions 7/7, strict L1 disposable VM with the published archive
  re-verified in the guest, three paired shared-node G4 runs with the
  maintainer-approved WARN, and the RSS sampler investigation).
- docs/evidence/ci/<sha>/manifest.json: RC_RELEASE_CANDIDATE gate manifest.
- STATUS/COMPATIBILITY/CHANGELOG: publication record, release link, evidence
  paths and the released version heading.

Post-release docs commit: it references the tagged SHA and does not move the
release source.
2026-11-25 00:00:29 +08:00
cflmy 1e2a045cc7 perf: time the execution path, not the opt-in Observation document
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
The first rc.3 perf comparison reused the old workload commands but switched
them to `run/call --output json`, so the candidate was timed while producing
thousands of structural events that the beta baseline never emitted. The result
was a reproducible +240..+375% p50 and +130% RSS delta caused by the
measurement, not by the program's execution cost.

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

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

Same-SHA CI: https://ci.cflmy.cn/repos/1/pipeline/71
2026-11-24 19:23:26 +08:00
94 changed files with 8324 additions and 1681 deletions

No files matched your search

+2 -18
View File
@@ -28,24 +28,8 @@ steps:
python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers
python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/control-analysis.json /tmp/control-observation.json python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/control-analysis.json /tmp/control-observation.json
python3 tests/consumers/observation_consumer.py --validate-schema --analysis /tmp/control-analysis.json /tmp/control-events.jsonl python3 tests/consumers/observation_consumer.py --validate-schema --analysis /tmp/control-analysis.json /tmp/control-events.jsonl
- | - python3 tools/ci/verify_observation_stream.py /tmp/control-events.jsonl /tmp/control-observation.json
set -eu - python3 tools/ci/assert_stale_analysis.py /tmp/control-analysis.json /tmp/control-events.jsonl
python3 - <<'PY'
import json, pathlib
events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()]
snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_text())
assert snapshot["events"] == events, "stream and snapshot must be one event sequence"
print("stream and snapshot share one event sequence")
PY
- |
set -eu
cp /tmp/control-analysis.json /tmp/analysis-stale.json
printf ' ' >> /tmp/analysis-stale.json
if python3 tests/consumers/observation_consumer.py --analysis /tmp/analysis-stale.json /tmp/control-events.jsonl; then
echo "stale Analysis was accepted" >&2
exit 1
fi
echo "stale Analysis rejected"
test: test:
image: rust:1.100-bookworm image: rust:1.100-bookworm
+1 -1
View File
@@ -3,7 +3,7 @@
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative. **Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative.
For next-phase work, the authoritative release policy for the current For next-phase work, the authoritative release policy for the current
`3.0.0-beta.1` line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates, 3.0 prerelease line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates,
REL-01..REL-05, version axes, LTS conditions). `docs/STABLE_RELEASE_IMPLEMENTATION.md` REL-01..REL-05, version axes, LTS conditions). `docs/STABLE_RELEASE_IMPLEMENTATION.md`
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable (stable gates G-A/G-B/G-C) is historical roadmap input for the later stable
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md` release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
+101 -16
View File
@@ -1,20 +1,73 @@
# Changelog # Changelog
All notable changes to the Marqdo CLI workspace. Product version All notable changes to the Marqdo CLI workspace. Published prereleases:
`3.0.0-beta.1` was tagged on 2026-11-22 at source `3.0.0-beta.1` (2026-11-22, source
`2c7c4f31e7a388d3fcfa717a77067e696ed13854` `2c7c4f31e7a388d3fcfa717a77067e696ed13854`),
([release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1)); `3.0.0-rc.1` (source `f7a5a7b0163bf5229ed09adfffd892f9899e6667`) and
the next section collects post-beta `3.0.0-rc.2` (source `9149ee40a48fcda692c5c112f66c465487d13dfb`) and
changes. Current protocol contracts are Analysis, Observation, CLI Tool, `3.0.0-rc.3` (2026-11-24, source `1e2a045cc78bf40972181abb44e7117c56cf4401`); the section below is the current
release record. Current
protocol contracts are Analysis v3, Observation v1, CLI Tool revision 1,
Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4; independent Plugin ABI v1, Foreign wire v1, Provider manifest v2 and lock v4; independent
package versions (including the bundled stdlib `0.1.0`) are versioned package versions (including the bundled stdlib `0.1.0`) are versioned
separately and do not follow the product version. Dates use ISO 8601. separately and do not follow the product version. Dates use ISO 8601.
Older sections are release records: a retired option or spec they name is
available at its tagged commit, not in the current tree.
## 3.0.0-rc.3 (candidate) ## 3.0.0-rc.4 (2026-11-25, candidate)
- The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.4`; the supported platform remains Linux x86_64 on glibc 2.39 and
the locked Rust minimum remains 1.89.
### Closed public Analysis boundary — issue #10 (breaking in place)
Executed policy: [ADR-0069](docs/adr/0069-public-analysis-boundary.md), replacing
`marqdo.analysis` revision 3 in place under ADR-0068. There is no old reader,
version negotiation or fallback; a same-revision artifact that lacks a current
required field is rejected and must be regenerated.
- **Document facts are public.** `modules[].source` carries the exact UTF-8
source already read by the loader and `modules[].document` is the canonical
Markdown AST in the public shape shared with `inspect --ast`. Consumers no
longer parse Markdown a second time or read package-cache paths.
- **Heading scope is one index.** Units expose the structured `path`, parent,
effective mode, mode origin and source unit, the heading span and the complete
section span. The root covers the whole source including a BOM. Exec H2
function ownership stays explicit.
- **Entry and snapshot identity are explicit.** `project.entry_module_id`,
captured `manifest_digest`/`lock_digest`, stdlib identity and the static
extension identities used by preparation are part of the artifact. The
post-preparation lock re-read and its silent empty digest on IO failure are
gone.
- **One document-link resolver.** Analysis `references`, `check --refs` and
`inspect --refs` share one pure resolver and explicit catalogs. It reports
`resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, `outside_scope`
or `invalid`; ordinary Analysis never opens a link target and a same-document
anchor names the real source module. The duplicate `commands.rs` resolver is
deleted.
- **Calls stay bound once.** Static call records keep the single prepared
binding table and now expose target kind, exact function/builtin/plugin target
and a reason for unresolved calls. Plugin targets carry only their verified
static owner; no plugin function is fabricated.
- **Output is private and atomic.** `--emit` writes owner-only exclusive bytes
through a temporary file and rename, and refuses to overwrite a loaded source,
manifest, lock file, directory, symlink or hard link to an input.
- **Independent consumers are the gate.** The Python Analysis consumer performs
semantic validation in addition to JSON Schema; mutation fixtures reject
missing current fields, tampered source/digests/spans, cycles, wrong owners
and invalid reference/nullability combinations. View-, lint- and
knowledge-like fixtures drive the real installed CLI.
## 3.0.0-rc.3 (2026-11-24)
- The Rust workspace, CLI version output and protocol producers report - The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux `3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux
x86_64 on glibc 2.39. x86_64 on glibc 2.39.
- **Licensing:** the workspace is now Apache-2.0 only. `Cargo.toml` declares
`license = "Apache-2.0"` and the dual-licensed `LICENSE-MIT` file is removed;
the archive ships `LICENSE-APACHE` only. This is a repository-licensing
change, not a protocol or language change.
### Single current public contracts — issue #8 (breaking) ### Single current public contracts — issue #8 (breaking)
@@ -36,7 +89,9 @@ automatic migration.
the same execution. `run_id`, `seq`, frame identity, terminal semantics, the same execution. `run_id`, `seq`, frame identity, terminal semantics,
capture budgets and privacy rules are defined once in capture budgets and privacy rules are defined once in
[`spec/observation.md`](spec/observation.md). The retired `--json`, [`spec/observation.md`](spec/observation.md). The retired `--json`,
`--trace-file` and `--event-stream` options are rejected. `--trace-file`, `--event-stream` and `--trace` options are rejected, and the
in-process effect-trace document is gone: effects are `effect` observation
events.
- **CLI Tool requirements are single exact values.** `tool.json` declares - **CLI Tool requirements are single exact values.** `tool.json` declares
`requires.api_revision` (required) plus optional exact `analysis` and `requires.api_revision` (required) plus optional exact `analysis` and
`observation` integers. Version arrays and intersection negotiation are `observation` integers. Version arrays and intersection negotiation are
@@ -53,7 +108,30 @@ automatic migration.
explicit regeneration/reinstall instruction; no migrator runs. explicit regeneration/reinstall instruction; no migrator runs.
- **`spec/` now contains only current contracts.** Retired specifications are - **`spec/` now contains only current contracts.** Retired specifications are
available in Git history and tagged archives. ADRs covering retired public available in Git history and tagged archives. ADRs covering retired public
contracts carry a Historical header. contracts carry a Historical header. `docs/developers/analysis-trace.md` was
replaced by `analysis-observation.md`.
- **CI is a protocol consumer.** A fast `contract` lane builds both shipped
binaries and drives the real CLI through the independent Python consumers,
while the full `test` lane runs fmt/clippy/tests/docs/architecture gates.
`tools/ci/verify_observation_stream.py` (checked in, unit-tested) asserts
that one run's JSONL stream and JSON snapshot are the same event sequence.
### Review fixes after the first candidate build
- A rejected strict observation destination no longer emits a partial JSONL
stream: `--output jsonl` and `--observation-file` are refused before any
session opens.
- `check --emit` removes a previous Analysis artifact when the project cannot
be loaded, not only when it has compile errors.
- Filesystem resource requests report their concrete effect operation
(`fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`,
`fs.rename`) instead of a generic `resource.request`.
- The shared worker transport preserves the plugin ABI frame codes
`worker_frame_too_large` and `worker_encode_failed`.
- The event and snapshot schemas agree on the capture `level` enum.
- The G4 workload catalogue uses `run`/`call --output json` and pins the
current snapshot in its correctness digest; the previously retired `--json`
flag made every non-check workload fail correctness verification.
Migration for consumers: Migration for consumers:
@@ -78,13 +156,20 @@ Migration for consumers:
- `crates/cli/tests/architecture_boundaries.rs` forbids a second worker - `crates/cli/tests/architecture_boundaries.rs` forbids a second worker
framing implementation and pins the workspace layer list; framing implementation and pins the workspace layer list;
`docs_consistency` keeps one current overview and resolving links. `docs_consistency` keeps one current overview and resolving links.
- Same-SHA Linux CI [pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70) - Same-SHA Linux CI ([pipeline #80](https://ci.cflmy.cn/repos/1/pipeline/80)),
passed all lanes, produced archive sha256 the archive build, the from-archive smoke, the cold-install container check
`d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37`, passed and the frozen external conformance suite (fixtures at
the from-archive smoke and the frozen external conformance suite 7/7 with `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`, 7/7) are recorded in the
fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`. per-gate manifest
- Publication still requires the RC strict-VM and G4 performance evidence [`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
described in [`docs/releasing.md`](docs/releasing.md). (`RC_RELEASE_CANDIDATE`).
- The RC strict-L1 disposable-VM lane passed on the tagged SHA and the
published archive was re-verified in that guest; see
[`docs/evidence/2026-11-24-rc.3-release.md`](docs/evidence/2026-11-24-rc.3-release.md).
G4 is a maintainer-approved shared-node `WARN` for this named RC (three
paired runs, no p50 threshold breach), with the environment and limits in the
release notes. Release:
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3.
## 3.0.0-rc.2 (candidate) ## 3.0.0-rc.2 (candidate)
+44 -44
View File
@@ -1,17 +1,19 @@
# Compatibility and support matrix # Compatibility and support matrix
Snapshot: product version **`3.0.0-beta.1`** (prerelease), branch `master`, Snapshot: product version **`3.0.0-rc.4`** (prerelease candidate, 2026-11-25).
tagged `v3.0.0-beta.1` at source SHA `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. This file records what was actually verified and The previous release is `3.0.0-rc.3` at source SHA
separates it from what is only implemented. The supported release platform is `1e2a045cc78bf40972181abb44e7117c56cf4401`; its evidence remains under
**Linux x86_64 (glibc)**; everything else is experimental and not claimed for [`docs/evidence/`](docs/evidence/2026-11-24-rc.3-release.md). This file records
this beta. Executed status and same-SHA evidence are in what was actually verified and separates it from what is only implemented. The
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under supported release platform is **Linux x86_64 (glibc 2.39)**; everything else is
[`docs/evidence/extension/`](docs/evidence/extension/README.md). experimental and not claimed for this prerelease. Executed status and SHA-bound
evidence are in [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/`](docs/evidence/).
The `3.0.0-rc.3` candidate targets Linux x86_64 on glibc 2.39 and The `3.0.0-rc.4` candidate includes the post-beta protocol convergence and the
includes the post-beta changes below. See the closed public Analysis boundary below. See the
[RC acceptance procedure](docs/releasing.md). The platform evidence table [RC acceptance procedure](docs/releasing.md). The platform evidence table
records the beta and subsequent development verification. records the beta, rc.1/rc.2/rc.3 and rc.4 candidate verification.
## Language source syntax (breaking change) ## Language source syntax (breaking change)
@@ -51,7 +53,7 @@ Consequences for compatibility:
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003) ## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
These landed after the beta tag and **are included in the `3.0.0-rc.3` candidate**; they are These landed after the beta tag and **are included in the `3.0.0-rc.4` candidate**; they are
intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md). evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -65,9 +67,9 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown` or heading annotations projection exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. | | Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown` or heading annotations projection exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
| Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. | | Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. |
## Structured control flow (RFC-CTRL-0005, RC.2) ## Structured control flow (RFC-CTRL-0005, RC.2 and later)
The RC.2 candidate reserves `break` and `continue` only as complete The RC.2 and RC.3 candidates reserve `break` and `continue` only as complete
payloads. An existing standalone identifier read can be written as payloads. An existing standalone identifier read can be written as
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within `(break)` or `(continue)`. Calls, bindings, fields and identifiers within
expressions retain their meaning. Two separate carriers containing `else` and expressions retain their meaning. Two separate carriers containing `else` and
@@ -77,25 +79,24 @@ Parameter inference ignores reads after a definite transfer. When upgrading
a caller that passed an argument inferred solely from unreachable code, a caller that passed an argument inferred solely from unreachable code,
remove the argument or keep it through an explicit `params(...)` declaration. remove the argument or keep it through an explicit `params(...)` declaration.
`marqdo-lint 0.1.0` reads legacy Analysis v2 documents. Its control layout The current Analysis contract is `schema_version: 3` for every project, so an
alignment for `else if` and its Analysis v3 support require an update in external tool that still reads Analysis v2 must be updated before it can
that tool. consume this candidate's `check --emit` output.
## Public protocol versions ## Public protocol versions
| Surface | Version | Compatibility rule | | Surface | Version | Compatibility rule |
|---|---|---| |---|---|---|
| Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. | | Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. |
| Language / CLI | `3.0.0-rc.3` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. | | Language / CLI | `3.0.0-rc.4` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. |
| `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). | | `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). |
| Analysis | v2/v3 | Projects with loop transfers emit v3. Other projects emit v2. Consumers reject unknown majors. | | Analysis | v3 | One writer and one current major for every project, including projects without loop transfers. Consumers reject other majors; the retired v2 selector, schema and documents are gone (ADR-0068). |
| Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. | | Observation | v1 | One `run_id`/`seq` event sequence per execution, delivered as JSONL, JSON snapshot or file snapshot from the same run. Values are opt-in and bounded; consumers reject other identifiers (spec/observation.md). |
| Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). | | CLI Tool | revision 1 | `requires.api_revision` is one exact integer; `analysis`/`observation` are optional exact integers. Version arrays and intersection negotiation are rejected with a reinstall instruction. |
| CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. |
| Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. | | Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. |
| Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). | | Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). |
| Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). | | Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). |
| Analysis `calls[].state/target` | v2 (projection) | Now projected from the unique binding; official stdlib aliases appear as `function`. Schema/version unchanged; private binding table not serialized. | | Analysis `calls[].state/target` | v3 projection | Projected from the unique binding; official stdlib aliases appear as `function`. The private binding table is not serialized. |
| Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). | | Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). |
| Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. | | Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. |
@@ -118,10 +119,9 @@ portable/tested locally but the native platform lane has not run here;
| Official stdlib public aliases (print de-magic; byte-identical output) | PASS | UNVERIFIED | UNVERIFIED | | Official stdlib public aliases (print de-magic; byte-identical output) | PASS | UNVERIFIED | UNVERIFIED |
| Resource Provider v2 CLI (`--provider`/`--allow-provider`, worker helper) | PASS (linux/x86_64; real C sensor + helper) | **FAIL-CLOSED** (`ext.platform_unsupported`) | **UNSUPPORTED** | | Resource Provider v2 CLI (`--provider`/`--allow-provider`, worker helper) | PASS (linux/x86_64; real C sensor + helper) | **FAIL-CLOSED** (`ext.platform_unsupported`) | **UNSUPPORTED** |
| Capability handler registry (`fs.read` handler, audit, unavailable) | PASS | UNVERIFIED | UNVERIFIED | | Capability handler registry (`fs.read` handler, audit, unavailable) | PASS | UNVERIFIED | UNVERIFIED |
| External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (`--release` binary sha256 `28e3776d…`, fixture repo `e4b7352c…`; see `docs/evidence/extension/6a7bb983.../manifest.json`) | UNVERIFIED | UNVERIFIED | | External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (7/7 categories against the published archive, fixture repo `015ff8ac…`; see the rc.3 evidence bundle) | UNVERIFIED | UNVERIFIED |
| Analysis v2 / Trace v2 + Python consumers | PASS | UNVERIFIED | UNVERIFIED | | Analysis v3 + Observation v1 + Python consumers | PASS (same-SHA CI contract lane and archive smoke; independent consumers) | UNVERIFIED | UNVERIFIED |
| Execution Events v1 (`--event-stream jsonl`, P0/P1) | PASS locally (14 CLI contract tests + 8 host + 4 runtime; independent Python schema consumer); post-beta, not in the tagged archive | UNVERIFIED | UNVERIFIED | | CLI Tool revision 1 + independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Tool Protocol v1 + 3 independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** | | Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** |
| Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) | | Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) |
| Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED | | Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED |
@@ -149,14 +149,15 @@ the Windows C ABI/provider paths remain fail-closed.
rlimits and wall-clock/output supervision; the child verifies `PID 1`, rlimits and wall-clock/output supervision; the child verifies `PID 1`,
`NoNewPrivs`, `CapEff=0`, a non-initial uid map and no non-loopback network. `NoNewPrivs`, `CapEff=0`, a non-initial uid map and no non-loopback network.
- Refused before launch: `--allow-read`, `--allow-write`, `--allow-foreign`, - Refused before launch: `--allow-read`, `--allow-write`, `--allow-foreign`,
`--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`, `--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`;
`--trace-file`. `--output jsonl` and `--observation-file` are refused because the supervisor
owns the output channel.
- Strict L2 (letting Worker/Foreign/native plugin run inside the sandbox) is - Strict L2 (letting Worker/Foreign/native plugin run inside the sandbox) is
not implemented and must not be inferred from L1 passing. not implemented and must not be inferred from L1 passing.
## Minimum environment ## Minimum environment
- Rust 1.82+ (verified with 1.100.0). - Rust 1.89+ (locked minimum; verified with 1.100.0).
- Linux/macOS: a C compiler for Native ABI fixtures; Python/Node only for - Linux/macOS: a C compiler for Native ABI fixtures; Python/Node only for
Foreign kernels; `git` for Git dependencies. Foreign kernels; `git` for Git dependencies.
- `strict` additionally requires Bubblewrap and a kernel/environment that - `strict` additionally requires Bubblewrap and a kernel/environment that
@@ -175,7 +176,7 @@ the Windows C ABI/provider paths remain fail-closed.
* The external conformance suite is a mandatory **additional** release gate * The external conformance suite is a mandatory **additional** release gate
(`docs/releasing.md` §7); it does not replace G3/G4/native lanes. (`docs/releasing.md` §7); it does not replace G3/G4/native lanes.
## Explicitly unsupported in this beta ## Explicitly unsupported in this prerelease
- Pre-RFC `.mq.md` source syntax (Strong-execute / Emph-return / ordered-list - Pre-RFC `.mq.md` source syntax (Strong-execute / Emph-return / ordered-list
branch / bullet-list loop / block-quote call / first code-span signature). branch / bullet-list loop / block-quote call / first code-span signature).
@@ -190,20 +191,19 @@ the Windows C ABI/provider paths remain fail-closed.
sessions, and general-purpose CAS. The three `sample-*` tools are test sessions, and general-purpose CAS. The three `sample-*` tools are test
fixtures for the generic Tool protocol, not product features. fixtures for the generic Tool protocol, not product features.
- Tagged Windows/macOS release archives: only the Linux x86_64 archive is - Tagged Windows/macOS release archives: only the Linux x86_64 archive is
produced for `3.0.0-beta.1`. macOS/Windows native artifacts are not claimed; produced for the 3.0 prerelease line. macOS/Windows native artifacts are not
the Windows lane is a Linux-hosted compile gate only. claimed; the Windows lane is a Linux-hosted compile gate only.
## Release decision ## Release decision
**`3.0.0-beta.1` prerelease — approved as a Linux x86_64 beta with explicitly **`3.0.0-rc.4` prerelease — released as a Linux x86_64 RC.** The RC profile in
recorded gaps.** The beta profile in [`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3 was
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3.1 used: Linux is the only supported platform, macOS/Windows are UNSUPPORTED for
was used, not the stable profile: Linux is the only supported platform, this scope, strict L1 has same-SHA disposable-VM evidence, and G4 performance is
macOS/Windows are declared unsupported/experimental, G4 is a Beta-only `WARN` a maintainer-approved shared-node `WARN` for this named RC only. The aggregate
on the fixed Woodpecker agent, and strict policy and frozen-binary conformance decision and per-gate evidence are in
are recorded with same-SHA evidence in [`docs/STATUS.md`](docs/STATUS.md) and [`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
[`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json) (`RC_RELEASE_CANDIDATE`) and the release assets; see
(`BETA_RELEASE_CANDIDATE`). Release: [`docs/evidence/2026-11-24-rc.3-release.md`](docs/evidence/2026-11-24-rc.3-release.md).
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. Beta status A prerelease does not imply stable `3.0.0` or LTS; the stable gate remains
does not imply stable `3.0.0` or LTS; the stable gate remains stricter and stricter and separate.
separate.
Generated
+16 -16
View File
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "marqdo-cli" name = "marqdo-cli"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"clap", "clap",
"hex", "hex",
@@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-expression" name = "marqdo-expression"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
@@ -449,7 +449,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-foreign" name = "marqdo-foreign"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"hex", "hex",
"libc", "libc",
@@ -465,7 +465,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-frontend" name = "marqdo-frontend"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-ir", "marqdo-ir",
@@ -480,7 +480,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-host" name = "marqdo-host"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"flate2", "flate2",
"getrandom 0.4.3", "getrandom 0.4.3",
@@ -505,7 +505,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-ir" name = "marqdo-ir"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-span", "marqdo-span",
@@ -515,7 +515,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-markdown" name = "marqdo-markdown"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"comrak", "comrak",
"marqdo-span", "marqdo-span",
@@ -526,7 +526,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-package" name = "marqdo-package"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"hex", "hex",
"semver", "semver",
@@ -540,7 +540,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-abi" name = "marqdo-plugin-abi"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"hex", "hex",
"libloading", "libloading",
@@ -556,7 +556,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-sdk" name = "marqdo-plugin-sdk"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-plugin-abi", "marqdo-plugin-abi",
"serde", "serde",
@@ -565,7 +565,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-provider-worker" name = "marqdo-provider-worker"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"libloading", "libloading",
"marqdo-host", "marqdo-host",
@@ -578,7 +578,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-runtime" name = "marqdo-runtime"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-frontend", "marqdo-frontend",
@@ -597,7 +597,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-sandbox" name = "marqdo-sandbox"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"libc", "libc",
"serde", "serde",
@@ -605,14 +605,14 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-span" name = "marqdo-span"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"serde", "serde",
] ]
[[package]] [[package]]
name = "marqdo-value" name = "marqdo-value"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
@@ -623,7 +623,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-worker-ipc" name = "marqdo-worker-ipc"
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"serde_json", "serde_json",
"thiserror", "thiserror",
+1 -1
View File
@@ -20,7 +20,7 @@ members = [
] ]
[workspace.package] [workspace.package]
version = "3.0.0-rc.3" version = "3.0.0-rc.4"
edition = "2021" edition = "2021"
rust-version = "1.89" rust-version = "1.89"
license = "Apache-2.0" license = "Apache-2.0"
+4 -4
View File
@@ -10,7 +10,7 @@ The official implementation is a Rust workspace; Python/Node are optional
foreign kernels, never the compiler target. foreign kernels, never the compiler target.
This repository is the new, independent Marqdo toolchain, now at product This repository is the new, independent Marqdo toolchain, now at product
version **`3.0.0-rc.3`** in this checkout. It is **not** a compatibility rewrite of version **`3.0.0-rc.4`** in this checkout. It is **not** a compatibility rewrite of
`cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not `cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not
claimed to work here. See [docs/developers/](docs/developers/README.md) for the claimed to work here. See [docs/developers/](docs/developers/README.md) for the
third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta
@@ -215,7 +215,7 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
`lock`, strict `sync --locked` with atomic `.marqdo/env` materialization. `lock`, strict `sync --locked` with atomic `.marqdo/env` materialization.
`run`/`call`/`check` never fetch or rewrite the lock. `run`/`call`/`check` never fetch or rewrite the lock.
* **P4 security core** — capability-checked host operations, project-relative * **P4 security core** — capability-checked host operations, project-relative
FS globs with traversal rejection, budgets, effect trace, `pure`/`project` FS globs with traversal rejection, budgets, Observation effect events, `pure`/`project`
modes, and **Linux `strict` mode** using Bubblewrap namespaces, no-new-privs, modes, and **Linux `strict` mode** using Bubblewrap namespaces, no-new-privs,
capability dropping, rlimits, a wall-clock supervisor and child capability dropping, rlimits, a wall-clock supervisor and child
self-verification (ADR-0021). It is probe-gated and verified in a disposable self-verification (ADR-0021). It is probe-gated and verified in a disposable
@@ -251,7 +251,7 @@ cargo clippy --workspace --all-targets -- -D warnings
* **Strict is Linux-only and L1-only.** `--mode strict` enables the * **Strict is Linux-only and L1-only.** `--mode strict` enables the
Bubblewrap supervisor only when its runtime probe passes; otherwise it exits Bubblewrap supervisor only when its runtime probe passes; otherwise it exits
1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels, 1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels,
external grants and trace files (exit 2). Worker plugins provide external grants and live/file observation destinations (exit 2). Worker plugins provide
crash/address-space isolation, not an OS sandbox, and are not allowed in crash/address-space isolation, not an OS sandbox, and are not allowed in
strict. strict.
* **Native plugins run in-process** and require an explicit unsafe trust flag. * **Native plugins run in-process** and require an explicit unsafe trust flag.
@@ -327,7 +327,7 @@ tests/ conformance/negative corpus (see tests/README.md)
* [`docs/developers/README.md`](docs/developers/README.md) — third-party and * [`docs/developers/README.md`](docs/developers/README.md) — third-party and
integrator entry point (libraries, tools, plugins, kernels, providers, integrator entry point (libraries, tools, plugins, kernels, providers,
Analysis/Trace consumers, compatibility). Analysis/Trace consumers, compatibility).
* [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md) * [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md) — beta-era integration handbook (historical; current contracts are `spec/`)
— end-to-end third-party integration handbook. — end-to-end third-party integration handbook.
* [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md) * [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md)
— historical stable-release roadmap input (its own header marks it Proposed — historical stable-release roadmap input (its own header marks it Proposed
-653
View File
@@ -1,653 +0,0 @@
//! Public Analysis projection (spec/analysis.md).
//!
//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node
//! kinds are the public contract, while internal Rust types may change. The
//! exporter is read-only and never executes a document, loads a plugin or
//! starts a foreign kernel.
use std::path::Path;
use marqdo_expression::{BinaryOp, Expr, UnaryOp};
use marqdo_ir::{Function, Module, ModuleId, PlaceTarget, Resource, SignatureKind, Stmt, UnitKind};
use marqdo_span::Span;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.analysis";
pub const SCHEMA_VERSION: u32 = 3;
/// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value {
let mut modules = Vec::new();
for (module_id, file) in &project.files {
let module = &file.analysis.module;
modules.push(json!({
"id": module_id.to_string(),
"package_instance_id": module_id.instance,
"relative_path": module_id.relative_path,
"source_digest": sha256_hex(file.source.as_bytes()),
"units": units_json(module),
"functions": module.functions.iter().map(function_json).collect::<Vec<_>>(),
"imports": module.imports.iter().map(|import| json!({
"alias": import.alias,
"target": import.target,
"span": import.span,
"resolved": project.program.resolve_import(module_id, &import.alias).map(ToString::to_string),
})).collect::<Vec<_>>(),
"references": reference_edges(project, module_id),
"calls": module.functions.iter().flat_map(|function| calls_json(project, module, function)).collect::<Vec<_>>(),
"resources": resources_json(module_id, module),
}));
}
modules.sort_by(|a, b| {
a.get("id")
.and_then(Value::as_str)
.cmp(&b.get("id").and_then(Value::as_str))
});
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"producer": {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
"markdown_profile": "marqdo.md.v1",
},
"project": {
"root_id": project.identity.root_id(),
"identity_kind": project.identity.kind(),
"lock_digest": lock_digest(project),
"stdlib": project.stdlib.as_ref().map(|stdlib| json!({
"version": stdlib.version,
"digest": stdlib.digest,
"instance_id": stdlib.instance_id,
})),
},
"modules": modules,
"diagnostics": diagnostics_json(project),
})
}
/// Encode exactly the bytes written by `check --emit`.
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(&build(project))
.map_err(|error| format!("cannot encode analysis: {error}"))
}
/// SHA-256 of the exact emitted Analysis bytes.
pub fn digest(project: &LoadedProject) -> Result<String, String> {
encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes)))
}
/// Atomically write the projection. An error must not leave a stale success
/// artifact behind.
pub fn write(project: &LoadedProject, path: &Path) -> Result<(), String> {
let bytes = encode(project)?;
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?;
let temporary = parent.join(format!(
".{}.tmp-{}",
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "analysis.json".to_string()),
std::process::id()
));
std::fs::write(&temporary, bytes)
.map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("cannot publish `{}`: {error}", path.display()));
}
Ok(())
}
fn lock_digest(project: &LoadedProject) -> Value {
let path = project.root.join(marqdo_package::LOCK_FILE);
match std::fs::read(path) {
Ok(bytes) => Value::String(format!("sha256:{}", sha256_hex(&bytes))),
Err(_) => Value::String(String::new()),
}
}
fn resources_json(module_id: &ModuleId, module: &Module) -> Vec<Value> {
let mut formula_index = 0usize;
let mut code_index = 0usize;
module
.resources
.iter()
.map(|resource| match resource {
Resource::Formula {
unit,
latex,
display,
span,
} => {
formula_index += 1;
json!({
"id": format!("{module_id}#resource:formula-{formula_index}"),
"module_id": module_id.to_string(),
"unit_id": unit.to_string(),
"kind": "formula",
"span": span_json(*span),
"content_digest": sha256_hex(latex.as_bytes()),
"language": null,
"display": display,
})
}
Resource::Code {
unit,
language,
source: _,
content_hash,
span,
} => {
code_index += 1;
json!({
"id": format!("{module_id}#resource:code-{code_index}"),
"module_id": module_id.to_string(),
"unit_id": unit.to_string(),
"kind": "code",
"span": span_json(*span),
"content_digest": content_hash,
"language": language,
})
}
})
.collect()
}
fn diagnostics_json(project: &LoadedProject) -> Vec<Value> {
project
.diagnostics
.iter()
.map(|item| {
let (line, column) = item
.line_col()
.map(|(line, column)| (Value::from(line), Value::from(column)))
.unwrap_or((Value::Null, Value::Null));
json!({
"module": item.module_id.to_string(),
"relative_path": item.module_id.relative_path,
"span": item.diagnostic.span.map(span_json),
"line": line,
"column": column,
"severity": if item.diagnostic.is_error() { "error" } else { "warning" },
"code": item.diagnostic.code,
"message": item.diagnostic.message,
"hints": item.diagnostic.hints,
})
})
.collect()
}
fn units_json(module: &Module) -> Vec<Value> {
module
.units
.iter()
.map(|unit| {
let kind = match unit.kind {
UnitKind::Root => "root",
UnitKind::Namespace => "namespace",
UnitKind::Function => "function",
UnitKind::Knowledge => "knowledge",
UnitKind::Section => "section",
};
json!({
"id": unit.id.to_string(),
"kind": kind,
"name": unit.name,
"level": unit.level,
"span": span_json(unit.span),
"function": unit.function.as_ref().map(ToString::to_string),
})
})
.collect()
}
fn function_json(function: &Function) -> Value {
json!({
"id": function.id.to_string(),
"unit_id": function.unit.to_string(),
"local_name": function.local_name,
"namespace": function.namespace,
"span": span_json(function.span),
"heading_span": span_json(function.heading_span),
"signature": {
"kind": match function.signature {
SignatureKind::Explicit => "explicit",
SignatureKind::Inferred => "inferred",
},
"params": function.params.iter().map(|param| json!({
"name": param.name,
"required": param.default.is_none(),
"type": param.type_annotation,
"default": param.default.as_ref().map(expr_json),
"span": span_json(param.span),
})).collect::<Vec<_>>(),
},
"effects": ["unknown"],
"body": function.body.iter().map(stmt_json).collect::<Vec<_>>(),
})
}
/// Project an assignment place. Local targets keep the v1 string form; the new
/// index target is an additive object so existing consumers that compare the
/// local `target` string are unaffected (Analysis v2, ADR-0022).
fn place_json(place: &PlaceTarget) -> Value {
match place {
PlaceTarget::Local { name, .. } => Value::String(name.clone()),
PlaceTarget::Index { base, index, span } => json!({
"kind": "index",
"base": expr_json(base),
"index": expr_json(index),
"span": span_json(*span),
}),
}
}
fn stmt_json(stmt: &Stmt) -> Value {
match stmt {
Stmt::Assign {
target,
value,
span,
..
} => json!({
"kind": "assign",
"target": place_json(target),
"value": expr_json(value),
"span": span_json(*span),
}),
Stmt::Eval { expr, span } => json!({
"kind": "expression",
"value": expr_json(expr),
"span": span_json(*span),
}),
Stmt::Branch { arms, span } => json!({
"kind": "branch",
"arms": arms.iter().map(|arm| json!({
"condition": expr_json(&arm.condition),
"condition_span": span_json(arm.condition_span),
"body": arm.body.iter().map(stmt_json).collect::<Vec<_>>(),
"span": span_json(arm.span),
})).collect::<Vec<_>>(),
"span": span_json(*span),
}),
Stmt::Loop {
condition,
condition_span,
body,
span,
} => json!({
"kind": "loop",
"condition": expr_json(condition),
"condition_span": span_json(*condition_span),
"body": body.iter().map(stmt_json).collect::<Vec<_>>(),
"span": span_json(*span),
}),
Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}),
Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}),
Stmt::Return { value, span } => json!({
"kind": "return",
"value": expr_json(value),
"span": span_json(*span),
}),
}
}
fn expr_json(expr: &Expr) -> Value {
let span = span_json(expr.span());
match expr {
Expr::Int(value) => {
json!({"kind":"literal","type":"int","value":value.to_string(),"span":span})
}
Expr::Float(value) => json!({"kind":"literal","type":"float","value":value,"span":span}),
Expr::Text(value) => json!({"kind":"literal","type":"text","value":value,"span":span}),
Expr::Bool(value) => json!({"kind":"literal","type":"bool","value":value,"span":span}),
Expr::None => json!({"kind":"literal","type":"none","span":span}),
Expr::Ident(ident) => {
json!({"kind":"variable","name":ident.name,"span":span_json(ident.span)})
}
Expr::List(items) => {
json!({"kind":"list","items":items.iter().map(expr_json).collect::<Vec<_>>(),"span":span})
}
Expr::Record(entries) => json!({
"kind":"record",
"entries": entries.iter().map(|entry| json!({
"key": entry.key,
"key_span": span_json(entry.key_span),
"value": expr_json(&entry.value),
})).collect::<Vec<_>>(),
"span":span
}),
Expr::Unary { op, operand, .. } => json!({
"kind":"unary",
"op": unary_name(*op),
"operand": expr_json(operand),
"span":span
}),
Expr::Binary {
op, left, right, ..
} => json!({
"kind":"binary",
"op": binary_name(*op),
"left": expr_json(left),
"right": expr_json(right),
"span":span
}),
Expr::Member { base, name, .. } => json!({
"kind":"member",
"base": expr_json(base),
"field": name,
"span":span
}),
Expr::Index { base, index, .. } => json!({
"kind":"index",
"base": expr_json(base),
"index": expr_json(index),
"span":span
}),
Expr::Call { callee, args, .. } => json!({
"kind":"call",
"callee": expr_json(callee),
"args": args.iter().map(arg_json).collect::<Vec<_>>(),
"span":span
}),
}
}
fn arg_json(arg: &marqdo_expression::Arg) -> Value {
json!({
"name": arg.name,
"value": expr_json(&arg.value),
"span": span_json(arg.span),
})
}
fn reference_edges(project: &LoadedProject, module_id: &marqdo_ir::ModuleId) -> Vec<Value> {
let Some(file) = project.files.get(module_id) else {
return Vec::new();
};
let parent = file.path.parent().unwrap_or_else(|| Path::new("."));
let mut edges = Vec::new();
file.analysis.document.root.walk(&mut |node| {
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
return;
};
edges.push(resolve_reference(
project,
module_id,
&file.analysis.units,
parent,
url,
node.span,
));
});
edges.sort_by_key(|edge| {
edge.get("span")
.and_then(|span| span.get("start"))
.and_then(Value::as_u64)
.unwrap_or(0)
});
edges
}
fn resolve_reference(
project: &LoadedProject,
source_module: &marqdo_ir::ModuleId,
units: &marqdo_frontend::UnitIndex,
parent: &Path,
url: &str,
span: Span,
) -> Value {
if let Some(fragment) = url.strip_prefix('#') {
let unit = units.anchors.get(fragment).or_else(|| {
units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
});
return json!({
"source": source_module.to_string(),
"url": url,
"span": span_json(span),
"state": if unit.is_some() { "resolved" } else { "unresolved" },
"target_module": source_module.to_string(),
"target_unit": unit.map(ToString::to_string),
});
}
if url.starts_with("http://") || url.starts_with("https://") {
return json!({
"source": source_module.to_string(),
"url": url,
"span": span_json(span),
"state": "external",
"target_module": null,
"target_unit": null,
});
}
let (path_part, fragment) = match url.split_once('#') {
Some((path, fragment)) => (path, Some(fragment)),
None => (url, None),
};
let candidate = parent.join(path_part);
let Some(target_module) = project.module_id_for_path(&candidate) else {
return json!({
"source": source_module.to_string(),
"url": url,
"span": span_json(span),
"state": "unresolved",
"target_module": null,
"target_unit": null,
});
};
let target_units = project
.files
.get(&target_module)
.map(|file| &file.analysis.units);
let resolved = match (fragment, target_units) {
(None, _) => Some(None),
(Some(fragment), Some(units)) => units
.anchors
.get(fragment)
.or_else(|| {
units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
})
.map(|unit| Some(unit.to_string())),
(Some(_), None) => None,
};
let (state, target_unit) = match resolved {
Some(unit) => ("resolved", unit),
None => ("unresolved", None),
};
json!({
"source": source_module.to_string(),
"url": url,
"span": span_json(span),
"state": state,
"target_module": target_module.to_string(),
"target_unit": target_unit,
})
}
fn calls_json(project: &LoadedProject, module: &Module, function: &Function) -> Vec<Value> {
let mut calls = Vec::new();
collect_calls(project, module, function, &function.body, &mut calls);
calls.sort_by_key(|call| {
call.get("span")
.and_then(|span| span.get("start"))
.and_then(Value::as_u64)
.unwrap_or(0)
});
calls
}
fn collect_calls(
project: &LoadedProject,
module: &Module,
function: &Function,
body: &[Stmt],
calls: &mut Vec<Value>,
) {
for stmt in body {
match stmt {
Stmt::Assign { target, value, .. } => {
if let PlaceTarget::Index { base, index, .. } = target {
expr_calls(project, module, function, base, calls);
expr_calls(project, module, function, index, calls);
}
expr_calls(project, module, function, value, calls);
}
Stmt::Eval { expr: value, .. } => expr_calls(project, module, function, value, calls),
Stmt::Return { value, .. } => expr_calls(project, module, function, value, calls),
Stmt::Branch { arms, .. } => {
for arm in arms {
expr_calls(project, module, function, &arm.condition, calls);
collect_calls(project, module, function, &arm.body, calls);
}
}
Stmt::Loop {
condition, body, ..
} => {
expr_calls(project, module, function, condition, calls);
collect_calls(project, module, function, body, calls);
}
Stmt::Break { .. } | Stmt::Continue { .. } => {}
}
}
}
fn expr_calls(
project: &LoadedProject,
module: &Module,
function: &Function,
expr: &Expr,
calls: &mut Vec<Value>,
) {
match expr {
Expr::Call { callee, args, span } => {
let (state, target) = resolve_callee(project, module, function, *span);
calls.push(json!({
"function": function.id.to_string(),
"span": span_json(*span),
"callee": callee_json(callee),
"state": state,
"target": target,
}));
for arg in args {
expr_calls(project, module, function, &arg.value, calls);
}
}
Expr::Unary { operand, .. } => expr_calls(project, module, function, operand, calls),
Expr::Binary { left, right, .. } => {
expr_calls(project, module, function, left, calls);
expr_calls(project, module, function, right, calls);
}
Expr::List(items) => {
for item in items {
expr_calls(project, module, function, item, calls);
}
}
Expr::Record(entries) => {
for entry in entries {
expr_calls(project, module, function, &entry.value, calls);
}
}
Expr::Member { base, .. } => expr_calls(project, module, function, base, calls),
Expr::Index { base, index, .. } => {
expr_calls(project, module, function, base, calls);
expr_calls(project, module, function, index, calls);
}
_ => {}
}
}
/// Project the authoritative call binding into the Analysis `state`/`target`
/// fields.
///
/// Analysis is a read-only projection of the same prepared binding the runtime
/// consumes (RFC-EXT-0001 §4/§9): there is no second name-resolution algorithm
/// here. `state` keeps its v1 vocabulary (`function`, `builtin`, `plugin`,
/// `unresolved`); official stdlib aliases such as `打印` therefore appear as
/// `function` targets because that is the implementation that actually runs.
fn resolve_callee(
project: &LoadedProject,
_module: &Module,
function: &Function,
span: Span,
) -> (&'static str, Value) {
let key = marqdo_ir::call_binding::CallSiteKey::new(function.id.clone(), span);
match project.program.call_bindings.get(&key) {
Some(marqdo_ir::call_binding::BoundTarget::Builtin { canonical_name }) => {
("builtin", json!(canonical_name))
}
Some(marqdo_ir::call_binding::BoundTarget::Marqdo { function }) => {
("function", json!(function.to_string()))
}
Some(marqdo_ir::call_binding::BoundTarget::AbiPlugin { export, .. }) => {
("plugin", json!(export))
}
Some(marqdo_ir::call_binding::BoundTarget::DynamicValue) | None => {
("unresolved", Value::Null)
}
}
}
fn callee_json(callee: &Expr) -> Value {
match callee {
Expr::Ident(ident) => json!({"kind":"ident","name":ident.name}),
Expr::Member { base, name, .. } => {
json!({"kind":"member","base":callee_json(base),"field":name})
}
other => json!({"kind":"expression","span":span_json(other.span())}),
}
}
fn span_json(span: Span) -> Value {
json!({"start": span.start, "end": span.end})
}
fn unary_name(op: UnaryOp) -> &'static str {
match op {
UnaryOp::Not => "not",
UnaryOp::Neg => "neg",
UnaryOp::Pos => "pos",
}
}
fn binary_name(op: BinaryOp) -> &'static str {
match op {
BinaryOp::Or => "or",
BinaryOp::And => "and",
BinaryOp::Eq => "eq",
BinaryOp::Ne => "ne",
BinaryOp::Lt => "lt",
BinaryOp::Le => "le",
BinaryOp::Gt => "gt",
BinaryOp::Ge => "ge",
BinaryOp::Add => "add",
BinaryOp::Sub => "sub",
BinaryOp::Mul => "mul",
BinaryOp::Div => "div",
BinaryOp::FloorDiv => "floor_div",
BinaryOp::Mod => "mod",
BinaryOp::Pow => "pow",
}
}
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
+115
View File
@@ -0,0 +1,115 @@
//! Explicit projector from the canonical Markdown AST to the public document
//! shape (spec/markdown-profile.md §5, spec/analysis.md §3.1).
//!
//! The same projector is used by Analysis and `inspect --ast`; there is no
//! second tree and no serde dump of an internal Rust enum.
use marqdo_markdown::{MdKind, MdNode};
use marqdo_span::Span;
use serde_json::{json, Map, Value};
/// Project one document root. The root span is normalised to the whole source
/// (including a tolerated BOM); child spans keep their parser coordinates.
pub fn document_json(root: &MdNode, source_len: usize) -> Value {
node_json(root, Some(Span::new(0, source_len)))
}
fn node_json(node: &MdNode, span_override: Option<Span>) -> Value {
let span = span_override.unwrap_or(node.span);
let mut object = Map::new();
object.insert("kind".to_string(), json!(node.kind.tag()));
object.insert(
"span".to_string(),
json!({"start": span.start, "end": span.end}),
);
let children: Vec<Value> = node
.children
.iter()
.map(|child| node_json(child, None))
.collect();
object.insert("children".to_string(), Value::Array(children));
match &node.kind {
MdKind::Document
| MdKind::BlockQuote
| MdKind::Paragraph
| MdKind::Strong
| MdKind::Emph
| MdKind::Strikethrough
| MdKind::TableCell
| MdKind::ThematicBreak
| MdKind::SoftBreak
| MdKind::LineBreak => {}
MdKind::FrontMatter => {
object.insert(
"literal".to_string(),
Value::String(node.literal.clone().unwrap_or_default()),
);
}
MdKind::Text | MdKind::MathBlock | MdKind::HtmlBlock | MdKind::HtmlInline => {
object.insert(
"literal".to_string(),
Value::String(node.literal.clone().unwrap_or_default()),
);
}
MdKind::Code { ticks } => {
object.insert("ticks".to_string(), json!(ticks));
object.insert(
"literal".to_string(),
Value::String(node.literal.clone().unwrap_or_default()),
);
}
MdKind::CodeBlock { fenced, info } => {
object.insert("fenced".to_string(), json!(fenced));
object.insert("info".to_string(), json!(info));
object.insert(
"literal".to_string(),
Value::String(node.literal.clone().unwrap_or_default()),
);
}
MdKind::Math { display } => {
object.insert("display".to_string(), json!(display));
object.insert(
"literal".to_string(),
Value::String(node.literal.clone().unwrap_or_default()),
);
}
MdKind::Heading { level, setext } => {
object.insert("level".to_string(), json!(level));
object.insert("setext".to_string(), json!(setext));
}
MdKind::List {
ordered,
start,
tight,
} => {
object.insert("ordered".to_string(), json!(ordered));
object.insert("start".to_string(), json!(start));
object.insert("tight".to_string(), json!(tight));
}
MdKind::Item { task } => {
object.insert("task".to_string(), json!(task));
}
MdKind::Link { url, title } | MdKind::Image { url, title } => {
object.insert("url".to_string(), json!(url));
object.insert("title".to_string(), json!(title));
}
MdKind::Table { alignments } => {
object.insert("alignments".to_string(), json!(alignments));
}
MdKind::TableRow { header } => {
object.insert("header".to_string(), json!(header));
}
MdKind::FootnoteDefinition { .. } | MdKind::FootnoteReference { .. } => {
// The frozen profile disables footnotes; the semantic validator
// rejects them if a future parser change ever emits one.
object.insert("tag".to_string(), json!(node.kind.tag()));
}
MdKind::Other { tag } => {
object.insert("tag".to_string(), json!(tag));
if let Some(literal) = &node.literal {
object.insert("literal".to_string(), Value::String(literal.clone()));
}
}
}
Value::Object(object)
}
File diff suppressed because it is too large. Load diff
+340
View File
@@ -0,0 +1,340 @@
//! Typed public Analysis DTO (spec/analysis.md).
//!
//! These types are the boundary model, not a dump of internal IR: every field
//! is projected explicitly from the prepared program. The canonical encoder
//! serializes this model once; the file writer and the Observation digest use
//! the same bytes.
use serde::Serialize;
use serde_json::Value;
/// Half-open UTF-8 byte span in the owning module's `source`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SpanJson {
/// Inclusive byte offset.
pub start: usize,
/// Exclusive byte offset.
pub end: usize,
}
impl From<marqdo_span::Span> for SpanJson {
fn from(span: marqdo_span::Span) -> Self {
Self {
start: span.start,
end: span.end,
}
}
}
/// Root Analysis document.
#[derive(Debug, Clone, Serialize)]
pub struct Analysis {
/// `marqdo.analysis`.
pub schema: &'static str,
/// Current revision.
pub schema_version: u32,
/// Producer identity.
pub producer: Producer,
/// Project snapshot and entry context.
pub project: Project,
/// Loaded modules, sorted by id.
pub modules: Vec<ModuleAnalysis>,
/// Deterministic diagnostics.
pub diagnostics: Vec<DiagnosticRecord>,
}
/// Producer identity.
#[derive(Debug, Clone, Serialize)]
pub struct Producer {
/// Always `marqdo`.
pub name: &'static str,
/// Product version.
pub version: &'static str,
/// Markdown profile id.
pub markdown_profile: &'static str,
}
/// Project snapshot identity.
#[derive(Debug, Clone, Serialize)]
pub struct Project {
/// Logical root id.
pub root_id: String,
/// `manifest` or `workspace_snapshot`.
pub identity_kind: &'static str,
/// Module loaded from the CLI entry.
pub entry_module_id: String,
/// Captured lock digest, empty when no lock exists.
pub lock_digest: String,
/// Captured manifest digest, empty when no manifest exists.
pub manifest_digest: String,
/// Verified stdlib identity, if any.
pub stdlib: Option<Stdlib>,
/// Static extension identities that participated in preparation.
pub extensions: Vec<Extension>,
}
/// Verified bundled stdlib identity.
#[derive(Debug, Clone, Serialize)]
pub struct Stdlib {
/// Declared version.
pub version: String,
/// Verified content digest.
pub digest: String,
/// Package instance id.
pub instance_id: String,
}
/// One static extension identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Extension {
/// `plugin`, `kernel` or `provider`.
pub kind: &'static str,
/// Declared package/provider name.
pub name: String,
/// Declared version.
pub version: String,
/// Logical owner package instance.
pub logical_owner: String,
/// Declared activation source, or `--plugin`.
pub source: String,
/// Manifest digest (`sha256:<hex>`).
pub manifest_digest: String,
/// Selected artifact digest (`sha256:<hex>`).
pub artifact_digest: String,
/// Selected host target triple.
pub selected_target: String,
}
/// One loaded module.
#[derive(Debug, Clone, Serialize)]
pub struct ModuleAnalysis {
/// Canonical module id.
pub id: String,
/// Package instance.
pub package_instance_id: String,
/// Package-relative path with `/` separators.
pub relative_path: String,
/// SHA-256 of the exact source bytes.
pub source_digest: String,
/// Exact UTF-8 source text.
pub source: String,
/// Public Markdown AST.
pub document: Value,
/// Heading units in document order.
pub units: Vec<UnitRecord>,
/// Anchor map sorted by anchor.
pub anchors: Vec<AnchorRecord>,
/// Exec H2 functions in document order.
pub functions: Vec<FunctionRecord>,
/// Explicit imports in document order.
pub imports: Vec<ImportRecord>,
/// Markdown references in source order.
pub references: Vec<ReferenceRecord>,
/// Static call bindings in source order.
pub calls: Vec<CallRecord>,
/// Inert resources in document order.
pub resources: Vec<ResourceRecord>,
}
/// One addressable heading range.
#[derive(Debug, Clone, Serialize)]
pub struct UnitRecord {
/// Canonical unit id.
pub id: String,
/// Structured canonical path.
pub path: Vec<String>,
/// Parent unit id, root `null`.
pub parent_id: Option<String>,
/// `root`, `namespace`, `function`, `knowledge` or `section`.
pub kind: &'static str,
/// Normalised heading name.
pub name: String,
/// Heading level, root 0.
pub level: u8,
/// Effective mode.
pub mode: &'static str,
/// `default`, `explicit` or `inherited`.
pub mode_origin: &'static str,
/// Unit that provided the effective mode.
pub mode_source_unit_id: String,
/// Original heading span, root `null`.
pub heading_span: Option<SpanJson>,
/// Complete section range.
pub span: SpanJson,
/// Owning function id.
pub function: Option<String>,
}
/// One anchor entry.
#[derive(Debug, Clone, Serialize)]
pub struct AnchorRecord {
/// GitHub-style anchor.
pub anchor: String,
/// Addressable unit.
pub unit_id: String,
}
/// One Exec H2 function.
#[derive(Debug, Clone, Serialize)]
pub struct FunctionRecord {
/// Canonical function id.
pub id: String,
/// Addressable unit.
pub unit_id: String,
/// Local function name.
pub local_name: String,
/// Enclosing namespace.
pub namespace: Option<String>,
/// Declaration span.
pub span: SpanJson,
/// Heading span.
pub heading_span: SpanJson,
/// Signature.
pub signature: SignatureRecord,
/// Conservative effects.
pub effects: Vec<&'static str>,
/// Statements.
pub body: Vec<Value>,
}
/// Function signature.
#[derive(Debug, Clone, Serialize)]
pub struct SignatureRecord {
/// `explicit` or `inferred`.
pub kind: &'static str,
/// Parameters.
pub params: Vec<ParamRecord>,
}
/// One function parameter.
#[derive(Debug, Clone, Serialize)]
pub struct ParamRecord {
/// Parameter name.
pub name: String,
/// Whether no default value exists.
pub required: bool,
/// Declared type annotation.
pub r#type: Option<String>,
/// Default expression.
pub default: Option<Value>,
/// Declaration span.
pub span: SpanJson,
}
/// One explicit import.
#[derive(Debug, Clone, Serialize)]
pub struct ImportRecord {
/// Local alias.
pub alias: String,
/// Declared target.
pub target: String,
/// Declaration span.
pub span: SpanJson,
/// Resolved module id.
pub resolved: Option<String>,
}
/// One resolved document reference.
#[derive(Debug, Clone, Serialize)]
pub struct ReferenceRecord {
/// Source module.
pub source: String,
/// Innermost owning unit.
pub source_unit: String,
/// Raw URL.
pub url: String,
/// Link span.
pub span: SpanJson,
/// Resolver state.
pub state: &'static str,
/// `module`, `file` or `null`.
pub target_kind: Option<&'static str>,
/// Resolved module.
pub target_module: Option<String>,
/// Resolved unit.
pub target_unit: Option<String>,
/// Logical candidate package instance.
pub candidate_package_instance_id: Option<String>,
/// Normalised package-relative candidate.
pub candidate_path: Option<String>,
/// Decoded fragment.
pub fragment: Option<String>,
/// Ambiguous exact candidates.
pub candidates: Vec<String>,
}
/// One static call record.
#[derive(Debug, Clone, Serialize)]
pub struct CallRecord {
/// Caller function id.
pub function: String,
/// Call expression span.
pub span: SpanJson,
/// Callee shape.
pub callee: Value,
/// Function, builtin, plugin or unresolved.
pub state: &'static str,
/// Bound target value.
pub target: Option<String>,
/// `function`, `builtin`, `plugin` or `null`.
pub target_kind: Option<&'static str>,
/// Static plugin owner, if any.
pub target_owner: Option<TargetOwner>,
/// `dynamic`, `unbound` or `null`.
pub reason: Option<&'static str>,
}
/// Static plugin owner of a bound export.
#[derive(Debug, Clone, Serialize)]
pub struct TargetOwner {
/// Always `plugin`.
pub kind: &'static str,
/// Plugin package.
pub package: String,
/// Verified artifact digest.
pub digest: String,
}
/// One inert resource.
#[derive(Debug, Clone, Serialize)]
pub struct ResourceRecord {
/// Module-local ordinal id.
pub id: String,
/// Owning module.
pub module_id: String,
/// Innermost owning unit.
pub unit_id: String,
/// `formula` or `code`.
pub kind: &'static str,
/// AST node span.
pub span: SpanJson,
/// Payload digest.
pub content_digest: String,
/// Code fence language.
pub language: Option<String>,
/// Formula display mode (`null` for code).
pub display: Option<bool>,
}
/// One diagnostic.
#[derive(Debug, Clone, Serialize)]
pub struct DiagnosticRecord {
/// Owning module.
pub module: String,
/// Package-relative path.
pub relative_path: String,
/// Primary span.
pub span: Option<SpanJson>,
/// 1-based line.
pub line: Option<usize>,
/// 1-based column.
pub column: Option<usize>,
/// `error` or `warning`.
pub severity: &'static str,
/// Stable code.
pub code: String,
/// Message.
pub message: String,
/// Hints.
pub hints: Vec<String>,
}
+2 -122
View File
@@ -64,38 +64,6 @@ pub(super) fn prepare_project(
} }
} }
/// `marqdo check`.
fn validate_refs(project: &LoadedProject) -> Vec<FileDiagnostic> {
let mut diagnostics = Vec::new();
for file in project.files.values() {
let parent = file.path.parent().unwrap_or_else(|| Path::new("."));
let mut unresolved: Vec<marqdo_span::Span> = Vec::new();
file.analysis.document.root.walk(&mut |node| {
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
return;
};
let (resolved, _, _) = resolve_link(project, &file.analysis.units, parent, url);
if !resolved {
unresolved.push(node.span);
}
});
for span in unresolved {
diagnostics.push(FileDiagnostic {
module_id: file.module_id.clone(),
path: file.path.clone(),
source: file.source.clone(),
diagnostic: marqdo_value::Diagnostic::error(
marqdo_value::codes::REF_UNRESOLVED,
Some(span),
"reference target could not be resolved",
)
.with_hint("fix the link target or add the missing heading/file"),
});
}
}
diagnostics
}
fn summary_json(project: &LoadedProject) -> serde_json::Value { fn summary_json(project: &LoadedProject) -> serde_json::Value {
let entry = project.entry_file(); let entry = project.entry_file();
json!({ json!({
@@ -130,94 +98,6 @@ fn signatures_json(module: &marqdo_ir::Module) -> serde_json::Value {
) )
} }
fn refs_json(project: &LoadedProject) -> serde_json::Value {
let entry = project.entry_file();
let parent = entry.path.parent().unwrap_or_else(|| Path::new("."));
let mut edges = Vec::new();
entry.analysis.document.root.walk(&mut |node| {
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
return;
};
let (resolved, target_module, target_unit) =
resolve_link(project, &entry.analysis.units, parent, url);
edges.push(json!({
"source": entry.module_id.to_string(),
"url": url,
"span": node.span,
"resolved": resolved,
"target_module": target_module,
"target_unit": target_unit,
}));
});
serde_json::Value::Array(edges)
}
fn resolve_link(
project: &LoadedProject,
units: &marqdo_frontend::UnitIndex,
parent: &Path,
url: &str,
) -> (bool, Option<String>, Option<String>) {
if let Some(fragment) = url.strip_prefix('#') {
let unit = units.anchors.get(fragment).or_else(|| {
units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
});
return match unit {
Some(unit) => (
true,
Some(project.entry.to_string()),
Some(unit.to_string()),
),
None => (false, None, None),
};
}
if url.starts_with("http://") || url.starts_with("https://") {
return (true, None, None);
}
let (path_part, fragment) = match url.split_once('#') {
Some((path, fragment)) => (path, Some(fragment)),
None => (url, None),
};
let candidate = parent.join(path_part);
let Ok(candidate) = candidate.canonicalize() else {
return (false, None, None);
};
let Some(module_id) = project.module_id_for_path(&candidate) else {
return (false, None, None);
};
let analyzed;
let target_units = match project.files.get(&module_id) {
Some(target_file) => &target_file.analysis.units,
None => {
// Links may reference documents that are not imported. Analyse the
// target statically for reference checking; nothing executes.
let Ok(source) = std::fs::read_to_string(&candidate) else {
return (false, None, None);
};
analyzed = marqdo_frontend::analyze_source(&module_id.to_string(), &source);
&analyzed.units
}
};
let Some(fragment) = fragment else {
return (true, Some(module_id.to_string()), None);
};
let resolved = target_units.anchors.get(fragment).or_else(|| {
target_units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
});
match resolved {
Some(unit) => (true, Some(module_id.to_string()), Some(unit.to_string())),
None => (false, Some(module_id.to_string()), None),
}
}
/// Machine-readable routing decision for one captured strict execution. /// Machine-readable routing decision for one captured strict execution.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum StrictRoute { enum StrictRoute {
@@ -418,7 +298,8 @@ fn runtime_location_json(
if let Some(located) = project.locate(module_id, span) { if let Some(located) = project.locate(module_id, span) {
location["line"] = json!(located.line); location["line"] = json!(located.line);
location["column"] = json!(located.column); location["column"] = json!(located.column);
location["file"] = json!(located.file.path.display().to_string()); // Attribution for a shareable snapshot is the project-relative
// path; an absolute host path is environment data, not contract.
location["relative_path"] = json!(located.file.module_id.relative_path); location["relative_path"] = json!(located.file.module_id.relative_path);
} }
} }
@@ -444,7 +325,6 @@ fn runtime_error_json(error: &RuntimeError, project: &LoadedProject) -> serde_js
"span": location["span"], "span": location["span"],
"line": location["line"], "line": location["line"],
"column": location["column"], "column": location["column"],
"file": location["file"],
"relative_path": location["relative_path"], "relative_path": location["relative_path"],
"frames": frames, "frames": frames,
}) })
+39 -11
View File
@@ -11,22 +11,50 @@ pub fn check(
) -> i32 { ) -> i32 {
let prepared = match prepare_project(file, json, plugins) { let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(code) => return code, Err(code) => {
}; // A failed check never leaves a success artifact behind: a consumer
let mut project = prepared.loaded; // must not bind `run` to a previous Analysis after the project
if refs { // stopped loading. The input document is never the cleanup target.
let ref_diagnostics = validate_refs(&project);
project.diagnostics.extend(ref_diagnostics);
}
let errors = output::error_count(&project.diagnostics);
if let Some(path) = emit { if let Some(path) = emit {
if errors > 0 { if let Err(error) = crate::analysis::discard_without_prepare(file, path) {
let _ = std::fs::remove_file(path);
} else if let Err(error) = crate::analysis::write(&project, path) {
eprintln!("error: {error}"); eprintln!("error: {error}");
return 2; return 2;
} }
} }
return code;
}
};
let mut prepared = prepared;
if refs {
let report = crate::document_refs::references_for_project(
&prepared.loaded,
crate::document_refs::ReferenceMode::VerifyLocal,
);
for issue in report.issues {
let Some(file) = prepared.loaded.files.get(&issue.module) else {
continue;
};
prepared.loaded.diagnostics.push(FileDiagnostic {
module_id: issue.module,
path: file.path.clone(),
source: file.source.clone(),
diagnostic: issue.diagnostic,
});
}
}
let errors = output::error_count(&prepared.loaded.diagnostics);
if let Some(path) = emit {
if errors > 0 {
if let Err(error) = crate::analysis::discard(&prepared, path) {
eprintln!("error: {error}");
return 2;
}
} else if let Err(error) = crate::analysis::write(&prepared, path) {
eprintln!("error: {error}");
return 2;
}
}
let project = &prepared.loaded;
if json { if json {
output::print_json(&json!({ output::print_json(&json!({
"command": "check", "command": "check",
+63 -6
View File
@@ -46,13 +46,20 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
if flags.ast { if flags.ast {
object.insert( object.insert(
"ast".into(), "ast".into(),
serde_json::to_value(&entry.analysis.document.root).unwrap_or_default(), crate::analysis::document_projection(
&entry.analysis.document.root,
entry.source.len(),
),
); );
} }
if flags.units { if flags.units {
object.insert( object.insert(
"units".into(), "units".into(),
serde_json::to_value(&entry.analysis.units.units).unwrap_or_default(), serde_json::to_value(crate::analysis::units_projection(
&entry.analysis.units,
entry.source.len(),
))
.unwrap_or_default(),
); );
} }
if flags.signature { if flags.signature {
@@ -65,7 +72,9 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
); );
} }
if flags.refs { if flags.refs {
object.insert("refs".into(), json!(refs_json(project))); let (references, issues) = refs_json(&prepared, &entry.module_id);
object.insert("refs".into(), references);
object.insert("reference_issues".into(), issues);
} }
if flags.platform { if flags.platform {
object.insert( object.insert(
@@ -106,13 +115,21 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
if flags.ast { if flags.ast {
println!( println!(
"{}", "{}",
serde_json::to_string_pretty(&entry.analysis.document.root).unwrap_or_default() serde_json::to_string_pretty(&crate::analysis::document_projection(
&entry.analysis.document.root,
entry.source.len()
))
.unwrap_or_default()
); );
} }
if flags.units { if flags.units {
println!( println!(
"{}", "{}",
serde_json::to_string_pretty(&entry.analysis.units.units).unwrap_or_default() serde_json::to_string_pretty(&crate::analysis::units_projection(
&entry.analysis.units,
entry.source.len()
))
.unwrap_or_default()
); );
} }
if flags.signature { if flags.signature {
@@ -128,9 +145,14 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
); );
} }
if flags.refs { if flags.refs {
let (references, issues) = refs_json(&prepared, &entry.module_id);
println!( println!(
"{}", "{}",
serde_json::to_string_pretty(&refs_json(project)).unwrap_or_default() serde_json::to_string_pretty(&json!({
"refs": references,
"reference_issues": issues,
}))
.unwrap_or_default()
); );
} }
if flags.platform { if flags.platform {
@@ -149,6 +171,41 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
0 0
} }
/// Resolve the entry module's links through the one document resolver and the
/// explicit `--refs` catalog. `inspect` never executes a target.
fn refs_json(
prepared: &crate::project_prepare::PreparedProgram,
entry: &marqdo_ir::ModuleId,
) -> (serde_json::Value, serde_json::Value) {
let report = crate::document_refs::references_for_project(
&prepared.loaded,
crate::document_refs::ReferenceMode::VerifyLocal,
);
let references: Vec<crate::analysis::ReferenceRecord> = report
.by_module
.get(entry)
.cloned()
.unwrap_or_default()
.into_iter()
.map(crate::analysis::reference_projection)
.collect();
let references = serde_json::to_value(references).unwrap_or_default();
let issues = report
.issues
.iter()
.filter(|issue| &issue.module == entry)
.map(|issue| {
json!({
"code": issue.diagnostic.code,
"severity": if issue.diagnostic.is_error() { "error" } else { "warning" },
"span": issue.diagnostic.span.map(|span| json!({"start": span.start, "end": span.end})),
"message": issue.diagnostic.message,
})
})
.collect::<Vec<_>>();
(references, serde_json::Value::Array(issues))
}
/// Static extension identity projection for `inspect --extensions`. /// Static extension identity projection for `inspect --extensions`.
/// ///
/// Reports declared sources, lock identity, static plugin descriptors and /// Reports declared sources, lock identity, static plugin descriptors and
+38 -29
View File
@@ -21,16 +21,25 @@ pub fn execute(
); );
return 2; return 2;
} }
// Strict runs project code under the isolation supervisor, which owns
// stdout. A live JSONL stream or a file destination would bypass that
// supervisor, so reject the destination before any session is opened: an
// unsupported destination must never produce a partial stream.
if settings.mode == "strict"
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some())
{
return fail(
None,
"strict",
"strict.unsupported_grant",
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
2,
);
}
// Open before preparation so option, compile and authorization failures // Open before preparation so option, compile and authorization failures
// can still publish a rejection on the requested observation destination. // can still publish a rejection on the requested observation destination.
let strict_destination_rejected = settings.mode == "strict" let events = if observation.enabled() {
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some()); match ObservationSession::open(observation) {
let mut destinations = observation.clone();
if strict_destination_rejected {
destinations.file = None;
}
let events = if destinations.enabled() {
match ObservationSession::open(&destinations) {
Ok(events) => Some(events), Ok(events) => Some(events),
Err(error) => return transport_failure(&error), Err(error) => return transport_failure(&error),
} }
@@ -38,18 +47,9 @@ pub fn execute(
None None
}; };
let stream = events.as_ref(); let stream = events.as_ref();
if strict_destination_rejected {
return fail(
stream,
"strict",
"strict.unsupported_grant",
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
2,
);
}
let named_args = match named_args { let named_args = match named_args {
Ok(args) => args, Ok(args) => args,
Err(message) => return fail(stream, "prepare", "cli.invalid_argument", &message, 2), Err(message) => return fail(stream, "options", "cli.invalid_argument", &message, 2),
}; };
let options = PrepareOptions { let options = PrepareOptions {
plugins: settings.plugins.clone(), plugins: settings.plugins.clone(),
@@ -58,12 +58,10 @@ pub fn execute(
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, "prepare", &error), Err(error) => return fail_prepare(stream, "prepare", &error),
}; };
let extension_sources = prepared.loaded.extension_sources.clone(); if prepared.loaded.has_errors() {
let project = prepared.loaded;
let static_plugins = prepared.plugins;
if project.has_errors() {
if let Some(stream) = stream { if let Some(stream) = stream {
let code = project let code = prepared
.loaded
.diagnostics .diagnostics
.iter() .iter()
.find(|item| item.diagnostic.is_error()) .find(|item| item.diagnostic.is_error())
@@ -77,10 +75,24 @@ pub fn execute(
return transport_failure(&error); return transport_failure(&error);
} }
} }
eprint!("{}", output::render_text(&project.diagnostics)); eprint!("{}", output::render_text(&prepared.loaded.diagnostics));
eprintln!("error: refusing to run a project with compile errors"); eprintln!("error: refusing to run a project with compile errors");
return 1; return 1;
} }
// Bind the Observation snapshot to the exact bytes of the ordinary
// Analysis for these static options. Build it before moving the prepared
// program apart, but only when an observation destination is requested.
let analysis_digest = if stream.is_some() {
match crate::analysis::digest(&prepared) {
Ok(digest) => Some(digest),
Err(error) => return fail(stream, "prepare", "cli.analysis_failed", &error, 1),
}
} else {
None
};
let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded;
let static_plugins = prepared.plugins;
let warnings: Vec<FileDiagnostic> = project let warnings: Vec<FileDiagnostic> = project
.diagnostics .diagnostics
.iter() .iter()
@@ -342,15 +354,12 @@ pub fn execute(
}; };
if let Some(stream) = stream { if let Some(stream) = stream {
let entry = format!("{}::{}", project.entry, function_name); let entry = format!("{}::{}", project.entry, function_name);
let analysis_digest = match crate::analysis::digest(&project) { let analysis_digest = analysis_digest.as_deref().unwrap_or_default();
Ok(digest) => digest,
Err(error) => return fail(Some(stream), "prepare", "cli.analysis_failed", &error, 1),
};
if let Err(error) = stream.started( if let Err(error) = stream.started(
&entry, &entry,
mode.as_str(), mode.as_str(),
&project.identity.root_id(), &project.identity.root_id(),
&analysis_digest, analysis_digest,
) { ) {
return transport_failure(&error); return transport_failure(&error);
} }
File diff suppressed because it is too large. Load diff
+81 -31
View File
@@ -119,6 +119,14 @@ fn source_digest(source: &str) -> String {
hex::encode(hasher.finalize()) hex::encode(hasher.finalize())
} }
/// `sha256:<hex>` of exact bytes, the wire form used by Analysis snapshots.
fn bytes_digest(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
format!("sha256:{}", hex::encode(hasher.finalize()))
}
/// A resolved source location inside a loaded file. /// A resolved source location inside a loaded file.
pub struct LocatedSource<'a> { pub struct LocatedSource<'a> {
/// The owning file. /// The owning file.
@@ -167,6 +175,13 @@ pub struct LoadedProject {
pub manifest: Option<Manifest>, pub manifest: Option<Manifest>,
/// Verified lock file, when present (lock v4). /// Verified lock file, when present (lock v4).
pub lock: Option<LockFile>, pub lock: Option<LockFile>,
/// SHA-256 of the exact `marqdo.lock` bytes captured while loading, or an
/// empty string when the project has no lock. Analysis must never re-read
/// the file: a later edit cannot change the snapshot the program used.
pub lock_digest: String,
/// SHA-256 of the exact `marqdo.yaml` bytes captured while loading, or an
/// empty string when there is no manifest.
pub manifest_digest: String,
/// Resolved `marqdo.yaml.extensions` activation sources (static paths only). /// Resolved `marqdo.yaml.extensions` activation sources (static paths only).
pub extension_sources: Vec<marqdo_package::ResolvedExtension>, pub extension_sources: Vec<marqdo_package::ResolvedExtension>,
} }
@@ -201,29 +216,6 @@ impl LoadedProject {
column: position.column, column: position.column,
}) })
} }
/// Resolve a physical path to its loaded or statically addressable module.
pub fn module_id_for_path(&self, path: &Path) -> Option<ModuleId> {
let canonical = path.canonicalize().ok()?;
let mut best: Option<(&String, &PathBuf)> = None;
for (instance, root) in &self.packages {
if canonical.starts_with(root)
&& best
.as_ref()
.map(|(_, current)| root.components().count() > current.components().count())
.unwrap_or(true)
{
best = Some((instance, root));
}
}
let (instance, root) = best?;
let relative = canonical.strip_prefix(root).ok()?;
let mut parts = Vec::new();
for component in relative.components() {
parts.push(component.as_os_str().to_string_lossy().to_string());
}
Some(ModuleId::new(instance.clone(), parts.join("/")))
}
} }
struct Loader { struct Loader {
@@ -251,19 +243,32 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
.map(|parent| parent.to_path_buf()) .map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from(".")), .unwrap_or_else(|| PathBuf::from(".")),
}; };
let manifest = if root.join(MANIFEST_FILE).is_file() { // Read each snapshot input exactly once. The digest recorded in Analysis
Some(Manifest::load(&root.join(MANIFEST_FILE))?) // is computed from these bytes, not from a second read after preparation.
let manifest_path = root.join(MANIFEST_FILE);
let (manifest, manifest_digest) = if manifest_path.is_file() {
let bytes = std::fs::read(&manifest_path)
.map_err(|error| format!("cannot read {MANIFEST_FILE}: {error}"))?;
let yaml = String::from_utf8(bytes.clone())
.map_err(|error| format!("{MANIFEST_FILE} is not valid UTF-8: {error}"))?;
let manifest =
Manifest::from_yaml(&yaml).map_err(|error| format!("{MANIFEST_FILE}: {error}"))?;
(Some(manifest), bytes_digest(&bytes))
} else { } else {
None (None, String::new())
}; };
let lock = if root.join(LOCK_FILE).is_file() { let lock_path = root.join(LOCK_FILE);
let lock = LockFile::load(&root.join(LOCK_FILE)) let (lock, lock_digest) = if lock_path.is_file() {
.map_err(|error| format!("{LOCK_FILE}: {error}"))?; let bytes = std::fs::read(&lock_path)
.map_err(|error| format!("cannot read {LOCK_FILE}: {error}"))?;
let yaml = String::from_utf8(bytes.clone())
.map_err(|error| format!("{LOCK_FILE} is not valid UTF-8: {error}"))?;
let lock = LockFile::from_yaml(&yaml).map_err(|error| format!("{LOCK_FILE}: {error}"))?;
if let Some(manifest) = &manifest { if let Some(manifest) = &manifest {
lock.validate_root(manifest) lock.validate_root(manifest)
.map_err(|error| format!("{LOCK_FILE}: {error}"))?; .map_err(|error| format!("{LOCK_FILE}: {error}"))?;
} }
Some(lock) (Some(lock), bytes_digest(&bytes))
} else { } else {
if manifest if manifest
.as_ref() .as_ref()
@@ -275,7 +280,7 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
.to_string(), .to_string(),
); );
} }
None (None, String::new())
}; };
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone()); let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone());
let entry_module = resolver.resolve_entry(&entry)?; let entry_module = resolver.resolve_entry(&entry)?;
@@ -326,6 +331,8 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
official_aliases, official_aliases,
manifest, manifest,
lock, lock,
lock_digest,
manifest_digest,
extension_sources, extension_sources,
}) })
} }
@@ -683,3 +690,46 @@ fn collect_identifiers_expr(expr: &Expr, names: &mut std::collections::BTreeSet<
Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {} Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {}
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn temp_project(files: &[(&str, &str)]) -> PathBuf {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let root =
std::env::temp_dir().join(format!("marqdo-loader-test-{}-{id}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
for (name, source) in files {
std::fs::write(root.join(name), source).unwrap();
}
root
}
#[test]
fn project_snapshot_digests_are_captured_once() {
let root = temp_project(&[
("marqdo.yaml", "project:\n name: snap\n version: 0.1.0\n"),
("index.mq.md", "## @exec main\n\n`return 1`\n"),
]);
let entry = root.join("index.mq.md");
let project = load(&entry).expect("load project");
let manifest_bytes = std::fs::read(root.join("marqdo.yaml")).unwrap();
assert_eq!(project.manifest_digest, bytes_digest(&manifest_bytes));
assert!(project.lock_digest.is_empty());
// The snapshot is what the program used; editing the manifest after
// loading cannot change the recorded digest.
std::fs::write(
root.join("marqdo.yaml"),
"project:\n name: snap\n version: 0.2.0\n",
)
.unwrap();
assert_eq!(project.manifest_digest, bytes_digest(&manifest_bytes));
let _ = std::fs::remove_dir_all(&root);
}
}
+1
View File
@@ -7,6 +7,7 @@
mod analysis; mod analysis;
mod args; mod args;
mod commands; mod commands;
mod document_refs;
mod extension_descriptors; mod extension_descriptors;
mod extension_selection; mod extension_selection;
mod loader; mod loader;
+591
View File
@@ -0,0 +1,591 @@
//! Public Analysis boundary tests (issue #10, ADR-0069).
//!
//! These drive the real CLI binary: exact source/AST/scope projection, explicit
//! reference states, output safety, Observation digest binding, independent
//! consumers and schema/semantic mutation rejection.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use sha2::{Digest, Sha256};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-analysis-boundary-{}-{id}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
fn write(&self, name: &str, source: &str) -> PathBuf {
let path = self.0.join(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(&path, source).unwrap();
path
}
fn read(&self, name: &str) -> String {
std::fs::read_to_string(self.0.join(name)).unwrap()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
.args(args)
.current_dir(dir)
.output()
.expect("run marqdo")
}
fn emit(dir: &Path, entry: &str, output: &str, extra: &[&str]) -> Output {
let mut args = vec!["check", entry, "--emit", output];
args.extend_from_slice(extra);
cli(dir, &args)
}
fn analysis(dir: &Path, name: &str) -> serde_json::Value {
serde_json::from_slice(&std::fs::read(dir.join(name)).unwrap()).unwrap()
}
fn digest(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
const DOCUMENT: &str = "\u{feff}# @knowledge 数学\r\n\r\n## @exec 计算\r\n\r\n`params(n: Int)`\r\n\r\n`return n + 1`\r\n\r\n### 细节\r\n\r\n正文\r\n";
#[test]
fn analysis_projects_exact_source_document_and_complete_scopes() {
let dir = TempDir::new("scope");
dir.write("index.mq.md", DOCUMENT);
let output = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let value = analysis(dir.path(), "analysis.json");
let module = &value["modules"][0];
assert_eq!(module["source"], DOCUMENT);
assert_eq!(module["source_digest"], digest(DOCUMENT.as_bytes()));
assert_eq!(value["project"]["entry_module_id"], module["id"]);
let document = &module["document"];
assert_eq!(document["kind"], "document");
assert_eq!(document["span"]["start"], 0);
assert_eq!(
document["span"]["end"].as_u64().unwrap() as usize,
DOCUMENT.len()
);
let heading = document["children"]
.as_array()
.unwrap()
.iter()
.find(|node| node["kind"] == "heading" && node["level"] == 1)
.expect("level-1 heading");
assert!(heading["children"].is_array());
assert!(heading["children"].as_array().unwrap().iter().any(|node| {
node["kind"] == "text"
&& node["literal"]
.as_str()
.is_some_and(|literal| literal.contains("数学"))
}));
let units = module["units"].as_array().unwrap();
let by_name = |name: &str| {
units
.iter()
.find(|unit| unit["name"] == name)
.unwrap_or_else(|| panic!("missing unit {name}"))
};
let root = &units[0];
assert_eq!(root["kind"], "root");
assert_eq!(root["parent_id"], serde_json::Value::Null);
assert_eq!(root["heading_span"], serde_json::Value::Null);
assert_eq!(root["span"]["start"], 0);
assert_eq!(
root["span"]["end"].as_u64().unwrap() as usize,
DOCUMENT.len()
);
let namespace = by_name("数学");
assert_eq!(namespace["kind"], "namespace");
assert_eq!(namespace["parent_id"], root["id"]);
assert_eq!(namespace["mode"], "knowledge");
assert_eq!(namespace["mode_origin"], "explicit");
assert_eq!(namespace["mode_source_unit_id"], namespace["id"]);
let function = by_name("计算");
assert_eq!(function["kind"], "function");
assert_eq!(function["parent_id"], namespace["id"]);
assert_eq!(function["mode"], "exec");
assert_eq!(function["mode_origin"], "explicit");
assert!(function["function"].is_string());
assert_ne!(function["span"], function["heading_span"]);
let section = by_name("细节");
assert_eq!(section["kind"], "section");
assert_eq!(section["parent_id"], function["id"]);
assert_eq!(section["mode"], "exec");
assert_eq!(section["mode_origin"], "inherited");
assert_eq!(section["mode_source_unit_id"], function["id"]);
// The complete function range includes the H3 child and runs to EOF.
assert_eq!(
function["span"]["end"].as_u64().unwrap() as usize,
DOCUMENT.len()
);
assert_eq!(
section["span"]["end"].as_u64().unwrap() as usize,
DOCUMENT.len()
);
let heading_start = DOCUMENT.find("## @exec 计算").unwrap();
assert_eq!(
function["heading_span"]["start"].as_u64().unwrap() as usize,
heading_start
);
let anchors = module["anchors"].as_array().unwrap();
assert!(anchors.iter().any(|anchor| anchor["anchor"] == "计算"));
let signature = &module["functions"][0]["signature"];
assert_eq!(signature["kind"], "explicit");
assert_eq!(signature["params"][0]["name"], "n");
assert_eq!(signature["params"][0]["type"], "Int");
}
#[test]
fn reference_states_are_distinct_and_explicit_refs_do_not_change_the_program() {
let dir = TempDir::new("references");
dir.write(
"index.mq.md",
"## @exec main\n\n[本地](./other.mq.md#公式) [外链](https://example.com) [本文](#main)\n\n`return 1`\n",
);
dir.write("other.mq.md", "## @knowledge 公式\n\n正文\n");
let ordinary = emit(dir.path(), "index.mq.md", "ordinary.json", &[]);
assert!(
ordinary.status.success(),
"{}",
String::from_utf8_lossy(&ordinary.stderr)
);
let value = analysis(dir.path(), "ordinary.json");
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
let references = value["modules"][0]["references"].as_array().unwrap();
let state = |url: &str| {
references
.iter()
.find(|reference| reference["url"] == url)
.unwrap_or_else(|| panic!("missing reference {url}"))["state"]
.as_str()
.unwrap()
.to_string()
};
assert_eq!(state("./other.mq.md#公式"), "not_loaded");
assert_eq!(state("https://example.com"), "external");
assert_eq!(state("#main"), "resolved");
// The ordinary artifact still describes only the loaded program.
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
// Explicit refs verify the direct target and keep the same ordinary bytes'
// module set. The emitted Analysis still uses the loaded catalog.
let verified = emit(dir.path(), "index.mq.md", "verified.json", &["--refs"]);
assert!(
verified.status.success(),
"{}",
String::from_utf8_lossy(&verified.stderr)
);
let verified_value = analysis(dir.path(), "verified.json");
assert_eq!(verified_value["modules"].as_array().unwrap().len(), 1);
let verified_refs = verified_value["modules"][0]["references"]
.as_array()
.unwrap();
assert_eq!(
verified_refs
.iter()
.find(|reference| reference["url"] == "./other.mq.md#公式")
.unwrap()["state"],
"not_loaded",
"the emitted artifact must keep the loaded catalog"
);
let inspected = cli(dir.path(), &["inspect", "index.mq.md", "--refs", "--json"]);
assert!(inspected.status.success());
let inspected: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
let resolved = inspected["refs"]
.as_array()
.unwrap()
.iter()
.find(|reference| reference["url"] == "./other.mq.md#公式")
.unwrap();
assert_eq!(resolved["state"], "resolved");
assert_eq!(resolved["target_kind"], "module");
assert!(resolved["target_module"]
.as_str()
.unwrap()
.ends_with("::other.mq.md"));
// A broken explicitly verified target is an error and publishes no artifact.
dir.write(
"broken.mq.md",
"## @exec main\n\n[坏](./other.mq.md#不存在)\n\n`return 1`\n",
);
let broken = emit(dir.path(), "broken.mq.md", "broken.json", &["--refs"]);
assert_eq!(broken.status.code(), Some(1), "{broken:?}");
assert!(!dir.path().join("broken.json").exists());
assert!(String::from_utf8_lossy(&broken.stderr).contains("ref.unresolved"));
}
#[test]
fn emit_refuses_inputs_symlinks_hardlinks_and_directories() {
let dir = TempDir::new("emit-safety");
let source = "## @exec main\n\n`return 1`\n";
let entry = dir.write("index.mq.md", source);
let self_emit = emit(dir.path(), "index.mq.md", "index.mq.md", &[]);
assert_eq!(self_emit.status.code(), Some(2), "{self_emit:?}");
assert_eq!(dir.read("index.mq.md"), source);
#[cfg(unix)]
{
std::os::unix::fs::symlink(&entry, dir.path().join("link.json")).unwrap();
let symlink_emit = emit(dir.path(), "index.mq.md", "link.json", &[]);
assert_eq!(symlink_emit.status.code(), Some(2), "{symlink_emit:?}");
assert_eq!(dir.read("index.mq.md"), source);
std::fs::hard_link(&entry, dir.path().join("hard.json")).unwrap();
let hard_emit = emit(dir.path(), "index.mq.md", "hard.json", &[]);
assert_eq!(hard_emit.status.code(), Some(2), "{hard_emit:?}");
assert_eq!(dir.read("index.mq.md"), source);
}
std::fs::create_dir(dir.path().join("outdir")).unwrap();
let directory_emit = emit(dir.path(), "index.mq.md", "outdir", &[]);
assert_eq!(directory_emit.status.code(), Some(2), "{directory_emit:?}");
let ok = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
assert!(ok.status.success(), "{ok:?}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(dir.path().join("analysis.json"))
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600, "Analysis output must be owner-only");
}
}
#[test]
fn observation_binds_the_exact_emitted_analysis_bytes() {
let dir = TempDir::new("digest");
dir.write(
"index.mq.md",
"## @exec main\n\n`params(n: Int)`\n\n`return n + 1`\n",
);
let emitted = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
assert!(
emitted.status.success(),
"{}",
String::from_utf8_lossy(&emitted.stderr)
);
let bytes = std::fs::read(dir.path().join("analysis.json")).unwrap();
let expected = format!("sha256:{}", digest(&bytes));
let run = cli(
dir.path(),
&[
"call",
"index.mq.md",
"main",
"--arg",
"n=1",
"--output",
"json",
"--observation-file",
"observation.json",
],
);
assert!(
run.status.success(),
"{}",
String::from_utf8_lossy(&run.stderr)
);
let observation = analysis(dir.path(), "observation.json");
let started = observation["events"]
.as_array()
.unwrap()
.iter()
.find(|event| event["kind"] == "run.started")
.expect("run.started");
assert_eq!(started["payload"]["source"]["analysis_digest"], expected);
}
#[test]
fn independent_view_lint_and_knowledge_consumers_drive_the_real_cli() {
let dir = TempDir::new("consumers");
dir.write(
"marqdo.yaml",
"project:\n name: consumers\n version: 0.1.0\n",
);
dir.write("theory.mq.md", "## @knowledge 公式\n\n正文\n");
dir.write(
"index.mq.md",
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n[公式](./theory.mq.md#公式) [未加载](./notes.mq.md)\n\n`return 1`\n",
);
dir.write("notes.mq.md", "## @exec main\n\n`return 2`\n");
assert!(emit(dir.path(), "index.mq.md", "index.json", &[])
.status
.success());
assert!(emit(dir.path(), "notes.mq.md", "notes.json", &[])
.status
.success());
let consumers = repo_root().join("tests/consumers");
let run = |script: &str, args: &[&Path]| -> Output {
let mut command = Command::new("python3");
command.arg(consumers.join(script));
for arg in args {
command.arg(arg);
}
command.output().expect("python3 consumer")
};
let index_json = dir.path().join("index.json");
let notes_json = dir.path().join("notes.json");
let view = run("view_consumer.py", &[&index_json]);
assert!(
view.status.success(),
"{}",
String::from_utf8_lossy(&view.stderr)
);
assert!(String::from_utf8_lossy(&view.stdout).contains("view: rendered=1"));
let lint = run("lint_consumer.py", &[&index_json]);
assert!(
lint.status.success(),
"{}",
String::from_utf8_lossy(&lint.stderr)
);
let lint_text = String::from_utf8_lossy(&lint.stdout);
assert!(lint_text.contains("state=not_loaded"));
assert!(lint_text.contains("unresolved=1"));
let knowledge = run("knowledge_consumer.py", &[&index_json, &notes_json]);
assert!(
knowledge.status.success(),
"{}",
String::from_utf8_lossy(&knowledge.stderr)
);
let knowledge_text = String::from_utf8_lossy(&knowledge.stdout);
assert!(knowledge_text.contains("entries=2"));
assert!(knowledge_text.contains("not_loaded=1"));
}
#[test]
fn protocol_validator_accepts_current_bytes_and_rejects_mutations() {
let dir = TempDir::new("protocol-validator");
dir.write(
"index.mq.md",
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n$$x^2$$\n\n```python\nprint(1)\n```\n\n[公式](./theory.mq.md#公式)\n\n`结果 = theory.加一(1)`\n\n`return 结果`\n",
);
dir.write(
"theory.mq.md",
"## @exec 加一\n\n`params(n: Int)`\n\n`return n + 1`\n\n## @knowledge 公式\n\n正文\n",
);
let check = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
assert!(
check.status.success(),
"{}",
String::from_utf8_lossy(&check.stderr)
);
let run = cli(
dir.path(),
&[
"call",
"index.mq.md",
"main",
"--output",
"json",
"--observation-file",
"observation.json",
],
);
assert!(run.status.success(), "{run:?}");
let validator = repo_root().join("tests/consumers/validate_protocols.py");
let output = Command::new("python3")
.arg(&validator)
.arg(dir.path().join("analysis.json"))
.arg(dir.path().join("observation.json"))
.arg(repo_root().join("examples/tool-unknown-name/tool.json"))
.output()
.expect("python3 protocol validator");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains("validated analysis"));
}
#[test]
fn two_entries_keep_their_own_snapshot_context() {
let dir = TempDir::new("entries");
for (name, body) in [("first", "1"), ("second", "2")] {
dir.write(
&format!("{name}.mq.md"),
&format!("## @exec main\n\n`return {body}`\n"),
);
let output = emit(
dir.path(),
&format!("{name}.mq.md"),
&format!("{name}.json"),
&[],
);
assert!(output.status.success(), "{output:?}");
}
let first = analysis(dir.path(), "first.json");
let second = analysis(dir.path(), "second.json");
assert!(first["project"]["entry_module_id"]
.as_str()
.unwrap()
.ends_with("::first.mq.md"));
assert!(second["project"]["entry_module_id"]
.as_str()
.unwrap()
.ends_with("::second.mq.md"));
assert_ne!(first["project"]["root_id"], second["project"]["root_id"]);
}
#[test]
fn explicit_refs_verify_plain_files_reject_symlinks_and_never_guess_coverage() {
let dir = TempDir::new("refs-files");
dir.write("marqdo.yaml", "project:\n name: files\n version: 0.1.0\n");
dir.write("asset.pdf", "%PDF-1.4 not a program\n");
dir.write("notes.md", "# Notes\n\nplain markdown\n");
dir.write(
"index.mq.md",
"## @exec main\n\n[资产](./asset.pdf) [普通](./notes.md#notes) [越界](./%2e%2e/secret.mq.md)\n\n`return 1`\n",
);
#[cfg(unix)]
{
std::os::unix::fs::symlink("/etc/hostname", dir.path().join("escape.mq.md")).unwrap();
dir.write(
"symlink.mq.md",
"## @exec main\n\n[逃逸](./escape.mq.md)\n\n`return 1`\n",
);
}
let inspected = cli(dir.path(), &["inspect", "index.mq.md", "--refs", "--json"]);
assert!(inspected.status.success(), "{inspected:?}");
let value: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
let refs = value["refs"].as_array().unwrap();
let by_url = |url: &str| {
refs.iter()
.find(|reference| reference["url"] == url)
.unwrap_or_else(|| panic!("missing {url}"))
};
assert_eq!(by_url("./asset.pdf")["state"], "resolved");
assert_eq!(by_url("./asset.pdf")["target_kind"], "file");
assert_eq!(by_url("./notes.md#notes")["state"], "not_loaded");
assert_eq!(by_url("./%2e%2e/secret.mq.md")["state"], "outside_scope");
let issues = value["reference_issues"].as_array().unwrap();
assert!(issues.iter().any(|issue| issue["code"] == "ref.invalid"));
assert!(issues.iter().any(|issue| issue["code"] == "ref.not_loaded"));
#[cfg(unix)]
{
let symlinked = cli(
dir.path(),
&["inspect", "symlink.mq.md", "--refs", "--json"],
);
assert!(symlinked.status.success(), "{symlinked:?}");
let value: serde_json::Value = serde_json::from_slice(&symlinked.stdout).unwrap();
assert_eq!(value["refs"][0]["state"], "not_loaded");
assert!(value["reference_issues"]
.as_array()
.unwrap()
.iter()
.any(|issue| issue["code"] == "ref.invalid"));
}
}
#[test]
fn missing_unimported_program_is_an_explicit_refs_error_but_not_loaded_otherwise() {
let dir = TempDir::new("refs-missing");
dir.write(
"index.mq.md",
"## @exec main\n\n[不存在](./absent.mq.md#x)\n\n`return 1`\n",
);
let ordinary = emit(dir.path(), "index.mq.md", "ordinary.json", &[]);
assert!(ordinary.status.success(), "{ordinary:?}");
let analysis = analysis(dir.path(), "ordinary.json");
assert_eq!(
analysis["modules"][0]["references"][0]["state"],
"not_loaded"
);
let refs = emit(dir.path(), "index.mq.md", "refs.json", &["--refs"]);
assert_eq!(refs.status.code(), Some(1), "{refs:?}");
assert!(!dir.path().join("refs.json").exists());
assert!(String::from_utf8_lossy(&refs.stderr).contains("ref.unresolved"));
}
#[test]
fn lock_digest_binds_the_prepared_lock_snapshot() {
let dir = TempDir::new("lock-digest");
dir.write("marqdo.yaml", "project:\n name: lock\n version: 0.1.0\n");
dir.write("index.mq.md", "## @exec main\n\n`return 1`\n");
let lock = cli(dir.path(), &["lock"]);
assert!(lock.status.success(), "{lock:?}");
let locked = emit(dir.path(), "index.mq.md", "locked.json", &[]);
assert!(locked.status.success(), "{locked:?}");
let lock_bytes = std::fs::read(dir.path().join("marqdo.lock")).unwrap();
let analysis = analysis(dir.path(), "locked.json");
assert_eq!(
analysis["project"]["lock_digest"],
format!("sha256:{}", digest(&lock_bytes))
);
let manifest_bytes = std::fs::read(dir.path().join("marqdo.yaml")).unwrap();
assert_eq!(
analysis["project"]["manifest_digest"],
format!("sha256:{}", digest(&manifest_bytes))
);
// A lock that no longer validates cannot leave a success artifact behind.
std::fs::write(dir.path().join("marqdo.lock"), "lock_version: 4\n").unwrap();
let failed = emit(dir.path(), "index.mq.md", "locked.json", &[]);
assert_ne!(failed.status.code(), Some(0), "{failed:?}");
assert!(!dir.path().join("locked.json").exists());
}
+35 -3
View File
@@ -267,9 +267,16 @@ print(1)
assert_eq!(code["language"], "python"); assert_eq!(code["language"], "python");
assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64); assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64);
assert_eq!(code["content_digest"].as_str().unwrap().len(), 64); assert_eq!(code["content_digest"].as_str().unwrap().len(), 64);
assert!( let source = analysis["modules"][0]["source"]
!analysis.to_string().contains("A = x + 1"), .as_str()
"resource payloads stay in source, not Analysis" .expect("exact source is public");
assert!(source.contains("A = x + 1"));
assert_eq!(
source.len(),
analysis["modules"][0]["source_digest"]
.as_str()
.map(|_| source.len())
.unwrap_or(0)
); );
} }
@@ -337,6 +344,31 @@ fn failed_check_removes_stale_analysis() {
assert!(!target.exists(), "stale success artifact must be removed"); assert!(!target.exists(), "stale success artifact must be removed");
} }
#[test]
fn check_that_cannot_load_the_project_removes_stale_analysis() {
let dir = TempDir::new("analysis-load-error");
write(dir.path(), "index.mq.md", "## @exec main\n\n`return 1`\n");
let target = dir.path().join("analysis.json");
let first = cli(
dir.path(),
&["check", "index.mq.md", "--emit", target.to_str().unwrap()],
);
assert_eq!(first.status.code(), Some(0), "{first:?}");
assert!(target.exists());
// The load failure happens before the compile-error cleanup branch, so the
// remove must also cover the prepare path.
let failed = cli(
dir.path(),
&["check", "missing.mq.md", "--emit", target.to_str().unwrap()],
);
assert_ne!(failed.status.code(), Some(0), "{failed:?}");
assert!(
!target.exists(),
"a load failure must not leave the previous Analysis in place"
);
}
#[test] #[test]
fn snapshot_records_calls_effects_and_status_without_secrets() { fn snapshot_records_calls_effects_and_status_without_secrets() {
let dir = TempDir::new("trace"); let dir = TempDir::new("trace");
+69
View File
@@ -231,3 +231,72 @@ fn ci_configuration_uses_only_current_protocols() {
} }
} }
} }
/// The current contract documents must describe the interface that exists.
/// A retired option or a path to a deleted spec in `spec/` or the current
/// developer guides is a release-record defect: consumers would implement a
/// contract the binary does not accept. Historical ADRs, evidence and
/// `docs/history/` keep their original text and are intentionally excluded.
#[test]
fn current_contract_documents_do_not_reference_retired_interfaces() {
let root = repo_root();
let mut files = vec![
"COMPATIBILITY.md".to_string(),
"README.md".to_string(),
"docs/ci.md".to_string(),
"docs/architecture/CURRENT.md".to_string(),
];
for directory in ["spec", "docs/developers", "examples"] {
let base = root.join(directory);
let mut stack = vec![base];
while let Some(path) = stack.pop() {
for entry in std::fs::read_dir(&path).expect("read contract docs") {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
} else if path.extension().and_then(|ext| ext.to_str()) == Some("md") {
files.push(
path.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string(),
);
}
}
}
}
let retired = [
"--trace-file",
"--event-stream",
"EffectTrace",
"crates/marqdo-host/src/trace.rs",
"spec/trace-v1.md",
"spec/trace-v2.md",
"spec/execution-events-v1.md",
"spec/analysis-v1.md",
"spec/analysis-v2.md",
"spec/tool-v1.md",
"worker_frame_invalid for an over-limit",
];
for relative in files {
let text = read(&root.join(&relative));
for (number, line) in text.lines().enumerate() {
for token in retired {
if !line.contains(token) {
continue;
}
// A sentence that explicitly marks the interface as retired or
// removed is documentation of the migration, not a claim that
// it is available.
let explained = line.contains("retired")
|| line.contains("removed")
|| line.contains("no longer");
assert!(
explained,
"{relative}:{} still documents retired `{token}`",
number + 1
);
}
}
}
}
+5 -15
View File
@@ -663,7 +663,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
assert_exit(&refs, 0, "inspect --refs"); assert_exit(&refs, 0, "inspect --refs");
let value = json_stdout(&refs); let value = json_stdout(&refs);
let edges = value["refs"].as_array().expect("refs array"); let edges = value["refs"].as_array().expect("refs array");
assert!(edges.iter().any(|edge| edge["resolved"] == true)); assert!(edges.iter().any(|edge| edge["state"] == "resolved"));
// A broken #anchor is reported as unresolved by `inspect --refs`. // A broken #anchor is reported as unresolved by `inspect --refs`.
let dir = TempDir::new("refs"); let dir = TempDir::new("refs");
@@ -677,7 +677,8 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
let edges = value["refs"].as_array().expect("refs array"); let edges = value["refs"].as_array().expect("refs array");
assert_eq!(edges.len(), 1); assert_eq!(edges.len(), 1);
assert_eq!(edges[0]["url"], "#不存在的标题"); assert_eq!(edges[0]["url"], "#不存在的标题");
assert_eq!(edges[0]["resolved"], false); assert_eq!(edges[0]["state"], "missing");
assert_eq!(edges[0]["target_unit"], serde_json::Value::Null);
} }
#[test] #[test]
@@ -989,22 +990,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
); );
assert_eq!(error["relative_path"], "physics.mq.md"); assert_eq!(error["relative_path"], "physics.mq.md");
assert!( assert!(
error["file"] error.get("file").is_none(),
.as_str() "a shareable snapshot must not embed an absolute host path: {error}"
.unwrap_or_default()
.ends_with("physics.mq.md"),
"{}",
error["file"]
); );
let line = error["line"].as_u64().unwrap_or(0); let line = error["line"].as_u64().unwrap_or(0);
assert!(line >= 5, "expected the failing statement line, got {line}"); assert!(line >= 5, "expected the failing statement line, got {line}");
assert!(
!error["file"]
.as_str()
.unwrap_or_default()
.ends_with("index.mq.md"),
"must not blame the entry file"
);
let human = cli(dir.path(), &["run", "index.mq.md"]); let human = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&human, 1, "human rendering also fails"); assert_exit(&human, 1, "human rendering also fails");
+43
View File
@@ -878,3 +878,46 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
assert_eq!(statement["span"], span); assert_eq!(statement["span"], span);
} }
} }
#[test]
fn strict_mode_rejects_live_and_file_destinations_before_opening_a_stream() {
let dir = TempDir::new("strict-destinations");
dir.write("index.mq.md", BASIC);
let snapshot = dir.path().join("snapshot.json");
let snapshot_arg = snapshot.to_str().unwrap().to_string();
for args in [
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"jsonl",
],
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"text",
"--observation-file",
snapshot_arg.as_str(),
],
] {
let output = cli(dir.path(), &args);
assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
assert!(
output.stdout.is_empty(),
"a rejected strict destination must not emit a partial stream: {}",
String::from_utf8_lossy(&output.stdout)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("strict.unsupported_grant"), "{stderr}");
assert!(
!snapshot.exists(),
"a rejected strict destination must not publish a snapshot file"
);
}
}
+249 -14
View File
@@ -39,6 +39,16 @@ pub struct HeadingInfo {
pub kind: UnitKind, pub kind: UnitKind,
/// Semantic mode declared or inherited by this heading. /// Semantic mode declared or inherited by this heading.
pub mode: SemanticMode, pub mode: SemanticMode,
/// How the effective mode was established.
pub mode_origin: ModeOrigin,
/// Unit that provided the effective mode (this unit, an explicit ancestor,
/// or the document root).
pub mode_source_unit_id: UnitId,
/// Nearest real ancestor unit (the root for a top-level heading).
pub parent_id: UnitId,
/// Complete section range: this heading through the next same-or-higher
/// heading, or the end of the source. It includes child headings.
pub full_span: Span,
} }
/// A function range mapped from a level-2 heading. /// A function range mapped from a level-2 heading.
@@ -95,6 +105,38 @@ impl UnitIndex {
.iter() .iter()
.find(|f| block_index >= f.body_start && block_index < f.body_end) .find(|f| block_index >= f.body_start && block_index < f.body_end)
} }
/// Complete public range of one unit: the whole source for the root, the
/// heading-through-next-same-or-higher-heading range otherwise.
pub fn unit_range(&self, id: &UnitId) -> Option<Span> {
if id.path.is_empty() {
return self
.units
.iter()
.find(|unit| unit.id.path.is_empty())
.map(|unit| unit.span);
}
self.headings
.iter()
.find(|heading| heading.path == id.path)
.map(|heading| heading.full_span)
}
/// Innermost unit whose complete range contains `span`.
///
/// Used for document links: the root covers the whole source, so a linked
/// span always has an owner. Ties prefer the deeper path, then the later
/// start (a child cannot be larger than its parent).
pub fn unit_containing_span(&self, span: Span) -> Option<UnitId> {
self.units
.iter()
.filter_map(|unit| {
let range = self.unit_range(&unit.id)?;
(range.start <= span.start && span.end <= range.end).then_some((unit, range))
})
.max_by_key(|(unit, range)| (unit.id.path.len(), range.start))
.map(|(unit, _)| unit.id.clone())
}
} }
fn has_payload(node: &MdNode) -> bool { fn has_payload(node: &MdNode) -> bool {
@@ -116,6 +158,28 @@ pub enum SemanticMode {
Exec, Exec,
} }
/// How a heading's effective mode was established.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModeOrigin {
/// The document root is Knowledge by default.
Default,
/// The ATX heading declares `@exec` or `@knowledge`.
Explicit,
/// The heading inherits the mode of an ancestor or the root.
Inherited,
}
impl ModeOrigin {
/// Stable public name used by Analysis.
pub fn as_str(self) -> &'static str {
match self {
ModeOrigin::Default => "default",
ModeOrigin::Explicit => "explicit",
ModeOrigin::Inherited => "inherited",
}
}
}
fn heading_declaration( fn heading_declaration(
node: &MdNode, node: &MdNode,
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) { ) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
@@ -184,20 +248,22 @@ fn heading_declaration(
/// Build the heading/function index for a parsed document. /// Build the heading/function index for a parsed document.
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex { pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let mut index = UnitIndex::default(); let mut index = UnitIndex::default();
index.units.push(UnitInfo { let root_id = UnitId {
id: UnitId {
module: module.clone(), module: module.clone(),
path: Vec::new(), path: Vec::new(),
}, };
index.units.push(UnitInfo {
id: root_id.clone(),
level: 0, level: 0,
name: String::new(), name: String::new(),
span: doc.root.span, // The root covers the whole source, including a tolerated UTF-8 BOM.
span: Span::new(0, doc.source.len()),
kind: UnitKind::Root, kind: UnitKind::Root,
function: None, function: None,
}); });
// Stack of (level, path, mode) for ancestors. // Stack of (level, path, mode, mode_source_unit_id) for ancestors.
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new(); let mut stack: Vec<(u8, Vec<String>, SemanticMode, UnitId)> = Vec::new();
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new(); let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
let mut current_namespace: Option<String> = None; let mut current_namespace: Option<String> = None;
let mut current_function: Option<FunctionId> = None; let mut current_function: Option<FunctionId> = None;
@@ -224,7 +290,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
// Resolve the ancestor scope before deriving the mode: remove every // Resolve the ancestor scope before deriving the mode: remove every
// same-or-higher-level heading first so a heading can only inherit from // same-or-higher-level heading first so a heading can only inherit from
// its nearest *ancestor*, never from the previous sibling. // its nearest *ancestor*, never from the previous sibling.
while let Some((parent_level, _, _)) = stack.last() { while let Some((parent_level, _, _, _)) = stack.last() {
if *parent_level >= level { if *parent_level >= level {
stack.pop(); stack.pop();
} else { } else {
@@ -233,8 +299,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
} }
let inherited = stack let inherited = stack
.last() .last()
.map(|(_, _, mode)| *mode) .map(|(_, _, mode, _)| *mode)
.unwrap_or(SemanticMode::Knowledge); .unwrap_or(SemanticMode::Knowledge);
let inherited_source = stack
.last()
.map(|(_, _, _, source)| source.clone())
.unwrap_or_else(|| root_id.clone());
let mode = declared.unwrap_or(inherited); let mode = declared.unwrap_or(inherited);
let raw_name = match declared_name { let raw_name = match declared_name {
Some(name) => name, Some(name) => name,
@@ -254,13 +324,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let parent_path = stack let parent_path = stack
.last() .last()
.map(|(_, path, _)| path.clone()) .map(|(_, path, _, _)| path.clone())
.unwrap_or_default(); .unwrap_or_default();
let parent_id = UnitId {
module: module.clone(),
path: parent_path.clone(),
};
let path = { let path = {
let mut path = parent_path.clone(); let mut path = parent_path.clone();
path.push(name.clone()); path.push(name.clone());
path path
}; };
let unit_id = UnitId {
module: module.clone(),
path: path.clone(),
};
let (mode_origin, mode_source_unit_id) = match declared {
Some(_) => (ModeOrigin::Explicit, unit_id.clone()),
None => (ModeOrigin::Inherited, inherited_source),
};
let key = (parent_path.clone(), name.clone()); let key = (parent_path.clone(), name.clone());
if let Some(previous) = seen.get(&key) { if let Some(previous) = seen.get(&key) {
@@ -304,6 +386,27 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
Some(namespace) => format!("{namespace}.{local}"), Some(namespace) => format!("{namespace}.{local}"),
None => local.clone(), None => local.clone(),
}; };
// `.` separates namespace from local name in a FunctionId. A
// component that itself contains `.` would make two different
// definitions render the same public id; reject it explicitly
// instead of silently producing a non-injective identity.
let ambiguous = local.contains('.')
|| current_namespace
.as_deref()
.map(|namespace| namespace.contains('.'))
.unwrap_or(false);
if ambiguous {
index.diagnostics.push(
Diagnostic::error(
codes::SEM_AMBIGUOUS_IDENTITY,
Some(child.span),
"function or namespace name contains `.`, which is the namespace separator; the public function id would be ambiguous",
)
.with_hint(
"rename the namespace or function so it does not contain a dot",
),
);
}
let id = FunctionId { let id = FunctionId {
module: module.clone(), module: module.clone(),
name: qualified, name: qualified,
@@ -327,10 +430,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
path: path.clone(), path: path.clone(),
kind, kind,
mode, mode,
}; mode_origin,
let unit_id = UnitId { mode_source_unit_id,
module: module.clone(), parent_id,
path, // Filled after all headings are known (the end is the next
// same-or-higher heading or EOF).
full_span: child.span,
}; };
index.units.push(UnitInfo { index.units.push(UnitInfo {
id: unit_id, id: unit_id,
@@ -361,7 +466,26 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
} }
} }
heading_infos.push(info.clone()); heading_infos.push(info.clone());
stack.push((level, info.path.clone(), mode)); stack.push((
level,
info.path.clone(),
mode,
info.mode_source_unit_id.clone(),
));
}
// Complete section ranges: from this heading to the next heading of the
// same or a higher level, or EOF. Child headings are included.
let total = doc.source.len();
for position in 0..heading_infos.len() {
let level = heading_infos[position].level;
let start = heading_infos[position].span.start;
let end = heading_infos[position + 1..]
.iter()
.find(|candidate| candidate.level <= level)
.map(|candidate| candidate.span.start)
.unwrap_or(total);
heading_infos[position].full_span = Span::new(start, end.max(start));
} }
// Function body ranges and spans. // Function body ranges and spans.
@@ -624,6 +748,117 @@ mod tests {
assert_eq!(normal.kind, UnitKind::Knowledge); assert_eq!(normal.kind, UnitKind::Knowledge);
} }
#[test]
fn full_spans_cover_sections_and_parent_edges_form_a_tree() {
let source = "# @knowledge 力学\n\n## @exec 计算力\n\n`return 1`\n\n### 细节\n\n正文\n\n## 说明\n\n结尾\n";
let index = index_of(source);
let by_name = |name: &str| {
index
.headings
.iter()
.find(|heading| heading.name == name)
.unwrap_or_else(|| panic!("missing heading {name}"))
};
let calc = by_name("计算力");
let detail = by_name("细节");
let note = by_name("说明");
// The function range includes its H3 child but not the next H2.
assert_eq!(calc.full_span.start, calc.span.start);
assert!(calc.full_span.end > detail.span.start);
assert_eq!(calc.full_span.end, note.span.start);
assert_eq!(detail.full_span.end, note.span.start);
assert_eq!(note.full_span.end, source.len());
assert_eq!(
detail.parent_id.path,
vec!["力学".to_string(), "计算力".to_string()]
);
assert_eq!(calc.parent_id.path, vec!["力学".to_string()]);
let root = &index.units[0];
assert_eq!(root.span, marqdo_span::Span::new(0, source.len()));
assert_eq!(
calc.parent_id,
index
.units
.iter()
.find(|u| u.name == "力学")
.unwrap()
.id
.clone()
);
assert_eq!(by_name("力学").parent_id, root.id);
}
#[test]
fn mode_origin_and_source_are_explicit() {
let index = index_of(
"# @knowledge 数学\n\n## @exec 计算\n\n### 细节\n\n`return 1`\n\n## 说明\n\n正文\n",
);
let by_name = |name: &str| {
index
.headings
.iter()
.find(|heading| heading.name == name)
.unwrap_or_else(|| panic!("missing heading {name}"))
};
let namespace = by_name("数学");
assert_eq!(namespace.mode_origin, ModeOrigin::Explicit);
assert_eq!(
namespace.mode_source_unit_id,
namespace_unit(&index, "数学")
);
let calc = by_name("计算");
assert_eq!(calc.mode_origin, ModeOrigin::Explicit);
assert_eq!(
calc.mode_source_unit_id.path,
vec!["数学".to_string(), "计算".to_string()]
);
let detail = by_name("细节");
assert_eq!(detail.mode_origin, ModeOrigin::Inherited);
assert_eq!(
detail.mode_source_unit_id.path,
calc.mode_source_unit_id.path
);
let note = by_name("说明");
assert_eq!(note.mode_origin, ModeOrigin::Inherited);
assert_eq!(note.mode_source_unit_id.path, vec!["数学".to_string()]);
}
fn namespace_unit(index: &UnitIndex, name: &str) -> UnitId {
index
.units
.iter()
.find(|unit| unit.name == name)
.map(|unit| unit.id.clone())
.expect("namespace unit")
}
#[test]
fn a_dot_in_a_function_component_is_rejected_as_an_ambiguous_identity() {
let index = index_of("# @knowledge a.b\n\n## @exec f\n\n`return 1`\n");
assert!(index
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "sem.ambiguous_identity"));
let index = index_of("## @exec a.b\n\n`return 1`\n");
assert!(index
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "sem.ambiguous_identity"));
}
#[test]
fn innermost_unit_owns_a_linked_span() {
let source = "前置说明。\n\n# @knowledge 数学\n\n## @exec 计算\n\n见[链接](#细节)。\n\n### 细节\n\n`return 1`\n";
let index = index_of(source);
let link_start = source.find("[链接]").unwrap();
let owner = index
.unit_containing_span(Span::new(link_start, link_start + 2))
.expect("owning unit");
assert_eq!(owner.path, vec!["数学".to_string(), "计算".to_string()]);
let root = index.unit_containing_span(Span::new(0, 1)).expect("root");
assert!(root.path.is_empty());
}
#[test] #[test]
fn knowledge_scope_payloads_and_sections_stay_inert() { fn knowledge_scope_payloads_and_sections_stay_inert() {
let index = index_of( let index = index_of(
@@ -516,7 +516,7 @@ impl StdHost {
_ => unreachable!(), _ => unreachable!(),
} }
let result = self.fs.request(name, &paths, ctx.span)?; let result = self.fs.request(name, &paths, ctx.span)?;
self.observe_effect("resource.request", "ok", ctx); self.observe_effect(&format!("fs.{name}"), "ok", ctx);
Ok(result) Ok(result)
} }
_ => { _ => {
+31
View File
@@ -333,8 +333,39 @@ fn transport_error(error: TransportError) -> PluginError {
"plugin.crashed", "plugin.crashed",
format!("worker frame I/O failed: {error}"), format!("worker frame I/O failed: {error}"),
), ),
// The shared transport classifies an over-limit or unencodable frame
// before anything is written. Keep the boundary-specific codes the
// plugin ABI has always reported instead of flattening them into
// `worker_frame_invalid`.
TransportError::Frame(FrameError::Encode(error)) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
TransportError::Frame(FrameError::Length(length)) => PluginError::wire(
"worker_frame_too_large",
format!("worker frame is {length} bytes"),
),
TransportError::Frame(other) => { TransportError::Frame(other) => {
PluginError::wire("worker_frame_invalid", other.to_string()) PluginError::wire("worker_frame_invalid", other.to_string())
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transport_errors_keep_the_boundary_specific_codes() {
let too_large = transport_error(TransportError::Frame(FrameError::Length(9 * 1024 * 1024)));
assert_eq!(too_large.code, "worker_frame_too_large");
let over_limit = transport_error(TransportError::Frame(FrameError::PartialPayload {
expected: 10,
actual: 3,
}));
assert_eq!(over_limit.code, "worker_frame_invalid");
let closed = transport_error(TransportError::Closed);
assert_eq!(closed.code, "plugin.crashed");
}
}
+73
View File
@@ -462,3 +462,76 @@ fn value_encoding_is_selected_bounded_and_handle_safe() {
assert_eq!(state, ValueState::Unsupported); assert_eq!(state, ValueState::Unsupported);
assert!(value.is_none()); assert!(value.is_none());
} }
#[test]
fn filesystem_operations_report_the_concrete_effect_name() {
let dir = std::env::temp_dir().join(format!(
"marqdo-host-fs-effect-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("data.txt"), b"x").unwrap();
std::fs::create_dir_all(dir.join("sub")).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let mut host = StdHost::new(
SandboxMode::Project,
Capabilities::project().allow_read("**").allow_write("**"),
dir.clone(),
)
.with_observation(
ObservationConfig::default(),
Box::new(Recorder {
events: Rc::clone(&events),
fail: false,
}),
);
let ctx = context();
for (operation, args) in [
("fs.exists", vec![Value::Text("data.txt".to_string())]),
("fs.metadata", vec![Value::Text("data.txt".to_string())]),
("fs.list", vec![Value::Text("sub".to_string())]),
("fs.mkdir", vec![Value::Text("created".to_string())]),
("fs.remove", vec![Value::Text("created".to_string())]),
(
"fs.rename",
vec![
Value::Text("data.txt".to_string()),
Value::Text("moved.txt".to_string()),
],
),
] {
host.resource_request(operation, args, &ctx)
.unwrap_or_else(|error| panic!("{operation}: {error}"));
}
let operations: Vec<String> = events
.borrow()
.iter()
.filter_map(|event| match event {
Recorded::Effect {
operation,
result_code,
} => {
assert_eq!(result_code, "ok");
Some(operation.clone())
}
_ => None,
})
.collect();
assert_eq!(
operations,
[
"fs.exists",
"fs.metadata",
"fs.list",
"fs.mkdir",
"fs.remove",
"fs.rename",
],
"each filesystem request must report its concrete operation"
);
let _ = std::fs::remove_dir_all(&dir);
}
+1 -1
View File
@@ -3,7 +3,7 @@
//! The frontend resolves every statically visible call site exactly once and //! The frontend resolves every statically visible call site exactly once and
//! records the decision here. The runtime only dispatches by this table: it //! records the decision here. The runtime only dispatches by this table: it
//! never re-resolves a qualified name and never guesses a plugin from a string //! never re-resolves a qualified name and never guesses a plugin from a string
//! prefix. The table is internal IR (not part of Analysis/Trace v2 wire //! prefix. The table is internal IR (not part of the Analysis/Observation wire
//! contracts) and is deliberately skipped when a [`crate::Program`] is //! contracts) and is deliberately skipped when a [`crate::Program`] is
//! serialized. //! serialized.
//! //!
+77 -3
View File
@@ -117,10 +117,19 @@ pub struct FunctionId {
impl fmt::Display for FunctionId { impl fmt::Display for FunctionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}::{}", self.module, self.name) write!(f, "{}::{}", self.module, escape_function_name(&self.name))
} }
} }
/// Escape the module/function delimiter inside a function name.
///
/// The canonical form is `<module>::<name>`; a name that itself contains `::`
/// would make the delimiter ambiguous. Normal names are unchanged. `%` is
/// escaped first so a literal `%3A%3A` cannot collide with an escaped `::`.
pub fn escape_function_name(name: &str) -> String {
name.replace('%', "%25").replace("::", "%3A%3A")
}
/// Identity of an addressable heading range. /// Identity of an addressable heading range.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct UnitId { pub struct UnitId {
@@ -137,12 +146,31 @@ impl fmt::Display for UnitId {
if index > 0 { if index > 0 {
f.write_str("/")?; f.write_str("/")?;
} }
f.write_str(part)?; f.write_str(&escape_identity_segment(part))?;
} }
Ok(()) Ok(())
} }
} }
/// Escape the structural separators of a canonical identity segment.
///
/// A unit display id is `<module>#<seg>/<seg>`. Escaping `%`, `/` and `#`
/// inside each segment keeps the rendering injective: a single heading named
/// `a/b` renders `a%2Fb`, never the two-level path `a` -> `b`. Headings that
/// do not contain a separator keep their existing rendering.
pub fn escape_identity_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for ch in segment.chars() {
match ch {
'%' => out.push_str("%25"),
'/' => out.push_str("%2F"),
'#' => out.push_str("%23"),
other => out.push(other),
}
}
out
}
/// Role of a heading range. /// Role of a heading range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@@ -491,7 +519,7 @@ pub struct Program {
pub external_callables: Vec<callable::CallableDescriptor>, pub external_callables: Vec<callable::CallableDescriptor>,
/// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054). /// Resolved static call bindings (RFC-EXT-0001 §4.2, ADR-0054).
/// ///
/// Internal IR: deliberately skipped on the wire so Analysis/Trace v2 /// Internal IR: deliberately skipped on the wire so Analysis v3/Observation v1
/// consumers are unaffected. A prepared program always carries a complete /// consumers are unaffected. A prepared program always carries a complete
/// table; the runtime never re-resolves names. /// table; the runtime never re-resolves names.
#[serde(skip)] #[serde(skip)]
@@ -582,6 +610,52 @@ mod tests {
assert_eq!(module.id.to_string(), "root:default::index.mq.md"); assert_eq!(module.id.to_string(), "root:default::index.mq.md");
} }
#[test]
fn function_ids_escape_the_module_delimiter_inside_names() {
let module = ModuleId::from("index.mq.md");
let plain = FunctionId {
module: module.clone(),
name: "数学.计算".to_string(),
};
assert_eq!(plain.to_string(), "root:default::index.mq.md::数学.计算");
let dotted = FunctionId {
module: module.clone(),
name: "a::b".to_string(),
};
assert_eq!(dotted.to_string(), "root:default::index.mq.md::a%3A%3Ab");
let literal = FunctionId {
module,
name: "a%3A%3Ab".to_string(),
};
assert_ne!(literal.to_string(), dotted.to_string());
}
#[test]
fn unit_ids_are_injective_across_separator_characters() {
let module = ModuleId::from("index.mq.md");
let one_segment = UnitId {
module: module.clone(),
path: vec!["a/b".to_string()],
};
let two_segments = UnitId {
module: module.clone(),
path: vec!["a".to_string(), "b".to_string()],
};
assert_ne!(one_segment.to_string(), two_segments.to_string());
assert!(one_segment.to_string().ends_with("#a%2Fb"));
assert!(two_segments.to_string().ends_with("#a/b"));
let hash = UnitId {
module: module.clone(),
path: vec!["a#b%c".to_string()],
};
assert_eq!(hash.to_string(), "root:default::index.mq.md#a%23b%25c");
let plain = UnitId {
module,
path: vec!["数学".to_string(), "计算力".to_string()],
};
assert_eq!(plain.to_string(), "root:default::index.mq.md#数学/计算力");
}
#[test] #[test]
fn ir_serializes_for_inspect() { fn ir_serializes_for_inspect() {
let stmt = Stmt::Return { let stmt = Stmt::Return {
+9
View File
@@ -53,6 +53,9 @@ pub mod codes {
pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function"; pub const SEM_NO_ENTRY_FUNCTION: &str = "sem.no_entry_function";
/// A signature was inferred rather than declared. /// A signature was inferred rather than declared.
pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature"; pub const SEM_INFERRED_SIGNATURE: &str = "sem.inferred_signature";
/// A canonical identity would be ambiguous (a separator appears inside a
/// component), so no injective public identity can be produced.
pub const SEM_AMBIGUOUS_IDENTITY: &str = "sem.ambiguous_identity";
/// An executable payload failed to parse as an expression or statement. /// An executable payload failed to parse as an expression or statement.
pub const EXPR_PARSE: &str = "expr.parse"; pub const EXPR_PARSE: &str = "expr.parse";
/// A function name is referenced but no such function exists. /// A function name is referenced but no such function exists.
@@ -69,6 +72,12 @@ pub mod codes {
pub const MODULE_CYCLE: &str = "module.cycle"; pub const MODULE_CYCLE: &str = "module.cycle";
/// A Markdown reference or link target cannot be resolved. /// A Markdown reference or link target cannot be resolved.
pub const REF_UNRESOLVED: &str = "ref.unresolved"; pub const REF_UNRESOLVED: &str = "ref.unresolved";
/// A Markdown reference has several exact canonical-name candidates.
pub const REF_AMBIGUOUS: &str = "ref.ambiguous";
/// A Markdown reference is malformed or outside the allowed scope.
pub const REF_INVALID: &str = "ref.invalid";
/// A Markdown reference target was not verified by the current catalog.
pub const REF_NOT_LOADED: &str = "ref.not_loaded";
/// The requested math operation is outside the supported subset. /// The requested math operation is outside the supported subset.
pub const MATH_UNSUPPORTED: &str = "math.unsupported"; pub const MATH_UNSUPPORTED: &str = "math.unsupported";
/// A foreign language kernel is not available on this machine. /// A foreign language kernel is not available on this machine.
+1 -1
View File
@@ -38,7 +38,7 @@
3. 冻结 CLI 的外部仓库黑盒验收在**发布 SHA**重新执行,至少 pure pinned-Git 包、Callable Worker、陌生 Foreign Kernel、Provider v2、Tool/Analysis/Trace、权限负例及工件改动负例全部 PASS;生成并校验 `docs/evidence/extension/<SHA>/manifest.json`。 3. 冻结 CLI 的外部仓库黑盒验收在**发布 SHA**重新执行,至少 pure pinned-Git 包、Callable Worker、陌生 Foreign Kernel、Provider v2、Tool/Analysis/Trace、权限负例及工件改动负例全部 PASS;生成并校验 `docs/evidence/extension/<SHA>/manifest.json`。
4. 冷安装、离线 `--version`/`--help`、`check/run/call`、lock/sync、Tool 安装与分发、Provider Worker 启动、错 SHA/错目标/未授权拒绝全部由发布归档中的**实际二进制**完成;不得依赖开发源码目录。 4. 冷安装、离线 `--version`/`--help`、`check/run/call`、lock/sync、Tool 安装与分发、Provider Worker 启动、错 SHA/错目标/未授权拒绝全部由发布归档中的**实际二进制**完成;不得依赖开发源码目录。
5. **不得虚假宣传安全隔离。** 发布包若保留并开放 Linux `strict`,必须有该 SHA 的真实 G3 隔离负例证据;若暂无证据,需采用明确经过测试的 fail-closed 禁用方式并在公告中写 `strict: unsupported`。不允许仅改 README 却继续将未验证的 `strict` 描述为安全保障。Beta 的这一策略必须经维护者明确签字并由 CI 可复查。 5. **不得虚假宣传安全隔离。** 发布包若保留并开放 Linux `strict`,必须有该 SHA 的真实 G3 隔离负例证据;若暂无证据,需采用明确经过测试的 fail-closed 禁用方式并在公告中写 `strict: unsupported`。不允许仅改 README 却继续将未验证的 `strict` 描述为安全保障。Beta 的这一策略必须经维护者明确签字并由 CI 可复查。
6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta-only WARN** 并公开环境和限制;必须通过 9 个正确性基准,不允许数值漂移或已确认的灾难性回退。 6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta/RC-only WARN** 并公开环境和限制;必须通过正确性基准,不允许数值漂移或已确认的灾难性回退。RC 允许经维护者批准的共享节点 WARN;最终 stable/LTS 必须使用专用固定节点,该共享节点例外不延续到 LTS。
7. 明确产品版本 `3.0.0-beta.1` 与协议独立版本;工具 SemVer 协商在真实测试版上可安装、拒绝不兼容范围、不会误把 `<1` 当成支持 3.x。 7. 明确产品版本 `3.0.0-beta.1` 与协议独立版本;工具 SemVer 协商在真实测试版上可安装、拒绝不兼容范围、不会误把 `<1` 当成支持 3.x。
8. `README`、`CHANGELOG`、`COMPATIBILITY`、`docs/STATUS`、`docs/releasing`、协议入口页、迁移说明,均更新至同一事实基线;无“未实现却声称已发布”或“已实现仍称 Proposed”的矛盾。 8. `README`、`CHANGELOG`、`COMPATIBILITY`、`docs/STATUS`、`docs/releasing`、协议入口页、迁移说明,均更新至同一事实基线;无“未实现却声称已发布”或“已实现仍称 Proposed”的矛盾。
9. 不发布未经实际构建/烟测的平台二进制;产物附 SHA256、SOURCE_SHA、构建工具链信息和已知限制。 9. 不发布未经实际构建/烟测的平台二进制;产物附 SHA256、SOURCE_SHA、构建工具链信息和已知限制。
@@ -1,5 +1,14 @@
# Marqdo 3.x 第三方开发者接入手册 # Marqdo 3.x 第三方开发者接入手册
> **历史文档(beta 时代记录)。** 本文于 `3.0.0-beta.1` 上验证并随其发布。
> beta 时代的 Analysis v2、Trace v2、Tool Protocol v1 与
> `run/call --trace-file` 等接口已被 [ADR-0068](adr/0068-single-current-public-contracts.md)
> 原地替换:当前契约是 Analysis v3、Observation v1、CLI Tool revision 1。
> 请以 `spec/`([analysis](spec/analysis.md)、[observation](spec/observation.md)、
> [cli-tool](spec/cli-tool.md))和
> [`developers/README.md`](developers/README.md) 为当前入口;本文仅作 beta
> 接洽流程与迁移背景保留,其中出现的旧命令/旧协议名不代表当前 CLI 可用。
>
> 状态:**随 `3.0.0-beta.1` 发布**(Linux x86_64 beta)。产品版本为 `3.0.0-beta.1`;协议版本独立:Analysis v2、Trace v2、Tool v1、Plugin ABI v1、Foreign wire v1、Provider manifest v2、Lock v4、Markdown profile `marqdo.md.v1`。官方 stdlib 包版本 `0.1.0`、插件/工具/示例包版本也都是独立版本轴,不随产品版本变化。 > 状态:**随 `3.0.0-beta.1` 发布**(Linux x86_64 beta)。产品版本为 `3.0.0-beta.1`;协议版本独立:Analysis v2、Trace v2、Tool v1、Plugin ABI v1、Foreign wire v1、Provider manifest v2、Lock v4、Markdown profile `marqdo.md.v1`。官方 stdlib 包版本 `0.1.0`、插件/工具/示例包版本也都是独立版本轴,不随产品版本变化。
> >
> 本文是入门与工程接洽流程;与已发布二进制冲突时,以该版本 `--help`、`--version`、`spec/` 和 release notes 为准。本文所有命令片段都已在 `3.0.0-beta.1` 二进制上验证;未验证的可能平台行为会明确标注为 UNVERIFIED/UNSUPPORTED,绝不默认为支持。 > 本文是入门与工程接洽流程;与已发布二进制冲突时,以该版本 `--help`、`--version`、`spec/` 和 release notes 为准。本文所有命令片段都已在 `3.0.0-beta.1` 二进制上验证;未验证的可能平台行为会明确标注为 UNVERIFIED/UNSUPPORTED,绝不默认为支持。
+110 -26
View File
@@ -1,13 +1,16 @@
# Marqdo Implementation Status # Marqdo Implementation Status
Snapshot: **2026-11-22**, product version **`3.0.0-beta.1`** (prerelease, tag Snapshot: **2026-11-25**, product version **`3.0.0-rc.4`** (prerelease
`v3.0.0-beta.1`). Released platform: **Linux x86_64 (glibc)**. Tagged source candidate). The previous release is `3.0.0-rc.3` at source SHA
SHA: **`2c7c4f31e7a388d3fcfa717a77067e696ed13854`**; release: **`1e2a045cc78bf40972181abb44e7117c56cf4401`**; release:
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. The https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3. The supported
same-SHA evidence aggregate is platform is **Linux x86_64 (glibc 2.39)**. The rc.3 same-SHA gate aggregate is
[`evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json) [`evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
(decision `BETA_RELEASE_CANDIDATE`); binary hashes are in the archive's (decision `RC_RELEASE_CANDIDATE`); its binary hashes are in that archive's
`RELEASE_INFO.json`. Do not copy a SHA from a plan. `RELEASE_INFO.json`, not in the rc.4 candidate. Previous prereleases:
`3.0.0-rc.2` at `9149ee40a48fcda692c5c112f66c465487d13dfb` and
`3.0.0-beta.1` at `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. Do not copy a
SHA from a plan.
Current architecture overview: Current architecture overview:
[`architecture/CURRENT.md`](architecture/CURRENT.md). [`architecture/CURRENT.md`](architecture/CURRENT.md).
@@ -26,11 +29,13 @@ as current status.
## RC candidate ## RC candidate
The workspace reports `3.0.0-rc.3` and declares Rust 1.89 as its locked The workspace reports `3.0.0-rc.4` and declares Rust 1.89 as its locked
minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The
[release procedure](releasing.md) requires a green manifest bound to the [release procedure](releasing.md) requires a green manifest bound to the
candidate SHA before publication. The release record below refers to the candidate SHA before publication. A candidate is not a release: it must not be
published beta. tagged or announced until the same-SHA CI, archive-only cold install, frozen
external conformance, strict VM and performance gates are executed for that
SHA. The release records below refer to their tagged binaries.
## Current protocol integration ## Current protocol integration
@@ -68,6 +73,52 @@ The `spec/` tree contains only current contracts; retired specifications are in
Git history and tagged archives. The earlier release records below describe Git history and tagged archives. The earlier release records below describe
their tagged binaries and are not current protocol claims. their tagged binaries and are not current protocol claims.
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 candidate)
The candidate replaces the program-only Analysis projection in place under
[ADR-0069](adr/0069-public-analysis-boundary.md): exact source and document
AST, complete heading scopes and anchors, entry/manifest/lock/stdlib/extension
snapshot identity, one shared document-link resolver with explicit states,
calls with target kind/owner/reason, and an owner-only atomic `--emit` writer.
The retired duplicate resolver and the post-preparation lock re-read are gone.
Local evidence and raw numbers:
[`evidence/2026-11-25-rc.4-analysis-boundary.md`](evidence/2026-11-25-rc.4-analysis-boundary.md).
Executed 2026-11-25 in the local Linux x86_64 development container
(workspace `3.0.0-rc.4`, Rust 1.100.0):
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS
cargo test -p marqdo-cli --test analysis_boundary PASS
cargo test -p marqdo-cli --test analysis_observation PASS
cargo test -p marqdo-cli --test integration_cli PASS
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker PASS
python3 tests/consumers/analysis_consumer.py <artifact> PASS
python3 tests/consumers/validate_protocols.py <analysis> <observation> <tool> PASS
python3 tests/consumers/view_consumer.py <artifact> PASS
python3 tests/consumers/lint_consumer.py <artifact> PASS
python3 tests/consumers/knowledge_consumer.py <artifact...> PASS
```
Local development-container performance against the rc.3 archive binary on a
101-module fixture (p95 ratio, peak-RSS ratio): no-emit `0.999 / 1.001`,
`--emit` `1.210 / 1.186`, `--refs` `1.145 / 1.093`. These are smoke numbers,
not a dedicated-node G4 result.
Same-SHA CI ([pipeline #89](https://ci.cflmy.cn/repos/1/pipeline/89)) is PASS
for the candidate code SHA `e0645f3` on all four lanes, and the follow-up
CI/tooling tree `b1fc211` is fully green in
[pipeline #91](https://ci.cflmy.cn/repos/1/pipeline/91); its build lane packaged the archive, ran the
archive smoke and the frozen extension suite 7/7. A local same-SHA archive
passed smoke and the archive-only Ubuntu 24.04 cold-install container, and the
frozen suite passed 7/7 from a clean worktree. The gate aggregate is
[`evidence/ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json`](evidence/ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json)
and decides `DO_NOT_RELEASE`: the RC profile still requires a same-SHA strict
VM PASS and an approved G4 node result, neither of which is available here. The
rc.3 rows below remain the last published release evidence.
## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate) ## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate)
The current tree replaces the retired protocols in place, with no compatibility The current tree replaces the retired protocols in place, with no compatibility
@@ -76,19 +127,21 @@ path. Policy: [ADR-0068](adr/0068-single-current-public-contracts.md) and
section records commands executed on the candidate tree; it is local Linux section records commands executed on the candidate tree; it is local Linux
evidence, not a same-SHA CI or archive gate. evidence, not a same-SHA CI or archive gate.
Executed 2026-11-24 on Linux x86_64 (workspace `3.0.0-rc.3`, Rust 1.93.1): Executed 2026-11-24 on the reviewed candidate tree, Linux x86_64
(workspace `3.0.0-rc.3`, Rust 1.100.0):
```text ```text
cargo fmt --all -- --check PASS cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS: 601 passed, 0 failed, 2 ignored cargo test --workspace --locked PASS: 607 passed, 0 failed, 2 ignored
cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed
cargo test -p marqdo-cli --test docs_consistency PASS: 5 passed cargo test -p marqdo-cli --test docs_consistency PASS: 7 passed
cargo test -p marqdo-cli --test observation PASS: 15 passed cargo test -p marqdo-cli --test observation PASS: 16 passed
cargo test -p marqdo-cli --test analysis_observation PASS: 10 passed cargo test -p marqdo-cli --test analysis_observation PASS: 23 passed
cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed
cargo test -p marqdo-cli --test extension_selection PASS: 14 passed cargo test -p marqdo-cli --test extension_selection PASS: 14 passed
cargo test -p marqdo-worker-ipc PASS: 5 passed cargo test -p marqdo-worker-ipc PASS: 5 passed
python3 -m unittest discover -s tools/ci -p "test_*.py" PASS: 41 tests
``` ```
Black-box consumer run against the real `target/debug/marqdo`: Black-box consumer run against the real `target/debug/marqdo`:
@@ -107,7 +160,7 @@ observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected
marqdo --version marqdo 3.0.0-rc.3 marqdo --version marqdo 3.0.0-rc.3
``` ```
Same-SHA CI on Linux x86_64 Same-SHA CI on the first (pre-review) candidate build, Linux x86_64
([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit ([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit
`5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full `5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full
Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows
@@ -119,16 +172,47 @@ passed the from-archive smoke, and passed the frozen external conformance suite
(callable registry, plugin worker, foreign kernel, provider CLI, pinned package, (callable registry, plugin worker, foreign kernel, provider CLI, pinned package,
tool Analysis consumer, negative security). tool Analysis consumer, negative security).
The detailed local log and the CI addendum are in The detailed local log and that CI addendum are in
[`evidence/2026-11-24-rc.3-protocol-convergence-local.md`](evidence/2026-11-24-rc.3-protocol-convergence-local.md). [`evidence/2026-11-24-rc.3-protocol-convergence-local.md`](evidence/2026-11-24-rc.3-protocol-convergence-local.md);
they describe the protocol convergence itself. The reviewed candidate's own
same-SHA CI, archive and gate evidence are recorded in the release evidence
bound to the released SHA.
Release status: the tree, contracts, archive and same-SHA Linux CI are ready for ### 0.9.1 Review closure on the candidate tree
`3.0.0-rc.3`, but **publication is not authorized by this evidence**. The RC
profile in [`releasing.md`](releasing.md) additionally requires a same-SHA A code review of the first candidate build found and closed these defects
strict-L1 PASS on a disposable VM as a non-root user and fixed-node G4 (regression test for each):
performance evidence (or the recorded maintainer exception). Neither exists
here; the CI host truthfully reports `strict: unavailable` fail-closed. Do not - A strict run no longer emits a partial JSONL stream for a destination it
tag or publish `v3.0.0-rc.3` from this section. refuses; live and file destinations are rejected before any session opens.
- `check --emit` removes a previous Analysis artifact when the project cannot
be loaded, not only when it has compile errors.
- Filesystem resource requests report their concrete effect operation
(`fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`,
`fs.rename`).
- The shared worker transport preserves `worker_frame_too_large` and
`worker_encode_failed` for the plugin boundary.
- Observation error locations no longer embed an absolute host path, and
pre-start option errors use the documented `options` phase.
- The event and snapshot schemas agree on the capture `level` enum.
- The G4 workload catalogue measures `run`/`call` through `--output json`; the
retired `--json` flag had made every non-check workload fail correctness.
- `spec/` and the current developer guides were brought back in line with the
binary, and a docs-consistency gate now fails when a retired interface or a
deleted spec path returns.
Release status: **published as `v3.0.0-rc.3`**. The RC profile gates in
[`releasing.md`](releasing.md) were executed on the tagged SHA: same-SHA Linux
CI (formatted, clippy-clean, 607 workspace tests, contract lane, minimum Rust
1.89, build lane with from-archive smoke and frozen extensions 7/7), the
archive-only clean install, frozen external conformance against the published
archive, version compatibility, a disposable-VM strict L1 PASS as non-root with
the published archive re-verified in that guest, and three paired shared-node
G4 runs whose maintainer-approved `WARN` is recorded for this named RC. The
per-gate manifest, release notes and logs are in
[`evidence/2026-11-24-rc.3-release.md`](evidence/2026-11-24-rc.3-release.md),
[`evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json) and the
release assets. An unavailable strict host is fail-closed, never a downgrade.
## 0. Beta release record — `3.0.0-beta.1` ## 0. Beta release record — `3.0.0-beta.1`
@@ -6,9 +6,10 @@
- **Status:** Accepted - **Status:** Accepted
- **Date:** 2026-11-22 - **Date:** 2026-11-22
- **Decision owners:** CLI, runtime and host maintainers - **Decision owners:** CLI, runtime and host maintainers
- **Inputs:** [RFC-OBS-0001](../architecture/RFC-OBS-0001-runtime-observability.md) - **Inputs:** RFC-OBS-0001 (issue `#1` of `cflmy/marqdo-cli`), Trace v2,
(issue `#1` of `cflmy/marqdo-cli`), [Trace v2](../../spec/trace-v2.md), Analysis v2 and Tool Protocol v1. Those documents were retired in place by
[Analysis v2](../../spec/analysis-v2.md), [Tool Protocol v1](../../spec/tool-v1.md) [ADR-0068](0068-single-current-public-contracts.md) and are available at
their tagged commits, not in the current `spec/` tree.
## Context ## Context
+80
View File
@@ -0,0 +1,80 @@
# ADR-0069 — One public Analysis boundary for independent static tools
Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-25).
## Context
Issue [#10](https://git.cflmy.cn/cflmy/marqdo-cli/issues/10) audited the
public Analysis contract at `master@e6066e6`. The CLI already restricts
View/Lint-style consumers to installed Tools, but the emitted
`marqdo.analysis` document only exposed program IR. It omitted the Markdown
document AST, the exact source text, the entry/context snapshot, heading
scopes and anchors, complete section ranges, and reference resolution states.
Independent tools therefore had to re-parse Markdown, guess section ends or run
a second non-public analysis path. Two implementations of Markdown-link
resolution existed (`analysis.rs` and `commands.rs`), the Analysis `unresolved`
state could not distinguish "not loaded" from "missing", and `analysis.rs`
re-read `marqdo.lock` after preparation.
## Decision
`marqdo check ENTRY --emit PATH` remains the only public static-analysis
producer. Before the first stable release, replace `marqdo.analysis` revision 3
in place under ADR-0068. There is one shape, one producer and one validation
path; retired fields are not read.
The projection is built by one typed encoder from the same
`project_prepare::prepare` facts consumed by `check`, `inspect`, `run` and
`call`:
* `project.entry_module_id`, `manifest_digest`, the captured `lock_digest`,
stdlib identity and the static extension identities that actually took part
in preparation;
* each loaded module's exact UTF-8 `source` and its `source_digest`, plus the
public Markdown AST (`document`) in the shape already described by
`spec/markdown-profile.md`;
* one heading index: canonical path, parent, effective mode, mode origin and
source unit, heading span, complete section span and the function created by
an Exec H2;
* the anchor map, functions, explicit imports, resources, static call bindings
and diagnostics;
* every Markdown link through one scoped `document_refs` resolver that
distinguishes `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`,
`outside_scope` and `invalid`.
The resolver is a pure function over an explicit catalog. Ordinary Analysis
uses the loaded-module catalog and never opens a link target. `check --refs`
and `inspect --refs` build a separate, explicitly limited catalog for direct
link targets and append diagnostics; they do not change the ordinary Analysis
module set and never execute or import a target.
Identity strings stay the current presentation for names that do not contain
the structural separators. Unit paths are now also exposed as the structured
`path` array, and identity display escapes `/`, `#` and `%` inside a path
segment so `<module>#<seg>/<seg>` cannot collide with a segment containing
`/`. `Function.local_name` and `namespace` remain structured fields; consumers
must not split display ids.
The public source field is an explicit local artifact. It is written with
owner-only permissions where the platform supports them, is never copied into
Observation, is never printed by default, and its digestion is the exact
UTF-8 bytes (SHA-256). Observation continues to bind to the SHA-256 of the
exact bytes emitted by `check --emit` with the same static options.
## Security and verification
The boundary remains non-executing: no plugin shared library, worker, foreign
kernel, network request or implicit module load. `--emit` publishes atomically
through an owner-only exclusive temporary file and rename, refuses to overwrite
a loaded source, manifest, lock file, symlink to one, or a hard link to one,
and only removes a previous artifact at a caller-specified output path under
the same guard.
Production checks local typed invariants and the canonical encoder; an
independent Python consumer validates the emitted bytes against the published
JSON Schema and semantic invariants, and mutation fixtures prove that missing
required fields, stale same-revision artifacts, tampered digests/spans,
duplicate ids, wrong ownership and invalid reference states are rejected.
`docs/STATUS.md` records exactly what was executed on which SHA; the
pre-stable line makes no compatibility promise for consumers linked to the
retired shape.
+4
View File
@@ -66,3 +66,7 @@ Files: `0001`–`0050`, plus:
* [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded * [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded
communication and cancellation; communication and cancellation;
* [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers. * [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers.
* [0068](0068-single-current-public-contracts.md) — one current contract per
pre-stable public boundary, replaced in place;
* [0069](0069-public-analysis-boundary.md) — one public Analysis projection for
independent document, lint and knowledge consumers.
+9 -4
View File
@@ -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 is today. It is not a release promise, does not reopen a frozen ADR, and does not
replace `spec/` or a recorded test log. replace `spec/` or a recorded test log.
- Baseline: `2c7c4f31e7a388d3fcfa717a77067e696ed13854` (2026-11-22, tagged `v3.0.0-beta.1`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`). - Baseline: `1e2a045cc78bf40972181abb44e7117c56cf4401` (2026-11-24, tagged `v3.0.0-rc.3`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`). The `3.0.0-rc.4` candidate state is recorded in `../STATUS.md` §0.10.
- Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`. - Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`.
- This is the **single current overview**. Do not add a second running "current state" file; - This is the **single current overview**. Do not add a second running "current state" file;
update this file, `docs/STATUS.md` and an evidence file together. update this file, `docs/STATUS.md` and an evidence file together.
@@ -58,10 +58,14 @@ replace `spec/` or a recorded test log.
[ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy [ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy
for replacing public interfaces before the first stable release. for replacing public interfaces before the first stable release.
[ADR-0069](../adr/0069-public-analysis-boundary.md) closes the public Analysis
boundary: the projection carries the exact source, document AST, complete
heading scope, entry/snapshot identity and one shared document-link resolver,
and the retired program-only fields and duplicate resolver have no active path.
| Boundary | Owner | Current contract | | Boundary | Owner | Current contract |
|---|---|---| |---|---|---|
| Static facts | CLI Analysis projection of the prepared project | [Analysis](../../spec/analysis.md) | | Static facts | CLI Analysis projection of the prepared project: source, document AST, heading scopes, entry/snapshot identity, calls, resources and one document-link resolver | [Analysis](../../spec/analysis.md), [Markdown profile](../../spec/markdown-profile.md), [References](../../spec/references.md) |
| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) | | Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) |
| Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) | | Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) |
| Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) | | Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) |
@@ -183,7 +187,7 @@ review RFC, not a new crate per provider.
| `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` | | `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` |
| core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` | | core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
| `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` | | `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
| Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); third-party heading annotations are **Proposed** metadata only, Analysis v2 unchanged (H-05/H-07) | core mode: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` | | Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); the same index is exposed in Analysis with parent/mode-origin/full-range facts; third-party heading annotations are **Proposed** metadata only (H-05/H-07) | core mode and public scope facts: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, `analysis_boundary`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` |
| Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` | | Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` |
| `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` | | `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` |
| `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` | | `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` |
@@ -199,7 +203,8 @@ review RFC, not a new crate per provider.
| `std:net/http` | byte-exact HTTP/1.1 parse/build; chunk sizes are byte counts; text wrapper compatible | implemented (pure `.mq.md`) | `stdlib_http` | | `std:net/http` | byte-exact HTTP/1.1 parse/build; chunk sizes are byte counts; text wrapper compatible | implemented (pure `.mq.md`) | `stdlib_http` |
| HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` | | HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` |
| print / official stdlib aliases | `打印`/`print` are verified `stdlib.json` public aliases bound to `io.mq.md::写值`; ordinary Marqdo calls, no `print_override`, no runtime branch, no `HostOp::Print` | implemented (ADR-0058) | `stdlib_alias_routing`, `print_routing`, `stdlib_product` | | print / official stdlib aliases | `打印`/`print` are verified `stdlib.json` public aliases bound to `io.mq.md::写值`; ordinary Marqdo calls, no `print_override`, no runtime branch, no `HostOp::Print` | implemented (ADR-0058) | `stdlib_alias_routing`, `print_routing`, `stdlib_product` |
| callable resolution | one registry + one `bind_program_calls` pass; `check`/`run`/`inspect`/Analysis share `CallSiteKey` bindings; plugin exports reconcile exactly with static manifests; no runtime name fallback | implemented (ADR-0054) | `callable_resolution`, `plugin_worker`, `analysis_trace` | | callable resolution | one registry + one `bind_program_calls` pass; `check`/`run`/`inspect`/Analysis share `CallSiteKey` bindings; plugin exports reconcile exactly with static manifests; no runtime name fallback | implemented (ADR-0054) | `callable_resolution`, `plugin_worker`, `analysis_observation` |
| document references | one pure `document_refs` resolver over an explicit catalog; Analysis uses the loaded catalog and never opens a link, `--refs` may verify direct local targets; states distinguish unloaded/missing/ambiguous/external/outside-scope/invalid | implemented (ADR-0069) | `analysis_boundary`, `document_refs` unit tests, `view_consumer`, `lint_consumer`, `knowledge_consumer` |
| resource provider v2 CLI | `--provider`/`--allow-provider` select and authorize a `provider.json` schema-2 `c-abi-1` worker artifact; manifest/artifact/grants/duplicate kinds verified before spawn; sibling helper only | implemented linux/x86_64; other platforms fail closed (ADR-0055) | `provider_cli` | | resource provider v2 CLI | `--provider`/`--allow-provider` select and authorize a `provider.json` schema-2 `c-abi-1` worker artifact; manifest/artifact/grants/duplicate kinds verified before spawn; sibling helper only | implemented linux/x86_64; other platforms fail closed (ADR-0055) | `provider_cli` |
| capability handlers | trusted handler registry executes granted capabilities under budget/audit; missing handler is `capability.unavailable`; `fs.read` is the first real handler | implemented (ADR-0057) | `capability_handlers` | | capability handlers | trusted handler registry executes granted capabilities under budget/audit; missing handler is `capability.unavailable`; `fs.read` is the first real handler | implemented (ADR-0057) | `capability_handlers` |
| strict mode | only the pure/Math execution path and the built-in stdout console channel; project/foreign/plugin/tool/trace/file/network grants are rejected | implemented L1; L2 not implemented | `tests/security`, `resource_streams`, `stdlib_product` | | strict mode | only the pure/Math execution path and the built-in stdout console channel; project/foreign/plugin/tool/trace/file/network grants are rejected | implemented L1; L2 not implemented | `tests/security`, `resource_streams`, `stdlib_product` |
@@ -1,9 +1,9 @@
# RFC-OBS-0001: Runtime observability and real-time execution events # RFC-OBS-0001: Runtime observability and real-time execution events
> **Status:** Accepted and implemented at the level recorded in > **Status:** Historical design input. [ADR-0068](../adr/0068-single-current-public-contracts.md)
> [`docs/STATUS.md`](../STATUS.md); this file is the frozen design input. > replaced Execution Events v1 and Trace v2 with the single current
> The normative protocol contract is > [Observation contract](../../spec/observation.md); the retired spec named
> [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md). > below exists only in Git history and in tagged archives.
> >
> **Source:** issue `#1` of `cflmy/marqdo-cli`, filed 2026-11-22 against > **Source:** issue `#1` of `cflmy/marqdo-cli`, filed 2026-11-22 against
> `master@eeea01d672c07b6be7d6444031d1619309dc88ab`. It is reproduced here so > `master@eeea01d672c07b6be7d6444031d1619309dc88ab`. It is reproduced here so
+25 -22
View File
@@ -18,52 +18,55 @@ and the Windows cross-target compile check; `build` packages the archive, runs
the from-archive smoke and the frozen external conformance suite. the from-archive smoke and the frozen external conformance suite.
```text ```text
contract: contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
cargo build --locked -p marqdo-cli -p marqdo-provider-worker cargo build --locked -p marqdo-cli -p marqdo-provider-worker
real CLI check/run over the Observation fixtures real CLI check/run over the Observation fixtures
analysis_consumer / observation_consumer / validate_protocols analysis_consumer / observation_consumer / validate_protocols
stream==snapshot assertion and stale-Analysis rejection stream==snapshot assertion (tools/ci/verify_observation_stream.py)
stale-Analysis rejection
test: test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries):
rustup component add clippy rustfmt
apt install curl/ca-certificates/python3/python3-jsonschema + Node.js 22
cargo fmt --all -- --check cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings cargo clippy --workspace --all-targets -- -D warnings
cargo build --locked -p marqdo-cli -p marqdo-provider-worker cargo build --locked -p marqdo-provider-worker
cargo test --workspace --locked cargo test --workspace --locked
check + run tests/consumers/fixtures/observation/basic.mq.md docs_consistency / architecture_boundaries / stdlib_product
analysis_consumer.py / observation_consumer.py (stream + snapshot)
check + run the nested-loop control-flow conformance fixture
validate_protocols.py / analysis_consumer.py --require-transfers
observation_consumer.py (stream, snapshot, stale-Analysis rejection)
stream JSONL == snapshot events assertion
cargo test -p marqdo-cli --test docs_consistency
cargo test -p marqdo-cli --test architecture_boundaries
cargo test -p marqdo-cli --test stdlib_product
python3 -m unittest discover -s tools/ci -p "test_*.py" python3 -m unittest discover -s tools/ci -p "test_*.py"
rustup target add x86_64-pc-windows-gnu rustup target add x86_64-pc-windows-gnu
cargo check --workspace --all-targets --target x86_64-pc-windows-gnu cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
build (depends on test): minimum-rust (rust:1.89-bookworm):
cargo check --locked --workspace --all-targets
build (depends on test, minimum-rust, contract):
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
package + cold-install smoke (current Analysis/Observation contracts) package the deterministic archive for $CI_COMMIT_SHA
from-archive smoke (tools/release/smoke.py)
frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7)
``` ```
A separate manual workflow, [`.woodpecker/performance.yml`](../.woodpecker/performance.yml),
builds the beta baseline and the candidate archive on the shared Woodpecker
agent and records the nine G4 comparisons. Its reports stay `SMOKE`; only the
maintainer-approved RC `WARN` exception can use them (see
[`releasing.md`](releasing.md) and [`performance.md`](performance.md)).
The pipeline is a protocol consumer itself: it must exercise only the current The pipeline is a protocol consumer itself: it must exercise only the current
Analysis and Observation contracts. `docs_consistency::ci_configuration_uses_only_current_protocols` Analysis and Observation contracts. `docs_consistency::ci_configuration_uses_only_current_protocols`
fails if a retired option or consumer name returns. fails if a retired option or consumer name returns, and
`current_contract_documents_do_not_reference_retired_interfaces` extends the
same rule to `spec/` and the current developer guides.
Node.js 22 is required because the optional foreign-kernel tests use ES-module Node.js 22 is required because the optional foreign-kernel tests use ES-module
syntax; Debian bookworm's Node 18 fails those tests. syntax; Debian bookworm's Node 18 fails those tests.
> **Language contract note.** `cargo test --workspace` includes conformance > **Language contract note.** `cargo test --workspace` includes conformance
> fixtures that execute `.mq.md` source under > fixtures that execute `.mq.md` source under
> [RFC-LANG-0002](architecture/RFC-LANG-0002-unified-semantics.md). The > [RFC-LANG-0002](architecture/RFC-LANG-0002-unified-semantics.md). A red
> implementation, stdlib digest and corpus are green at `ffd1cc9`; a red
> executable-source suite is a real regression, not an expected migration > executable-source suite is a real regression, not an expected migration
> state. Do not "fix" it by restoring the old mapper or regenerating goldens; > state. Do not "fix" it by restoring the old mapper or regenerating goldens;
> see [`STATUS.md`](STATUS.md). The pipeline definition itself > see [`STATUS.md`](STATUS.md). The lanes above are the current definition; it
> (fmt/clippy/test/build, security lane, platform gaps) is unchanged. > changes only with this document.
## What this pipeline does not cover ## What this pipeline does not cover
+2 -2
View File
@@ -18,7 +18,7 @@ their date.
```text ```text
marqdo-cli/ marqdo-cli/
├── Cargo.toml workspace (15 crates, resolver 2) ├── Cargo.toml workspace (16 crates, resolver 2)
├── AGENTS.md operator rules for contributors/agents ├── AGENTS.md operator rules for contributors/agents
├── README.md user-facing quickstart and limits ├── README.md user-facing quickstart and limits
├── docs/ ├── docs/
@@ -209,7 +209,7 @@ counts, harness responsibilities and known observations.
## 5. Coding conventions ## 5. Coding conventions
* Rust edition 2021, `rust-version = 1.82`, workspace version `3.0.0-beta.1`. * Rust edition 2021, `rust-version = 1.89`, workspace version `3.0.0-rc.4`.
* `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses * `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses
`#![forbid(unsafe_code)]`); the ABI/loader crates contain the only `#![forbid(unsafe_code)]`); the ABI/loader crates contain the only
`unsafe` code and every block has a SAFETY comment explaining the contract. `unsafe` code and every block has a SAFETY comment explaining the contract.
+4 -2
View File
@@ -6,7 +6,7 @@ Rust structures, `marqdo-ir` internals, `inspect --ir`, relative paths into the
core checkout, or host memory layout. Adding a new domain function must not core checkout, or host memory layout. Adding a new domain function must not
require a core commit. require a core commit.
Product version for these docs: **`3.0.0-rc.3`** (Linux x86_64 candidate). Product version for these docs: **`3.0.0-rc.4`** (Linux x86_64 candidate).
Current protocol contracts: Analysis, Observation, CLI Tool, Plugin ABI v1, Current protocol contracts: Analysis, Observation, CLI Tool, Plugin ABI v1,
Foreign wire v1, Provider manifest v2, lock v4 and markdown profile Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
`marqdo.md.v1`. Product, protocol and package versions are independent; see `marqdo.md.v1`. Product, protocol and package versions are independent; see
@@ -41,7 +41,9 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
file ships in the archive as `KNOWN_LIMITATIONS.md`). file ships in the archive as `KNOWN_LIMITATIONS.md`).
The full worked handbook is The full worked handbook is
[`../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md). [`../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](../MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md)
(beta-era integration handbook, kept as a historical record; the current
contracts are the pages above and `spec/`).
Normative contracts live in [`../../spec/`](../../spec/); this directory is a Normative contracts live in [`../../spec/`](../../spec/); this directory is a
task-oriented map, not a second specification. task-oriented map, not a second specification.
+255
View File
@@ -0,0 +1,255 @@
# Public Analysis consumers after issue #10
Applies to `marqdo.analysis` revision 3 as defined by
[ADR-0069](../adr/0069-public-analysis-boundary.md), [spec/analysis.md](../../spec/analysis.md)
and [the schema](../../spec/schemas/analysis.schema.json). This page is the
integration guide for downstream static tools, in particular `marqdo-lint` and
`marqdo-view`.
The revision number did not change, but the shape did. An old revision-3
artifact is **not** accepted: current required fields are missing, and the
current schema and consumer semantics reject it. Rebuild the artifact and
update the consumer; do not add a compatibility reader or a second Analysis
shape.
## 1. What the CLI already provides
Run one command per program entry:
```sh
marqdo check path/to/index.mq.md --emit analysis.json
```
The artifact contains everything a document/lint/knowledge reader needs, from
the same static preparation as `check`, `inspect`, `run` and `call`:
- exact UTF-8 `modules[].source` and its SHA-256 `source_digest`;
- the Markdown AST in `modules[].document`;
- heading scopes in `modules[].units` and anchors in `modules[].anchors`;
- functions, imports, calls and resources;
- Markdown references with explicit resolution states;
- project context: `entry_module_id`, `identity_kind`, `root_id`,
`manifest_digest`, captured `lock_digest`, stdlib and extension identities;
- deterministic diagnostics.
`inspect --ast` and `inspect --units` now project the **same** AST and unit
shape. They remain human/debug selections; a machine consumer should read
`check --emit` and stop running a second `inspect --ast` process per module.
## 2. Required consumer changes
### 2.1 Read the source from the artifact
`modules[].source` is the exact text the loader read. Every span is a half-open
UTF-8 byte offset into that string.
- Do not reopen the file from `relative_path` for spans or digests; package
caches, stdlib and dependencies have no stable consumer-facing physical path.
- Verify `sha256(source.encode("utf-8")) == source_digest` before trusting a
span.
- `relative_path` remains package-relative and useful for display and project
layout, not for reconstructing an absolute path.
### 2.2 Document AST
`modules[].document` is the public AST described by
[`spec/markdown-profile.md`](../../spec/markdown-profile.md). Every node has
`kind`, `span` and `children` (`[]` for leaves); attributes/literals follow the
profile. The root `document` span now covers the whole source, including a BOM.
- Parse `document` directly; do not parse Markdown again for program
annotations.
- Renderers may keep their own rendering parser, but any *semantic* decision
(executable region, heading scope, function ownership) must use Analysis.
- Literal payloads are not guaranteed byte-equal to their span (entities,
escapes and code whitespace are normalised).
### 2.3 Heading scope: `span` changed meaning
For every non-root unit:
| Field | Meaning |
|---|---|
| `heading_span` | The original heading AST node span. Use this to locate the heading itself. |
| `span` | **Complete section range** from the heading through the next heading of the same or higher level, or EOF. It includes child headings. |
| `path` | Canonical structured heading path. Do not split `id` to recover it. |
| `parent_id` | Nearest real ancestor unit; root is `null`. |
| `mode` | Effective `exec` or `knowledge`. |
| `mode_origin` | `explicit` (ATX declaration), `inherited`, or `default` for the root. |
| `mode_source_unit_id` | The unit that supplied the mode; self-or-ancestor. |
| `kind` | `root`, `namespace`, `function`, `knowledge`, `section`. |
| `function` | Owning function id for Exec sections; `null` otherwise. |
Do not infer section ends from the next heading's text or from the old
short-span assumption. Use `heading_span` for heading UI; use `span` for the
whole section body.
`anchors` is `[{anchor, unit_id}]`, sorted by anchor. Anchors are navigation
names, not identities; a missing anchor is not a missing document.
### 2.4 References: boolean `resolved` is gone
`modules[].references[]` now always carries:
```json
{
"source": "root:x@0.1.0::index.mq.md",
"source_unit": "root:x@0.1.0::index.mq.md#数学",
"url": "./theory.mq.md#formula",
"span": {"start": 20, "end": 50},
"state": "not_loaded",
"target_kind": null,
"target_module": null,
"target_unit": null,
"candidate_package_instance_id": "root:x@0.1.0",
"candidate_path": "theory.mq.md",
"fragment": "formula",
"candidates": []
}
```
| `state` | Consumer meaning |
|---|---|
| `resolved` | Exact module/unit or explicitly verified local file. `target_kind` is `module` or `file`. |
| `not_loaded` | The loaded catalog did not cover the local candidate. It is **not** missing; do not auto-create it. |
| `missing` | A known catalog module lacks the fragment, or explicit `--refs` verification proved absence. |
| `ambiguous` | Multiple exact canonical-name candidates; `target_unit` is null and `candidates` lists them. Never choose the first. |
| `external` | External URI scheme. No network access; not an error. |
| `outside_scope` | Absolute/drive/UNC/file URI, or a package-root escape. Never read it. |
| `invalid` | Malformed URI/percent encoding/unsupported address. |
Ordinary Analysis resolves only the loaded program. If a consumer needs to
verify unimported local files, use the CLI's explicit check:
```sh
marqdo check entry.mq.md --refs --json
marqdo inspect entry.mq.md --refs --json
```
Do not use the `--refs` artifact as the Observation binding input: `--refs`
adds diagnostics and changes the exact bytes. Run/call bind to the ordinary
`check --emit` bytes with the same static options.
### 2.5 Calls, functions and resources
- `functions[]` still has `id`, `unit_id`, `local_name`, `namespace`, `span`,
`heading_span`, `signature`, `effects`, `body`.
- `calls[]` now has `target_kind`, `target_owner` and `reason`. A plugin target
names the static owner (package/digest); it is never a Marqdo function.
`unresolved` with `reason: dynamic|unbound` is honest, not an error.
- `resources[]` carries `display: null` for code and a boolean for formulas;
verify its `content_digest` against the AST payload if you need integrity.
- The schema is closed: unknown required kinds/fields must be rejected, not
ignored.
### 2.6 Project context and freshness
- Load `project.entry_module_id`; it must occur once in `modules`.
- `root_id` is a logical manifest identity or a content snapshot, not a
cross-project permanent id.
- `manifest_digest` and `lock_digest` are the captured bytes; a changed file on
disk means a new check, not a retry of the old artifact.
- Verify the exact bytes with the published JSON Schema + semantic checks; keep
rejecting stale artifacts whose `source_digest` no longer matches the source
you display.
## 3. `marqdo-view` integration
Current View behavior to replace:
1. It runs `check --json --emit` and separately calls `inspect --ast --json`
per document. Replace the machine path with one `check --emit`; the AST is
`modules[].document`. Keep `inspect` only for human debug output.
2. It re-reads files and compares `source_digest`. Prefer `modules[].source`
directly; if it must use its own file snapshot, compare the artifact digest
and reject a mismatch.
3. Its `RawProject` ignores new required fields. Make
`entry_module_id`, `manifest_digest` and `extensions` required (or validate
with the schema) and remove the v2 acceptance branch. View must accept only
the current revision-3 shape.
4. `RawUnit.span` now means the complete section. For annotation placement use
`heading_span`; for source highlighting use the complete `span`.
5. `RawReference` already reads `state`; remove any remaining `resolved`
boolean mapping and map `not_loaded` as *unverified*, not as a broken link.
For a local candidate the View catalog does not know, show "未加载/未核验";
only `missing`/`ambiguous`/`invalid`/`outside_scope` are actionable errors.
6. Keep validating `source.analysis_digest` for Observation binding. The digest
remains SHA-256 of the exact `--emit` bytes; `--refs` diagnostics change it.
Suggested request/render flow:
```text
check --emit -> verify schema + source_digest -> document AST
-> units (complete span + heading_span) for annotations
-> references (state) for link presentation
-> calls/functions for executable markers
run/call + observation -> verify analysis_digest == sha256(artifact bytes)
```
## 4. `marqdo-lint` integration
Current Lint behavior to replace:
1. It performs one `inspect --ast` per module and then matches it with
Analysis. Use `modules[].source` and `modules[].document` from the same
`check --emit`; this removes a second process and any AST/span drift.
2. Its `AnalysisModule` model only requires the old fields and silently ignores
the new ones. Make `source`, `document`, `anchors` and the new unit fields
required; reject old same-revision artifacts. Prefer generating types from
the published schema rather than `Vec<Value>` for units/references.
3. Heading-boundary rules must use `units[].span` as the complete section and
`heading_span` as the heading itself. This is the authoritative range; do
not infer boundaries from Markdown siblings.
4. Link/reference lint: iterate `references[].state`. Report:
- `missing`/`ambiguous`/`invalid`/`outside_scope` as errors with
`source_unit` + `span`;
- `not_loaded` as an honest "unverified" notice, not a broken reference;
- `external` as informational.
Use the explicit `check --refs --json` run only when the user asks to verify
direct unimported targets.
5. `calls[]` can report static call targets and dynamic/unbound reasons; do not
infer a target from the display string. Plugin/builtin targets are not
Marqdo functions.
6. Continue using `--json` for diagnostic summaries; `--emit` is the only full
Analysis producer.
Suggested lint flow:
```text
check --emit -> verify schema + semantic invariants
-> per module: document + units(full span/heading_span)
-> rules: narrative/executable boundaries, calls, links, docs
-> diagnostics projected from Analysis + local rules
```
## 5. Shared rules for both consumers
- One current contract. Do not add a v2/v3 reader, field probing, fallback AST
from a second parser, or `try old shape then new shape`.
- Reject malformed/old artifacts with a corrective message: regenerate with the
current CLI, reinstall the Tool manifest, rebuild the consumer.
- Tool manifests keep `requires.analysis: 3`; the revision is unchanged, so
reinstall/rebuild is required because the old same-revision bytes are
rejected by the current schema.
- No private Rust crate, no `inspect --ir`, no package-cache path, no writing
to the analyzed project.
- The source in Analysis may contain secrets from the document. Do not log or
upload it by default; store artifacts with owner-only permissions.
- Keep the three independent fixture flows green: document rendering, lint with
diagnostics, and multi-entry knowledge linking.
## 6. Verification commands
On the current CLI:
```sh
marqdo check entry.mq.md --emit analysis.json
python3 tests/consumers/validate_protocols.py analysis.json observation.json tool.json
python3 tests/consumers/analysis_consumer.py analysis.json
marqdo inspect entry.mq.md --refs --json
```
For a downstream checkout, pin the CLI archive and run its real fixtures
against `MARQDO_BIN`; record the CLI SHA and the Analysis schema hash in the
consumer's evidence. See the issue accompanying this document for the exact
downstream acceptance items.
+2 -1
View File
@@ -38,6 +38,7 @@ has opted into this disclosure. Program output and explicit returned values
can themselves contain sensitive data. can themselves contain sensitive data.
Update integrations that previously used the retired run/call JSON, Update integrations that previously used the retired run/call JSON,
Trace or Execution Events options. Use the commands above, remove the old Trace, Execution Events or retired run/call options. Use the commands above,
remove the old
reader, and rebuild and reinstall the Tool with the reader, and rebuild and reinstall the Tool with the
[current manifest](../../spec/cli-tool.md). [current manifest](../../spec/cli-tool.md).
+11 -12
View File
@@ -6,13 +6,12 @@ This page summarizes the public support policy. The authoritative matrix is
## Version axes (do not conflate) ## Version axes (do not conflate)
| Axis | `3.0.0-rc.3` value | Change rule | | Axis | `3.0.0-rc.4` value | Change rule |
|---|---|---| |---|---|---|
| Product / CLI | `3.0.0-rc.2` | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. | | Product / CLI | `3.0.0-rc.4` (candidate) | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. |
| Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. | | Analysis | v3 | One writer and one current major for every project. New major for incompatible changes; consumers reject unknown majors. |
| Trace | v2 | New major for incompatible changes; binds to exact Analysis bytes. | | Observation | v1 | One `run_id`/`seq` event sequence per execution; JSONL, JSON snapshot and file snapshot come from the same run. New major for incompatible required-field/ordering/redaction changes. |
| Execution Events | v1 | One-line NDJSON stream; new major for incompatible required-field/ordering/redaction changes. Consumers reject unknown majors. | | CLI Tool | revision 1 | Exact `requires.api_revision` plus optional exact `analysis`/`observation` integers; no version arrays or negotiation. |
| CLI Tool | v1 | Frozen manifest/negotiation/bundle contract for v1. |
| Plugin ABI | v1 (`1.0`) | Frozen C layout and version negotiation. | | Plugin ABI | v1 (`1.0`) | Frozen C layout and version negotiation. |
| Foreign wire | v1 | One-shot request envelope. | | Foreign wire | v1 | One-shot request envelope. |
| Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`. | | Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`. |
@@ -21,8 +20,8 @@ This page summarizes the public support policy. The authoritative matrix is
| Bundled stdlib | `0.1.0` | Independent package version; not the product version. | | Bundled stdlib | `0.1.0` | Independent package version; not the product version. |
| Plugin/tool/example packages | their own | Independent SemVer. | | Plugin/tool/example packages | their own | Independent SemVer. |
`project.marqdo` and a tool's `compatibility.marqdo` are **enforced product `project.marqdo` is an **enforced product range**; a tool declares its exact
ranges**. Prerelease cores require a prerelease range such as current protocol requirements in `requires`. Prerelease cores require a prerelease range such as
`>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match the RC. `>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match the RC.
## Candidate platform scope ## Candidate platform scope
@@ -36,13 +35,13 @@ ranges**. Prerelease cores require a prerelease range such as
Strict is Linux-only and probe-gated. Plugin/provider worker transports are not Strict is Linux-only and probe-gated. Plugin/provider worker transports are not
OS sandboxes. `pure`/`project` are execution modes, not security boundaries. OS sandboxes. `pure`/`project` are execution modes, not security boundaries.
Execution Events v1 is a live observation protocol: it is not a capability Observation v1 is a live observation protocol: it is not a capability grant,
grant, values are off by default, and `--mode strict` currently refuses values are off by default, and `--mode strict` refuses `--output jsonl` and
`--output jsonl` explicitly (no downgrade). `--observation-file` explicitly (no downgrade).
## Language compatibility ## Language compatibility
`3.0.0-rc.3` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source `3.0.0-rc.4` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source
(Strong-execute / Emph-return / ordered-list branch / bullet-list loop / (Strong-execute / Emph-return / ordered-list branch / bullet-list loop /
block-quote call / first code-span signature) is **not executable**; there is no block-quote call / first code-span signature) is **not executable**; there is no
`--legacy`, syntax switch or downgrade path. Migration is a rewrite task `--legacy`, syntax switch or downgrade path. Migration is a rewrite task
+5 -5
View File
@@ -1,15 +1,15 @@
# Quickstart: install and run # Quickstart: install and run
Product: `3.0.0-rc.3` (Linux x86_64 candidate). Install a **release archive**, not Product: `3.0.0-rc.4` (Linux x86_64 candidate). Install a **release archive**, not
a source checkout, when you only consume Marqdo. a source checkout, when you only consume Marqdo.
## 1. Install the archive ## 1. Install the archive
```bash ```bash
sha256sum -c marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz.sha256 sha256sum -c marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz.sha256
tar -xzf marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz tar -xzf marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz
cd marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu cd marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu
./marqdo --version # marqdo 3.0.0-rc.3 ./marqdo --version # marqdo 3.0.0-rc.4
./marqdo --help ./marqdo --help
``` ```
+9 -9
View File
@@ -1,4 +1,4 @@
# Marqdo 3.0.0-rc.3 — known limitations # Marqdo 3.0.0-rc.4 — known limitations
This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of
the release record: it defines the platform and feature scope for the release candidate. the release record: it defines the platform and feature scope for the release candidate.
@@ -49,15 +49,15 @@ Even when available:
wire-incompatible kernels. wire-incompatible kernels.
* **CLI tools**: a tool is an ordinary user-authorized executable and does * **CLI tools**: a tool is an ordinary user-authorized executable and does
**not** inherit `pure`/`project`/`strict` guarantees from the documents it **not** inherit `pure`/`project`/`strict` guarantees from the documents it
reads. `MARQDO_BIN`, `MARQDO_TOOL_PROTOCOL`, `MARQDO_PROTOCOL_ANALYSIS` and reads. `MARQDO_BIN` and `MARQDO_API_REVISION` are the only helpers the CLI
`MARQDO_PROTOCOL_TRACE` are the only helpers the CLI injects. injects; version negotiation was removed.
* **Extension selection** (`marqdo.yaml.extensions`, lock v4) is never * **Extension selection** (`marqdo.yaml.extensions`, lock v4) is never
authorization. `--allow-plugin`, `--allow-provider` and `--allow-foreign` authorization. `--allow-plugin`, `--allow-provider` and `--allow-foreign`
are still required. are still required.
## Compatibility and versioning ## Compatibility and versioning
* `3.0.0-rc.3` is a **prerelease**. The changelog lists changes from the beta. * `3.0.0-rc.4` is a **prerelease**. The changelog lists changes from the beta.
* The product version is independent of protocol versions: Analysis, * The product version is independent of protocol versions: Analysis,
Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2 Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2
and lock v4 keep their own identifiers. and lock v4 keep their own identifiers.
@@ -77,19 +77,19 @@ Archives are accompanied by SHA256 checksums and `RELEASE_INFO.json`
integrity only; they are **not** a publisher signature. A digest obtained from integrity only; they are **not** a publisher signature. A digest obtained from
an untrusted Git URL does not make the code trustworthy. an untrusted Git URL does not make the code trustworthy.
## Execution Events v1 ## Observation
* Implemented: live stdout/stderr chunks, lifecycle/terminal events, call * Implemented: live stdout/stderr chunks, lifecycle/terminal events, call
instance ids, branch/loop/effect events, explicit bounded value observation. instance ids, branch/loop/effect events, explicit bounded value observation.
* Not implemented: memory region/budget metadata (OBS-06/P2), raw memory * Not implemented: memory region/budget metadata (OBS-06/P2), raw memory
content, breakpoints/stepping/time travel, and a bidirectional debug content, breakpoints/stepping/time travel, and a bidirectional debug
protocol. Do not infer a debugger from this protocol. protocol. Do not infer a debugger from this protocol.
* `--mode strict` currently rejects `--output jsonl` explicitly; there is no * `--mode strict` rejects `--output jsonl` and `--observation-file` before
silent fallback to `project`. launch; there is no silent fallback to `project`.
* The live lane is tested on Linux x86_64; macOS/Windows are unverified for * The live lane is tested on Linux x86_64; macOS/Windows are unverified for
this option for this candidate. this option for this candidate.
* In-process native plugins are rejected in event mode * In-process native plugins are rejected with an active machine destination
(`ext.event_stream_unsupported_native_plugin`) because they share the process (`ext.observation_unsupported_native_plugin`) because they share the process
and can write the protocol fd directly; worker plugins remain usable. and can write the protocol fd directly; worker plugins remain usable.
* Observation lowers confidentiality when values are explicitly enabled. Text * Observation lowers confidentiality when values are explicitly enabled. Text
needs a second opt-in; View/agents must not enable these flags by default. needs a second opt-in; View/agents must not enable these flags by default.
+1 -1
View File
@@ -20,7 +20,7 @@ marqdo-view/
examples/ examples/
``` ```
`tool.json` for the `3.0.0-rc.3` candidate: `tool.json` for the `3.0.0-rc.4` candidate:
```json ```json
{ {
@@ -6,8 +6,9 @@
- **Source SHA:** `1d3dca7c1832eb9468e96384d9805a3812a303e4` (post-beta tree; - **Source SHA:** `1d3dca7c1832eb9468e96384d9805a3812a303e4` (post-beta tree;
the tagged beta is `2c7c4f31e7a388d3fcfa717a77067e696ed13854` and does **not** the tagged beta is `2c7c4f31e7a388d3fcfa717a77067e696ed13854` and does **not**
contain this feature). contain this feature).
- **Normative contract:** [`spec/execution-events-v1.md`](../../spec/execution-events-v1.md), - **Normative contract at that time:** `spec/execution-events-v1.md` (retired
schema `spec/schemas/execution-events-v1.schema.json`, decision by [ADR-0068](../adr/0068-single-current-public-contracts.md); the current
contract is [`spec/observation.md`](../../spec/observation.md)), decision
[ADR-0059](../adr/0059-runtime-observability-and-execution-events.md). [ADR-0059](../adr/0059-runtime-observability-and-execution-events.md).
This file records commands actually executed on Linux x86_64 with Rust This file records commands actually executed on Linux x86_64 with Rust
+102
View File
@@ -0,0 +1,102 @@
# RC 3.0.0-rc.3 release evidence — 1e2a045cc78bf40972181abb44e7117c56cf4401
- **Date:** 2026-11-24
- **Product:** `3.0.0-rc.3` (prerelease; not stable, not LTS)
- **Source SHA:** `1e2a045cc78bf40972181abb44e7117c56cf4401` (tag `v3.0.0-rc.3`)
- **Platform:** Linux x86_64, glibc 2.39 baseline; macOS/Windows UNSUPPORTED for
this candidate
- **Release:** https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3
- **Gate manifest:** [`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
(`RC_RELEASE_CANDIDATE`, every gate bound to the SHA above)
- **Verification bundle:**
https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.3/rc3-verification.tar.gz
Local release archive: `marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz`,
sha256 `43796a4834f2a5a887eee1b2d2193076887ac09cbdb45ca4465b34755ca8cc90` (published asset). The same-SHA CI build lane also builds,
smokes and runs the frozen extension suite against its own archive
(sha256 `35268ab72a316d51f54733ba2f81f88f9c5c4d5025aa4901498388dc8d127381`);
the CI log records that smoke, the 7/7 conformance categories and the frozen
CLI/provider-worker hashes for that build.
## Gates executed on this SHA
| Gate | State | Evidence |
|---|---|---|
| Linux CI — contract lane (real CLI + independent Python consumers, one-run stream/snapshot assertion, stale-Analysis rejection) | PASS | [pipeline #80](https://ci.cflmy.cn/repos/1/pipeline/80) |
| Linux CI — test lane (fmt, clippy, 607 workspace tests, docs/architecture gates, tools/ci unittests, Windows cross-target compile) | PASS | pipeline #80 |
| Linux CI — minimum Rust 1.89 check | PASS | pipeline #80 |
| Linux CI — build lane (archive, from-archive smoke, frozen extensions 7/7) | PASS | pipeline #80, `ci-80-build.log` |
| Frozen external conformance against the published archive | PASS (7/7, fixtures `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`) | `extension-manifest.json` |
| Archive-only smoke (stdlib digests, consumers, tools, workers, strict refusal, missing-stdlib fail-closed) | PASS | `release-smoke.log` |
| Clean install: archive-only container, ubuntu 24.04, non-root, no network, no Cargo | PASS | `cold-install.log` |
| Version compatibility (locked Rust minimum, CLI/product identity, prerelease ranges, archive stdlib) | PASS | pipeline #80 test lane + archive smoke |
| Strict L1 in a disposable VM as non-root `marqdo` (uid 1000) | PASS | `strict-evidence.json`, `strict-lane.log` |
| Published archive verified in that same VM (`--version`, `SOURCE_SHA`, strict `run`/`call`) | PASS | `strict-lane.log` |
| G4 performance, three paired shared-node runs | WARN (maintainer-approved for this RC) | `perf-81..83-*.json`, `rss-investigation.json` |
| Windows / macOS | UNSUPPORTED | Linux-only RC scope |
### Strict evidence details
Runner: disposable Ubuntu 26.04 cloud-image VM under QEMU/TCG, booted from the
dated image with sha256 `7b90593f5532b49b7e3fe3d2743f0d1f0d822e5b07cebcd8e00c0df8069ecab9`
(the same pinned image recorded by the rc.1/rc.2 evidence). The lane ran as
user `marqdo` (uid 1000, `root: false`) with bubblewrap 0.11.1: the seven
adversarial isolation tests, the strict CLI contract, strict resource refusal,
inert `@knowledge` and the forged-marker rejection all passed
(`G-C security lane: PASS`). The evidence records `tested_sha_verified: true`
(from `git rev-parse`), the kernel (`7.0.0-43-generic`), cgroup v2 and the
toolchain used by the lane (`rustc 1.100.0`). The published archive was then
unpacked inside the same guest, its checksum and `SOURCE_SHA` verified,
`inspect --platform` reported strict `available`, and strict
`run examples/hello.mq.md` plus
`call examples/factorial.mq.md 数学.阶乘 --arg n=5` produced the expected
output.
### G4 performance and the shared-node exception
Three paired runs compare `v3.0.0-beta.1` with this candidate on Woodpecker
agent 1 (shared node: Intel i7-12700H, kernel 7.0.0-31-generic, `powersave`
governor, logical CPU 0 pinned, five warmups and twenty samples per workload,
nine workloads). Every workload is correctness-verified in every run.
| Paired run | p50 delta range | Threshold breaches (>= +15% p50) |
|---|---|---|
| [#81](https://ci.cflmy.cn/repos/1/pipeline/81) | -28.45% … +1.52% | none |
| [#82](https://ci.cflmy.cn/repos/1/pipeline/82) | -28.02% … +4.10% | none |
| [#83](https://ci.cflmy.cn/repos/1/pipeline/83) | -23.00% … +1.23% | none |
The timed command is now the plain execution path while correctness is verified
against the current Observation snapshot, so an opt-in observability document
is not billed as a regression. The first candidate build compared
`--output json` against the beta summary and produced a spurious
+240%…+375% p50 delta; that comparison was rejected and the sampler fixed
before the frozen SHA.
RSS deltas computed across the two *different* sampler versions are an artefact
of `ru_maxrss` inheriting the sampler parent's pages; the baseline report is
produced by the beta-tagged sampler. A same-parent `/usr/bin/time` cross-check
of the archived binaries (rc.3 vs rc.2, eight comparable workloads) shows RSS
deltas between -4.69% and +13.27%, below the +20% threshold
(`rss-investigation.json`; `stdlib-print-demo` is excluded because the rc.2
checkout does not load the candidate stdlib in that layout).
**Maintainer approval:** the shared-node G4 `WARN` is approved for
`v3.0.0-rc.3` only (2026-11-24). Shared-node reports stay `SMOKE`; they are
never promoted to a dedicated-node claim, and a fixed node is planned for the
next cycle.
## Behaviour changes since rc.2 (review closure)
A code review of the first candidate build found and closed: a strict run
emitting a partial JSONL stream for a destination it refuses; a stale Analysis
artifact surviving a load failure; `fs.*` effects collapsing to
`resource.request`; plugin frame error codes flattened; event/snapshot `level`
enums disagreeing; snapshots embedding absolute host paths; option errors
using the wrong phase; and a G4 workload catalogue that still passed the
retired `--json` flag. Each has a regression test and is recorded in
[STATUS.md](../STATUS.md) section 0.9.1.
## What this evidence does not claim
Stable `3.0.0`, LTS, Windows/macOS support, strict L2, dedicated-node
performance, or a publisher signature. Checksums are integrity only.
@@ -0,0 +1,121 @@
# RC 3.0.0-rc.4 — closed public Analysis boundary (issue #10)
- **Date:** 2026-11-25
- **Product:** `3.0.0-rc.4` (prerelease candidate; not stable, not LTS)
- **Base:** `e6066e6ba91981b7d2bc55191b7eb54387ee34d3`
- **Candidate source SHA:** `e0645f376b03e31e342a6d3fb749a335f0840d1b`
- **Platform:** local Linux x86_64 development container; Windows/macOS remain
UNSUPPORTED for this candidate
- **Policy:** [ADR-0069](../adr/0069-public-analysis-boundary.md),
[ADR-0068](../adr/0068-single-current-public-contracts.md)
- **Contract:** `spec/analysis.md`, `spec/schemas/analysis.schema.json`
- **Gate manifest:** [`ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json`](ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json)
(`DO_NOT_RELEASE`: strict VM UNVERIFIED and no approved G4 node)
This document records commands actually executed on the candidate tree. The
raw command log is
[`2026-11-25-rc.4-local-gate.log`](2026-11-25-rc.4-local-gate.log). It is local
evidence, not a same-SHA CI, archive-only or strict-VM release gate. A release
decision must cite the gate manifest for the tagged SHA and must not promote
these numbers to a platform claim.
## Implemented boundary
`check ENTRY --emit PATH` now projects the same prepared facts consumed by
`check`, `inspect`, `run` and `call`:
- exact UTF-8 `modules[].source` and `source_digest`;
- the canonical Markdown AST (`document`) shared with `inspect --ast`;
- one heading index with structured path, parent, mode, mode origin and source
unit, heading span and complete section span (root covers the whole source);
- anchors, functions, imports, calls with target kind/owner/reason, resources
with AST-payload digest validation and the explicit diagnostics;
- `project.entry_module_id`, captured `manifest_digest`/`lock_digest`, stdlib
and static extension identities;
- one `document_refs` resolver used by Analysis, `check --refs` and
`inspect --refs`, with `resolved`/`not_loaded`/`missing`/`ambiguous`/
`external`/`outside_scope`/`invalid` states.
The retired duplicate resolver and the post-preparation lock re-read are gone.
`--emit` writes owner-only exclusive bytes through a temporary file and rename
and refuses inputs, directories, symlinks and hard links to inputs.
## Commands executed
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS: 633 passed, 0 failed, 2 ignored
cargo test -p marqdo-cli --test analysis_boundary PASS: 10 passed
cargo test -p marqdo-cli --test analysis_observation PASS: 11 passed
cargo test -p marqdo-cli --test architecture_boundaries PASS
cargo test -p marqdo-cli --test docs_consistency PASS
cargo test -p marqdo-cli --test integration_cli PASS: 23 passed
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker PASS
python3 tests/consumers/analysis_consumer.py <artifact> PASS
python3 tests/consumers/validate_protocols.py <analysis> <observation> <tool> PASS
python3 tests/consumers/view_consumer.py <artifact> PASS
python3 tests/consumers/lint_consumer.py <artifact> PASS
python3 tests/consumers/knowledge_consumer.py <artifact...> PASS
```
The independent semantic consumer and mutation gate were exercised with a
project containing an import, a cross-module reference, a formula, a code
fence and a static call. The gate rejects missing current required fields,
tampered source/digests/spans, duplicate module ids, parent cycles, wrong mode
sources, missing call targets, missing reference units and injected successful
error diagnostics.
## Performance (local smoke, not G4)
Fixture: 101 modules, 82,094 source bytes, 903 units, 100 cross-module
references; release builds of rc.3 (baseline archive binary) and the rc.4
candidate, five warmups and twenty samples per command, same host and cwd.
| Command | rc.3 p50/p95 (ms) | rc.4 p50/p95 (ms) | p95 ratio | peak RSS ratio |
|---|---|---|---|---|
| `check index.mq.md --json` | 18.28 / 19.09 | 18.47 / 19.07 | 0.999 | 1.001 |
| `check index.mq.md --emit out.json` | 36.49 / 42.65 | 48.66 / 51.59 | 1.210 | 1.186 |
| `check index.mq.md --refs --json` | 19.09 / 19.66 | 21.99 / 22.51 | 1.145 | 1.093 |
The rc.4 artifact is 2,739,156 bytes (rc.3: 899,146) because it now carries the
exact source and AST. The emit p95 and peak-RSS ratios are below the issue's
2.5x budget; the no-emit p95 ratio is below 1.15. These are development-container
numbers and must not be cited as the dedicated-node G4 result.
## Executed archive and CI gates
- **Same-SHA CI** ([pipeline #89](https://ci.cflmy.cn/repos/1/pipeline/89),
commit `e0645f3`): `contract`, `test`, `minimum-rust` and `build` all PASS.
The follow-up CI/tooling commit `b1fc211` is also fully green
([pipeline #91](https://ci.cflmy.cn/repos/1/pipeline/91)); it changes only the
CI stale-artifact helper and the pipeline step, not the shipped binaries.
The build lane packaged `marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`
(sha256 `10f98078ff3c747c751cedfa07a767c967e17b9dffb183f93db2743c34fa6453`),
ran the archive-only smoke and the frozen extension suite 7/7 PASS
(CLI `119b4d7d0431d8e958253add4b67a6ed826678b5254583d5320136b1b9a6e93b`).
- **Local same-SHA archive** (`8cabddc9f7860ac9f9138dba75794d3026a47d3cfecc460742ac2a4c2a017516`):
`smoke.py` PASS (see
[`2026-11-25-rc.4-release-smoke.log`](2026-11-25-rc.4-release-smoke.log)) and
the archive-only Ubuntu 24.04 cold-install container PASS (see
[`2026-11-25-rc.4-cold-install.log`](2026-11-25-rc.4-cold-install.log)).
- **Frozen external conformance** from a clean worktree at the candidate SHA:
7/7 PASS, manifest
[`2026-11-25-rc.4-extension-manifest.json`](2026-11-25-rc.4-extension-manifest.json)
and log
[`2026-11-25-rc.4-extension-conformance.log`](2026-11-25-rc.4-extension-conformance.log).
## Release decision
`DO_NOT_RELEASE` for rc.4. The code/contract/CI/archive/conformance gates pass,
but the RC profile still requires a same-SHA strict-field PASS on a disposable
VM (this development container cannot create namespaces) and an approved
dedicated/shared-node G4 result. Neither is recorded for this SHA, so no tag,
archive publication or release claim is made.
## Not claimed
- No disposable-VM strict L1 evidence for this SHA.
- No approved dedicated-node G4 measurement (the local comparison above is
smoke evidence only).
- No Windows/macOS support claim.
@@ -0,0 +1,11 @@
你好,Marqdo
checked 2 module(s): ok
checked 1 module(s): ok
6
warning[sem.inferred_signature]: /tmp/marqdo/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/examples/math-library/index.mq.md:5:1: function signature was inferred; declare it with `params(...)`
## @exec 最大公约数
^
warning[sem.inferred_signature]: /tmp/marqdo/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/examples/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
runtime error[kernel.unavailable]: 打印 requires the bundled stdlib print module; install the official CLI bundle
@@ -0,0 +1,43 @@
From https://git.cflmy.cn/cflmy/marqdo-extension-conformance
* branch 015ff8ac15417b7ebbdb31ce2be2dab5362a1eba -> FETCH_HEAD
frozen CLI: /tmp/tmp.4rCUTQwVeO/install/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e
[PASS] plugin_worker: plugin check is static and succeeds
[PASS] plugin_worker: worker plugin executes three exports
[PASS] callable_registry: missing plugin export is symbol.unknown
[PASS] callable_registry: bad plugin args fail statically
[PASS] negative_security: plugin without grant is permission.denied
[PASS] negative_security: tampered plugin artifact fails before main
[PASS] negative_security: check does not require the plugin artifact to exist
[PASS] foreign_kernel: unknown language mocklang executes
[PASS] negative_security: foreign kernel without grant is denied
[PASS] resource_provider_cli: provider v2 reads five bytes through the CLI
[PASS] negative_security: provider without grant is denied
[PASS] negative_security: provider v1 schema is rejected without migration
[PASS] negative_security: provider artifact digest tamper is rejected
[PASS] negative_security: pure and strict modes reject provider flags
[PASS] negative_security: strict mode rejects provider flags
[PASS] tool_analysis_consumer: independent tool consumes the current Analysis
[PASS] tool_analysis_consumer: registered tool command dispatches
[PASS] negative_security: tool install rejects unknown entrypoint traversal
[PASS] tool_analysis_consumer: tool remove unregisters
[PASS] package_pinned_git: pinned Git .mq.md library runs from a separate repo
[PASS] package_pinned_git: consumer runs the pinned dependency
[PASS] package_pinned_git: verified cache still runs after moving the checkout and deleting the source
[PASS] reference_applications: HTTP status, POST and bounded framing
[PASS] reference_applications: URL validation and denial before connect
[PASS] reference_applications: TLS with an explicit local trust root
[PASS] reference_applications: live SSE visibility and caller close
[PASS] reference_applications: socket read timeout and teardown
[PASS] reference_applications: agent tool authority and two-turn provenance
[PASS] negative_security: frozen CLI binary did not change
[PASS] negative_security: frozen provider worker did not change
{
"callable_registry": "PASS",
"plugin_worker": "PASS",
"foreign_kernel": "PASS",
"resource_provider_cli": "PASS",
"package_pinned_git": "PASS",
"tool_analysis_consumer": "PASS",
"negative_security": "PASS"
}
wrote extension evidence: /root/work/marqdo-cli/docs/evidence/2026-11-25-rc.4-extension-manifest.json
@@ -0,0 +1,32 @@
{
"schema": "marqdo.extension-evidence",
"schema_version": 1,
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"cli_binary_sha256": "a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e",
"fixture_repo_sha": "015ff8ac15417b7ebbdb31ce2be2dab5362a1eba",
"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.4rCUTQwVeO/fixtures/tests/run_all.py (cwd=/tmp/tmp.4rCUTQwVeO/fixtures)"
],
"failures": [],
"unverified": [],
"provider_worker_sha256": "2d32fcfa4c6a04cb784dcb77ea4fae76a3f181708d962bb6adf7512b994e64bf",
"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,98 @@
rc.4 final local gate 2026-11-25T03:40:44Z
source_sha: e0645f376b03e31e342a6d3fb749a335f0840d1b
platform: Linux 7.0.0-43-generic x86_64
rustc: rustc 1.100.0 (0ef1bc386 2026-11-09)
$ cargo fmt --all -- --check
PASS
$ cargo clippy --workspace --all-targets -- -D warnings
Compiling proc-macro2 v1.0.107
Checking serde_core v1.0.229
Checking zmij v1.0.23
Checking num-traits v0.2.19
Checking generic-array v0.14.7
Checking libc v0.2.191
Checking rustix v1.1.6
Checking crc32fast v1.5.5
Checking flate2 v1.1.11
Compiling phf_generator v0.14.0
Compiling quote v1.0.47
Compiling phf_codegen v0.14.0
Compiling comrak v1.0.0
Compiling syn v3.0.10
Checking block-buffer v0.10.4
Checking crypto-common v0.1.7
Checking num-integer v0.1.47
Checking digest v0.10.7
Checking sha2 v0.10.9
Checking getrandom v0.4.3
Checking getrandom v0.2.17
Checking ring v0.17.14
Checking tempfile v3.27.0
Checking serde_json v1.0.154
Checking rustls-webpki v0.103.17
Checking rcgen v0.13.2
Checking rustls v0.23.46
Compiling serde_derive v1.0.229
Compiling thiserror-impl v2.0.21
Compiling fearless_simd_macros v0.1.0
Compiling clap_derive v4.6.9
Checking memchr-n v0.1.10
Checking thiserror v2.0.21
Checking marqdo-worker-ipc v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-worker-ipc)
Checking marqdo-provider-worker v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-provider-worker)
Checking clap v4.6.9
Checking serde v1.0.229
Checking marqdo-span v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-span)
Checking num-bigint v0.4.8
Checking serde_yaml v0.9.34+deprecated
Checking marqdo-sandbox v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-sandbox)
Checking marqdo-markdown v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-markdown)
Checking marqdo-package v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-package)
Checking marqdo-value v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-value)
Checking marqdo-expression v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-expression)
Checking num-rational v0.4.2
Checking marqdo-plugin-abi v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-plugin-abi)
Checking marqdo-foreign v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-foreign)
Checking marqdo-ir v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-ir)
Checking marqdo-host v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-host)
Checking marqdo-plugin-sdk v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-plugin-sdk)
Checking marqdo-frontend v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-frontend)
Checking marqdo-runtime v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-runtime)
Checking marqdo-cli v3.0.0-rc.4 (/root/work/marqdo-cli/crates/cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 8.53s
PASS
$ cargo test --workspace --locked
PASS
passed 633, failed 0, ignored 2
$ cargo test -p marqdo-cli --test architecture_boundaries
test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
$ cargo test -p marqdo-cli --test docs_consistency
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
$ cargo test -p marqdo-cli --test analysis_observation
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s
$ cargo test -p marqdo-cli --test observation
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.23s
$ cargo test -p marqdo-cli --test tool_protocol
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.09s
$ cargo test -p marqdo-cli --test callable_resolution
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.28s
$ cargo test -p marqdo-cli --test heading_inheritance
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.07s
$ cargo test -p marqdo-cli --test conformance_ast
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
$ cargo test -p marqdo-cli --test conformance_semantics
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.69s
$ cargo test -p marqdo-cli --test analysis_boundary
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.97s
$ python3 -m unittest discover -s tools/ci -p test_*.py
Ran 43 tests in 0.092s
OK
$ cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
Finished `release` profile [optimized] target(s) in 0.05s
PASS
@@ -0,0 +1,5 @@
smoke: verified stdlib 0.1.0 tree=sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713 aliases=sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb files=42
smoke: archive version 3.0.0-rc.4, source e0645f376b03e31e342a6d3fb749a335f0840d1b
smoke: bundled stdlib missing -> fail-closed OK
smoke: strict unsupported on this host; fail-closed refused: {'reason': 'bubblewrap cannot create the required namespaces: bwrap: No permissions to create a new namespace, likely because the kernel does not allow non-privileged user namespaces. See <https://deb.li/bubblewrap> or <file:///usr/share/doc/bubblewrap/README.Debian.gz>.', 'state': 'unavailable'}
smoke: PASS
@@ -0,0 +1,59 @@
{
"schema": "marqdo.release-gates.v1",
"profile": "rc",
"target_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"recorded_utc": "2026-11-24T15:56:23Z",
"gates": {
"linux": {
"state": "PASS",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/80",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"strict_vm": {
"state": "PASS",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.3/rc3-verification.tar.gz",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"extension": {
"state": "PASS",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.3/rc3-verification.tar.gz",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"clean_install": {
"state": "PASS",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.3/rc3-verification.tar.gz",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"version_compat": {
"state": "PASS",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/80",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"windows": {
"state": "UNSUPPORTED",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "linux-only-rc-scope-release-notes",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"macos": {
"state": "UNSUPPORTED",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "linux-only-rc-scope-release-notes",
"recorded_utc": "2026-11-24T15:56:23Z"
},
"performance": {
"state": "WARN",
"tested_sha": "1e2a045cc78bf40972181abb44e7117c56cf4401",
"run_url": "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.3/rc3-verification.tar.gz",
"rc_shared_node_approval": "Maintainer approved the shared-node G4 WARN for v3.0.0-rc.3 on 2026-11-24 (RC only; a dedicated fixed node is planned for the next cycle); https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3#performance",
"recorded_utc": "2026-11-24T15:56:23Z"
}
},
"release_decision": "RC_RELEASE_CANDIDATE",
"reasons": []
}
@@ -0,0 +1,61 @@
{
"schema": "marqdo.release-gates.v1",
"profile": "rc",
"target_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"recorded_utc": "2026-11-25T03:46:11Z",
"gates": {
"linux": {
"state": "PASS",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/89",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"extension": {
"state": "PASS",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "docs/evidence/2026-11-25-rc.4-extension-manifest.json",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"clean_install": {
"state": "PASS",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "docs/evidence/2026-11-25-rc.4-cold-install.log",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"version_compat": {
"state": "PASS",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/89",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"windows": {
"state": "UNSUPPORTED",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "COMPATIBILITY.md",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"macos": {
"state": "UNSUPPORTED",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "COMPATIBILITY.md",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"performance": {
"state": "WARN",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "docs/evidence/2026-11-25-rc.4-analysis-boundary.md",
"recorded_utc": "2026-11-25T03:46:11Z"
},
"strict_vm": {
"state": "UNVERIFIED",
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"run_url": "docs/security-vm.md",
"recorded_utc": "2026-11-25T03:46:11Z"
}
},
"release_decision": "DO_NOT_RELEASE",
"reasons": [
"strict_vm: UNVERIFIED is not accepted; expected PASS",
"performance: WARN is not accepted; expected PASS"
]
}
+9
View File
@@ -4,6 +4,15 @@ Status: the sampler and correctness corpus are implemented; **no release
performance baseline exists yet**. Do not cite a development-container or performance baseline exists yet**. Do not cite a development-container or
TCG/QEMU number as a release gate. TCG/QEMU number as a release gate.
## Release-class policy
- **RC candidates** may use a maintainer-approved shared node. The environment,
load, limits, paired baseline/candidate comparison and approval are recorded
in the release notes; the result remains `WARN`, never a dedicated-node PASS.
- **Stable/LTS** releases require a dedicated fixed node and the full paired-run
protocol. The shared-node exception is RC-only and must not be reused for
LTS evidence.
## Three separate measurements ## Three separate measurements
| Class | Goal | Host | | Class | Goal | Host |
+13 -11
View File
@@ -75,17 +75,19 @@ Use the frozen-SHA build and archive checks above. Additionally:
- Strict L1 requires a same-SHA PASS on a disposable VM as a non-root user. - Strict L1 requires a same-SHA PASS on a disposable VM as a non-root user.
Record the strict evidence and verify the archived binary on that guest. Record the strict evidence and verify the archived binary on that guest.
- Measure the packaged CLI on a dedicated fixed node with 5 warmups and - Measure the packaged CLI with 5 warmups and 20 samples or more for each of
20 samples or more for each of the nine workloads. Compare against a the nine workloads, or for the changed boundary's representative fixture when
correctness-verified baseline on the same node, CPU affinity, governor, the gate is scoped by an accepted ADR. Compare against a correctness-verified
kernel and toolchain. Record investigation and resolution for any p50 baseline on the same node, CPU affinity, governor, kernel and toolchain.
increase of at least 15% or median peak RSS increase of at least 20%. Record investigation and resolution for any p50 increase of at least 15% or
A dedicated node is the default. For a prerelease approved by the median peak RSS increase of at least 20%.
maintainer to use a shared node, take at least three paired beta/RC runs **RC candidates may use a shared node.** The maintainer approves the shared
under the same measured conditions and keep all reports. Verify all nine node for that named RC, the environment/load/limits and the comparison are
workloads and investigate threshold breaches or unstable samples before recorded in the release notes, and the result stays a `WARN`; it is never
accepting a `WARN`. Record the approval, runner environment and limits in promoted to a dedicated-node PASS. A final stable/LTS release requires a
the release notes. This exception applies to the named RC only. dedicated fixed node with the full paired-run protocol; the shared-node
exception does not carry over to it. Verify correctness before timing and do
not accept results from an unmeasured or unexplained environment.
- Version compatibility covers the locked Rust minimum, CLI and Analysis - Version compatibility covers the locked Rust minimum, CLI and Analysis
product identity, Tool/project prerelease ranges, and beta migration. product identity, Tool/project prerelease ranges, and beta migration.
- Use Ubuntu 24.04 (glibc 2.39) for the independent archive-only runtime - Use Ubuntu 24.04 (glibc 2.39) for the independent archive-only runtime
+2 -2
View File
@@ -1,6 +1,6 @@
# Unknown-name CLI tool example # Unknown-name CLI tool example
This directory is a complete Tool Protocol v1 package. Nothing named This directory is a complete CLI Tool (revision 1) package. Nothing named
`benchmark` exists in the Marqdo CLI source; after installation the unknown `benchmark` exists in the Marqdo CLI source; after installation the unknown
top-level command is dispatched by the registry. top-level command is dispatched by the registry.
@@ -13,7 +13,7 @@ marqdo tool remove benchmark
The executable receives the remaining arguments verbatim, inherits stdio/cwd, The executable receives the remaining arguments verbatim, inherits stdio/cwd,
and its exit code is propagated. `MARQDO_API_REVISION=1` and `MARQDO_BIN` are and its exit code is propagated. `MARQDO_API_REVISION=1` and `MARQDO_BIN` are
provided for tools that need `check --emit`/`run --trace-file`. provided for tools that need `check --emit`/`run --output json`.
A Tool is a user-run native process. It is **not** a C ABI plugin, a foreign A Tool is a user-run native process. It is **not** a C ABI plugin, a foreign
kernel, or a program inside the `.mq.md` sandbox. kernel, or a program inside the `.mq.md` sandbox.
+398 -125
View File
@@ -1,20 +1,43 @@
# Marqdo Analysis # Marqdo Analysis
Current public contract for `marqdo check --emit PATH`. Every project emits Current public contract for `marqdo check --emit PATH`. Every project emits
`marqdo.analysis` with `schema_version: 3`. `marqdo.analysis` with `schema_version: 3`. The contract is implemented by
[ADR-0069](../docs/adr/0069-public-analysis-boundary.md); it replaces the
program-only Analysis shape in place. Retired artifacts with the same revision
are rejected because every field below is required.
## 1. Invariants ## 1. Invariants
`check --emit`: `check --emit`:
* never executes the document, loads a plugin shared library, starts a foreign * never executes the document, opens a plugin shared library, starts a worker
kernel or imports a module implicitly; or foreign kernel, accesses the network, or imports a module implicitly;
* validates the loaded program first; on a compile error it writes no artifact * validates the prepared program first; on a compile or load error it writes
and removes an existing artifact at the target path; no artifact and only removes a previous artifact at the caller-specified
* writes atomically through a temporary file and rename; output path when that path is a safe output (see §8);
* contains no absolute machine paths, timestamps, PIDs or other environmental * writes through an owner-only exclusive temporary file in the target directory
data, so the same logical project emits byte-identical Analysis from and renames it into place atomically;
different checkout directories and is safe to compare across machines. * contains no absolute machine paths, timestamps, PIDs, random ids or other
environmental data, so the same logical project emits byte-identical
Analysis from different checkout directories;
* exposes only facts that one of `check`, `inspect`, `run` or `call` already
consumes through `project_prepare::prepare`. There is no second parser,
second call-binding pass or tool-specific branching.
`source` is present because it is the one artifact that lets a reader slice
every span without knowing package-cache or stdlib layouts. It contains only
modules that the loader already read statically; no extra file, asset or
binary is read. Treat an emitted Analysis as sensitive local source data:
`--help` and this specification say so, and the CLI neither uploads nor logs
it.
`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written
by `check --emit` (pretty JSON), represented in Observation as
`sha256:<64 hex>`. Diagnostics and every static option that changes the
projection are part of those bytes. `run`/`call` bind to the same projection
with the same static options; a `--refs` invocation adds diagnostics and
therefore has a different digest, and must not be substituted for the ordinary
artifact.
## 2. Top-level shape ## 2. Top-level shape
@@ -24,59 +47,82 @@ Current public contract for `marqdo check --emit PATH`. Every project emits
"schema_version": 3, "schema_version": 3,
"producer": { "producer": {
"name": "marqdo", "name": "marqdo",
"version": "<crate version>", "version": "<product version>",
"markdown_profile": "marqdo.md.v1" "markdown_profile": "marqdo.md.v1"
}, },
"project": { "project": {
"root_id": "root:quantum@0.1.0", "root_id": "root:demo@0.1.0",
"identity_kind": "manifest", "identity_kind": "manifest",
"entry_module_id": "root:demo@0.1.0::index.mq.md",
"lock_digest": "sha256:<64 hex>", "lock_digest": "sha256:<64 hex>",
"stdlib": { "manifest_digest": "sha256:<64 hex>",
"version": "0.1.0", "stdlib": null,
"digest": "sha256:<64 hex>", "extensions": []
"instance_id": "std:marqdo-stdlib@0.1.0#<64 hex>"
}
}, },
"modules": [], "modules": [],
"diagnostics": [] "diagnostics": []
} }
``` ```
`project.identity_kind` is: ### 2.1 Project identity and snapshot
| Kind | `root_id` | Meaning | | Field | Meaning |
|---|---|---| |---|---|
| `manifest` | `root:<project.name>@<project.version>` | Logical identity of a project with `marqdo.yaml`. Moving the checkout or a Git clone does not change it. | | `root_id` | `root:<name>@<version>` for a project with `marqdo.yaml`; `sha256:<64 hex>` content snapshot without one. A snapshot is not a persistent project identity. |
| `workspace_snapshot` | `sha256:<64 hex>` | No manifest. Digest of sorted `(module_id, source_digest)` pairs; identifies content, not a persistent project. | | `identity_kind` | `manifest` or `workspace_snapshot`. |
| `entry_module_id` | The canonical id of the module loaded from `ENTRY`; it must occur exactly once in `modules`. A second entry of the same project produces its own Analysis and is never merged by basename. |
| `lock_digest` | `sha256:` + SHA-256 of the exact `marqdo.lock` bytes captured during preparation; `""` only when no lock file exists. A read failure is a load error, never an empty digest. |
| `manifest_digest` | `sha256:` + SHA-256 of the exact `marqdo.yaml` bytes captured during preparation; `""` when there is no manifest. This distinguishes equal name/version projects with different static configuration. |
| `stdlib` | `null`, or the verified bundle `{version, digest, instance_id}` actually used by this load. |
| `extensions` | Static extension identities that participated in preparation, sorted by `(kind, name, logical_owner, manifest_digest)`. See §2.2. |
`project.lock_digest` is the SHA-256 of the exact `marqdo.lock` bytes prefixed Manifest and lock bytes are read once while loading. Analysis never re-reads
with `sha256:`, or `""` when there is no lock. It is not a logical identity. them; a concurrent edit cannot make the artifact claim bytes other than the
snapshot that determined the program.
`project.stdlib` records the verified bundled standard library identity used by ### 2.2 Extension identity
this load: declared version, content digest and package instance id. It is
`null` when no bundle was available. A digest mismatch is a hard load error, so
an Analysis artifact can only name a bundle whose bytes matched the manifest.
`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written
by `check --emit` (pretty JSON). This is what Observation binds to
`source.analysis_digest`; an independent consumer can verify it by hashing the
file. Diagnostics and any configuration options that change the projection are
part of that digest.
Module ids are `<package instance>::<package-relative path>` (ADR-0008) and are
scoped by `project.root_id`. A module id alone is not a cross-project symbol.
## 3. Modules
The module object is unchanged from Analysis v1 except for `resources`:
```json ```json
{ {
"id": "root:res@0.1.0::index.mq.md", "kind": "plugin",
"package_instance_id": "root:res@0.1.0", "name": "example.echo",
"version": "0.1.0",
"logical_owner": "root:demo@0.1.0",
"source": "./plugin",
"manifest_digest": "sha256:<64 hex>",
"artifact_digest": "sha256:<64 hex>",
"selected_target": "x86_64-unknown-linux-gnu"
}
```
`kind` is `plugin`, `kernel` or `provider`. Declared extensions use the lock v4
identity that was validated during preparation; explicit `--plugin` descriptors
are included with their verified manifest identity, `source: "--plugin"` and
`logical_owner: "cli"`. No secret, physical path, handle, signature or grant is
projected. Two exports of the same package are one identity; equal export names
in different packages remain distinct.
### 2.3 Module paths and ordering
Modules are sorted by canonical `id`. `id` is
`<package instance>::<package-relative path>` and is scoped by
`project.root_id`. `relative_path` must be non-empty UTF-8 with `/`
separators, contain no empty, `.` or `..` segment and no OS absolute, drive or
UNC prefix. Valid names such as `foo..bar.mq.md` are accepted; a file name that
cannot be represented losslessly is rejected rather than silently rewritten.
## 3. Module shape
```json
{
"id": "root:demo@0.1.0::index.mq.md",
"package_instance_id": "root:demo@0.1.0",
"relative_path": "index.mq.md", "relative_path": "index.mq.md",
"source_digest": "<64 hex of exact source bytes>", "source_digest": "<64 hex SHA-256 of source bytes>",
"source": "<exact UTF-8 source text>",
"document": {"kind": "document", "span": {"start": 0, "end": 0}, "children": []},
"units": [], "units": [],
"anchors": [],
"functions": [], "functions": [],
"imports": [], "imports": [],
"references": [], "references": [],
@@ -85,119 +131,346 @@ The module object is unchanged from Analysis v1 except for `resources`:
} }
``` ```
Modules are sorted by `id`; functions, units and calls keep document order and `source_digest` is the lowercase hex SHA-256 of the decoded UTF-8 bytes of
the v1 semantic node shapes (`assign`, `expression`, `branch`, `loop`, `source`. BOM, CRLF, missing trailing newline and NUL bytes are preserved in
`return`; literals, variables, lists, records, unary/binary, member, index, `source`; JSON escaping changes the encoding only, not the decoded bytes.
call). The v1 `call_site` node was retired with RFC-LANG-0002: calls are Every `span` in the module indexes `source`.
`call` expressions inside an `assign`/`expression`/`return`/condition body, not
a separate statement. `imports`, `references` and `calls` remain static facts; a
Markdown reference is not a call. `effects` remains `["unknown"]` (a
conservative summary, not a purity proof).
`calls[]` is projected from the single prepared call binding ### 3.1 Document AST
(`spec/callable-resolution.md` §6): `state` remains
`function`/`builtin`/`plugin`/`unresolved`, and official stdlib aliases such as
`打印` are reported as `function` targets because that is the implementation
that runs. The private `CallBindingTable` is not serialized; Analysis's
schema and version are unchanged.
An `assign` node keeps the v1 string `target` for a local rebinding. Addressable `document` is the public shape already defined by
memory adds one additive target form (ADR-0022); consumers that only understand `spec/markdown-profile.md` §5, emitted by an explicit projector and shared with
local assignments can ignore an object target: `inspect --ast`. Every node has `kind`, `span` and `children` (leaves use `[]`).
Leaves carry `literal` where the profile defines one. Attribute rules:
```json | Kind | Attributes |
{"kind":"assign", |---|---|
"target":{"kind":"index", | `document`, `block_quote`, `paragraph`, `strong`, `emph`, `strikethrough`, `table_cell` | none |
"base":{"kind":"variable","name":"内存","span":{"start":23,"end":26}}, | `front_matter` | `literal` |
"index":{"kind":"literal","type":"int","value":"0","span":{"start":27,"end":28}}, | `list` | `ordered`, `start` (`null` for bullet), `tight` |
"span":{"start":23,"end":29}}, | `item` | `task` (`null`, `true`, `false`) |
"value":{"kind":"literal","type":"int","value":"7","span":{"start":32,"end":33}}, | `heading` | `level` (1-6), `setext` |
"span":{"start":18,"end":35}} | `text`, `math_block`, `html_block`, `html_inline` | `literal` |
``` | `code` | `ticks` (delimiter length), `literal` |
| `code_block` | `fenced`, `info`, `literal` |
| `math` | `display`, `literal` |
| `link`, `image` | `url`, `title` |
| `table` | `alignments` (`none`, `left`, `center`, `right`) |
| `table_row` | `header` |
| `thematic_break`, `soft_break`, `line_break` | none |
| `other` | `tag`, optional `literal`, children preserved |
`target.kind` is `"index"`; `base` and `index` use the same expression node The root `document` span covers the whole source including a BOM. All node
shapes as every other expression. Analysis is static: it records the place but spans are half-open UTF-8 byte offsets, `start <= end <= source.len()` and on
never allocates a region or executes the write. UTF-8 boundaries. Container spans follow the parser source map, including its
documented empty/synthetic exceptions; semantic validation checks the
invariants that hold and does not pretend `literal` is byte-identical to the
span (entities, escapes and code whitespace may be normalised). HTML, links and
code blocks are inert data.
## 4. Resources ### 3.2 Units and heading scopes
`resources` is an array, not a count. The projection includes exactly the `units` is in document order with the root first:
resource kinds represented by `marqdo-ir::Resource`; it does not invent table,
HTML or link resources.
```json ```json
{ {
"id": "root:res@0.1.0::index.mq.md#resource:formula-1", "id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"module_id": "root:res@0.1.0::index.mq.md", "path": ["力学", "计算力"],
"unit_id": "root:res@0.1.0::index.mq.md#calc", "parent_id": "root:demo@0.1.0::index.mq.md#力学",
"kind": "formula", "kind": "function",
"span": {"start": 30, "end": 44}, "name": "计算力",
"content_digest": "<64 hex>", "level": 2,
"language": null, "mode": "exec",
"display": true "mode_origin": "explicit",
"mode_source_unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"heading_span": {"start": 10, "end": 30},
"span": {"start": 10, "end": 90},
"function": "root:demo@0.1.0::index.mq.md::力学.计算力"
} }
``` ```
| Field | Semantics | | Field | Requirement |
|---|---| |---|---|
| `id` | `<module_id>#resource:<kind>-<n>`; `n` is the 1-based ordinal among resources of that kind in the module, in document order | | `id` | Canonical unit id. Display escapes `/`, `#` and `%` inside each path segment as `%2F`, `%23`, `%25`; `path` is the authoritative structure and consumers must not split `id`. |
| `module_id` | redundant with the enclosing module, present for flattened consumers | | `path` | Canonical NFC/whitespace-normalised heading path, including this heading; `[]` for the root. |
| `unit_id` | innermost owning unit | | `parent_id` | Root: `null`. Non-root: nearest real ancestor unit, `null` only for the root; not the Markdown DOM parent. |
| `kind` | `formula` or `code`; future kinds are additive and unknown kinds must be ignored | | `kind` | `root`, `namespace` (H1), `function` (Exec H2), `knowledge` (Knowledge H2), `section` (H3-H6). |
| `span` | Markdown node byte span, including math delimiters/fence, relative to that module's source | | `name` | Normalised heading name; `""` for the root. |
| `content_digest` | SHA-256 of the payload: formula LaTeX bytes without delimiters; exact code fence source bytes | | `level` | 0 for the root, otherwise 1-6. |
| `language` | code fence info string (may be `""`); `null` for formulas | | `mode` | Effective `exec` or `knowledge`; the root is `knowledge`. |
| `display` | formula only: block vs inline math | | `mode_origin` | Root: `default`. Non-root: `explicit` when the ATX heading declares `@exec`/`@knowledge`; otherwise `inherited`. Setext headings never declare. |
| `mode_source_unit_id` | The unit that provides the effective mode: the root, or the nearest explicit ancestor (possibly the unit itself). Must be the unit or one of its ancestors. |
| `heading_span` | Root: `null`. Otherwise the original heading AST span. |
| `span` | Root: whole source including BOM. Otherwise the complete section range: from the heading start to the next heading of the same or higher level, or EOF; it includes all child headings and excludes the next sibling. |
| `function` | Canonical owning `FunctionId` for an Exec section; `null` for Knowledge/namespace/root. Only an Exec H2 creates a callable; nested sections point at it. |
Resource ids are Analysis-local ordinals, not persistent symbols and not `ref` Mode declarations are only the ATX first-Text-child `@exec`/`@knowledge`
anchors. Content identity is `(module_id, content_digest)`; location identity is tokens; any other `@word` is `sem.invalid_mode_marker`. Mode inheritance pops
`(module_id, span)`. Inserting an earlier resource renumbers later ordinals, but same-or-higher-level ancestors first, so a sibling never supplies a mode.
the content digest and span still let a consumer detect the change. Payloads Headings inside lists, block quotes or fences do not create language units.
are not copied into Analysis: consumers read the module source (via
`relative_path`) and slice `span` or verify `content_digest`.
## 5. Diagnostics ### 3.3 Anchors
Diagnostics no longer embed absolute physical paths: ```json
{"anchor": "计算力", "unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力"}
```
`anchors` projects the single `UnitIndex.anchors` map, sorted by `anchor`.
Anchors are navigation names, not identities; slug collisions use the current
numbered algorithm. A display title, semantic name, anchor and unit id are
different concepts; the display title comes from the AST.
### 3.4 Functions
```json ```json
{ {
"module": "root:res@0.1.0::index.mq.md", "id": "root:demo@0.1.0::index.mq.md::力学.计算力",
"unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"local_name": "计算力",
"namespace": "力学",
"span": {"start": 10, "end": 90},
"heading_span": {"start": 10, "end": 30},
"signature": {
"kind": "explicit",
"params": [{"name": "n", "required": true, "type": "Int", "default": null,
"span": {"start": 31, "end": 41}}]
},
"effects": ["unknown"],
"body": []
}
```
Every function corresponds one-to-one to an Exec H2 and to its `function` unit.
`namespace` is `null` outside an H1 namespace. Parameters keep declaration order
for explicit signatures and the canonical order for inferred ones; spans are
projected as written. `effects` is the honest conservative default
`["unknown"]`, never a purity proof.
`body` supports every current public statement: `assign` (string local target or
`{"kind":"index",...}`), `expression`, `branch` (ordered arms), `loop`,
`return`, `break` and `continue`, with the expression variants `literal`,
`variable`, `list`, `record`, `unary`, `binary`, `member`, `index`, `call`.
Arbitrary-precision integers are decimal strings; a float is a finite JSON
number. An unknown required kind is rejected by schema/semantic validation, not
silently dropped.
### 3.5 Imports
`imports` keeps `{alias, target, span, resolved}` in document order.
`resolved` is the canonical target module id from the single prepared import
resolution, or `null` for a diagnostic import. Imports are explicit; a link is
never an import.
### 3.6 References
See §5.
### 3.7 Calls
```json
{
"function": "root:demo@0.1.0::index.mq.md::main",
"span": {"start": 40, "end": 52},
"callee": {"kind": "ident", "name": "计算力"},
"state": "function",
"target": "root:demo@0.1.0::index.mq.md::力学.计算力",
"target_kind": "function",
"target_owner": null,
"reason": null
}
```
Calls are projected from the single prepared `CallBindingTable`, one record per
call expression occurrence, in source order. `state`:
| State | `target` | `target_kind` |
|---|---|---|
| `function` | existing canonical `FunctionId` | `function` |
| `builtin` | canonical builtin name | `builtin` |
| `plugin` | full dotted export name | `plugin` |
| `unresolved` | `null` | `null` |
For `plugin`, `target_owner` is
`{"kind":"plugin","package":"<package>","digest":"sha256:<64 hex>"}` from the
static descriptor; no plugin function node is fabricated. `reason` is
`dynamic` for a value call and `unbound` when preparation could not bind a
statically known callee, otherwise `null`. Legal dynamic calls do not
invalidate Analysis; genuine compile errors do.
### 3.8 Resources
`resources` projects exactly the inert `marqdo-ir::Resource` kinds `formula` and
`code`: `id` (module-local ordinal), `module_id`, `unit_id`, `kind`, `span`,
`content_digest`, `language` (`null` for formula), `display` (`true|false` for
formula, `null` for code). The payload lives in `source`, not in the artifact.
Ordinals are snapshot-local, never persistent symbols.
## 4. Diagnostics
```json
{
"module": "root:demo@0.1.0::index.mq.md",
"relative_path": "index.mq.md", "relative_path": "index.mq.md",
"span": {"start": 10, "end": 20}, "span": {"start": 10, "end": 20},
"line": 2, "line": 2,
"column": 3, "column": 3,
"severity": "warning", "severity": "error",
"code": "sem.inferred_signature", "code": "sem.invalid_mode_marker",
"message": "...", "message": "...",
"hints": [] "hints": []
} }
``` ```
`span` is the primary coordinate; `line`/`column` are presentation-derived from `span` is primary; `line`/`column` are 1-based presentation derived from the
the owning module. `span`, `line` or `column` may be `null` when no precise owning module and may be `null`. A successful Analysis contains no `error`
location exists. diagnostic. Diagnostics are deterministic: source position, then code.
The `code` value is an open, stable string: the current language revision adds ## 5. Reference resolution
the `sem.*` family (`spec/mapping.md` §8) and removes the old
`markdown.inert_executable` warning. Diagnostic codes may be added without changing the structure.
## 6. Loop transfers One pure resolver (`crates/cli/src/document_refs.rs`) handles every Markdown
link. It takes the source module, source span, raw URL and an explicit catalog
of documents with anchors and exact names. It performs no load, call binding,
import, network access or caller-entry fallback.
Conditional arms appear in source order. Both `break` and `continue` are ### 5.1 Catalog scope
statements with a `kind` and the half-open UTF-8 `span` of their carrier.
They have no operands or call edges. Walk the enclosing bodies to find
the nearest loop. `break` transfers past that loop and `continue` transfers
to its condition.
## 7. Validation * Ordinary Analysis uses only the modules already loaded for this program.
A local target outside that set is `not_loaded`; the artifact states that the
current scope did not verify it, never that it is absent.
* `check --refs` and `inspect --refs` build an explicit extension catalog:
direct local `.mq.md` targets are read once and parsed with the same heading
index; plain files are checked for existence only. They are not added to
`modules`, imports, call bindings or the program, and are never executed.
Budget/IO failures produce errors, never a silent downgrade.
* Given the same catalog, Analysis, `check` and `inspect` must produce the same
state for the same link.
Require exactly `schema: "marqdo.analysis"` and `schema_version: 3` before ### 5.2 Reference record
traversing the document. The [JSON Schema](schemas/analysis.schema.json)
validates record shapes. Check source digests, spans, ownership and
reference targets separately. Its full branch and loop structure applies
equally to simple projects and imported modules.
Source digests cover the original bytes. Preserve UTF-8 byte offsets for ```json
BOM, CRLF, CJK and emoji. Observation binds to the SHA-256 of the exact {
emitted Analysis JSON bytes. "source": "root:demo@0.1.0::index.mq.md",
"source_unit": "root:demo@0.1.0::index.mq.md#力学",
"url": "./theory.mq.md#formula",
"span": {"start": 20, "end": 50},
"state": "not_loaded",
"target_kind": null,
"target_module": null,
"target_unit": null,
"candidate_package_instance_id": "root:demo@0.1.0",
"candidate_path": "theory.mq.md",
"fragment": "formula",
"candidates": []
}
```
`source_unit` is the innermost unit whose complete `span` contains the link.
`candidate_path` is the normalised package-relative logical candidate; no OS
path is emitted. `fragment` is the once-decoded fragment or `null`; the raw
`url` is always preserved. `candidates` contains exact unit ids only for an
ambiguous canonical-name fallback.
| State | Meaning | Constraints |
|---|---|---|
| `resolved` | exact target in this catalog, or an explicitly verified local file | `target_kind: module` requires `target_module`; no fragment means `target_unit: null`; a verified plain file uses `target_kind: file` and needs no module |
| `not_loaded` | local candidate is outside this catalog; existence unverified | `target_unit: null`; never reported as missing |
| `missing` | catalog module has no such fragment, or explicit verification proved the file absent | keep the known `target_module` when available |
| `ambiguous` | canonical-name fallback has two or more exact candidates | `target_unit: null`; `candidates` lists all |
| `external` | URI has an external scheme (`http`, `https`, `mailto`, ...) | no network access; target fields `null`; not an error |
| `outside_scope` | local target escapes the allowed package root, or uses an absolute/file/drive/UNC path | target unread; no physical path emitted |
| `invalid` | malformed URI/percent encoding or unsupported address | no guessed repair |
Exact anchor lookup comes first; the existing canonical-name fallback (if
retained) collects all exact name candidates: 0 `missing`, 1 `resolved`, 2+
`ambiguous`. No `.find()`, case folding, edit distance or fuzzy binding. An
empty fragment is the document root. The fragment is percent-decoded exactly
once; invalid sequences are `invalid`.
Consumers may not reinterpret a non-`.mq.md` target as a Marqdo module. A
regular Markdown fragment is not verified against a foreign document profile:
the state is `not_loaded` with a diagnostic that coverage was insufficient, not
`missing`.
### 5.3 Security
Paths are normalised segment-by-segment after one percent decode. `file:`
URIs, OS absolute paths, drive/UNC paths, NUL, symlink escape and encoded
traversal are rejected or `outside_scope`. A legal `../` is allowed only while
the normalised candidate stays inside the package module root. The ordinary
Analysis opens no candidate. `--refs` opens only allowed local files, with
size/count limits, conservative symlink rejection and canonical root checking.
## 6. Validation
There are two steps on one boundary:
1. the [JSON Schema](schemas/analysis.schema.json) validates closed record
shapes, required fields, enums, types and array element shapes;
2. a semantic validator checks cross-record invariants that JSON Schema cannot
express.
The required semantic invariants are:
1. schema/revision/profile/entry/root/package/module identities agree; ids are
unique; paths do not escape their package; text is valid UTF-8.
2. every `source_digest` matches its `source`; every span belongs to that
module's source, has `start <= end <= source.len()` and lies on UTF-8
boundaries; functions, statements, resources and references never point at
another module.
3. there is exactly one root unit; parent edges form a tree (no cycle); each
`path` equals its parent's path plus its name; full spans nest with their
parent; heading AST, unit, function and anchor links exist and are
unambiguous; mode source units are self-or-ancestor.
4. functions are unique and correspond to Exec H2 units; each `function` field
points at the real definition; resolved call targets exist; builtin/plugin
targets never pretend to be Marqdo functions; imports resolve to catalog
modules.
5. reference state/nullability/candidates are consistent; `resolved` targets
exist in the catalog; ordinary Analysis has no fabricated external module;
resources refer to real units and their digests match the AST payload.
6. diagnostic owner/severity/code/span/line/column are valid; a successful
Analysis has no error; all arrays and modules are deterministically sorted.
The producer runs typed local checks before encoding; the independent
`tests/consumers/analysis_consumer.py` and `validate_protocols.py` validate the
serialized bytes. Production validation never replaces consumer validation of
untrusted input.
## 7. Failure and exit semantics
`check` keeps its existing CLI contract: success `0`; static diagnostic
errors and verified lock/extension load failures `1`; argument errors, a
missing/unreadable entry document and output-publication failures `2`. This
matches the current implementation and the other commands; this contract change
does not reclassify a missing `ENTRY` as a static diagnostic. `--json` is a
check diagnostic summary, not a second Analysis writer. `--emit` is the only
full Analysis writer.
A failed check publishes no success artifact. It may remove a previous artifact
at the caller-specified output path only when that path is not an input source,
manifest, lock/dependency file, directory, symlink or hard link to one, and only
when that previous artifact is the one the caller named. Partial/unsuccessful
Analysis documents do not exist.
## 8. Output safety
`--emit PATH`:
* refuses a path equal to any loaded source, the manifest or the lock file,
including through a hard link or symlink;
* refuses a directory, a symlink at the destination, or an output whose parent
cannot be created safely;
* creates the temporary file exclusively with owner-only permissions on Unix,
writes and flushes it, then renames it over the destination;
* on failure removes only its own temporary file and leaves inputs untouched;
* uses the same canonical encoder for the file and for the Observation digest.
No second pretty writer is allowed.
## 9. Observation binding
`run`/`call` compute `source.analysis_digest` by encoding the same
`PreparedProgram` with the same encoder and hashing the exact bytes.
Observation never copies `source`, document AST or link targets into runtime
events. A run with different static options (for example `--refs`, `--plugin`
or a different entry) binds a different artifact; consumers must re-check
digests against the disk version they rely on.
+3 -2
View File
@@ -333,8 +333,9 @@ refuses to run (see `security.md`).
For a fixed source, mode, capabilities and budget, evaluation is For a fixed source, mode, capabilities and budget, evaluation is
deterministic. Stdout/stderr from host operations are separated: program deterministic. Stdout/stderr from host operations are separated: program
stdout and program stderr are captured separately, diagnostics/traces go to the stdout and program stderr are captured separately, diagnostics/traces go to the
CLI stderr, and `--json` output never mixes with any program output. JSON CLI stderr, and a machine destination never mixes program bytes with
reports `stdout` and `stderr` as separate strings. diagnostics. The Observation contract commits program bytes as separate
`stdout.chunk` and `stderr.chunk` events.
## 8. Builtins v1 ## 8. Builtins v1
+1 -1
View File
@@ -296,4 +296,4 @@ security negatives.
remain authoritative and must not be skipped for a refactor. remain authoritative and must not be skipped for a refactor.
- Forbidden in both phases: persistent Python/Node sessions, Notebook-cell - Forbidden in both phases: persistent Python/Node sessions, Notebook-cell
execution, `@python` heading auto-execution, and a second foreign runtime in View. execution, `@python` heading auto-execution, and a second foreign runtime in View.
Streaming stays in Execution Events v1, not a second foreign network protocol. Streaming stays in the Observation contract, not a second foreign network protocol.
+5 -1
View File
@@ -80,7 +80,11 @@ parses it exactly once with `serde_yaml`. Supported semantics:
## 5. AST view ## 5. AST view
`marqdo inspect --ast --json` prints this tree: `marqdo inspect --ast --json` prints this tree, and `marqdo check --emit`
projects the identical `modules[].document` shape with the same projector
(`spec/analysis.md` §3.1). Neither is a second parser or a second long-lived
AST. The root `document` span covers the whole source including a BOM; every
span is a half-open UTF-8 byte offset into `modules[].source`.
```json ```json
{ {
+10 -1
View File
@@ -30,12 +30,19 @@ the [event schema](schemas/observation-event.schema.json) for the exact
fields. Reject other format identifiers, unknown kinds and invalid payloads. fields. Reject other format identifiers, unknown kinds and invalid payloads.
- `stream.opened` is first, with producer, capture policy and budget limits. - `stream.opened` is first, with producer, capture policy and budget limits.
The capture level is `base` (lifecycle only), `structural` (frame, branch,
loop and effect events) or `values` (explicitly selected names); the
snapshot `capture` metadata repeats the same level.
- `run.started` binds an entry, mode and source. `source.root_id` and - `run.started` binds an entry, mode and source. `source.root_id` and
`source.analysis_digest` identify the exact Analysis JSON emitted by `source.analysis_digest` identify the exact Analysis JSON emitted by
`check --emit` for the same project and static options. The digest is `check --emit` for the same project and static options. The digest is
SHA-256 over the file bytes, including formatting. Before highlighting a SHA-256 over the file bytes, including formatting. Before highlighting a
source span, validate the binding, module source digest and original UTF-8 source span, validate the binding, module source digest and original UTF-8
half-open byte range. A changed source or Analysis invalidates attribution. half-open byte range. A changed source or Analysis invalidates attribution.
The static options that change the projection include the entry, `--plugin`,
load/extension selection and diagnostics; a `--refs` check adds diagnostics
and therefore emits different bytes. Run/call never copy `source`, the
document AST or link targets into runtime events; they only bind the digest.
- `call.enter` identifies the call instance and its parent. `call.exit` - `call.enter` identifies the call instance and its parent. `call.exit`
closes that same instance. Call carriers belong to the caller module. closes that same instance. Call carriers belong to the caller module.
Parameter spans identify declarations in the called module. Parameter spans identify declarations in the called module.
@@ -52,7 +59,9 @@ fields. Reject other format identifiers, unknown kinds and invalid payloads.
Structural and selected-value events may stop at that point. Lifecycle Structural and selected-value events may stop at that point. Lifecycle
and committed byte chunks remain subject to their own execution and and committed byte chunks remain subject to their own execution and
output limits. The interpreter continues under unchanged program limits. output limits. The interpreter continues under unchanged program limits.
- `run.completed` contains the explicit return using [Value Wire](value-wire.md). - Error locations in `run.failed` carry `module_id`, `relative_path`, `line` and
`column`; a snapshot never embeds an absolute host path. `run.completed`
contains the explicit return using [Value Wire](value-wire.md).
A result containing a non-transferable handle has a null wire value and A result containing a non-transferable handle has a null wire value and
identifies its type. An explicit result, like a program print, can itself identifies its type. An explicit result, like a program print, can itself
contain sensitive data. `run.failed` follows a started run and contains contain sensitive data. `run.failed` follows a started run and contains
+6 -3
View File
@@ -353,9 +353,12 @@ resolver.
## 7. JSON output ## 7. JSON output
`check`, `inspect`, `run`, `call`, `plugin inspect`, `add`, `remove`, `lock` `check`, `inspect`, `plugin inspect`, `add`, `remove`, `lock` and `sync`
and `sync` accept `--json` and print a single JSON object on stdout. Relevant accept `--json` and print a single JSON object on stdout. `run` and `call` use
package shapes: the observation destinations instead (`--output text|json|jsonl` and
`--observation-file`), because one execution publishes one event sequence
([observation.md](observation.md)); the retired `--json` flag is rejected.
Relevant package shapes:
* `lock`: `{"command":"lock","success":true,"packages":[...]}` * `lock`: `{"command":"lock","success":true,"packages":[...]}`
* `sync`: `{"command":"sync","success":true,"locked":<bool>,"packages":[...]}` * `sync`: `{"command":"sync","success":true,"locked":<bool>,"packages":[...]}`
+14 -2
View File
@@ -16,7 +16,7 @@ Normative implementation:
| Resource collection and attribution | `crates/marqdo-frontend/src/resources.rs` | | Resource collection and attribution | `crates/marqdo-frontend/src/resources.rs` |
| Executable payload → statement mapping | `crates/marqdo-frontend/src/map.rs` | | Executable payload → statement mapping | `crates/marqdo-frontend/src/map.rs` |
| `ref(...)` runtime resolution | `crates/marqdo-runtime/src/builtins_impl.rs` | | `ref(...)` runtime resolution | `crates/marqdo-runtime/src/builtins_impl.rs` |
| Static link graph (`inspect --refs`) | `crates/cli/src/commands.rs` | | Static link graph (Analysis `references`, `check --refs`, `inspect --refs`) | `crates/cli/src/document_refs.rs` |
| Cross-module call validation | `crates/marqdo-frontend/src/calls.rs` | | Cross-module call validation | `crates/marqdo-frontend/src/calls.rs` |
This file complements [`mapping.md`](mapping.md) (AST roles) and This file complements [`mapping.md`](mapping.md) (AST roles) and
@@ -89,7 +89,10 @@ pub struct UnitId { pub module: ModuleId, pub path: Vec<String> }
normalization. `## @exec main` has the semantic name `main`; the declaration normalization. `## @exec main` has the semantic name `main`; the declaration
is never part of a `UnitId`, `FunctionId` or anchor. is never part of a `UnitId`, `FunctionId` or anchor.
* `Display` renders `<module>#<path joined by '/'>`; the root unit renders as * `Display` renders `<module>#<path joined by '/'>`; the root unit renders as
`<module>#`. `<module>#`. A path segment escapes `%`, `/` and `#` as `%25`, `%2F` and
`%23`, so a single segment named `a/b` cannot collide with the two-level path
`a` -> `b`. Consumers must use the structured `UnitId.path` exposed by
Analysis and must never split a display id to recover hierarchy.
* `UnitKind` is `root`, `namespace` (`#`), `function` (`##` Exec) or `section` * `UnitKind` is `root`, `namespace` (`#`), `function` (`##` Exec) or `section`
(`###`+). A Knowledge H2 is an addressable knowledge unit, not a `function`. (`###`+). A Knowledge H2 is an addressable knowledge unit, not a `function`.
Sections are addressable but not callable. Sections are addressable but not callable.
@@ -125,6 +128,15 @@ to units (`crates/marqdo-frontend/src/units.rs::github_slug`):
Internal ids stay canonical, so a heading rename is a link-breaking change Internal ids stay canonical, so a heading rename is a link-breaking change
but never changes the canonical unit path. but never changes the canonical unit path.
## 2.5 One document-link resolver
Analysis `references`, `check --refs` and `inspect --refs` use one pure
resolver over an explicit catalog (`spec/analysis.md` §5). It never loads a
module, binds a call or accesses the network. Ordinary Analysis uses only the
loaded modules; the `--refs` checks may add directly referenced local files to
a separate catalog for existence/anchor verification. The retired
`commands.rs::resolve_link` algorithm does not exist.
## 3. Front matter imports ## 3. Front matter imports
Imports exist only as an explicit YAML mapping in the document's front matter Imports exist only as an explicit YAML mapping in the document's front matter
+8 -3
View File
@@ -223,6 +223,11 @@ Token lifecycle:
6. Provider error codes map to existing categories: `permission.denied`, 6. Provider error codes map to existing categories: `permission.denied`,
`resource.closed`, `resource.exhausted`, `resource.unsupported`, otherwise `resource.closed`, `resource.exhausted`, `resource.unsupported`, otherwise
`host.error`. `host.error`.
7. Any transport failure — including a request frame that exceeds the 1 MiB
budget or a malformed reply — kills and reaps the helper. The peer is never
reused after a protocol error, so a program that sends an oversized request
must expect subsequent calls to that provider to fail closed rather than
silently truncate the payload.
## 6. Authorization ## 6. Authorization
@@ -240,9 +245,9 @@ Token lifecycle:
## 7. Error codes and exit codes ## 7. Error codes and exit codes
Manifest/CLI option failures exit 2; load/verification/spawn failures exit 1; Manifest/CLI option failures exit 2; load/verification/spawn failures exit 1;
`permission.denied` exits 1. With `--json` the CLI emits exactly one JSON `permission.denied` exits 1. With a machine destination the CLI publishes
document with a `code` (nested under `error.code` for these structured exactly one terminal event: a `run.rejected` event whose `payload.error.code`
errors). carries the same code.
| Code | Stage | Trigger | | Code | Stage | Trigger |
|---|---|---| |---|---|---|
+606 -267
View File
@@ -3,6 +3,7 @@
"$id": "https://marqdo.dev/schemas/analysis.schema.json", "$id": "https://marqdo.dev/schemas/analysis.schema.json",
"title": "Marqdo Analysis", "title": "Marqdo Analysis",
"type": "object", "type": "object",
"additionalProperties": false,
"required": [ "required": [
"schema", "schema",
"schema_version", "schema_version",
@@ -12,68 +13,118 @@
"diagnostics" "diagnostics"
], ],
"properties": { "properties": {
"schema": { "schema": {"const": "marqdo.analysis"},
"const": "marqdo.analysis" "schema_version": {"const": 3},
"producer": {"$ref": "#/$defs/producer"},
"project": {"$ref": "#/$defs/project"},
"modules": {
"type": "array",
"items": {"$ref": "#/$defs/module"}
}, },
"schema_version": { "diagnostics": {
"const": 3 "type": "array",
"items": {"$ref": "#/$defs/diagnostic"}
}
},
"$defs": {
"span": {
"type": "object",
"additionalProperties": false,
"required": ["start", "end"],
"properties": {
"start": {"type": "integer", "minimum": 0},
"end": {"type": "integer", "minimum": 0}
}
}, },
"producer": { "producer": {
"type": "object", "type": "object",
"required": [ "additionalProperties": false,
"name", "required": ["name", "version", "markdown_profile"],
"version",
"markdown_profile"
],
"properties": { "properties": {
"name": { "name": {"const": "marqdo"},
"type": "string" "version": {"type": "string", "minLength": 1},
}, "markdown_profile": {"const": "marqdo.md.v1"}
"version": {
"type": "string"
},
"markdown_profile": {
"const": "marqdo.md.v1"
} }
}, },
"additionalProperties": true
},
"project": { "project": {
"type": "object", "type": "object",
"additionalProperties": false,
"required": [ "required": [
"root_id", "root_id",
"identity_kind", "identity_kind",
"lock_digest" "entry_module_id",
"lock_digest",
"manifest_digest",
"stdlib",
"extensions"
], ],
"properties": { "properties": {
"root_id": { "root_id": {
"type": "string", "type": "string",
"minLength": 1, "pattern": "^(root:[A-Za-z0-9_.@+/-]+|sha256:[0-9a-f]{64})$"
"pattern": "^(root:|sha256:[0-9a-f]{64}$)"
},
"identity_kind": {
"enum": [
"manifest",
"workspace_snapshot"
]
}, },
"identity_kind": {"enum": ["manifest", "workspace_snapshot"]},
"entry_module_id": {"type": "string", "minLength": 1},
"lock_digest": { "lock_digest": {
"type": "string", "type": "string",
"pattern": "^(sha256:[0-9a-f]{64})?$" "pattern": "^(sha256:[0-9a-f]{64})?$"
},
"manifest_digest": {
"type": "string",
"pattern": "^(sha256:[0-9a-f]{64})?$"
},
"stdlib": {
"type": ["object", "null"],
"additionalProperties": false,
"required": ["version", "digest", "instance_id"],
"properties": {
"version": {"type": "string", "minLength": 1},
"digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"},
"instance_id": {"type": "string", "minLength": 1}
} }
}, },
"additionalProperties": true "extensions": {
},
"modules": {
"type": "array", "type": "array",
"items": { "items": {"$ref": "#/$defs/extension"}
}
}
},
"extension": {
"type": "object", "type": "object",
"additionalProperties": false,
"required": [
"kind",
"name",
"version",
"logical_owner",
"source",
"manifest_digest",
"artifact_digest",
"selected_target"
],
"properties": {
"kind": {"enum": ["plugin", "kernel", "provider"]},
"name": {"type": "string", "minLength": 1},
"version": {"type": "string", "minLength": 1},
"logical_owner": {"type": "string", "minLength": 1},
"source": {"type": "string", "minLength": 1},
"manifest_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"},
"artifact_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"},
"selected_target": {"type": "string", "minLength": 1}
}
},
"module": {
"type": "object",
"additionalProperties": false,
"required": [ "required": [
"id", "id",
"package_instance_id", "package_instance_id",
"relative_path", "relative_path",
"source_digest", "source_digest",
"source",
"document",
"units", "units",
"anchors",
"functions", "functions",
"imports", "imports",
"references", "references",
@@ -81,296 +132,584 @@
"resources" "resources"
], ],
"properties": { "properties": {
"id": { "id": {"type": "string", "pattern": "::"},
"type": "string", "package_instance_id": {"type": "string", "minLength": 1},
"pattern": "::"
},
"package_instance_id": {
"type": "string",
"minLength": 1
},
"relative_path": { "relative_path": {
"type": "string", "type": "string",
"minLength": 1, "minLength": 1,
"pattern": "^(?!/)(?!.*\\.\\.)" "pattern": "^(?!/)(?![A-Za-z]:)(?!.*\\\\)(?!.*//)(?!.*(?:^|/)\\.\\.?(?:/|$)).*$"
}, },
"source_digest": { "source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"type": "string", "source": {"type": "string"},
"pattern": "^[0-9a-f]{64}$" "document": {"$ref": "#/$defs/node"},
"units": {"type": "array", "items": {"$ref": "#/$defs/unit"}},
"anchors": {"type": "array", "items": {"$ref": "#/$defs/anchor"}},
"functions": {"type": "array", "items": {"$ref": "#/$defs/function"}},
"imports": {"type": "array", "items": {"$ref": "#/$defs/import"}},
"references": {"type": "array", "items": {"$ref": "#/$defs/reference"}},
"calls": {"type": "array", "items": {"$ref": "#/$defs/call"}},
"resources": {"type": "array", "items": {"$ref": "#/$defs/resource"}}
}
}, },
"units": { "node": {
"type": "array"
},
"functions": {
"type": "array",
"items": {
"type": "object", "type": "object",
"required": [ "additionalProperties": false,
"body" "required": ["kind", "span", "children"],
],
"properties": { "properties": {
"body": {
"$ref": "#/$defs/body"
}
}
}
},
"imports": {
"type": "array"
},
"references": {
"type": "array"
},
"calls": {
"type": "array"
},
"resources": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"module_id",
"unit_id",
"kind",
"span",
"content_digest"
],
"properties": {
"id": {
"type": "string",
"pattern": "#resource:(formula|code)-[0-9]+$"
},
"module_id": {
"type": "string",
"pattern": "::"
},
"unit_id": {
"type": "string",
"minLength": 1
},
"kind": { "kind": {
"enum": [ "enum": [
"formula", "document", "front_matter", "block_quote", "list", "item",
"code" "heading", "paragraph", "text", "strong", "emph", "strikethrough",
"code", "code_block", "math", "math_block", "link", "image",
"table", "table_row", "table_cell", "thematic_break",
"soft_break", "line_break", "html_block", "html_inline", "other"
] ]
}, },
"span": { "span": {"$ref": "#/$defs/span"},
"type": "object", "children": {"type": "array", "items": {"$ref": "#/$defs/node"}},
"required": [ "literal": {"type": "string"},
"start", "tag": {"type": "string", "minLength": 1},
"end" "level": {"type": "integer", "minimum": 1, "maximum": 6},
], "setext": {"type": "boolean"},
"properties": { "ordered": {"type": "boolean"},
"start": { "start": {"type": ["integer", "null"], "minimum": 0},
"type": "integer", "tight": {"type": "boolean"},
"minimum": 0 "task": {"type": ["boolean", "null"]},
"ticks": {"type": "integer", "minimum": 1},
"fenced": {"type": "boolean"},
"info": {"type": "string"},
"display": {"type": "boolean"},
"url": {"type": "string"},
"title": {"type": "string"},
"alignments": {
"type": "array",
"items": {"enum": ["none", "left", "center", "right"]}
}, },
"end": { "header": {"type": "boolean"}
"type": "integer",
"minimum": 0
}
}, },
"additionalProperties": true "allOf": [
}, {"if": {"properties": {"kind": {"const": "front_matter"}}},
"content_digest": { "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}},
"type": "string", {"if": {"properties": {"kind": {"const": "text"}}},
"pattern": "^[0-9a-f]{64}$" "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}},
}, {"if": {"properties": {"kind": {"const": "code"}}},
"language": { "then": {"required": ["literal", "ticks"], "properties": {"children": {"maxItems": 0}}}},
"type": [ {"if": {"properties": {"kind": {"const": "code_block"}}},
"string", "then": {"required": ["literal", "fenced", "info"], "properties": {"children": {"maxItems": 0}}}},
"null" {"if": {"properties": {"kind": {"const": "math"}}},
"then": {"required": ["literal", "display"], "properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "math_block"}}},
"then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "html_block"}}},
"then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "html_inline"}}},
"then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "thematic_break"}}},
"then": {"properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "soft_break"}}},
"then": {"properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "line_break"}}},
"then": {"properties": {"children": {"maxItems": 0}}}},
{"if": {"properties": {"kind": {"const": "heading"}}},
"then": {"required": ["level", "setext"]}},
{"if": {"properties": {"kind": {"const": "list"}}},
"then": {"required": ["ordered", "start", "tight"]}},
{"if": {"properties": {"kind": {"const": "item"}}},
"then": {"required": ["task"]}},
{"if": {"properties": {"kind": {"const": "link"}}},
"then": {"required": ["url", "title"]}},
{"if": {"properties": {"kind": {"const": "image"}}},
"then": {"required": ["url", "title"]}},
{"if": {"properties": {"kind": {"const": "table"}}},
"then": {"required": ["alignments"]}},
{"if": {"properties": {"kind": {"const": "table_row"}}},
"then": {"required": ["header"]}},
{"if": {"properties": {"kind": {"const": "other"}}},
"then": {"required": ["tag"]}}
] ]
}, },
"display": { "unit": {
"type": "boolean"
}
},
"additionalProperties": true
}
}
},
"additionalProperties": true
}
},
"diagnostics": {
"type": "array",
"items": {
"type": "object", "type": "object",
"additionalProperties": false,
"required": [ "required": [
"module", "id", "path", "parent_id", "kind", "name", "level", "mode",
"relative_path", "mode_origin", "mode_source_unit_id", "heading_span", "span", "function"
"severity",
"code",
"message"
], ],
"properties": { "properties": {
"module": { "id": {"type": "string", "minLength": 1},
"type": "string", "path": {
"pattern": "::"
},
"relative_path": {
"type": "string",
"minLength": 1
},
"span": {
"type": [
"object",
"null"
],
"required": [
"start",
"end"
],
"properties": {
"start": {
"type": "integer",
"minimum": 0
},
"end": {
"type": "integer",
"minimum": 0
}
}
},
"line": {
"type": [
"integer",
"null"
],
"minimum": 1
},
"column": {
"type": [
"integer",
"null"
],
"minimum": 1
},
"severity": {
"enum": [
"error",
"warning"
]
},
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string",
"minLength": 1
},
"hints": {
"type": "array", "type": "array",
"items": { "items": {"type": "string", "minLength": 1}
"type": "string" },
} "parent_id": {"type": ["string", "null"]},
"kind": {"enum": ["root", "namespace", "function", "knowledge", "section"]},
"name": {"type": "string"},
"level": {"type": "integer", "minimum": 0, "maximum": 6},
"mode": {"enum": ["exec", "knowledge"]},
"mode_origin": {"enum": ["default", "explicit", "inherited"]},
"mode_source_unit_id": {"type": "string", "minLength": 1},
"heading_span": {"oneOf": [{"$ref": "#/$defs/span"}, {"type": "null"}]},
"span": {"$ref": "#/$defs/span"},
"function": {"type": ["string", "null"]}
} }
}, },
"additionalProperties": true "anchor": {
}
}
},
"additionalProperties": true,
"$defs": {
"body": {
"type": "array",
"items": {
"$ref": "#/$defs/statement"
}
},
"span": {
"type": "object", "type": "object",
"additionalProperties": false,
"required": ["anchor", "unit_id"],
"properties": {
"anchor": {"type": "string", "minLength": 1},
"unit_id": {"type": "string", "minLength": 1}
}
},
"function": {
"type": "object",
"additionalProperties": false,
"required": [ "required": [
"start", "id", "unit_id", "local_name", "namespace", "span", "heading_span",
"end" "signature", "effects", "body"
], ],
"properties": { "properties": {
"start": { "id": {"type": "string", "minLength": 1},
"type": "integer", "unit_id": {"type": "string", "minLength": 1},
"minimum": 0 "local_name": {"type": "string", "minLength": 1},
}, "namespace": {"type": ["string", "null"]},
"end": { "span": {"$ref": "#/$defs/span"},
"type": "integer", "heading_span": {"$ref": "#/$defs/span"},
"minimum": 0 "signature": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "params"],
"properties": {
"kind": {"enum": ["explicit", "inferred"]},
"params": {"type": "array", "items": {"$ref": "#/$defs/param"}}
} }
},
"effects": {
"type": "array",
"items": {"enum": ["unknown"]}
},
"body": {"type": "array", "items": {"$ref": "#/$defs/statement"}}
}
},
"param": {
"type": "object",
"additionalProperties": false,
"required": ["name", "required", "type", "default", "span"],
"properties": {
"name": {"type": "string", "minLength": 1},
"required": {"type": "boolean"},
"type": {"type": ["string", "null"]},
"default": {
"oneOf": [{"$ref": "#/$defs/expression"}, {"type": "null"}]
},
"span": {"$ref": "#/$defs/span"}
} }
}, },
"statement": { "statement": {
"type": "object", "oneOf": [
"required": [ {"$ref": "#/$defs/stmt_assign"},
"kind", {"$ref": "#/$defs/stmt_expression"},
"span" {"$ref": "#/$defs/stmt_branch"},
], {"$ref": "#/$defs/stmt_loop"},
"properties": { {"$ref": "#/$defs/stmt_return"},
"kind": { {"$ref": "#/$defs/stmt_break"},
"enum": [ {"$ref": "#/$defs/stmt_continue"}
"assign",
"expression",
"branch",
"loop",
"return",
"break",
"continue"
] ]
}, },
"span": { "stmt_assign": {
"$ref": "#/$defs/span" "type": "object",
"additionalProperties": false,
"required": ["kind", "target", "value", "span"],
"properties": {
"kind": {"const": "assign"},
"target": {"$ref": "#/$defs/place"},
"value": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
} }
}, },
"stmt_expression": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "value", "span"],
"properties": {
"kind": {"const": "expression"},
"value": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"stmt_branch": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "arms", "span"],
"properties": {
"kind": {"const": "branch"},
"arms": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"required": ["condition", "condition_span", "body", "span"],
"properties": {
"condition": {"$ref": "#/$defs/expression"},
"condition_span": {"$ref": "#/$defs/span"},
"body": {"type": "array", "items": {"$ref": "#/$defs/statement"}},
"span": {"$ref": "#/$defs/span"}
}
}
},
"span": {"$ref": "#/$defs/span"}
}
},
"stmt_loop": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "condition", "condition_span", "body", "span"],
"properties": {
"kind": {"const": "loop"},
"condition": {"$ref": "#/$defs/expression"},
"condition_span": {"$ref": "#/$defs/span"},
"body": {"type": "array", "items": {"$ref": "#/$defs/statement"}},
"span": {"$ref": "#/$defs/span"}
}
},
"stmt_return": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "value", "span"],
"properties": {
"kind": {"const": "return"},
"value": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"stmt_break": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "span"],
"properties": {
"kind": {"const": "break"},
"span": {"$ref": "#/$defs/span"}
}
},
"stmt_continue": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "span"],
"properties": {
"kind": {"const": "continue"},
"span": {"$ref": "#/$defs/span"}
}
},
"place": {
"oneOf": [
{"type": "string", "minLength": 1},
{
"type": "object",
"additionalProperties": false,
"required": ["kind", "base", "index", "span"],
"properties": {
"kind": {"const": "index"},
"base": {"$ref": "#/$defs/expression"},
"index": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
}
]
},
"expression": {
"oneOf": [
{"$ref": "#/$defs/expr_literal"},
{"$ref": "#/$defs/expr_variable"},
{"$ref": "#/$defs/expr_list"},
{"$ref": "#/$defs/expr_record"},
{"$ref": "#/$defs/expr_unary"},
{"$ref": "#/$defs/expr_binary"},
{"$ref": "#/$defs/expr_member"},
{"$ref": "#/$defs/expr_index"},
{"$ref": "#/$defs/expr_call"}
]
},
"expr_literal": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "type", "span"],
"properties": {
"kind": {"const": "literal"},
"type": {"enum": ["int", "float", "text", "bool", "none"]},
"value": {"type": ["string", "number", "boolean"]},
"span": {"$ref": "#/$defs/span"}
},
"allOf": [ "allOf": [
{ {"if": {"properties": {"type": {"const": "int"}}},
"if": { "then": {"required": ["value"], "properties": {"value": {"type": "string", "pattern": "^-?[0-9]+$"}}}},
{"if": {"properties": {"type": {"const": "float"}}},
"then": {"required": ["value"], "properties": {"value": {"type": "number"}}}},
{"if": {"properties": {"type": {"const": "text"}}},
"then": {"required": ["value"], "properties": {"value": {"type": "string"}}}},
{"if": {"properties": {"type": {"const": "bool"}}},
"then": {"required": ["value"], "properties": {"value": {"type": "boolean"}}}},
{"if": {"properties": {"type": {"const": "none"}}},
"then": {"not": {"required": ["value"]}}}
]
},
"expr_variable": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "name", "span"],
"properties": { "properties": {
"kind": { "kind": {"const": "variable"},
"const": "loop" "name": {"type": "string", "minLength": 1},
} "span": {"$ref": "#/$defs/span"}
} }
}, },
"then": { "expr_list": {
"required": [ "type": "object",
"body" "additionalProperties": false,
], "required": ["kind", "items", "span"],
"properties": { "properties": {
"body": { "kind": {"const": "list"},
"$ref": "#/$defs/body" "items": {"type": "array", "items": {"$ref": "#/$defs/expression"}},
} "span": {"$ref": "#/$defs/span"}
}
} }
}, },
{ "expr_record": {
"if": { "type": "object",
"additionalProperties": false,
"required": ["kind", "entries", "span"],
"properties": { "properties": {
"kind": { "kind": {"const": "record"},
"const": "branch" "entries": {
}
}
},
"then": {
"required": [
"arms"
],
"properties": {
"arms": {
"type": "array", "type": "array",
"items": { "items": {
"type": "object", "type": "object",
"additionalProperties": false,
"required": ["key", "key_span", "value"],
"properties": {
"key": {"type": "string", "minLength": 1},
"key_span": {"$ref": "#/$defs/span"},
"value": {"$ref": "#/$defs/expression"}
}
}
},
"span": {"$ref": "#/$defs/span"}
}
},
"expr_unary": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "op", "operand", "span"],
"properties": {
"kind": {"const": "unary"},
"op": {"enum": ["not", "neg", "pos"]},
"operand": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"expr_binary": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "op", "left", "right", "span"],
"properties": {
"kind": {"const": "binary"},
"op": {
"enum": [
"or", "and", "eq", "ne", "lt", "le", "gt", "ge",
"add", "sub", "mul", "div", "floor_div", "mod", "pow"
]
},
"left": {"$ref": "#/$defs/expression"},
"right": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"expr_member": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "base", "field", "span"],
"properties": {
"kind": {"const": "member"},
"base": {"$ref": "#/$defs/expression"},
"field": {"type": "string", "minLength": 1},
"span": {"$ref": "#/$defs/span"}
}
},
"expr_index": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "base", "index", "span"],
"properties": {
"kind": {"const": "index"},
"base": {"$ref": "#/$defs/expression"},
"index": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"expr_call": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "callee", "args", "span"],
"properties": {
"kind": {"const": "call"},
"callee": {"$ref": "#/$defs/expression"},
"args": {"type": "array", "items": {"$ref": "#/$defs/arg"}},
"span": {"$ref": "#/$defs/span"}
}
},
"arg": {
"type": "object",
"additionalProperties": false,
"required": ["name", "value", "span"],
"properties": {
"name": {"type": ["string", "null"]},
"value": {"$ref": "#/$defs/expression"},
"span": {"$ref": "#/$defs/span"}
}
},
"import": {
"type": "object",
"additionalProperties": false,
"required": ["alias", "target", "span", "resolved"],
"properties": {
"alias": {"type": "string", "minLength": 1},
"target": {"type": "string", "minLength": 1},
"span": {"$ref": "#/$defs/span"},
"resolved": {"type": ["string", "null"]}
}
},
"reference": {
"type": "object",
"additionalProperties": false,
"required": [ "required": [
"body" "source", "source_unit", "url", "span", "state", "target_kind",
"target_module", "target_unit", "candidate_package_instance_id",
"candidate_path", "fragment", "candidates"
], ],
"properties": { "properties": {
"body": { "source": {"type": "string", "minLength": 1},
"$ref": "#/$defs/body" "source_unit": {"type": "string", "minLength": 1},
} "url": {"type": "string"},
"span": {"$ref": "#/$defs/span"},
"state": {
"enum": [
"resolved", "not_loaded", "missing", "ambiguous",
"external", "outside_scope", "invalid"
]
},
"target_kind": {"enum": ["module", "file", null]},
"target_module": {"type": ["string", "null"]},
"target_unit": {"type": ["string", "null"]},
"candidate_package_instance_id": {"type": ["string", "null"]},
"candidate_path": {"type": ["string", "null"]},
"fragment": {"type": ["string", "null"]},
"candidates": {
"type": "array",
"items": {"type": "string", "minLength": 1}
} }
} }
},
"callee": {
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"required": ["kind", "name"],
"properties": {
"kind": {"const": "ident"},
"name": {"type": "string", "minLength": 1}
} }
},
{
"type": "object",
"additionalProperties": false,
"required": ["kind", "base", "field"],
"properties": {
"kind": {"const": "member"},
"base": {"$ref": "#/$defs/callee"},
"field": {"type": "string", "minLength": 1}
} }
},
{
"type": "object",
"additionalProperties": false,
"required": ["kind", "span"],
"properties": {
"kind": {"const": "expression"},
"span": {"$ref": "#/$defs/span"}
} }
} }
] ]
},
"target_owner": {
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"required": ["kind", "package", "digest"],
"properties": {
"kind": {"const": "plugin"},
"package": {"type": "string", "minLength": 1},
"digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}
}
},
{"type": "null"}
]
},
"call": {
"type": "object",
"additionalProperties": false,
"required": [
"function", "span", "callee", "state", "target", "target_kind",
"target_owner", "reason"
],
"properties": {
"function": {"type": "string", "minLength": 1},
"span": {"$ref": "#/$defs/span"},
"callee": {"$ref": "#/$defs/callee"},
"state": {"enum": ["function", "builtin", "plugin", "unresolved"]},
"target": {"type": ["string", "null"]},
"target_kind": {"enum": ["function", "builtin", "plugin", null]},
"target_owner": {"$ref": "#/$defs/target_owner"},
"reason": {"enum": ["dynamic", "unbound", null]}
}
},
"resource": {
"type": "object",
"additionalProperties": false,
"required": [
"id", "module_id", "unit_id", "kind", "span", "content_digest",
"language", "display"
],
"properties": {
"id": {"type": "string", "pattern": "#resource:(formula|code)-[0-9]+$"},
"module_id": {"type": "string", "pattern": "::"},
"unit_id": {"type": "string", "minLength": 1},
"kind": {"enum": ["formula", "code"]},
"span": {"$ref": "#/$defs/span"},
"content_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"language": {"type": ["string", "null"]},
"display": {"type": ["boolean", "null"]}
}
},
"diagnostic": {
"type": "object",
"additionalProperties": false,
"required": [
"module", "relative_path", "span", "line", "column",
"severity", "code", "message", "hints"
],
"properties": {
"module": {"type": "string", "pattern": "::"},
"relative_path": {"type": "string", "minLength": 1},
"span": {"oneOf": [{"$ref": "#/$defs/span"}, {"type": "null"}]},
"line": {"type": ["integer", "null"], "minimum": 1},
"column": {"type": ["integer", "null"], "minimum": 1},
"severity": {"enum": ["error", "warning"]},
"code": {"type": "string", "minLength": 1},
"message": {"type": "string", "minLength": 1},
"hints": {"type": "array", "items": {"type": "string"}}
}
} }
} }
} }
@@ -81,6 +81,7 @@
"properties": { "properties": {
"level": { "level": {
"enum": [ "enum": [
"base",
"structural", "structural",
"values" "values"
] ]
+43 -34
View File
@@ -1,6 +1,6 @@
# Marqdo Security Model (implemented status) # Marqdo Security Model (implemented status)
Status: describes enforcement in the `3.0.0-rc.3` candidate. Status: describes enforcement in the `3.0.0-rc.4` candidate.
Normative implementation: Normative implementation:
@@ -12,7 +12,7 @@ Normative implementation:
| Host dispatch and per-op checks | `crates/marqdo-host/src/host.rs` | | Host dispatch and per-op checks | `crates/marqdo-host/src/host.rs` |
| Project-rooted filesystem | `crates/marqdo-host/src/fs.rs` | | Project-rooted filesystem | `crates/marqdo-host/src/fs.rs` |
| Budgets | `crates/marqdo-host/src/budget.rs` | | Budgets | `crates/marqdo-host/src/budget.rs` |
| Effect tracing | `crates/marqdo-host/src/trace.rs` | | Observation events (effects included) | `crates/marqdo-host/src/observe.rs`, `crates/cli/src/observation.rs` |
| Foreign adapter | `crates/marqdo-host/src/kernels.rs` | | Foreign adapter | `crates/marqdo-host/src/kernels.rs` |
| Foreign child processes | `crates/marqdo-foreign/src/lib.rs` | | Foreign child processes | `crates/marqdo-foreign/src/lib.rs` |
| Plugin loading / in-process plugin calls | `crates/marqdo-host/src/host.rs` (`load_plugin`, `op_plugin_invoke`), `crates/marqdo-plugin-abi/src/loader.rs` | | Plugin loading / in-process plugin calls | `crates/marqdo-host/src/host.rs` (`load_plugin`, `op_plugin_invoke`), `crates/marqdo-plugin-abi/src/loader.rs` |
@@ -28,7 +28,7 @@ Normative implementation:
|---|---|---| |---|---|---|
| `pure` | No external I/O; memory computation and budgets only. | **Enforced.** `Capabilities::pure()` = `console`, `math` only; every FS/foreign/plugin grant flag makes the CLI exit 2 with "pure mode prohibits external I/O grants". | | `pure` | No external I/O; memory computation and budgets only. | **Enforced.** `Capabilities::pure()` = `console`, `math` only; every FS/foreign/plugin grant flag makes the CLI exit 2 with "pure mode prohibits external I/O grants". |
| `project` | Operator-approved project resources under `CapabilityHost` + bounded resources. | **Enforced for the implemented operations.** Defaults equal `pure`; `--allow-read`, `--allow-write`, `--allow-net`, `--allow-env`, `--allow-process`, `--allow-random`, `--allow-foreign`, `--allow-plugin` add grants. `resource.open` supports stdin read, separate stdout/stderr write, granted project-file read/write (ADR-0025/0026/0040), granted in-process provider kinds (ADR-0033) and granted TCP/UDP/listener/TLS streams, including DNS names after an exact host grant (ADR-0034/0047/0048); process/device remain unsupported. Sandboxing is cooperative (in-process checks), not OS isolation; in-process providers are trusted, not sandboxed. | | `project` | Operator-approved project resources under `CapabilityHost` + bounded resources. | **Enforced for the implemented operations.** Defaults equal `pure`; `--allow-read`, `--allow-write`, `--allow-net`, `--allow-env`, `--allow-process`, `--allow-random`, `--allow-foreign`, `--allow-plugin` add grants. `resource.open` supports stdin read, separate stdout/stderr write, granted project-file read/write (ADR-0025/0026/0040), granted in-process provider kinds (ADR-0033) and granted TCP/UDP/listener/TLS streams, including DNS names after an exact host grant (ADR-0034/0047/0048); process/device remain unsupported. Sandboxing is cooperative (in-process checks), not OS isolation; in-process providers are trusted, not sandboxed. |
| `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-random/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. | | `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-random/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. |
`marqdo inspect <file> --platform` prints the detection report, for example: `marqdo inspect <file> --platform` prints the detection report, for example:
@@ -57,28 +57,32 @@ produces no IR and therefore cannot cause a host effect at all. No heading
annotation, keyword or Markdown container can grant a file/network/process annotation, keyword or Markdown container can grant a file/network/process
capability, and permission flags never change the AST→IR result. capability, and permission flags never change the AST→IR result.
### 1.2 Strict failure and `--json` contract ### 1.2 Strict failure and output contract
Strict execution is a two-phase operation: detect, then launch. Availability Strict execution is a two-phase operation: detect, then launch. Availability
observed by `inspect --platform` is a snapshot, not a permanent promise. The observed by `inspect --platform` is a snapshot, not a permanent promise. The
runtime therefore re-probes before launching; a failure after a successful runtime therefore re-probes before launching; a failure after a successful
probe is a refusal, never a fallback. probe is a refusal, never a fallback.
`--json` consumers must receive **exactly one** JSON document on stdout for A strict run supports text output and one `--output json` Observation snapshot
every outcome: on stdout. The verified child executes the program under the isolation
supervisor and produces that one snapshot document itself; its stdout bytes and
exit code are forwarded unchanged. A live JSONL stream and a file destination
(`--observation-file`) are refused before launch with
`strict.unsupported_grant` and exit 2: the supervisor owns the only channel and
a rejected destination never emits a partial stream.
* a verified child in `--json` mode produces that document itself and its The parent never executes project code. A control-plane failure (probe,
bytes and exit code are forwarded unchanged; supervisor spawn, namespace construction, timeout, capture) prints the
* a control-plane failure (probe, supervisor spawn, namespace construction, diagnostic on stderr and, when a snapshot destination is active, finishes the
timeout, capture) produces one CLI error document parent's snapshot as `incomplete` without a terminal event; an empty or invalid
`{"command": ..., "success": false, "error": ..., "code": ...}`; child document is `strict.child_invalid` and raw supervisor text is never
* output that is empty or is not exactly one JSON document is rejected as forwarded as program stdout. Consumers treat an incomplete delivery as no
`strict.child_invalid`; raw supervisor text is never forwarded as program evidence about the final execution outcome.
stdout.
The stable codes are `strict.probe_unavailable`, `strict.spawn_failed`, The stable codes are `strict.probe_unavailable`, `strict.spawn_failed`,
`strict.namespace_failure`, `strict.timeout`, `strict.resource_limit`, `strict.namespace_failure`, `strict.launch_failed`, `strict.timeout`,
`strict.child_invalid`, `strict.identity_invalid` and `strict.resource_limit`, `strict.child_invalid`, `strict.identity_invalid` and
`strict.unsupported_grant` (ADR-0053). A marker alone never authorizes strict `strict.unsupported_grant` (ADR-0053). A marker alone never authorizes strict
execution: Linux verifies the namespace/privilege identity, and every other execution: Linux verifies the namespace/privilege identity, and every other
platform rejects `MARQDO_STRICT_ACTIVE` outright (ADR-0053). platform rejects `MARQDO_STRICT_ACTIVE` outright (ADR-0053).
@@ -270,28 +274,32 @@ foreign child processes and worker plugins are terminated by the host (kill on
timeout/output overflow). Native plugins are not OS-limited; the core no longer timeout/output overflow). Native plugins are not OS-limited; the core no longer
hosts an in-process math kernel. hosts an in-process math kernel.
## 4. Effect tracing ## 4. Effect observation
`EffectTrace` records one entry per `Host::invoke` when enabled An effect is one `effect` event in the current Observation contract
(`--trace`, or implicitly `--json` for `run`/`call`). Entry fields: ([`observation.md`](observation.md)); it is emitted through the same
`ObservationSink` as lifecycle events when a machine destination is active
(`--output json`, `--output jsonl` or `--observation-file`). There is no
`--trace` flag, no separate trace file and no trace array in another document.
Event payload fields:
```json ```json
{"op":"print","module":"hello.mq.md","span":{"start":43,"end":57}, {"frame_id":"f1","operation":"print","result_code":"ok",
"duration_micros":3,"result":"ok"} "module_id":"root:default::hello.mq.md","span":{"start":43,"end":57}}
``` ```
* `op` is the stable `HostOp::name()` (`foreign.run`, `foreign.call`, * `operation` is the concrete host operation (`print`, `foreign.run`,
`fs.read`, `fs.write`, `plugin.invoke`, ...); `resource.request` traces the `fs.read`, `fs.write`, `plugin.invoke`, `resource.request`, ...); resource
operation name in its semantic metadata instead of a `HostOp` variant; operations report their concrete name (`fs.exists`, `fs.metadata`, ...);
* `module` is the initiating module id; `span` is the call site when known; * `module_id` is the initiating module; `span` is the call site when known;
* `result` is `"ok"` or the failure code (for example * `result_code` is `"ok"` or the failure code (for example
`permission.denied`); `permission.denied`);
* argument values and file contents are **not** recorded, so ordinary secrets * argument values and file contents are **not** recorded, so ordinary secrets
do not leak into traces by design. Paths are also not recorded today. do not leak into the observation by design. Paths are not recorded either.
* In text mode trace entries are printed to stderr (`trace: ...`); in JSON * Program output is committed as `stdout.chunk`/`stderr.chunk` byte events and
mode they are a `trace` array next to separate program `stdout`/`stderr` never shares a buffer with diagnostics. An in-process native plugin is
strings. Program output is always separate from diagnostics/trace, and refused in observation mode (`ext.observation_unsupported_native_plugin`)
`stdio/stderr` never shares the `stdout` buffer. because it can write directly to the inherited fds.
## 5. Foreign kernels: process isolation, not a sandbox ## 5. Foreign kernels: process isolation, not a sandbox
@@ -409,6 +417,7 @@ Neither command executes project code. Specifically:
(ADR-0014, `value-wire.md` §4.1). (ADR-0014, `value-wire.md` §4.1).
7. Budgets do not cover all allocation paths (for example list/table growth 7. Budgets do not cover all allocation paths (for example list/table growth
inside the interpreter is bounded only by fuel and memory). inside the interpreter is bounded only by fuel and memory).
8. `--json` run output includes the full program stdout string; that is the 8. An Observation snapshot contains the program's own stdout and stderr bytes
program's own output, not a host secret, but it is embedded in the JSON as base64 byte events. That is the program's output, not a host secret, but
document consumers must parse. selected value observation and text consent lower confidentiality; consumers
must treat a snapshot like the program output it embeds.
+4 -3
View File
@@ -158,9 +158,10 @@ The following are **not** bounded by `WireLimits` in
| Foreign kernel stdin | `{"wire_version":1,"kind":"request","input":<typed value or null>}` (`crates/marqdo-foreign/src/lib.rs`) | `input` is a `to_wire(value)` result, or JSON `null` when absent. | | Foreign kernel stdin | `{"wire_version":1,"kind":"request","input":<typed value or null>}` (`crates/marqdo-foreign/src/lib.rs`) | `input` is a `to_wire(value)` result, or JSON `null` when absent. |
| Foreign typed return (`foreign.call`) | stdout must be exactly one typed value | decoded with `from_wire` and default limits. | | Foreign typed return (`foreign.call`) | stdout must be exactly one typed value | decoded with `from_wire` and default limits. |
The `--json` output of `run`/`call` embeds `"value": to_wire(outcome.value)` The `run.completed` event of the current Observation snapshot embeds
(`crates/cli/src/commands.rs`), so CLI JSON consumers see the same typed `"value": to_wire(outcome.value)` (`crates/cli/src/observation.rs`), so CLI
representation. consumers see the same typed representation. A result containing a
non-transferable handle has a null value and names its type.
## 6. Compatibility rules ## 6. Compatibility rules
+501 -55
View File
@@ -1,77 +1,523 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Independent Analysis consumer: no Marqdo/Rust imports.""" """Independent semantic consumer for `marqdo.analysis`.
This script imports only the Python standard library. It validates the public
invariants that JSON Schema cannot express: source digests, span ownership,
heading trees, mode origins, function/anchor/call ownership, reference state
consistency and resource attribution. It never links a private Rust crate and
never executes a document.
usage: analysis_consumer.py ANALYSIS.json [--require-transfers]
"""
import hashlib
import json import json
import re
import sys import sys
def visit(body, loop_span=None): SCHEMA = "marqdo.analysis"
SCHEMA_VERSION = 3
STATES = {
"resolved",
"not_loaded",
"missing",
"ambiguous",
"external",
"outside_scope",
"invalid",
}
DIGEST64 = re.compile(r"^[0-9a-f]{64}$")
STATEMENT_KINDS = {
"assign",
"expression",
"branch",
"loop",
"return",
"break",
"continue",
}
EXPRESSION_KINDS = {
"literal",
"variable",
"list",
"record",
"unary",
"binary",
"member",
"index",
"call",
}
class InvalidAnalysis(Exception):
"""The artifact violates the current public contract."""
def fail(path, message):
raise InvalidAnalysis(f"{path}: {message}")
def validate(analysis):
"""Validate a parsed Analysis document; raise InvalidAnalysis on failure."""
if not isinstance(analysis, dict):
fail("$", "analysis must be an object")
if analysis.get("schema") != SCHEMA:
fail("$.schema", "unexpected schema")
if analysis.get("schema_version") != SCHEMA_VERSION:
fail("$.schema_version", "unsupported revision")
producer = analysis.get("producer") or {}
if producer.get("name") != "marqdo":
fail("$.producer.name", "unexpected producer")
if producer.get("markdown_profile") != "marqdo.md.v1":
fail("$.producer.markdown_profile", "unexpected Markdown profile")
project = analysis.get("project") or {}
modules = analysis.get("modules")
if not isinstance(modules, list) or not modules:
fail("$.modules", "at least one module is required")
by_id = {}
for index, module in enumerate(modules):
path = f"$.modules[{index}]"
module_id = module.get("id")
if not isinstance(module_id, str) or "::" not in module_id:
fail(path + ".id", "invalid module id")
if module_id in by_id:
fail(path + ".id", "duplicate module id")
by_id[module_id] = module
if project.get("entry_module_id") not in by_id:
fail("$.project.entry_module_id", "does not name a module")
if project.get("identity_kind") not in ("manifest", "workspace_snapshot"):
fail("$.project.identity_kind", "invalid identity kind")
for field in ("lock_digest", "manifest_digest"):
value = project.get(field)
if not isinstance(value, str) or not (
value == "" or re.fullmatch(r"sha256:[0-9a-f]{64}", value)
):
fail(f"$.project.{field}", "invalid snapshot digest")
if project.get("root_id") not in (None, "") and not isinstance(
project["root_id"], str
):
fail("$.project.root_id", "invalid root id")
extensions = project.get("extensions")
if not isinstance(extensions, list):
fail("$.project.extensions", "must be an array")
for index, extension in enumerate(extensions):
path = f"$.project.extensions[{index}]"
if extension.get("kind") not in ("plugin", "kernel", "provider"):
fail(path + ".kind", "invalid extension kind")
for field in ("manifest_digest", "artifact_digest"):
if not re.fullmatch(r"sha256:[0-9a-f]{64}", extension.get(field, "")):
fail(f"{path}.{field}", "invalid extension digest")
function_ids = set()
module_units = {}
for index, module in enumerate(modules):
path = f"$.modules[{index}]"
unit_ids = {unit.get("id") for unit in module.get("units", [])}
module_units[module["id"]] = unit_ids
function_ids.update(
function.get("id") for function in module.get("functions", [])
)
for index, module in enumerate(modules):
path = f"$.modules[{index}]"
source = module.get("source")
if not isinstance(source, str):
fail(path + ".source", "exact source must be a string")
encoded = source.encode("utf-8")
digest = module.get("source_digest")
if digest != hashlib.sha256(encoded).hexdigest():
fail(path + ".source_digest", "does not match source bytes")
digest = module.get("document", {}).get("span")
if not isinstance(module.get("document"), dict):
fail(path + ".document", "missing document AST")
ast_index = {}
validate_ast(module["document"], encoded, path + ".document", ast_index)
document_span = module["document"].get("span") or {}
if document_span.get("start") != 0 or document_span.get("end") != len(encoded):
fail(path + ".document.span", "root does not cover the source")
units = module.get("units") or []
if not units:
fail(path + ".units", "missing root unit")
unit_by_id = {}
for unit in units:
if unit.get("id") in unit_by_id:
fail(path + ".units", "duplicate unit id")
unit_by_id[unit["id"]] = unit
roots = [unit for unit in units if unit.get("kind") == "root"]
if len(roots) != 1:
fail(path + ".units", "expected exactly one root unit")
root = roots[0]
if root.get("parent_id") is not None or root.get("path") != []:
fail(path + ".units.root", "root must not have a parent or path")
if root.get("heading_span") is not None or root.get("level") != 0:
fail(path + ".units.root", "root must not carry a heading")
for unit in units:
upath = f"{path}.units[{unit['id']}]"
check_span(unit.get("span"), encoded, upath + ".span")
if unit.get("heading_span") is not None:
check_span(unit.get("heading_span"), encoded, upath + ".heading_span")
if unit is root:
continue
parent = unit_by_id.get(unit.get("parent_id"))
if parent is None:
fail(upath + ".parent_id", "missing parent unit")
expected = list(parent.get("path") or []) + [unit.get("name")]
if expected != unit.get("path"):
fail(upath + ".path", "does not match parent path plus name")
unit_span = unit.get("span") or {}
parent_span = parent.get("span") or {}
if not (
parent_span.get("start", 0) <= unit_span.get("start", 0)
and unit_span.get("end", -1) <= parent_span.get("end", -2)
):
fail(upath + ".span", "escapes the parent span")
if unit.get("mode") not in ("exec", "knowledge"):
fail(upath + ".mode", "invalid mode")
if unit.get("mode_origin") not in ("explicit", "inherited"):
fail(upath + ".mode_origin", "non-root unit must be explicit or inherited")
if not in_ancestor_chain(unit, unit.get("mode_source_unit_id"), unit_by_id):
fail(upath + ".mode_source_unit_id", "is not an ancestor")
function = unit.get("function")
if function is not None:
if unit.get("kind") not in ("function", "section"):
fail(upath + ".function", "only Exec H2/section units own a function")
if function not in function_ids:
fail(upath + ".function", "names a missing function")
if root.get("mode_origin") != "default":
fail(path + ".units.root.mode_origin", "root origin must be default")
anchors = module.get("anchors") or []
previous = None
for anchor in anchors:
if previous is not None and previous >= anchor.get("anchor"):
fail(path + ".anchors", "not strictly sorted")
previous = anchor.get("anchor")
if anchor.get("unit_id") not in unit_by_id:
fail(path + ".anchors", "names a missing unit")
seen_functions = set()
for function in module.get("functions") or []:
fpath = f"{path}.functions[{function.get('id')}]"
if function.get("id") in seen_functions:
fail(fpath, "duplicate function")
seen_functions.add(function.get("id"))
unit = unit_by_id.get(function.get("unit_id"))
if unit is None or unit.get("kind") != "function":
fail(fpath + ".unit_id", "not an Exec H2 unit")
if unit.get("function") != function.get("id"):
fail(fpath + ".id", "unit/function link mismatch")
check_span(function.get("span"), encoded, fpath + ".span")
check_span(function.get("heading_span"), encoded, fpath + ".heading_span")
for statement in function.get("body") or []:
validate_statement(statement, encoded, fpath)
for import_record in module.get("imports") or []:
check_span(import_record.get("span"), encoded, f"{path}.imports")
resolved = import_record.get("resolved")
if resolved is not None and resolved not in by_id:
fail(path + ".imports", "resolved target is not a module")
for reference in module.get("references") or []:
validate_reference(reference, by_id, module_units, encoded, path)
seen_call_sites = set()
for call in module.get("calls") or []:
cpath = f"{path}.calls"
check_span(call.get("span"), encoded, cpath)
key = (call.get("function"), call["span"]["start"], call["span"]["end"])
if key in seen_call_sites:
fail(cpath, "duplicate call site")
seen_call_sites.add(key)
if call.get("function") not in function_ids:
fail(cpath, "missing caller function")
state = call.get("state")
if state == "function":
if call.get("target_kind") != "function":
fail(cpath, "function call has wrong target kind")
if call.get("target") not in function_ids:
fail(cpath, "function target does not exist")
elif state == "builtin":
if call.get("target_kind") != "builtin" or not call.get("target"):
fail(cpath, "builtin call is incomplete")
elif state == "plugin":
if call.get("target_kind") != "plugin" or not call.get("target_owner"):
fail(cpath, "plugin call lacks its owner")
elif state == "unresolved":
if call.get("target") is not None or call.get("target_kind") is not None:
fail(cpath, "unresolved call carries a target")
if call.get("reason") not in ("dynamic", "unbound"):
fail(cpath, "unresolved call lacks a reason")
else:
fail(cpath, "invalid call state")
seen_resources = set()
for resource in module.get("resources") or []:
rpath = f"{path}.resources"
if resource.get("id") in seen_resources:
fail(rpath, "duplicate resource id")
seen_resources.add(resource.get("id"))
if resource.get("module_id") != module["id"]:
fail(rpath, "resource module mismatch")
if resource.get("unit_id") not in unit_by_id:
fail(rpath, "resource names a missing unit")
check_span(resource.get("span"), encoded, rpath)
if resource.get("kind") not in ("formula", "code"):
fail(rpath, "unknown resource kind")
if not DIGEST64.fullmatch(resource.get("content_digest", "")):
fail(rpath, "invalid resource digest")
if resource["kind"] == "formula" and not isinstance(
resource.get("display"), bool
):
fail(rpath, "formula display must be a bool")
if resource["kind"] == "code" and resource.get("display") is not None:
fail(rpath, "code display must be null")
node = ast_index.get(
(resource["span"]["start"], resource["span"]["end"])
)
if node is None:
fail(rpath, "resource span does not name an AST payload node")
expected_kinds = (
("math", "math_block")
if resource["kind"] == "formula"
else ("code_block",)
)
if node.get("kind") not in expected_kinds:
fail(rpath, "resource kind does not match its AST node")
payload = node.get("literal", "").encode("utf-8")
if resource["content_digest"] != hashlib.sha256(payload).hexdigest():
fail(rpath, "content_digest does not match the AST payload")
diagnostics = analysis.get("diagnostics")
if not isinstance(diagnostics, list):
fail("$.diagnostics", "must be an array")
for diagnostic in diagnostics:
if diagnostic.get("module") not in by_id:
fail("$.diagnostics", "names a missing module")
if diagnostic.get("severity") == "error":
fail("$.diagnostics", "successful Analysis contains an error")
span = diagnostic.get("span")
if span is not None:
module = by_id[diagnostic["module"]]
check_span(span, module["source"].encode("utf-8"), "$.diagnostics.span")
return analysis
def check_span(span, encoded, path):
if not isinstance(span, dict):
fail(path, "missing span")
start, end = span.get("start"), span.get("end")
if not isinstance(start, int) or not isinstance(end, int):
fail(path, "span endpoints must be integers")
if start < 0 or start > end or end > len(encoded):
fail(path, "span is outside the source")
for offset in (start, end):
try:
encoded[offset:].decode("utf-8")
except UnicodeDecodeError:
fail(path, "span is not on a UTF-8 boundary")
def in_ancestor_chain(unit, target, unit_by_id):
current = unit
while current is not None:
if current.get("id") == target:
return True
parent = current.get("parent_id")
current = unit_by_id.get(parent) if parent else None
return False
def validate_ast(node, encoded, path, ast_index=None):
if not isinstance(node, dict):
fail(path, "AST node must be an object")
kind = node.get("kind")
if not isinstance(kind, str):
fail(path + ".kind", "missing node kind")
if kind.startswith("footnote"):
fail(path + ".kind", "disabled profile node")
check_span(node.get("span"), encoded, path + ".span")
children = node.get("children")
if not isinstance(children, list):
fail(path + ".children", "must be an array")
if kind in {
"text",
"code",
"code_block",
"math",
"math_block",
"html_block",
"html_inline",
"front_matter",
"thematic_break",
"soft_break",
"line_break",
} and children:
fail(path + ".children", "leaf node has children")
if ast_index is not None and kind in ("code_block", "math", "math_block"):
span = node.get("span") or {}
ast_index[(span.get("start"), span.get("end"))] = node
for index, child in enumerate(children):
validate_ast(child, encoded, f"{path}.children[{index}]", ast_index)
def validate_statement(statement, encoded, path):
if not isinstance(statement, dict):
fail(path, "statement must be an object")
kind = statement.get("kind")
if kind not in STATEMENT_KINDS:
fail(path + ".kind", "unknown statement kind")
check_span(statement.get("span"), encoded, path + ".span")
if kind == "assign":
validate_place(statement.get("target"), encoded, path + ".target")
validate_expression(statement.get("value"), encoded, path + ".value")
elif kind == "expression":
validate_expression(statement.get("value"), encoded, path + ".value")
elif kind == "return":
validate_expression(statement.get("value"), encoded, path + ".value")
elif kind == "branch":
arms = statement.get("arms")
if not isinstance(arms, list) or not arms:
fail(path + ".arms", "branch needs at least one arm")
for arm in arms:
validate_expression(arm.get("condition"), encoded, path + ".condition")
check_span(arm.get("condition_span"), encoded, path + ".condition_span")
for nested in arm.get("body") or []:
validate_statement(nested, encoded, path + ".arm")
elif kind == "loop":
validate_expression(statement.get("condition"), encoded, path + ".condition")
check_span(statement.get("condition_span"), encoded, path + ".condition_span")
for nested in statement.get("body") or []:
validate_statement(nested, encoded, path + ".body")
elif kind in ("break", "continue"):
pass
def validate_place(place, encoded, path):
if isinstance(place, str):
if not place:
fail(path, "empty local target")
return
if not isinstance(place, dict) or place.get("kind") != "index":
fail(path, "invalid assignment target")
validate_expression(place.get("base"), encoded, path + ".base")
validate_expression(place.get("index"), encoded, path + ".index")
check_span(place.get("span"), encoded, path + ".span")
def validate_expression(expression, encoded, path):
if not isinstance(expression, dict):
fail(path, "expression must be an object")
kind = expression.get("kind")
if kind not in EXPRESSION_KINDS:
fail(path + ".kind", "unknown expression kind")
check_span(expression.get("span"), encoded, path + ".span")
if kind == "literal":
literal_type = expression.get("type")
if literal_type not in ("int", "float", "text", "bool", "none"):
fail(path + ".type", "unknown literal type")
if literal_type == "int":
if not re.fullmatch(r"-?[0-9]+", expression.get("value", "")):
fail(path + ".value", "integer literal must be a decimal string")
elif literal_type == "none":
if "value" in expression:
fail(path + ".value", "none literal carries a value")
elif kind == "variable":
if not expression.get("name"):
fail(path + ".name", "empty variable name")
elif kind == "list":
for item in expression.get("items") or []:
validate_expression(item, encoded, path + ".items")
elif kind == "record":
for entry in expression.get("entries") or []:
validate_expression(entry.get("value"), encoded, path + ".entry")
elif kind == "unary":
validate_expression(expression.get("operand"), encoded, path + ".operand")
elif kind in ("binary",):
validate_expression(expression.get("left"), encoded, path + ".left")
validate_expression(expression.get("right"), encoded, path + ".right")
elif kind == "member":
validate_expression(expression.get("base"), encoded, path + ".base")
elif kind == "index":
validate_expression(expression.get("base"), encoded, path + ".base")
validate_expression(expression.get("index"), encoded, path + ".index")
elif kind == "call":
validate_expression(expression.get("callee"), encoded, path + ".callee")
for argument in expression.get("args") or []:
validate_expression(argument.get("value"), encoded, path + ".arg")
def validate_reference(reference, by_id, module_units, encoded, path):
rpath = f"{path}.references"
check_span(reference.get("span"), encoded, rpath + ".span")
if reference.get("source_unit") not in module_units.get(reference.get("source"), set()):
fail(rpath + ".source_unit", "not a unit of the source module")
state = reference.get("state")
if state not in STATES:
fail(rpath + ".state", "unknown state")
target_module = reference.get("target_module")
target_unit = reference.get("target_unit")
target_kind = reference.get("target_kind")
if state == "resolved":
if target_kind == "module":
if target_module not in by_id:
fail(rpath + ".target_module", "does not name a module")
if target_unit is not None and target_unit not in module_units.get(
target_module, set()
):
fail(rpath + ".target_unit", "does not name a target unit")
elif target_kind == "file":
if target_module is not None or target_unit is not None:
fail(rpath, "file target must not name a module/unit")
else:
fail(rpath + ".target_kind", "resolved reference has no target kind")
elif state == "missing":
if target_unit is not None:
fail(rpath + ".target_unit", "missing reference carries a unit")
elif state == "ambiguous":
if target_unit is not None or len(reference.get("candidates") or []) < 2:
fail(rpath, "ambiguous reference needs several candidates")
else:
if target_module is not None or target_unit is not None or target_kind is not None:
fail(rpath, "non-resolved reference carries a target")
def visit_transfers(body, loop_span=None):
for statement in body: for statement in body:
kind = statement["kind"] kind = statement["kind"]
if kind == "loop": if kind == "loop":
yield from visit(statement["body"], statement["span"]) yield from visit_transfers(statement["body"], statement["span"])
elif kind == "branch": elif kind == "branch":
for arm in statement["arms"]: for arm in statement["arms"]:
yield from visit(arm["body"], loop_span) yield from visit_transfers(arm["body"], loop_span)
elif kind in ("break", "continue"): elif kind in ("break", "continue"):
if loop_span is None: if loop_span is None:
raise SystemExit(f"{kind} outside a projected loop") fail("$", f"{kind} outside a projected loop")
span = statement["span"] span = statement["span"]
if not 0 <= loop_span["start"] < span["start"] < span["end"]: if not 0 <= loop_span["start"] < span["start"] < span["end"]:
raise SystemExit(f"invalid {kind} carrier span") fail("$", f"invalid {kind} carrier span")
yield kind, loop_span["start"] yield kind, loop_span["start"]
elif kind not in ("assign", "expression", "return"):
raise SystemExit(f"unsupported statement kind {kind}")
if sys.argv[2:] not in ([], ["--require-transfers"]) or len(sys.argv) < 2: def main(argv):
raise SystemExit("usage: analysis_consumer.py ANALYSIS.json [--require-transfers]") if len(argv) not in (2, 3) or (len(argv) == 3 and argv[2] != "--require-transfers"):
raise SystemExit(
with open(sys.argv[1], encoding="utf-8") as handle: "usage: analysis_consumer.py ANALYSIS.json [--require-transfers]"
)
with open(argv[1], encoding="utf-8") as handle:
analysis = json.load(handle) analysis = json.load(handle)
validate(analysis)
if analysis.get("schema") != "marqdo.analysis":
raise SystemExit("unexpected schema")
if analysis.get("schema_version") != 3:
raise SystemExit("unsupported schema_version")
project = analysis["project"]
if project.get("identity_kind") not in ("manifest", "workspace_snapshot"):
raise SystemExit("bad project identity")
if not isinstance(project.get("root_id"), str) or not project["root_id"]:
raise SystemExit("bad root_id")
functions = []
transfers = [] transfers = []
functions = 0
for module in analysis["modules"]: for module in analysis["modules"]:
module_id = module["id"]
if "::" not in module_id or not module_id.startswith(("root:", "dep:", "std:")):
raise SystemExit("unexpected module identity")
if not isinstance(module["source_digest"], str) or len(module["source_digest"]) != 64:
raise SystemExit("bad source digest")
resources = module.get("resources")
if not isinstance(resources, list):
raise SystemExit("resources must be an array")
seen = set()
for resource in resources:
if resource.get("id") in seen:
raise SystemExit("duplicate resource id")
seen.add(resource.get("id"))
if resource.get("kind") not in ("formula", "code"):
raise SystemExit("unknown resource kind")
if resource.get("module_id") != module["id"]:
raise SystemExit("resource module mismatch")
if not isinstance(resource.get("content_digest"), str) or len(resource["content_digest"]) != 64:
raise SystemExit("bad resource digest")
span = resource.get("span") or {}
if not isinstance(span.get("start"), int) or not isinstance(span.get("end"), int):
raise SystemExit("bad resource span")
for function in module["functions"]: for function in module["functions"]:
transfers.extend(visit(function["body"])) functions += 1
functions.append(function["id"]) transfers.extend(visit_transfers(function["body"]))
if len(argv) == 3 and not transfers:
if not functions:
raise SystemExit("no functions")
print("functions=" + str(len(functions)))
if len(sys.argv) == 3 and not transfers:
raise SystemExit("missing loop transfers") raise SystemExit("missing loop transfers")
print(f"functions={functions}")
print(f"transfers={len(transfers)}") print(f"transfers={len(transfers)}")
if __name__ == "__main__":
main(sys.argv)
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Knowledge-like independent consumer of several explicit program entries.
Each entry is a separate `marqdo check --emit` artifact with its own project
snapshot. This fixture deduplicates modules by canonical id plus source digest,
keeps the real entry context, and reports links the loaded catalog did not
verify. It never scans a directory and never asks the CLI to build a combined
program.
usage: knowledge_consumer.py ANALYSIS...
"""
import json
import sys
def main(argv):
if len(argv) < 2:
raise SystemExit("usage: knowledge_consumer.py ANALYSIS...")
entries = 0
modules = {}
unverified = 0
projects = set()
for path in argv[1:]:
with open(path, encoding="utf-8") as handle:
analysis = json.load(handle)
if analysis.get("schema") != "marqdo.analysis":
raise SystemExit(f"knowledge: unexpected schema in {path}")
project = analysis["project"]
project_key = (
project["root_id"],
project["entry_module_id"],
project.get("manifest_digest", ""),
project.get("lock_digest", ""),
)
if project_key in projects:
raise SystemExit("knowledge: duplicate entry contribution")
projects.add(project_key)
entries += 1
module_ids = {module["id"] for module in analysis["modules"]}
if project["entry_module_id"] not in module_ids:
raise SystemExit("knowledge: entry is not in modules")
for module in analysis["modules"]:
key = (module["id"], module["source_digest"])
existing = modules.get(key)
if existing is not None and existing != module["source"]:
raise SystemExit("knowledge: same id/digest carries different source")
modules[key] = module["source"]
for reference in module["references"]:
if reference["state"] == "not_loaded":
unverified += 1
print(f"knowledge: entries={entries} modules={len(modules)}")
print(f"knowledge: not_loaded={unverified}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Lint-like independent consumer of public references and diagnostics.
Reports unresolved/ambiguous/out-of-scope links with their exact module and
source span. It never reads a private AST/IR and never fixes a reference.
usage: lint_consumer.py ANALYSIS.json
"""
import json
import sys
def line_col(source, span):
prefix = source.encode("utf-8")[: span["start"]].decode("utf-8")
line = prefix.count("\n") + 1
column = len(prefix.rsplit("\n", 1)[-1]) + 1
return line, column
def main(argv):
if len(argv) != 2:
raise SystemExit("usage: lint_consumer.py ANALYSIS.json")
with open(argv[1], encoding="utf-8") as handle:
analysis = json.load(handle)
if analysis.get("schema") != "marqdo.analysis":
raise SystemExit("lint: unexpected analysis schema")
modules = {module["id"]: module for module in analysis["modules"]}
problems = 0
for module in analysis["modules"]:
source = module["source"]
for reference in module["references"]:
state = reference["state"]
if state in ("resolved", "external"):
continue
line, column = line_col(source, reference["span"])
print(
f"lint: {reference['url']} state={state} "
f"{module['relative_path']}:{line}:{column}"
)
if state in ("ambiguous",):
print("lint: candidates=" + ",".join(reference["candidates"]))
problems += 1
for diagnostic in analysis["diagnostics"]:
if diagnostic["severity"] != "error":
continue
raise SystemExit(
"lint: a successful artifact must not contain an error diagnostic"
)
for diagnostic in analysis["diagnostics"]:
module = modules[diagnostic["module"]]
span = diagnostic["span"]
location = module["relative_path"]
if span is not None:
line, column = line_col(module["source"], span)
location = f"{location}:{line}:{column}"
print(f"lint: {diagnostic['code']} {location}")
print(f"lint: unresolved={problems}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+130
View File
@@ -11,6 +11,9 @@ import sys
from jsonschema import Draft202012Validator from jsonschema import Draft202012Validator
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from analysis_consumer import InvalidAnalysis, validate as validate_analysis
try: try:
# jsonschema >= 4.18 resolves the external event schema through # jsonschema >= 4.18 resolves the external event schema through
# `referencing`. The CI image may ship an older jsonschema, so keep the # `referencing`. The CI image may ship an older jsonschema, so keep the
@@ -62,6 +65,29 @@ def require_invalid(schema_name, document, label):
raise SystemExit(f"{label}: expected schema validation to fail") raise SystemExit(f"{label}: expected schema validation to fail")
def semantic_error(document):
try:
validate_analysis(document)
except InvalidAnalysis as error:
return str(error)
return None
def require_rejected(schema_name, document, label):
"""A mutation must be rejected by the schema or the semantic validator."""
schema_errors = list(validator(load_schema(schema_name)).iter_errors(document))
error = semantic_error(document)
if not schema_errors and error is None:
raise SystemExit(f"{label}: expected schema or semantic validation to fail")
def drop(document, path):
parent = document
for key in path[:-1]:
parent = parent[key]
del parent[path[-1]]
def main(): def main():
if len(sys.argv) != 4: if len(sys.argv) != 4:
raise SystemExit( raise SystemExit(
@@ -74,9 +100,38 @@ def main():
analysis_schema = "analysis.schema.json" analysis_schema = "analysis.schema.json"
require_valid(analysis_schema, analysis, "analysis") require_valid(analysis_schema, analysis, "analysis")
error = semantic_error(analysis)
if error is not None:
raise SystemExit(f"analysis: semantic validation failed: {error}")
require_valid("observation-file.schema.json", observation, "observation") require_valid("observation-file.schema.json", observation, "observation")
require_valid("cli-tool.schema.json", tool, "tool") require_valid("cli-tool.schema.json", tool, "tool")
# V01: every newly required field is load-bearing. Removing it must be
# rejected by the current schema or the semantic validator; an old
# same-revision artifact is not accepted.
required_paths = [
["project", "entry_module_id"],
["project", "manifest_digest"],
["project", "extensions"],
["modules", 0, "source"],
["modules", 0, "document"],
["modules", 0, "anchors"],
["modules", 0, "units", 0, "path"],
["modules", 0, "units", 0, "parent_id"],
["modules", 0, "units", 0, "mode_origin"],
["modules", 0, "units", 0, "mode_source_unit_id"],
["modules", 0, "units", 0, "heading_span"],
["modules", 0, "units", 0, "span"],
["modules", 0, "functions"],
["modules", 0, "references"],
["modules", 0, "calls"],
["modules", 0, "resources"],
]
for path in required_paths:
bad = copy.deepcopy(analysis)
drop(bad, path)
require_rejected(analysis_schema, bad, "analysis missing " + "/".join(map(str, path)))
# Negative mutations: structure, version and traversal must fail closed. # Negative mutations: structure, version and traversal must fail closed.
bad = copy.deepcopy(analysis) bad = copy.deepcopy(analysis)
bad["schema_version"] = 2 bad["schema_version"] = 2
@@ -90,6 +145,81 @@ def main():
bad["modules"][0]["resources"] = 3 bad["modules"][0]["resources"] = 3
require_invalid(analysis_schema, bad, "analysis resources integer") require_invalid(analysis_schema, bad, "analysis resources integer")
# V02/V03: tampered digests and spans must never be accepted.
bad = copy.deepcopy(analysis)
bad["modules"][0]["source"] = bad["modules"][0]["source"] + "x"
require_rejected(analysis_schema, bad, "analysis tampered source")
bad = copy.deepcopy(analysis)
bad["modules"][0]["source_digest"] = "0" * 64
require_rejected(analysis_schema, bad, "analysis tampered source digest")
bad = copy.deepcopy(analysis)
bad["modules"][0]["document"]["span"]["end"] = 10**12
require_rejected(analysis_schema, bad, "analysis out-of-range span")
bad = copy.deepcopy(analysis)
bad["modules"].append(copy.deepcopy(bad["modules"][0]))
require_rejected(analysis_schema, bad, "analysis duplicate module id")
# V04: heading tree and ownership invariants are semantic.
units = analysis["modules"][0]["units"]
if len(units) >= 3:
bad = copy.deepcopy(analysis)
bad_units = bad["modules"][0]["units"]
bad_units[1]["parent_id"] = bad_units[2]["id"]
bad_units[2]["parent_id"] = bad_units[1]["id"]
require_rejected(analysis_schema, bad, "analysis parent cycle")
bad = copy.deepcopy(analysis)
bad["modules"][0]["units"][1]["mode_source_unit_id"] = "root:missing"
require_rejected(analysis_schema, bad, "analysis mode source outside ancestors")
# V05: call, reference and resource targets are semantic.
module = analysis["modules"][0]
function_ids = {fn["id"] for module_iter in analysis["modules"] for fn in module_iter["functions"]}
for call in module["calls"]:
if call["state"] == "function":
bad = copy.deepcopy(analysis)
for candidate in bad["modules"][0]["calls"]:
if candidate["span"] == call["span"] and candidate["function"] == call["function"]:
candidate["target"] = "root:missing::missing"
require_rejected(analysis_schema, bad, "analysis missing call target")
break
references = [ref for module_iter in analysis["modules"] for ref in module_iter["references"]]
for reference in references:
if reference["state"] == "resolved" and reference["target_unit"] is not None:
bad = copy.deepcopy(analysis)
for module_iter in bad["modules"]:
for candidate in module_iter["references"]:
if (
candidate["span"] == reference["span"]
and candidate["source"] == reference["source"]
):
candidate["target_unit"] = "root:missing#missing"
require_rejected(analysis_schema, bad, "analysis missing reference unit")
break
for resource in module["resources"]:
bad = copy.deepcopy(analysis)
bad["modules"][0]["resources"][0]["content_digest"] = "0" * 64
require_rejected(analysis_schema, bad, "analysis tampered resource digest")
break
bad = copy.deepcopy(analysis)
bad["diagnostics"].append(
{
"module": module["id"],
"relative_path": module["relative_path"],
"span": None,
"line": None,
"column": None,
"severity": "error",
"code": "test.injected",
"message": "injected error",
"hints": [],
}
)
require_rejected(analysis_schema, bad, "analysis successful output with an error")
bad = copy.deepcopy(observation) bad = copy.deepcopy(observation)
bad["events"][0]["seq"] = "zero" bad["events"][0]["seq"] = "zero"
require_invalid("observation-file.schema.json", bad, "observation event sequence type") require_invalid("observation-file.schema.json", bad, "observation event sequence type")
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""View-like independent consumer of the public Analysis artifact.
Uses only the JSON document: section ranges, source text and function headings.
Never imports a Marqdo/Rust crate and never executes the document.
usage: view_consumer.py ANALYSIS.json
"""
import json
import sys
def utf8_slice(source, span):
data = source.encode("utf-8")
return data[span["start"] : span["end"]].decode("utf-8")
def main(argv):
if len(argv) != 2:
raise SystemExit("usage: view_consumer.py ANALYSIS.json")
with open(argv[1], encoding="utf-8") as handle:
analysis = json.load(handle)
if analysis.get("schema") != "marqdo.analysis":
raise SystemExit("view: unexpected analysis schema")
rendered = 0
for module in analysis["modules"]:
source = module["source"]
units = module["units"]
if not units:
raise SystemExit("view: module has no units")
by_id = {unit["id"]: unit for unit in units}
for unit in units:
parent = unit.get("parent_id")
if parent is not None and parent not in by_id:
raise SystemExit("view: dangling unit parent")
if unit["span"]["start"] > unit["span"]["end"]:
raise SystemExit("view: reversed section span")
for unit in units:
if unit["kind"] != "function":
continue
section = utf8_slice(source, unit["span"])
heading = utf8_slice(source, unit["heading_span"])
if not heading.strip():
raise SystemExit("view: empty function heading")
if not section.startswith(heading):
raise SystemExit("view: function section does not start at its heading")
label = "/".join(unit["path"])
print(f"view: {module['id']}#{label} [{len(section)} bytes]")
rendered += 1
if not rendered:
raise SystemExit("view: no callable section to render")
print(f"view: rendered={rendered}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Assert that an Observation consumer rejects a drifted Analysis artifact.
The CI contract lane must prove that stale Analysis bytes are not accepted by a
consumer. The check lives in a checked-in script because the CI runner does not
reliably preserve shell quoting inside multiline YAML commands.
usage: assert_stale_analysis.py ANALYSIS EVENTS
"""
import pathlib
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parents[2]
def main(argv):
if len(argv) != 3:
raise SystemExit("usage: assert_stale_analysis.py ANALYSIS EVENTS")
analysis_path = pathlib.Path(argv[1])
events_path = pathlib.Path(argv[2])
temporary = None
try:
with tempfile.NamedTemporaryFile(
prefix="marqdo-stale-", suffix=".json", delete=False
) as handle:
handle.write(analysis_path.read_bytes() + b" ")
temporary = pathlib.Path(handle.name)
result = subprocess.run(
[
sys.executable,
str(ROOT / "tests" / "consumers" / "observation_consumer.py"),
"--analysis",
str(temporary),
str(events_path),
],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
print("stale Analysis was accepted", file=sys.stderr)
return 1
print("stale Analysis rejected")
return 0
finally:
if temporary is not None:
try:
temporary.unlink()
except FileNotFoundError:
pass
if __name__ == "__main__":
sys.exit(main(sys.argv))
+144
View File
@@ -0,0 +1,144 @@
"""Tests for the performance workload catalogue and correctness digest.
The G4 release gate runs one fixed release binary over nine workloads. A
retired CLI option or a digest that changes per invocation silently turns a
correctness-verified measurement into CORRECTNESS_FAIL, so both are pinned
here.
"""
import importlib.util
import json
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
WORKLOADS = ROOT / "tools" / "perf" / "workloads.json"
RUNNER = ROOT / "tools" / "perf" / "runner.py"
def load_runner():
spec = importlib.util.spec_from_file_location("marqdo_perf_runner", RUNNER)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def snapshot(run_id: str, status: str, value, extra_file: str = "/tmp/index.mq.md"):
return {
"schema": "marqdo.observation",
"schema_version": 1,
"run": {"id": run_id, "status": status, "source": None},
"capture": {},
"events": [
{
"schema": "marqdo.observation",
"schema_version": 1,
"run_id": run_id,
"seq": 0,
"kind": "stream.opened",
"payload": {"producer": {"name": "marqdo", "version": "3.0.0-rc.4"}},
},
{
"schema": "marqdo.observation",
"schema_version": 1,
"run_id": run_id,
"seq": 1,
"kind": "run.started",
"payload": {"entry": "e::index.mq.md::main", "started_unix_ms": 1795523668882},
},
{
"schema": "marqdo.observation",
"schema_version": 1,
"run_id": run_id,
"seq": 2,
"kind": "run.completed",
"payload": {"status": status, "value": value, "value_type": "Int"},
},
],
}
class WorkloadCatalogueTest(unittest.TestCase):
def test_run_and_call_workloads_use_the_current_output_option(self):
catalogue = json.loads(WORKLOADS.read_text(encoding="utf-8"))
workloads = catalogue["workloads"]
self.assertEqual(len(workloads), 9)
for workload in workloads:
argv = workload["argv"]
if workload["kind"] in ("run", "call"):
self.assertIn(
["--output", "json"],
[argv[index : index + 2] for index in range(len(argv))],
f"{workload['name']} must request the current Observation snapshot",
)
self.assertNotIn(
"--json",
argv,
f"{workload['name']} still passes the retired run/call flag",
)
else:
self.assertIn("--json", argv)
class DualCommandWorkloadTest(unittest.TestCase):
def test_run_and_call_workloads_separate_correctness_from_timing(self):
catalogue = json.loads(WORKLOADS.read_text(encoding="utf-8"))
for workload in catalogue["workloads"]:
if workload["kind"] not in ("run", "call"):
self.assertNotIn("measure_argv", workload)
continue
measure = workload.get("measure_argv")
self.assertIsNotNone(measure, f"{workload['name']} lacks measure_argv")
self.assertNotIn("--output", measure)
self.assertNotIn("--json", measure)
self.assertEqual(measure[0], workload["argv"][0])
class DigestStabilityTest(unittest.TestCase):
def setUp(self):
self.runner = load_runner()
def test_observation_digest_ignores_run_identity_and_paths(self):
first = self.runner.wire_digest(snapshot("run-1", "ok", 120))
second = self.runner.wire_digest(
snapshot("run-2", "ok", 120, extra_file="/other/host/index.mq.md")
)
self.assertEqual(first, second)
def test_observation_digest_tracks_the_result(self):
ok = self.runner.wire_digest(snapshot("run-1", "ok", 120))
wrong = self.runner.wire_digest(snapshot("run-1", "ok", 121))
failed = self.runner.wire_digest(snapshot("run-1", "error", 120))
self.assertNotEqual(ok, wrong)
self.assertNotEqual(ok, failed)
def test_observation_digest_tracks_the_event_stream(self):
document = snapshot("run-1", "ok", 120)
truncated = dict(document)
truncated["events"] = document["events"][:2]
self.assertNotEqual(
self.runner.wire_digest(document), self.runner.wire_digest(truncated)
)
def test_measured_text_digest_ignores_the_checkout_path(self):
runner = self.runner
first = runner.text_digest(b"output 120\n")
second = runner.text_digest(b"output 120\n")
self.assertEqual(first, second)
self.assertNotEqual(first, runner.text_digest(b"output 121\n"))
def test_check_document_keeps_the_command_digest(self):
report = {
"command": "check",
"success": True,
"diagnostics": [{"code": "sem.x", "severity": "error", "line": 1, "column": 2, "message": "m"}],
"stdout": "",
"stderr": "",
}
normalized = self.runner.normalize(report)
self.assertEqual(normalized["command"], "check")
self.assertEqual(len(normalized["diagnostics"]), 1)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
"""Tests for the one-run Observation stream/snapshot verifier."""
import json
import pathlib
import subprocess
import sys
import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "tools" / "ci" / "verify_observation_stream.py"
def event(seq: int, kind: str) -> dict:
return {
"schema": "marqdo.observation",
"schema_version": 1,
"run_id": "run-1",
"seq": seq,
"kind": kind,
"payload": {},
}
def write(path: pathlib.Path, value) -> pathlib.Path:
if isinstance(value, list):
path.write_text(
"".join(json.dumps(item) + "\n" for item in value), encoding="utf-8"
)
else:
path.write_text(json.dumps(value), encoding="utf-8")
return path
class VerifyObservationStreamTest(unittest.TestCase):
def run_script(self, stream, snapshot):
with tempfile.TemporaryDirectory() as name:
directory = pathlib.Path(name)
stream_path = write(directory / "stream.jsonl", stream)
snapshot_path = write(directory / "snapshot.json", snapshot)
return subprocess.run(
[sys.executable, str(SCRIPT), str(stream_path), str(snapshot_path)],
capture_output=True,
text=True,
)
def test_identical_stream_and_snapshot_pass(self):
events = [event(0, "stream.opened"), event(1, "run.completed")]
snapshot = {
"schema": "marqdo.observation",
"schema_version": 1,
"run": {"id": "run-1", "status": "ok", "source": None},
"capture": {},
"events": events,
}
result = self.run_script(events, snapshot)
self.assertEqual(result.returncode, 0, result.stderr)
def test_divergent_event_fails(self):
stream = [event(0, "stream.opened"), event(1, "run.completed")]
snapshot = {
"schema": "marqdo.observation",
"schema_version": 1,
"run": {"id": "run-1", "status": "ok", "source": None},
"capture": {},
"events": [event(0, "stream.opened"), event(1, "run.failed")],
}
result = self.run_script(stream, snapshot)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertIn("differ", result.stderr)
def test_retired_format_fails(self):
events = [event(0, "stream.opened")]
retired = dict(events[0], schema="marqdo.execution-events")
result = self.run_script([retired], {"events": [events[0]]})
self.assertEqual(result.returncode, 1)
self.assertIn("current Observation", result.stderr)
if __name__ == "__main__":
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Assert that one Observation run's JSONL stream and JSON snapshot agree.
Usage:
python3 tools/ci/verify_observation_stream.py STREAM.jsonl SNAPSHOT.json
Exit 0 when the snapshot's events are exactly the stream's events, 1 when they
differ or a document is not a current Observation artifact. Both destinations
must come from the same execution; this check never re-runs the program.
"""
from __future__ import annotations
import json
import pathlib
import sys
def load_events(path: pathlib.Path, *, snapshot: bool) -> list:
raw = path.read_bytes()
if snapshot:
document = json.loads(raw.decode("utf-8"))
if document.get("schema") != "marqdo.observation":
raise SystemExit(f"{path}: not a current Observation snapshot")
events = document.get("events")
else:
if raw and not raw.endswith(b"\n"):
raise SystemExit(f"{path}: interrupted JSONL record")
events = [json.loads(line) for line in raw.splitlines()]
if not isinstance(events, list) or not events:
raise SystemExit(f"{path}: no Observation events")
for event in events:
if event.get("schema") != "marqdo.observation":
raise SystemExit(f"{path}: event is not current Observation")
return events
def main(argv: list[str]) -> int:
if len(argv) != 3:
print(
"usage: verify_observation_stream.py STREAM.jsonl SNAPSHOT.json",
file=sys.stderr,
)
return 2
stream = load_events(pathlib.Path(argv[1]), snapshot=False)
snapshot = load_events(pathlib.Path(argv[2]), snapshot=True)
if stream != snapshot:
for index, (left, right) in enumerate(zip(stream, snapshot)):
if left != right:
print(
f"stream and snapshot differ at seq {left.get('seq', index)}",
file=sys.stderr,
)
break
else:
print(
f"stream has {len(stream)} events, snapshot has {len(snapshot)}",
file=sys.stderr,
)
return 1
print(f"stream and snapshot share {len(stream)} events from one run")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+10 -2
View File
@@ -8,8 +8,16 @@ workload whose wire output did not match the committed expected digest.
* Build one release binary with `cargo build --release --locked -p marqdo-cli` * Build one release binary with `cargo build --release --locked -p marqdo-cli`
and keep it fixed for the whole run. The report records its SHA256, the and keep it fixed for the whole run. The report records its SHA256, the
`Cargo.lock` digest, `rustc -vV`, source SHA and profile. `Cargo.lock` digest, `rustc -vV`, source SHA and profile.
* Correctness comes first: every warmup run is parsed and hashed. A mismatch * Correctness comes first. Each workload has one correctness command and one
is `CORRECTNESS_FAIL`; its faster wall time is never reported. measurement command. For `run`/`call` the correctness command requests the
current Observation snapshot (`--output json`) and its digest pins the
terminal status/result, the committed stdout/stderr byte digests and the
ordered event-kind counts; the measurement command is the same program
without the opt-in observability destination, and every timed sample must
reproduce the committed text digest. A mismatch is `CORRECTNESS_FAIL`; its
faster wall time is never reported. Comparing the timed execution path
against the baseline execution path is the point: an opt-in protocol document
must not be billed as a product regression.
* Approved-node release evidence needs at least 5 warmups and 20 samples per * Approved-node release evidence needs at least 5 warmups and 20 samples per
workload on a dedicated, stable node. A maintainer-approved shared-node workload on a dedicated, stable node. A maintainer-approved shared-node
RC comparison needs the same sample counts in at least three paired runs. RC comparison needs the same sample counts in at least three paired runs.
+37 -5
View File
@@ -1,9 +1,39 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "branch.eval": 134,
"success": true, "call.enter": 255,
"call.exit": 255,
"effect": 249,
"loop.iteration": 40,
"parameter.observed": 558,
"return": 255,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 507
},
"count": 2256,
"sequence_sha256": "sha256:7ef37396e4e92c246a44e144f5532b8cefe460cb9bffe4897a561cf42f6a2b4b"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -289,9 +319,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:039ec1523726f48375f1fb5fafdfe849e296e1ee39b8a4820a0a0970cf3f8c3b", "wire_sha256": "sha256:1fc8f64612fe89c66cc38884f31ba2a883c3962a36d431b4e8d224ce8a58922b",
"workload": "allocator-free-list" "workload": "allocator-free-list"
} }
+37 -5
View File
@@ -1,9 +1,39 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/63-memory-bytecode-vm.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "branch.eval": 51,
"success": true, "call.enter": 7,
"call.exit": 7,
"effect": 28,
"loop.iteration": 34,
"parameter.observed": 14,
"return": 7,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 66
},
"count": 217,
"sequence_sha256": "sha256:218b342c70a1388d8f9e5ba5843c828ea53fa01c31ddae171c023dd581423f3a"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -34,9 +64,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:418131f5780815da5716d84ed5c00269760a881856cce67e0f4c8b42d417c7ec", "wire_sha256": "sha256:35b915e08c3f69fa0f6375565caaee21393a707d35852d03734b4b9c9643a5c0",
"workload": "bytecode-vm" "workload": "bytecode-vm"
} }
+38 -14
View File
@@ -1,24 +1,48 @@
{ {
"normalized": { "measure_argv": [
"command": "call", "call",
"diagnostics": [ "examples/factorial.mq.md",
{ "数学.阶乘",
"code": "sem.inferred_signature", "--arg",
"column": 1, "n=5"
"line": 3,
"message": "function signature was inferred; declare it with `params(...)`",
"severity": "warning"
}
], ],
"stderr": "", "measure_sha256": "sha256:97b912eb4a61df5f806ca6239dde3e1a4f51ad20aced1642cbb83dc510a5fa6b",
"stdout": "", "normalized": {
"success": true, "events": {
"by_kind": {
"branch.eval": 9,
"call.enter": 5,
"call.exit": 5,
"parameter.observed": 5,
"return": 5,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 4
},
"count": 36,
"sequence_sha256": "sha256:1c776fb38bbfa9cfb32e907385b18e75d84df3e62d96fee7859a739054513daf"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"decimal": "120", "decimal": "120",
"type": "int" "type": "int"
},
"value_type": "Int"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:0cbd8ab0b0e9e671e7e54f707ff2de00181b2721924b7fdec998ff9611873275", "wire_sha256": "sha256:34c724c5abc46f3c38875cf90c23e70e8f4048124a8571665f00f30bbbfab758",
"workload": "factorial-run" "workload": "factorial-run"
} }
+36 -5
View File
@@ -1,9 +1,38 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/71-http-parser.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "branch.eval": 545,
"success": true, "call.enter": 34,
"call.exit": 34,
"loop.iteration": 756,
"parameter.observed": 90,
"return": 34,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 1548
},
"count": 3044,
"sequence_sha256": "sha256:d394bf12395c193818794d34de4fef9f6a9048eb63235f30ce53a6785c4a2ab5"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -28,9 +57,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:540f8dd9a2071d40c1f07d82961e0e0174822e123c828ffc5d2a06cc880052ed", "wire_sha256": "sha256:1617796958d6b8e30c65884f26640f1072cde6037158e3abf0a196ecb9e39712",
"workload": "http-parser" "workload": "http-parser"
} }
+36 -5
View File
@@ -1,9 +1,38 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/62-json-array-parser.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "branch.eval": 632,
"success": true, "call.enter": 341,
"call.exit": 341,
"loop.iteration": 208,
"parameter.observed": 567,
"return": 341,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 700
},
"count": 3133,
"sequence_sha256": "sha256:cac83ea2856c09d105554b0e0d3bd1ed3d2541c19af51bddf236ab9b6e87f354"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -191,9 +220,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:d6f795f43eb1ae4c3d2f04254b8135f71d717ef8a649efdf7785f172b5381011", "wire_sha256": "sha256:c9833930c28ef238a606db40b33005338e75b83cf9ad98ffaa16f6d9f371a12a",
"workload": "json-parser" "workload": "json-parser"
} }
+35 -5
View File
@@ -1,9 +1,37 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/70-matrix-multiply.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "call.enter": 2,
"success": true, "call.exit": 2,
"loop.iteration": 25,
"parameter.observed": 2,
"return": 2,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 54
},
"count": 90,
"sequence_sha256": "sha256:a2b99c523f389a8efd203f54a88f4c9c4ecefe03cf453a3c18ab255913423327"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -122,9 +150,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:c5edb02098191e081a143b8f5d23424fcc43172643a44912cdc8ae17ace99cc2", "wire_sha256": "sha256:b975ac00d3e9d4d01d7e0fd26e0fde152333b254d38e7e1c4195bde824e97f32",
"workload": "matrix-multiply" "workload": "matrix-multiply"
} }
+38 -5
View File
@@ -1,14 +1,47 @@
{ {
"measure_argv": [
"run",
"stdlib/demo.mq.md"
],
"measure_sha256": "sha256:4f5fcde6b4073511330c50f15bf07db13abc2cf0cf71de777e8e23ca870220fe",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "[\"文本\", 2, 1.5, [3, true], {a: 1, b: \"x\"}, None]\n[\"文本\", 2, 1.5, [3, true], {a: 1, b: \"x\"}, None]\nTable[名称 | 分数]{甲 | 87; 乙 | 92}\nTable[名称 | 分数]{甲 | 87; 乙 | 92}\n[Formula(\"a = 1\"), Code(\"text\", 9 bytes), FunctionRef(root:default::demo.mq.md::演示函数)]\n[Formula(\"a = 1\"), Code(\"text\", 9 bytes), FunctionRef(root:default::demo.mq.md::演示函数)]\n", "branch.eval": 1956,
"success": true, "call.enter": 131,
"call.exit": 131,
"effect": 404,
"loop.iteration": 810,
"parameter.observed": 166,
"return": 131,
"run.completed": 1,
"run.started": 1,
"stdout.chunk": 6,
"stream.opened": 1,
"variable.assigned": 2533
},
"count": 6271,
"sequence_sha256": "sha256:e17ea3ebe3ecd40f9e619f06e3bd9d4370d34616caf02a6099bbffe0f686522d"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 380,
"sha256": "sha256:4f5fcde6b4073511330c50f15bf07db13abc2cf0cf71de777e8e23ca870220fe"
},
"terminal": {
"status": "ok",
"value": { "value": {
"type": "none" "type": "none"
},
"value_type": "None"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:80dfbfb894544b5cd4281999a67deaa9ce4fb19ef32d160fb4ee72dbd615d03c", "wire_sha256": "sha256:7bed5196b8cd52d1de12561f445bc2271dd5e91ed9c4065ebf79d0cb22d8a826",
"workload": "stdlib-print-demo" "workload": "stdlib-print-demo"
} }
+36 -5
View File
@@ -1,9 +1,38 @@
{ {
"measure_argv": [
"run",
"tests/conformance/semantics/65-table-sort-stdlib.mq.md"
],
"measure_sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"normalized": { "normalized": {
"command": "run", "events": {
"stderr": "", "by_kind": {
"stdout": "", "branch.eval": 9,
"success": true, "call.enter": 5,
"call.exit": 5,
"loop.iteration": 10,
"parameter.observed": 11,
"return": 5,
"run.completed": 1,
"run.started": 1,
"stream.opened": 1,
"variable.assigned": 35
},
"count": 83,
"sequence_sha256": "sha256:287e3f01941c53559c4113fceded4612a1f6c8ff44d2c19712aebf3c9034a172"
},
"schema": "marqdo.observation",
"status": "ok",
"stderr": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"stdout": {
"bytes": 0,
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"terminal": {
"status": "ok",
"value": { "value": {
"items": [ "items": [
{ {
@@ -86,9 +115,11 @@
} }
], ],
"type": "list" "type": "list"
},
"value_type": "List"
} }
}, },
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"wire_sha256": "sha256:12b61dcd9955cb7e137c705e51e29d58322d9525993681170f2dded48e94ee97", "wire_sha256": "sha256:d09caebb0ee91b593a8798f67a082ee38c008ea41274eeef3c05b2a4236081d1",
"workload": "table-sort" "workload": "table-sort"
} }
+156 -27
View File
@@ -17,6 +17,8 @@ performance evidence.
""" """
import argparse import argparse
import base64
from collections import Counter
import hashlib import hashlib
import json import json
import os import os
@@ -64,8 +66,72 @@ def git_sha(repo: Path) -> str:
return output(["git", "-C", str(repo), "rev-parse", "HEAD"]) or "unknown" return output(["git", "-C", str(repo), "rev-parse", "HEAD"]) or "unknown"
OBSERVATION_SCHEMA = "marqdo.observation"
# Run-specific or host-specific payload fields never contribute to correctness.
VOLATILE_PAYLOAD_KEYS = {"file", "started_unix_ms"}
def _stable(value):
"""Drop run/host-specific data from an observation payload."""
if isinstance(value, dict):
return {
key: _stable(item)
for key, item in value.items()
if key not in VOLATILE_PAYLOAD_KEYS
}
if isinstance(value, list):
return [_stable(item) for item in value]
if isinstance(value, str):
return value.replace(str(ROOT), "<repo>")
return value
def _committed_bytes(chunks: list[str]) -> dict:
data = b"".join(base64.b64decode(chunk) for chunk in chunks)
return {
"bytes": len(data),
"sha256": f"sha256:{hashlib.sha256(data).hexdigest()}",
}
def normalize(document: dict) -> dict: def normalize(document: dict) -> dict:
"""Canonical subset used for correctness: no timings, no trace, no paths.""" """Canonical subset used for correctness: no timings, no run ids, no paths."""
if document.get("schema") == OBSERVATION_SCHEMA:
# Current `run`/`call --output json` snapshot: one execution event
# sequence. The run id, wall-clock start and absolute paths are
# per-invocation. Correctness pins the terminal status/result, the
# committed stdout/stderr bytes and the ordered event kinds (count,
# per-kind totals and a sequence digest) without storing thousands of
# structural payloads in the repository.
events = document.get("events") or []
kinds = [event.get("kind") or "" for event in events]
counts = Counter(kinds)
terminal = _stable(events[-1].get("payload")) if events else None
return {
"schema": OBSERVATION_SCHEMA,
"status": (document.get("run") or {}).get("status"),
"terminal": terminal,
"stdout": _committed_bytes(
[
event["payload"]["data_base64"]
for event in events
if event.get("kind") == "stdout.chunk"
]
),
"stderr": _committed_bytes(
[
event["payload"]["data_base64"]
for event in events
if event.get("kind") == "stderr.chunk"
]
),
"events": {
"count": len(events),
"sequence_sha256": "sha256:"
+ hashlib.sha256("\n".join(kinds).encode("utf-8")).hexdigest(),
"by_kind": dict(sorted(counts.items())),
},
}
payload = {} payload = {}
for key in ("command", "success", "value", "stdout", "stderr", "errors"): for key in ("command", "success", "value", "stdout", "stderr", "errors"):
if key in document: if key in document:
@@ -93,28 +159,37 @@ def expected_path(name: str) -> Path:
return EXPECTED / f"{name}.json" return EXPECTED / f"{name}.json"
def load_expected(name: str) -> str | None: def text_digest(data: bytes) -> str:
"""Digest of measured text output with the checkout path normalised."""
normalized = data.replace(str(ROOT).encode(), b"<repo>")
return f"sha256:{hashlib.sha256(normalized).hexdigest()}"
def load_expected(name: str) -> dict | None:
path = expected_path(name) path = expected_path(name)
if not path.is_file(): if not path.is_file():
return None return None
return json.loads(path.read_text())["wire_sha256"] return json.loads(path.read_text())
def record_expected(name: str, document: dict) -> None: def record_expected(
name: str,
document: dict,
measure_stdout: bytes | None,
measure_argv: list[str] | None,
) -> None:
EXPECTED.mkdir(parents=True, exist_ok=True) EXPECTED.mkdir(parents=True, exist_ok=True)
expected_path(name).write_text( payload = {
json.dumps(
{
"schema": "marqdo.perf.expected.v1", "schema": "marqdo.perf.expected.v1",
"workload": name, "workload": name,
"wire_sha256": wire_digest(document), "wire_sha256": wire_digest(document),
"normalized": normalize(document), "normalized": normalize(document),
}, }
ensure_ascii=False, if measure_stdout is not None:
sort_keys=True, payload["measure_sha256"] = text_digest(measure_stdout)
indent=2, payload["measure_argv"] = measure_argv
) expected_path(name).write_text(
+ "\n" json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
) )
@@ -242,44 +317,71 @@ def run_workload(
prefix = [] prefix = []
if cpu_list: if cpu_list:
prefix = [shutil.which("taskset") or "taskset", "-c", cpu_list] prefix = [shutil.which("taskset") or "taskset", "-c", cpu_list]
argv = prefix + [str(binary)] + workload["argv"] # Correctness and measurement are separate commands for run/call: the
# machine document (Observation snapshot) pins the full public contract,
# while timing copies the plain execution path so an opt-in observability
# contract is not compared against a summary document.
correctness_argv = prefix + [str(binary)] + workload["argv"]
measured_argv = prefix + [str(binary)] + (workload.get("measure_argv") or workload["argv"])
env = dict(os.environ) env = dict(os.environ)
env.pop("MARQDO_STDLIB_DIR", None) env.pop("MARQDO_STDLIB_DIR", None)
if not (binary.parent / "stdlib" / "stdlib.json").is_file(): if not (binary.parent / "stdlib" / "stdlib.json").is_file():
env["MARQDO_STDLIB_DIR"] = str(ROOT / "stdlib") env["MARQDO_STDLIB_DIR"] = str(ROOT / "stdlib")
env.setdefault("NO_COLOR", "1") env.setdefault("NO_COLOR", "1")
expected = load_expected(name) expected_document = load_expected(name)
expected = expected_document.get("wire_sha256") if expected_document else None
expected_measure = (
expected_document.get("measure_sha256") if expected_document else None
)
result = { result = {
"name": name, "name": name,
"kind": workload.get("kind", "run"), "kind": workload.get("kind", "run"),
"source": workload["source"], "source": workload["source"],
"argv": workload["argv"], "argv": workload["argv"],
} }
if workload.get("measure_argv"):
result["measure_argv"] = workload["measure_argv"]
correctness = "VERIFIED" correctness = "VERIFIED"
warmup_samples: list[dict] = [] warmup_samples: list[dict] = []
measured: list[dict] = [] measured: list[dict] = []
# Correctness is checked on every warmup execution; a wrong result is never measure_stdout: bytes | None = None
# timed and can never become a "fast" regression sample.
for index in range(warmups + samples): # One correctness preflight per workload: the machine document must match
code, usage, wall, stdout, stderr = spawn_capture( # the committed contract digest before anything is timed.
argv, ROOT, env, timeout code, _usage, _wall, stdout, stderr = spawn_capture(
correctness_argv, ROOT, env, timeout
) )
if code != 0: if code != 0:
correctness = "CORRECTNESS_FAIL" correctness = "CORRECTNESS_FAIL"
result["error"] = ( result["error"] = f"exit {code}: {stderr.decode('utf-8', 'replace')[:500]}"
f"exit {code}: {stderr.decode('utf-8', 'replace')[:500]}" else:
)
break
try: try:
document = json.loads(stdout) document = json.loads(stdout)
except json.JSONDecodeError as error: except json.JSONDecodeError as error:
correctness = "CORRECTNESS_FAIL" correctness = "CORRECTNESS_FAIL"
result["error"] = f"invalid JSON: {error}" result["error"] = f"invalid JSON: {error}"
break document = None
if document is not None:
digest = wire_digest(document) digest = wire_digest(document)
if record: if workload.get("measure_argv"):
record_expected(name, document) code, _usage, _wall, measure_stdout, stderr = spawn_capture(
measured_argv, ROOT, env, timeout
)
if code != 0:
correctness = "CORRECTNESS_FAIL"
result["error"] = (
f"measurement probe exit {code}: "
f"{stderr.decode('utf-8', 'replace')[:500]}"
)
document = None
if record and document is not None:
record_expected(
name, document, measure_stdout, workload.get("measure_argv")
)
expected = digest expected = digest
if measure_stdout is not None:
expected_measure = text_digest(measure_stdout)
if document is not None:
if expected is None: if expected is None:
correctness = "UNVERIFIED_NO_EXPECTED" correctness = "UNVERIFIED_NO_EXPECTED"
elif digest != expected: elif digest != expected:
@@ -287,6 +389,33 @@ def run_workload(
result["error"] = ( result["error"] = (
f"wire digest mismatch: expected {expected}, got {digest}" f"wire digest mismatch: expected {expected}, got {digest}"
) )
elif measure_stdout is not None:
probe = text_digest(measure_stdout)
if expected_measure is None:
correctness = "UNVERIFIED_NO_EXPECTED"
elif probe != expected_measure:
correctness = "CORRECTNESS_FAIL"
result["error"] = (
"measurement output mismatch: expected "
f"{expected_measure}, got {probe}"
)
# Timing loop: only a verified workload contributes samples, and every
# sample's output must match the committed measurement digest.
if correctness == "VERIFIED":
for index in range(warmups + samples):
code, usage, wall, stdout, stderr = spawn_capture(
measured_argv, ROOT, env, timeout
)
if code != 0:
correctness = "CORRECTNESS_FAIL"
result["error"] = (
f"exit {code}: {stderr.decode('utf-8', 'replace')[:500]}"
)
break
if expected_measure is not None and text_digest(stdout) != expected_measure:
correctness = "CORRECTNESS_FAIL"
result["error"] = "measurement output changed between samples"
break break
sample = { sample = {
"wall_ms": wall * 1000.0, "wall_ms": wall * 1000.0,
+51 -8
View File
@@ -21,7 +21,15 @@
"数学.阶乘", "数学.阶乘",
"--arg", "--arg",
"n=5", "n=5",
"--json" "--output",
"json"
],
"measure_argv": [
"call",
"examples/factorial.mq.md",
"数学.阶乘",
"--arg",
"n=5"
] ]
}, },
{ {
@@ -31,7 +39,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md", "tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/55-first-fit-free-list-allocator.mq.md"
] ]
}, },
{ {
@@ -41,7 +54,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/62-json-array-parser.mq.md", "tests/conformance/semantics/62-json-array-parser.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/62-json-array-parser.mq.md"
] ]
}, },
{ {
@@ -51,7 +69,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/65-table-sort-stdlib.mq.md", "tests/conformance/semantics/65-table-sort-stdlib.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/65-table-sort-stdlib.mq.md"
] ]
}, },
{ {
@@ -61,7 +84,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/63-memory-bytecode-vm.mq.md", "tests/conformance/semantics/63-memory-bytecode-vm.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/63-memory-bytecode-vm.mq.md"
] ]
}, },
{ {
@@ -71,7 +99,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/70-matrix-multiply.mq.md", "tests/conformance/semantics/70-matrix-multiply.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/70-matrix-multiply.mq.md"
] ]
}, },
{ {
@@ -81,7 +114,12 @@
"argv": [ "argv": [
"run", "run",
"tests/conformance/semantics/71-http-parser.mq.md", "tests/conformance/semantics/71-http-parser.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"tests/conformance/semantics/71-http-parser.mq.md"
] ]
}, },
{ {
@@ -91,7 +129,12 @@
"argv": [ "argv": [
"run", "run",
"stdlib/demo.mq.md", "stdlib/demo.mq.md",
"--json" "--output",
"json"
],
"measure_argv": [
"run",
"stdlib/demo.mq.md"
] ]
} }
] ]
+1 -1
View File
@@ -16,7 +16,7 @@ Usage (from the repository root, after
python3 tools/release/package.py \ python3 tools/release/package.py \
--source-sha "$(git rev-parse HEAD)" \ --source-sha "$(git rev-parse HEAD)" \
--version 3.0.0-rc.3 --version 3.0.0-rc.4
""" """
from __future__ import annotations from __future__ import annotations
+1 -1
View File
@@ -9,7 +9,7 @@ Provider v2 worker (positive, unauthorized and missing-helper fail-closed), and
strict mode when the host genuinely supports it. strict mode when the host genuinely supports it.
Usage: Usage:
python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz
""" """
from __future__ import annotations from __future__ import annotations