66 Commits
Author SHA1 Message Date
cflmy deadf6edee ci: keep the contract lane short and make Bundle materialization idempotent
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
Woodpecker executes the job commands as one shell script; the inline contract
block plus its trailing commands exceeded the runner's command buffer and the
last command was truncated mid-argument (the raw log shows the shell received
'python3 tools/c'). Move the lane into tools/ci/contract_lane.sh and keep the
CI commands short, preserving every check.

CI jobs share one workspace, so a second job saw 'output already exists' from
the first fetch. The helper now reuses an output only after verifying it against
the pin, builds into a temporary sibling and moves it into place atomically.

Refs cflmy/marqdo-cli#11
2026-11-27 01:21:46 +08:00
cflmy 72f57beee0 refactor: accept the ecosystem stdlib Bundle and remove the in-repo sources
ci/woodpecker/push/main Pipeline failed
ci/woodpecker/pr/main Pipeline failed
Phase B of ADR-0070 (issue #11): the CLI no longer owns standard-library
sources. The pin names the accepted ecosystem Bundle (marqdo-stdlib@0.2.0,
root commit + tree/alias digests); tools/ci/fetch_ecosystem_bundle.py
materializes it from the pinned root commit and stdlib gitlinks and verifies
the digests. bundle.py and the test harness require an explicit verified Bundle
for the accepted identity, and runtime discovery has no compile-time source
fallback in any profile.

Delete stdlib/ (modules, self-tests, aliases manifest). Module and domain tests
stay with their component owners; the CLI product lane now verifies the
external Bundle's public surface, std: resolution and official print/打印 alias
routing (tests/product-stdlib). Composition assertions whose owner is the
ecosystem (Table split, print-format equivalence) moved to the root Bundle
acceptance; the generic TCP round-trip stays a CLI test. Spawned-CLI tests name
the verified Bundle explicitly.

CI (Woodpecker + GitHub) materializes the pinned Bundle before product tests,
packaging and performance lanes; packaging and release take --stdlib-dir from
that artifact. Docs, STATUS, ADR-0070 and a Phase B evidence record updated.

Refs cflmy/marqdo#9, cflmy/marqdo-cli#11
2026-11-27 01:04:01 +08:00
cflmy f8b82d4143 merge: bring master (issue #13 boundary + SDK revert) into issue #11 Phase A
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
2026-11-26 23:00:32 +08:00
cflmy f836f05998 docs: align the issue #13 snapshot with the SDK split revert
ci/woodpecker/push/main Pipeline was successful
- mark the old 0.12 remaining-work line as superseded by 0.13;
- record Woodpecker #112 success for the revert code commit in the evidence.

Docs-only change; no code/lock/protocol bytes move.
2026-11-26 21:28:24 +08:00
cflmy 98d256f5a2 refactor: keep the plugin SDK in the CLI workspace (revert split)
ci/woodpecker/push/main Pipeline was successful
The pre-stable line prioritizes atomic ABI/header/spec/SDK/loader changes over
a premature repository boundary. ADR-0073 supersedes ADR-0072:

- restore crates/marqdo-plugin-sdk as a contract-only CLI workspace crate
  (marqdo-plugin-abi + serde; no loader/host/worker dependency);
- restore tests/sdk-plugin and tools/ci/check_plugin_sdk.py, including the real
  CLI invocation and tampered-digest negative case;
- restore workspace/lock/architecture/dependency/docs/CI references; the SDK is
  a reviewed workspace member again and must not become a remote repo, mirror
  or submodule in this stage;
- ADR-0072 and the old issue #15 evidence are marked superseded; ADR-0073 and
  the split-revert evidence record the decision and the deleted remote repo;
- logical ADR-0071 boundaries are unchanged.

Workspace: 636 passed / 0 failed / 2 ignored; fmt, clippy, docs, architecture,
dependency, SDK gate and engine differential all PASS.

Refs #13, #15
2026-11-26 21:21:41 +08:00
cflmy 89acb709c6 Merge PR #16: independent plugin SDK repository
ci/woodpecker/push/main Pipeline was successful
Implements ADR-0072 / issue #15. SDK moved to cflmy/marqdo-plugin-sdk pinned to the CLI contract revision; CLI no longer carries or depends on it. CI push #108 and PR #110 green.
2026-11-26 20:13:11 +08:00
cflmy 3ab4aaa861 refactor: move the plugin SDK to its independent repository (issue #15)
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Implements ADR-0072 and the SDK physical migration tracked by issue #15:

- remove crates/marqdo-plugin-sdk, tests/sdk-plugin and the CLI-side
  check_plugin_sdk.py; the public cflmy/marqdo-plugin-sdk repository now owns
  the SDK workspace, lock, fixture, docs, AGENTS rules and CI definition.
- SDK consumes marqdo-plugin-abi at the exact CLI contract rev
  2585915e16906dac75f8571bed02e7f6f868c6bc; no path/submodule/copied contract.
- CLI does not depend on the SDK and must not re-add it as a workspace member
  or copy; dependency/architecture gates enforce this.
- docs: ADR-0072, CURRENT responsibility map/dependency graph, ADR-0071
  amendment, indexes, README, spec/plugin-abi, CI and developer entries.
- evidence: clean-clone SDK build/tests and real frozen 3.0.0-rc.4 CLI
  invocation (Int 42; tampered digest rejected).

CLI workspace: 631 passed / 0 failed / 0 ignored; fmt/clippy/docs/architecture/
dependency gates green.

Refs #15, #13
2026-11-26 19:48:24 +08:00
cflmy 2585915e16 Merge PR #14: Engine / Host Contract boundary and plugin ABI decoupling
ci/woodpecker/push/main Pipeline was successful
Closes the core M0-M3 boundary work for issue #13. CI push #103 and PR #104 are green on the candidate tree.
2026-11-26 19:29:13 +08:00
cflmy e2162add22 docs: record the issue #13 CI evidence and domain service ledger
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Docs-only delta on top of the verified code SHA 9b4f0a0:
- Woodpecker PR pipeline #101 (test/minimum-rust/build all green, including
  archive smoke and frozen external conformance).
- domain-service ledger stays DEFERRED under ADR-0062 (no new domain op).
- STATUS/evidence update; no code, lock or protocol change.
2026-11-26 18:49:48 +08:00
cflmy 9b4f0a0822 refactor: extract neutral host contract and decouple plugin ABI (issue #13)
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was canceled
Implements the core M0-M3 boundary work from issue #13 / ADR-0071 without
changing language semantics or any public protocol:

- add marqdo-host-contract owning Host/HostOp/ExecutionContext/ResourceRead
  and the runtime observation facts; the engine depends on it only.
- marqdo-runtime no longer links marqdo-host; the native host implements the
  contract and has no reverse edge to runtime/frontend/IR.
- reduce marqdo-plugin-abi to the public C ABI/wire/error contract; move
  manifest/artifact/loader/worker execution into marqdo-host::plugin so the
  SDK carries no loader/worker/host dependency.
- add a real independent consumer (tests/embedding, own workspace+lock) that
  runs Markdown -> frontend -> IR -> runtime with bounded budgets and explicit
  effect refusal, plus differential CLI comparison.
- add an SDK-only third-party plugin fixture and real CLI invocation gate.
- replace the frozen-crate architecture test with a reviewed responsibility
  graph enforced from Cargo metadata, with negative unit cases.
- consolidate current docs/entry: ADR-0071, CURRENT responsibility map,
  developers/architecture indexes, historical banners, STATUS and evidence.
- record keep-in-workspace for Engine/Native Host; no empty candidate repo.

Evidence: docs/evidence/2026-11-26-issue-13-engine-host-boundary.md
Refs #13
2026-11-26 18:37:02 +08:00
cflmy c769eafc60 docs: list the Phase A commits in the evidence record
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Add the smoke commit and the CI gate follow-up so the evidence names the
reviewed implementation sequence instead of a relative commit.
2026-11-26 15:59:07 +08:00
cflmy 2acaaefe77 ci: fold the independent build into the linux evidence gate
tools/ci/release_evidence.py accepts only its declared gate names; the
extra independent_build gate would have failed the release-evidence job.
The job still depends on independent-build and marks linux FAIL when it
does not pass.
2026-11-26 15:56:20 +08:00
cflmy 88ce91a9e1 docs: record the issue #11 Phase A state and evidence
Update STATUS, the architecture overview, README and tests/README with
the explicit Bundle input, pinned test/perf lanes and the independent
build. Add the Phase A evidence record: bundle identity, failure paths,
deterministic pack/package digests, independent build, archive smoke,
cold install and the 634-passed workspace gate. Phase B remains
explicitly unclaimed.
2026-11-26 15:52:04 +08:00
cflmy 0e1efc713e smoke: keep language-only execution after removing the Bundle
Moving the shipped stdlib aside must fail the print program with an
explicit diagnostic and still run a language-only program. The archive
smoke and the cold-install container now both call the factorial
example after the move, and the archive contract test pins the new
message.
2026-11-26 15:51:39 +08:00
cflmy ab6b6b1a23 ci: add the independent-build lane and pin the perf Bundle
Add tools/ci/independent_build.py: export HEAD without stdlib/, build
both shipped binaries with --locked, run a language-only check/call, and
require a stdlib-dependent run to fail closed with no sibling stdlib.
Add tests/independent/language-only.mq.md and run the lane as its own
GitHub job and Woodpecker step.

Perf runner resolves the pinned Bundle (--stdlib-dir/--bundle-pin),
exports it to every workload and records it in the report; GitHub and
Woodpecker lanes verify the pin and pass the product tests an explicit
Bundle. docs/ci.md and performance docs describe the lanes.
2026-11-26 15:25:40 +08:00
cflmy 3a68260cf2 tests: resolve one pinned Bundle and separate the loader lane
Add crates/cli/tests/support/stdlib.rs as the product/conformance test
resolver: explicit MARQDO_TEST_STDLIB_BUNDLE or the pinned path, always
verified against bundle-pin.json (name/version/commit/digests), with a
bad explicit override failing closed. Route stdlib_product,
stdlib_bundle, http, table, alias routing, p2_closure,
conformance_semantics and architecture_boundaries through it.

Loader unit tests now build small synthetic Bundles; discovery is split
into discover_with so the bad-override-no-fallback rule is testable.
2026-11-26 15:15:59 +08:00
cflmy 422b9de6d7 release: take the stdlib Bundle as one explicit, pinned input
package.py now requires --stdlib-dir and accepts --bundle-pin; it
verifies the manifest, required files, tree/alias digests and the pin
before staging, copies exactly that Bundle next to the binary, and
records stdlib.source{kind,repository,commit,path} in RELEASE_INFO.
Digest logic moves to tools/stdlib/bundle.py. GitHub/Woodpecker
release steps and docs/releasing.md pass the pinned input.
2026-11-26 15:07:29 +08:00
cflmy 1b9d9c4c26 stdlib: add one pinned Bundle resolver and explicit pack input
Add tools/stdlib/bundle.py + bundle-pin.json as the single source-side
Bundle identity (name, version, source commit, tree/alias digests) and
require tools/pack-stdlib.py --stdlib-dir instead of reading the
checkout implicitly. Missing input, missing manifest, digest/alias
mismatch, pin mismatch and symlinks fail closed; two packs are
byte-identical. Tests: tools/ci/test_stdlib_bundle_tools.py.
2026-11-26 15:00:26 +08:00
cflmy b9c72e1d2a docs: inventory stdlib source coupling and record the Phase A boundary
Record ADR-0070 (one explicit stdlib Bundle build input) and the
issue #11 Phase A inventory of every direct checkout-stdlib reference.
Baseline 4bbefc9; bundle source 2cbde54; no runtime contract change.
2026-11-26 14:54:11 +08:00
cflmy 4bbefc9244 release: publish 3.0.0-rc.4 with analysis boundary evidence
ci/woodpecker/push/main Pipeline was successful
Record the RC_RELEASE_CANDIDATE gate manifest, same-SHA CI #94, frozen
extension 7/7, archive smoke, Ubuntu 24.04 cold install, disposable-VM strict
L1 PASS (uid 1000), archived-binary VM verification and the maintainer-approved
shared-node performance WARN for this named RC. Document that stable/LTS still
requires a dedicated fixed node and link the downstream view/lint issues.
2026-11-25 14:17:31 +08:00
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
cflmy 5c371a9bef evidence: record the same-SHA CI for the rc.3 candidate
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
2026-11-24 18:49:54 +08:00
cflmy 5a89a137c7 ci: pin the converged conformance fixtures
ci/woodpecker/push/main Pipeline was successful
2026-11-24 18:32:44 +08:00
cflmy f55559b531 ci: keep the contract lane compatible with the image shell
ci/woodpecker/push/main Pipeline failed
2026-11-24 18:20:41 +08:00
cflmy 6b509d344e ci: split a fast contract lane from the full Rust lane
ci/woodpecker/push/main Pipeline was canceled
2026-11-24 18:18:35 +08:00
cflmy 33b73f41e3 consumers: resolve the event schema on jsonschema before 4.18
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:49:24 +08:00
cflmy 4f3a9bff29 docs: describe the current CI protocol gates 2026-11-24 17:40:54 +08:00
cflmy 09ab131b96 ci: exercise only the current Analysis and Observation contracts
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:37:49 +08:00
cflmy 93fada3d92 evidence: record the rc.3 local protocol-convergence gate
ci/woodpecker/push/main Pipeline failed
2026-11-24 17:16:05 +08:00
cflmy 291e521cec release: prepare 3.0.0-rc.3 with the converged contracts 2026-11-24 17:12:51 +08:00
cflmy ca0f0799e7 ext: reject retired descriptor revisions without migration 2026-11-24 17:05:38 +08:00
cflmy 867cd72ced docs: remove retired protocol names from current guides 2026-11-24 17:04:27 +08:00
cflmy 3fe1ca3c0c docs: record the single-contract policy and review gate 2026-11-24 17:04:03 +08:00
cflmy bf141a1f26 worker: share one bounded transport across plugin and provider workers 2026-11-24 16:55:19 +08:00
Codex 404d559b86 observation: deliver one execution event sequence to stream and snapshot 2026-11-24 15:30:18 +08:00
Codex f83d992c61 tool: require exact current contracts without negotiation 2026-11-24 14:23:48 +08:00
Codex 8bfe0c36ee analysis: publish one schema for every project 2026-11-24 14:16:56 +08:00
Codex 8bd33a4615 docs: define single current contracts before the first stable release 2026-11-24 14:11:26 +08:00
Codex 652ea76360 Use Apache-2.0 as the sole project license
ci/woodpecker/push/main Pipeline was successful
2026-11-23 22:58:10 +08:00
334 changed files with 52277 additions and 13304 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
+940
View File
@@ -0,0 +1,940 @@
{
"schema": "marqdo.analysis",
"schema_version": 3,
"producer": {
"name": "marqdo",
"version": "3.0.0-rc.4",
"markdown_profile": "marqdo.md.v1"
},
"project": {
"root_id": "sha256:68fe7f20571673eda2078779c82fb2457f109e6c31da95b8b91b0513acb0fe15",
"identity_kind": "workspace_snapshot",
"entry_module_id": "root:default::85-nested-loop-control.mq.md",
"lock_digest": "",
"manifest_digest": "",
"stdlib": {
"version": "0.2.0",
"digest": "sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7",
"instance_id": "std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7"
},
"extensions": []
},
"modules": [
{
"id": "root:default::85-nested-loop-control.mq.md",
"package_instance_id": "root:default",
"relative_path": "85-nested-loop-control.mq.md",
"source_digest": "f0d654a033937dd5ab963cb021a155e2e01f05fc3a865af9907ebabbbc5a9b24",
"source": "## @exec main\n\n`外 = 0`\n\n`合计 = 0`\n\n`while 外 < 3`\n\n`外 = 外 + 1`\n\n`内 = 0`\n\n`while 内 < 4`\n\n`内 = 内 + 1`\n\n`if 内 == 1`\n\n`continue`\n\n`else if 内 == 3`\n\n`break`\n\n`end`\n\n`合计 = 合计 + 外`\n\n`end`\n\n`if 外 == 2`\n\n`continue`\n\n`end`\n\n`合计 = 合计 + 10`\n\n`end`\n\n`return 合计`\n",
"document": {
"children": [
{
"children": [
{
"children": [],
"kind": "text",
"literal": "@exec main",
"span": {
"end": 13,
"start": 3
}
}
],
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"end": 13,
"start": 0
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "外 = 0",
"span": {
"end": 24,
"start": 15
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 24,
"start": 15
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "合计 = 0",
"span": {
"end": 38,
"start": 26
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 38,
"start": 26
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "while 外 < 3",
"span": {
"end": 55,
"start": 40
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 55,
"start": 40
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "外 = 外 + 1",
"span": {
"end": 72,
"start": 57
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 72,
"start": 57
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "内 = 0",
"span": {
"end": 83,
"start": 74
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 83,
"start": 74
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "while 内 < 4",
"span": {
"end": 100,
"start": 85
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 100,
"start": 85
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "内 = 内 + 1",
"span": {
"end": 117,
"start": 102
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 117,
"start": 102
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "if 内 == 1",
"span": {
"end": 132,
"start": 119
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 132,
"start": 119
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "continue",
"span": {
"end": 144,
"start": 134
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 144,
"start": 134
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "else if 内 == 3",
"span": {
"end": 164,
"start": 146
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 164,
"start": 146
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "break",
"span": {
"end": 173,
"start": 166
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 173,
"start": 166
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "end",
"span": {
"end": 180,
"start": 175
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 180,
"start": 175
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "合计 = 合计 + 外",
"span": {
"end": 205,
"start": 182
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 205,
"start": 182
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "end",
"span": {
"end": 212,
"start": 207
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 212,
"start": 207
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "if 外 == 2",
"span": {
"end": 227,
"start": 214
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 227,
"start": 214
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "continue",
"span": {
"end": 239,
"start": 229
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 239,
"start": 229
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "end",
"span": {
"end": 246,
"start": 241
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 246,
"start": 241
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "合计 = 合计 + 10",
"span": {
"end": 270,
"start": 248
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 270,
"start": 248
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "end",
"span": {
"end": 277,
"start": 272
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 277,
"start": 272
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "return 合计",
"span": {
"end": 294,
"start": 279
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 294,
"start": 279
}
}
],
"kind": "document",
"span": {
"end": 295,
"start": 0
}
},
"units": [
{
"id": "root:default::85-nested-loop-control.mq.md#",
"path": [],
"parent_id": null,
"kind": "root",
"name": "",
"level": 0,
"mode": "knowledge",
"mode_origin": "default",
"mode_source_unit_id": "root:default::85-nested-loop-control.mq.md#",
"heading_span": null,
"span": {
"start": 0,
"end": 295
},
"function": null
},
{
"id": "root:default::85-nested-loop-control.mq.md#main",
"path": [
"main"
],
"parent_id": "root:default::85-nested-loop-control.mq.md#",
"kind": "function",
"name": "main",
"level": 2,
"mode": "exec",
"mode_origin": "explicit",
"mode_source_unit_id": "root:default::85-nested-loop-control.mq.md#main",
"heading_span": {
"start": 0,
"end": 13
},
"span": {
"start": 0,
"end": 295
},
"function": "root:default::85-nested-loop-control.mq.md::main"
}
],
"anchors": [
{
"anchor": "main",
"unit_id": "root:default::85-nested-loop-control.mq.md#main"
}
],
"functions": [
{
"id": "root:default::85-nested-loop-control.mq.md::main",
"unit_id": "root:default::85-nested-loop-control.mq.md#main",
"local_name": "main",
"namespace": null,
"span": {
"start": 0,
"end": 294
},
"heading_span": {
"start": 0,
"end": 13
},
"signature": {
"kind": "inferred",
"params": []
},
"effects": [
"unknown"
],
"body": [
{
"kind": "assign",
"span": {
"end": 24,
"start": 15
},
"target": "外",
"value": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
}
},
{
"kind": "assign",
"span": {
"end": 38,
"start": 26
},
"target": "合计",
"value": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
}
},
{
"body": [
{
"kind": "assign",
"span": {
"end": 72,
"start": 57
},
"target": "外",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "外",
"span": {
"end": 67,
"start": 64
}
},
"op": "add",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "1"
},
"span": {
"end": 71,
"start": 64
}
}
},
{
"kind": "assign",
"span": {
"end": 83,
"start": 74
},
"target": "内",
"value": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "0"
}
},
{
"body": [
{
"kind": "assign",
"span": {
"end": 117,
"start": 102
},
"target": "内",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "内",
"span": {
"end": 112,
"start": 109
}
},
"op": "add",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "1"
},
"span": {
"end": 116,
"start": 109
}
}
},
{
"arms": [
{
"body": [
{
"kind": "continue",
"span": {
"end": 144,
"start": 134
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "内",
"span": {
"end": 126,
"start": 123
}
},
"op": "eq",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "1"
},
"span": {
"end": 131,
"start": 123
}
},
"condition_span": {
"end": 132,
"start": 119
},
"span": {
"end": 132,
"start": 119
}
},
{
"body": [
{
"kind": "break",
"span": {
"end": 173,
"start": 166
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "内",
"span": {
"end": 158,
"start": 155
}
},
"op": "eq",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "3"
},
"span": {
"end": 163,
"start": 155
}
},
"condition_span": {
"end": 164,
"start": 146
},
"span": {
"end": 164,
"start": 146
}
}
],
"kind": "branch",
"span": {
"end": 132,
"start": 119
}
},
{
"kind": "assign",
"span": {
"end": 205,
"start": 182
},
"target": "合计",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "合计",
"span": {
"end": 198,
"start": 192
}
},
"op": "add",
"right": {
"kind": "variable",
"name": "外",
"span": {
"end": 204,
"start": 201
}
},
"span": {
"end": 204,
"start": 192
}
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "内",
"span": {
"end": 95,
"start": 92
}
},
"op": "lt",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "4"
},
"span": {
"end": 99,
"start": 92
}
},
"condition_span": {
"end": 100,
"start": 85
},
"kind": "loop",
"span": {
"end": 100,
"start": 85
}
},
{
"arms": [
{
"body": [
{
"kind": "continue",
"span": {
"end": 239,
"start": 229
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "外",
"span": {
"end": 221,
"start": 218
}
},
"op": "eq",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "2"
},
"span": {
"end": 226,
"start": 218
}
},
"condition_span": {
"end": 227,
"start": 214
},
"span": {
"end": 227,
"start": 214
}
}
],
"kind": "branch",
"span": {
"end": 227,
"start": 214
}
},
{
"kind": "assign",
"span": {
"end": 270,
"start": 248
},
"target": "合计",
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "合计",
"span": {
"end": 264,
"start": 258
}
},
"op": "add",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "10"
},
"span": {
"end": 269,
"start": 258
}
}
}
],
"condition": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "外",
"span": {
"end": 50,
"start": 47
}
},
"op": "lt",
"right": {
"kind": "literal",
"span": {
"end": 0,
"start": 0
},
"type": "int",
"value": "3"
},
"span": {
"end": 54,
"start": 47
}
},
"condition_span": {
"end": 55,
"start": 40
},
"kind": "loop",
"span": {
"end": 55,
"start": 40
}
},
{
"kind": "return",
"span": {
"end": 294,
"start": 279
},
"value": {
"kind": "variable",
"name": "合计",
"span": {
"end": 293,
"start": 287
}
}
}
]
}
],
"imports": [],
"references": [],
"calls": [],
"resources": []
}
],
"diagnostics": []
}
+66
View File
@@ -0,0 +1,66 @@
{"kind":"stream.opened","payload":{"limits":{"max_observation_bytes":16777216,"max_observation_events":100000,"max_value_bytes":256},"observation":{"allow_text_values":false,"level":"structural","selected_parameters":[],"selected_variables":[],"values":false},"producer":{"name":"marqdo","version":"3.0.0-rc.4"}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":0}
{"kind":"run.started","payload":{"entry":"root:default::85-nested-loop-control.mq.md::main","mode":"project","source":{"analysis_digest":"sha256:9ed92f781c37d2560803e5a67d35c1d26cf37637d6bd435fe70856bb38d9cc72","root_id":"sha256:68fe7f20571673eda2078779c82fb2457f109e6c31da95b8b91b0513acb0fe15"},"started_unix_ms":1795713596382},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":1}
{"kind":"call.enter","payload":{"frame_id":"f1","function_id":"root:default::85-nested-loop-control.mq.md::main","module_id":"root:default::85-nested-loop-control.mq.md","parent_frame_id":null,"span":null},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":2}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":24,"start":15},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":3}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":38,"start":26},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":4}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":55,"start":40}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":5}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":72,"start":57},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":6}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":83,"start":74},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":7}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":8}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":9}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":10}
{"kind":"control.continue","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":144,"start":134}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":11}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":12}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":13}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":14}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":15}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":205,"start":182},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":16}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":17}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":18}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":19}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":20}
{"kind":"control.break","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":173,"start":166}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":21}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":227,"start":214}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":22}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":270,"start":248},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":23}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":55,"start":40}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":24}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":72,"start":57},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":25}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":83,"start":74},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":26}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":27}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":28}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":29}
{"kind":"control.continue","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":144,"start":134}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":30}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":31}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":32}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":33}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":34}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":205,"start":182},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":35}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":36}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":37}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":38}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":39}
{"kind":"control.break","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":173,"start":166}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":40}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":227,"start":214}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":41}
{"kind":"control.continue","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":239,"start":229}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":42}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":55,"start":40}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":43}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":72,"start":57},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":44}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":83,"start":74},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":45}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":46}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":47}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":48}
{"kind":"control.continue","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":144,"start":134}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":49}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":50}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":51}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":52}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":53}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":205,"start":182},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":54}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":55}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":56}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":57}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":58}
{"kind":"control.break","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":173,"start":166}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":59}
{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":227,"start":214}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":60}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":270,"start":248},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":61}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":55,"start":40}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":62}
{"kind":"return","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":294,"start":279},"value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":63}
{"kind":"call.exit","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":null,"status":"return"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":64}
{"kind":"run.completed","payload":{"status":"ok","value":{"decimal":"26","type":"int"},"value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":65}
@@ -0,0 +1 @@
{"events":[{"kind":"stream.opened","payload":{"limits":{"max_observation_bytes":16777216,"max_observation_events":100000,"max_value_bytes":256},"observation":{"allow_text_values":false,"level":"structural","selected_parameters":[],"selected_variables":[],"values":false},"producer":{"name":"marqdo","version":"3.0.0-rc.4"}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":0},{"kind":"run.started","payload":{"entry":"root:default::85-nested-loop-control.mq.md::main","mode":"project","source":{"analysis_digest":"sha256:9ed92f781c37d2560803e5a67d35c1d26cf37637d6bd435fe70856bb38d9cc72","root_id":"sha256:68fe7f20571673eda2078779c82fb2457f109e6c31da95b8b91b0513acb0fe15"},"started_unix_ms":1795713596382},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":1},{"kind":"call.enter","payload":{"frame_id":"f1","function_id":"root:default::85-nested-loop-control.mq.md::main","module_id":"root:default::85-nested-loop-control.mq.md","parent_frame_id":null,"span":null},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":2},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":24,"start":15},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":3},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":38,"start":26},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":4},{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":55,"start":40}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":5},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"外","span":{"end":72,"start":57},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":6},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":83,"start":74},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":7},{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":8},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":9},{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":true,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":10},{"kind":"control.continue","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":144,"start":134}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":11},{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","span":{"end":100,"start":85}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":12},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"内","span":{"end":117,"start":102},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":13},{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":132,"start":119}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":14},{"kind":"branch.eval","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","result":false,"span":{"end":164,"start":146}},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":15},{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::85-nested-loop-control.mq.md","name":"合计","span":{"end":205,"start":182},"value_state":"not_requested","value_type":"Int"},"run_id":"20-1795713596362568889","schema":"marqdo.observation","schema_version":1,"seq":16},{"kind":"loop.iteration","payload":{"decisiLine truncated
+1
View File
@@ -0,0 +1 @@
{"events":[{"kind":"stream.opened","payload":{"limits":{"max_observation_bytes":16777216,"max_observation_events":100000,"max_value_bytes":256},"observation":{"allow_text_values":false,"level":"structural","selected_parameters":[],"selected_variables":[],"values":false},"producer":{"name":"marqdo","version":"3.0.0-rc.4"}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":0},{"kind":"run.started","payload":{"entry":"root:default::basic.mq.md::main","mode":"project","source":{"analysis_digest":"sha256:3e64eee5ba9686a578b5d5789075010d87177a727f7e54ac19fd61c99d7519d5","root_id":"sha256:0403dd889a7d44f0f3b2b823530c9301062d5ade2cd63329d3803abad55841f0"},"started_unix_ms":1795713570722},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":1},{"kind":"call.enter","payload":{"frame_id":"f1","function_id":"root:default::basic.mq.md::Execution Events fixture A.main","module_id":"root:default::basic.mq.md","parent_frame_id":null,"span":null},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":2},{"kind":"call.enter","payload":{"frame_id":"f2","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md::io.写值","module_id":"root:default::basic.mq.md","parent_frame_id":"f1","span":{"end":72,"start":57}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":3},{"kind":"parameter.observed","payload":{"frame_id":"f2","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","name":"值","source":"provided","span":{"end":315,"start":312},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":4},{"kind":"call.enter","payload":{"frame_id":"f3","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md::format.显示","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","parent_frame_id":"f2","span":{"end":422,"start":404}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":5},{"kind":"parameter.observed","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"值","source":"provided","span":{"end":489,"start":486},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":6},{"kind":"variable.assigned","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"类别","span":{"end":701,"start":677},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":7},{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":724,"start":703}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":8},{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":749,"start":743}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":9},{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":771,"start":750}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":10},{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":796,"start":790}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":11},{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":818,"start":797}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":12},{"kind":"return","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":832,"start":820},"value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":13},{"kind":"call.exit","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::ioLine truncated
+316
View File
@@ -0,0 +1,316 @@
{"kind":"stream.opened","payload":{"limits":{"max_observation_bytes":16777216,"max_observation_events":100000,"max_value_bytes":256},"observation":{"allow_text_values":false,"level":"structural","selected_parameters":[],"selected_variables":[],"values":false},"producer":{"name":"marqdo","version":"3.0.0-rc.4"}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":0}
{"kind":"run.started","payload":{"entry":"root:default::basic.mq.md::main","mode":"project","source":{"analysis_digest":"sha256:3e64eee5ba9686a578b5d5789075010d87177a727f7e54ac19fd61c99d7519d5","root_id":"sha256:0403dd889a7d44f0f3b2b823530c9301062d5ade2cd63329d3803abad55841f0"},"started_unix_ms":1795713570722},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":1}
{"kind":"call.enter","payload":{"frame_id":"f1","function_id":"root:default::basic.mq.md::Execution Events fixture A.main","module_id":"root:default::basic.mq.md","parent_frame_id":null,"span":null},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":2}
{"kind":"call.enter","payload":{"frame_id":"f2","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md::io.写值","module_id":"root:default::basic.mq.md","parent_frame_id":"f1","span":{"end":72,"start":57}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":3}
{"kind":"parameter.observed","payload":{"frame_id":"f2","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","name":"值","source":"provided","span":{"end":315,"start":312},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":4}
{"kind":"call.enter","payload":{"frame_id":"f3","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md::format.显示","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","parent_frame_id":"f2","span":{"end":422,"start":404}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":5}
{"kind":"parameter.observed","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"值","source":"provided","span":{"end":489,"start":486},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":6}
{"kind":"variable.assigned","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"类别","span":{"end":701,"start":677},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":7}
{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":724,"start":703}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":8}
{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":749,"start":743}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":9}
{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":771,"start":750}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":10}
{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":796,"start":790}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":11}
{"kind":"branch.eval","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":818,"start":797}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":12}
{"kind":"return","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":832,"start":820},"value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":13}
{"kind":"call.exit","payload":{"frame_id":"f3","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":422,"start":404},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":14}
{"kind":"call.enter","payload":{"frame_id":"f4","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.写文本","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","parent_frame_id":"f2","span":{"end":430,"start":387}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":15}
{"kind":"parameter.observed","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"文本","source":"provided","span":{"end":1178,"start":1172},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":16}
{"kind":"call.enter","payload":{"frame_id":"f5","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md::format.字节长度","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f4","span":{"end":1418,"start":1391}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":17}
{"kind":"parameter.observed","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"文本","source":"provided","span":{"end":46,"start":40},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":18}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"点","span":{"end":84,"start":51},"value_state":"not_requested","value_type":"List"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":19}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":103,"start":86},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":20}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":119,"start":105},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":21}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":22}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":23}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":24}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":25}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":26}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":27}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":28}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":29}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":30}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":31}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":32}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":33}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":34}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":35}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":36}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":37}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":38}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":39}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":40}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":41}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":42}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":43}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":44}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":45}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":46}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":47}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":48}
{"kind":"branch.eval","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":49}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":50}
{"kind":"variable.assigned","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":51}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":52}
{"kind":"return","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":466,"start":448},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":53}
{"kind":"call.exit","payload":{"frame_id":"f5","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1418,"start":1391},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":54}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节数","span":{"end":1420,"start":1377},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":55}
{"kind":"call.enter","payload":{"frame_id":"f6","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.页数","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f4","span":{"end":1461,"start":1444}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":56}
{"kind":"parameter.observed","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节","source":"provided","span":{"end":114,"start":108},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":57}
{"kind":"variable.assigned","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"页","span":{"end":154,"start":119},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":58}
{"kind":"branch.eval","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":169,"start":156}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":59}
{"kind":"branch.eval","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":189,"start":183}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":60}
{"kind":"branch.eval","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":199,"start":190}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":61}
{"kind":"return","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":213,"start":201},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":62}
{"kind":"call.exit","payload":{"frame_id":"f6","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1461,"start":1444},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":63}
{"kind":"call.enter","payload":{"frame_id":"f7","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.页数","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f4","span":{"end":1480,"start":1463}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":64}
{"kind":"parameter.observed","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节","source":"provided","span":{"end":114,"start":108},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":65}
{"kind":"variable.assigned","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"页","span":{"end":154,"start":119},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":66}
{"kind":"branch.eval","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":169,"start":156}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":67}
{"kind":"branch.eval","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":189,"start":183}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":68}
{"kind":"branch.eval","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":199,"start":190}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":69}
{"kind":"return","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":213,"start":201},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":70}
{"kind":"call.exit","payload":{"frame_id":"f7","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1480,"start":1463},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":71}
{"kind":"effect","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"memory.new","result_code":"ok","span":{"end":1481,"start":1433}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":72}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"内存","span":{"end":1483,"start":1422},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":73}
{"kind":"call.enter","payload":{"frame_id":"f8","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md::utf8.编码","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f4","span":{"end":1526,"start":1496}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":74}
{"kind":"parameter.observed","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"文本","source":"provided","span":{"end":260,"start":254},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":75}
{"kind":"parameter.observed","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"内存","source":"provided","span":{"end":268,"start":261},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":76}
{"kind":"parameter.observed","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"基址","source":"provided","span":{"end":276,"start":269},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":77}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"点","span":{"end":466,"start":433},"value_state":"not_requested","value_type":"List"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":78}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":482,"start":468},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":79}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":498,"start":484},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":80}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":81}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":82}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":83}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":84}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":85}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":86}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":87}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":88}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":89}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":90}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":91}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":92}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":93}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":94}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":95}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":96}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":97}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":98}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":99}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":100}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":101}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":102}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":103}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":104}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":105}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":106}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":107}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":108}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":109}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":110}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":111}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":112}
{"kind":"branch.eval","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":113}
{"kind":"effect","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":114}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":115}
{"kind":"variable.assigned","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":116}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":117}
{"kind":"return","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":1370,"start":1355},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":118}
{"kind":"call.exit","payload":{"frame_id":"f8","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1526,"start":1496},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":119}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"长度","span":{"end":1528,"start":1485},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":120}
{"kind":"effect","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.open","result_code":"ok","span":{"end":1581,"start":1538}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":121}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"流","span":{"end":1583,"start":1530},"value_state":"not_requested","value_type":"Resource"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":122}
{"kind":"call.enter","payload":{"frame_id":"f9","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.写全部","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f4","span":{"end":1632,"start":1599}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":123}
{"kind":"parameter.observed","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"流","source":"provided","span":{"end":251,"start":248},"value_state":"not_requested","value_type":"Resource"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":124}
{"kind":"parameter.observed","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"内存","source":"provided","span":{"end":259,"start":252},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":125}
{"kind":"parameter.observed","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"起点","source":"provided","span":{"end":267,"start":260},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":126}
{"kind":"parameter.observed","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"长度","source":"provided","span":{"end":275,"start":268},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":127}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"已写","span":{"end":447,"start":433},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":128}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"失败","span":{"end":467,"start":449},"value_state":"not_requested","value_type":"Bool"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":129}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"本次","span":{"end":511,"start":469},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":130}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"错误结果","span":{"end":610,"start":513},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":131}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":635,"start":612}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":132}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"剩余","span":{"end":665,"start":637},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":133}
{"kind":"stdout.chunk","payload":{"byte_count":6,"data_base64":"U1RBUlQK","encoding":"base64"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":134}
{"kind":"effect","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.write","result_code":"ok","span":{"end":730,"start":678}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":135}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"本次","span":{"end":732,"start":667},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":136}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":752,"start":734}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":137}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":827,"start":821}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":138}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":856,"start":828}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":139}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":904,"start":898}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":140}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":914,"start":905}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":141}
{"kind":"variable.assigned","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"已写","span":{"end":956,"start":916},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":142}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":635,"start":612}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":143}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":993,"start":982}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":144}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1024,"start":1018}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":145}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1045,"start":1025}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":146}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1076,"start":1070}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":147}
{"kind":"branch.eval","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1086,"start":1077}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":148}
{"kind":"return","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1131,"start":1088},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":149}
{"kind":"call.exit","payload":{"frame_id":"f9","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1632,"start":1599},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":150}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"写结果","span":{"end":1634,"start":1585},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":151}
{"kind":"effect","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.close","result_code":"ok","span":{"end":1666,"start":1647}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":152}
{"kind":"variable.assigned","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"关闭","span":{"end":1668,"start":1636},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":153}
{"kind":"branch.eval","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1691,"start":1670}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":154}
{"kind":"branch.eval","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1719,"start":1713}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":155}
{"kind":"branch.eval","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1738,"start":1720}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":156}
{"kind":"branch.eval","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1763,"start":1757}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":157}
{"kind":"branch.eval","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1773,"start":1764}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":158}
{"kind":"return","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1818,"start":1775},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":159}
{"kind":"call.exit","payload":{"frame_id":"f4","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":430,"start":387},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":160}
{"kind":"return","payload":{"frame_id":"f2","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":431,"start":379},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":161}
{"kind":"call.exit","payload":{"frame_id":"f2","module_id":"root:default::basic.mq.md","span":{"end":72,"start":57},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":162}
{"kind":"variable.assigned","payload":{"frame_id":"f1","module_id":"root:default::basic.mq.md","name":"n","span":{"end":83,"start":75},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":163}
{"kind":"call.enter","payload":{"frame_id":"f10","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md::io.写值","module_id":"root:default::basic.mq.md","parent_frame_id":"f1","span":{"end":100,"start":86}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":164}
{"kind":"parameter.observed","payload":{"frame_id":"f10","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","name":"值","source":"provided","span":{"end":315,"start":312},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":165}
{"kind":"call.enter","payload":{"frame_id":"f11","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md::format.显示","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","parent_frame_id":"f10","span":{"end":422,"start":404}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":166}
{"kind":"parameter.observed","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"值","source":"provided","span":{"end":489,"start":486},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":167}
{"kind":"variable.assigned","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"类别","span":{"end":701,"start":677},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":168}
{"kind":"branch.eval","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":724,"start":703}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":169}
{"kind":"branch.eval","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":749,"start":743}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":170}
{"kind":"branch.eval","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":false,"span":{"end":771,"start":750}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":171}
{"kind":"branch.eval","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":796,"start":790}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":172}
{"kind":"branch.eval","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":818,"start":797}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":173}
{"kind":"return","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":832,"start":820},"value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":174}
{"kind":"call.exit","payload":{"frame_id":"f11","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":422,"start":404},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":175}
{"kind":"call.enter","payload":{"frame_id":"f12","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.写文本","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","parent_frame_id":"f10","span":{"end":430,"start":387}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":176}
{"kind":"parameter.observed","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"文本","source":"provided","span":{"end":1178,"start":1172},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":177}
{"kind":"call.enter","payload":{"frame_id":"f13","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md::format.字节长度","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f12","span":{"end":1418,"start":1391}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":178}
{"kind":"parameter.observed","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"文本","source":"provided","span":{"end":46,"start":40},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":179}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"点","span":{"end":84,"start":51},"value_state":"not_requested","value_type":"List"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":180}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":103,"start":86},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":181}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":119,"start":105},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":182}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":183}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":184}
{"kind":"branch.eval","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":185}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":186}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":187}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":188}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":189}
{"kind":"branch.eval","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":190}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":191}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":192}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":193}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":194}
{"kind":"branch.eval","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":195}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":196}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":197}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":198}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":199}
{"kind":"branch.eval","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":200}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":201}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":202}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":203}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"码点","span":{"end":175,"start":151},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":204}
{"kind":"branch.eval","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","result":true,"span":{"end":194,"start":177}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":205}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"总字节","span":{"end":225,"start":196},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":206}
{"kind":"variable.assigned","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","name":"下标","span":{"end":440,"start":417},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":207}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":149,"start":121}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":208}
{"kind":"return","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::format.mq.md","span":{"end":466,"start":448},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":209}
{"kind":"call.exit","payload":{"frame_id":"f13","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1418,"start":1391},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":210}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节数","span":{"end":1420,"start":1377},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":211}
{"kind":"call.enter","payload":{"frame_id":"f14","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.页数","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f12","span":{"end":1461,"start":1444}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":212}
{"kind":"parameter.observed","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节","source":"provided","span":{"end":114,"start":108},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":213}
{"kind":"variable.assigned","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"页","span":{"end":154,"start":119},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":214}
{"kind":"branch.eval","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":169,"start":156}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":215}
{"kind":"branch.eval","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":189,"start":183}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":216}
{"kind":"branch.eval","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":199,"start":190}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":217}
{"kind":"return","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":213,"start":201},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":218}
{"kind":"call.exit","payload":{"frame_id":"f14","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1461,"start":1444},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":219}
{"kind":"call.enter","payload":{"frame_id":"f15","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.页数","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f12","span":{"end":1480,"start":1463}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":220}
{"kind":"parameter.observed","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"字节","source":"provided","span":{"end":114,"start":108},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":221}
{"kind":"variable.assigned","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"页","span":{"end":154,"start":119},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":222}
{"kind":"branch.eval","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":169,"start":156}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":223}
{"kind":"branch.eval","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":189,"start":183}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":224}
{"kind":"branch.eval","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":199,"start":190}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":225}
{"kind":"return","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":213,"start":201},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":226}
{"kind":"call.exit","payload":{"frame_id":"f15","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1480,"start":1463},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":227}
{"kind":"effect","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"memory.new","result_code":"ok","span":{"end":1481,"start":1433}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":228}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"内存","span":{"end":1483,"start":1422},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":229}
{"kind":"call.enter","payload":{"frame_id":"f16","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md::utf8.编码","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f12","span":{"end":1526,"start":1496}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":230}
{"kind":"parameter.observed","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"文本","source":"provided","span":{"end":260,"start":254},"value_state":"not_requested","value_type":"Text"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":231}
{"kind":"parameter.observed","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"内存","source":"provided","span":{"end":268,"start":261},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":232}
{"kind":"parameter.observed","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"基址","source":"provided","span":{"end":276,"start":269},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":233}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"点","span":{"end":466,"start":433},"value_state":"not_requested","value_type":"List"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":234}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":482,"start":468},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":235}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":498,"start":484},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":236}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":237}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":238}
{"kind":"branch.eval","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":239}
{"kind":"effect","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":240}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":241}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":242}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":243}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":244}
{"kind":"branch.eval","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":245}
{"kind":"effect","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":246}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":247}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":248}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":249}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":250}
{"kind":"branch.eval","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":251}
{"kind":"effect","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":252}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":253}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":254}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":255}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":256}
{"kind":"branch.eval","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":257}
{"kind":"effect","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":258}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":259}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":260}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":261}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"码点","span":{"end":554,"start":530},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":262}
{"kind":"branch.eval","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","result":true,"span":{"end":573,"start":556}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":263}
{"kind":"effect","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","operation":"memory.write","result_code":"ok","span":{"end":601,"start":578}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":264}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"偏移","span":{"end":638,"start":615},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":265}
{"kind":"variable.assigned","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","name":"下标","span":{"end":1347,"start":1324},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":266}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":528,"start":500}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":267}
{"kind":"return","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::text/utf8.mq.md","span":{"end":1370,"start":1355},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":268}
{"kind":"call.exit","payload":{"frame_id":"f16","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1526,"start":1496},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":269}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"长度","span":{"end":1528,"start":1485},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":270}
{"kind":"effect","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.open","result_code":"ok","span":{"end":1581,"start":1538}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":271}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"流","span":{"end":1583,"start":1530},"value_state":"not_requested","value_type":"Resource"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":272}
{"kind":"call.enter","payload":{"frame_id":"f17","function_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md::stream.写全部","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","parent_frame_id":"f12","span":{"end":1632,"start":1599}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":273}
{"kind":"parameter.observed","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"流","source":"provided","span":{"end":251,"start":248},"value_state":"not_requested","value_type":"Resource"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":274}
{"kind":"parameter.observed","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"内存","source":"provided","span":{"end":259,"start":252},"value_state":"not_requested","value_type":"Memory"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":275}
{"kind":"parameter.observed","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"起点","source":"provided","span":{"end":267,"start":260},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":276}
{"kind":"parameter.observed","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"长度","source":"provided","span":{"end":275,"start":268},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":277}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"已写","span":{"end":447,"start":433},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":278}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"失败","span":{"end":467,"start":449},"value_state":"not_requested","value_type":"Bool"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":279}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"本次","span":{"end":511,"start":469},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":280}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"错误结果","span":{"end":610,"start":513},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":281}
{"kind":"loop.iteration","payload":{"decision":"continue","frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":635,"start":612}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":282}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"剩余","span":{"end":665,"start":637},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":283}
{"kind":"stdout.chunk","payload":{"byte_count":5,"data_base64":"RE9ORQo=","encoding":"base64"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":284}
{"kind":"effect","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.write","result_code":"ok","span":{"end":730,"start":678}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":285}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"本次","span":{"end":732,"start":667},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":286}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":752,"start":734}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":287}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":827,"start":821}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":288}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":856,"start":828}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":289}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":904,"start":898}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":290}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":914,"start":905}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":291}
{"kind":"variable.assigned","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"已写","span":{"end":956,"start":916},"value_state":"not_requested","value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":292}
{"kind":"loop.iteration","payload":{"decision":"exit","frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":635,"start":612}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":293}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":993,"start":982}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":294}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1024,"start":1018}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":295}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1045,"start":1025}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":296}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1076,"start":1070}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":297}
{"kind":"branch.eval","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1086,"start":1077}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":298}
{"kind":"return","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1131,"start":1088},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":299}
{"kind":"call.exit","payload":{"frame_id":"f17","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1632,"start":1599},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":300}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"写结果","span":{"end":1634,"start":1585},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":301}
{"kind":"effect","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","operation":"resource.close","result_code":"ok","span":{"end":1666,"start":1647}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":302}
{"kind":"variable.assigned","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","name":"关闭","span":{"end":1668,"start":1636},"value_state":"not_requested","value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":303}
{"kind":"branch.eval","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1691,"start":1670}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":304}
{"kind":"branch.eval","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1719,"start":1713}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":305}
{"kind":"branch.eval","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":false,"span":{"end":1738,"start":1720}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":306}
{"kind":"branch.eval","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1763,"start":1757}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":307}
{"kind":"branch.eval","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","result":true,"span":{"end":1773,"start":1764}},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":308}
{"kind":"return","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io/stream.mq.md","span":{"end":1818,"start":1775},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":309}
{"kind":"call.exit","payload":{"frame_id":"f12","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":430,"start":387},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":310}
{"kind":"return","payload":{"frame_id":"f10","module_id":"std:marqdo-stdlib@0.2.0#db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7::io.mq.md","span":{"end":431,"start":379},"value_type":"Map"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":311}
{"kind":"call.exit","payload":{"frame_id":"f10","module_id":"root:default::basic.mq.md","span":{"end":100,"start":86},"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":312}
{"kind":"return","payload":{"frame_id":"f1","module_id":"root:default::basic.mq.md","span":{"end":113,"start":103},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":313}
{"kind":"call.exit","payload":{"frame_id":"f1","module_id":"root:default::basic.mq.md","span":null,"status":"return"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":314}
{"kind":"run.completed","payload":{"status":"ok","value":{"decimal":"10","type":"int"},"value_type":"Int"},"run_id":"9-1795713570566476436","schema":"marqdo.observation","schema_version":1,"seq":315}
+67 -32
View File
@@ -12,6 +12,8 @@ jobs:
test:
name: fmt + clippy + test (Linux x86_64)
runs-on: ubuntu-latest
env:
MARQDO_TEST_STDLIB_BUNDLE: ${{ github.workspace }}/target/ecosystem-stdlib
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
@@ -19,6 +21,10 @@ jobs:
components: rustfmt, clippy
- name: Rust cache
uses: Swatinem/rust-cache@v2
- name: Materialize the pinned ecosystem stdlib Bundle
run: python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- name: Verify the pinned stdlib Bundle
run: python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib
- name: Formatting
run: cargo fmt --all -- --check
- name: Clippy
@@ -39,9 +45,15 @@ jobs:
run: cargo test -p marqdo-cli --test docs_consistency
- name: Architecture boundaries
run: cargo test -p marqdo-cli --test architecture_boundaries
- name: Dependency-direction gate (Engine / Host Contract / Native Host)
run: python3 tools/ci/check_dependency_boundaries.py
- name: Engine independence and CLI differential execution
run: python3 tools/ci/check_engine_boundary.py
- name: Plugin SDK real consumption
run: python3 tools/ci/check_plugin_sdk.py
- name: CI evidence tool tests
run: python3 -m unittest discover -s tools/ci -p "test_*.py"
- name: Whole stdlib product tests
- name: Whole stdlib product tests (explicit pinned Bundle)
run: cargo test -p marqdo-cli --test stdlib_product
- name: Validate public JSON schemas
run: |
@@ -61,16 +73,16 @@ jobs:
./target/debug/marqdo check examples/multi-module/index.mq.md --refs \
--emit /tmp/marqdo-analysis.json
./target/debug/marqdo run examples/multi-module/index.mq.md \
--trace-file /tmp/marqdo-analysis-trace.json
--observation-file /tmp/marqdo-observation.json
python3 tests/consumers/analysis_consumer.py /tmp/marqdo-analysis.json
python3 tests/consumers/trace_consumer.py \
/tmp/marqdo-analysis.json /tmp/marqdo-analysis-trace.json
python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/marqdo-observation.json --analysis /tmp/marqdo-analysis.json
./target/debug/marqdo run examples/hello.mq.md \
--trace-file /tmp/marqdo-trace.json
--observation-file /tmp/marqdo-hello-observation.json
python3 - <<'PY'
import json
json.load(open("/tmp/marqdo-trace.json"))
print("trace parses")
json.load(open("/tmp/marqdo-hello-observation.json"))
print("snapshot parses")
PY
./target/debug/marqdo run examples/packages-multi-version/index.mq.md
./target/debug/marqdo run examples/kernel-mock/demo.mq.md \
@@ -93,6 +105,16 @@ jobs:
--trust-native-plugin \
--allow-plugin demo.solver
independent-build:
name: independent CLI/worker build (no stdlib source)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build from a copy without stdlib and run a language-only program
run: python3 tools/ci/independent_build.py
schema:
name: schema instance validation + consumers
runs-on: ubuntu-latest
@@ -106,27 +128,36 @@ jobs:
run: |
cargo build -p marqdo-cli
./target/debug/marqdo check examples/multi-module/index.mq.md --refs \
--emit /tmp/analysis-v2.json
--emit /tmp/analysis-simple.json
./target/debug/marqdo run examples/multi-module/index.mq.md \
--trace-file /tmp/trace-v2.json
--observation-file /tmp/observation.json
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v2.json /tmp/trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json
python3 tests/consumers/trace_consumer.py \
/tmp/analysis-v2.json /tmp/trace-v2.json
/tmp/analysis-simple.json /tmp/observation.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-simple.json
python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/observation.json --analysis /tmp/analysis-simple.json
./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md \
--emit /tmp/analysis-v3.json
--emit /tmp/analysis-control.json
./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md \
--event-stream jsonl --trace-file /tmp/control-trace-v2.json > /tmp/control-events.jsonl
--output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v3.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_v3_consumer.py /tmp/analysis-v3.json
if python3 tests/consumers/analysis_consumer.py /tmp/analysis-v3.json; then
echo "Analysis v2 consumer accepted a v3 document" >&2
/tmp/analysis-control.json /tmp/control-observation.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_consumer.py /tmp/analysis-control.json --require-transfers
python3 tests/consumers/observation_consumer.py --snapshot /tmp/control-observation.json --analysis /tmp/analysis-control.json
python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl \
--analysis /tmp/analysis-control.json --validate-schema
python3 - <<'PY'
import json, pathlib
events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()]
snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_bytes())
assert snapshot["events"] == events
PY
cp /tmp/analysis-control.json /tmp/analysis-stale.json
printf ' ' >> /tmp/analysis-stale.json
if python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl \
--analysis /tmp/analysis-stale.json; then
exit 1
fi
python3 tests/consumers/trace_consumer.py /tmp/analysis-v3.json /tmp/control-trace-v2.json
python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl
cross-platform:
name: runtime contract (${{ matrix.os }})
@@ -158,7 +189,7 @@ jobs:
workspace-tests.log "Workspace tests on ${{ matrix.os }}"
fi
exit "$status"
- name: Portable CLI, analysis and trace smoke
- name: Portable CLI, Analysis and Observation smoke
shell: bash
run: |
set -e
@@ -166,9 +197,9 @@ jobs:
--refs --emit /tmp/marqdo-portable-analysis.json
python3 tests/consumers/analysis_consumer.py /tmp/marqdo-portable-analysis.json
cargo run -q -p marqdo-cli -- run examples/multi-module/index.mq.md \
--trace-file /tmp/marqdo-portable-trace.json
python3 tests/consumers/trace_consumer.py \
/tmp/marqdo-portable-analysis.json /tmp/marqdo-portable-trace.json
--observation-file /tmp/marqdo-portable-observation.json
python3 tests/consumers/observation_consumer.py --snapshot \
/tmp/marqdo-portable-observation.json --analysis /tmp/marqdo-portable-analysis.json
- name: Strict isolation is unavailable and must fail closed
shell: bash
run: |
@@ -184,16 +215,16 @@ jobs:
run: |
set -euo pipefail
set +e
json=$(cargo run -q -p marqdo-cli -- run examples/hello.mq.md --mode strict --json)
json=$(cargo run -q -p marqdo-cli -- run examples/hello.mq.md --mode strict --output json)
code=$?
set -e
test "$code" -eq 1
JSON_DOC="$json" python3 - <<'PY'
import json, os
document = json.loads(os.environ["JSON_DOC"])
assert document["success"] is False, document
assert document["command"] == "run", document
assert document["code"] == "strict.probe_unavailable", document
assert document["schema"] == "marqdo.observation", document
assert document["run"]["status"] == "rejected", document
assert document["events"][-1]["payload"]["error"]["code"] == "strict.probe_unavailable", document
PY
frozen-extensions:
@@ -205,6 +236,8 @@ jobs:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Materialize the pinned ecosystem stdlib Bundle
run: python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- name: Build and check the frozen archive
shell: bash
run: |
@@ -212,7 +245,8 @@ jobs:
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version" \
--stdlib-dir target/ecosystem-stdlib --bundle-pin tools/stdlib/bundle-pin.json
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
- uses: actions/upload-artifact@v4
@@ -230,7 +264,7 @@ jobs:
release-evidence:
name: release evidence manifest
needs: [test, schema, cross-platform, frozen-extensions]
needs: [test, schema, cross-platform, frozen-extensions, independent-build]
if: always()
runs-on: ubuntu-latest
steps:
@@ -243,6 +277,7 @@ jobs:
LINUX_RESULT: ${{ needs.test.result }}
SCHEMA_RESULT: ${{ needs.schema.result }}
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
INDEPENDENT_RESULT: ${{ needs.independent-build.result }}
run: |
set -euo pipefail
state() {
@@ -253,7 +288,7 @@ jobs:
esac
}
linux="$(state "$LINUX_RESULT")"
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ] || [ "$(state "$INDEPENDENT_RESULT")" != "PASS" ]; then
linux="FAIL"
fi
python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \
+9
View File
@@ -37,3 +37,12 @@ __pycache__/
*.pyc
.perf-out-*
.perf-err-*
# Independent consumer/fixture build outputs and the local scratch dir
/tests/embedding/target/
/tests/sdk-plugin/target/
/.tmp/
# Accidental curl/test capture files
/out
/log.txt
+38 -19
View File
@@ -5,39 +5,55 @@ when:
event: [push, pull_request]
steps:
# Fast contract lane: build the two shipped binaries and exercise the public
# Analysis/Observation contracts through the real CLI plus independent Python
# consumers. Kept separate from the Rust lane so a protocol break surfaces in
# minutes instead of waiting for the cross-target toolchain packages.
contract:
image: rust:1.100-bookworm
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git python3 python3-jsonschema
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker
- python3 tools/ci/check_dependency_boundaries.py
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" bash tools/ci/contract_lane.sh
test:
image: rust:1.100-bookworm
commands:
- rustup component add clippy rustfmt
- apt-get update
- apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
- apt-get install -y --no-install-recommends curl ca-certificates git python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y --no-install-recommends nodejs
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
# The provider CLI tests resolve a real provider worker next to the CLI
# Provider CLI tests resolve a real provider worker next to the CLI
# binary. Build it once so the test harness does not need a nested build.
- cargo build --locked -p marqdo-provider-worker
- cargo test --workspace --locked
# Execution Events v1 black-box contract: a released-binary-shaped run
# validated by the independent Python consumer and the public schema.
- cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl
- python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
- ./target/debug/marqdo check examples/control-flow.mq.md --emit /tmp/control-analysis.json
- ./target/debug/marqdo run examples/control-flow.mq.md --event-stream jsonl --trace-file /tmp/control-trace.json > /tmp/control-events.jsonl
- python3 tests/consumers/analysis_v3_consumer.py /tmp/control-analysis.json
- python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-trace.json examples/tool-unknown-name/tool.json
- python3 tests/consumers/trace_consumer.py /tmp/control-analysis.json /tmp/control-trace.json
- python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl
- cargo test -p marqdo-cli --test docs_consistency
- cargo test -p marqdo-cli --test architecture_boundaries
- python3 -m unittest discover -s tools/ci -p "test_*.py"
- cargo test -p marqdo-cli --test stdlib_product
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" cargo test --workspace --locked
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" cargo test -p marqdo-cli --test docs_consistency
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" cargo test -p marqdo-cli --test architecture_boundaries
- python3 tools/ci/check_dependency_boundaries.py
- python3 tools/ci/check_engine_boundary.py
- python3 tools/ci/check_plugin_sdk.py
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" python3 -m unittest discover -s tools/ci -p "test_*.py"
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib" cargo test -p marqdo-cli --test stdlib_product
# Windows compile gate: runtime lanes are native on GitHub; this catches
# cfg/compile regressions on the Linux CI without a Windows runner.
- rustup target add x86_64-pc-windows-gnu
- cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
independent-build:
image: rust:1.100-bookworm
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git python3
- python3 tools/ci/independent_build.py
minimum-rust:
image: rust:1.89-bookworm
commands:
@@ -47,7 +63,7 @@ steps:
build:
image: rust:1.100-bookworm
depends_on: [test, minimum-rust]
depends_on: [test, minimum-rust, contract]
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 python3-jsonschema build-essential
@@ -55,13 +71,16 @@ steps:
# only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- test -x target/release/marqdo-provider-worker
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib
# Build the deterministic archive from this exact commit and cold-install
# smoke-test it; the package script refuses a dirty tree or wrong SHA.
- |
set -eu
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" \
--stdlib-dir target/ecosystem-stdlib --bundle-pin tools/stdlib/bundle-pin.json
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
cat dist/frozen-extension-evidence.json
+6 -2
View File
@@ -10,6 +10,8 @@ steps:
commands:
- apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
- python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- |
set -eu
@@ -22,7 +24,8 @@ steps:
(cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli)
version="$(target/release/marqdo --version | cut -d ' ' -f 2)"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" \
--stdlib-dir target/ecosystem-stdlib --bundle-pin tools/stdlib/bundle-pin.json --out-dir "$perf_dir"
archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
tar -xzf "$archive" -C "$perf_dir"
@@ -37,7 +40,8 @@ steps:
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" \
--stdlib-dir "$candidate/stdlib" --warmups 5 --samples 20 \
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null
python3 - <<'PY'
+27 -13
View File
@@ -1,19 +1,20 @@
# Marqdo CLI — Agent / Contributor Operating Rules
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative.
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/architecture/CURRENT.md` (the single current architecture overview, including the Engine / Host Contract / Native Host map), [ADR-0071](docs/adr/0071-engine-host-contract-boundary.md) (boundary rules and keep-in-workspace decision), `docs/STATUS.md` (what is actually implemented), the relevant `spec/` files, `docs/adr/` for decisions at their date, the developer entry point `docs/developers/README.md`, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation, legacy Marqdo syntax, historical planning document or old architecture gate is authoritative.
For next-phase work, the authoritative release policy for the current
`3.0.0-beta.1` line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates,
REL-01..REL-05, version axes, LTS conditions). `docs/STABLE_RELEASE_IMPLEMENTATION.md`
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`
(historical stabilization spec, baseline `0adebe4`), `docs/NEXT_PHASE_IMPLEMENTATION.md`
(M0.6 plan), `docs/EXTENSIBILITY_AUDIT.md` (E01–E16), `COMPATIBILITY.md` and
`docs/security-gate.md`. Older plans are historical input; the 3.0 prerelease plan is authoritative for
current release decisions, and the stable-release spec applies only when the
project moves from beta to stable.
None describes implemented behavior; re-check against HEAD and tests. `strict`
remains fail-closed until G-C passes.
3.0 prerelease line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates,
REL-01..REL-05, version axes, LTS conditions). The current architecture and
dependency direction are owned by `docs/architecture/CURRENT.md` and
[ADR-0071](docs/adr/0071-engine-host-contract-boundary.md). The historical plans
(`DEVELOPMENT_BLUEPRINT.md`, `NEXT_PHASE_IMPLEMENTATION.md`,
`STABLE_RELEASE_IMPLEMENTATION.md`, `CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`,
`EXTENSIBILITY_AUDIT.md`, `NEXT_RELEASE_CI_CONVERGENCE.md`) are archived design
history: read them with that status, do not use them as current requirements, and
do not create a second running-status page. `COMPATIBILITY.md` and
`docs/security-gate.md` remain current inputs. None describes implemented
behavior; re-check against HEAD and tests. `strict` remains fail-closed until
G-C passes.
The stable-release spec also governs scope: do not add a top-level CLI command,
Knowledge/Proof/View special-casing, a second interpreter or a new package
@@ -33,6 +34,19 @@ correctness and release evidence before expanding the surface.
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the SDK consumes the contract only. CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py`, `tools/ci/check_plugin_sdk.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071.
13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires the issue #13 §9.2 evidence and a separate accepted ADR; "keep in workspace" is a valid recorded decision. The plugin SDK stays in this CLI workspace as a contract-only crate (ADR-0073); do not re-create an independent SDK repository, mirror or submodule for the pre-stable line. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path.
## Pre-stable protocol changes
Read [ADR-0068](docs/adr/0068-single-current-public-contracts.md) and the
[single-contract convergence policy](docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md)
before changing a public boundary. Keep one current specification, producer and validator per
boundary. Replace retired paths in the same integration, reject unsupported
formats explicitly, and update independent consumers and release smoke tests.
Keep old formats in Git history. Preserve authority, attribution and resource
limits during refactors. Confirm cross-repository and release evidence before
closing a protocol replacement issue.
## Development workflow
@@ -40,7 +54,7 @@ correctness and release evidence before expanding the surface.
2. Update the normative spec **in place** first; there is never a second active syntax spec.
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
5. Run formatting, clippy, unit tests, golden tests and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`).
5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`, `python3 tools/ci/check_plugin_sdk.py`).
6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly.
## Unresolved design topics
+171 -9
View File
@@ -1,14 +1,176 @@
# Changelog
All notable changes to the Marqdo CLI workspace. Product version
`3.0.0-beta.1` was tagged on 2026-11-22 at source
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`
([release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1));
the next section collects post-beta
changes. Protocol versions (Analysis v2, Trace v2, Tool v1, Plugin ABI v1,
Foreign wire v1, Provider manifest v2, lock v4) and independent package
versions (including the bundled stdlib `0.1.0`) are versioned separately and
do not follow the product version. Dates use ISO 8601.
All notable changes to the Marqdo CLI workspace. Published prereleases:
`3.0.0-beta.1` (2026-11-22, source
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`),
`3.0.0-rc.1` (source `f7a5a7b0163bf5229ed09adfffd892f9899e6667`) and
`3.0.0-rc.2` (source `9149ee40a48fcda692c5c112f66c465487d13dfb`) and
`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
package versions (including the bundled stdlib `0.1.0`) are versioned
separately and do not follow the product version. Dates use ISO 8601.
Older sections are release records: a retired option or spec they name is
available at its tagged commit, not in the current tree.
## 3.0.0-rc.4 (2026-11-25)
- The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.4`; the supported platform remains Linux x86_64 on glibc 2.39 and
the locked Rust minimum remains 1.89. Released as tag `v3.0.0-rc.4` at
`452e9a32bd9e40dba427d4180691c58bab74449e`.
### Closed public Analysis boundary — issue #10 (breaking in place)
Executed policy: [ADR-0069](docs/adr/0069-public-analysis-boundary.md), replacing
`marqdo.analysis` revision 3 in place under ADR-0068. There is no old reader,
version negotiation or fallback; a same-revision artifact that lacks a current
required field is rejected and must be regenerated.
- **Document facts are public.** `modules[].source` carries the exact UTF-8
source already read by the loader and `modules[].document` is the canonical
Markdown AST in the public shape shared with `inspect --ast`. Consumers no
longer parse Markdown a second time or read package-cache paths.
- **Heading scope is one index.** Units expose the structured `path`, parent,
effective mode, mode origin and source unit, the heading span and the complete
section span. The root covers the whole source including a BOM. Exec H2
function ownership stays explicit.
- **Entry and snapshot identity are explicit.** `project.entry_module_id`,
captured `manifest_digest`/`lock_digest`, stdlib identity and the static
extension identities used by preparation are part of the artifact. The
post-preparation lock re-read and its silent empty digest on IO failure are
gone.
- **One document-link resolver.** Analysis `references`, `check --refs` and
`inspect --refs` share one pure resolver and explicit catalogs. It reports
`resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, `outside_scope`
or `invalid`; ordinary Analysis never opens a link target and a same-document
anchor names the real source module. The duplicate `commands.rs` resolver is
deleted.
- **Calls stay bound once.** Static call records keep the single prepared
binding table and now expose target kind, exact function/builtin/plugin target
and a reason for unresolved calls. Plugin targets carry only their verified
static owner; no plugin function is fabricated.
- **Output is private and atomic.** `--emit` writes owner-only exclusive bytes
through a temporary file and rename, and refuses to overwrite a loaded source,
manifest, lock file, directory, symlink or hard link to an input.
- **Independent consumers are the gate.** The Python Analysis consumer performs
semantic validation in addition to JSON Schema; mutation fixtures reject
missing current fields, tampered source/digests/spans, cycles, wrong owners
and invalid reference/nullability combinations. View-, lint- and
knowledge-like fixtures drive the real installed CLI.
## 3.0.0-rc.3 (2026-11-24)
- The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.3`. The locked workspace requires Rust 1.89 and targets Linux
x86_64 on glibc 2.39.
- **Licensing:** the workspace is now Apache-2.0 only. `Cargo.toml` declares
`license = "Apache-2.0"` and the dual-licensed `LICENSE-MIT` file is removed;
the archive ships `LICENSE-APACHE` only. This is a repository-licensing
change, not a protocol or language change.
### Single current public contracts — issue #8 (breaking)
Executed policy: [ADR-0068](docs/adr/0068-single-current-public-contracts.md) and
[the protocol convergence policy](docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md).
This is a pre-stable replacement, not a compatibility release. Retired formats
are rejected; there is no legacy reader, alias, fallback, negotiation or
automatic migration.
- **Analysis has one writer for every project.** `check --emit` always emits
`marqdo.analysis` `schema_version: 3`, including projects without
`break`/`continue`. The content-driven v2/v3 selector is deleted, and the
retired `spec/analysis-v*.md` documents and schemas are removed from the
current tree. Consumers no longer need to branch on the project content.
- **Trace v2 and Execution Events v1 became one Observation contract.**
`run`/`call` emit one `marqdo.observation` `schema_version: 1` event sequence
per execution. `--output jsonl` streams those events, `--output json` and
`--observation-file PATH` publish an atomic snapshot of the same events from
the same execution. `run_id`, `seq`, frame identity, terminal semantics,
capture budgets and privacy rules are defined once in
[`spec/observation.md`](spec/observation.md). The retired `--json`,
`--trace-file`, `--event-stream` and `--trace` options are rejected, and the
in-process effect-trace document is gone: effects are `effect` observation
events.
- **CLI Tool requirements are single exact values.** `tool.json` declares
`requires.api_revision` (required) plus optional exact `analysis` and
`observation` integers. Version arrays and intersection negotiation are
removed. Retired manifests and records are rejected with a remove/reinstall
instruction and are never rewritten.
- **Plugin and resource-provider workers share one transport.** Framing,
bounded reads, deadlines, dead-worker quarantine and teardown live in
`marqdo-worker-ipc` ([`spec/worker-ipc.md`](spec/worker-ipc.md)); the invoke
vocabulary, grants, kind rights and error codes stay with each boundary.
- **Extension descriptors and lock keep their current identifiers.** There is
no version renumbering without a shape change: plugin `abi: ^1.0`, provider
`schema_version: 2`, kernel `wire_version: 1` and lock v4 stay current.
Retired provider/kernel/plugin revisions and lock v1–v3 are rejected with an
explicit regeneration/reinstall instruction; no migrator runs.
- **`spec/` now contains only current contracts.** Retired specifications are
available in Git history and tagged archives. ADRs covering retired public
contracts carry a Historical header. `docs/developers/analysis-trace.md` was
replaced by `analysis-observation.md`.
- **CI is a protocol consumer.** A fast `contract` lane builds both shipped
binaries and drives the real CLI through the independent Python consumers,
while the full `test` lane runs fmt/clippy/tests/docs/architecture gates.
`tools/ci/verify_observation_stream.py` (checked in, unit-tested) asserts
that one run's JSONL stream and JSON snapshot are the same event sequence.
### Review fixes after the first candidate build
- A rejected strict observation destination no longer emits a partial JSONL
stream: `--output jsonl` and `--observation-file` are refused before any
session opens.
- `check --emit` removes a previous Analysis artifact when the project cannot
be loaded, not only when it has compile errors.
- Filesystem resource requests report their concrete effect operation
(`fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`,
`fs.rename`) instead of a generic `resource.request`.
- The shared worker transport preserves the plugin ABI frame codes
`worker_frame_too_large` and `worker_encode_failed`.
- The event and snapshot schemas agree on the capture `level` enum.
- The G4 workload catalogue uses `run`/`call --output json` and pins the
current snapshot in its correctness digest; the previously retired `--json`
flag made every non-check workload fail correctness verification.
Migration for consumers:
1. Re-run `marqdo check --emit` and read `marqdo.analysis` without a version
branch; verify `project`, module ids and source digests.
2. Replace Trace/Event readers with an Observation reader; stream with
`--output jsonl` and/or read `--observation-file`. Verify `run_id`, `seq`,
source binding and the single terminal event.
3. Rewrite `tool.json` to the exact current requirements, rebuild the tool and
`marqdo tool remove` + reinstall. Old registrations are not migrated.
4. Rebuild/reinstall plugins, providers and kernels from their current
descriptors; re-run `marqdo lock` instead of reusing a retired lock.
### Verification
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D
warnings`, `cargo test --workspace --locked` pass on the candidate tree.
- Independent consumers (`tests/consumers/analysis_consumer.py`,
`observation_consumer.py`, `validate_protocols.py`) validate real CLI output;
`tests/consumers/observation_consumer.py` checks that stream and snapshot are
the same event sequence.
- `crates/cli/tests/architecture_boundaries.rs` forbids a second worker
framing implementation and pins the workspace layer list;
`docs_consistency` keeps one current overview and resolving links.
- Same-SHA Linux CI ([pipeline #80](https://ci.cflmy.cn/repos/1/pipeline/80)),
the archive build, the from-archive smoke, the cold-install container check
and the frozen external conformance suite (fixtures at
`015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`, 7/7) are recorded in the
per-gate manifest
[`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
(`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)
+47 -44
View File
@@ -1,17 +1,22 @@
# Compatibility and support matrix
Snapshot: product version **`3.0.0-beta.1`** (prerelease), branch `master`,
tagged `v3.0.0-beta.1` at source SHA `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. This file records what was actually verified and
separates it from what is only implemented. The supported release platform is
**Linux x86_64 (glibc)**; everything else is experimental and not claimed for
this beta. Executed status and same-SHA evidence are in
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under
[`docs/evidence/extension/`](docs/evidence/extension/README.md).
Snapshot: product version **`3.0.0-rc.4`** (prerelease, released 2026-11-25).
Tag `v3.0.0-rc.4` at source SHA
`452e9a32bd9e40dba427d4180691c58bab74449e`; release
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4. The previous
release is `3.0.0-rc.3` at source SHA
`1e2a045cc78bf40972181abb44e7117c56cf4401`; its evidence remains under
[`docs/evidence/`](docs/evidence/2026-11-24-rc.3-release.md). This file records
what was actually verified and separates it from what is only implemented. The
supported release platform is **Linux x86_64 (glibc 2.39)**; everything else is
experimental and not claimed for this prerelease. Executed status and SHA-bound
evidence are in [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/`](docs/evidence/).
The `3.0.0-rc.2` candidate targets Linux x86_64 on glibc 2.39 and
includes the post-beta changes below. See the
The `3.0.0-rc.4` release includes the post-beta protocol convergence and the
closed public Analysis boundary below. See the
[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)
@@ -51,7 +56,7 @@ Consequences for compatibility:
## 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.2` 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
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -65,9 +70,9 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown` or heading annotations projection exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
| 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
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within
expressions retain their meaning. Two separate carriers containing `else` and
@@ -77,25 +82,24 @@ Parameter inference ignores reads after a definite transfer. When upgrading
a caller that passed an argument inferred solely from unreachable code,
remove the argument or keep it through an explicit `params(...)` declaration.
`marqdo-lint 0.1.0` reads legacy Analysis v2 documents. Its control layout
alignment for `else if` and its Analysis v3 support require an update in
that tool.
The current Analysis contract is `schema_version: 3` for every project, so an
external tool that still reads Analysis v2 must be updated before it can
consume this candidate's `check --emit` output.
## Public protocol versions
| 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. |
| Language / CLI | `3.0.0-rc.2` (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). |
| Analysis | v2/v3 | Projects with loop transfers emit v3. Other projects emit v2. Consumers reject unknown majors. |
| Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. |
| Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). |
| CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. |
| 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). |
| 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). |
| 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. |
| 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). |
| 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`). |
| Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. |
@@ -118,10 +122,9 @@ portable/tested locally but the native platform lane has not run here;
| Official stdlib public aliases (print de-magic; byte-identical output) | PASS | UNVERIFIED | UNVERIFIED |
| Resource Provider v2 CLI (`--provider`/`--allow-provider`, worker helper) | PASS (linux/x86_64; real C sensor + helper) | **FAIL-CLOSED** (`ext.platform_unsupported`) | **UNSUPPORTED** |
| Capability handler registry (`fs.read` handler, audit, unavailable) | PASS | UNVERIFIED | UNVERIFIED |
| External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (`--release` binary sha256 `28e3776d…`, fixture repo `e4b7352c…`; see `docs/evidence/extension/6a7bb983.../manifest.json`) | UNVERIFIED | UNVERIFIED |
| Analysis v2 / Trace v2 + Python consumers | PASS | UNVERIFIED | UNVERIFIED |
| Execution Events v1 (`--event-stream jsonl`, P0/P1) | PASS locally (14 CLI contract tests + 8 host + 4 runtime; independent Python schema consumer); post-beta, not in the tagged archive | UNVERIFIED | UNVERIFIED |
| Tool Protocol v1 + 3 independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| 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 v3 + Observation v1 + Python consumers | PASS (same-SHA CI contract lane and archive smoke; independent consumers) | UNVERIFIED | UNVERIFIED |
| CLI Tool revision 1 + independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** |
| Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) |
| Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED |
@@ -149,14 +152,15 @@ the Windows C ABI/provider paths remain fail-closed.
rlimits and wall-clock/output supervision; the child verifies `PID 1`,
`NoNewPrivs`, `CapEff=0`, a non-initial uid map and no non-loopback network.
- Refused before launch: `--allow-read`, `--allow-write`, `--allow-foreign`,
`--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`,
`--trace-file`.
`--allow-plugin`, `--plugin`, `--trust-native-plugin`, `--kernel`;
`--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
not implemented and must not be inferred from L1 passing.
## 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
Foreign kernels; `git` for Git dependencies.
- `strict` additionally requires Bubblewrap and a kernel/environment that
@@ -175,7 +179,7 @@ the Windows C ABI/provider paths remain fail-closed.
* The external conformance suite is a mandatory **additional** release gate
(`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
branch / bullet-list loop / block-quote call / first code-span signature).
@@ -190,20 +194,19 @@ the Windows C ABI/provider paths remain fail-closed.
sessions, and general-purpose CAS. The three `sample-*` tools are test
fixtures for the generic Tool protocol, not product features.
- Tagged Windows/macOS release archives: only the Linux x86_64 archive is
produced for `3.0.0-beta.1`. macOS/Windows native artifacts are not claimed;
the Windows lane is a Linux-hosted compile gate only.
produced for the 3.0 prerelease line. macOS/Windows native artifacts are not
claimed; the Windows lane is a Linux-hosted compile gate only.
## Release decision
**`3.0.0-beta.1` prerelease — approved as a Linux x86_64 beta with explicitly
recorded gaps.** The beta profile in
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3.1
was used, not the stable profile: Linux is the only supported platform,
macOS/Windows are declared unsupported/experimental, G4 is a Beta-only `WARN`
on the fixed Woodpecker agent, and strict policy and frozen-binary conformance
are recorded with same-SHA evidence in [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`](docs/evidence/ci/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json)
(`BETA_RELEASE_CANDIDATE`). Release:
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1. Beta status
does not imply stable `3.0.0` or LTS; the stable gate remains stricter and
separate.
**`3.0.0-rc.4` prerelease — released as a Linux x86_64 RC.** The RC profile in
[`docs/MARQDO_3_0_PRERELEASE_PLAN.md`](docs/MARQDO_3_0_PRERELEASE_PLAN.md) §3 was
used: Linux is the only supported platform, macOS/Windows are UNSUPPORTED for
this scope, strict L1 has same-SHA disposable-VM evidence, and G4 performance is
a maintainer-approved shared-node `WARN` for this named RC only. The aggregate
decision and per-gate evidence are in
[`docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`](docs/evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json)
(`RC_RELEASE_CANDIDATE`) and the release assets; see
[`docs/evidence/2026-11-24-rc.3-release.md`](docs/evidence/2026-11-24-rc.3-release.md).
A prerelease does not imply stable `3.0.0` or LTS; the stable gate remains
stricter and separate.
Generated
+41 -21
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "adler2"
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "marqdo-cli"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"clap",
"hex",
@@ -420,6 +420,7 @@ dependencies = [
"marqdo-foreign",
"marqdo-frontend",
"marqdo-host",
"marqdo-host-contract",
"marqdo-ir",
"marqdo-markdown",
"marqdo-package",
@@ -438,7 +439,7 @@ dependencies = [
[[package]]
name = "marqdo-expression"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"num-bigint",
@@ -449,7 +450,7 @@ dependencies = [
[[package]]
name = "marqdo-foreign"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"hex",
"libc",
@@ -465,7 +466,7 @@ dependencies = [
[[package]]
name = "marqdo-frontend"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-ir",
@@ -480,17 +481,20 @@ dependencies = [
[[package]]
name = "marqdo-host"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"flate2",
"getrandom 0.4.3",
"glob",
"hex",
"libloading",
"marqdo-foreign",
"marqdo-host-contract",
"marqdo-plugin-abi",
"marqdo-sandbox",
"marqdo-span",
"marqdo-value",
"marqdo-worker-ipc",
"rcgen",
"regex",
"rustls",
@@ -498,13 +502,23 @@ dependencies = [
"rustls-pemfile",
"serde",
"serde_json",
"serde_yaml",
"sha2",
"tempfile",
"thiserror",
]
[[package]]
name = "marqdo-host-contract"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"marqdo-value",
]
[[package]]
name = "marqdo-ir"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-span",
@@ -514,7 +528,7 @@ dependencies = [
[[package]]
name = "marqdo-markdown"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"comrak",
"marqdo-span",
@@ -525,7 +539,7 @@ dependencies = [
[[package]]
name = "marqdo-package"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"hex",
"semver",
@@ -539,22 +553,17 @@ dependencies = [
[[package]]
name = "marqdo-plugin-abi"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"hex",
"libloading",
"marqdo-span",
"marqdo-value",
"serde",
"serde_json",
"serde_yaml",
"sha2",
"thiserror",
]
[[package]]
name = "marqdo-plugin-sdk"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-plugin-abi",
"serde",
@@ -563,23 +572,26 @@ dependencies = [
[[package]]
name = "marqdo-provider-worker"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"libloading",
"marqdo-host",
"marqdo-host-contract",
"marqdo-sandbox",
"marqdo-value",
"marqdo-worker-ipc",
"serde_json",
"tempfile",
]
[[package]]
name = "marqdo-runtime"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-frontend",
"marqdo-host",
"marqdo-host-contract",
"marqdo-ir",
"marqdo-sandbox",
"marqdo-span",
@@ -594,7 +606,7 @@ dependencies = [
[[package]]
name = "marqdo-sandbox"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"libc",
"serde",
@@ -602,14 +614,14 @@ dependencies = [
[[package]]
name = "marqdo-span"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"serde",
]
[[package]]
name = "marqdo-value"
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"num-bigint",
@@ -618,6 +630,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "marqdo-worker-ipc"
version = "3.0.0-rc.4"
dependencies = [
"serde_json",
"thiserror",
]
[[package]]
name = "memchr"
version = "2.8.3"
+6 -2
View File
@@ -10,8 +10,10 @@ members = [
"crates/marqdo-foreign",
"crates/marqdo-plugin-abi",
"crates/marqdo-provider-worker",
"crates/marqdo-worker-ipc",
"crates/marqdo-plugin-sdk",
"crates/marqdo-host",
"crates/marqdo-host-contract",
"crates/marqdo-runtime",
"crates/marqdo-package",
"crates/marqdo-sandbox",
@@ -19,10 +21,10 @@ members = [
]
[workspace.package]
version = "3.0.0-rc.2"
version = "3.0.0-rc.4"
edition = "2021"
rust-version = "1.89"
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
repository = "https://github.com/cflmy/marqdo-cli"
authors = ["Marqdo contributors"]
@@ -35,7 +37,9 @@ marqdo-ir = { path = "crates/marqdo-ir" }
marqdo-frontend = { path = "crates/marqdo-frontend" }
marqdo-foreign = { path = "crates/marqdo-foreign" }
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" }
marqdo-host = { path = "crates/marqdo-host" }
marqdo-host-contract = { path = "crates/marqdo-host-contract" }
marqdo-runtime = { path = "crates/marqdo-runtime" }
marqdo-package = { path = "crates/marqdo-package" }
marqdo-sandbox = { path = "crates/marqdo-sandbox" }
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Marqdo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+61 -30
View File
@@ -10,7 +10,7 @@ The official implementation is a Rust workspace; Python/Node are optional
foreign kernels, never the compiler target.
This repository is the new, independent Marqdo toolchain, now at product
version **`3.0.0-rc.2`** 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
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
@@ -27,11 +27,14 @@ release policy.
> [`docs/STATUS.md`](docs/STATUS.md) and
> [`docs/migration/README.md`](docs/migration/README.md).
> **Published baseline: `3.0.0-beta.1` prerelease** —
> **Current release: `3.0.0-rc.4` prerelease** —
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4),
> source `452e9a32bd9e40dba427d4180691c58bab74449e`, Linux x86_64. The previous
> published baseline was `3.0.0-beta.1` —
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1),
> source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the
> C ABI plugin/provider paths are Linux-only in this beta. The language
> (RFC-LANG-0002), lock v4, Analysis v2, Trace v2, Tool v1, Plugin ABI v1
> (RFC-LANG-0002), lock v4, Analysis, Observation, CLI Tool, Plugin ABI v1
> (native + worker), pinned Foreign providers and Resource Provider v2 are
> implemented and covered by tests. **`strict` OS isolation is Linux-only and
> probe-gated**; unsupported hosts must fail closed, and strict L2
@@ -46,8 +49,9 @@ release policy.
CI: the source of truth is the Gitea remote
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
runs fmt, clippy, workspace tests with `--locked`, the Windows cross-target
compile gate and a release build of both binaries. The strict OS-isolation lane
runs fmt, clippy, workspace tests with `--locked`, the dependency-direction and
engine-independence gates, the plugin SDK consumption gate, the Windows
cross-target compile gate and a release build of both binaries. The strict OS-isolation lane
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
mirror is not used as the authoritative lane for this beta.
@@ -60,6 +64,30 @@ cargo build -p marqdo-cli
# binary: target/debug/marqdo (or $CARGO_TARGET_DIR/debug/marqdo)
```
The CLI and Provider Worker compile without any stdlib sources. The accepted
standard-library Bundle is assembled by the ecosystem repository
(`cflmy/marqdo`) from pinned component gitlinks; this repository has **no**
`stdlib/` source tree and no compile-time source fallback (ADR-0070 Phase B).
Every product test, package step and release names one explicit, verified
Bundle; `MARQDO_STDLIB_DIR` remains the explicit runtime override and the
installed `stdlib/` next to the binary is the default:
```bash
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
# CI/maintainers materialize the exact pinned Bundle (commit + gitlinks):
python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
python3 tools/stdlib/bundle.py --stdlib-dir target/ecosystem-stdlib --print-path
python3 tools/release/package.py --source-sha "$(git rev-parse HEAD)" \
--version <version> --stdlib-dir target/ecosystem-stdlib \
--bundle-pin tools/stdlib/bundle-pin.json
```
Product tests and CI set `MARQDO_TEST_STDLIB_BUNDLE` to that materialized
Bundle; without it the product lane fails closed instead of reaching a source
tree.
See [`docs/releasing.md`](docs/releasing.md) for the full procedure.
## Quickstart
```bash
@@ -67,7 +95,7 @@ marqdo init demo
cd demo
marqdo check index.mq.md
marqdo run index.mq.md # executes ## @exec main
marqdo run index.mq.md --event-stream jsonl # live Execution Events v1 NDJSON
marqdo run index.mq.md --output jsonl # live Observation JSON Lines
marqdo inspect index.mq.md --ast
marqdo inspect index.mq.md --signature
marqdo call index.mq.md main
@@ -152,15 +180,17 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
`{ok:false,code,message}` as an ordinary Map, with a `.mq.md` first-fit
free-list allocator demonstrating reuse, splitting and `alloc.no_space`
recovery (ADR-0024). No `Result` type or exception syntax.
* **Bundled stdlib + official print aliases (RFC-CM CM-A07/A10)** — offline
`stdlib/` with explicit `std:io`/`std:format`/`std:text` imports, SHA-256
digest verification, Analysis identity and a frozen-CLI closure test; the
* **Bundled stdlib + official print aliases (RFC-CM CM-A07/A10)** — one
offline, ecosystem-assembled Bundle (component-owned module sources) with
explicit `std:io`/`std:format`/`std:text` imports, SHA-256 digest
verification, Analysis identity and a frozen-CLI closure test; the
`.mq.md` print chain is the only execution path for `打印`/`print` on an official install (ADR-0031),
covering all 15 value types; `HostOp::Print` and the legacy formatter are
removed (ADR-0027/0028/0029/0030/0031).
* **HTTP/1.1 framing in `.mq.md`** — `stdlib/net/http.mq.md` status/header/
chunked parsing and request construction; a loopback TCP test runs a real
exchange (ADR-0034; no TLS/host HTTP claim).
* **HTTP/1.1 framing in `.mq.md`** — the `marqdo-ext-http` explicit Package
provides status/header/chunked parsing and request construction; the CLI
keeps the generic TCP endpoint and a loopback round-trip test (ADR-0034; no
TLS/host HTTP claim).
* **Blocking TCP endpoint (RFC-CM P5 first slice)** — `resource.open("tcp",
"<ip>:<port>", ["read","write"])` with exact IP grants, project mode and
5-second timeouts; DNS/TLS/UDP/server sockets excluded (ADR-0034).
@@ -215,7 +245,7 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
`lock`, strict `sync --locked` with atomic `.marqdo/env` materialization.
`run`/`call`/`check` never fetch or rewrite the lock.
* **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,
capability dropping, rlimits, a wall-clock supervisor and child
self-verification (ADR-0021). It is probe-gated and verified in a disposable
@@ -232,11 +262,10 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
target-triple + sha256 artifact verification, native and isolated worker
transports, brokered `fs.read`, and explicitly trusted in-process calls
(`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox.
* **Public protocols** — Analysis [v2](spec/analysis-v2.md)/[v3](spec/analysis-v3.md) and Trace v2 with JSON Schemas and
independent Python consumers; Tool Protocol v1 with arbitrary command names,
SemVer negotiation and whole-bundle digest verification; **Execution Events
v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and
explicitly selected, bounded values (post-beta addition, ADR-0059).
* **Public protocols** — [Analysis](spec/analysis.md) projects static facts.
[Observation](spec/observation.md) delivers the same run as live JSONL or
a JSON snapshot. [CLI Tool](spec/cli-tool.md) installs independently built
commands with exact protocol requirements and verifies their entire bundle.
Run everything:
@@ -252,7 +281,7 @@ cargo clippy --workspace --all-targets -- -D warnings
* **Strict is Linux-only and L1-only.** `--mode strict` enables the
Bubblewrap supervisor only when its runtime probe passes; otherwise it exits
1. It supports pure Marqdo 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
strict.
* **Native plugins run in-process** and require an explicit unsafe trust flag.
@@ -292,17 +321,18 @@ crates/marqdo-ir module/unit/function/statement IR, builtin table
crates/marqdo-frontend heading scopes, mapping, inference, static calls
crates/marqdo-foreign Python/Node one-shot kernel supervisor
crates/marqdo-sandbox mode parsing + platform isolation detection
crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro
crates/marqdo-host CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
crates/marqdo-runtime tree-walk interpreter
crates/marqdo-host-contract neutral Host trait, HostOp, context and runtime facts
crates/marqdo-plugin-abi public C ABI v1 contract: layout, wire envelope, errors
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro (contract-only)
crates/marqdo-host Native Host: capability, resources, OS, plugin loader/worker
crates/marqdo-runtime tree-walk interpreter (depends only on the neutral contract)
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
crates/cli CLI composition root (binary `marqdo`)
include/ frozen plugin C ABI header
spec/ normative language/format/ABI specs
docs/ blueprint, ADRs, status, contributor guide
examples/ runnable documents + multi-module + plugin demo
tests/ conformance/negative corpus (see tests/README.md)
tests/ conformance/negative corpus, embedding consumer and SDK fixture
```
## Documentation index
@@ -328,7 +358,7 @@ tests/ conformance/negative corpus (see tests/README.md)
* [`docs/developers/README.md`](docs/developers/README.md) — third-party and
integrator entry point (libraries, tools, plugins, kernels, providers,
Analysis/Trace consumers, compatibility).
* [`docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md`](docs/MARQDO_THIRD_PARTY_INTEGRATION_GUIDE.md)
* [`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.
* [`docs/STABLE_RELEASE_IMPLEMENTATION.md`](docs/STABLE_RELEASE_IMPLEMENTATION.md)
— historical stable-release roadmap input (its own header marks it Proposed
@@ -356,15 +386,16 @@ tests/ conformance/negative corpus (see tests/README.md)
* [`docs/adr/`](docs/adr/) — accepted decisions (crate graph, inert executables,
`ref` ambiguity, strict refusal, AST normalization, CLI contract, BigInt/wire,
package identity, callable resolution, plugin export routing, capability
broker, kernel providers, generic CLI tools, plugin-handle authority, public Analysis/Trace v1).
broker, kernel providers, generic CLI tools, plugin-handle authority, public contract replacement).
* Specs: [`markdown-profile.md`](spec/markdown-profile.md),
[`mapping.md`](spec/mapping.md), [`expression.ebnf`](spec/expression.ebnf),
[`evaluation.md`](spec/evaluation.md), [`references.md`](spec/references.md),
[`value-wire.md`](spec/value-wire.md), [`security.md`](spec/security.md),
[`package-format.md`](spec/package-format.md),
[`plugin-abi.md`](spec/plugin-abi.md), [`math.md`](spec/math.md),
[`foreign.md`](spec/foreign.md), [`tool-v1.md`](spec/tool-v1.md),
[`analysis-v2.md`](spec/analysis-v2.md), [`trace-v2.md`](spec/trace-v2.md);
[`foreign.md`](spec/foreign.md), [`cli-tool.md`](spec/cli-tool.md),
[`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md),
[`worker-ipc.md`](spec/worker-ipc.md);
JSON Schemas in [`spec/schemas/`](spec/schemas/).
* [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS`
workflow.
@@ -432,7 +463,7 @@ marqdo run kernel/demo.mq.md \
marqdo run provider/demo.mq.md \
--provider provider/build/provider.json --allow-provider demo.sensor
# 5. Independent CLI Tool consuming only public Analysis v2
# 5. Independent CLI Tool consuming public Analysis
marqdo tool install tool/tool.json
marqdo inspect-ext tool/demo.mq.md
```
@@ -488,7 +519,7 @@ extensions. Lock v3 requires an explicit `marqdo lock` migration. See
#### Official stdlib aliases, no print magic
`打印`/`print` are declared in the verified `stdlib/stdlib.json`
`打印`/`print` are declared in the accepted Bundle's verified `stdlib.json`
(`public_aliases`, covered by `aliases_digest`) and bound as ordinary
`Marqdo` calls to `io.mq.md::写值` (ADR-0058). There is no
`Program.print_override`, no AST-wide print scan and no runtime print branch;
+2 -3
View File
@@ -18,6 +18,7 @@ marqdo-frontend = { workspace = true }
marqdo-foreign = { workspace = true }
marqdo-plugin-abi = { workspace = true }
marqdo-host = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-runtime = { workspace = true }
marqdo-package = { workspace = true }
marqdo-sandbox = { workspace = true }
@@ -28,10 +29,8 @@ walkdir = { workspace = true }
hex = { workspace = true }
sha2 = { workspace = true }
semver = { workspace = true }
tempfile = { workspace = true }
[[bin]]
name = "marqdo"
path = "src/main.rs"
[dev-dependencies]
tempfile = { workspace = true }
-675
View File
@@ -1,675 +0,0 @@
//! Public Analysis projection (spec/analysis-v2.md and spec/analysis-v3.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 BASE_VERSION: u32 = 2;
/// First schema version with structured loop transfers.
pub const LOOP_CONTROL_VERSION: u32 = 3;
/// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value {
let mut modules = Vec::new();
let mut version = BASE_VERSION;
for (module_id, file) in &project.files {
let module = &file.analysis.module;
if version == BASE_VERSION
&& module
.functions
.iter()
.any(|function| has_loop_control(&function.body))
{
version = LOOP_CONTROL_VERSION;
}
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": 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),
})
}
fn has_loop_control(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match stmt {
Stmt::Break { .. } | Stmt::Continue { .. } => true,
Stmt::Branch { arms, .. } => arms.iter().any(|arm| has_loop_control(&arm.body)),
Stmt::Loop { body, .. } => has_loop_control(body),
Stmt::Assign { .. } | Stmt::Eval { .. } | Stmt::Return { .. } => false,
})
}
/// 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 (Trace binds to this digest).
pub fn digest(project: &LoadedProject) -> String {
encode(project)
.map(|bytes| sha256_hex(&bytes))
.unwrap_or_else(|_| sha256_hex(b""))
}
/// 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>,
}
+50 -182
View File
@@ -3,7 +3,8 @@
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use marqdo_host::{Host, StdHost};
use marqdo_host::StdHost;
use marqdo_host_contract::Host;
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome};
use marqdo_span::Span;
@@ -29,6 +30,7 @@ pub use tool::{fmt, plugin_inspect};
use crate::args;
use crate::extension_descriptors::{self, StaticPluginSet};
use crate::loader::{FileDiagnostic, LoadedProject};
use crate::observation::ObservationSession;
use crate::output;
use crate::project_prepare::{self, PrepareOptions, PreparedProgram};
@@ -63,38 +65,6 @@ pub(super) fn prepare_project(
}
}
/// `marqdo check`.
fn validate_refs(project: &LoadedProject) -> Vec<FileDiagnostic> {
let mut diagnostics = Vec::new();
for file in project.files.values() {
let parent = file.path.parent().unwrap_or_else(|| Path::new("."));
let mut unresolved: Vec<marqdo_span::Span> = Vec::new();
file.analysis.document.root.walk(&mut |node| {
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
return;
};
let (resolved, _, _) = resolve_link(project, &file.analysis.units, parent, url);
if !resolved {
unresolved.push(node.span);
}
});
for span in unresolved {
diagnostics.push(FileDiagnostic {
module_id: file.module_id.clone(),
path: file.path.clone(),
source: file.source.clone(),
diagnostic: marqdo_value::Diagnostic::error(
marqdo_value::codes::REF_UNRESOLVED,
Some(span),
"reference target could not be resolved",
)
.with_hint("fix the link target or add the missing heading/file"),
});
}
}
diagnostics
}
fn summary_json(project: &LoadedProject) -> serde_json::Value {
let entry = project.entry_file();
json!({
@@ -129,113 +99,6 @@ fn signatures_json(module: &marqdo_ir::Module) -> serde_json::Value {
)
}
fn refs_json(project: &LoadedProject) -> serde_json::Value {
let entry = project.entry_file();
let parent = entry.path.parent().unwrap_or_else(|| Path::new("."));
let mut edges = Vec::new();
entry.analysis.document.root.walk(&mut |node| {
let marqdo_markdown::MdKind::Link { url, .. } = &node.kind else {
return;
};
let (resolved, target_module, target_unit) =
resolve_link(project, &entry.analysis.units, parent, url);
edges.push(json!({
"source": entry.module_id.to_string(),
"url": url,
"span": node.span,
"resolved": resolved,
"target_module": target_module,
"target_unit": target_unit,
}));
});
serde_json::Value::Array(edges)
}
fn resolve_link(
project: &LoadedProject,
units: &marqdo_frontend::UnitIndex,
parent: &Path,
url: &str,
) -> (bool, Option<String>, Option<String>) {
if let Some(fragment) = url.strip_prefix('#') {
let unit = units.anchors.get(fragment).or_else(|| {
units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
});
return match unit {
Some(unit) => (
true,
Some(project.entry.to_string()),
Some(unit.to_string()),
),
None => (false, None, None),
};
}
if url.starts_with("http://") || url.starts_with("https://") {
return (true, None, None);
}
let (path_part, fragment) = match url.split_once('#') {
Some((path, fragment)) => (path, Some(fragment)),
None => (url, None),
};
let candidate = parent.join(path_part);
let Ok(candidate) = candidate.canonicalize() else {
return (false, None, None);
};
let Some(module_id) = project.module_id_for_path(&candidate) else {
return (false, None, None);
};
let analyzed;
let target_units = match project.files.get(&module_id) {
Some(target_file) => &target_file.analysis.units,
None => {
// Links may reference documents that are not imported. Analyse the
// target statically for reference checking; nothing executes.
let Ok(source) = std::fs::read_to_string(&candidate) else {
return (false, None, None);
};
analyzed = marqdo_frontend::analyze_source(&module_id.to_string(), &source);
&analyzed.units
}
};
let Some(fragment) = fragment else {
return (true, Some(module_id.to_string()), None);
};
let resolved = target_units.anchors.get(fragment).or_else(|| {
target_units
.units
.iter()
.find(|unit| unit.name == fragment)
.map(|unit| &unit.id)
});
match resolved {
Some(unit) => (true, Some(module_id.to_string()), Some(unit.to_string())),
None => (false, Some(module_id.to_string()), None),
}
}
/// Re-execute this CLI inside the strict Linux supervisor.
/// Emit one CLI error through the requested channel.
///
/// `--json` consumers require exactly one JSON document; human mode keeps the
/// conventional `error:` line on stderr. This helper is shared with the run
/// assembly so every strict control-plane failure follows one contract.
pub(super) fn emit_error(json: bool, command_name: &str, code: &str, message: &str) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": message,
"code": code,
}));
} else {
eprintln!("error: {message}");
}
}
/// Machine-readable routing decision for one captured strict execution.
#[derive(Debug, PartialEq, Eq)]
enum StrictRoute {
@@ -247,17 +110,15 @@ enum StrictRoute {
/// Classify a captured strict execution.
///
/// A strict child in `--json` mode must produce exactly one JSON document on
/// stdout. Anything else is a control-plane failure: forwarding bwrap text or
/// an empty stream would break the CLI protocol (the GitHub-hosted Linux CI
/// failure that motivated this contract).
fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
/// Machine output is forwarded only if the child emitted one complete
/// current Observation snapshot whose terminal agrees with the exit status.
fn classify_strict_outcome(outcome: &StrictOutcome, snapshot: bool) -> StrictRoute {
let exit_code = outcome.exit_code.unwrap_or(1);
if !json {
if !snapshot {
return StrictRoute::Forward { exit_code };
}
if !outcome.stdout.is_empty()
&& serde_json::from_slice::<serde_json::Value>(&outcome.stdout).is_ok()
if outcome.exit_code.is_some()
&& crate::observation::is_complete_snapshot(&outcome.stdout, exit_code)
{
return StrictRoute::Forward { exit_code };
}
@@ -277,33 +138,39 @@ fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
}
StrictRoute::Failure {
code: "strict.child_invalid",
message: "the strict child did not produce exactly one JSON document; refusing to forward partial output"
message: "the strict child did not produce exactly one JSON observation snapshot"
.to_string(),
}
}
/// Route one captured strict execution to stdout/stderr or one error document.
fn route_strict_outcome(outcome: StrictOutcome, json: bool, command_name: &str) -> i32 {
/// Route captured child bytes through the selected output contract.
fn route_strict_outcome(outcome: StrictOutcome, observation: Option<&ObservationSession>) -> i32 {
use std::io::Write;
match classify_strict_outcome(&outcome, json) {
match classify_strict_outcome(&outcome, observation.is_some()) {
StrictRoute::Forward { exit_code } => {
let _ = std::io::stdout().write_all(&outcome.stdout);
let _ = std::io::stdout().flush();
let mut stdout = std::io::stdout().lock();
if let Err(error) = stdout
.write_all(&outcome.stdout)
.and_then(|()| stdout.flush())
{
return run::transport_failure(&error.to_string());
}
let _ = std::io::stderr().write_all(&outcome.stderr);
let _ = std::io::stderr().flush();
exit_code
}
StrictRoute::Failure { code, message } => {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": message,
"code": code,
}));
match outcome.exit_code {
Some(code) if code != 0 => code,
_ => 1,
eprintln!("error[{code}]: {message}");
if let Some(observation) = observation {
let result = if code == "strict.namespace_failure" {
observation.rejected("strict", code, &message)
} else {
observation.incomplete()
};
if let Err(error) = result {
return run::transport_failure(&error);
}
}
outcome.exit_code.filter(|code| *code != 0).unwrap_or(1)
}
}
}
@@ -312,22 +179,26 @@ fn launch_strict_process(
project_root: &Path,
document: Option<&Path>,
settings: &SandboxSettings,
json: bool,
command_name: &str,
observation: Option<&ObservationSession>,
) -> i32 {
let program = match std::env::current_exe() {
Ok(path) => path,
Err(error) => {
let message = format!("cannot locate the marqdo executable: {error}");
emit_error(json, command_name, "strict.launch_failed", &message);
return 1;
return run::fail(observation, "strict", "strict.launch_failed", &message, 1);
}
};
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let output_limit = settings
let program_output_limit = settings
.max_output
.unwrap_or(1024 * 1024)
.min(64 * 1024 * 1024);
.unwrap_or(marqdo_host::DEFAULT_OUTPUT_BYTES);
let output_limit = if observation.is_some() {
// Allow framing and runtime observations within the existing
// supervisor capture ceiling. The child's program budget still applies.
64 * 1024 * 1024
} else {
program_output_limit.min(64 * 1024 * 1024)
};
let timeout = Duration::from_secs(settings.timeout.unwrap_or(30));
let stdlib_dir = crate::stdlib::StdlibBundle::discover()
.ok()
@@ -344,11 +215,8 @@ fn launch_strict_process(
stdlib_dir: stdlib_dir.as_deref(),
};
match marqdo_sandbox::launch_strict_capture(&command) {
Ok(outcome) => route_strict_outcome(outcome, json, command_name),
Err(error) => {
emit_error(json, command_name, error.code(), &error.to_string());
1
}
Ok(outcome) => route_strict_outcome(outcome, observation),
Err(error) => run::fail(observation, "strict", error.code(), &error.to_string(), 1),
}
}
@@ -403,12 +271,12 @@ fn load_plugin_into_host(
.parent()
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let manifest = marqdo_plugin_abi::PluginManifest::load(&manifest_path)
let manifest = marqdo_host::plugin::PluginManifest::load(&manifest_path)
.map_err(|error| format!("{}: {}", error.code, error.message))?;
manifest
.validate()
.map_err(|error| format!("{}: {}", error.code, error.message))?;
if manifest.plugin.kind == marqdo_plugin_abi::PluginKind::Native && !trusted {
if manifest.plugin.kind == marqdo_host::plugin::PluginKind::Native && !trusted {
return Err(format!(
"loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation",
manifest.plugin.name
@@ -431,7 +299,8 @@ fn runtime_location_json(
if let Some(located) = project.locate(module_id, span) {
location["line"] = json!(located.line);
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);
}
}
@@ -457,7 +326,6 @@ fn runtime_error_json(error: &RuntimeError, project: &LoadedProject) -> serde_js
"span": location["span"],
"line": location["line"],
"column": location["column"],
"file": location["file"],
"relative_path": location["relative_path"],
"frames": frames,
})
@@ -544,7 +412,7 @@ mod tests {
#[test]
fn strict_json_success_is_forwarded_once() {
let route = classify_strict_outcome(
&outcome(Some(0), None, br#"{"command":"run","success":true}"#, b""),
&outcome(Some(0), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"ok"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.completed","payload":{"status":"ok"}}]}"#, b""),
true,
);
assert_eq!(route, StrictRoute::Forward { exit_code: 0 });
@@ -553,7 +421,7 @@ mod tests {
#[test]
fn strict_json_program_error_is_forwarded_unchanged() {
let route = classify_strict_outcome(
&outcome(Some(2), None, br#"{"command":"run","success":false}"#, b""),
&outcome(Some(2), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"error"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.failed","payload":{"status":"error"}}]}"#, b""),
true,
);
assert_eq!(route, StrictRoute::Forward { exit_code: 2 });
+35 -7
View File
@@ -11,22 +11,50 @@ pub fn check(
) -> i32 {
let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
Err(code) => {
// A failed check never leaves a success artifact behind: a consumer
// must not bind `run` to a previous Analysis after the project
// stopped loading. The input document is never the cleanup target.
if let Some(path) = emit {
if let Err(error) = crate::analysis::discard_without_prepare(file, path) {
eprintln!("error: {error}");
return 2;
}
}
return code;
}
};
let mut project = prepared.loaded;
let mut prepared = prepared;
if refs {
let ref_diagnostics = validate_refs(&project);
project.diagnostics.extend(ref_diagnostics);
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(&project.diagnostics);
let errors = output::error_count(&prepared.loaded.diagnostics);
if let Some(path) = emit {
if errors > 0 {
let _ = std::fs::remove_file(path);
} else if let Err(error) = crate::analysis::write(&project, path) {
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 {
output::print_json(&json!({
"command": "check",
+63 -6
View File
@@ -46,13 +46,20 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
if flags.ast {
object.insert(
"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 {
object.insert(
"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 {
@@ -65,7 +72,9 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
);
}
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 {
object.insert(
@@ -106,13 +115,21 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
if flags.ast {
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 {
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 {
@@ -128,9 +145,14 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
);
}
if flags.refs {
let (references, issues) = refs_json(&prepared, &entry.module_id);
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 {
@@ -149,6 +171,41 @@ pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &
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`.
///
/// Reports declared sources, lock identity, static plugin descriptors and
+115 -310
View File
@@ -4,53 +4,64 @@
//! runtime helpers, but keeps the run session out of the command table.
use super::*;
use crate::execution_events::{EventStream, ObservationOptions};
use crate::observation::{ObservationOptions, ObservationSession, OutputFormat};
use crate::provider_manifest;
use marqdo_sandbox::StrictChildState;
pub fn execute(
file: Option<&Path>,
function: Option<&str>,
named_args: &[(String, Value)],
named_args: Result<Vec<(String, Value)>, String>,
settings: &SandboxSettings,
json: bool,
trace: bool,
observation: Option<&ObservationOptions>,
observation: &ObservationOptions,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
// Open the dedicated protocol channel before any project work so prepare
// and authorization failures can still produce `run.rejected`.
let events = match observation {
Some(options) => match EventStream::open(options) {
Ok(stream) => Some(stream),
Err(error) => {
eprintln!("error[observe.transport_failed]: {error}");
return 1;
}
},
None => None,
};
let stream = events.as_ref();
let prepared = if stream.is_some() {
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, json, command_name, "prepare", &error),
if !observation.enabled() && observation.has_capture_overrides() {
eprintln!(
"error: capture options require --output json, --output jsonl or --observation-file"
);
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
// can still publish a rejection on the requested observation destination.
let events = if observation.enabled() {
match ObservationSession::open(observation) {
Ok(events) => Some(events),
Err(error) => return transport_failure(&error),
}
} else {
match prepare_project(file, json, &settings.plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
}
None
};
let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded;
let static_plugins = prepared.plugins;
if project.has_errors() {
let stream = events.as_ref();
let named_args = match named_args {
Ok(args) => args,
Err(message) => return fail(stream, "options", "cli.invalid_argument", &message, 2),
};
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
let prepared = match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, "prepare", &error),
};
if prepared.loaded.has_errors() {
if let Some(stream) = stream {
let code = project
let code = prepared
.loaded
.diagnostics
.iter()
.find(|item| item.diagnostic.is_error())
@@ -64,39 +75,37 @@ pub fn execute(
return transport_failure(&error);
}
}
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
eprint!("{}", output::render_text(&prepared.loaded.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
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
.diagnostics
.iter()
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !json && !warnings.is_empty() {
if !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
return fail(
stream,
json,
command_name,
"authorization",
"cli.invalid_mode",
&error,
2,
);
return fail(stream, "authorization", "cli.invalid_mode", &error, 2);
}
};
// A project-declared extension is activation, not authorization, but it is
@@ -115,15 +124,7 @@ pub fn execute(
marqdo_package::MANIFEST_FILE,
settings.mode
);
return fail(
stream,
json,
command_name,
"authorization",
code,
&message,
2,
);
return fail(stream, "authorization", code, &message, 2);
}
let mut kernel_paths = settings.kernels.clone();
kernel_paths.extend(
@@ -144,28 +145,8 @@ pub fn execute(
provider_paths.sort();
provider_paths.dedup();
if mode == SandboxMode::Strict {
if stream.is_some() {
return fail(
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
"--event-stream jsonl is not supported under --mode strict; strict refuses \
trace/event artifacts and never downgrades to project mode",
2,
);
}
if let Err(error) = settings.strict_preflight() {
return fail(
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
&error,
2,
);
return fail(stream, "strict", "strict.unsupported_grant", &error, 2);
}
match marqdo_sandbox::inspect_strict_child() {
// A verified supervisor child may run project code.
@@ -174,32 +155,16 @@ pub fn execute(
Ok(StrictChildState::NotChild) => {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(
stream,
json,
command_name,
"strict",
error.code(),
&error.to_string(),
1,
);
return fail(stream, "strict", error.code(), &error.to_string(), 1);
}
return launch_strict_process(&project.root, file, settings, json, command_name);
return launch_strict_process(&project.root, file, settings, stream);
}
// A marker without a verified identity is never trusted, and the
// platform-neutral inspection keeps Linux-only symbols out of this
// module so macOS/Windows builds compile.
Err(reason) => {
let message = format!("strict isolation verification failed: {reason}");
return fail(
stream,
json,
command_name,
"strict",
"strict.identity_invalid",
&message,
1,
);
return fail(stream, "strict", "strict.identity_invalid", &message, 1);
}
}
}
@@ -207,8 +172,6 @@ pub fn execute(
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(
stream,
json,
command_name,
"authorization",
"sandbox.unavailable",
&error.to_string(),
@@ -218,15 +181,7 @@ pub fn execute(
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
return fail(
stream,
json,
command_name,
"authorization",
"cli.invalid_grants",
&error,
2,
);
return fail(stream, "authorization", "cli.invalid_grants", &error, 2);
}
};
let stdin = read_stdin();
@@ -234,18 +189,6 @@ pub fn execute(
if let Some(stream) = stream {
host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
}
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
@@ -260,15 +203,7 @@ pub fn execute(
}
for kernel_path in &kernel_paths {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
return fail(
stream,
json,
command_name,
"prepare",
"ext.kernel_load_failed",
&error,
2,
);
return fail(stream, "prepare", "ext.kernel_load_failed", &error, 2);
}
}
// T6: verify every selected artifact/path/hash before starting a worker or
@@ -282,7 +217,7 @@ pub fn execute(
let providers = match provider_manifest::read_provider_manifests(&provider_paths) {
Ok(providers) => providers,
Err(error) => {
return fail_prepare(stream, json, command_name, "prepare", &error);
return fail_prepare(stream, "prepare", &error);
}
};
// `--provider` alone never authorizes; the exact `--allow-provider NAME`
@@ -302,7 +237,7 @@ pub fn execute(
provider.name, provider.name
),
);
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
// A grant that matches no selected provider is a deterministic option
@@ -317,7 +252,7 @@ pub fn execute(
providers are never discovered automatically"
),
);
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
for plugin in &static_plugins.plugins {
@@ -325,31 +260,27 @@ pub fn execute(
&plugin.base_dir,
&plugin.artifact_relative,
) {
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
let artifact = plugin.artifact_path();
if let Err(error) = extension_descriptors::verify_sha256(&artifact, &plugin.artifact_sha256)
{
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
// A native plugin shares this process and can write fd 1 directly, so it
// can pollute the JSONL channel. Fail closed rather than presenting
// untrusted raw bytes as program stdout (RFC-OBS-0001 §4.4/§9.2, T26).
// An in-process native plugin can write directly to the inherited fds.
// Require a controlled channel before publishing observed program bytes.
if stream.is_some()
&& static_plugins
.plugins
.iter()
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native)
.any(|plugin| plugin.kind == marqdo_host::plugin::PluginKind::Native)
{
return fail(
stream,
json,
command_name,
"authorization",
"ext.event_stream_unsupported_native_plugin",
"--event-stream jsonl cannot guarantee a clean channel with an in-process native \
plugin; use a worker plugin or disable event mode",
"ext.observation_unsupported_native_plugin",
"observation requires a controlled output channel; use a worker plugin or text output without a snapshot",
2,
);
}
@@ -362,8 +293,6 @@ pub fn execute(
) {
return fail(
stream,
json,
command_name,
"authorization",
"ext.plugin_load_failed",
&message,
@@ -376,8 +305,6 @@ pub fn execute(
if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) {
return fail(
stream,
json,
command_name,
"authorization",
"ext.plugin_binding_mismatch",
&message,
@@ -393,7 +320,7 @@ pub fn execute(
provider,
&settings.allow_provider,
) {
return fail_prepare(stream, json, command_name, "prepare", &error);
return fail_prepare(stream, "prepare", &error);
}
}
let function_name = function.unwrap_or("main").to_string();
@@ -411,15 +338,7 @@ pub fn execute(
project.entry_file().path.display()
)
};
return fail(
stream,
json,
command_name,
"compile",
"sem.no_entry_function",
&message,
1,
);
return fail(stream, "compile", "sem.no_entry_function", &message, 1);
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
@@ -435,17 +354,17 @@ pub fn execute(
};
if let Some(stream) = stream {
let entry = format!("{}::{}", project.entry, function_name);
let analysis_digest = format!("sha256:{}", crate::analysis::digest(&project));
let analysis_digest = analysis_digest.as_deref().unwrap_or_default();
if let Err(error) = stream.started(
&entry,
mode.as_str(),
&project.identity.root_id(),
&analysis_digest,
analysis_digest,
) {
return transport_failure(&error);
}
}
let mut result = run_with_limits(
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
@@ -453,128 +372,45 @@ pub fn execute(
runtime_args,
memory_limits,
);
// A dead event pipe is a run failure even if the program itself returned.
if result.is_ok() {
if let Some(message) = host.observation_failure() {
result = Err(RuntimeError::new(
marqdo_value::ErrorCategory::Observation,
None,
format!("observe.transport_failed: {message}"),
));
}
}
let trace_run_id = stream.map(EventStream::run_id);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(
&project,
&host,
&entry,
status,
path,
trace_run_id.as_deref(),
) {
if let Some(stream) = stream {
let _ = stream.failed_error("cli.trace_failed", &error);
} else {
emit_error(json, command_name, "cli.trace_failed", &error);
}
return 1;
}
}
if let Some(stream) = stream {
// The program's stdout/stderr were already emitted as chunk events at
// their real host commit points; never replay them on this channel.
match &result {
Ok(outcome) => {
if let Err(error) = stream.completed(&outcome.value) {
return transport_failure(&error);
}
}
Err(error) => {
if let Err(write_error) = stream.failed(error) {
eprintln!("error[observe.transport_failed]: {write_error}");
}
eprint!("{}", render_runtime_error(error, &project));
return 1;
}
if let Some(error) = host.observation_failure() {
return transport_failure(error);
}
let delivered = match &result {
Ok(outcome) => stream.completed(&outcome.value),
Err(error) => stream.failed(runtime_error_json(error, &project)),
};
if let Err(error) = delivered {
return transport_failure(&error);
}
return 0;
}
let stdout = host.take_output();
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
let stderr = host.take_error();
let stderr_text = String::from_utf8_lossy(&stderr).to_string();
let trace_entries = host.trace().to_vec();
match result {
Ok(outcome) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
if observation.output == OutputFormat::Text {
use std::io::Write;
let _ = std::io::stderr().write_all(&host.take_error());
let _ = std::io::stdout().write_all(&host.take_output());
if let (Some(_), Ok(outcome)) = (function, &result) {
if outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
0
}
}
match result {
Ok(_) => 0,
Err(error) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
eprint!("{}", render_runtime_error(&error, &project));
1
}
}
}
fn transport_failure(error: &str) -> i32 {
pub(super) fn transport_failure(error: &str) -> i32 {
eprintln!("error[observe.transport_failed]: {error}");
1
}
/// Emit one pre-execution rejection (or the legacy non-event error form).
fn fail(
stream: Option<&EventStream>,
json: bool,
command_name: &str,
/// Report a failure before the interpreter starts.
pub(super) fn fail(
stream: Option<&ObservationSession>,
phase: &str,
code: &str,
message: &str,
@@ -585,47 +421,16 @@ fn fail(
return transport_failure(&error);
}
}
if json && stream.is_none() {
emit_error(json, command_name, code, message);
} else {
eprintln!("error[{code}]: {message}");
}
eprintln!("error[{code}]: {message}");
exit
}
/// Emit one prepare/authorization rejection using a `PrepareError`.
fn fail_prepare(
stream: Option<&EventStream>,
json: bool,
command_name: &str,
stream: Option<&ObservationSession>,
phase: &str,
error: &crate::extension_descriptors::PrepareError,
) -> i32 {
if let Some(stream) = stream {
if let Err(write_error) = stream.rejected(phase, &error.code, &error.message) {
return transport_failure(&write_error);
}
eprintln!("error[{}]: {}", error.code, error.message);
} else {
emit_prepare_error(json, command_name, error);
}
error.exit_code
}
fn emit_prepare_error(
json: bool,
command_name: &str,
error: &crate::extension_descriptors::PrepareError,
) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": {"code": error.code, "message": error.message},
}));
} else {
eprintln!("error[{}]: {}", error.code, error.message);
}
fail(stream, phase, &error.code, &error.message, error.exit_code)
}
/// Compare the Host's actual plugin exports with the static manifest set.
@@ -753,9 +558,9 @@ mod tests {
base_dir: PathBuf::from("/fixtures/demo"),
package: "demo.ext".into(),
version: "0.1.0".into(),
kind: marqdo_plugin_abi::PluginKind::Worker,
kind: marqdo_host::plugin::PluginKind::Worker,
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
artifact_target: marqdo_plugin_abi::HostTarget::current()
artifact_target: marqdo_host::plugin::HostTarget::current()
.triple()
.to_string(),
artifact_sha256: "a".repeat(64),
+3 -10
View File
@@ -49,12 +49,6 @@ pub struct SandboxSettings {
pub allow_provider: Vec<String>,
/// Explicit trust decision for in-process native plugin loading.
pub trust_native_plugin: bool,
/// Optional Trace v2 output path.
pub trace_file: Option<PathBuf>,
/// Trace event budget override (0 = unlimited).
pub trace_max_events: Option<usize>,
/// Trace approximate byte budget override (0 = unlimited).
pub trace_max_bytes: Option<usize>,
/// External foreign-kernel descriptor paths.
pub kernels: Vec<PathBuf>,
}
@@ -72,7 +66,7 @@ impl SandboxSettings {
/// Reject strict-mode requests that this L1 isolation level does not
/// support. Strict currently covers pure Marqdo and native Math only;
/// granting Foreign, ABI plugins, resource providers, tools or trace files
/// granting Foreign, ABI plugins, resource providers or tools
/// would require extending the supervisor contract first.
pub fn strict_preflight(&self) -> Result<(), String> {
let requested = self.allow_foreign
@@ -87,14 +81,13 @@ impl SandboxSettings {
|| !self.providers.is_empty()
|| !self.allow_provider.is_empty()
|| self.trust_native_plugin
|| !self.kernels.is_empty()
|| self.trace_file.is_some();
|| !self.kernels.is_empty();
if requested {
return Err(
"strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\
--trust-native-plugin/--kernel/--trace-file are rejected. \
--trust-native-plugin/--kernel are rejected. \
Use --mode project for those capabilities."
.to_string(),
);
+2 -2
View File
@@ -44,7 +44,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
.parent()
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
let manifest = match marqdo_host::plugin::PluginManifest::load(&manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
report_plugin_error(&error, json);
@@ -55,7 +55,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
report_plugin_error(&error, json);
return 1;
}
let host_target = marqdo_plugin_abi::HostTarget::current();
let host_target = marqdo_host::plugin::HostTarget::current();
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
Ok((path, artifact)) => {
let abi = match manifest.abi_requirement() {
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -10,9 +10,9 @@
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use marqdo_host::plugin::{HostTarget, PluginKind, PluginManifest};
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
use marqdo_ir::SignatureKind;
use marqdo_plugin_abi::{HostTarget, PluginKind, PluginManifest};
use marqdo_span::Span;
use sha2::{Digest, Sha256};
+4 -4
View File
@@ -81,12 +81,12 @@ fn plugin_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
),
)
})?;
let manifest = marqdo_plugin_abi::PluginManifest::load(&extension.path)
let manifest = marqdo_host::plugin::PluginManifest::load(&extension.path)
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
manifest
.validate()
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
let host = marqdo_plugin_abi::HostTarget::current();
let host = marqdo_host::plugin::HostTarget::current();
let artifact = manifest
.resolve_artifact(&host)
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
@@ -161,7 +161,7 @@ fn provider_identity(extension: &ResolvedExtension) -> Result<LockedExtension, P
format!("`{}` has no version", extension.path.display()),
)
})?;
let target = marqdo_plugin_abi::HostTarget::current()
let target = marqdo_host::plugin::HostTarget::current()
.triple()
.to_string();
let artifacts = manifest
@@ -293,7 +293,7 @@ fn kernel_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
version: format!("wire:{wire_version}"),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: digest.to_ascii_lowercase(),
selected_target: marqdo_plugin_abi::HostTarget::current()
selected_target: marqdo_host::plugin::HostTarget::current()
.triple()
.to_string(),
source: extension.from.clone(),
+81 -31
View File
@@ -119,6 +119,14 @@ fn source_digest(source: &str) -> String {
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.
pub struct LocatedSource<'a> {
/// The owning file.
@@ -167,6 +175,13 @@ pub struct LoadedProject {
pub manifest: Option<Manifest>,
/// Verified lock file, when present (lock v4).
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).
pub extension_sources: Vec<marqdo_package::ResolvedExtension>,
}
@@ -201,29 +216,6 @@ impl LoadedProject {
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 {
@@ -251,19 +243,32 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from(".")),
};
let manifest = if root.join(MANIFEST_FILE).is_file() {
Some(Manifest::load(&root.join(MANIFEST_FILE))?)
// Read each snapshot input exactly once. The digest recorded in Analysis
// 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 {
None
(None, String::new())
};
let lock = if root.join(LOCK_FILE).is_file() {
let lock = LockFile::load(&root.join(LOCK_FILE))
.map_err(|error| format!("{LOCK_FILE}: {error}"))?;
let lock_path = root.join(LOCK_FILE);
let (lock, lock_digest) = if lock_path.is_file() {
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 {
lock.validate_root(manifest)
.map_err(|error| format!("{LOCK_FILE}: {error}"))?;
}
Some(lock)
(Some(lock), bytes_digest(&bytes))
} else {
if manifest
.as_ref()
@@ -275,7 +280,7 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
.to_string(),
);
}
None
(None, String::new())
};
let resolver = PackageResolver::new(root.clone(), manifest.clone(), lock.clone());
let entry_module = resolver.resolve_entry(&entry)?;
@@ -326,6 +331,8 @@ pub fn load(entry: &Path) -> Result<LoadedProject, String> {
official_aliases,
manifest,
lock,
lock_digest,
manifest_digest,
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 => {}
}
}
#[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);
}
}
+37 -102
View File
@@ -7,16 +7,16 @@
mod analysis;
mod args;
mod commands;
mod execution_events;
mod document_refs;
mod extension_descriptors;
mod extension_selection;
mod loader;
mod observation;
mod output;
mod project_prepare;
mod provider_manifest;
mod stdlib;
mod tool;
mod trace;
use std::ffi::OsString;
use std::path::PathBuf;
@@ -35,69 +35,44 @@ struct Cli {
command: Command,
}
/// Execution Events v1 options (RFC-OBS-0001).
///
/// `--event-stream jsonl` makes the CLI stdout a dedicated NDJSON channel;
/// program stdout/stderr become events. It is mutually exclusive with
/// `--json` and is not accepted by static commands.
/// Output and capture options for run and call.
#[derive(Args, Clone)]
struct ObserveArgs {
/// Stream Execution Events v1 as JSON Lines on stdout (only `jsonl`).
#[arg(
long = "event-stream",
value_name = "FORMAT",
value_parser = [execution_events::FORMAT_JSONL],
conflicts_with = "json"
)]
event_stream: Option<String>,
/// Select terminal text, a JSON observation snapshot or live JSON Lines.
#[arg(long, value_enum, default_value = "text")]
output: observation::OutputFormat,
/// Atomically save a private observation snapshot of this run.
#[arg(long, value_name = "PATH")]
observation_file: Option<PathBuf>,
/// Publish the value of one exactly named local variable (repeatable).
#[arg(
long = "observe-variable",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-variable", value_name = "NAME")]
observe_variable: Vec<String>,
/// Publish the value of one exactly named parameter (repeatable).
#[arg(
long = "observe-parameter",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-parameter", value_name = "NAME")]
observe_parameter: Vec<String>,
/// Allow selected Text values to be published (second explicit consent).
#[arg(long = "observe-text-values", requires = "event_stream")]
#[arg(long = "observe-text-values")]
observe_text_values: bool,
/// Maximum encoded source bytes for one observed value (0 = unlimited).
#[arg(
long = "observe-max-value-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-value-bytes", value_name = "BYTES")]
observe_max_value_bytes: Option<usize>,
/// Override the structural/value event budget (0 = unlimited).
#[arg(
long = "observe-max-events",
value_name = "COUNT",
requires = "event_stream"
)]
#[arg(long = "observe-max-events", value_name = "COUNT")]
observe_max_events: Option<u64>,
/// Override the approximate structural/value byte budget (0 = unlimited).
#[arg(
long = "observe-max-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-bytes", value_name = "BYTES")]
observe_max_bytes: Option<u64>,
}
impl ObserveArgs {
fn options(&self) -> Option<execution_events::ObservationOptions> {
self.event_stream.as_ref()?;
let mut options = execution_events::ObservationOptions {
fn options(&self) -> observation::ObservationOptions {
let mut options = observation::ObservationOptions {
output: self.output,
file: self.observation_file.clone(),
variables: self.observe_variable.clone(),
parameters: self.observe_parameter.clone(),
allow_text_values: self.observe_text_values,
..execution_events::ObservationOptions::default()
..observation::ObservationOptions::default()
};
if let Some(bytes) = self.observe_max_value_bytes {
options.max_value_bytes = bytes;
@@ -108,7 +83,7 @@ impl ObserveArgs {
if let Some(bytes) = self.observe_max_bytes {
options.max_bytes = bytes;
}
Some(options)
options
}
}
@@ -220,15 +195,6 @@ struct SandboxArgs {
/// (repeatable; wildcards are not supported).
#[arg(long = "allow-provider", value_name = "NAME")]
allow_provider: Vec<String>,
/// Write a versioned Trace v2 file for this run.
#[arg(long = "trace-file", value_name = "PATH")]
trace_file: Option<PathBuf>,
/// Override the trace event budget (0 = unlimited).
#[arg(long = "trace-max-events")]
trace_max_events: Option<usize>,
/// Override the approximate trace byte budget (0 = unlimited).
#[arg(long = "trace-max-bytes")]
trace_max_bytes: Option<usize>,
/// Register an external foreign-kernel provider (repeatable).
#[arg(long = "kernel", value_name = "PATH")]
kernel: Vec<PathBuf>,
@@ -259,9 +225,6 @@ impl SandboxArgs {
providers: self.provider.clone(),
allow_provider: self.allow_provider.clone(),
trust_native_plugin: self.trust_native_plugin,
trace_file: self.trace_file.clone(),
trace_max_events: self.trace_max_events,
trace_max_bytes: self.trace_max_bytes,
kernels: self.kernel.clone(),
}
}
@@ -273,12 +236,6 @@ struct RunArgs {
file: Option<PathBuf>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output; program stdout is embedded, never mixed.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -294,12 +251,6 @@ struct CallArgs {
args: Vec<String>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -314,7 +265,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Write public Analysis JSON, using v3 for projects with loop transfers.
/// Write the current public Analysis JSON for the checked project.
#[arg(long, value_name = "PATH")]
emit: Option<PathBuf>,
/// Machine readable JSON output.
@@ -514,36 +465,20 @@ fn dispatch() -> i32 {
};
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
}
Command::Run(args) => {
let observation = args.observe.options();
commands::execute(
args.file.as_deref(),
None,
&[],
&args.sandbox.settings(),
args.json,
args.trace,
observation.as_ref(),
)
}
Command::Call(args) => match commands::parse_named_args(&args.args) {
Ok(named) => {
let observation = args.observe.options();
commands::execute(
Some(&args.file),
Some(&args.function),
&named,
&args.sandbox.settings(),
args.json,
args.trace,
observation.as_ref(),
)
}
Err(error) => {
eprintln!("error: {error}");
2
}
},
Command::Run(args) => commands::execute(
args.file.as_deref(),
None,
Ok(Vec::new()),
&args.sandbox.settings(),
&args.observe.options(),
),
Command::Call(args) => commands::execute(
Some(&args.file),
Some(&args.function),
commands::parse_named_args(&args.args),
&args.sandbox.settings(),
&args.observe.options(),
),
Command::Fmt(args) => commands::fmt(args.file.as_deref(), args.check),
Command::Plugin(args) => match args.command {
PluginCommand::Inspect(args) => commands::plugin_inspect(&args.target, args.json),
@@ -565,7 +500,7 @@ fn dispatch() -> i32 {
},
Command::External(args) => tool::dispatch(&args),
Command::PluginWorker(args) => {
marqdo_plugin_abi::worker::serve(&args.manifest, &args.base_dir)
marqdo_host::plugin::worker::serve(&args.manifest, &args.base_dir)
}
}
}
@@ -1,36 +1,38 @@
//! Execution Events v1 JSONL writer and public envelope.
//!
//! Normative contract: `spec/execution-events-v1.md`; decision record:
//! ADR-0059. The host owns the typed events; this module only assigns the
//! public envelope/sequence, encodes bytes as base64 and writes one flushed
//! line per event to the CLI protocol stdout.
//!
//! There is no HTTP, SSE, WebSocket, View or Agent branch here.
//! Deliver the Host observation sequence to JSONL or atomic JSON snapshots.
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::io::{self, Write};
use std::io::{self, Seek, Write};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::{SystemTime, UNIX_EPOCH};
use marqdo_host::{
FrameId, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES,
ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ValueState,
DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES,
};
use marqdo_value::{RuntimeError, Value};
use marqdo_host_contract::{FrameId, ParameterSource};
use marqdo_value::Value;
use serde_json::{json, Value as Json};
/// Public schema name.
pub const SCHEMA: &str = "marqdo.execution-events";
pub const SCHEMA: &str = "marqdo.observation";
/// Public schema major version.
pub const SCHEMA_VERSION: u32 = 1;
/// The only accepted `--event-stream` format in v1.
pub const FORMAT_JSONL: &str = "jsonl";
/// Delivery format on stdout.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Text,
Json,
Jsonl,
}
/// CLI observation options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObservationOptions {
pub output: OutputFormat,
pub file: Option<PathBuf>,
/// Exact local-variable names selected with `--observe-variable`.
pub variables: Vec<String>,
/// Exact parameter names selected with `--observe-parameter`.
@@ -48,6 +50,8 @@ pub struct ObservationOptions {
impl Default for ObservationOptions {
fn default() -> Self {
Self {
output: OutputFormat::Text,
file: None,
variables: Vec::new(),
parameters: Vec::new(),
allow_text_values: false,
@@ -59,6 +63,20 @@ impl Default for ObservationOptions {
}
impl ObservationOptions {
pub fn enabled(&self) -> bool {
self.output != OutputFormat::Text || self.file.is_some()
}
pub fn has_capture_overrides(&self) -> bool {
let defaults = Self::default();
!self.variables.is_empty()
|| !self.parameters.is_empty()
|| self.allow_text_values
|| self.max_value_bytes != defaults.max_value_bytes
|| self.max_events != defaults.max_events
|| self.max_bytes != defaults.max_bytes
}
/// Typed host policy for this run.
pub fn config(&self) -> ObservationConfig {
ObservationConfig {
@@ -73,15 +91,15 @@ impl ObservationOptions {
}
}
/// One run's JSONL writer, shared with the host sink.
/// One run and event sequence, shared with the host observation sink.
#[derive(Clone)]
pub struct EventStream {
inner: Rc<RefCell<JsonlWriter>>,
pub struct ObservationSession {
inner: Rc<RefCell<EventWriter>>,
config: ObservationConfig,
}
impl EventStream {
/// Open the protocol channel and write `stream.opened` as `seq: 0`.
impl ObservationSession {
/// Set up all destinations and publish the first event.
pub fn open(options: &ObservationOptions) -> Result<Self, String> {
let run_id = new_run_id();
let config = options.config();
@@ -90,10 +108,6 @@ impl EventStream {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
},
"protocol": {
"name": SCHEMA,
"schema_version": SCHEMA_VERSION,
},
"observation": {
"level": config.level(),
"values": config.values_enabled(),
@@ -107,10 +121,15 @@ impl EventStream {
"max_value_bytes": config.max_value_bytes,
},
});
let mut writer = JsonlWriter {
out: Box::new(io::stdout()),
run_id: run_id.clone(),
let mut writer = EventWriter {
output: options.output,
snapshot: Snapshot::open(options)?,
run_id,
seq: 0,
source: Json::Null,
truncated: Json::Null,
capture: opened["observation"].clone(),
failed: false,
};
writer.emit("stream.opened", opened)?;
Ok(Self {
@@ -119,11 +138,6 @@ impl EventStream {
})
}
/// Opaque run identity shared with Trace v2 when both are requested.
pub fn run_id(&self) -> String {
self.inner.borrow().run_id.clone()
}
/// Typed policy (used to install the host sink).
pub fn config(&self) -> ObservationConfig {
self.config.clone()
@@ -163,40 +177,26 @@ impl EventStream {
)
}
/// Write the successful terminal event.
/// Write the successful terminal event and its explicitly returned result.
pub fn completed(&self, value: &Value) -> Result<(), String> {
let transferable = !value.contains_memory()
&& !value.contains_resource()
&& !marqdo_host::contains_plugin_handle(value);
let wire = transferable.then(|| marqdo_value::to_wire(value));
self.emit(
"run.completed",
json!({"status": "ok", "value": marqdo_value::to_wire(value)}),
json!({"status": "ok", "value": wire, "value_type": value.type_name()}),
)
}
/// Write the failed terminal event.
pub fn failed(&self, error: &RuntimeError) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {
"code": error.code(),
"message": error.message,
"module_id": error.module_id.as_deref(),
"span": error.span.map(span_json),
}
}),
)
pub fn failed(&self, error: Json) -> Result<(), String> {
self.emit("run.failed", json!({"status": "error", "error": error}))
}
/// Write a failed terminal event for a CLI-level failure that still has a
/// stable code (for example `cli.trace_failed`).
pub fn failed_error(&self, code: &str, message: &str) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {"code": code, "message": message},
}),
)
/// Deliver a snapshot without a terminal event when isolation interrupted a run.
pub fn incomplete(&self) -> Result<(), String> {
self.inner.borrow_mut().finish_snapshot("incomplete")
}
/// Write the pre-execution rejection terminal event.
@@ -220,7 +220,7 @@ impl EventStream {
/// `ObservationSink` adapter installed into `StdHost`.
pub struct HostEventSink {
stream: EventStream,
stream: ObservationSession,
}
impl ObservationSink for HostEventSink {
@@ -231,14 +231,105 @@ impl ObservationSink for HostEventSink {
}
}
struct JsonlWriter {
out: Box<dyn Write>,
run_id: String,
seq: u64,
struct Snapshot {
staging: tempfile::NamedTempFile,
path: Option<PathBuf>,
}
impl JsonlWriter {
impl Snapshot {
fn open(options: &ObservationOptions) -> Result<Option<Self>, String> {
if options.output != OutputFormat::Json && options.file.is_none() {
return Ok(None);
}
let staging = if let Some(path) = &options.file {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create observation directory: {error}"))?;
tempfile::NamedTempFile::new_in(parent)
} else {
tempfile::NamedTempFile::new()
}
.map_err(|error| format!("cannot stage observation snapshot: {error}"))?;
let mut snapshot = Self {
staging,
path: options.file.clone(),
};
snapshot.write(b"{\"events\":[")?;
Ok(Some(snapshot))
}
fn write(&mut self, bytes: &[u8]) -> Result<(), String> {
self.staging
.write_all(bytes)
.map_err(|error| format!("cannot write observation snapshot: {error}"))
}
fn finish(mut self, metadata: Json, stdout: bool) -> Result<(), String> {
let suffix = serde_json::to_vec(&metadata)
.map_err(|error| format!("cannot encode observation metadata: {error}"))?;
self.write(b"],")?;
self.write(&suffix[1..])?;
self.write(b"\n")?;
if let Some(path) = &self.path {
self.staging
.as_file()
.sync_all()
.map_err(|error| format!("cannot sync observation snapshot: {error}"))?;
let mut file = self
.staging
.persist(path)
.map_err(|error| format!("cannot publish observation snapshot: {error}"))?;
if stdout {
write_snapshot_stdout(&mut file)?;
}
} else {
write_snapshot_stdout(self.staging.as_file_mut())?;
}
Ok(())
}
}
fn write_snapshot_stdout(file: &mut std::fs::File) -> Result<(), String> {
let mut out = io::stdout().lock();
file.rewind()
.and_then(|()| io::copy(file, &mut out))
.and_then(|_| out.flush())
.map_err(|error| format!("cannot write observation snapshot to stdout: {error}"))
}
struct EventWriter {
output: OutputFormat,
snapshot: Option<Snapshot>,
run_id: String,
seq: u64,
source: Json,
truncated: Json,
capture: Json,
failed: bool,
}
impl EventWriter {
fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> {
if self.failed {
return Err("observation transport already failed".into());
}
let result = self.deliver(kind, payload);
if result.is_err() {
self.failed = true;
self.snapshot.take();
}
result
}
fn deliver(&mut self, kind: &str, payload: Json) -> Result<(), String> {
match kind {
"run.started" => self.source = payload["source"].clone(),
"observation.truncated" => self.truncated = payload.clone(),
_ => {}
}
let event = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
@@ -247,18 +338,78 @@ impl JsonlWriter {
"kind": kind,
"payload": payload,
});
let mut line = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode execution event: {error}"))?;
line.push(b'\n');
// Flush each line: line-buffered batching would hide real-time output
// behind the run duration (RFC-OBS-0001 §5.2).
self.out
.write_all(&line)
.and_then(|()| self.out.flush())
.map_err(|error| format!("cannot write execution event stream: {error}"))?;
let mut bytes = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode observation event: {error}"))?;
if let Some(snapshot) = &mut self.snapshot {
if self.seq != 0 {
snapshot.write(b",")?;
}
snapshot.write(&bytes)?;
}
if matches!(kind, "run.completed" | "run.failed" | "run.rejected") {
self.finish_snapshot(payload["status"].as_str().expect("terminal status"))?;
}
if self.output == OutputFormat::Jsonl {
let mut out = io::stdout().lock();
bytes.push(b'\n');
out.write_all(&bytes)
.and_then(|()| out.flush())
.map_err(|error| format!("cannot write observation stream: {error}"))?;
}
self.seq += 1;
Ok(())
}
fn finish_snapshot(&mut self, status: &str) -> Result<(), String> {
let Some(snapshot) = self.snapshot.take() else {
return Ok(());
};
let mut capture = self.capture.clone();
capture["truncated"] = self.truncated.clone();
snapshot.finish(
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": self.run_id, "status": status, "source": self.source},
"capture": capture,
}),
self.output == OutputFormat::Json,
)
}
}
/// The strict supervisor forwards only a complete current snapshot.
pub fn is_complete_snapshot(bytes: &[u8], exit_code: i32) -> bool {
let Ok(snapshot) = serde_json::from_slice::<Json>(bytes) else {
return false;
};
let Some(events) = snapshot["events"].as_array() else {
return false;
};
let Some(run_id) = snapshot["run"]["id"].as_str() else {
return false;
};
let Some(last) = events.last() else {
return false;
};
let status = match last["kind"].as_str() {
Some("run.completed") if exit_code == 0 => "ok",
Some("run.failed") if exit_code != 0 => "error",
Some("run.rejected") if exit_code != 0 => "rejected",
_ => return false,
};
snapshot["schema"] == SCHEMA
&& snapshot["schema_version"] == SCHEMA_VERSION
&& snapshot["run"]["status"] == status
&& snapshot["capture"].is_object()
&& last["payload"]["status"] == status
&& events[0]["kind"] == "stream.opened"
&& events.iter().enumerate().all(|(seq, event)| {
event["schema"] == SCHEMA
&& event["schema_version"] == SCHEMA_VERSION
&& event["run_id"] == run_id
&& event["seq"] == seq
})
}
fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
@@ -365,6 +516,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
}),
),
ObservationEvent::Effect {
frame_id,
operation,
result_code,
module_id,
@@ -372,6 +524,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
} => (
"effect",
json!({
"frame_id": frame_id.map(FrameId::as_wire),
"operation": operation,
"result_code": result_code,
"module_id": module_id,
+2 -2
View File
@@ -16,8 +16,8 @@
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use marqdo_host::plugin::{HostTarget, TargetTriple};
use marqdo_host::StdHost;
use marqdo_plugin_abi::{HostTarget, TargetTriple};
use serde::Deserialize;
use sha2::{Digest, Sha256};
@@ -577,7 +577,7 @@ fn is_lowercase_sha256(value: &str) -> bool {
}
fn is_known_capability(name: &str) -> bool {
marqdo_plugin_abi::KNOWN_CAPABILITIES.contains(&name)
marqdo_host::plugin::KNOWN_CAPABILITIES.contains(&name)
}
/// A dotted vendor capability proposal (validation only, never a grant).
+66 -60
View File
@@ -45,24 +45,33 @@ pub struct StdlibBundle {
impl StdlibBundle {
/// Discover the bundle.
///
/// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid), a `stdlib`
/// directory next to the executable, and finally — **debug builds only** — the
/// compile-time source tree. A release binary never falls back to a build
/// machine path: the release archive must ship a verified `stdlib/` next to
/// the binary (RFC-EXT-0003 H-08, ADR).
/// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid) then a `stdlib`
/// directory next to the executable. The official Bundle is an installed
/// artifact next to the binary (RFC-EXT-0003 H-08, ADR-0070); there is no
/// compile-time source-tree fallback in any build profile.
pub fn discover() -> Result<Option<Self>, String> {
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
return Self::load(PathBuf::from(dir)).map(Some);
let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from);
let exe_dir = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf));
Self::discover_with(override_dir, exe_dir)
}
/// Discovery with the explicit override and the executable directory passed
/// in. The override is authoritative: a bad `MARQDO_STDLIB_DIR` fails even
/// when a valid sibling Bundle exists (no silent fallback).
fn discover_with(
override_dir: Option<PathBuf>,
exe_dir: Option<PathBuf>,
) -> Result<Option<Self>, String> {
if let Some(dir) = override_dir {
return Self::load(dir).map(Some);
}
Self::discover_from_exe_dir(
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf)),
)
Self::discover_from_exe_dir(exe_dir)
}
/// Discover from the directory that holds the executable, without the explicit
/// environment override. Release builds do not read the source tree.
/// environment override. Only the installed sibling Bundle is considered.
fn discover_from_exe_dir(exe_dir: Option<PathBuf>) -> Result<Option<Self>, String> {
if let Some(parent) = exe_dir {
let candidate = parent.join("stdlib");
@@ -70,16 +79,6 @@ impl StdlibBundle {
return Self::load(candidate).map(Some);
}
}
#[cfg(debug_assertions)]
{
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("stdlib");
if dev.is_dir() {
return Self::load(dev).map(Some);
}
}
Ok(None)
}
@@ -454,21 +453,41 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String {
mod tests {
use super::*;
fn dev_bundle() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("stdlib")
/// A small synthetic Bundle so loader unit tests never depend on the
/// product tree (ADR-0070 test-lane separation).
fn write_synthetic_bundle(root: &Path) {
for (relative, body) in [
("io.mq.md", "## @knowledge test\n"),
("io/console.mq.md", "## @knowledge console\n"),
] {
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, body).unwrap();
}
let digest = tree_digest(root).unwrap();
let manifest = serde_json::json!({
"name": "test-stdlib",
"version": "0.0.0-test",
"digest": digest,
});
std::fs::write(
root.join("stdlib.json"),
serde_json::to_vec(&manifest).unwrap(),
)
.unwrap();
}
#[test]
fn dev_bundle_verifies_and_resolves() {
let bundle = StdlibBundle::load(dev_bundle()).unwrap();
assert!(bundle.digest.starts_with("sha256:"));
fn synthetic_bundle_verifies_and_resolves() {
let dir = tempfile::tempdir().unwrap();
write_synthetic_bundle(dir.path());
let bundle = StdlibBundle::load(dir.path()).unwrap();
assert_eq!(bundle.version(), "0.0.0-test");
let io = bundle.resolve("io").unwrap();
assert_eq!(io.relative_path, "io.mq.md");
assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@"));
assert!(io.package.instance_id.starts_with("std:test-stdlib@"));
assert!(bundle.resolve("../escape").is_err());
assert!(bundle.resolve("/absolute").is_err());
}
#[test]
@@ -476,44 +495,31 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let bundle = dir.path().join("stdlib");
std::fs::create_dir_all(&bundle).unwrap();
for entry in std::fs::read_dir(dev_bundle()).unwrap() {
let entry = entry.unwrap();
let target = bundle.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), target).unwrap();
}
}
write_synthetic_bundle(&bundle);
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
.unwrap()
.expect("sibling stdlib");
assert_eq!(found.root, bundle.canonicalize().unwrap());
assert_eq!(found.root(), bundle.canonicalize().unwrap());
}
fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let destination = target.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &destination);
} else {
std::fs::copy(entry.path(), destination).unwrap();
}
}
#[test]
fn bad_override_fails_closed_even_with_a_valid_sibling() {
let dir = tempfile::tempdir().unwrap();
let sibling = dir.path().join("stdlib");
std::fs::create_dir_all(&sibling).unwrap();
write_synthetic_bundle(&sibling);
let error = StdlibBundle::discover_with(
Some(dir.path().join("missing")),
Some(dir.path().to_path_buf()),
)
.unwrap_err();
assert!(error.contains("cannot open stdlib directory"), "{error}");
}
#[test]
fn digest_tamper_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let source = dev_bundle();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
if entry.path().is_file() {
std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap();
}
}
write_synthetic_bundle(dir.path());
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
let error = StdlibBundle::load(dir.path()).unwrap_err();
assert!(error.contains("digest mismatch"), "{error}");
+89 -137
View File
@@ -1,4 +1,4 @@
//! Generic external CLI tool protocol (spec/tool-v1.md).
//! Generic external CLI tool protocol (spec/cli-tool.md).
//!
//! The core never knows a tool's name. It validates a user-supplied
//! `tool.json`, verifies protocol compatibility, copies the whole bundle into a
@@ -11,7 +11,7 @@ use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::process::Command as ProcessCommand;
use semver::{Version, VersionReq};
use semver::Version;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@@ -21,22 +21,7 @@ const RECORD_VERSION: u32 = 2;
const MAX_BUNDLE_FILES: usize = 4096;
const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024;
/// Protocols this core can provide to tools.
#[derive(Debug, Clone, Copy)]
struct SupportedProtocols {
tool: u32,
analysis: &'static [u32],
trace: &'static [u32],
}
const SUPPORTED: SupportedProtocols = SupportedProtocols {
tool: PROTOCOL_VERSION,
analysis: &[
crate::analysis::BASE_VERSION,
crate::analysis::LOOP_CONTROL_VERSION,
],
trace: &[2],
};
const API_REVISION: u32 = 1;
const BUILTIN_COMMANDS: &[&str] = &[
"init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync",
@@ -44,6 +29,7 @@ const BUILTIN_COMMANDS: &[&str] = &[
];
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolManifest {
schema: String,
schema_version: u32,
@@ -51,38 +37,29 @@ struct ToolManifest {
version: String,
command: String,
entrypoint: PathBuf,
#[serde(default)]
compatibility: Compatibility,
requires: Requirements,
}
#[derive(Debug, Clone, Default, Deserialize)]
struct Compatibility {
#[serde(default)]
marqdo: Option<String>,
#[serde(default)]
analysis: Option<Vec<u32>>,
#[serde(default)]
trace: Option<Vec<u32>>,
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Requirements {
api_revision: u32,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "read_requirement"
)]
analysis: Option<u32>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "read_requirement"
)]
observation: Option<u32>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct RecordedCompatibility {
#[serde(default, skip_serializing_if = "Option::is_none")]
marqdo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
analysis: Option<Vec<u32>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
trace: Option<Vec<u32>>,
}
impl RecordedCompatibility {
fn as_compatibility(&self) -> Compatibility {
Compatibility {
marqdo: self.marqdo.clone(),
analysis: self.analysis.clone(),
trace: self.trace.clone(),
}
}
fn read_requirement<'de, D: serde::Deserializer<'de>>(reader: D) -> Result<Option<u32>, D::Error> {
u32::deserialize(reader).map(Some)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -93,6 +70,7 @@ struct BundleEntry {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolRecord {
record_version: u32,
command: String,
@@ -103,8 +81,7 @@ struct ToolRecord {
bundle_sha256: String,
source: String,
schema_version: u32,
#[serde(default)]
compatibility: RecordedCompatibility,
requires: Requirements,
}
/// `marqdo tool install <manifest-or-directory>`.
@@ -204,11 +181,7 @@ fn install_inner(manifest_path: &Path) -> Result<ToolRecord, String> {
bundle_sha256: bundle_sha256.clone(),
source: manifest_file.display().to_string(),
schema_version: manifest.schema_version,
compatibility: RecordedCompatibility {
marqdo: manifest.compatibility.marqdo.clone(),
analysis: manifest.compatibility.analysis.clone(),
trace: manifest.compatibility.trace.clone(),
},
requires: manifest.requires.clone(),
};
let record_json = serde_json::to_string_pretty(&record)
.map_err(|error| format!("cannot serialize record: {error}"))?;
@@ -229,7 +202,7 @@ impl ToolManifest {
let text = std::fs::read_to_string(path)
.map_err(|error| format!("cannot read `{}`: {error}", path.display()))?;
let manifest: Self =
serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}"))?;
serde_json::from_str(&text).map_err(|error| format!("invalid tool.json: {error}. Build the tool with current exact protocol requirements"))?;
Ok(manifest)
}
}
@@ -238,10 +211,10 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
if manifest.schema != SCHEMA {
return Err(format!("unsupported tool schema `{}`", manifest.schema));
}
if manifest.schema_version != SUPPORTED.tool {
if manifest.schema_version != PROTOCOL_VERSION {
return Err(format!(
"unsupported tool schema_version {} (expected {})",
manifest.schema_version, SUPPORTED.tool
manifest.schema_version, PROTOCOL_VERSION
));
}
if !is_valid_command(&manifest.command) {
@@ -265,57 +238,34 @@ fn validate_manifest(manifest: &ToolManifest) -> Result<(), String> {
manifest.version
)
})?;
negotiate(&manifest.version, &manifest.compatibility)
validate_requirements(&manifest.requires)
}
fn negotiate(tool_version: &str, compatibility: &Compatibility) -> Result<(), String> {
Version::parse(tool_version)
.map_err(|error| format!("tool version `{tool_version}` is not valid SemVer: {error}"))?;
let core_version = Version::parse(env!("CARGO_PKG_VERSION"))
.map_err(|error| format!("core version is not valid SemVer: {error}"))?;
if let Some(range) = &compatibility.marqdo {
let requirement = VersionReq::parse(range)
.map_err(|error| format!("invalid marqdo compatibility range `{range}`: {error}"))?;
if !requirement.matches(&core_version) {
return Err(format!(
"tool requires marqdo `{range}`, this core is {}",
env!("CARGO_PKG_VERSION")
));
fn validate_requirements(requires: &Requirements) -> Result<(), String> {
for (name, requested, current) in [
("api_revision", Some(requires.api_revision), API_REVISION),
(
"analysis",
requires.analysis,
crate::analysis::SCHEMA_VERSION,
),
(
"observation",
requires.observation,
crate::observation::SCHEMA_VERSION,
),
] {
if let Some(requested) = requested {
if requested != current {
return Err(format!(
"tool.protocol_incompatible: tool requires {name} {requested}, this core provides {current}"
));
}
}
}
negotiate_protocol(
"analysis",
compatibility.analysis.as_deref(),
SUPPORTED.analysis,
)?;
negotiate_protocol("trace", compatibility.trace.as_deref(), SUPPORTED.trace)?;
Ok(())
}
fn negotiate_protocol(
name: &str,
requested: Option<&[u32]>,
supported: &[u32],
) -> Result<(), String> {
let Some(requested) = requested else {
return Ok(());
};
if shared_version(requested, supported).is_none() {
return Err(format!(
"tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}"
));
}
Ok(())
}
fn shared_version(requested: &[u32], supported: &[u32]) -> Option<u32> {
requested
.iter()
.copied()
.filter(|version| supported.contains(version))
.max()
}
fn is_valid_command(command: &str) -> bool {
let mut bytes = command.bytes();
matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase())
@@ -486,7 +436,7 @@ pub fn list(json: bool) -> i32 {
"name": record.name,
"version": record.version,
"bundle_files": record.bundle.len(),
"compatibility": record.compatibility,
"requires": record.requires,
})
})
.collect();
@@ -571,8 +521,8 @@ pub fn dispatch(args: &[OsString]) -> i32 {
return 2;
};
let command = first.to_string_lossy();
if BUILTIN_COMMANDS.contains(&command.as_ref()) {
eprintln!("error: internal dispatch error for built-in command `{command}`");
if !is_valid_command(&command) || BUILTIN_COMMANDS.contains(&command.as_ref()) {
eprintln!("error: invalid external command `{command}`");
return 2;
}
let home = match tool_home() {
@@ -585,6 +535,10 @@ pub fn dispatch(args: &[OsString]) -> i32 {
let dir = home.join(command.as_ref());
let record = match load_record(&dir) {
Ok(record) => record,
Err(error) if dir.exists() => {
eprintln!("error: tool `{command}`: {error}");
return 1;
}
Err(_) => {
eprintln!(
"error: unknown command `{command}`; install a tool with `marqdo tool install <tool.json>`"
@@ -596,14 +550,6 @@ pub fn dispatch(args: &[OsString]) -> i32 {
eprintln!("error: tool record does not match command `{command}`; reinstall it");
return 1;
}
if let Err(error) = negotiate(&record.version, &record.compatibility.as_compatibility()) {
eprintln!("error: tool `{command}` is not compatible with this core: {error}");
return 1;
}
if record.record_version != RECORD_VERSION {
eprintln!("error: tool `{command}` uses an old record; reinstall it");
return 1;
}
let bundle = match collect_bundle(&dir, true) {
Ok(bundle) => bundle,
Err(error) => {
@@ -630,26 +576,16 @@ pub fn dispatch(args: &[OsString]) -> i32 {
};
let mut process = ProcessCommand::new(&entrypoint);
process.args(&args[1..]);
if let Ok(bin) = std::env::current_exe() {
process.env("MARQDO_BIN", bin);
}
process.env("MARQDO_TOOL_PROTOCOL", "1");
if let Some(version) = record
.compatibility
.analysis
.as_deref()
.and_then(|versions| shared_version(versions, SUPPORTED.analysis))
{
process.env("MARQDO_PROTOCOL_ANALYSIS", version.to_string());
}
if let Some(version) = record
.compatibility
.trace
.as_deref()
.and_then(|versions| shared_version(versions, SUPPORTED.trace))
{
process.env("MARQDO_PROTOCOL_TRACE", version.to_string());
match std::env::current_exe() {
Ok(bin) => {
process.env("MARQDO_BIN", bin);
}
Err(error) => {
eprintln!("error: cannot locate marqdo for tool `{command}`: {error}");
return 1;
}
}
process.env("MARQDO_API_REVISION", API_REVISION.to_string());
match process.status() {
Ok(status) => status.code().unwrap_or(1),
Err(error) => {
@@ -693,7 +629,10 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
if entry.file_name().to_string_lossy().starts_with('.') {
continue;
}
if let Ok(record) = load_record(&entry.path()) {
if entry.path().join("record.json").is_file() {
let record = load_record(&entry.path()).map_err(|error| {
format!("tool `{}`: {error}", entry.file_name().to_string_lossy())
})?;
records.insert(record.command.clone(), record);
}
}
@@ -701,13 +640,26 @@ fn installed_records() -> Result<Vec<ToolRecord>, String> {
}
fn load_record(dir: &Path) -> Result<ToolRecord, String> {
let text = std::fs::read_to_string(dir.join("record.json"))
.map_err(|error| format!("tool record is missing: {error}"))?;
let record: ToolRecord =
serde_json::from_str(&text).map_err(|error| format!("invalid tool record: {error}"))?;
if record.record_version != RECORD_VERSION {
return Err("tool record is from an older protocol; reinstall it".to_string());
let record_path = dir.join("record.json");
let inspect = |path| {
std::fs::symlink_metadata(path)
.map_err(|error| format!("cannot inspect tool registration: {error}"))
};
if !inspect(dir)?.is_dir() || !inspect(record_path.as_path())?.is_file() {
return Err("invalid tool registration path. Remove and reinstall the tool".to_string());
}
let text = std::fs::read_to_string(record_path)
.map_err(|error| format!("tool record is missing: {error}"))?;
let record: ToolRecord = serde_json::from_str(&text).map_err(|error| {
format!("invalid or retired tool record: {error}. Remove and reinstall the tool")
})?;
if record.record_version != RECORD_VERSION || record.schema_version != PROTOCOL_VERSION {
return Err(
"tool record uses an unsupported format. Remove and reinstall the tool".to_string(),
);
}
validate_requirements(&record.requires)
.map_err(|error| format!("{error}. Remove and reinstall the tool"))?;
Ok(record)
}
-144
View File
@@ -1,144 +0,0 @@
//! Public Trace v2 writer (spec/trace-v2.md).
//!
//! Events come from the interpreter (semantic) and the capability host
//! (effects). No argument values, secrets or handles are recorded.
use std::path::Path;
use marqdo_host::{Host, SemanticEvent, StdHost, TraceEntry};
use serde_json::{json, Value};
use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.trace";
pub const SCHEMA_VERSION: u32 = 2;
/// Write a trace atomically for one run.
pub fn write(
project: &LoadedProject,
host: &StdHost,
entry: &str,
status: &str,
path: &Path,
run_id: Option<&str>,
) -> Result<(), String> {
// A combined `--event-stream` run shares the CLI-generated opaque run id
// with Execution Events v1; Trace v2 keeps its schema and field types.
let run_id = run_id.map(str::to_string).unwrap_or_else(|| {
format!(
"{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
)
});
let analysis_digest = crate::analysis::digest(project);
let root_id = project.identity.root_id();
let state = host.trace_state();
let mut events: Vec<Value> = host
.semantic_events()
.iter()
.map(semantic_json)
.chain(host.trace().iter().map(effect_json))
.collect();
events.sort_by_key(|event| event.get("seq").and_then(Value::as_u64).unwrap_or(u64::MAX));
let mut truncation = state.truncation.clone();
let max_bytes = state.budget.max_bytes;
let bytes = loop {
let mut all = events.clone();
if let Some(truncation) = &truncation {
let seq = all
.last()
.and_then(|event| event.get("seq"))
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1;
all.push(json!({
"seq": seq,
"kind": "trace.truncated",
"module_id": null,
"span": null,
"detail": truncation.reason,
}));
}
let trace = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": run_id, "entry": entry, "status": status},
"source": {
"root_id": root_id,
"analysis_digest": format!("sha256:{analysis_digest}"),
},
"limits": {
"max_events": state.budget.max_events,
"max_bytes": state.budget.max_bytes,
},
"truncated": truncation,
"events": all,
});
let bytes = serde_json::to_vec_pretty(&trace)
.map_err(|error| format!("cannot encode trace: {error}"))?;
if max_bytes == 0 || bytes.len() <= max_bytes || events.is_empty() {
break bytes;
}
events.pop();
if truncation.is_none() {
truncation = Some(marqdo_host::TraceTruncation {
reason: "byte_budget".to_string(),
limit: max_bytes as u64,
written: events.len() as u64,
});
}
};
atomic_write(path, &bytes)
}
fn semantic_json(event: &SemanticEvent) -> Value {
json!({
"seq": event.seq,
"kind": event.kind,
"function_id": event.function_id,
"module_id": event.module_id,
"span": event.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": event.detail,
})
}
fn effect_json(entry: &TraceEntry) -> Value {
json!({
"seq": entry.seq,
"kind": "effect",
"module_id": entry.module,
"span": entry.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": entry.result,
"operation": entry.op,
"duration_micros": entry.duration_micros,
})
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?;
let temporary = parent.join(format!(
".{}.tmp-{}",
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "trace.json".to_string()),
std::process::id()
));
std::fs::write(&temporary, bytes)
.map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("cannot publish `{}`: {error}", path.display()));
}
Ok(())
}
+589
View File
@@ -0,0 +1,589 @@
//! 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.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
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 cli(dir: &Path, args: &[&str]) -> Output {
stdlib_support::cli_command()
.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());
}
@@ -1,5 +1,10 @@
//! Public Analysis/Trace v1 black-box contract (spec/analysis-v1.md,
//! spec/trace-v1.md).
//! Public Analysis and Observation black-box contracts (spec/analysis.md,
//! spec/observation.md).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -31,12 +36,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -96,7 +97,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
let analysis: serde_json::Value = serde_json::from_slice(&first_bytes).unwrap();
assert_eq!(analysis["schema"], "marqdo.analysis");
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0];
assert_eq!(module["id"], "root:default::index.mq.md");
assert_eq!(module["package_instance_id"], "root:default");
@@ -140,7 +141,7 @@ fn analysis_is_deterministic_and_has_stable_semantic_nodes() {
}
#[test]
fn analysis_v2_identity_is_location_independent() {
fn analysis_identity_is_location_independent() {
let first = TempDir::new("analysis-identity-a");
let second = TempDir::new("analysis-identity-b");
let source = "## @exec main\n\n`x = 1`\n\n`return x`\n";
@@ -182,7 +183,7 @@ fn analysis_v2_identity_is_location_independent() {
}
#[test]
fn analysis_v2_projects_memory_place_targets_additively() {
fn analysis_projects_memory_place_targets_additively() {
let dir = TempDir::new("analysis-place");
let source =
"## @exec main\n\n`内存 = memory.new(1, 2)`\n\n`内存[0] = 7`\n\n`return 内存[0]`\n";
@@ -211,7 +212,7 @@ fn analysis_v2_projects_memory_place_targets_additively() {
}
#[test]
fn analysis_v2_projects_addressable_formula_and_code_resources() {
fn analysis_projects_addressable_formula_and_code_resources() {
let dir = TempDir::new("analysis-resources");
let source = r#"## @exec calc
@@ -264,14 +265,21 @@ print(1)
assert_eq!(code["language"], "python");
assert_eq!(formula["content_digest"].as_str().unwrap().len(), 64);
assert_eq!(code["content_digest"].as_str().unwrap().len(), 64);
assert!(
!analysis.to_string().contains("A = x + 1"),
"resource payloads stay in source, not Analysis"
let source = analysis["modules"][0]["source"]
.as_str()
.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)
);
}
#[test]
fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
fn snapshot_budget_truncates_long_loops_without_failing_the_run() {
let dir = TempDir::new("trace-budget");
write(
dir.path(),
@@ -284,9 +292,9 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
&[
"run",
"index.mq.md",
"--trace-file",
"--observation-file",
trace_path.to_str().unwrap(),
"--trace-max-events",
"--observe-max-events",
"20",
],
);
@@ -298,14 +306,18 @@ fn trace_v2_budget_truncates_long_loops_without_failing_the_run() {
);
let trace: serde_json::Value =
serde_json::from_slice(&std::fs::read(&trace_path).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2);
assert_eq!(trace["schema_version"], 1);
assert_eq!(trace["run"]["status"], "ok");
assert_eq!(trace["limits"]["max_events"], 20);
assert_eq!(trace["truncated"]["reason"], "event_budget");
assert_eq!(trace["truncated"]["limit"], 20);
assert_eq!(
trace["events"][0]["payload"]["limits"]["max_observation_events"],
20
);
assert_eq!(trace["capture"]["truncated"]["reason"], "event_budget");
assert_eq!(trace["capture"]["truncated"]["limit"], 20);
let events = trace["events"].as_array().unwrap();
assert!(events.len() <= 21, "events: {}", events.len());
assert_eq!(events.last().unwrap()["kind"], "trace.truncated");
assert_eq!(events.len(), 24);
assert_eq!(events[22]["kind"], "observation.truncated");
assert_eq!(events[23]["kind"], "run.completed");
let mut previous = None;
for event in events {
let seq = event["seq"].as_u64().unwrap();
@@ -331,7 +343,32 @@ fn failed_check_removes_stale_analysis() {
}
#[test]
fn trace_records_calls_effects_and_status_without_secrets() {
fn check_that_cannot_load_the_project_removes_stale_analysis() {
let dir = TempDir::new("analysis-load-error");
write(dir.path(), "index.mq.md", "## @exec main\n\n`return 1`\n");
let target = dir.path().join("analysis.json");
let first = cli(
dir.path(),
&["check", "index.mq.md", "--emit", target.to_str().unwrap()],
);
assert_eq!(first.status.code(), Some(0), "{first:?}");
assert!(target.exists());
// The load failure happens before the compile-error cleanup branch, so the
// remove must also cover the prepare path.
let failed = cli(
dir.path(),
&["check", "missing.mq.md", "--emit", target.to_str().unwrap()],
);
assert_ne!(failed.status.code(), Some(0), "{failed:?}");
assert!(
!target.exists(),
"a load failure must not leave the previous Analysis in place"
);
}
#[test]
fn snapshot_records_calls_effects_and_status_without_secrets() {
let dir = TempDir::new("trace");
write(dir.path(), "index.mq.md", PROGRAM);
let trace_path = dir.path().join("trace.json");
@@ -340,7 +377,7 @@ fn trace_records_calls_effects_and_status_without_secrets() {
&[
"run",
"index.mq.md",
"--trace-file",
"--observation-file",
trace_path.to_str().unwrap(),
],
);
@@ -356,15 +393,16 @@ fn trace_records_calls_effects_and_status_without_secrets() {
"values must not be recorded"
);
let trace: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(trace["schema"], "marqdo.trace");
assert_eq!(trace["schema_version"], 2);
assert_eq!(trace["schema"], "marqdo.observation");
assert_eq!(trace["schema_version"], 1);
assert_eq!(trace["run"]["status"], "ok");
assert_eq!(trace["run"]["entry"], "root:default::index.mq.md::main");
assert_eq!(
trace["events"][1]["payload"]["entry"],
"root:default::index.mq.md::main"
);
let events = trace["events"].as_array().unwrap();
assert!(events
.iter()
.any(|event| event["kind"] == "call.enter"
&& event["module_id"] == "root:default::index.mq.md"));
assert!(events.iter().any(|event| event["kind"] == "call.enter"
&& event["payload"]["module_id"] == "root:default::index.mq.md"));
assert!(events.iter().any(|event| event["kind"] == "effect"));
assert!(events.iter().any(|event| event["kind"] == "call.exit"));
let mut previous = None;
@@ -384,18 +422,22 @@ fn trace_records_calls_effects_and_status_without_secrets() {
&[
"run",
"bad.mq.md",
"--trace-file",
"--observation-file",
error_trace.to_str().unwrap(),
],
);
assert_eq!(output.status.code(), Some(1));
let trace: serde_json::Value =
serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap();
assert_eq!(trace["run"]["status"], "runtime.division_by_zero");
assert_eq!(trace["run"]["status"], "error");
assert_eq!(
trace["events"].as_array().unwrap().last().unwrap()["payload"]["error"]["code"],
"runtime.division_by_zero"
);
}
#[test]
fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
fn multi_arm_branch_preserves_analysis_and_carrier_positions() {
let dir = TempDir::new("else-if");
let source = r#"## @exec 分类
@@ -427,7 +469,7 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
assert!(output.status.success(), "{output:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["schema_version"], 3);
assert_eq!(analysis["producer"]["markdown_profile"], "marqdo.md.v1");
let branch = &analysis["modules"][0]["functions"][0]["body"][0];
assert_eq!(branch["kind"], "branch");
@@ -453,17 +495,18 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
"分类",
"--arg",
&format!("数值={input}"),
"--json",
"--output",
"json",
],
);
assert!(output.status.success(), "{output:?}");
let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(result["value"]["decimal"], expected);
assert_eq!(observation::terminal(&result)["value"]["decimal"], expected);
}
}
#[test]
fn an_imported_loop_transfer_selects_v3_and_keeps_the_else_if_call_edge() {
fn an_imported_loop_transfer_uses_current_schema_and_keeps_the_else_if_call_edge() {
let dir = TempDir::new("imported-loop");
write(
dir.path(),
+288 -57
View File
@@ -1,10 +1,15 @@
//! Architecture boundary gate (review RFC-CM P0/P1).
//!
//! These checks pin the documented layering: the runtime depends on the host
//! platform layer, the bundled stdlib stays in this repository, `std:` import
//! targets resolve only inside the bundle, and the host keeps the documented
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an
//! OS-sandbox proof.
//! These checks pin the documented layering: the engine depends on the neutral
//! Host contract (never the native host), the plugin ABI contract carries no
//! loader/worker execution side, the stdlib Bundle is an explicit ecosystem
//! input rather than an in-repo source tree, `std:` import targets resolve only
//! inside the bundle, and the host keeps the
//! documented stdio/file/TCP resource endpoints. They are source and digest
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
//! adds the Cargo-metadata graph gate.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
@@ -23,86 +28,154 @@ fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
}
const WORKSPACE_CRATES: &[&str] = &[
"marqdo-span",
"marqdo-value",
"marqdo-expression",
"marqdo-markdown",
"marqdo-ir",
"marqdo-frontend",
"marqdo-foreign",
"marqdo-plugin-abi",
"marqdo-provider-worker",
"marqdo-plugin-sdk",
"marqdo-host",
"marqdo-runtime",
"marqdo-package",
"marqdo-sandbox",
"cli",
];
/// Issue #13 / ADR-0071: the reviewed responsibility allowlist is the crate
/// table in the single current architecture overview, not a frozen count. A new
/// crate must be added there (and to the dependency gate's reviewed map) in the
/// same change.
#[test]
fn workspace_crates_match_the_documented_layers() {
let manifest = read(&repo_root().join("Cargo.toml"));
fn workspace_crates_are_documented_responsibilities() {
let root = repo_root();
let manifest = read(&root.join("Cargo.toml"));
let members = manifest
.split("members = [")
.nth(1)
.and_then(|rest| rest.split(']').next())
.expect("workspace members");
let names: Vec<&str> = members
let names: Vec<String> = members
.split(',')
.map(|item| item.trim().trim_matches('"'))
.filter(|item| !item.is_empty())
.map(|member| {
let directory = member
.strip_prefix("crates/")
.expect("workspace members are crates/<name>");
let manifest = read(&root.join(member).join("Cargo.toml"));
manifest
.lines()
.find_map(|line| line.strip_prefix("name = "))
.map(|name| name.trim().trim_matches('"').to_string())
.unwrap_or_else(|| directory.to_string())
})
.collect();
let expected: Vec<String> = WORKSPACE_CRATES
.iter()
.map(|name| format!("crates/{name}"))
.collect();
assert_eq!(
names,
expected.iter().map(String::as_str).collect::<Vec<_>>(),
"workspace members drifted; update docs/architecture/CURRENT.md with the layer"
);
let current = read(&root.join("docs/architecture/CURRENT.md"));
let responsibilities = current
.split("## Workspace crate responsibility map")
.nth(1)
.expect("CURRENT.md must own the reviewed crate responsibility map")
.split("\n## ")
.next()
.unwrap_or("");
for name in &names {
assert!(
responsibilities.contains(&format!("`{name}`")),
"workspace crate `{name}` has no documented responsibility in CURRENT.md"
);
}
for name in [
"marqdo-host-contract",
"marqdo-host",
"marqdo-plugin-abi",
"marqdo-cli",
] {
assert!(
names.iter().any(|crate_name| crate_name == name),
"required layer crate `{name}` is missing from the workspace"
);
}
assert!(
!names.contains(&"crates/marqdo-stdlib"),
"the stdlib must stay in this repository (ADR-0039), not become a crate"
!names.iter().any(|name| name == "marqdo-stdlib"),
"the stdlib is a Bundle input, not a workspace crate (ADR-0039/ADR-0070)"
);
}
#[test]
fn runtime_depends_on_the_host_platform_layer_without_a_cycle() {
let runtime = read(&repo_root().join("crates/marqdo-runtime/Cargo.toml"));
fn engine_depends_on_the_neutral_host_contract_only() {
let root = repo_root();
let runtime = read(&root.join("crates/marqdo-runtime/Cargo.toml"));
let runtime_dependencies = runtime
.split("[dependencies]")
.nth(1)
.expect("runtime dependencies")
.split("[dev-dependencies]")
.next()
.expect("runtime normal dependencies");
assert!(
runtime
runtime_dependencies
.lines()
.any(|line| line.trim() == "marqdo-host-contract = { workspace = true }"),
"runtime must depend on the neutral marqdo-host-contract crate"
);
assert!(
!runtime_dependencies
.lines()
.any(|line| line.trim() == "marqdo-host = { workspace = true }"),
"runtime must keep the documented marqdo-runtime -> marqdo-host direction"
"runtime normal/build dependencies must not link the native host"
);
let host = read(&repo_root().join("crates/marqdo-host/Cargo.toml"));
let contract = read(&root.join("crates/marqdo-host-contract/Cargo.toml"));
let contract_deps: Vec<&str> = contract
.split("[dependencies]")
.nth(1)
.expect("contract dependencies")
.lines()
.filter_map(|line| line.split('=').next())
.map(str::trim)
.filter(|name| !name.is_empty() && !name.starts_with('['))
.collect();
assert_eq!(
contract_deps,
["marqdo-span", "marqdo-value"],
"the host contract must stay platform neutral (value/span only)"
);
let host = read(&root.join("crates/marqdo-host/Cargo.toml"));
for forbidden in ["marqdo-runtime", "marqdo-frontend", "marqdo-ir ="] {
assert!(
!host.contains(forbidden),
"the native host must not depend back on `{forbidden}`"
);
}
assert!(
!host.contains("marqdo-runtime"),
"marqdo-host must not depend back on marqdo-runtime"
host.contains("marqdo-host-contract = { workspace = true }"),
"the native host must implement the neutral contract crate"
);
}
#[test]
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
let root = repo_root().join("stdlib");
fn stdlib_sources_live_in_the_ecosystem_not_in_this_repository() {
// Phase B (ADR-0070): the in-repo source tree is gone. The accepted Bundle
// identity is the ecosystem pin; product tests consume an explicit, verified
// Bundle (CI materializes it with tools/ci/fetch_ecosystem_bundle.py).
assert!(
!repo_root().join("stdlib").exists(),
"Phase B must not carry an in-repo stdlib source tree"
);
let pin = stdlib_support::BundlePin::committed();
assert!(
pin.source_path.is_none(),
"the accepted Bundle pin must name the ecosystem source, not a vendored path"
);
assert_eq!(pin.name, "marqdo-stdlib");
assert_eq!(pin.version, "0.2.0");
assert_eq!(pin.source_commit.len(), 40);
let root = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], "marqdo-stdlib");
assert_eq!(manifest["version"], "0.1.0");
assert_eq!(manifest["name"], pin.name);
assert_eq!(manifest["version"], pin.version);
let declared = manifest["digest"].as_str().expect("digest string");
assert_eq!(
declared, pin.tree_digest,
"the resolved Bundle must match the pin"
);
let actual = format!("sha256:{}", tree_digest(&root).unwrap());
assert_eq!(
actual, declared,
"stdlib digest mismatch; regenerate it with tools/pack-stdlib.py and commit the digest"
"stdlib digest mismatch; rebuild the Bundle from the pinned ecosystem gitlinks"
);
}
#[test]
fn stdlib_imports_resolve_inside_the_bundle() {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
for entry in walk_markdown(&root) {
let is_test = entry.starts_with(root.join("tests"));
let text = read(&entry);
@@ -140,6 +213,41 @@ fn stdlib_imports_resolve_inside_the_bundle() {
}
}
#[test]
fn shared_worker_transport_is_neutral_and_not_duplicated() {
let root = repo_root();
let transport = read(&root.join("crates/marqdo-worker-ipc/Cargo.toml"));
for forbidden in ["marqdo-host", "marqdo-plugin-abi", "marqdo-provider-worker"] {
assert!(
!transport.contains(forbidden),
"marqdo-worker-ipc must stay transport-only; it must not depend on `{forbidden}`"
);
}
for user in [
"crates/marqdo-host/Cargo.toml",
"crates/marqdo-provider-worker/Cargo.toml",
] {
assert!(
read(&root.join(user)).contains("marqdo-worker-ipc = {"),
"{user} must use the one shared worker transport"
);
}
// The four-byte length prefix and its bounds live in exactly one crate.
for private in [
"crates/marqdo-host/src/plugin_worker.rs",
"crates/marqdo-host/src/plugin/worker.rs",
"crates/marqdo-host/src/provider_worker.rs",
"crates/marqdo-provider-worker/src/main.rs",
] {
let text = read(&root.join(private));
let implementation = text.split("#[cfg(test)]").next().unwrap_or(&text);
assert!(
!implementation.contains("from_be_bytes") && !implementation.contains("to_be_bytes"),
"{private} reimplements worker framing instead of using marqdo-worker-ipc"
);
}
}
#[test]
fn host_keeps_the_documented_resource_endpoints() {
let resource = read(&repo_root().join("crates/marqdo-host/src/resource.rs"));
@@ -372,12 +480,12 @@ fn builtin_names_and_aliases_are_reviewed() {
}
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
const _: fn(marqdo_host::HostOp) = |operation| match operation {
marqdo_host::HostOp::ForeignRun
| marqdo_host::HostOp::ForeignCall
| marqdo_host::HostOp::FsRead
| marqdo_host::HostOp::FsWrite
| marqdo_host::HostOp::PluginInvoke => (),
const _: fn(marqdo_host_contract::HostOp) = |operation| match operation {
marqdo_host_contract::HostOp::ForeignRun
| marqdo_host_contract::HostOp::ForeignCall
| marqdo_host_contract::HostOp::FsRead
| marqdo_host_contract::HostOp::FsWrite
| marqdo_host_contract::HostOp::PluginInvoke => (),
};
const _: fn(marqdo_value::Value) = |value| match value {
@@ -402,7 +510,7 @@ const _: fn(marqdo_value::Value) = |value| match value {
/// hard-coded runtime names. Recompute the canonical metadata digest.
#[test]
fn official_stdlib_public_aliases_are_verified_metadata() {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
let aliases = manifest["public_aliases"]
@@ -528,6 +636,129 @@ fn domain_math_kernel_is_not_part_of_the_core() {
}
}
/// E02/E03: there is exactly one Host trait/HostOp definition and it belongs to
/// the neutral contract; the native host only implements it.
#[test]
fn host_contract_is_the_single_side_effect_interface() {
let root = repo_root();
let mut host_traits = Vec::new();
let mut host_ops = Vec::new();
for source in walk_rs(&root.join("crates")) {
let relative = source
.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string();
if relative.contains("/tests/") {
continue;
}
let text = read(&source);
if text.contains("pub trait Host {") {
host_traits.push(relative.clone());
}
if text.contains("pub enum HostOp {") {
host_ops.push(relative);
}
}
assert_eq!(
host_traits,
["crates/marqdo-host-contract/src/host.rs"],
"the Host trait must be defined once in the neutral contract"
);
assert_eq!(
host_ops,
["crates/marqdo-host-contract/src/host.rs"],
"HostOp must be defined once in the neutral contract"
);
let runtime = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
assert!(
runtime.contains("use marqdo_host_contract::{"),
"the interpreter must consume the neutral contract"
);
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
assert!(
host.contains("impl Host for StdHost"),
"StdHost remains the single native host implementation"
);
}
/// A05/S01: the public ABI crate is a contract, not a loader; execution side
/// lives in the native host and the SDK consumes only the contract.
#[test]
fn plugin_contract_carries_no_native_execution() {
let root = repo_root();
let abi = read(&root.join("crates/marqdo-plugin-abi/Cargo.toml"));
for forbidden in ["libloading", "marqdo-worker-ipc", "serde_yaml", "sha2"] {
assert!(
!abi.contains(forbidden),
"marqdo-plugin-abi must not depend on execution-side `{forbidden}`"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
!root
.join(format!("crates/marqdo-plugin-abi/src/{module}.rs"))
.exists(),
"`{module}` is execution-side and belongs to the native host"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
root.join(format!("crates/marqdo-host/src/plugin/{module}.rs"))
.exists(),
"native host must own plugin `{module}`"
);
}
let sdk = read(&root.join("crates/marqdo-plugin-sdk/Cargo.toml"));
for forbidden in [
"marqdo-host",
"marqdo-cli",
"libloading",
"marqdo-worker-ipc",
] {
assert!(
!sdk.contains(forbidden),
"the plugin SDK must not depend on `{forbidden}`"
);
}
}
/// E01/E04: the independent embedding consumer is a real package outside the
/// workspace and depends only on engine crates.
#[test]
fn embedding_consumer_is_engine_only() {
let root = repo_root();
let consumer = read(&root.join("tests/embedding/Cargo.toml"));
assert!(
consumer.contains("[workspace]"),
"the embedding consumer must be its own workspace to avoid feature unification"
);
assert!(
consumer.contains("marqdo-runtime"),
"the embedding consumer must execute through the real runtime"
);
for forbidden in [
"marqdo-host",
"marqdo-cli",
"marqdo-sandbox",
"marqdo-foreign",
] {
let dependency_line = format!("\n{forbidden} =");
assert!(
!consumer.contains(&dependency_line),
"the embedding consumer must not depend on `{forbidden}`"
);
}
assert!(
root.join("tests/embedding/Cargo.lock").is_file(),
"the independent consumer must pin its own lock file"
);
assert!(
root.join("tools/ci/check_engine_boundary.py").is_file(),
"the build-and-run engine gate must exist"
);
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
+16 -9
View File
@@ -4,12 +4,17 @@
//! point is to prove that `check` and `run` share one static resolution and
//! that the runtime never guesses a plugin from a dotted string prefix.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -47,7 +52,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -187,11 +192,11 @@ fn renamed_import_alias_binds_the_module_function() {
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
let run = cli(&["run", "index.mq.md", "--output", "json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "101"})
);
}
@@ -482,11 +487,14 @@ fn local_function_reference_is_a_dynamic_language_call() {
&dir.path().join("index.mq.md"),
"## @exec 平方\n\n`params(n: Int)`\n\n`return n * n`\n\n## @exec 主\n\n`f = ref(\"#平方\")`\n\n`return f(n=4)`\n",
);
let run = cli(&["call", "index.mq.md", "主", "--json"], dir.path());
let run = cli(
&["call", "index.mq.md", "主", "--output", "json"],
dir.path(),
);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "16"})
);
}
@@ -526,11 +534,11 @@ fn explicit_import_aliases_bind_same_named_functions_independently() {
&dir.path().join("index.mq.md"),
"---\nimport:\n aa: \"./a.mq.md\"\n bb: \"./b.mq.md\"\n---\n\n## @exec main\n\n`return aa.value() + bb.value()`\n",
);
let run = cli(&["run", "index.mq.md", "--json"], dir.path());
let run = cli(&["run", "index.mq.md", "--output", "json"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
let json: serde_json::Value = serde_json::from_str(&stdout(&run)).unwrap();
assert_eq!(
json["value"],
observation::terminal(&json)["value"],
serde_json::json!({"type": "int", "decimal": "30"})
);
}
@@ -632,7 +640,6 @@ fn check_emit_and_run_share_the_same_static_binding_source() {
plugin_dir.path().to_str().unwrap(),
"--allow-plugin",
"demo.solver",
"--json",
],
dir.path(),
);
+7 -3
View File
@@ -18,11 +18,15 @@
//! Developer note: `UPDATE_SEMANTICS_GOLDENS=1` rewrites `value`/`stdout` from
//! the implementation. Never use it without hand-checking every rewritten
//! expectation; the checked-in goldens were reviewed individually.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::fs;
use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
@@ -291,7 +295,7 @@ fn normalise_relative(path: &Path) -> String {
/// unique registry, run the single binding pass and install its table. There is
/// no `print_override` and no runtime name guessing.
fn bind_calls_with_stdlib_aliases(program: &mut Program) {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let mut loaded = std::collections::BTreeSet::new();
let mut official = Vec::new();
if root.join("stdlib.json").is_file() {
@@ -428,7 +432,7 @@ fn install_entry_stdlib_imports(
module_id: &ModuleId,
analysis: &marqdo_frontend::AnalysisResult,
) {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let Some(imports) = analysis
.document
.frontmatter()
+98
View File
@@ -202,3 +202,101 @@ fn has_hex_sha(text: &str) -> bool {
}
false
}
/// CI is a consumer of the public protocols: its configuration must exercise
/// only the current contracts. A retired name in a pipeline is a latent
/// failure and implies a compatibility path was kept somewhere.
#[test]
fn ci_configuration_uses_only_current_protocols() {
let root = repo_root();
for relative in [
".woodpecker/main.yml",
".github/workflows/ci.yml",
"docs/ci.md",
] {
let text = read(&root.join(relative));
for retired in [
"--event-stream",
"--trace-file",
"execution-events",
"execution_events",
"analysis_v3_consumer",
"trace_consumer",
"analysis-v3",
] {
assert!(
!text.contains(retired),
"{relative} still references retired `{retired}`"
);
}
}
}
/// The current contract documents must describe the interface that exists.
/// A retired option or a path to a deleted spec in `spec/` or the current
/// developer guides is a release-record defect: consumers would implement a
/// contract the binary does not accept. Historical ADRs, evidence and
/// `docs/history/` keep their original text and are intentionally excluded.
#[test]
fn current_contract_documents_do_not_reference_retired_interfaces() {
let root = repo_root();
let mut files = vec![
"COMPATIBILITY.md".to_string(),
"README.md".to_string(),
"docs/ci.md".to_string(),
"docs/architecture/CURRENT.md".to_string(),
];
for directory in ["spec", "docs/developers", "examples"] {
let base = root.join(directory);
let mut stack = vec![base];
while let Some(path) = stack.pop() {
for entry in std::fs::read_dir(&path).expect("read contract docs") {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
} else if path.extension().and_then(|ext| ext.to_str()) == Some("md") {
files.push(
path.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string(),
);
}
}
}
}
let retired = [
"--trace-file",
"--event-stream",
"EffectTrace",
"crates/marqdo-host/src/trace.rs",
"spec/trace-v1.md",
"spec/trace-v2.md",
"spec/execution-events-v1.md",
"spec/analysis-v1.md",
"spec/analysis-v2.md",
"spec/tool-v1.md",
"worker_frame_invalid for an over-limit",
];
for relative in files {
let text = read(&root.join(&relative));
for (number, line) in text.lines().enumerate() {
for token in retired {
if !line.contains(token) {
continue;
}
// A sentence that explicitly marks the interface as retired or
// removed is documentation of the migration, not a claim that
// it is available.
let explained = line.contains("retired")
|| line.contains("removed")
|| line.contains("no longer");
assert!(
explained,
"{relative}:{} still documents retired `{token}`",
number + 1
);
}
}
}
}
+29 -40
View File
@@ -1,8 +1,13 @@
//! R6 integration examples that do not require an official external repo.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path;
use std::process::{Command, Output};
use std::process::Output;
fn repo() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -13,7 +18,7 @@ fn repo() -> &'static Path {
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(repo())
.output()
@@ -24,40 +29,15 @@ fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
#[test]
fn mqmd_stdlib_print_output_matches_builtin_print() {
let output = cli(&["run", "stdlib/demo.mq.md"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let stdout = String::from_utf8_lossy(&output.stdout);
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 6, "{stdout:?}");
for pair in [(0, 1), (2, 3), (4, 5)] {
assert_eq!(
lines[pair.0], lines[pair.1],
"stdlib formatting differs from 打印 at line {}",
pair.0
);
}
assert_eq!(
lines[0],
r#"["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]"#
);
assert_eq!(lines[2], "Table[名称 | 分数]{甲 | 87; 乙 | 92}");
assert_eq!(
lines[4],
r#"[Formula("a = 1"), Code("text", 9 bytes), FunctionRef(root:default::demo.mq.md::演示函数)]"#
);
}
#[test]
fn addressable_memory_example_runs_through_the_cli() {
let output = cli(&["run", "examples/memory-buffer.mq.md", "--json"]);
let output = cli(&["run", "examples/memory-buffer.mq.md", "--output", "json"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON");
assert_eq!(report["success"], true);
assert_eq!(report["value"]["type"], "int");
assert_eq!(report["value"]["decimal"], "141");
serde_json::from_slice(&output.stdout).expect("run --output json emits a snapshot");
assert_eq!(report["run"]["status"], "ok");
assert_eq!(observation::terminal(&report)["value"]["type"], "int");
assert_eq!(observation::terminal(&report)["value"]["decimal"], "141");
}
#[test]
@@ -67,13 +47,17 @@ fn cli_memory_budget_override_fails_closed() {
"examples/memory-buffer.mq.md",
"--max-memory",
"0",
"--json",
"--output",
"json",
]);
assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("run --json emits JSON");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "resource.exhausted");
serde_json::from_slice(&output.stdout).expect("run --output json emits a snapshot");
assert_eq!(report["run"]["status"], "error");
assert_eq!(
observation::terminal(&report)["error"]["code"],
"resource.exhausted"
);
}
#[test]
@@ -106,14 +90,14 @@ fn unknown_tool_name_installs_and_dispatches() {
.unwrap()
.as_nanos()
));
let install = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let install = stdlib_support::cli_command()
.args(["tool", "install", "examples/tool-unknown-name/tool.json"])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
.output()
.unwrap();
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let run = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let run = stdlib_support::cli_command()
.args(["benchmark", "run", "."])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
@@ -121,7 +105,7 @@ fn unknown_tool_name_installs_and_dispatches() {
.unwrap();
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
assert!(String::from_utf8_lossy(&run.stdout).contains("arg=run"));
let remove = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let remove = stdlib_support::cli_command()
.args(["tool", "remove", "benchmark"])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
@@ -133,7 +117,12 @@ fn unknown_tool_name_installs_and_dispatches() {
#[test]
fn public_schemas_are_valid_json_and_versioned() {
for name in ["analysis-v1", "trace-v1", "tool-v1", "execution-events-v1"] {
for name in [
"analysis",
"observation-event",
"cli-tool",
"observation-file",
] {
let path = repo()
.join("spec/schemas")
.join(format!("{name}.schema.json"));
+60 -2
View File
@@ -4,12 +4,14 @@
//! sources, `marqdo lock` records their exact identity, and `check`/`run`
//! compare the current declaration with the lock before using any extension.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -47,7 +49,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -493,3 +495,59 @@ fn declared_kernel_extension_is_activated_from_the_manifest() {
let run = cli(&["run", "index.mq.md", "--allow-foreign"], project.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
#[test]
fn retired_extension_descriptor_revisions_are_rejected_without_migration() {
// A kernel descriptor is only current at wire_version 1. There is no v2
// reader and no migration: the descriptor is rejected before locking.
let project = TempDir::new("retired-kernel");
std::fs::create_dir_all(project.path().join("kernel")).unwrap();
std::fs::write(
project.path().join("kernel/kernel.json"),
r#"{
"provider_id": "retired-provider",
"languages": ["retired-lang"],
"wire_version": 2,
"entrypoint": "./retired-lang",
"permissions_requested": [],
"digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}"#,
)
.unwrap();
write_project(
project.path(),
"extensions:\n kernels:\n - from: ./kernel/kernel.json\n",
);
std::fs::write(project.path().join("index.mq.md"), "## @exec main\n\nx\n").unwrap();
let rejected = lock(project.path());
assert!(!rejected.status.success(), "{}", stderr(&rejected));
assert!(
stderr(&rejected).contains("unsupported wire_version 2"),
"{}",
stderr(&rejected)
);
assert!(
!project.path().join("marqdo.lock").exists(),
"a rejected retired descriptor must not produce a lock"
);
// A plugin manifest whose ABI requirement targets a retired major is
// rejected by the single current manifest validator.
let Some(project) = plugin_project("retired-abi") else {
return;
};
let manifest_path = project.path().join("adapter/plugin.yaml");
let manifest = std::fs::read_to_string(&manifest_path).unwrap();
std::fs::write(
&manifest_path,
manifest.replace("abi: \"^1.0\"", "abi: \"^2.0\""),
)
.unwrap();
let rejected = lock(project.path());
assert!(!rejected.status.success(), "{}", stderr(&rejected));
assert!(
stderr(&rejected).contains("abi_requirement_unsupported"),
"{}",
stderr(&rejected)
);
}
+4 -2
View File
@@ -5,9 +5,11 @@
//! binary and assert that `check --emit`, `run` and `call` agree.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -41,7 +43,7 @@ impl Drop for TempDir {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+112 -70
View File
@@ -8,6 +8,11 @@
//!
//! Temporary directories live under the OS temp directory and are removed on
//! drop; the repository itself is never modified.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::fs;
use std::path::{Path, PathBuf};
@@ -72,7 +77,7 @@ impl Drop for TempDir {
/// Run the CLI in `dir`.
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -81,7 +86,7 @@ fn cli(dir: &Path, args: &[&str]) -> Output {
/// Run the CLI in `dir` with one extra environment variable.
fn cli_env(dir: &Path, args: &[&str], key: &str, value: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env(key, value)
@@ -253,16 +258,16 @@ fn run_json_embeds_program_stdout() {
"print.mq.md",
"## @exec main\n\n`打印(\"你好\")`\n\n`打印(42)`\n\n`return None`\n",
);
let output = cli(dir.path(), &["run", "print.mq.md", "--json"]);
assert_exit(&output, 0, "run --json must succeed");
let output = cli(dir.path(), &["run", "print.mq.md", "--output", "json"]);
assert_exit(&output, 0, "run --output json must succeed");
// Exactly one JSON document on stdout: program output is embedded, never
// interleaved with the machine-readable envelope.
let value = json_stdout(&output);
assert_eq!(value["command"], "run");
assert_eq!(value["success"], true);
assert_eq!(value["stdout"], "你好\n42\n");
assert_eq!(value["value"]["type"], "none");
assert!(value["trace"].as_array().is_some());
assert_eq!(value["schema"], "marqdo.observation");
assert_eq!(value["run"]["status"], "ok");
assert_eq!(observation::text(&value, "stdout.chunk"), "你好\n42\n");
assert_eq!(observation::terminal(&value)["value"]["type"], "none");
assert!(value["events"].as_array().is_some());
assert!(stderr_text(&output).is_empty());
// Text mode writes program output only to stdout, no JSON envelope.
@@ -297,24 +302,33 @@ fn call_executes_examples_with_typed_arguments() {
"数学.阶乘",
"--arg",
"n=5",
"--json",
"--output",
"json",
],
);
assert_exit(&output, 0, "call must execute factorial");
let value = json_stdout(&output);
assert_eq!(value["success"], true);
assert_eq!(value["value"]["type"], "int");
assert_eq!(value["value"]["decimal"], "120");
assert_eq!(value["run"]["status"], "ok");
assert_eq!(observation::terminal(&value)["value"]["type"], "int");
assert_eq!(observation::terminal(&value)["value"]["decimal"], "120");
let math = examples.join("math.mq.md");
let output = cli(
&root,
&["call", math.to_str().unwrap(), "计算圆面积", "--json"],
&[
"call",
math.to_str().unwrap(),
"计算圆面积",
"--output",
"json",
],
);
assert_exit(&output, 0, "call must execute the math example");
let value = json_stdout(&output);
assert_eq!(value["value"]["type"], "float");
let area = value["value"]["value"].as_f64().expect("float value");
assert_eq!(observation::terminal(&value)["value"]["type"], "float");
let area = observation::terminal(&value)["value"]["value"]
.as_f64()
.expect("float value");
assert!(
(area - std::f64::consts::PI * 16.0).abs() < 1e-12,
"area={area}"
@@ -323,11 +337,17 @@ fn call_executes_examples_with_typed_arguments() {
let references = examples.join("references.mq.md");
let output = cli(
&root,
&["call", references.to_str().unwrap(), "计算作用力", "--json"],
&[
"call",
references.to_str().unwrap(),
"计算作用力",
"--output",
"json",
],
);
assert_exit(&output, 0, "call must execute the references example");
let value = json_stdout(&output);
assert_eq!(value["value"]["decimal"], "6");
assert_eq!(observation::terminal(&value)["value"]["decimal"], "6");
let hello = examples.join("hello.mq.md");
let output = cli(&root, &["run", hello.to_str().unwrap()]);
@@ -425,7 +445,8 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
assert!(
stderr.contains("namespace")
|| stderr.contains("Resource temporarily unavailable")
|| stderr.contains("os error 11"),
|| stderr.contains("os error 11")
|| (stderr.contains("bwrap") && stderr.contains("Permission denied")),
"strict failure diagnostic does not identify the launch failure: {stderr}"
);
assert!(
@@ -436,12 +457,19 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
let json = cli(
&root,
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"],
&[
"run",
hello.to_str().unwrap(),
"--mode",
"strict",
"--output",
"json",
],
);
if json.status.success() {
let value = json_stdout(&json);
assert_eq!(value["success"], true);
assert_eq!(value["value"]["type"], "none");
assert_eq!(value["run"]["status"], "ok");
assert_eq!(observation::terminal(&value)["value"]["type"], "none");
} else {
assert_exit(
&json,
@@ -449,8 +477,8 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
"strict launch failure keeps exit code 1 in JSON mode",
);
let value = json_stdout(&json);
assert_eq!(value["success"], false);
assert!(value["error"]
assert_eq!(value["run"]["status"], "rejected");
assert!(observation::terminal(&value)["error"]["message"]
.as_str()
.expect("error string")
.contains("strict"));
@@ -472,19 +500,26 @@ fn strict_mode_enforces_isolation_or_refuses_closed() {
let json = cli(
&root,
&["run", hello.to_str().unwrap(), "--mode", "strict", "--json"],
&[
"run",
hello.to_str().unwrap(),
"--mode",
"strict",
"--output",
"json",
],
);
assert_exit(&json, 1, "strict refusal keeps exit code 1 in JSON mode");
let value = json_stdout(&json);
assert_eq!(value["success"], false);
assert!(value["error"]
assert_eq!(value["run"]["status"], "rejected");
assert!(observation::terminal(&value)["error"]["message"]
.as_str()
.expect("error string")
.contains("strict mode"));
}
/// A forged `MARQDO_STRICT_ACTIVE` marker must never be trusted and every
/// `--json` refusal must still contain exactly one JSON document. This runs on
/// `--output json` refusal must still contain exactly one JSON document. This runs on
/// every platform; Linux rejects the marker during identity verification and
/// non-Linux builds reject it as unsupported.
#[test]
@@ -494,15 +529,18 @@ fn forged_strict_marker_is_rejected_with_one_json_document() {
let hello = hello.to_str().unwrap();
let json = cli_env(
&root,
&["run", hello, "--mode", "strict", "--json"],
&["run", hello, "--mode", "strict", "--output", "json"],
"MARQDO_STRICT_ACTIVE",
"1",
);
assert_exit(&json, 1, "forged strict marker must fail closed");
let value = json_stdout(&json);
assert_eq!(value["command"], "run");
assert_eq!(value["success"], false);
assert_eq!(value["code"], "strict.identity_invalid");
assert_eq!(value["schema"], "marqdo.observation");
assert_eq!(value["run"]["status"], "rejected");
assert_eq!(
observation::terminal(&value)["error"]["code"],
"strict.identity_invalid"
);
let human = cli_env(
&root,
@@ -519,7 +557,7 @@ fn forged_strict_marker_is_rejected_with_one_json_document() {
assert!(stderr_text(&human).contains("strict isolation verification failed"));
}
/// CLI usage errors in `--json` mode keep the same one-document contract as
/// CLI usage errors in `--output json` mode keep the same one-document contract as
/// successful and runtime-failure paths.
#[test]
fn json_mode_reports_cli_errors_as_one_document() {
@@ -527,11 +565,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
let hello = root.join("examples").join("hello.mq.md");
let hello = hello.to_str().unwrap();
let mode = cli(&root, &["run", hello, "--mode", "bogus", "--json"]);
let mode = cli(
&root,
&["run", hello, "--mode", "bogus", "--output", "json"],
);
assert_exit(&mode, 2, "unknown mode");
let value = json_stdout(&mode);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "cli.invalid_mode");
assert_eq!(value["run"]["status"], "rejected");
assert_eq!(
observation::terminal(&value)["error"]["code"],
"cli.invalid_mode"
);
let grants = cli(
&root,
@@ -542,13 +586,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
"pure",
"--allow-read",
"x",
"--json",
"--output",
"json",
],
);
assert_exit(&grants, 2, "pure mode must reject grants");
let value = json_stdout(&grants);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "cli.invalid_grants");
assert_eq!(value["run"]["status"], "rejected");
assert_eq!(
observation::terminal(&value)["error"]["code"],
"cli.invalid_grants"
);
let strict = cli(
&root,
@@ -558,13 +606,17 @@ fn json_mode_reports_cli_errors_as_one_document() {
"--mode",
"strict",
"--allow-foreign",
"--json",
"--output",
"json",
],
);
assert_exit(&strict, 2, "strict L1 must reject foreign grants");
let value = json_stdout(&strict);
assert_eq!(value["success"], false);
assert_eq!(value["code"], "strict.unsupported_grant");
assert_eq!(value["run"]["status"], "rejected");
assert_eq!(
observation::terminal(&value)["error"]["code"],
"strict.unsupported_grant"
);
}
#[test]
@@ -613,7 +665,7 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
assert_exit(&refs, 0, "inspect --refs");
let value = json_stdout(&refs);
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`.
let dir = TempDir::new("refs");
@@ -627,7 +679,8 @@ fn inspect_outputs_ast_units_signatures_ir_and_refs() {
let edges = value["refs"].as_array().expect("refs array");
assert_eq!(edges.len(), 1);
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]
@@ -732,7 +785,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
/// the Linux-only example manifest. This is what makes the integration test a
/// real test on macOS/Windows rather than an accidental "no matching artifact".
fn host_triple() -> String {
marqdo_plugin_abi::artifact::current_target_triple()
marqdo_host::plugin::artifact::current_target_triple()
.as_str()
.to_string()
}
@@ -923,11 +976,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
"## @exec boom\n\n说明文字。\n\n`x = 1 / 0`\n\n`return x`\n",
);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_exit(&output, 1, "division by zero is a runtime error");
let value: serde_json::Value =
serde_json::from_str(&stdout_text(&output)).expect("run --json emits JSON");
let error = &value["error"];
serde_json::from_str(&stdout_text(&output)).expect("run --output json emits JSON");
let error = &observation::terminal(&value)["error"];
assert_eq!(error["code"], "runtime.division_by_zero");
assert!(
error["module_id"]
@@ -939,22 +992,11 @@ fn runtime_error_in_imported_module_reports_that_module() {
);
assert_eq!(error["relative_path"], "physics.mq.md");
assert!(
error["file"]
.as_str()
.unwrap_or_default()
.ends_with("physics.mq.md"),
"{}",
error["file"]
error.get("file").is_none(),
"a shareable snapshot must not embed an absolute host path: {error}"
);
let line = error["line"].as_u64().unwrap_or(0);
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"]);
assert_exit(&human, 1, "human rendering also fails");
@@ -1171,22 +1213,22 @@ fn power_branch_loop_and_inert_code_end_to_end() {
"branch.mq.md",
"## @exec main\n\n`n = 2`\n\n`if n ** 2 == 4`\n\n`print(\"乘方正确\")`\n\n`else`\n\n`if n ** 2 != 4`\n\n`print(\"乘方错误\")`\n\n`end`\n\n`end`\n",
);
let branch = cli(dir.path(), &["run", "branch.mq.md", "--json"]);
let branch = cli(dir.path(), &["run", "branch.mq.md", "--output", "json"]);
assert_exit(&branch, 0, "power branch run");
let value = json_stdout(&branch);
assert_eq!(value["success"], true);
assert_eq!(value["stdout"], "乘方正确\n");
assert_eq!(value["value"]["type"], "unit");
assert_eq!(value["run"]["status"], "ok");
assert_eq!(observation::text(&value, "stdout.chunk"), "乘方正确\n");
assert_eq!(observation::terminal(&value)["value"]["type"], "unit");
dir.write(
"loop.mq.md",
"## @exec main\n\n`n = 0`\n\n`limit = 100`\n\n`while n ** 2 < limit`\n\n`n = n + 1`\n\n`end`\n\n`return n`\n",
);
let looped = cli(dir.path(), &["run", "loop.mq.md", "--json"]);
let looped = cli(dir.path(), &["run", "loop.mq.md", "--output", "json"]);
assert_exit(&looped, 0, "power loop run");
let value = json_stdout(&looped);
assert_eq!(value["value"]["type"], "int");
assert_eq!(value["value"]["decimal"], "10");
assert_eq!(observation::terminal(&value)["value"]["type"], "int");
assert_eq!(observation::terminal(&value)["value"]["decimal"], "10");
// A code fence containing power syntax is an inert value: it produces no
// diagnostics and never changes the returned value.
@@ -1194,10 +1236,10 @@ fn power_branch_loop_and_inert_code_end_to_end() {
"inert.mq.md",
"## @exec main\n\n```text\n**n = 2 ** 3**\n```\n\n`x = 1`\n\n`return x`\n\n### @knowledge 说明\n\n正文里的 `2 ** 3` 不执行。\n",
);
let inert = cli(dir.path(), &["run", "inert.mq.md", "--json"]);
let inert = cli(dir.path(), &["run", "inert.mq.md", "--output", "json"]);
assert_exit(&inert, 0, "inert code run");
let value = json_stdout(&inert);
assert_eq!(value["value"]["decimal"], "1");
assert_eq!(observation::terminal(&value)["value"]["decimal"], "1");
}
#[test]
+4 -2
View File
@@ -4,9 +4,11 @@
//! checked-in examples.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -49,7 +51,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -1,9 +1,11 @@
//! Black-box Execution Events v1 contract tests (RFC-OBS-0001).
//! Black-box Observation contract tests.
//!
//! These drive the real `marqdo` binary (`CARGO_BIN_EXE_marqdo`) and parse the
//! stdout line stream exactly like an external consumer. They cover the P0
//! envelope/lifecycle/byte-fidelity contract and the P1 frame/value policy,
//! plus trace coexistence, truncation, live delivery and a broken pipe.
//! plus snapshot equivalence, truncation, live delivery and a broken pipe.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::fs;
use std::io::{BufRead, BufReader, Read};
@@ -51,7 +53,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -124,7 +126,7 @@ fn assert_envelope(events: &[Value]) {
assert!(!events.is_empty());
let first = &events[0];
assert_eq!(first["kind"], "stream.opened");
assert_eq!(first["schema"], "marqdo.execution-events");
assert_eq!(first["schema"], "marqdo.observation");
assert_eq!(first["schema_version"], 1);
assert_eq!(first["seq"], 0);
let run_id = first["run_id"].as_str().unwrap().to_string();
@@ -174,15 +176,16 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
eprintln!("python3 + jsonschema unavailable; schema consumer skipped");
return;
}
let fixtures = repo_root().join("tests/consumers/fixtures/execution-events");
let consumer = repo_root().join("tests/consumers/execution_events_consumer.py");
let fixtures = repo_root().join("tests/consumers/fixtures/observation");
let consumer = repo_root().join("tests/consumers/observation_consumer.py");
for name in ["minimal.jsonl", "full.jsonl"] {
let path = fixtures.join("valid").join(name);
let output = Command::new("python3")
.arg(&consumer)
.arg("--validate-schema")
.arg(&path)
.output()
.expect("run execution events consumer");
.expect("run observation consumer");
assert!(
output.status.success(),
"valid fixture {name} rejected: {}",
@@ -193,9 +196,10 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
let path = entry.unwrap().path();
let output = Command::new("python3")
.arg(&consumer)
.arg("--validate-schema")
.arg(&path)
.output()
.expect("run execution events consumer");
.expect("run observation consumer");
assert!(
!output.status.success(),
"invalid fixture {} was accepted",
@@ -208,7 +212,7 @@ fn checked_in_fixtures_validate_against_the_public_schema() {
fn structure_fixture_attributes_repeated_recursive_frames() {
let dir = TempDir::new("structure");
let source = fs::read_to_string(
repo_root().join("tests/consumers/fixtures/execution-events/structure.mq.md"),
repo_root().join("tests/consumers/fixtures/observation/structure.mq.md"),
)
.unwrap();
dir.write("index.mq.md", &source);
@@ -217,7 +221,7 @@ fn structure_fixture_attributes_repeated_recursive_frames() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-max-events",
"1000",
@@ -278,7 +282,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
let manifest = format!(
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
marqdo_plugin_abi::HostTarget::current().triple(),
marqdo_host::plugin::HostTarget::current().triple(),
digest
);
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
@@ -287,7 +291,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--plugin",
plugin_dir.join("plugin.yaml").to_str().unwrap(),
@@ -302,7 +306,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
assert_eq!(terminal["kind"], "run.rejected");
assert_eq!(
terminal["payload"]["error"]["code"],
"ext.event_stream_unsupported_native_plugin"
"ext.observation_unsupported_native_plugin"
);
assert!(
events_of(&events, "run.started").is_empty(),
@@ -311,8 +315,8 @@ fn native_plugin_is_fail_closed_in_event_mode() {
}
#[test]
fn observed_values_never_enter_trace_v2() {
let dir = TempDir::new("trace-redaction");
fn selected_values_apply_equally_to_stream_and_private_snapshot() {
let dir = TempDir::new("capture-consent");
dir.write(
"index.mq.md",
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
@@ -323,12 +327,12 @@ fn observed_values_never_enter_trace_v2() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-variable",
"secret_token",
"--observe-text-values",
"--trace-file",
"--observation-file",
trace_path.to_str().unwrap(),
],
);
@@ -337,24 +341,32 @@ fn observed_values_never_enter_trace_v2() {
String::from_utf8_lossy(&output.stdout).contains("DO_NOT_LEAK_SENTINEL_1"),
"the explicit event consent publishes the selected value in the stream"
);
let trace = fs::read(&trace_path).unwrap();
assert!(
!String::from_utf8_lossy(&trace).contains("DO_NOT_LEAK_SENTINEL_1"),
"Trace v2 must not gain observed values"
let snapshot_bytes = fs::read(&trace_path).unwrap();
let snapshot: Value = serde_json::from_slice(&snapshot_bytes).unwrap();
assert_eq!(
snapshot["events"],
serde_json::json!(parse_events(&output.stdout))
);
let trace: Value = serde_json::from_slice(&trace).unwrap();
assert_eq!(trace["schema"], "marqdo.trace");
assert_eq!(trace["schema_version"], 2);
assert_eq!(
snapshot["capture"]["selected_variables"],
serde_json::json!(["secret_token"])
);
assert!(String::from_utf8_lossy(&snapshot_bytes).contains("DO_NOT_LEAK_SENTINEL_1"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&trace_path).unwrap().permissions().mode() & 0o777,
0o600
);
}
}
#[test]
fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() {
let dir = TempDir::new("basic");
dir.write("index.mq.md", BASIC);
let output = cli(
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
let output = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
assert_eq!(
output.status.code(),
Some(0),
@@ -382,27 +394,27 @@ fn basic_stream_is_pure_jsonl_and_reconstructs_program_output() {
}
#[test]
fn event_stream_rejects_mixed_json_and_static_commands() {
fn retired_run_options_and_static_observation_are_rejected() {
let dir = TempDir::new("reject");
dir.write("index.mq.md", BASIC);
let mixed = cli(
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl", "--json"],
);
assert_eq!(mixed.status.code(), Some(2));
assert!(mixed.stdout.is_empty(), "no mixed stdout");
assert!(String::from_utf8_lossy(&mixed.stderr).contains("--json"));
for args in [
vec!["--json"],
vec!["--event-stream", "jsonl"],
vec!["--trace-file", "retired.json"],
vec!["--trace"],
vec!["--output", "jsonl", "--output", "json"],
vec!["--observe-variable", "n"],
] {
let mut command = vec!["run", "index.mq.md"];
command.extend(args);
let rejected = cli(dir.path(), &command);
assert_eq!(rejected.status.code(), Some(2));
assert!(rejected.stdout.is_empty(), "{command:?} must not execute");
}
assert!(!dir.path().join("retired.json").exists());
for command in ["check", "inspect"] {
let rejected = cli(
dir.path(),
&[command, "index.mq.md", "--event-stream", "jsonl"],
);
assert_eq!(
rejected.status.code(),
Some(2),
"{command} must reject the option"
);
let rejected = cli(dir.path(), &[command, "index.mq.md", "--output", "jsonl"]);
assert_eq!(rejected.status.code(), Some(2));
assert!(rejected.stdout.is_empty(), "{command} must not execute");
}
}
@@ -411,10 +423,7 @@ fn event_stream_rejects_mixed_json_and_static_commands() {
fn prepare_and_runtime_failures_have_defined_terminals() {
let dir = TempDir::new("failures");
dir.write("broken.mq.md", "## @exec main\n\n`if true`\n\n`return 1`\n");
let rejected = cli(
dir.path(),
&["run", "broken.mq.md", "--event-stream", "jsonl"],
);
let rejected = cli(dir.path(), &["run", "broken.mq.md", "--output", "jsonl"]);
assert_eq!(rejected.status.code(), Some(1));
let events = parse_events(&rejected.stdout);
assert_envelope(&events);
@@ -429,10 +438,7 @@ fn prepare_and_runtime_failures_have_defined_terminals() {
"runtime.mq.md",
"## @exec main\n\n`x = 1 / 0`\n\n`return x`\n",
);
let failed = cli(
dir.path(),
&["run", "runtime.mq.md", "--event-stream", "jsonl"],
);
let failed = cli(dir.path(), &["run", "runtime.mq.md", "--output", "jsonl"]);
assert_eq!(failed.status.code(), Some(1));
let events = parse_events(&failed.stdout);
assert_envelope(&events);
@@ -455,10 +461,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
"## @exec main\n\n`secret_token = \"DO_NOT_LEAK_SENTINEL_1\"`\n\n`visible_count = 42`\n\n`return visible_count`\n",
);
// Default: metadata only; no value, no sentinel anywhere.
let default = cli(
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
let default = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
assert_eq!(default.status.code(), Some(0));
assert!(!String::from_utf8_lossy(&default.stdout).contains("DO_NOT_LEAK_SENTINEL_1"));
for event in events_of(&parse_events(&default.stdout), "variable.assigned") {
@@ -471,7 +474,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-variable",
"visible_count",
@@ -498,7 +501,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-variable",
"secret_token",
@@ -519,7 +522,7 @@ fn value_observation_is_exact_and_requires_text_consent() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-variable",
"secret_token",
@@ -554,10 +557,7 @@ fn binary_and_multibyte_output_is_byte_exact() {
"{}",
String::from_utf8_lossy(&normal.stderr)
);
let streamed = cli(
dir.path(),
&["run", "index.mq.md", "--event-stream", "jsonl"],
);
let streamed = cli(dir.path(), &["run", "index.mq.md", "--output", "jsonl"]);
assert_eq!(streamed.status.code(), Some(0));
let events = parse_events(&streamed.stdout);
let chunks = chunk_bytes(&events, "stdout.chunk");
@@ -570,37 +570,50 @@ fn binary_and_multibyte_output_is_byte_exact() {
}
#[test]
fn trace_file_coexists_and_shares_the_run_identity() {
let dir = TempDir::new("trace");
fn stream_and_snapshot_share_every_event_from_one_run() {
let dir = TempDir::new("destinations");
dir.write("index.mq.md", BASIC);
let trace_path = dir.path().join("trace.json");
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--trace-file",
trace_path.to_str().unwrap(),
"--observation-file",
"run.json",
],
);
assert_eq!(output.status.code(), Some(0));
assert!(output.status.success(), "{output:?}");
let events = parse_events(&output.stdout);
assert_envelope(&events);
let trace: Value = serde_json::from_slice(&fs::read(&trace_path).unwrap()).unwrap();
assert_eq!(trace["schema"], "marqdo.trace");
assert_eq!(trace["schema_version"], 2);
assert_eq!(trace["run"]["id"], events[0]["run_id"]);
let started = events_of(&events, "run.started")[0];
let snapshot: Value =
serde_json::from_slice(&fs::read(dir.path().join("run.json")).unwrap()).unwrap();
assert_eq!(snapshot["schema"], "marqdo.observation");
assert_eq!(snapshot["schema_version"], 1);
assert_eq!(snapshot["run"]["id"], events[0]["run_id"]);
assert_eq!(snapshot["run"]["source"], events[1]["payload"]["source"]);
assert_eq!(snapshot["events"], serde_json::json!(events));
let second = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--output",
"json",
"--observation-file",
"run.json",
],
);
assert!(second.status.success(), "{second:?}");
assert_eq!(
started["payload"]["source"]["analysis_digest"],
trace["source"]["analysis_digest"]
);
assert!(
events_of(&events, "run.completed").len() == 1,
"trace writing does not suppress the terminal event"
second.stdout,
fs::read(dir.path().join("run.json")).unwrap()
);
let second: Value = serde_json::from_slice(&second.stdout).unwrap();
assert_ne!(second["run"]["id"], snapshot["run"]["id"]);
assert_eq!(second["run"]["status"], "ok");
}
#[test]
@@ -612,7 +625,7 @@ fn structural_budget_truncates_without_losing_critical_events() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-max-events",
"5",
@@ -637,7 +650,7 @@ fn output_budget_still_fails_the_run_and_emits_no_chunk() {
&[
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--max-output",
"3",
@@ -659,11 +672,11 @@ fn live_chunks_arrive_while_the_program_is_still_running() {
let dir = TempDir::new("live");
let source = "## @exec main\n\n`打印(\"READY\")`\n\n`i = 0`\n\n`while i < 2000000`\n\n`i = i + 1`\n\n`end`\n\n`打印(\"FINISH\")`\n\n`return i`\n";
dir.write("index.mq.md", source);
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-max-events",
"20",
@@ -712,11 +725,11 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
let dir = TempDir::new("pipe");
let source = "## @exec main\n\n`打印(\"START\")`\n\n`i = 0`\n\n`while i < 5000000`\n\n`i = i + 1`\n\n`end`\n\n`return i`\n";
dir.write("index.mq.md", source);
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
"--event-stream",
"--output",
"jsonl",
"--observe-max-events",
"10",
@@ -811,9 +824,9 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
"index.mq.md",
"--mode",
"pure",
"--event-stream",
"--output",
"jsonl",
"--trace-file",
"--observation-file",
"trace.json",
],
);
@@ -823,9 +836,9 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
assert_eq!(events.last().unwrap()["kind"], "run.completed");
let trace: Value =
serde_json::from_slice(&fs::read(dir.path().join("trace.json")).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2);
assert_eq!(trace["schema_version"], 1);
assert_eq!(
trace["source"]["analysis_digest"],
trace["run"]["source"]["analysis_digest"],
format!("sha256:{:x}", Sha256::digest(analysis_bytes))
);
@@ -850,7 +863,7 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
];
assert_eq!(kinds(&events), expected);
let trace_events = trace["events"].as_array().unwrap();
assert_eq!(kinds(trace_events), expected);
assert_eq!(trace_events, &events);
let frame = &events_of(&events, "call.enter")[0]["payload"]["frame_id"];
for (index, keyword) in ["continue", "break"].iter().enumerate() {
let kind = format!("control.{keyword}");
@@ -862,12 +875,51 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() {
assert_eq!(payload["module_id"], module["id"]);
assert_eq!(payload["span"], span);
assert_eq!(payload.as_object().unwrap().len(), 3);
let event = &events_of(trace_events, &kind)[0];
assert_eq!(event["module_id"], module["id"]);
assert_eq!(event["span"], span);
assert!(event["detail"].is_null());
let statement = &branch["arms"][index]["body"][0];
assert_eq!(statement["kind"], *keyword);
assert_eq!(statement["span"], span);
}
}
#[test]
fn strict_mode_rejects_live_and_file_destinations_before_opening_a_stream() {
let dir = TempDir::new("strict-destinations");
dir.write("index.mq.md", BASIC);
let snapshot = dir.path().join("snapshot.json");
let snapshot_arg = snapshot.to_str().unwrap().to_string();
for args in [
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"jsonl",
],
vec![
"run",
"index.mq.md",
"--mode",
"strict",
"--output",
"text",
"--observation-file",
snapshot_arg.as_str(),
],
] {
let output = cli(dir.path(), &args);
assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}");
assert!(
output.stdout.is_empty(),
"a rejected strict destination must not emit a partial stream: {}",
String::from_utf8_lossy(&output.stdout)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("strict.unsupported_grant"), "{stderr}");
assert!(
!snapshot.exists(),
"a rejected strict destination must not publish a snapshot file"
);
}
}
+42 -40
View File
@@ -1,7 +1,11 @@
//! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::path::{Path, PathBuf};
use std::process::Command;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -69,8 +73,15 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
"{criterion} fixture {name} uses forbidden host shortcut `{forbidden}`"
);
}
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"])
let output = stdlib_support::cli_command()
.args([
"run",
path.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(repo_root())
.output()
.expect("run marqdo");
@@ -82,47 +93,21 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
);
let report: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("json report");
assert_eq!(report["success"], true, "{name}");
assert_eq!(report["run"]["status"], "ok", "{name}");
let golden = expected(name);
assert_eq!(
report["value"], golden["value"],
observation::terminal(&report)["value"],
golden["value"],
"{criterion} fixture {name}"
);
assert_eq!(
report["stdout"].as_str().unwrap_or_default(),
observation::text(&report, "stdout.chunk"),
golden["stdout"].as_str().unwrap_or_default(),
"{criterion} fixture {name} stdout"
);
}
}
#[test]
fn p2_stdlib_table_also_runs_in_pure_mode() {
let path = repo_root().join("stdlib").join("tests").join("table.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"]
.as_array()
.expect("table test list");
assert_eq!(items.len(), 9);
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
#[test]
fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
let dir = tempfile::tempdir().unwrap();
@@ -132,15 +117,25 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
"## @knowledge 代码\n\n```python\nprint(1)\n```\n\n## @exec main\n\n`return foreign.call(ref(\"#代码\"), None)`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", foreign.to_str().unwrap(), "--mode", "pure", "--json"])
let output = stdlib_support::cli_command()
.args([
"run",
foreign.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(dir.path())
.output()
.expect("run foreign fixture");
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "permission.denied");
assert_ne!(report["run"]["status"], "ok");
assert_eq!(
observation::terminal(&report)["error"]["code"],
"permission.denied"
);
let plugin = dir.path().join("plugin.mq.md");
std::fs::write(
@@ -148,12 +143,19 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
"## @exec main\n\n`plugin.invoke(\"missing.export\", {})`\n\n`return None`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", plugin.to_str().unwrap(), "--mode", "pure", "--json"])
let output = stdlib_support::cli_command()
.args([
"run",
plugin.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(dir.path())
.output()
.expect("run plugin fixture");
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], false);
assert_ne!(report["run"]["status"], "ok");
}
+3 -5
View File
@@ -1,6 +1,8 @@
//! Package instance identity, transitive imports, pinned Git and environment
//! materialization (M0.6 R1/R5).
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -32,12 +34,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+6 -4
View File
@@ -1,11 +1,13 @@
//! Isolated plugin worker transport (ADR-0010).
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -118,7 +120,7 @@ fn write_manifest(dir: &Path, sha: &str) {
}
fn run(dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args([
"run",
dir.join("doc.mq.md").to_str().unwrap(),
@@ -167,7 +169,7 @@ fn worker_crash_is_isolated_from_the_host() {
"{stderr}"
);
// The host process survived and still runs a native Marqdo program.
let survivor = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let survivor = stdlib_support::cli_command()
.args(["run", "examples/hello.mq.md"])
.current_dir(repo())
.output()
@@ -235,7 +237,7 @@ fn write_capability_manifest(dir: &Path, sha: &str) {
}
fn run_capability(dir: &Path, allow_read: bool) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
let mut command = stdlib_support::cli_command();
command.args([
"run",
dir.join("doc.mq.md").to_str().unwrap(),
+6 -4
View File
@@ -1,7 +1,9 @@
//! Compat-B `打印` routing tests (ADR-0030).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
struct TempDir(PathBuf);
@@ -25,7 +27,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -52,7 +54,7 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
&[
"run",
"index.mq.md",
"--trace-file",
"--observation-file",
trace.to_str().unwrap(),
],
);
@@ -69,7 +71,7 @@ fn print_is_routed_through_the_stdlib_and_not_hostop_print() {
.as_array()
.unwrap()
.iter()
.filter_map(|event| event["operation"].as_str())
.filter_map(|event| event["payload"]["operation"].as_str())
.collect();
assert!(
operations.contains(&"resource.write"),
+53 -31
View File
@@ -15,6 +15,11 @@
//! Other platforms must keep this file compiling but run no provider
//! assertions; the CLI itself fails closed with `ext.platform_unsupported`.
#![cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::fs;
use std::path::{Path, PathBuf};
@@ -22,7 +27,7 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::OnceLock;
use marqdo_plugin_abi::HostTarget;
use marqdo_host::plugin::HostTarget;
use sha2::{Digest, Sha256};
const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER";
@@ -398,7 +403,7 @@ fn marker_text(path: &Path) -> String {
}
fn run_cli(dir: &Path, args: &[&str], marker: &Path) -> Output {
Command::new(cli_binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env(MARKER_ENV, marker)
@@ -417,17 +422,14 @@ fn json_of(output: &Output) -> serde_json::Value {
}
fn error_code(report: &serde_json::Value) -> String {
report
.get("error")
.and_then(|error| error.get("code"))
.or_else(|| report.get("code"))
.and_then(|code| code.as_str())
.unwrap_or("<missing error code>")
observation::terminal(report)["error"]["code"]
.as_str()
.expect("terminal error code")
.to_string()
}
fn map_field<'a>(report: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
&report["value"]["entries"][name]
&observation::terminal(report)["value"]["entries"][name]
}
fn cc_available() -> bool {
@@ -469,7 +471,8 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -480,7 +483,7 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
"run failed: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(report["success"].as_bool().unwrap_or(false));
assert_eq!(report["run"]["status"], "ok");
assert_eq!(map_field(&report, "count")["decimal"], "5");
assert!(map_field(&report, "eof")["value"]
.as_bool()
@@ -490,13 +493,14 @@ fn prov_01_authorized_v2_worker_reads_five_bytes() {
.unwrap_or(false));
// `hello` is in the Memory region the provider filled on the first byte.
assert_eq!(map_field(&report, "data")["decimal"], "104");
assert_eq!(report["stdout"], "");
assert_eq!(observation::text(&report, "stdout.chunk"), "");
// The Host recorded the real resource effect (not a synthetic success).
let trace = report["trace"].as_array().expect("trace array");
let trace = report["events"].as_array().expect("trace array");
assert!(
trace
.iter()
.any(|entry| entry["op"] == "resource.open" && entry["result"] == "ok"),
.any(|entry| entry["payload"]["operation"] == "resource.open"
&& entry["payload"]["result_code"] == "ok"),
"missing resource.open trace: {trace:?}"
);
let marks = marker_text(&marker);
@@ -534,13 +538,14 @@ fn prov_02_without_grant_is_permission_denied_and_never_starts_the_worker() {
"index.mq.md",
"--provider",
manifest.to_str().expect("utf-8 manifest path"),
"--json",
"--output",
"json",
],
&marker,
);
assert_eq!(output.status.code(), Some(1));
let report = json_of(&output);
assert!(!report["success"].as_bool().unwrap_or(true));
assert_eq!(report["run"]["status"], "rejected");
assert_eq!(error_code(&report), "permission.denied");
assert!(
!marker.exists(),
@@ -562,7 +567,8 @@ fn prov_03_grant_without_manifest_is_never_discovered() {
"index.mq.md",
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -603,7 +609,8 @@ fn prov_04_duplicate_kind_across_providers_is_rejected_before_spawn() {
"demo.one",
"--allow-provider",
"demo.two",
"--json",
"--output",
"json",
],
&marker,
);
@@ -636,7 +643,8 @@ fn prov_05_one_provider_serves_two_non_reserved_kinds() {
manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider",
"demo.multi",
"--json",
"--output",
"json",
],
&marker,
);
@@ -647,7 +655,9 @@ fn prov_05_one_provider_serves_two_non_reserved_kinds() {
String::from_utf8_lossy(&output.stderr)
);
let report = json_of(&output);
let items = report["value"]["items"].as_array().expect("list result");
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(items[0]["decimal"], "5");
assert_eq!(items[1]["decimal"], "2");
assert!(items[2]["value"].as_bool().unwrap_or(false));
@@ -691,7 +701,8 @@ fn prov_06_reserved_core_kinds_are_rejected() {
manifest.to_str().expect("utf-8 manifest path"),
"--allow-provider",
"demo.reserved",
"--json",
"--output",
"json",
],
&marker,
);
@@ -734,7 +745,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
digest_manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -772,7 +784,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
symlink_manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -803,7 +816,8 @@ fn prov_07_digest_symlink_and_traversal_fail_before_spawn() {
traversal_manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -838,7 +852,8 @@ fn prov_08_missing_current_target_is_no_matching_artifact() {
manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -873,7 +888,8 @@ fn prov_09_v1_manifest_is_unsupported_without_migration() {
manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -910,7 +926,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg,
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -932,7 +949,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg,
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
],
&marker,
);
@@ -953,7 +971,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() {
manifest_arg,
"--allow-provider",
"*",
"--json",
"--output",
"json",
],
&marker,
);
@@ -992,7 +1011,8 @@ fn prov_13_missing_sibling_helper_is_worker_unavailable_without_path_fallback()
manifest.to_str().expect("utf-8 path"),
"--allow-provider",
"demo.sensor",
"--json",
"--output",
"json",
])
.current_dir(fixture.path())
.env("PATH", path)
@@ -1007,7 +1027,9 @@ fn prov_13_missing_sibling_helper_is_worker_unavailable_without_path_fallback()
);
let report = json_of(&output);
assert_eq!(error_code(&report), "ext.worker_unavailable");
let message = report["error"]["message"].as_str().unwrap_or_default();
let message = observation::terminal(&report)["error"]["message"]
.as_str()
.unwrap_or_default();
assert!(
message.contains("marqdo-provider-worker") && message.contains("missing"),
"{message}"
+74 -30
View File
@@ -1,8 +1,13 @@
//! End-to-end resource stream tests through the CLI.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::process::{Output, Stdio};
struct TempDir(PathBuf);
@@ -27,7 +32,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -35,7 +40,7 @@ fn cli(dir: &Path, args: &[&str]) -> Output {
}
fn cli_with_stdin(dir: &Path, args: &[&str], input: &[u8]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.stdin(Stdio::piped())
@@ -80,7 +85,14 @@ fn project_file_stream_reads_chunks_into_memory() {
write_file(&dir.path().join("index.mq.md"), READER);
let output = cli(
dir.path(),
&["run", "index.mq.md", "--allow-read", "data.txt", "--json"],
&[
"run",
"index.mq.md",
"--allow-read",
"data.txt",
"--output",
"json",
],
);
assert_eq!(
output.status.code(),
@@ -89,8 +101,8 @@ fn project_file_stream_reads_chunks_into_memory() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values: Vec<&serde_json::Value> = report["value"]["items"]
assert_eq!(report["run"]["status"], "ok");
let values: Vec<&serde_json::Value> = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result")
.iter()
@@ -148,7 +160,8 @@ fn project_file_stream_writes_on_close_then_reads_back() {
"out.bin",
"--allow-read",
"out.bin",
"--json",
"--output",
"json",
],
);
assert_eq!(
@@ -158,8 +171,10 @@ fn project_file_stream_writes_on_close_then_reads_back() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(report["run"]["status"], "ok");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["decimal"], "3");
@@ -224,7 +239,8 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() {
"data.txt",
"--allow-write",
"out.bin",
"--json",
"--output",
"json",
],
);
assert_eq!(
@@ -234,8 +250,10 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(report["run"]["status"], "ok");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "6");
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], true);
@@ -287,7 +305,14 @@ fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
write_file(&dir.path().join("index.mq.md"), &program);
let output = cli(
dir.path(),
&["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"],
&[
"run",
"index.mq.md",
"--allow-net",
"127.0.0.1",
"--output",
"json",
],
);
assert_eq!(
output.status.code(),
@@ -296,8 +321,10 @@ fn tcp_stream_round_trips_through_mqmd_with_a_network_grant() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list");
assert_eq!(report["run"]["status"], "ok");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(values[0]["decimal"], "4");
assert_eq!(values[1]["decimal"], "4");
for (index, expected) in ["112", "105", "110", "103"].into_iter().enumerate() {
@@ -312,11 +339,14 @@ fn file_stream_requires_a_read_grant() {
let dir = TempDir::new("file-denied");
write_file(&dir.path().join("data.txt"), "abcdef");
write_file(&dir.path().join("index.mq.md"), READER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_eq!(output.status.code(), Some(1));
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], false);
assert_eq!(report["error"]["code"], "permission.denied");
assert_ne!(report["run"]["status"], "ok");
assert_eq!(
observation::terminal(&report)["error"]["code"],
"permission.denied"
);
}
const STDIN_READER: &str = r#"## @exec main
@@ -338,7 +368,11 @@ const STDIN_READER: &str = r#"## @exec main
fn piped_stdin_is_chunked_and_reaches_eof() {
let dir = TempDir::new("stdin");
write_file(&dir.path().join("index.mq.md"), STDIN_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"abcd");
let output = cli_with_stdin(
dir.path(),
&["run", "index.mq.md", "--output", "json"],
b"abcd",
);
assert_eq!(
output.status.code(),
Some(0),
@@ -346,8 +380,10 @@ fn piped_stdin_is_chunked_and_reaches_eof() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(report["run"]["status"], "ok");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "2");
assert_eq!(values[1]["value"], false);
assert_eq!(values[2]["decimal"], "2");
@@ -393,7 +429,7 @@ const STDERR_WRITER: &str = r#"## @exec main
fn program_stderr_is_separate_from_stdout_and_diagnostics() {
let dir = TempDir::new("stderr");
write_file(&dir.path().join("index.mq.md"), STDERR_WRITER);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
let output = cli(dir.path(), &["run", "index.mq.md", "--output", "json"]);
assert_eq!(
output.status.code(),
Some(0),
@@ -401,10 +437,12 @@ fn program_stderr_is_separate_from_stdout_and_diagnostics() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
assert_eq!(report["stdout"], "out");
assert_eq!(report["stderr"], "err");
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(report["run"]["status"], "ok");
assert_eq!(observation::text(&report, "stdout.chunk"), "out");
assert_eq!(observation::text(&report, "stderr.chunk"), "err");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["decimal"], "3");
assert_eq!(values[1]["decimal"], "3");
assert_eq!(values[2]["value"], true);
@@ -433,7 +471,11 @@ import:
fn stdlib_console_reads_lines_and_reports_eof() {
let dir = TempDir::new("console");
write_file(&dir.path().join("index.mq.md"), CONSOLE_READER);
let output = cli_with_stdin(dir.path(), &["run", "index.mq.md", "--json"], b"one\ntwo\n");
let output = cli_with_stdin(
dir.path(),
&["run", "index.mq.md", "--output", "json"],
b"one\ntwo\n",
);
assert_eq!(
output.status.code(),
Some(0),
@@ -441,9 +483,11 @@ fn stdlib_console_reads_lines_and_reports_eof() {
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json output");
assert_eq!(report["success"], true);
assert_eq!(report["stdout"], "one|two\n");
let values = report["value"]["items"].as_array().expect("list result");
assert_eq!(report["run"]["status"], "ok");
assert_eq!(observation::text(&report, "stdout.chunk"), "one|two\n");
let values = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list result");
assert_eq!(values[0]["value"], true);
assert_eq!(values[1]["value"], true);
assert_eq!(values[2]["value"], false);
+5 -12
View File
@@ -4,9 +4,11 @@
//! in the verified `stdlib.json` metadata. There is no `print_override`, no
//! runtime name special case and no hard-coded per-function scan.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -35,17 +37,8 @@ impl Drop for TempDir {
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
let mut command = stdlib_support::cli_command();
command.args(args).current_dir(dir);
for (key, value) in env {
command.env(key, value);
@@ -62,7 +55,7 @@ fn stdout(output: &Output) -> String {
}
fn copy_stdlib(target: &Path) {
let source = repo().join("stdlib");
let source = stdlib_support::bundle_dir();
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
+4 -12
View File
@@ -1,27 +1,19 @@
//! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::Command;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
stdlib_support::bundle_dir()
}
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env("MARQDO_STDLIB_DIR", stdlib)
-43
View File
@@ -1,43 +0,0 @@
//! CM-A08/P5 stdlib HTTP framing module tests.
use std::path::Path;
use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
#[test]
fn stdlib_http_parses_chunked_responses_and_builds_requests() {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/http.mq.md", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run http self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["decimal"], "200");
assert_eq!(items[1]["value"], "OK");
assert_eq!(items[2]["value"], "text/plain");
assert_eq!(items[3]["value"], "hello world");
assert_eq!(
items[4]["value"],
"POST /echo HTTP/1.1\r\nHost: example.test\r\nContent-Length: 2\r\n\r\nok"
);
assert_eq!(items[5]["decimal"], "200");
assert_eq!(items[6]["value"], "你好");
assert_eq!(items[7]["value"], "POST / HTTP/1.1\r\n\r\nAB");
}
+122 -476
View File
@@ -1,511 +1,157 @@
//! Product-level tests for the whole bundled `marqdo-stdlib` tree.
//! CLI product lane against the accepted external stdlib Bundle (ADR-0070 Phase B).
//!
//! Every public module in `stdlib/README.md` has a `.mq.md` self-test under
//! `stdlib/tests/`, and this lane runs the whole directory through the real
//! user import path (`std:` + the verified bundle), not through a conformance
//! fixture or a Rust shortcut.
//! The standard-library module sources and their self-tests live in the
//! component repositories; this lane proves what the CLI still owns: it loads
//! one verified offline Bundle, resolves the public `std:` surface, and routes
//! the official `print`/`打印` aliases through the ordinary target function.
//! The Bundle is an explicit input (`MARQDO_TEST_STDLIB_BUNDLE`) verified
//! against `tools/stdlib/bundle-pin.json`; there is no in-repo fallback.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard};
#[path = "support/observation.rs"]
pub mod observation;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
static FS_LOCK: Mutex<()> = Mutex::new(());
use std::process::{Command, Output};
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
if name == "fs.mq.md" {
Some(FS_LOCK.lock().unwrap_or_else(|error| error.into_inner()))
} else {
None
}
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
}
struct TestFile {
name: String,
stdin: &'static str,
stdout: &'static str,
args: Vec<String>,
env: Vec<(String, String)>,
}
fn product_tests() -> Vec<TestFile> {
let dir = stdlib_dir().join("tests");
let mut files: Vec<TestFile> = std::fs::read_dir(&dir)
.expect("read stdlib tests")
.map(|entry| {
let path = entry.unwrap().path();
if !path.is_file() {
return TestFile {
name: String::new(),
stdin: "",
stdout: "",
args: Vec::new(),
env: Vec::new(),
};
}
let name = path.file_name().unwrap().to_string_lossy().to_string();
let (stdin, stdout) = match name.as_str() {
"console.mq.md" => ("hello\n", ""),
"io.mq.md" => ("", "stdlib self-test\n"),
"stream.mq.md" => ("", "stream\n"),
_ => ("", ""),
};
let text_args = |values: &[&str]| -> Vec<String> {
values.iter().map(|value| value.to_string()).collect()
};
let (args, env) = if name == "fs.mq.md" {
(
text_args(&[
"--allow-read",
"out",
"--allow-read",
"out/**",
"--allow-write",
"out",
"--allow-write",
"out/**",
]),
Vec::new(),
)
} else if name == "env.mq.md" {
(
text_args(&[
"--allow-env",
"MARQDO_TEST_ENV",
"--allow-env",
"MARQDO_MISSING_ENV",
]),
vec![("MARQDO_TEST_ENV".to_string(), "env-value".to_string())],
)
} else if name == "process.mq.md" {
// Use the test binary itself as the granted program: it exists
// on every native platform, unlike the old `/bin/echo` fixture.
let program = env!("CARGO_BIN_EXE_marqdo").to_string();
(
vec![
"--allow-env".to_string(),
"MARQDO_TEST_PROCESS_PROGRAM".to_string(),
"--allow-process".to_string(),
program.clone(),
],
vec![("MARQDO_TEST_PROCESS_PROGRAM".to_string(), program)],
)
} else if name == "random.mq.md" {
(text_args(&["--allow-random"]), Vec::new())
} else {
(Vec::new(), Vec::new())
};
TestFile {
name,
stdin,
stdout,
args,
env,
}
})
.filter(|file| !file.name.is_empty())
.collect();
files.sort_by(|left, right| left.name.cmp(&right.name));
files
}
fn run_product_test(file: &TestFile) -> serde_json::Value {
if file.name == "fs.mq.md" {
let _ = std::fs::remove_dir_all(stdlib_dir().join("tests/out"));
}
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run"])
.arg(stdlib_dir().join("tests").join(&file.name))
.args(file.args.iter())
.args(["--json"])
.current_dir(stdlib_dir())
.env("MARQDO_STDLIB_DIR", stdlib_dir())
.envs(
file.env
.iter()
.map(|(key, value)| (key.as_str(), value.as_str())),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo");
child
.stdin
.as_mut()
.unwrap()
.write_all(file.stdin.as_bytes())
.unwrap();
let output = child.wait_with_output().expect("wait marqdo");
fn run_fixture(name: &str) -> (serde_json::Value, String) {
let bundle = stdlib_support::bundle_dir();
let fixture = stdlib_support::repo_root()
.join("tests")
.join("product-stdlib")
.join(format!("{name}.mq.md"));
let output: Output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"run",
fixture.to_str().expect("utf-8 fixture path"),
"--output",
"json",
])
.env("MARQDO_STDLIB_DIR", &bundle)
.current_dir(stdlib_support::repo_root())
.output()
.expect("run marqdo");
assert_eq!(
output.status.code(),
Some(0),
"{} failed: {}",
file.name,
"{name} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json report")
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json report");
assert_eq!(report["run"]["status"], "ok", "{name}");
let stdout = observation::text(&report, "stdout.chunk");
(report, stdout)
}
#[test]
fn every_public_stdlib_module_has_a_product_test() {
let names: Vec<String> = product_tests().into_iter().map(|file| file.name).collect();
assert_eq!(
names,
vec![
"clock.mq.md",
"compress.mq.md",
"console.mq.md",
"csv.mq.md",
"datetime.mq.md",
"demo.mq.md",
"env.mq.md",
"format.mq.md",
"fs.mq.md",
"http.mq.md",
"io.mq.md",
"json.mq.md",
"path.mq.md",
"process.mq.md",
"random.mq.md",
"regex.mq.md",
"stream.mq.md",
"table.mq.md",
"text.mq.md",
"utf8.mq.md",
],
"a public stdlib module is missing a product test"
fn the_accepted_bundle_is_external_and_has_the_required_surface() {
let pin = stdlib_support::BundlePin::committed();
assert!(
pin.source_path.is_none(),
"Phase B: the accepted Bundle must not be vendored in this repository"
);
}
#[test]
fn the_whole_bundled_library_runs_through_std_imports() {
for file in product_tests() {
let _guard = lock_fs(&file.name);
let report = run_product_test(&file);
assert_eq!(report["success"], true, "{}", file.name);
assert_eq!(
report["stdout"], file.stdout,
"{} wrote unexpected stdout",
file.name
let bundle = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(bundle.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], pin.name);
assert_eq!(manifest["version"], pin.version);
assert_eq!(manifest["digest"], pin.tree_digest);
assert_eq!(manifest["aliases_digest"], pin.aliases_digest);
for required in [
"io.mq.md",
"io/console.mq.md",
"io/stream.mq.md",
"format.mq.md",
"text.mq.md",
"text/utf8.mq.md",
"data/json.mq.md",
"collections/table.mq.md",
"data/table.mq.md",
"fs/file.mq.md",
"path.mq.md",
] {
assert!(
bundle.join(required).is_file(),
"the accepted Bundle is missing {required}"
);
}
}
#[test]
fn fs_test_exercises_the_file_operation_surface() {
let _guard = lock_fs("fs.mq.md");
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "fs.mq.md")
.expect("fs test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "7");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "file");
assert_eq!(items[4]["decimal"], "7");
assert_eq!(items[5]["items"][0]["value"], "fs-a.txt");
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], "你好\n");
assert_eq!(items[10]["decimal"], "7");
assert_eq!(items[11]["value"], "你好\n世界\n");
assert_eq!(items[12]["items"][0]["value"], "fs-b.txt");
assert_eq!(items[13]["value"], true);
assert_eq!(items[14]["value"], true);
assert!(
!stdlib_dir().join("tests/out").exists(),
"the fs test did not remove its directory"
!bundle.join("tests").exists(),
"the accepted Bundle must not ship component self-tests"
);
}
#[test]
fn json_test_parses_and_formats_nested_values() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "json.mq.md")
.expect("json test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "1");
assert_eq!(items[2]["value"], "说\"好");
fn official_print_aliases_match_the_target_function_output() {
let (report, stdout) = run_fixture("print-routing");
assert_eq!(report["run"]["status"], "ok");
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 6, "{stdout:?}");
for pair in [(0, 1), (2, 3), (4, 5)] {
assert_eq!(
lines[pair.0], lines[pair.1],
"official alias formatting differs at line {}",
pair.0
);
}
assert_eq!(
items[3]["value"],
"[1, 2.5, -300.0, 0.4, {\"a\": 1.0}, \"x\"]"
lines[0],
r#"["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]"#
);
assert_eq!(lines[2], "Table[名称 | 分数]{甲 | 87; 乙 | 92}");
assert_eq!(
lines[4],
r#"[Formula("a = 1"), Code("text", 9 bytes), FunctionRef(root:default::print-routing.mq.md::演示函数)]"#
);
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "json.invalid_array");
assert_eq!(items[6]["value"], "json.trailing");
assert_eq!(items[7]["value"], false);
assert_eq!(items[8]["value"], "json.depth");
assert_eq!(items[9]["value"], true);
assert_eq!(items[10]["items"][2]["items"][0]["decimal"], "3");
}
#[test]
fn csv_test_parses_and_formats_quoted_rows() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "csv.mq.md")
.expect("csv test"),
fn std_surface_executes_against_the_official_bundle() {
let (report, stdout) = run_fixture("std-surface");
assert_eq!(stdout, "");
assert_eq!(
observation::terminal(&report)["value"],
serde_json::json!({
"type": "list",
"items": [
{"type": "int", "decimal": "2"},
{"type": "text", "value": "é"},
{"type": "text", "value": "[1, 2]"},
{"type": "text", "value": "[\"ok\", 3]"},
{"type": "text", "value": "a/b"},
{"type": "text", "value": "2026-11-21T08:00:00.123Z"},
{"type": "text", "value": "| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |"}
]
})
);
let items = report["value"]["items"].as_array().expect("list");
let row = items[0]["items"].as_array().expect("row");
assert_eq!(row.len(), 3);
assert_eq!(row[0]["value"], "甲");
assert_eq!(row[1]["value"], "乙,丙");
assert_eq!(row[2]["value"], "说\"好");
assert_eq!(items[1]["value"], "甲,\"乙,丙\",\"说\"\"好\"");
let empty = items[2]["items"].as_array().expect("empty row");
assert_eq!(empty.len(), 1);
assert_eq!(empty[0]["value"], "");
assert_eq!(items[3]["value"], "csv.unterminated_quote");
let quoted = items[4]["items"].as_array().expect("quoted row");
assert_eq!(quoted[0]["value"], "a");
assert_eq!(quoted[1]["value"], "b");
assert_eq!(items[5]["value"], true);
let rows = items[6]["items"].as_array().expect("rows");
assert_eq!(rows.len(), 2);
assert_eq!(rows[1]["items"][0]["value"], "说\"好");
assert_eq!(items[7]["value"], "甲,\"乙,丙\"\n\"说\"\"好\",2");
}
#[test]
fn path_test_joins_and_normalizes_project_paths() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "path.mq.md")
.expect("path test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], "a/b/c");
assert_eq!(items[1]["value"], "c.txt");
assert_eq!(items[2]["value"], "a/b");
assert_eq!(items[3]["value"], "txt");
assert_eq!(items[4]["value"], "a/c");
assert_eq!(items[5]["value"], "/a/c");
assert_eq!(items[6]["value"], "../a/b");
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], false);
}
#[test]
fn regex_test_matches_anchors_classes_and_search() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "regex.mq.md")
.expect("regex test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], false);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
assert_eq!(items[5]["value"], true);
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], false);
assert_eq!(items[10]["value"], "regex.invalid");
assert_eq!(items[11]["value"], "regex.unsupported");
assert_eq!(items[12]["value"], true);
assert_eq!(items[13]["value"], true);
let groups = items[14]["items"].as_array().expect("groups");
assert_eq!(groups[0]["value"], "aab");
assert_eq!(groups[1]["value"], "aa");
assert_eq!(groups[2]["value"], "b");
}
#[test]
fn datetime_test_formats_and_parses_utc_instants() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "datetime.mq.md")
.expect("datetime test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z");
assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z");
assert_eq!(items[2]["decimal"], "0");
assert_eq!(items[3]["decimal"], "1795248000123");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], false);
assert_eq!(items[6]["value"], "1969-12-31T23:59:59.999Z");
}
#[test]
fn clock_test_reports_project_mode_unix_millis() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "clock.mq.md")
.expect("clock test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], "Int");
assert_eq!(items[2]["value"], true);
}
#[test]
fn env_test_reads_only_granted_names() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "env.mq.md")
.expect("env test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "env-value");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "env.not_found");
}
#[test]
fn process_test_runs_an_explicitly_granted_program() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "process.mq.md")
.expect("process test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "0");
let expected = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.arg("--version")
fn a_missing_explicit_bundle_fails_closed_without_fallback() {
let missing = stdlib_support::repo_root()
.join("target")
.join("does-not-exist-stdlib");
let fixture = stdlib_support::repo_root().join("tests/product-stdlib/std-surface.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"run",
fixture.to_str().expect("utf-8 fixture path"),
"--output",
"json",
])
.env("MARQDO_STDLIB_DIR", &missing)
.current_dir(stdlib_support::repo_root())
.output()
.expect("run marqdo --version");
let expected_stdout = String::from_utf8_lossy(&expected.stdout);
assert_eq!(
items[2]["value"].as_str().expect("process stdout"),
expected_stdout.as_ref(),
"process stdout must match the granted program"
.expect("run marqdo");
assert_ne!(
output.status.code(),
Some(0),
"an invalid explicit MARQDO_STDLIB_DIR must fail even when a Bundle is installed"
);
assert_eq!(items[3]["value"], "");
}
#[test]
fn random_test_reads_bounded_entropy() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "random.mq.md")
.expect("random test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "16");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
}
#[test]
fn compress_test_round_trips_gzip_text() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "compress.mq.md")
.expect("compress test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "hello 世界");
}
#[test]
fn format_test_pins_value_semantics_and_handle_observation() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "format.mq.md")
.expect("format test"),
);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items[0]["decimal"], "3");
assert_eq!(items[1]["value"], "[\"文本\", 2, 1.5]");
assert_eq!(items[2]["value"], "{a: 1}");
assert_eq!(items[3]["value"], "[\"a\", 2]");
assert_eq!(items[4]["value"], "None");
}
#[test]
fn text_and_utf8_tests_agree_on_the_byte_encoding() {
let text = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "text.mq.md")
.expect("text test"),
);
let utf8 = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "utf8.mq.md")
.expect("utf8 test"),
);
assert_eq!(text["value"]["items"][0]["decimal"], "2");
assert_eq!(text["value"]["items"][1]["decimal"], "195");
assert_eq!(text["value"]["items"][2]["decimal"], "169");
assert_eq!(utf8["value"]["items"][0]["decimal"], "2");
assert_eq!(utf8["value"]["items"][1]["value"], "é");
assert_eq!(utf8["value"]["items"][2]["value"], false);
}
#[test]
fn stream_and_console_use_the_resource_endpoints() {
let stream = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "stream.mq.md")
.expect("stream test"),
);
assert_eq!(stream["value"]["items"][0]["value"], true);
assert_eq!(stream["value"]["items"][1]["decimal"], "7");
let console = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "console.mq.md")
.expect("console test"),
);
assert_eq!(console["value"]["items"][0]["value"], true);
assert_eq!(console["value"]["items"][1]["value"], "hello");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
console["trace"]
.as_array()
.unwrap()
.iter()
.any(|event| event["op"] == "resource.read" || event["op"] == "resource.open"),
"console test did not go through a resource endpoint"
stderr.contains("stdlib") || stderr.contains("cannot open"),
"failure must name the Bundle: {stderr}"
);
}
-72
View File
@@ -1,72 +0,0 @@
//! CM-A08 table stdlib module tests.
use std::path::Path;
use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn run_table_self_test() -> serde_json::Value {
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/table.mq.md", "--json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json output")
}
fn rows(value: &serde_json::Value) -> &Vec<serde_json::Value> {
value["rows"].as_array().expect("rows")
}
#[test]
fn stdlib_table_algorithms_rebuild_without_mutating_inputs() {
let report = run_table_self_test();
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(items.len(), 9);
assert_eq!(items[0]["header"], serde_json::json!(["分数"]));
assert_eq!(items[0]["rows"].as_array().unwrap().len(), 3);
assert_eq!(rows(&items[1]).len(), 2);
assert_eq!(rows(&items[2]).len(), 3);
assert_eq!(rows(&items[2])[0][1]["decimal"], "71");
assert_eq!(rows(&items[3]).len(), 4);
assert_eq!(rows(&items[3])[3][0]["value"], "丁");
assert_eq!(rows(&items[4])[0][1]["decimal"], "99");
assert_eq!(rows(&items[5]).len(), 2);
assert_eq!(items[5]["header"].as_array().unwrap().len(), 4);
assert_eq!(
items[6]["entries"]["a"]["items"].as_array().unwrap().len(),
2
);
assert_eq!(
items[6]["entries"]["b"]["items"].as_array().unwrap().len(),
1
);
// Original input is unchanged.
assert_eq!(rows(&items[7]).len(), 3);
assert_eq!(rows(&items[7])[0][1]["decimal"], "87");
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
+58
View File
@@ -0,0 +1,58 @@
//! Helpers for black-box tests that inspect values or committed program bytes.
use serde_json::Value;
pub fn terminal(snapshot: &Value) -> &Value {
assert_eq!(snapshot["schema"], "marqdo.observation");
let event = snapshot["events"].as_array().unwrap().last().unwrap();
assert!(matches!(
event["kind"].as_str(),
Some("run.completed" | "run.failed" | "run.rejected")
));
&event["payload"]
}
pub fn text(snapshot: &Value, channel: &str) -> String {
let bytes = snapshot["events"]
.as_array()
.unwrap()
.iter()
.filter(|event| event["kind"] == channel)
.flat_map(|event| {
let payload = &event["payload"];
let bytes = base64_decode(payload["data_base64"].as_str().unwrap());
assert_eq!(payload["byte_count"], bytes.len());
bytes
})
.collect();
String::from_utf8(bytes).unwrap()
}
fn base64_decode(text: &str) -> Vec<u8> {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::new();
let bytes: Vec<u8> = text
.bytes()
.filter(|byte| *byte != b'=')
.map(|byte| {
ALPHABET
.iter()
.position(|item| *item == byte)
.unwrap_or_else(|| panic!("invalid base64 byte {byte}")) as u8
})
.collect();
for chunk in bytes.chunks(4) {
let mut triple = 0u32;
for (index, byte) in chunk.iter().enumerate() {
triple |= u32::from(*byte) << (18 - 6 * index);
}
out.push((triple >> 16) as u8);
if chunk.len() > 2 {
out.push((triple >> 8) as u8);
}
if chunk.len() > 3 {
out.push(triple as u8);
}
}
out
}
+407
View File
@@ -0,0 +1,407 @@
//! Pinned stdlib Bundle resolver shared by test harnesses (ADR-0070).
//!
//! Product tests consume one explicit Bundle whose identity is pinned in
//! `tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest and
//! alias digest). `MARQDO_TEST_STDLIB_BUNDLE` may change the location, but the
//! Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` may change the pin
//! file. A bad explicit input fails even when the default location is valid —
//! there is no silent fallback.
use std::path::{Component, Path, PathBuf};
use sha2::{Digest, Sha256};
pub const BUNDLE_ENV: &str = "MARQDO_TEST_STDLIB_BUNDLE";
pub const PIN_ENV: &str = "MARQDO_TEST_BUNDLE_PIN";
/// The checkout root (this test support module lives in `crates/cli/tests`).
pub fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates directory")
.parent()
.expect("repository root")
.to_path_buf()
}
/// Pin file path, overridable for a candidate Bundle.
pub fn pin_path() -> PathBuf {
std::env::var_os(PIN_ENV)
.map(PathBuf::from)
.unwrap_or_else(|| {
repo_root()
.join("tools")
.join("stdlib")
.join("bundle-pin.json")
})
}
/// One pinned Bundle identity (`tools/stdlib/bundle-pin.json`).
#[derive(Debug, Clone)]
pub struct BundlePin {
pub name: String,
pub version: String,
pub source_commit: String,
/// None for the accepted ecosystem Bundle (Phase B): it is not vendored in
/// this repository, so product tests require an explicit verified Bundle.
pub source_path: Option<PathBuf>,
pub tree_digest: String,
pub aliases_digest: String,
}
impl BundlePin {
pub fn load(path: &Path) -> Self {
let text = std::fs::read_to_string(path)
.unwrap_or_else(|error| panic!("cannot read Bundle pin {}: {error}", path.display()));
let value: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("invalid Bundle pin {}: {error}", path.display()));
assert_eq!(
value.get("schema").and_then(serde_json::Value::as_str),
Some("marqdo.stdlib-bundle-pin"),
"{} must use the marqdo.stdlib-bundle-pin schema",
path.display()
);
assert_eq!(
value
.get("schema_version")
.and_then(serde_json::Value::as_u64),
Some(1),
"{} must use pin schema_version 1",
path.display()
);
let source = value
.get("source")
.unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display()));
let source_kind = source
.get("kind")
.and_then(serde_json::Value::as_str)
.unwrap_or("in-repo");
let source_path = match source_kind {
"in-repo" => {
let declared = source
.get("path")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| {
panic!("in-repo Bundle pin {} has no source.path", path.display())
});
validate_relative(declared).unwrap_or_else(|error| {
panic!("Bundle pin {} source.path: {error}", path.display())
});
Some(PathBuf::from(declared))
}
"ecosystem" => {
for field in ["repository", "commit"] {
required_str(source, field, path);
}
None
}
other => panic!(
"Bundle pin {} has unknown source.kind {other:?}",
path.display()
),
};
Self {
name: required_str(&value, "name", path),
version: required_str(&value, "version", path),
source_commit: required_str(source, "commit", path),
source_path,
tree_digest: required_str(&value, "tree_digest", path),
aliases_digest: required_str(&value, "aliases_digest", path),
}
}
/// The committed pin for the current checkout.
pub fn committed() -> Self {
Self::load(&pin_path())
}
}
fn required_str(value: &serde_json::Value, field: &str, path: &Path) -> String {
value
.get(field)
.and_then(serde_json::Value::as_str)
.filter(|text| !text.is_empty())
.unwrap_or_else(|| panic!("Bundle pin {} has no `{field}`", path.display()))
.to_string()
}
/// One verified Bundle on disk.
#[derive(Debug, Clone)]
pub struct Bundle {
root: PathBuf,
pub name: String,
pub version: String,
pub tree_digest: String,
pub aliases_digest: String,
}
impl Bundle {
/// Resolve the Bundle for a product test: explicit override or pinned path,
/// verified against the pin.
pub fn pinned() -> Self {
let pin = BundlePin::committed();
let explicit = std::env::var_os(BUNDLE_ENV).map(PathBuf::from);
let root = match (explicit.clone(), pin.source_path.as_ref()) {
(Some(path), _) => path,
(None, Some(relative)) => repo_root().join(relative),
(None, None) => panic!(
"the accepted stdlib Bundle is not vendored in this repository; set \
{BUNDLE_ENV} to a Bundle produced from the pinned ecosystem commit {} \
(tools/ci/fetch_ecosystem_bundle.py)",
pin.source_commit
),
};
let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit {
Some(_) => panic!(
"{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}",
root.display()
),
None => panic!(
"pinned stdlib Bundle at {} is invalid: {error}",
root.display()
),
});
let mismatches = [
("name", &pin.name, &bundle.name),
("version", &pin.version, &bundle.version),
("tree_digest", &pin.tree_digest, &bundle.tree_digest),
(
"aliases_digest",
&pin.aliases_digest,
&bundle.aliases_digest,
),
];
for (field, expected, actual) in mismatches {
assert_eq!(
expected,
actual,
"stdlib Bundle at {} does not match the pin field `{field}`",
root.display()
);
}
for required in ["stdlib.json", "io.mq.md", "io/console.mq.md"] {
assert!(
bundle.root.join(required).is_file(),
"stdlib Bundle at {} is missing required file {required}",
bundle.root.display()
);
}
assert_eq!(
pin.source_commit.len(),
40,
"the pin must record a full source commit, got {:?}",
pin.source_commit
);
bundle
}
/// Verify one unpacked Bundle root.
pub fn verify(root: &Path) -> Result<Self, String> {
if !root.is_dir() {
return Err(format!("not a directory: {}", root.display()));
}
let manifest_path = root.join("stdlib.json");
if !manifest_path.is_file() {
return Err(format!("missing manifest: {}", manifest_path.display()));
}
let text = std::fs::read_to_string(&manifest_path)
.map_err(|error| format!("cannot read {}: {error}", manifest_path.display()))?;
let manifest: serde_json::Value = serde_json::from_str(&text)
.map_err(|error| format!("invalid {}: {error}", manifest_path.display()))?;
let name = manifest
.get("name")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no name", manifest_path.display()))?
.to_string();
let version = manifest
.get("version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no version", manifest_path.display()))?
.to_string();
let declared = manifest
.get("digest")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no digest", manifest_path.display()))?
.to_string();
let actual = tree_digest(root)?;
if declared != actual {
return Err(format!(
"tree digest mismatch: stdlib.json declares {declared}, the files are {actual}"
));
}
let aliases = manifest
.get("public_aliases")
.and_then(serde_json::Value::as_array)
.cloned()
.unwrap_or_default();
let declared_aliases = manifest
.get("aliases_digest")
.and_then(serde_json::Value::as_str)
.map(ToString::to_string);
let actual_aliases = aliases_digest(&aliases);
match (declared_aliases, aliases.is_empty()) {
(Some(declared_aliases), _) => {
if declared_aliases != actual_aliases {
return Err(format!(
"alias digest mismatch: stdlib.json declares {declared_aliases}, \
the alias table is {actual_aliases}"
));
}
}
(None, false) => {
return Err(format!(
"{} declares public_aliases without aliases_digest",
manifest_path.display()
));
}
(None, true) => {}
}
Ok(Self {
root: root
.canonicalize()
.map_err(|error| format!("cannot canonicalize {}: {error}", root.display()))?,
name,
version,
tree_digest: actual,
aliases_digest: actual_aliases,
})
}
pub fn root(&self) -> &Path {
&self.root
}
}
/// Resolve and verify the pinned Bundle once per test process.
pub fn bundle() -> &'static Bundle {
static BUNDLE: std::sync::OnceLock<Bundle> = std::sync::OnceLock::new();
BUNDLE.get_or_init(Bundle::pinned)
}
/// Bundle root for fixtures and `MARQDO_STDLIB_DIR`.
pub fn bundle_dir() -> PathBuf {
bundle().root().to_path_buf()
}
/// Bundle root when one is configured, without failing tests that do not need
/// the standard library (Phase B has no in-repo source tree).
pub fn try_bundle_dir() -> Option<PathBuf> {
let pin = BundlePin::committed();
if let Some(explicit) = std::env::var_os(BUNDLE_ENV) {
return Some(PathBuf::from(explicit));
}
pin.source_path.map(|relative| repo_root().join(relative))
}
/// A real CLI command that names the verified Bundle explicitly when one is
/// configured; spawned programs never rely on a compile-time source fallback.
pub fn cli_command() -> std::process::Command {
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo"));
if let Some(root) = try_bundle_dir() {
command.env("MARQDO_STDLIB_DIR", root);
}
command
}
/// Content digest over all `.mq.md` files: sorted relative path, NUL, bytes, NUL.
pub fn tree_digest(root: &Path) -> Result<String, String> {
let mut files = Vec::new();
collect_markdown(root, root, &mut files)?;
files.sort();
let mut hasher = Sha256::new();
for (relative, path) in files {
let bytes = std::fs::read(&path)
.map_err(|error| format!("cannot read {}: {error}", path.display()))?;
hasher.update(relative.as_bytes());
hasher.update([0]);
hasher.update(&bytes);
hasher.update([0]);
}
Ok(format!("sha256:{}", hex(&hasher.finalize())))
}
/// Canonical digest over the official public-alias table.
pub fn aliases_digest(aliases: &[serde_json::Value]) -> String {
let mut entries: Vec<&serde_json::Value> = aliases.iter().collect();
entries.sort_by_key(|alias| {
(
alias["target_module"].as_str().unwrap_or("").to_string(),
alias["target_function"].as_str().unwrap_or("").to_string(),
)
});
let mut hasher = Sha256::new();
for alias in entries {
if let Some(module) = alias["target_module"].as_str() {
hasher.update(module.as_bytes());
}
hasher.update([0]);
if let Some(function) = alias["target_function"].as_str() {
hasher.update(function.as_bytes());
}
hasher.update([0]);
let mut names: Vec<&str> = alias["public_names"]
.as_array()
.map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
.unwrap_or_default();
names.sort();
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
}
format!("sha256:{}", hex(&hasher.finalize()))
}
fn collect_markdown(
root: &Path,
dir: &Path,
out: &mut Vec<(String, PathBuf)>,
) -> Result<(), String> {
let entries = std::fs::read_dir(dir)
.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
let path = entry.path();
if path.is_dir() {
collect_markdown(root, &path, out)?;
} else if path
.file_name()
.is_some_and(|name| name.to_string_lossy().ends_with(".mq.md"))
{
let relative = path
.strip_prefix(root)
.map_err(|_| "stdlib file escaped its root".to_string())?
.components()
.map(|component| component.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/");
out.push((relative, path));
}
}
Ok(())
}
fn validate_relative(path: &str) -> Result<(), String> {
let mut normalised = PathBuf::new();
for component in Path::new(path).components() {
match component {
Component::Normal(part) => normalised.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err("must be a relative path inside the repository".to_string())
}
}
}
if normalised.as_os_str().is_empty() {
return Err("must not be empty".to_string());
}
Ok(())
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
@@ -1,9 +1,13 @@
//! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint.
//! C10/P5: a `.mq.md` program round-trips bytes over the TCP resource endpoint.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::Command;
struct TempDir(std::path::PathBuf);
@@ -27,7 +31,11 @@ impl Drop for TempDir {
}
#[test]
fn mqmd_http_client_parses_a_response_from_a_tcp_stream() {
fn a_marqdo_program_round_trips_bytes_over_the_tcp_resource() {
// The CLI owns the TCP resource endpoint; the HTTP domain module now lives in
// the explicit `marqdo-ext-http` package, so this test exercises the generic
// endpoint directly instead of importing a domain module that is not part of
// the default Bundle.
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
@@ -36,17 +44,14 @@ fn mqmd_http_client_parses_a_response_from_a_tcp_stream() {
let count = stream.read(&mut request).unwrap();
assert!(String::from_utf8_lossy(&request[..count]).starts_with("GET / HTTP/1.1\r\n"));
stream
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello",
)
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")
.unwrap();
});
let dir = TempDir::new("client");
let dir = TempDir::new("roundtrip");
let program = format!(
r#"---
import:
http: "std:net/http"
编码: "std:text"
---
@@ -54,7 +59,7 @@ import:
`流 = resource.open("tcp", "{address}", ["read", "write"])`
`请求 = http.构建请求("GET", "/", [["Host", "example.test"]], "")`
`请求 = "GET / HTTP/1.1\r\nHost: example.test\r\n\r\n"`
`请求内存 = memory.new(1, 1)`
@@ -82,24 +87,20 @@ import:
`关闭 = resource.close(流)`
`响应 = http.解析响应(响应文本)`
`return [写入.ok, 读出.ok, 响应.状态, 响应.头["Content-Type"], 响应.体, 关闭.ok]`
`return [写入.ok, 写入.value.count == 请求长度, 读出.ok, 数量 > 0, 响应文本, 关闭.ok]`
"#
);
std::fs::write(dir.path().join("index.mq.md"), program).unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "index.mq.md", "--allow-net", "127.0.0.1", "--json"])
let output = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
"--allow-net",
"127.0.0.1",
"--output",
"json",
])
.current_dir(dir.path())
.env(
"MARQDO_STDLIB_DIR",
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.join("stdlib"),
)
.output()
.expect("run marqdo");
assert_eq!(
@@ -110,13 +111,18 @@ import:
String::from_utf8_lossy(&output.stdout)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["success"], true);
let items = report["value"]["items"].as_array().expect("list");
assert_eq!(report["run"]["status"], "ok");
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["decimal"], "200");
assert_eq!(items[3]["value"], "text/plain");
assert_eq!(items[4]["value"], "hello");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(
items[4]["value"],
"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"
);
assert_eq!(items[5]["value"], true);
server.join().unwrap();
}
+88 -115
View File
@@ -1,13 +1,17 @@
//! External CLI Tool Protocol v1 black-box tests (spec/tool-v1.md).
//! External CLI CLI Tool black-box tests (spec/cli-tool.md).
//!
//! The tool fixture is compiled with rustc from `tests/fixtures/tool_echo.rs`
//! rather than a shell script, so these tests run on Windows and macOS too.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::OnceLock;
use sha2::Digest;
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
@@ -34,12 +38,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(home: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.env("MARQDO_TOOL_HOME", home)
.output()
@@ -95,7 +95,7 @@ fn write_tool(dir: &Path, command: &str, _script: &str) -> PathBuf {
std::fs::write(
&manifest,
format!(
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0"}}}}"#
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","requires":{{"api_revision":1}}}}"#
),
)
.unwrap();
@@ -120,7 +120,7 @@ fn repo_root() -> PathBuf {
}
/// Compile one of the checked-in independent consumer samples and package it
/// as a Tool Protocol v1 bundle. Sources live in `examples/tool-samples/` so
/// as a CLI Tool bundle. Sources live in `examples/tool-samples/` so
/// they are reviewable software, not hidden test strings.
fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
let root = repo_root();
@@ -137,27 +137,25 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf {
.status()
.expect("run rustc for the sample tool");
assert!(status.success(), "rustc failed for {command}");
let entrypoint = format!("bin/{command}{}", std::env::consts::EXE_SUFFIX);
let manifest = package.join("tool.json");
std::fs::write(
&manifest,
format!(
r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0","analysis":[2],"trace":[2]}}}}"#
),
)
.unwrap();
let template = root.join(format!("examples/tool-samples/{command}/tool.json"));
let mut document: serde_json::Value =
serde_json::from_slice(&std::fs::read(template).unwrap()).unwrap();
document["entrypoint"] =
serde_json::json!(format!("bin/{command}{}", std::env::consts::EXE_SUFFIX));
std::fs::write(&manifest, document.to_string()).unwrap();
manifest
}
#[test]
fn independent_sample_tools_consume_public_analysis_and_trace() {
fn independent_sample_tools_consume_public_analysis_and_observation() {
let dir = TempDir::new("samples");
let home = dir.path().join("home");
let analysis = dir.path().join("analysis.json");
let trace = dir.path().join("trace.json");
let root = repo_root();
let check = Command::new(binary())
let check = stdlib_support::cli_command()
.args([
"check",
"examples/multi-module/index.mq.md",
@@ -169,8 +167,12 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
.output()
.expect("run check");
assert!(check.status.success(), "check failed: {}", stderr(&check));
let run = Command::new(binary())
.args(["run", "examples/multi-module/index.mq.md", "--trace-file"])
let run = stdlib_support::cli_command()
.args([
"run",
"examples/multi-module/index.mq.md",
"--observation-file",
])
.arg(&trace)
.current_dir(&root)
.output()
@@ -200,22 +202,22 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
assert_eq!(view.status.code(), Some(0), "{}", stderr(&view));
let text = stdout(&view);
assert!(
text.contains("sample-view schema=marqdo.analysis version=2"),
text.contains("sample-view schema=marqdo.analysis version=3"),
"{text}"
);
assert!(text.contains("modules="), "{text}");
let knowledge = cli(
&home,
&["sample-knowledge", "--trace", trace.to_str().unwrap()],
&["sample-knowledge", "--analysis", analysis.to_str().unwrap()],
);
assert_eq!(knowledge.status.code(), Some(0), "{}", stderr(&knowledge));
let text = stdout(&knowledge);
assert!(
text.contains("sample-knowledge schema=marqdo.trace version=2"),
text.contains("sample-knowledge schema=marqdo.analysis version=3"),
"{text}"
);
assert!(text.contains("status=ok"), "{text}");
assert!(text.contains("reference_sets="), "{text}");
let proof = cli(
&home,
@@ -223,14 +225,20 @@ fn independent_sample_tools_consume_public_analysis_and_trace() {
"sample-proof",
"--analysis",
analysis.to_str().unwrap(),
"--trace",
"--observation",
trace.to_str().unwrap(),
],
);
assert_eq!(proof.status.code(), Some(0), "{}", stderr(&proof));
let text = stdout(&proof);
assert!(text.contains("sample-proof bound=true"), "{text}");
assert!(text.contains("digest=sha256:"), "{text}");
let digest = format!(
"sha256:{:x}",
sha2::Sha256::digest(std::fs::read(&analysis).unwrap())
);
assert!(
text.contains(&format!("sample-proof claimed_digest={digest}")),
"{text}"
);
for command in ["sample-view", "sample-knowledge", "sample-proof"] {
let removed = cli(&home, &["tool", "remove", command]);
@@ -245,7 +253,7 @@ fn install_dispatch_list_remove_without_core_knowledge_of_the_name() {
let manifest = write_tool(
dir.path(),
"benchmark",
"#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_TOOL_PROTOCOL\"\nexit 7\n",
"#!/bin/sh\nfor a in \"$@\"; do printf 'arg=%s\\n' \"$a\"; done\nprintf 'protocol=%s\\n' \"$MARQDO_API_REVISION\"\nexit 7\n",
);
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
@@ -301,7 +309,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
let incompatible = std::fs::read_to_string(&manifest)
.unwrap()
.replace(">=3.0.0-beta.1,<4.0.0", ">=99.0");
.replace("\"api_revision\":1", "\"api_revision\":99");
let incompatible_manifest = dir.path().join("incompatible.json");
std::fs::write(&incompatible_manifest, incompatible).unwrap();
let output = cli(
@@ -309,7 +317,7 @@ fn invalid_manifests_and_path_escapes_are_rejected() {
&["tool", "install", incompatible_manifest.to_str().unwrap()],
);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("requires marqdo"));
assert!(stderr(&output).contains("requires api_revision"));
}
#[test]
@@ -344,7 +352,7 @@ fn tampered_binary_and_path_hijack_are_not_executed() {
permissions.set_mode(0o755);
std::fs::set_permissions(&hijack, permissions).unwrap();
}
let output = Command::new(binary())
let output = stdlib_support::cli_command()
.arg("hijack")
.env("MARQDO_TOOL_HOME", &home)
.env("PATH", &path_dir)
@@ -355,58 +363,61 @@ fn tampered_binary_and_path_hijack_are_not_executed() {
}
#[test]
fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
fn tool_requires_exact_current_protocols_and_rejects_retired_registrations() {
use serde_json::json;
let dir = TempDir::new("protocols");
let home = dir.path().join("home");
let manifest = write_tool(
dir.path(),
"proto",
"#!/bin/sh\nprintf 'analysis=%s\\ntrace=%s\\n' \"$MARQDO_PROTOCOL_ANALYSIS\" \"$MARQDO_PROTOCOL_TRACE\"\n",
);
let text = std::fs::read_to_string(&manifest).unwrap().replace(
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"",
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",\"analysis\":[2],\"trace\":[2]",
);
std::fs::write(&manifest, text).unwrap();
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let output = cli(&home, &["proto"]);
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output));
let text = stdout(&output);
assert!(text.contains("analysis=2"), "{text}");
assert!(text.contains("trace=2"), "{text}");
let manifest = write_tool(dir.path(), "proto-v3", "");
let mut declared: serde_json::Value =
let manifest = write_tool(dir.path(), "proto", "");
let mut document: serde_json::Value =
serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
declared["compatibility"]["analysis"] = serde_json::json!([2, 3]);
std::fs::write(&manifest, declared.to_string()).unwrap();
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let output = cli(&home, &["proto-v3"]);
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output));
assert!(stdout(&output).contains("analysis=3"));
for (compat, tag) in [
("\"analysis\":[99]", "analysis-disjoint"),
("\"analysis\":[]", "analysis-empty"),
("\"trace\":[9]", "trace-disjoint"),
for (requires, expected) in [
(
json!({"api_revision": 1, "analysis": [3]}),
"invalid tool.json",
),
(
json!({"api_revision": 1, "analysis": null}),
"invalid tool.json",
),
(
json!({"api_revision": 1, "analysis": 2}),
"tool.protocol_incompatible",
),
(
json!({"api_revision": 1, "observation": 99}),
"tool.protocol_incompatible",
),
] {
let command = format!("bad-{tag}");
let manifest = write_tool(dir.path(), &command, "#!/bin/sh\nexit 0\n");
let text = std::fs::read_to_string(&manifest).unwrap().replace(
"\"marqdo\":\">=3.0.0-beta.1,<4.0.0\"",
&format!("\"marqdo\":\">=3.0.0-beta.1,<4.0.0\",{compat}"),
);
std::fs::write(&manifest, text).unwrap();
document["requires"] = requires;
std::fs::write(&manifest, document.to_string()).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1), "{tag}");
assert!(
stderr(&output).contains("protocol_incompatible"),
"{tag}: {}",
stderr(&output)
);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains(expected), "{}", stderr(&output));
}
document.as_object_mut().unwrap().remove("requires");
document["compatibility"] = json!({"analysis": [2, 3]});
std::fs::write(&manifest, document.to_string()).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("invalid tool.json"));
document.as_object_mut().unwrap().remove("compatibility");
document["requires"] = json!({"api_revision": 1, "analysis": 3, "observation": 1});
std::fs::write(&manifest, document.to_string()).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(cli(&home, &["proto"]).status.code(), Some(7));
let record = home.join("proto/record.json");
let mut installed: serde_json::Value =
serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
installed.as_object_mut().unwrap().remove("requires");
installed["compatibility"] = json!({"analysis": [2, 3]});
std::fs::write(&record, installed.to_string()).unwrap();
let output = cli(&home, &["proto"]);
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("Remove and reinstall"));
assert!(cli(&home, &["tool", "remove", "proto"]).status.success());
}
#[test]
@@ -460,41 +471,3 @@ fn a_root_record_json_in_the_source_package_is_rejected() {
assert_eq!(output.status.code(), Some(1));
assert!(stderr(&output).contains("must not contain a root record.json"));
}
#[test]
fn prerelease_core_requires_an_explicit_prerelease_compatible_range() {
let dir = TempDir::new("prerelease-range");
let home = dir.path().join("home");
let core = env!("CARGO_PKG_VERSION");
for (range, compatible) in [
(">=3.0.0-beta.1,<4.0.0".to_string(), true),
(format!("={core}"), true),
(">=3.0.0,<4.0.0".to_string(), !core.contains('-')),
(">=0.1,<1".to_string(), false),
] {
let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n");
let text = std::fs::read_to_string(&manifest)
.unwrap()
.replace(">=3.0.0-beta.1,<4.0.0", &range);
std::fs::write(&manifest, text).unwrap();
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(
output.status.success(),
compatible,
"{range} on {core}: {}",
stderr(&output)
);
if compatible {
assert!(cli(&home, &["tool", "remove", "prerelease"])
.status
.success());
} else {
assert!(
stderr(&output).contains("requires marqdo"),
"{}",
stderr(&output)
);
}
}
}
+250 -15
View File
@@ -39,6 +39,16 @@ pub struct HeadingInfo {
pub kind: UnitKind,
/// Semantic mode declared or inherited by this heading.
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.
@@ -95,6 +105,38 @@ impl UnitIndex {
.iter()
.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 {
@@ -116,6 +158,28 @@ pub enum SemanticMode {
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(
node: &MdNode,
) -> (Option<SemanticMode>, Option<String>, Option<Diagnostic>) {
@@ -184,20 +248,22 @@ fn heading_declaration(
/// Build the heading/function index for a parsed document.
pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let mut index = UnitIndex::default();
let root_id = UnitId {
module: module.clone(),
path: Vec::new(),
};
index.units.push(UnitInfo {
id: UnitId {
module: module.clone(),
path: Vec::new(),
},
id: root_id.clone(),
level: 0,
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,
function: None,
});
// Stack of (level, path, mode) for ancestors.
let mut stack: Vec<(u8, Vec<String>, SemanticMode)> = Vec::new();
// Stack of (level, path, mode, mode_source_unit_id) for ancestors.
let mut stack: Vec<(u8, Vec<String>, SemanticMode, UnitId)> = Vec::new();
let mut seen: BTreeMap<(Vec<String>, String), Span> = BTreeMap::new();
let mut current_namespace: Option<String> = None;
let mut current_function: Option<FunctionId> = None;
@@ -224,7 +290,7 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
// Resolve the ancestor scope before deriving the mode: remove every
// same-or-higher-level heading first so a heading can only inherit from
// its nearest *ancestor*, never from the previous sibling.
while let Some((parent_level, _, _)) = stack.last() {
while let Some((parent_level, _, _, _)) = stack.last() {
if *parent_level >= level {
stack.pop();
} else {
@@ -233,8 +299,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
}
let inherited = stack
.last()
.map(|(_, _, mode)| *mode)
.map(|(_, _, mode, _)| *mode)
.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 raw_name = match declared_name {
Some(name) => name,
@@ -254,13 +324,25 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
let parent_path = stack
.last()
.map(|(_, path, _)| path.clone())
.map(|(_, path, _, _)| path.clone())
.unwrap_or_default();
let parent_id = UnitId {
module: module.clone(),
path: parent_path.clone(),
};
let path = {
let mut path = parent_path.clone();
path.push(name.clone());
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());
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}"),
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 {
module: module.clone(),
name: qualified,
@@ -327,10 +430,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
path: path.clone(),
kind,
mode,
};
let unit_id = UnitId {
module: module.clone(),
path,
mode_origin,
mode_source_unit_id,
parent_id,
// 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 {
id: unit_id,
@@ -361,7 +466,26 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
}
}
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.
@@ -624,6 +748,117 @@ mod tests {
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]
fn knowledge_scope_payloads_and_sections_stay_inert() {
let index = index_of(
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "marqdo-host-contract"
description = "Platform-neutral Host contract: the only side-effect boundary the runtime may know"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
[dependencies]
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
File renamed without changes.
+194
View File
@@ -0,0 +1,194 @@
//! The host boundary used by the interpreter and future frontends.
//!
//! The trait is implemented by the native CLI host, by the independent
//! embedding/test host and by any future host. Implementations own effects,
//! grants and budgets; the runtime only requests operations through this
//! interface and never performs external I/O itself.
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use crate::context::ExecutionContext;
use crate::observe::{FrameId, RuntimeObservation};
use crate::resource::ResourceRead;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Platform-neutral Host contract.
//!
//! This crate owns the only side-effect interface the language engine knows:
//! the [`Host`] trait, its [`HostOp`] surface, the per-call
//! [`ExecutionContext`], the opaque resource read result and the runtime
//! observation notifications. It is a Rust compile-time interface inside one
//! codebase, not a wire protocol: there is no HTTP, RPC, C ABI or dynamic
//! loading boundary here.
//!
//! The crate is deliberately neutral. It depends only on the language value
//! and span types; it must never link the native host, the CLI, the sandbox,
//! foreign kernels, the plugin loader or a project filesystem. Native and
//! embedded hosts implement [`Host`] without re-implementing any language
//! semantics. Authorization, budgets, resource identity and OS isolation stay
//! owned by the trusted host implementation that consumes this contract.
pub mod context;
pub mod host;
pub mod observe;
pub mod resource;
pub use context::ExecutionContext;
pub use host::{Host, HostOp};
pub use observe::{FrameId, LoopTransfer, ParameterSource, RuntimeObservation};
pub use resource::ResourceRead;
+118
View File
@@ -0,0 +1,118 @@
//! Runtime observation facts shared by the interpreter and the host contract.
//!
//! Only the types the interpreter itself produces and hands to [`crate::Host`]
//! live here. The host implementation keeps the concrete sink, redaction,
//! encoding and budget state; the public Observation protocol remains the
//! CLI's single producer. This module must not grow a second event vocabulary.
use marqdo_span::Span;
use marqdo_value::Value;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Observation.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Value and control observations carry the owning call frame.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A local memory operation committed.
Effect {
operation: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
@@ -0,0 +1,10 @@
//! Values crossing the resource stream methods of [`crate::Host`].
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
+5
View File
@@ -12,7 +12,9 @@ authors.workspace = true
libloading = { workspace = true }
rustls = { workspace = true }
rustls-native-certs = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-plugin-abi = { workspace = true }
marqdo-worker-ipc = { workspace = true }
flate2 = { workspace = true }
getrandom = { workspace = true }
regex = { workspace = true }
@@ -22,6 +24,9 @@ marqdo-value = { workspace = true }
marqdo-foreign = { workspace = true }
marqdo-sandbox = { workspace = true }
serde = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
serde_yaml = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+36 -343
View File
@@ -7,239 +7,40 @@
use std::collections::{BTreeMap, BTreeSet};
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::time::Duration;
use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
use crate::plugin::{
CapabilityHandler, HostTarget, LoadOptions, LoadedPlugin, PluginKind, PluginManifest,
};
use marqdo_host_contract::{
ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
};
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, PluginError};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use rustls::pki_types::CertificateDer;
use crate::budget::Budget;
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
use crate::context::ExecutionContext;
use crate::fs::ProjectFs;
use crate::handles::{contains_plugin_handle, PluginHandleTable};
use crate::observe::{
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservationState, RuntimeObservation,
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, ObservationState,
};
use crate::plugin_worker::WorkerPlugin;
use crate::provider_c::{load_package, CResourceProvider};
use crate::provider_worker::WorkerResourceProvider;
use crate::resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
};
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
mod dispatch;
mod effects;
mod providers;
mod resource_ops;
mod resource_requests;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Recorded effects.
fn trace(&self) -> &[TraceEntry];
/// Record one semantic event (Trace v1). Default: ignored.
fn record_semantic(
&mut self,
_kind: &str,
_function_id: Option<&str>,
_module_id: Option<&str>,
_span: Option<Span>,
_detail: Option<&str>,
) {
}
/// Recorded semantic events. Default: empty.
fn semantic_events(&self) -> &[SemanticEvent] {
&[]
}
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when the run has no `--event-stream`.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
/// Default capability host implementation.
pub struct StdHost {
/// Requested sandbox mode.
@@ -252,8 +53,6 @@ pub struct StdHost {
pub budget: Budget,
/// Filesystem view.
pub fs: ProjectFs,
/// Effect trace.
pub trace: EffectTrace,
/// Maximum wall-clock time for one foreign kernel call.
pub foreign_timeout: Duration,
/// Maximum captured bytes per foreign stream.
@@ -280,9 +79,6 @@ pub struct StdHost {
resources: ResourceTable,
/// Registered in-process providers keyed by resource kind (ADR-0033).
resource_providers: BTreeMap<String, (String, SharedResourceProvider)>,
semantic_events: Vec<SemanticEvent>,
next_event_seq: u64,
trace_state: TraceState,
observation: Option<ObservationState>,
observation_error: Option<String>,
}
@@ -331,7 +127,6 @@ impl StdHost {
capabilities,
budget: Budget::default(),
fs: ProjectFs::new(project_root),
trace: EffectTrace::default(),
foreign_timeout: Duration::from_secs(10),
foreign_output_limit: 1024 * 1024,
kernel_registry: marqdo_foreign::KernelRegistry::builtin(),
@@ -346,9 +141,6 @@ impl StdHost {
stderr: Vec::new(),
resources: ResourceTable::new(),
resource_providers: BTreeMap::new(),
semantic_events: Vec::new(),
next_event_seq: 0,
trace_state: TraceState::default(),
observation: None,
observation_error: None,
}
@@ -402,7 +194,7 @@ impl StdHost {
exports.insert(export.name.clone(), export.signature.clone());
}
let artifact = manifest
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current())
.resolve_artifact(&HostTarget::current())
.map_err(map_plugin_error)?;
let manifest_digest = artifact.sha256.clone();
let transport = match manifest.plugin.kind {
@@ -428,8 +220,8 @@ impl StdHost {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let options = marqdo_plugin_abi::LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(),
let options = LoadOptions {
host_target: HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| {
broker.execute(&package, capability, request)
})),
@@ -449,10 +241,9 @@ impl StdHost {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let handler: marqdo_plugin_abi::CapabilityHandler =
Box::new(move |capability, request| {
broker.execute(&package, capability, request)
});
let handler: CapabilityHandler = Box::new(move |capability, request| {
broker.execute(&package, capability, request)
});
PluginTransport::Worker(
WorkerPlugin::spawn(manifest, base_dir, Some(handler))
.map_err(map_plugin_error)?,
@@ -502,22 +293,6 @@ impl StdHost {
exports
}
/// Recorded semantic events (Trace v1).
pub fn semantic_events(&self) -> &[SemanticEvent] {
&self.semantic_events
}
/// Trace capacity state for the writer.
pub fn trace_state(&self) -> &TraceState {
&self.trace_state
}
/// Override the trace event/byte budget.
pub fn with_trace_budget(mut self, budget: TraceBudget) -> Self {
self.trace_state.budget = budget;
self
}
/// Audited plugin capability decisions.
pub fn capability_audit(&self) -> Vec<CapabilityAudit> {
self.broker_audit
@@ -536,13 +311,6 @@ impl StdHost {
})
}
/// Enable effect tracing.
pub fn with_trace(mut self) -> Self {
self.trace = EffectTrace::enabled();
self.trace_state.enabled = true;
self
}
/// Install the typed observation sink and policy (RFC-OBS-0001).
///
/// Without this call the host has no observation state: it does not
@@ -617,8 +385,13 @@ impl StdHost {
result_code: &str,
ctx: &ExecutionContext,
) {
let frame_id = self
.observation
.as_ref()
.and_then(ObservationState::parent_frame);
let result = self.emit_observation(
ObservationEvent::Effect {
frame_id,
operation,
result_code,
module_id: &ctx.module_id,
@@ -777,26 +550,8 @@ impl Host for StdHost {
max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
let started = Instant::now();
let kind = self.resources.kind(handle, ctx.span)?;
let read = self.resources.read(handle, max_bytes, ctx.span)?;
self.record_semantic(
"resource.read",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!(
"kind={kind} count={} eof={}",
read.bytes.len(),
read.eof
)),
);
self.record_resource_effect(
"resource.read",
ctx,
started,
&format!("kind={kind} count={}", read.bytes.len()),
);
self.observe_effect("resource.read", "ok", ctx);
Ok(read)
}
@@ -806,7 +561,6 @@ impl Host for StdHost {
bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
let started = Instant::now();
let kind = self.resources.kind(handle, ctx.span)?;
let stdio = self.resources.stdio_name(handle, ctx.span)?;
let count = self.resources.write(handle, bytes, ctx.span)?;
@@ -829,19 +583,7 @@ impl Host for StdHost {
self.emit_observation(event, true)?;
}
}
self.record_semantic(
"resource.write",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={kind} count={count}")),
);
self.record_resource_effect(
"resource.write",
ctx,
started,
&format!("kind={kind} count={count}"),
);
self.observe_effect("resource.write", "ok", ctx);
Ok(count)
}
@@ -850,29 +592,11 @@ impl Host for StdHost {
handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
let started = Instant::now();
let pending = self.resources.pending_file_write(handle, ctx.span)?;
let count = match pending {
Some((relative, bytes)) => {
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
bytes.len()
}
None => 0,
};
if let Some((relative, bytes)) = self.resources.pending_file_write(handle, ctx.span)? {
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
}
self.resources.close(handle, ctx.span)?;
self.record_semantic(
"resource.close",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("flushed_bytes={count}")),
);
self.record_resource_effect(
"resource.close",
ctx,
started,
&format!("flushed_bytes={count}"),
);
self.observe_effect("resource.close", "ok", ctx);
Ok(())
}
@@ -881,16 +605,8 @@ impl Host for StdHost {
handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
let accepted = self.resources.accept(handle, ctx.span)?;
self.record_semantic(
"resource.accept",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=tcp-listener"),
);
self.record_resource_effect("resource.accept", ctx, started, "ok");
self.observe_effect("resource.accept", "ok", ctx);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::Resource(accepted));
@@ -990,6 +706,14 @@ impl Host for StdHost {
return Ok(());
}
match event {
RuntimeObservation::Effect {
operation,
module_id,
span,
} => {
self.observe_effect(operation, "ok", &ExecutionContext::new(module_id, span));
Ok(())
}
RuntimeObservation::Return {
frame_id,
value_type,
@@ -1130,37 +854,6 @@ impl Host for StdHost {
fn take_output(&mut self) -> Vec<u8> {
std::mem::take(&mut self.output)
}
fn trace(&self) -> &[TraceEntry] {
self.trace.entries()
}
fn record_semantic(
&mut self,
kind: &str,
function_id: Option<&str>,
module_id: Option<&str>,
span: Option<Span>,
detail: Option<&str>,
) {
let estimate = TraceState::estimate(kind, function_id, module_id, detail, None);
if !self.trace_state.accept(estimate) {
return;
}
let seq = self.next_seq();
self.semantic_events.push(SemanticEvent {
seq,
kind: kind.to_string(),
function_id: function_id.map(str::to_string),
module_id: module_id.map(str::to_string),
span,
detail: detail.map(str::to_string),
});
}
fn semantic_events(&self) -> &[SemanticEvent] {
&self.semantic_events
}
}
fn map_plugin_error(error: PluginError) -> RuntimeError {
+5 -23
View File
@@ -1,7 +1,7 @@
//! `Host::invoke` dispatch table.
//!
//! Child module of `host`: it may call the parent's private capability,
//! resource and trace helpers. `StdHost` remains the only host implementation.
//! resource and observation helpers. `StdHost` remains the only host implementation.
use super::*;
@@ -36,30 +36,12 @@ pub(crate) fn invoke(
),
));
}
let started = Instant::now();
let result = host.dispatch(op, args, ctx);
let summary = match &result {
Ok(_) => "ok".to_string(),
Err(error) => error.code().to_string(),
let result_code = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let estimate = TraceState::estimate(
"effect",
None,
Some(&ctx.module_id),
Some(&summary),
Some(op.name()),
);
if host.trace_state.accept(estimate) {
let seq = host.next_seq();
host.trace.record(
seq,
op.name(),
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary,
);
}
host.observe_effect(op.name(), result_code, ctx);
result
}
-44
View File
@@ -1,44 +0,0 @@
//! Trace/effect bookkeeping helpers for `StdHost`.
//!
//! Child module of `host`; it may use the parent's private trace state.
use super::*;
impl StdHost {
pub(crate) fn next_seq(&mut self) -> u64 {
let seq = self.next_event_seq;
self.next_event_seq += 1;
seq
}
pub(crate) fn record_resource_effect(
&mut self,
op: &str,
ctx: &ExecutionContext,
started: Instant,
summary: &str,
) {
let estimate = TraceState::estimate(
"effect",
None,
Some(&ctx.module_id),
Some(summary),
Some(op),
);
if !self.trace_state.accept(estimate) {
return;
}
let seq = self.next_seq();
self.trace.record(
seq,
op,
ctx.module_id.clone(),
ctx.span,
started.elapsed(),
summary.to_string(),
);
// Executed regardless of Trace v2 being enabled: the two writers are
// independent observation outputs (RFC-OBS-0001 §4.6).
self.observe_effect(op, summary, ctx);
}
}
+8 -65
View File
@@ -38,7 +38,6 @@ impl StdHost {
rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
if self.mode == SandboxMode::Strict {
// stdio/stdout is the existing console channel already permitted by
@@ -89,14 +88,7 @@ impl StdHost {
"stdout" => self.resources.open_stdout(),
_ => unreachable!(),
};
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=stdio descriptor={descriptor}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
"file" => {
@@ -105,28 +97,14 @@ impl StdHost {
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let bytes = self.fs.read_bytes(descriptor, ctx.span)?;
let handle = self.resources.open_file(relative, bytes);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=read"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
return Ok(Value::Resource(handle));
}
if requested == BTreeSet::from(["write"]) {
self.capabilities.check_write(descriptor, ctx.span)?;
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
let handle = self.resources.open_file_writer(relative);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some("kind=file rights=write"),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
return Ok(Value::Resource(handle));
}
Err(RuntimeError::new(
@@ -184,14 +162,7 @@ impl StdHost {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_tcp(stream);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
"tls" => {
@@ -284,14 +255,7 @@ impl StdHost {
})?;
let stream = rustls::StreamOwned::new(connection, tcp);
let handle = self.resources.open_tls(stream);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tls host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
"tcp-listener" => {
@@ -348,14 +312,7 @@ impl StdHost {
)
})?;
let handle = self.resources.open_tcp_listener(listener);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=tcp-listener host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
"udp" => {
@@ -416,14 +373,7 @@ impl StdHost {
let _ = socket.set_read_timeout(Some(Duration::from_secs(5)));
let _ = socket.set_write_timeout(Some(Duration::from_secs(5)));
let handle = self.resources.open_udp(socket);
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind=udp host={host} port={port}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
other => {
@@ -447,14 +397,7 @@ impl StdHost {
let handle = self
.resources
.open_provider(provider, other, descriptor, rights, ctx.span)?;
self.record_semantic(
"resource.open",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("kind={other} provider={provider_name}")),
);
self.record_resource_effect("resource.open", ctx, started, "ok");
self.observe_effect("resource.open", "ok", ctx);
Ok(Value::Resource(handle))
}
}
@@ -2,9 +2,9 @@
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use std::time::{SystemTime, UNIX_EPOCH};
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value};
use super::{ErrorCategory, ExecutionContext, RuntimeError, SandboxMode, StdHost, Value};
impl StdHost {
pub(super) fn request_compatibility_operation(
@@ -13,7 +13,6 @@ impl StdHost {
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
@@ -72,14 +71,7 @@ impl StdHost {
self.capabilities.check_process(&program, ctx.span)?;
let result =
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
self.observe_effect("process.run", "ok", ctx);
Ok(result)
}
"regex.match" | "regex.captures" => {
@@ -116,14 +108,7 @@ impl StdHost {
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
self.observe_effect(operation, "ok", ctx);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" {
@@ -192,14 +177,7 @@ impl StdHost {
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
self.observe_effect("compress.gzip", "ok", ctx);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
@@ -274,14 +252,7 @@ impl StdHost {
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
self.observe_effect("compress.gunzip", "ok", ctx);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text));
@@ -326,14 +297,7 @@ impl StdHost {
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
self.observe_effect("random.bytes", "ok", ctx);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
@@ -385,14 +349,7 @@ impl StdHost {
);
}
}
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
self.observe_effect("env.get", "ok", ctx);
Ok(Value::Map(map))
}
"clock.now" => {
@@ -420,14 +377,7 @@ impl StdHost {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis));
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
self.observe_effect("clock.now", "ok", ctx);
Ok(Value::Map(map))
}
"fs.read_at" => {
@@ -470,14 +420,7 @@ impl StdHost {
let result = self
.fs
.request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
self.observe_effect("fs.read_at", "ok", ctx);
Ok(result)
}
"fs.append" => {
@@ -507,14 +450,7 @@ impl StdHost {
};
self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
self.observe_effect("fs.append", "ok", ctx);
Ok(result)
}
"fs.walk" => {
@@ -537,14 +473,7 @@ impl StdHost {
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
self.observe_effect("fs.walk", "ok", ctx);
Ok(result)
}
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
@@ -587,19 +516,7 @@ impl StdHost {
_ => unreachable!(),
}
let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect(
"resource.request",
ctx,
started,
&format!("fs.{name}"),
);
self.observe_effect(&format!("fs.{name}"), "ok", ctx);
Ok(result)
}
_ => {
+2 -2
View File
@@ -11,8 +11,8 @@ use std::time::Duration;
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext;
use crate::host::{HostOp, StdHost};
use crate::host::StdHost;
use marqdo_host_contract::{ExecutionContext, HostOp};
pub(crate) fn foreign(
host: &mut StdHost,
+21 -14
View File
@@ -1,42 +1,49 @@
//! CapabilityHost: capability checks, resource budgets, effect tracing and the
//! only bridge to math, foreign kernels, files and plugins.
//! Native Host: the one concrete implementation of the neutral
//! [`marqdo_host_contract::Host`] boundary.
//!
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks
//! happen at the point of execution, and host failures are structured errors.
//! Every side effect goes through this crate, checks happen at the point of
//! execution, and host failures are structured errors. The crate owns the OS
//! adapters, capability grants, resource handles, observation sink and trusted
//! extension execution; it never owns language semantics and never depends back
//! on the runtime, frontend or IR.
//!
//! Responsibility map (ADR-0071):
//! - [`capability`]/[`budget`]: grants, broker, audit, fuel/stack/deadline/output;
//! - [`resource`], [`fs`], `process`: resource kinds, handles and OS effects;
//! - [`plugin`], `plugin_worker`, `provider_c`, `provider_worker`, [`kernels`]:
//! trusted plugin/provider/foreign execution (no second static binder);
//! - [`observe`]: the runtime observation sink, redaction, budget and encoding;
//! - [`host`]: `StdHost` assembly and the single dispatch table.
pub mod budget;
pub mod capability;
pub mod context;
pub mod fs;
pub mod handles;
pub mod host;
pub mod kernels;
pub mod observe;
pub mod plugin;
mod plugin_worker;
mod process;
mod provider_c;
mod provider_worker;
pub mod resource;
pub mod trace;
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
pub use capability::{
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
};
pub use context::ExecutionContext;
pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use host::{arity, expect_text, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use observe::{
encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, ObservedValue, ValueState, DEFAULT_MAX_OBSERVATION_BYTES,
DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
};
pub use resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
CORE_RESOURCE_KINDS,
};
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
+3 -105
View File
@@ -4,7 +4,7 @@
//! interpreter and host emit at real commit points, the optional sink the CLI
//! installs, the run-scoped frame identity and the bounded observation budget.
//! It does **not** know JSONL, HTTP, SSE, View, agents or the public envelope;
//! the CLI composes the public Execution Events v1 protocol from these events.
//! the CLI composes the public Observation protocol from these events.
//!
//! Defaults are deliberately inert: no sink means no allocation and no
//! serialization. The facade never exposes `Frame.locals`, the whole
@@ -12,6 +12,7 @@
use std::collections::BTreeSet;
use marqdo_host_contract::{FrameId, LoopTransfer, ParameterSource};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value};
@@ -24,38 +25,6 @@ pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
/// Maximum committed stdio bytes carried by one chunk event.
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// Observation policy for one run.
///
/// `structural` always implies frame identity; value events only exist for
@@ -202,6 +171,7 @@ pub enum ObservationEvent<'a> {
},
/// The host completed a controlled effect attempt.
Effect {
frame_id: Option<FrameId>,
operation: &'a str,
result_code: &'a str,
module_id: &'a str,
@@ -237,78 +207,6 @@ pub enum ObservationEvent<'a> {
},
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Trace and Execution Events.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Every variant carries an `Option<FrameId>`; observation of values and
/// structural events only happens while a frame identity exists.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
/// Sink installed by the composition root (the CLI JSONL writer in product
/// builds, an in-memory recorder in tests).
pub trait ObservationSink {
@@ -11,7 +11,7 @@ use std::path::Path;
use sha2::{Digest, Sha256};
use crate::error::PluginError;
use marqdo_plugin_abi::PluginError;
/// Length of a lowercase hexadecimal sha256 digest.
pub const SHA256_HEX_LEN: usize = 64;
@@ -16,16 +16,16 @@ use std::ptr;
use libloading::{Library, Symbol};
use serde::Deserialize;
use crate::abi::{
use super::artifact::HostTarget;
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::abi::{
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use crate::artifact::HostTarget;
use crate::error::PluginError;
use crate::manifest::{PluginKind, PluginManifest};
use crate::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// A callback the host installs to answer capability requests from a plugin.
///
@@ -304,13 +304,13 @@ impl LoadedPlugin {
/// This is primarily for ABI conformance tests; prefer
/// [`LoadedPlugin::invoke`] for normal use.
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
if args_wire.len() > crate::abi::MAX_REQUEST_WIRE_BYTES {
if args_wire.len() > marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES {
return Err(PluginError::wire(
"request_too_large",
format!(
"request wire is {} bytes, limit is {}",
args_wire.len(),
crate::abi::MAX_REQUEST_WIRE_BYTES
marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES
),
));
}
@@ -10,12 +10,12 @@ use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::abi::{
use super::artifact::{is_valid_sha256_hex, TargetTriple};
use super::artifact::{verify_sha256_file, HostTarget};
use marqdo_plugin_abi::abi::{
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use crate::artifact::{is_valid_sha256_hex, TargetTriple};
use crate::artifact::{verify_sha256_file, HostTarget};
use crate::error::PluginError;
use marqdo_plugin_abi::PluginError;
/// Maximum number of exports a single plugin may register.
pub const MAX_EXPORTS: usize = 256;
@@ -648,7 +648,7 @@ plugin:
#[test]
fn malformed_yaml_is_rejected() {
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
assert_eq!(error.kind, crate::error::ErrorKind::Manifest);
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Manifest);
assert_eq!(error.code, "manifest_parse_failed");
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
}
@@ -683,7 +683,7 @@ plugin:
),
Err(error) => assert_eq!(
error.kind,
crate::error::ErrorKind::Manifest,
marqdo_plugin_abi::ErrorKind::Manifest,
"`{field}` = `{value}` should fail manifest handling"
),
}
+26
View File
@@ -0,0 +1,26 @@
//! Execution side of the Callable Plugin ABI: manifest/artifact validation,
//! native loading, invocation dispatch and the worker process.
//!
//! The public contract (C layout, wire envelope and protocol errors) lives in
//! `marqdo-plugin-abi`; this module owns `dlopen`, process spawning, artifact
//! file selection and trusted invocation. The CLI may consume the static
//! descriptor types for `check`/`inspect` preparation, but preparation never
//! loads a library or starts a process.
//!
//! The `include/marqdo_plugin_abi_v1.h` header and the Rust layout assertions
//! in `marqdo_plugin_abi::abi` remain the single ABI authority.
pub mod artifact;
pub mod loader;
pub mod manifest;
pub mod worker;
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
@@ -13,10 +13,10 @@ use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
use crate::error::PluginError;
use crate::loader::{LoadOptions, LoadedPlugin};
use crate::manifest::{PluginKind, PluginManifest};
use crate::wire::{WireRequest, WireResponse};
use super::loader::{LoadOptions, LoadedPlugin};
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// Hidden CLI command name used to start a worker.
pub const WORKER_COMMAND: &str = "__plugin-worker";
@@ -30,84 +30,42 @@ pub const MAX_CAPABILITY_REQUEST_BYTES: usize = 64 * 1024;
/// Read one length-prefixed frame (4-byte big-endian length + JSON).
///
/// `Ok(None)` means a clean EOF at a frame boundary. A partial header or
/// truncated payload is a protocol error, never EOF.
/// truncated payload is a protocol error, never EOF. Framing itself is shared
/// with other persistent workers; the plugin vocabulary stays in this module.
pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Value>, PluginError> {
let mut length = [0_u8; 4];
let mut read = 0usize;
while read < length.len() {
match reader.read(&mut length[read..]) {
Ok(0) if read == 0 => return Ok(None),
Ok(0) => {
return Err(PluginError::wire(
"worker_frame_invalid",
"worker stream ended inside a frame header",
))
}
Ok(count) => read += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => {
return Err(PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
))
}
}
}
let length = u32::from_be_bytes(length) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(PluginError::wire(
"worker_frame_invalid",
format!("worker frame length {length} is invalid"),
));
}
let mut bytes = Vec::with_capacity(length.min(64 * 1024));
let read = reader
.take(length as u64)
.read_to_end(&mut bytes)
.map_err(|error| {
PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
)
})?;
if read != length {
return Err(PluginError::wire(
"worker_frame_invalid",
format!("worker frame declared {length} bytes but only {read} arrived"),
));
}
serde_json::from_slice(&bytes).map(Some).map_err(|error| {
PluginError::wire(
"worker_frame_invalid",
format!("worker frame is not valid JSON: {error}"),
)
})
marqdo_worker_ipc::read_frame(reader, MAX_FRAME_BYTES).map_err(frame_read_error)
}
/// Write one length-prefixed frame.
pub fn write_frame<W: Write>(writer: &mut W, value: &Value) -> Result<(), PluginError> {
let bytes = serde_json::to_vec(value).map_err(|error| {
PluginError::wire(
"worker_encode_failed",
format!("cannot encode worker frame: {error}"),
)
})?;
if bytes.len() > MAX_FRAME_BYTES {
return Err(PluginError::wire(
marqdo_worker_ipc::write_frame(writer, value, MAX_FRAME_BYTES).map_err(frame_write_error)
}
fn frame_read_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
match error {
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
"plugin.crashed",
format!("worker frame read failed: {error}"),
),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
}
}
fn frame_write_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
match error {
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
"plugin.crashed",
format!("worker frame write failed: {error}"),
),
marqdo_worker_ipc::FrameError::Encode(error) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
marqdo_worker_ipc::FrameError::Length(length) => PluginError::wire(
"worker_frame_too_large",
format!("worker frame is {} bytes", bytes.len()),
));
format!("worker frame is {length} bytes"),
),
other => PluginError::wire("worker_frame_invalid", other.to_string()),
}
writer
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| writer.write_all(&bytes))
.and_then(|()| writer.flush())
.map_err(|error| {
PluginError::invoke(
"plugin.crashed",
format!("worker frame write failed: {error}"),
)
})
}
/// Run one worker until shutdown/EOF. Returns a process exit code.
@@ -133,7 +91,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
let handler_stdout = Arc::clone(&stdout);
let handler_ids = Arc::clone(&next_request_id);
let handler_calls = Arc::clone(&capability_calls);
let capability_handler: crate::loader::CapabilityHandler = Box::new(
let capability_handler: super::loader::CapabilityHandler = Box::new(
move |capability, request| {
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
return Err(PluginError::capability(
@@ -227,7 +185,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
},
);
let options = LoadOptions {
host_target: crate::artifact::HostTarget::current(),
host_target: super::artifact::HostTarget::current(),
capability_handler: Some(capability_handler),
};
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
+119 -103
View File
@@ -4,27 +4,29 @@
//! `__plugin-worker` command. It isolates crashes and keeps native code out of
//! the interpreter process. A plain process is **not** an OS sandbox; strict
//! mode still refuses without a real isolation adapter.
//!
//! Framing, bounded reads, deadlines and teardown come from
//! [`marqdo_worker_ipc`]. The invoke/capability vocabulary, capability limit and
//! plugin error codes remain owned here: a shared transport never shares
//! capabilities.
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::thread;
use std::time::Duration;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use marqdo_plugin_abi::worker::{
read_frame, write_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, WORKER_COMMAND,
};
use marqdo_plugin_abi::{
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
use crate::plugin::worker::{
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
WORKER_COMMAND,
};
use crate::plugin::{CapabilityHandler, PluginManifest};
use marqdo_plugin_abi::{PluginError, WireRequest, WireResponse};
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::json;
/// A native plugin running in an isolated worker process.
pub struct WorkerPlugin {
child: Child,
stdin: ChildStdin,
frames: Receiver<Result<serde_json::Value, PluginError>>,
connection: Connection,
exports: BTreeMap<String, String>,
dead: bool,
capability_handler: Option<CapabilityHandler>,
@@ -36,7 +38,7 @@ const CALL_TIMEOUT: Duration = Duration::from_secs(10);
impl std::fmt::Debug for WorkerPlugin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkerPlugin")
.field("pid", &self.child.id())
.field("pid", &self.connection.id())
.field("exports", &self.exports.keys().collect::<Vec<_>>())
.finish()
}
@@ -77,7 +79,7 @@ impl WorkerPlugin {
format!("cannot find the current executable: {error}"),
)
})?;
let mut child = match Command::new(executable)
let child: Child = match Command::new(executable)
.arg(WORKER_COMMAND)
.arg(&manifest_path)
.arg(base_dir)
@@ -95,66 +97,33 @@ impl WorkerPlugin {
));
}
};
let Some(stdin) = child.stdin.take() else {
let _ = child.kill();
return Err(PluginError::load(
"worker_spawn_failed",
"worker stdin unavailable",
));
};
let Some(mut stdout) = child.stdout.take() else {
let _ = child.kill();
let _ = std::fs::remove_file(&manifest_path);
return Err(PluginError::load(
"worker_spawn_failed",
"worker stdout unavailable",
));
let connection = match Connection::attach(child, MAX_FRAME_BYTES) {
Ok(connection) => connection,
Err(error) => {
let _ = std::fs::remove_file(&manifest_path);
return Err(PluginError::load(
"worker_spawn_failed",
format!("cannot start plugin worker transport: {error}"),
));
}
};
let (sender, frames) = mpsc::channel();
thread::Builder::new()
.name("marqdo-plugin-worker-reader".to_string())
.spawn(move || loop {
match read_frame(&mut stdout) {
Ok(Some(frame)) => {
if sender.send(Ok(frame)).is_err() {
break;
}
}
Ok(None) => {
let _ = sender.send(Err(PluginError::invoke(
"plugin.crashed",
"plugin worker closed its output stream",
)));
break;
}
Err(error) => {
let _ = sender.send(Err(error));
break;
}
}
})
.map_err(|error| {
let _ = child.kill();
PluginError::load(
"worker_spawn_failed",
format!("cannot start worker reader: {error}"),
)
})?;
let ready = match frames.recv_timeout(HANDSHAKE_TIMEOUT) {
let mut connection = connection;
let ready = match connection.receive(Instant::now() + HANDSHAKE_TIMEOUT) {
Ok(frame) => frame,
Err(_) => {
Err(TransportError::Timeout) => {
let _ = std::fs::remove_file(&manifest_path);
let _ = child.kill();
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker handshake timed out",
));
}
Err(error) => {
let _ = std::fs::remove_file(&manifest_path);
return Err(transport_error(error));
}
};
let _ = std::fs::remove_file(&manifest_path);
let ready = ready?;
if ready.get("kind").and_then(serde_json::Value::as_str) != Some("ready") {
let _ = child.kill();
return Err(PluginError::load(
"worker_handshake_failed",
"worker did not report ready",
@@ -182,16 +151,13 @@ impl WorkerPlugin {
.collect();
let actual: std::collections::BTreeSet<&str> = exports.keys().map(String::as_str).collect();
if declared != actual {
let _ = child.kill();
return Err(PluginError::manifest(
"worker_export_mismatch",
"worker exports do not match the manifest",
));
}
Ok(Self {
child,
stdin,
frames,
connection,
exports,
dead: false,
capability_handler,
@@ -208,36 +174,21 @@ impl WorkerPlugin {
}
let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?)
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
if let Err(error) = write_frame(
&mut self.stdin,
&json!({"kind": "invoke", "request": request_value}),
let deadline = Instant::now() + CALL_TIMEOUT;
if let Err(error) = self.connection.send(
json!({"kind": "invoke", "request": request_value}),
deadline,
) {
self.mark_dead();
return Err(error);
return Err(invocation_error(error));
}
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
let mut capability_requests = 0usize;
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
self.mark_dead();
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
));
}
let frame = match self.frames.recv_timeout(remaining) {
Ok(Ok(frame)) => frame,
Ok(Err(error)) => {
let frame = match self.connection.receive(deadline) {
Ok(frame) => frame,
Err(error) => {
self.mark_dead();
return Err(error);
}
Err(_) => {
self.mark_dead();
return Err(PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
));
return Err(invocation_error(error));
}
};
match frame.get("kind").and_then(serde_json::Value::as_str) {
@@ -252,13 +203,13 @@ impl WorkerPlugin {
),
));
}
if let Err(error) = self.handle_capability_request(&frame) {
if let Err(error) = self.handle_capability_request(&frame, deadline) {
self.mark_dead();
return Err(error);
}
}
Some("response") => {
return marqdo_plugin_abi::worker::response_from_frame(&frame);
return response_from_frame(&frame);
}
Some("error") => {
return Err(PluginError::invoke(
@@ -283,7 +234,11 @@ impl WorkerPlugin {
}
}
fn handle_capability_request(&mut self, frame: &serde_json::Value) -> Result<(), PluginError> {
fn handle_capability_request(
&mut self,
frame: &serde_json::Value,
deadline: Instant,
) -> Result<(), PluginError> {
let id = frame
.get("id")
.and_then(serde_json::Value::as_u64)
@@ -332,23 +287,84 @@ impl WorkerPlugin {
"message":error.message,
}),
};
if let Err(error) = write_frame(&mut self.stdin, &reply) {
self.mark_dead();
return Err(error);
}
Ok(())
self.connection
.send(reply, deadline)
.map_err(invocation_error)
}
fn mark_dead(&mut self) {
self.dead = true;
let _ = self.child.kill();
self.connection.abort();
}
}
impl Drop for WorkerPlugin {
fn drop(&mut self) {
let _ = write_frame(&mut self.stdin, &json!({"kind": "shutdown"}));
let _ = self.child.kill();
let _ = self.child.wait();
if !self.dead {
let _ = self.connection.send(
json!({"kind": "shutdown"}),
Instant::now() + Duration::from_millis(500),
);
}
self.connection.abort();
}
}
fn invocation_error(error: TransportError) -> PluginError {
match error {
TransportError::Timeout => PluginError::invoke(
"plugin.timeout",
"plugin worker exceeded its invocation timeout",
),
other => transport_error(other),
}
}
fn transport_error(error: TransportError) -> PluginError {
match error {
TransportError::Timeout => {
PluginError::invoke("plugin.timeout", "plugin worker exceeded its timeout")
}
TransportError::Closed => {
PluginError::invoke("plugin.crashed", "plugin worker closed its output stream")
}
TransportError::Frame(FrameError::Io(error)) => PluginError::invoke(
"plugin.crashed",
format!("worker frame I/O failed: {error}"),
),
// The shared transport classifies an over-limit or unencodable frame
// before anything is written. Keep the boundary-specific codes the
// plugin ABI has always reported instead of flattening them into
// `worker_frame_invalid`.
TransportError::Frame(FrameError::Encode(error)) => {
PluginError::wire("worker_encode_failed", error.to_string())
}
TransportError::Frame(FrameError::Length(length)) => PluginError::wire(
"worker_frame_too_large",
format!("worker frame is {length} bytes"),
),
TransportError::Frame(other) => {
PluginError::wire("worker_frame_invalid", other.to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transport_errors_keep_the_boundary_specific_codes() {
let too_large = transport_error(TransportError::Frame(FrameError::Length(9 * 1024 * 1024)));
assert_eq!(too_large.code, "worker_frame_too_large");
let over_limit = transport_error(TransportError::Frame(FrameError::PartialPayload {
expected: 10,
actual: 3,
}));
assert_eq!(over_limit.code, "worker_frame_invalid");
let closed = transport_error(TransportError::Closed);
assert_eq!(closed.code, "plugin.crashed");
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use marqdo_value::{ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext;
use marqdo_host_contract::ExecutionContext;
fn process_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
+2 -1
View File
@@ -12,7 +12,8 @@ use libloading::Library;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::resource::{ResourceProvider, ResourceRead};
use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
const ABI_VERSION: u32 = 1;
const ERROR_MAX: usize = 1024;
+45 -49
View File
@@ -1,29 +1,35 @@
//! Host-managed worker resource provider (ADR-0035).
//!
//! This is a small, versioned framed-JSON transport for **trusted helper
//! processes**. It is not a C ABI binding and not an OS sandbox: the helper
//! runs as the host user. Registration is a host embedding API; language code
//! only sees the normal `resource.*` operations.
//! This is a bounded framed-JSON transport for **trusted helper processes**.
//! It is not a C ABI binding and not an OS sandbox: the helper runs as the host
//! user. Registration is a host embedding API; language code only sees the
//! normal `resource.*` operations.
//!
//! Framing, bounded reads, request deadlines and teardown come from
//! [`marqdo_worker_ipc`]. The `open`/`read`/`write`/`close` vocabulary, kind
//! rights and error categories stay owned by the resource boundary, so a
//! shared transport never widens provider authority.
use std::io::{BufReader, Read, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use marqdo_span::Span;
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::{json, Value as Json};
use crate::resource::{ResourceProvider, ResourceRead};
use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
use marqdo_value::{ErrorCategory, RuntimeError};
const MAX_FRAME_BYTES: usize = 1024 * 1024;
const WORKER_TIMEOUT: Duration = Duration::from_secs(30);
/// A `ResourceProvider` backed by a child process speaking framed JSON.
pub(crate) struct WorkerResourceProvider {
name: String,
kinds: Vec<String>,
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
connection: Connection,
}
impl WorkerResourceProvider {
@@ -33,7 +39,7 @@ impl WorkerResourceProvider {
program: &Path,
args: &[String],
) -> Result<Self, RuntimeError> {
let mut child = Command::new(program)
let child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -49,20 +55,12 @@ impl WorkerResourceProvider {
),
)
})?;
let stdin = child
.stdin
.take()
.ok_or_else(|| worker_error("missing stdin pipe"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| worker_error("missing stdout pipe"))?;
let connection = Connection::attach(child, MAX_FRAME_BYTES)
.map_err(|error| worker_error(&format!("cannot attach to worker: {error}")))?;
let mut provider = Self {
name: name.to_string(),
kinds: kinds.to_vec(),
child,
stdin,
stdout: BufReader::new(stdout),
connection,
};
// Handshake: the helper must answer a ping before it is trusted.
provider.request(json!({"op": "ping"}))?;
@@ -70,30 +68,11 @@ impl WorkerResourceProvider {
}
fn request(&mut self, request: Json) -> Result<Json, RuntimeError> {
let bytes = serde_json::to_vec(&request)
.map_err(|error| worker_error(&format!("cannot encode request: {error}")))?;
if bytes.len() > MAX_FRAME_BYTES {
return Err(worker_error("request frame is too large"));
}
self.stdin
.write_all(&(bytes.len() as u32).to_be_bytes())
.and_then(|()| self.stdin.write_all(&bytes))
.and_then(|()| self.stdin.flush())
.map_err(|error| worker_error(&format!("cannot write request frame: {error}")))?;
let mut header = [0u8; 4];
self.stdout
.read_exact(&mut header)
.map_err(|error| worker_error(&format!("cannot read response header: {error}")))?;
let length = u32::from_be_bytes(header) as usize;
if length == 0 || length > MAX_FRAME_BYTES {
return Err(worker_error("invalid response frame length"));
}
let mut payload = vec![0u8; length];
self.stdout
.read_exact(&mut payload)
.map_err(|error| worker_error(&format!("cannot read response frame: {error}")))?;
let response: Json = serde_json::from_slice(&payload)
.map_err(|error| worker_error(&format!("invalid response JSON: {error}")))?;
let deadline = Instant::now() + WORKER_TIMEOUT;
self.connection
.send(request, deadline)
.map_err(transport_error)?;
let response = self.connection.receive(deadline).map_err(transport_error)?;
if response.get("ok").and_then(Json::as_bool) != Some(true) {
let code = response
.get("code")
@@ -192,9 +171,11 @@ impl ResourceProvider for WorkerResourceProvider {
impl Drop for WorkerResourceProvider {
fn drop(&mut self) {
let _ = self.request(json!({"op": "shutdown"}));
let _ = self.child.kill();
let _ = self.child.wait();
let _ = self.connection.send(
json!({"op": "shutdown"}),
Instant::now() + Duration::from_millis(500),
);
self.connection.abort();
}
}
@@ -205,6 +186,21 @@ fn with_span(mut error: RuntimeError, span: Option<Span>) -> RuntimeError {
error
}
fn transport_error(error: TransportError) -> RuntimeError {
match error {
TransportError::Timeout => {
worker_error("worker resource provider did not answer before the deadline")
}
TransportError::Closed => worker_error("worker resource provider closed its transport"),
TransportError::Frame(FrameError::Io(error)) => {
worker_error(&format!("worker resource provider I/O failed: {error}"))
}
TransportError::Frame(other) => {
worker_error(&format!("worker resource provider frame error: {other}"))
}
}
}
fn worker_error(message: &str) -> RuntimeError {
RuntimeError::new(ErrorCategory::HostError, None, message.to_string())
}
+1 -9
View File
@@ -13,6 +13,7 @@ use rustls::{ClientConnection, StreamOwned};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use marqdo_host_contract::ResourceRead;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
@@ -83,15 +84,6 @@ pub trait ResourceProvider: Send {
/// Shared provider handle registered on the host.
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
struct StdinCursor {
bytes: Vec<u8>,
position: usize,
-180
View File
@@ -1,180 +0,0 @@
//! Effect tracing.
use std::time::Duration;
use marqdo_span::Span;
use serde::{Deserialize, Serialize};
/// One recorded host effect.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceEntry {
/// Global event sequence within the run.
#[serde(default)]
pub seq: u64,
/// Operation name (`print`, `fs.read`, `foreign.call`, ...).
pub op: String,
/// Module that initiated it.
pub module: String,
/// Source span of the call site.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Wall-clock duration.
pub duration_micros: u64,
/// Result summary (`ok`, or a diagnostic code). Never contains secrets.
pub result: String,
}
/// Collected effects for one run.
#[derive(Debug, Clone, Default)]
pub struct EffectTrace {
entries: Vec<TraceEntry>,
/// Whether tracing is enabled.
pub enabled: bool,
}
impl EffectTrace {
/// Enable tracing.
pub fn enabled() -> Self {
Self {
entries: Vec::new(),
enabled: true,
}
}
/// Record an effect.
pub fn record(
&mut self,
seq: u64,
op: impl Into<String>,
module: impl Into<String>,
span: Option<Span>,
duration: Duration,
result: impl Into<String>,
) {
if !self.enabled {
return;
}
self.entries.push(TraceEntry {
seq,
op: op.into(),
module: module.into(),
span,
duration_micros: duration.as_micros() as u64,
result: result.into(),
});
}
/// Recorded entries.
pub fn entries(&self) -> &[TraceEntry] {
&self.entries
}
}
/// Default maximum number of trace events.
pub const DEFAULT_MAX_TRACE_EVENTS: usize = 100_000;
/// Default approximate maximum serialized trace bytes.
pub const DEFAULT_MAX_TRACE_BYTES: usize = 32 * 1024 * 1024;
/// Trace capacity budget. A zero value means unlimited.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceBudget {
/// Maximum events (including the terminal truncation marker).
pub max_events: usize,
/// Approximate maximum serialized bytes.
pub max_bytes: usize,
}
impl Default for TraceBudget {
fn default() -> Self {
Self {
max_events: DEFAULT_MAX_TRACE_EVENTS,
max_bytes: DEFAULT_MAX_TRACE_BYTES,
}
}
}
/// Why and where a trace stopped recording.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TraceTruncation {
/// `event_budget` or `byte_budget`.
pub reason: String,
/// The configured limit that was reached.
pub limit: u64,
/// Events written before truncation.
pub written: u64,
}
/// Mutable trace capacity state for one run.
#[derive(Debug, Clone, Default)]
pub struct TraceState {
/// Whether trace recording is enabled.
pub enabled: bool,
/// Configured budget.
pub budget: TraceBudget,
/// Events accepted so far.
pub written: usize,
/// Estimated accepted bytes.
pub bytes: usize,
/// Truncation marker, set once.
pub truncation: Option<TraceTruncation>,
}
impl TraceState {
/// Accept one event if it fits the budget.
pub fn accept(&mut self, estimate: usize) -> bool {
if !self.enabled || self.truncation.is_some() {
return false;
}
if self.budget.max_events > 0 && self.written >= self.budget.max_events {
self.truncation = Some(TraceTruncation {
reason: "event_budget".to_string(),
limit: self.budget.max_events as u64,
written: self.written as u64,
});
return false;
}
if self.budget.max_bytes > 0 && self.bytes + estimate > self.budget.max_bytes {
self.truncation = Some(TraceTruncation {
reason: "byte_budget".to_string(),
limit: self.budget.max_bytes as u64,
written: self.written as u64,
});
return false;
}
self.written += 1;
self.bytes += estimate;
true
}
/// Estimate one semantic/effect event envelope.
pub fn estimate(
kind: &str,
function_id: Option<&str>,
module_id: Option<&str>,
detail: Option<&str>,
operation: Option<&str>,
) -> usize {
96 + kind.len()
+ function_id.map(str::len).unwrap_or(0)
+ module_id.map(str::len).unwrap_or(0)
+ detail.map(str::len).unwrap_or(0)
+ operation.map(str::len).unwrap_or(0)
}
}
/// One semantic event emitted by the interpreter (Trace v2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticEvent {
/// Global event sequence within the run.
pub seq: u64,
/// Stable event kind (`call.enter`, `call.exit`, `branch.eval`, ...).
pub kind: String,
/// Canonical function id, when inside a call.
pub function_id: Option<String>,
/// Logical module owning `span`.
pub module_id: Option<String>,
/// Source span, when known.
pub span: Option<Span>,
/// Non-sensitive detail (`ok`, `true`, `int`, an error code).
pub detail: Option<String>,
}
+4 -3
View File
@@ -3,12 +3,13 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
@@ -5,8 +5,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
@@ -11,9 +11,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{
sha256_file, ErrorKind, HostTarget, LoadedPlugin, PluginManifest, Value, WireRequest,
};
use marqdo_host::plugin::{sha256_file, HostTarget, LoadedPlugin, PluginManifest};
use marqdo_plugin_abi::{ErrorKind, WireRequest};
use marqdo_value::Value;
static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0);
+76 -3
View File
@@ -8,10 +8,10 @@ use std::cell::RefCell;
use std::rc::Rc;
use marqdo_host::{
encode_value, Capabilities, ExecutionContext, FrameId, Host, ObservationConfig,
ObservationError, ObservationEvent, ObservationSink, ParameterSource, RuntimeObservation,
StdHost, ValueState,
encode_value, Capabilities, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, StdHost, ValueState,
};
use marqdo_host_contract::{ExecutionContext, FrameId, Host, ParameterSource, RuntimeObservation};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
@@ -462,3 +462,76 @@ fn value_encoding_is_selected_bounded_and_handle_safe() {
assert_eq!(state, ValueState::Unsupported);
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);
}
+3 -2
View File
@@ -6,8 +6,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::Value;
+4 -3
View File
@@ -2,7 +2,8 @@
use std::path::Path;
use marqdo_host::{Capabilities, ExecutionContext, Host, HostOp, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{ExecutionContext, Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
@@ -325,12 +326,12 @@ impl marqdo_host::ResourceProvider for MockProvider {
token: u64,
max_bytes: usize,
_span: Option<marqdo_span::Span>,
) -> Result<marqdo_host::ResourceRead, marqdo_value::RuntimeError> {
) -> Result<marqdo_host_contract::ResourceRead, marqdo_value::RuntimeError> {
assert_eq!(token, 7);
let start = self.position;
let end = start.saturating_add(max_bytes).min(self.data.len());
self.position = end;
Ok(marqdo_host::ResourceRead {
Ok(marqdo_host_contract::ResourceRead {
bytes: self.data[start..end].to_vec(),
eof: end >= self.data.len(),
})
+4 -3
View File
@@ -1,9 +1,10 @@
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
+1 -1
View File
@@ -3,7 +3,7 @@
//! The frontend resolves every statically visible call site exactly once and
//! records the decision here. The runtime only dispatches by this table: it
//! never re-resolves a qualified name and never guesses a plugin from a string
//! prefix. The table is internal IR (not part of Analysis/Trace v2 wire
//! prefix. The table is internal IR (not part of the Analysis/Observation wire
//! contracts) and is deliberately skipped when a [`crate::Program`] is
//! serialized.
//!
Loaded 100 of 334 files, more files were not shown because too many files have changed in this diff. Show more