From 8bd33a46152fdf3a7f922289f3a1194228d53ce4 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 14:11:26 +0800 Subject: [PATCH 01/17] docs: define single current contracts before the first stable release --- AGENTS.md | 10 ++++ .../0068-single-current-public-contracts.md | 53 +++++++++++++++++++ docs/architecture/CURRENT.md | 4 ++ 3 files changed, 67 insertions(+) create mode 100644 docs/adr/0068-single-current-public-contracts.md diff --git a/AGENTS.md b/AGENTS.md index 009aa3a..52d1778 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,16 @@ correctness and release evidence before expanding the surface. 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`. +## Pre-stable protocol changes + +Read [ADR-0068](docs/adr/0068-single-current-public-contracts.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 1. Identify the affected rule and cite RFC-LANG-0002 / `spec/mapping.md` (or, for architecture-only changes, the relevant `docs/DEVELOPMENT_BLUEPRINT.md` section). diff --git a/docs/adr/0068-single-current-public-contracts.md b/docs/adr/0068-single-current-public-contracts.md new file mode 100644 index 0000000..59ab16d --- /dev/null +++ b/docs/adr/0068-single-current-public-contracts.md @@ -0,0 +1,53 @@ +# ADR-0068 — One current contract per public boundary + +Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-24). + +## Context + +Issue [#8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) identified two +independent Analysis version selectors. A tool could install successfully +even when it could not read the output for a given project. The runtime +also projected the same execution into independently defined Trace and +Execution Events protocols. The compilation pipeline described in +DEVELOPMENT_BLUEPRINT §7 remains the source of language facts. + +## Decision + +Before the first stable release, replace a broken public contract in place. +For each boundary, keep one current format identifier, one producer and one +validation path. Reject mismatches explicitly. Update the CLI, schemas, +consumers, fixtures and CI in the same integration. Use Git history and +release tags to retrieve retired specifications. A future stable release +requires its own compatibility policy. + +- Analysis is always `marqdo.analysis` revision 3, including projects without + loop transfers. The Markdown AST and IR remain internal authorities. +- Runtime observations use `marqdo.observation` revision 1. One run emits + one sequence. JSONL stdout and JSON snapshots deliver those same events. + `run` and `call` use `--output text|json|jsonl` and + `--observation-file PATH`. Capture selections and budgets apply to all + observation destinations. +- Tool manifests use `marqdo.cli-tool` revision 2, with a required + `requires.api_revision: 1` and optional exact Analysis and Observation + requirements. Reinstall tools registered under earlier formats. The + existing Tool subcommands and external dispatch suffice for this workflow. +- Keep the three current extension descriptors. Callable exports, resource + rights and foreign interpreter selection have independent validation and + lifecycles. Share value encoding and equivalent process transport + primitives. Keep Lock v4 because its graph and artifact identities still + describe the selected extensions without a format change. + +## Security and verification + +Static analysis stays non-executing. Observation binds to the exact Analysis +artifact and defaults to structural capture. Selected values, Text consent, +handles, buffering, output bytes and failure/truncation must follow the +current observation contract. Preserve native trust, process timeouts, +worker quarantine, capability grants, artifact integrity and fail-closed +strict behavior. + +Exercise real CLI output with an independent consumer, including old-input +rejection, two simultaneous destinations from a single invocation, source +digest mismatches, allowlisted capture, and consumer installation. Validate +independent View and Lint against the final CLI, then validate the shipped +archive and its SHA-bound release evidence before tagging an RC. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index d33bbd4..8796a3a 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -62,6 +62,10 @@ replace `spec/` or a recorded test log. > statements it emits. The interpreter owns the transfers and reports them > through the existing observation facade. +Protocol architecture and pre-stable replacement rules are recorded in +[ADR-0068](../adr/0068-single-current-public-contracts.md). Check the +[implementation status](../STATUS.md) for rollout and release evidence. + ## 1. Four state dimensions A claim is stated in exactly one of these dimensions. "Exists in the tree" is not From 8bfe0c36ee8613d74826480a1011ffce380c91ff Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 14:16:56 +0800 Subject: [PATCH 02/17] analysis: publish one schema for every project --- .github/workflows/ci.yml | 20 +-- crates/cli/src/analysis.rs | 26 +--- crates/cli/src/main.rs | 2 +- crates/cli/src/tool.rs | 5 +- crates/cli/tests/analysis_trace.rs | 16 +- crates/cli/tests/examples_r6.rs | 2 +- spec/analysis-v1.md | 140 ------------------ spec/analysis-v3.md | 27 ---- spec/{analysis-v2.md => analysis.md} | 67 +++------ spec/schemas/analysis-v1.schema.json | 52 ------- spec/schemas/analysis-v2.schema.json | 103 ------------- ...is-v3.schema.json => analysis.schema.json} | 4 +- tests/consumers/analysis_consumer.py | 36 ++++- tests/consumers/analysis_v3_consumer.py | 45 ------ tests/consumers/trace_consumer.py | 2 +- tests/consumers/validate_protocols.py | 9 +- tools/ci/test_release_archive.py | 11 +- tools/release/package.py | 3 +- tools/release/smoke.py | 23 ++- 19 files changed, 93 insertions(+), 500 deletions(-) delete mode 100644 spec/analysis-v1.md delete mode 100644 spec/analysis-v3.md rename spec/{analysis-v2.md => analysis.md} (72%) delete mode 100644 spec/schemas/analysis-v1.schema.json delete mode 100644 spec/schemas/analysis-v2.schema.json rename spec/schemas/{analysis-v3.schema.json => analysis.schema.json} (98%) delete mode 100644 tests/consumers/analysis_v3_consumer.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8395d9..9d98c1c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,26 +106,22 @@ 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 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 + /tmp/analysis-simple.json /tmp/trace-v2.json examples/tool-unknown-name/tool.json + python3 tests/consumers/analysis_consumer.py /tmp/analysis-simple.json python3 tests/consumers/trace_consumer.py \ - /tmp/analysis-v2.json /tmp/trace-v2.json + /tmp/analysis-simple.json /tmp/trace-v2.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 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 - exit 1 - fi - python3 tests/consumers/trace_consumer.py /tmp/analysis-v3.json /tmp/control-trace-v2.json + /tmp/analysis-control.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json + python3 tests/consumers/analysis_consumer.py /tmp/analysis-control.json --require-transfers + python3 tests/consumers/trace_consumer.py /tmp/analysis-control.json /tmp/control-trace-v2.json python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl cross-platform: diff --git a/crates/cli/src/analysis.rs b/crates/cli/src/analysis.rs index 787f87b..93d7fe1 100644 --- a/crates/cli/src/analysis.rs +++ b/crates/cli/src/analysis.rs @@ -1,4 +1,4 @@ -//! Public Analysis projection (spec/analysis-v2.md and spec/analysis-v3.md). +//! Public Analysis projection (spec/analysis.md). //! //! This is deliberately not a serde dump of `marqdo-ir`: the schema and node //! kinds are the public contract, while internal Rust types may change. The @@ -17,24 +17,13 @@ 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; +pub const SCHEMA_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, @@ -60,7 +49,7 @@ pub fn build(project: &LoadedProject) -> Value { }); json!({ "schema": SCHEMA, - "schema_version": version, + "schema_version": SCHEMA_VERSION, "producer": { "name": "marqdo", "version": env!("CARGO_PKG_VERSION"), @@ -81,15 +70,6 @@ pub fn build(project: &LoadedProject) -> Value { }) } -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, String> { serde_json::to_vec_pretty(&build(project)) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 22881c3..66e384b 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -314,7 +314,7 @@ struct CheckArgs { /// Declare a plugin manifest for static export-signature checking. #[arg(long = "plugin", value_name = "PATH")] plugin: Vec, - /// 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, /// Machine readable JSON output. diff --git a/crates/cli/src/tool.rs b/crates/cli/src/tool.rs index 2b001b8..474dc8e 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -31,10 +31,7 @@ struct SupportedProtocols { const SUPPORTED: SupportedProtocols = SupportedProtocols { tool: PROTOCOL_VERSION, - analysis: &[ - crate::analysis::BASE_VERSION, - crate::analysis::LOOP_CONTROL_VERSION, - ], + analysis: &[crate::analysis::SCHEMA_VERSION], trace: &[2], }; diff --git a/crates/cli/tests/analysis_trace.rs b/crates/cli/tests/analysis_trace.rs index 3e4acfd..fd504ff 100644 --- a/crates/cli/tests/analysis_trace.rs +++ b/crates/cli/tests/analysis_trace.rs @@ -1,4 +1,4 @@ -//! Public Analysis/Trace v1 black-box contract (spec/analysis-v1.md, +//! Public Analysis and Trace black-box contracts (spec/analysis.md, //! spec/trace-v1.md). use std::path::{Path, PathBuf}; @@ -96,7 +96,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 +140,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 +182,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 +211,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 @@ -395,7 +395,7 @@ fn trace_records_calls_effects_and_status_without_secrets() { } #[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 +427,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"); @@ -463,7 +463,7 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() { } #[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(), diff --git a/crates/cli/tests/examples_r6.rs b/crates/cli/tests/examples_r6.rs index af45705..64f35db 100644 --- a/crates/cli/tests/examples_r6.rs +++ b/crates/cli/tests/examples_r6.rs @@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() { #[test] fn public_schemas_are_valid_json_and_versioned() { - for name in ["analysis-v1", "trace-v1", "tool-v1", "execution-events-v1"] { + for name in ["analysis", "trace-v1", "tool-v1", "execution-events-v1"] { let path = repo() .join("spec/schemas") .join(format!("{name}.schema.json")); diff --git a/spec/analysis-v1.md b/spec/analysis-v1.md deleted file mode 100644 index c1bb405..0000000 --- a/spec/analysis-v1.md +++ /dev/null @@ -1,140 +0,0 @@ -# Marqdo Analysis v1 - -Status: **superseded by [Analysis v2](analysis-v2.md); never released, do not -write v1.** Kept as history. This was the M0.6 R4 read-only projection; it is -not a dump of `marqdo-ir`. - -## 1. Invariants - -`check --emit`: - -* never executes the document, loads a plugin shared library, starts a foreign - kernel or imports a module implicitly; -* validates the loaded program first; on a compile error it writes no artifact - and removes a stale file at the target path; -* writes atomically (temporary file + rename) only after a successful check; -* is deterministic: the same source, tool version and project path produce - byte-identical JSON (no timestamps, no random ids); -* exposes no private Rust layout, optimization instruction or host pointer. - -## 2. Top-level shape - -```json -{ - "schema": "marqdo.analysis", - "schema_version": 1, - "producer": {"name": "marqdo", "version": "0.1.0", "markdown_profile": "marqdo.md.v1"}, - "project": {"root_id": "sha256:...", "lock_digest": "sha256:..."}, - "modules": [], - "diagnostics": [] -} -``` - -* `root_id` is a digest of the normalized project root used for this run. -* `lock_digest` is a digest of `marqdo.lock`, or `""` when absent. -* Modules are sorted by canonical `id`; arrays keep source order. -* `schema_version` is a major version. Additive optional fields are allowed; - removing/renaming fields or changing units/types requires a major bump. - -## 3. Modules - -```json -{ - "id": "root:default::index.mq.md", - "package_instance_id": "root:default", - "relative_path": "index.mq.md", - "source_digest": "", - "units": [], - "functions": [], - "imports": [], - "references": [], - "calls": [], - "resources": 0 -} -``` - -Module identity is the package-aware `ModuleId` from -`spec/references.md` §2.1. `source_digest` hashes the exact source bytes. - -### 3.1 Units - -Each unit has `id`, `kind` (`root`/`namespace`/`function`/`section`), `name`, -`level`, `span` (`{start,end}` byte offsets) and optionally `function`. - -### 3.2 Functions and signatures - -```json -{ - "id": "root:default::index.mq.md::数学.阶乘", - "unit_id": "root:default::index.mq.md#数学/阶乘", - "local_name": "阶乘", - "namespace": "数学", - "span": {"start": 0, "end": 100}, - "heading_span": {"start": 0, "end": 10}, - "signature": { - "kind": "inferred", - "params": [{"name": "n", "required": true, "type": null, "default": null, "span": {"start": 0, "end": 0}}] - }, - "effects": ["unknown"], - "body": [] -} -``` - -`kind` is `explicit` or `inferred`. Inferred signatures only accept named -arguments. `effects` is a **conservative** summary; `unknown` is not a proof of -purity. Dynamic ABI/Foreign targets remain unknown unless a descriptor says -otherwise. - -### 3.3 Normalized body nodes - -Body nodes use a small stable language, never internal IR serialization: - -* `literal` (`type`: `int`/`float`/`text`/`bool`/`none`, `value` when present); -* `variable`, `list`, `record`, `member`, `index`; -* `unary` (`not`/`neg`/`pos`) and `binary` (`or`, `and`, `eq`, `ne`, `lt`, - `le`, `gt`, `ge`, `add`, `sub`, `mul`, `div`, `floor_div`, `mod`, `pow`); -* `call` with `callee` and `args`; -* `assign`, `expression`, `call_site`, `branch` (ordered arms), `loop`, - `return`. (`call_site` existed for the pre-RFC link-form block-quote call and - is not produced by the current language; this document is historical.) - -Every node carries a byte `span`. Nodes outside the supported public subset -must be marked `unsupported` (future extension), never silently given invented -semantics. - -### 3.4 Imports, references and calls - -* `imports[]`: `{alias, target, span, resolved}`; `resolved` is a module id or - null. Imports stay explicit. -* `references[]`: Markdown link edges with `{source, url, span, state, - target_module, target_unit}`. `state` is `resolved`, `unresolved` or - `external`; a failed resolution is never disguised as bound. -* `calls[]`: `{function, span, callee, state, target}` where `state` is - `function`, `builtin`, `plugin` or `unresolved`. - -Reference edges never execute anything and grant no capability. - -## 4. Diagnostics - -`diagnostics[]` uses the same stable codes/JSON shape as `marqdo check --json`. -An analysis emitted after a successful check normally has no error diagnostics -(warnings may remain). - -## 5. Consumer contract - -An independent consumer (Python/Go/JavaScript, without linking Rust crates) -must be able to: - -* find a function by `id` and read its signature/body; -* find recursive/forward calls and `ref` edges; -* map every body node back to `source_digest` + byte span; -* reject `schema_version` it does not understand. - -`tests/consumers/analysis_consumer.py` is one such black-box consumer and -`crates/cli/tests/analysis_trace.rs` runs it when Python is available. - -## 6. Not included - -Internal optimization IR, host pointers, plugin handles, proof status and -execution results are deliberately absent. Analysis does not claim that a -document runs successfully or that any function is proved. diff --git a/spec/analysis-v3.md b/spec/analysis-v3.md deleted file mode 100644 index d62d34a..0000000 --- a/spec/analysis-v3.md +++ /dev/null @@ -1,27 +0,0 @@ -# Marqdo Analysis v3 - -Analysis v3 extends the public [Analysis v2](analysis-v2.md) contract with -structured loop control. Its envelope keeps `schema: "marqdo.analysis"` and -sets `schema_version: 3`. The writer emits v3 if any emitted function body -contains either new statement, including inside a nested body or an imported -module. Other projects still emit v2. Multi-arm branches fit both versions. - -## Statement additions - -```json -{"kind": "break", "span": {"start": 30, "end": 37}} -{"kind": "continue", "span": {"start": 39, "end": 49}} -``` - -Both spans are half-open UTF-8 byte ranges covering the carrier in the -containing module. Walk the enclosing statement bodies to find the nearest -loop. `break` transfers to the statement after that loop. `continue` -transfers to its condition. There are no operands, labels or call edges. -Call and resource projections retain their v2 shapes. - -Consumers check the major version before traversing any function body. A v2 -reader rejects v3, while a reader that accepts both versions can share its -v2 decoding and add two statement kinds. Trace v2 binds to the version -automatically emitted for the same input via `source.analysis_digest`. - -JSON Schema: [analysis-v3.schema.json](schemas/analysis-v3.schema.json). diff --git a/spec/analysis-v2.md b/spec/analysis.md similarity index 72% rename from spec/analysis-v2.md rename to spec/analysis.md index d3b1a31..83d8f0a 100644 --- a/spec/analysis-v2.md +++ b/spec/analysis.md @@ -1,8 +1,7 @@ -# Marqdo Analysis v2 +# Marqdo Analysis -Status: **implemented by `marqdo check --emit ` (S2); ADR-0022 adds an -additive index target shape.** Supersedes -Analysis v1. v1 was never released; it is kept as history and is not written. +Current public contract for `marqdo check --emit PATH`. Every project emits +`marqdo.analysis` with `schema_version: 3`. ## 1. Invariants @@ -22,7 +21,7 @@ Analysis v1. v1 was never released; it is kept as history and is not written. ```json { "schema": "marqdo.analysis", - "schema_version": 2, + "schema_version": 3, "producer": { "name": "marqdo", "version": "", @@ -99,7 +98,7 @@ conservative summary, not a purity proof). (`spec/callable-resolution.md` §6): `state` remains `function`/`builtin`/`plugin`/`unresolved`, and official stdlib aliases such as `打印` are reported as `function` targets because that is the implementation -that runs. The private `CallBindingTable` is not serialized; Analysis v2's +that runs. The private `CallBindingTable` is not serialized; Analysis's schema and version are unchanged. An `assign` node keeps the v1 string `target` for a local rebinding. Addressable @@ -181,48 +180,24 @@ location exists. The `code` value is an open, stable string: the current language revision adds the `sem.*` family (`spec/mapping.md` §8) and removes the old -`markdown.inert_executable` warning. This is a diagnostic-value change, not an -Analysis schema change; `schema_version` stays 2. +`markdown.inert_executable` warning. Diagnostic codes may be added without changing the structure. -## 6. Compatibility +## 6. Loop transfers -* Writers emit `schema_version: 2`. There is no v1 writer and no - `--emit-version` flag; v1 was experimental. -* Consumers must reject unknown `schema_version` values and unknown resource - kinds rather than silently accepting them. -* Changing `root_id`, resource fields, diagnostic fields or the digest - definition is a protocol break requiring a new version and an ADR. -* JSON Schema: `spec/schemas/analysis-v2.schema.json` (Draft 2020-12). - Schema validation is structural; cross-record checks (span inside source, - call targets, digest verification) remain semantic tests. +Conditional arms appear in source order. Both `break` and `continue` are +statements with a `kind` and the half-open UTF-8 `span` of their carrier. +They have no operands or call edges. Walk the enclosing bodies to find +the nearest loop. `break` transfers past that loop and `continue` transfers +to its condition. -## 7. Tests +## 7. Validation -* `analysis_is_deterministic_and_has_stable_semantic_nodes` -* `analysis_v2_identity_is_location_independent` -* `analysis_v2_projects_addressable_formula_and_code_resources` -* `failed_check_removes_stale_analysis` -* `tests/consumers/analysis_consumer.py` (independent Python consumer) +Require exactly `schema: "marqdo.analysis"` and `schema_version: 3` before +traversing the document. The [JSON Schema](schemas/analysis.schema.json) +validates record shapes. Check source digests, spans, ownership and +reference targets separately. Its full branch and loop structure applies +equally to simple projects and imported modules. -## 8. Versioning and future heading metadata - -`units[]` keeps its v2 fields and semantics: `id/kind/name/level/span/function`. -The effective core mode and origin of a `section` unit are deliberately **not** -added to v2, and neither are heading annotations. - -The language still has exactly two Core Modes (`@exec`/`@knowledge`); unmarked -headings inherit from the nearest ancestor and the root default is Knowledge -(`spec/mapping.md` §1.2, including the H-06 sibling fix). A future declarative, -metadata-only Heading Annotation index is Proposed under -[ADR-0060](../docs/adr/0060-heading-modes-and-extensible-annotations.md) and is -**not implemented in this build**. - -When that work ships (target `3.1.x`), it must use a new protocol version -(Analysis v3) or a separate `heading-annotations.v1` sidecar, bound to both the -source digest and the exact Analysis bytes digest; it must not rewrite v2 `units[]`. -Consumers that only know v2 must keep passing the existing schema/version contract, -and must reject an unknown sidecar/v3 version rather than silently ignoring it. - -Projects containing structured loop transfers use [Analysis v3](analysis-v3.md). -A v2 projection never contains those transfer statements. Multiple conditional -arms use the existing ordered `branch.arms` array. +Source digests cover the original bytes. Preserve UTF-8 byte offsets for +BOM, CRLF, CJK and emoji. Observation binds to the SHA-256 of the exact +emitted Analysis JSON bytes. diff --git a/spec/schemas/analysis-v1.schema.json b/spec/schemas/analysis-v1.schema.json deleted file mode 100644 index 854a86f..0000000 --- a/spec/schemas/analysis-v1.schema.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/analysis-v1.schema.json", - "title": "Marqdo Analysis v1", - "type": "object", - "required": ["schema", "schema_version", "producer", "project", "modules", "diagnostics"], - "properties": { - "schema": {"const": "marqdo.analysis"}, - "schema_version": {"const": 1}, - "producer": { - "type": "object", - "required": ["name", "version", "markdown_profile"], - "properties": { - "name": {"type": "string"}, - "version": {"type": "string"}, - "markdown_profile": {"const": "marqdo.md.v1"} - }, - "additionalProperties": true - }, - "project": { - "type": "object", - "required": ["root_id", "lock_digest"], - "properties": { - "root_id": {"type": "string"}, - "lock_digest": {"type": "string"} - }, - "additionalProperties": true - }, - "modules": { - "type": "array", - "items": { - "type": "object", - "required": ["id", "package_instance_id", "relative_path", "source_digest", "units", "functions", "imports", "references", "calls"], - "properties": { - "id": {"type": "string", "pattern": "::"}, - "package_instance_id": {"type": "string"}, - "relative_path": {"type": "string"}, - "source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, - "units": {"type": "array"}, - "functions": {"type": "array"}, - "imports": {"type": "array"}, - "references": {"type": "array"}, - "calls": {"type": "array"}, - "resources": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - }, - "diagnostics": {"type": "array"} - }, - "additionalProperties": true -} diff --git a/spec/schemas/analysis-v2.schema.json b/spec/schemas/analysis-v2.schema.json deleted file mode 100644 index f29c5f7..0000000 --- a/spec/schemas/analysis-v2.schema.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/analysis-v2.schema.json", - "title": "Marqdo Analysis v2", - "type": "object", - "required": ["schema", "schema_version", "producer", "project", "modules", "diagnostics"], - "properties": { - "schema": {"const": "marqdo.analysis"}, - "schema_version": {"const": 2}, - "producer": { - "type": "object", - "required": ["name", "version", "markdown_profile"], - "properties": { - "name": {"type": "string"}, - "version": {"type": "string"}, - "markdown_profile": {"const": "marqdo.md.v1"} - }, - "additionalProperties": true - }, - "project": { - "type": "object", - "required": ["root_id", "identity_kind", "lock_digest"], - "properties": { - "root_id": {"type": "string", "minLength": 1, "pattern": "^(root:|sha256:[0-9a-f]{64}$)"}, - "identity_kind": {"enum": ["manifest", "workspace_snapshot"]}, - "lock_digest": {"type": "string", "pattern": "^(sha256:[0-9a-f]{64})?$"} - }, - "additionalProperties": true - }, - "modules": { - "type": "array", - "items": { - "type": "object", - "required": ["id", "package_instance_id", "relative_path", "source_digest", "units", "functions", "imports", "references", "calls", "resources"], - "properties": { - "id": {"type": "string", "pattern": "::"}, - "package_instance_id": {"type": "string", "minLength": 1}, - "relative_path": {"type": "string", "minLength": 1, "pattern": "^(?!/)(?!.*\\.\\.)"}, - "source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, - "units": {"type": "array"}, - "functions": {"type": "array"}, - "imports": {"type": "array"}, - "references": {"type": "array"}, - "calls": {"type": "array"}, - "resources": { - "type": "array", - "items": { - "type": "object", - "required": ["id", "module_id", "unit_id", "kind", "span", "content_digest"], - "properties": { - "id": {"type": "string", "pattern": "#resource:(formula|code)-[0-9]+$"}, - "module_id": {"type": "string", "pattern": "::"}, - "unit_id": {"type": "string", "minLength": 1}, - "kind": {"enum": ["formula", "code"]}, - "span": { - "type": "object", - "required": ["start", "end"], - "properties": { - "start": {"type": "integer", "minimum": 0}, - "end": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - }, - "content_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, - "language": {"type": ["string", "null"]}, - "display": {"type": "boolean"} - }, - "additionalProperties": true - } - } - }, - "additionalProperties": true - } - }, - "diagnostics": { - "type": "array", - "items": { - "type": "object", - "required": ["module", "relative_path", "severity", "code", "message"], - "properties": { - "module": {"type": "string", "pattern": "::"}, - "relative_path": {"type": "string", "minLength": 1}, - "span": { - "type": ["object", "null"], - "required": ["start", "end"], - "properties": { - "start": {"type": "integer", "minimum": 0}, - "end": {"type": "integer", "minimum": 0} - } - }, - "line": {"type": ["integer", "null"], "minimum": 1}, - "column": {"type": ["integer", "null"], "minimum": 1}, - "severity": {"enum": ["error", "warning"]}, - "code": {"type": "string", "minLength": 1}, - "message": {"type": "string", "minLength": 1}, - "hints": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": true - } - } - }, - "additionalProperties": true -} diff --git a/spec/schemas/analysis-v3.schema.json b/spec/schemas/analysis.schema.json similarity index 98% rename from spec/schemas/analysis-v3.schema.json rename to spec/schemas/analysis.schema.json index 7d85a78..18b4fdf 100644 --- a/spec/schemas/analysis-v3.schema.json +++ b/spec/schemas/analysis.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/analysis-v3.schema.json", - "title": "Marqdo Analysis v3", + "$id": "https://marqdo.dev/schemas/analysis.schema.json", + "title": "Marqdo Analysis", "type": "object", "required": [ "schema", diff --git a/tests/consumers/analysis_consumer.py b/tests/consumers/analysis_consumer.py index fd83758..8670a47 100644 --- a/tests/consumers/analysis_consumer.py +++ b/tests/consumers/analysis_consumer.py @@ -1,17 +1,36 @@ #!/usr/bin/env python3 -"""Independent Analysis v2 consumer: no Marqdo/Rust imports.""" +"""Independent Analysis consumer: no Marqdo/Rust imports.""" import json import sys -if len(sys.argv) != 2: - raise SystemExit("usage: analysis_consumer.py ANALYSIS.json") +def visit(body, loop_span=None): + for statement in body: + kind = statement["kind"] + if kind == "loop": + yield from visit(statement["body"], statement["span"]) + elif kind == "branch": + for arm in statement["arms"]: + yield from visit(arm["body"], loop_span) + elif kind in ("break", "continue"): + if loop_span is None: + raise SystemExit(f"{kind} outside a projected loop") + span = statement["span"] + if not 0 <= loop_span["start"] < span["start"] < span["end"]: + raise SystemExit(f"invalid {kind} carrier span") + yield kind, loop_span["start"] + elif kind not in ("assign", "expression", "return"): + raise SystemExit(f"unsupported statement kind {kind}") + + +if sys.argv[2:] not in ([], ["--require-transfers"]) or len(sys.argv) < 2: + raise SystemExit("usage: analysis_consumer.py ANALYSIS.json [--require-transfers]") with open(sys.argv[1], encoding="utf-8") as handle: analysis = json.load(handle) if analysis.get("schema") != "marqdo.analysis": raise SystemExit("unexpected schema") -if analysis.get("schema_version") != 2: +if analysis.get("schema_version") != 3: raise SystemExit("unsupported schema_version") project = analysis["project"] @@ -21,6 +40,7 @@ if not isinstance(project.get("root_id"), str) or not project["root_id"]: raise SystemExit("bad root_id") functions = [] +transfers = [] for module in analysis["modules"]: module_id = module["id"] if "::" not in module_id or not module_id.startswith(("root:", "dep:", "std:")): @@ -45,9 +65,13 @@ for module in analysis["modules"]: if not isinstance(span.get("start"), int) or not isinstance(span.get("end"), int): raise SystemExit("bad resource span") for function in module["functions"]: - body = json.dumps(function["body"], ensure_ascii=False) - functions.append((function["id"], body)) + transfers.extend(visit(function["body"])) + functions.append(function["id"]) if not functions: raise SystemExit("no functions") print("functions=" + str(len(functions))) + +if len(sys.argv) == 3 and not transfers: + raise SystemExit("missing loop transfers") +print(f"transfers={len(transfers)}") diff --git a/tests/consumers/analysis_v3_consumer.py b/tests/consumers/analysis_v3_consumer.py deleted file mode 100644 index e532151..0000000 --- a/tests/consumers/analysis_v3_consumer.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 -"""Read loop transfers from public Analysis JSON using only Python.""" -import json -import pathlib -import sys - - -def visit(body, loop_span=None): - for statement in body: - kind = statement["kind"] - if kind == "loop": - yield from visit(statement["body"], statement["span"]) - elif kind == "branch": - for arm in statement["arms"]: - yield from visit(arm["body"], loop_span) - elif kind in ("break", "continue"): - if loop_span is None: - raise SystemExit(f"{kind} outside a projected loop") - span = statement["span"] - if not 0 <= loop_span["start"] < span["start"] < span["end"]: - raise SystemExit(f"invalid {kind} carrier span") - yield kind, loop_span["start"] - elif kind not in ("assign", "expression", "return"): - raise SystemExit(f"unsupported statement kind {kind}") - - -def main(): - if len(sys.argv) != 2: - raise SystemExit("usage: analysis_v3_consumer.py ANALYSIS.json") - analysis = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) - if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3: - raise SystemExit("unsupported Analysis schema version") - transfers = [ - transfer - for module in analysis["modules"] - for function in module["functions"] - for transfer in visit(function["body"]) - ] - if not transfers: - raise SystemExit("missing loop transfers") - print(f"transfers={len(transfers)} nearest_loops={len({target for _, target in transfers})}") - - -if __name__ == "__main__": - main() diff --git a/tests/consumers/trace_consumer.py b/tests/consumers/trace_consumer.py index 3f4a818..bc719b7 100644 --- a/tests/consumers/trace_consumer.py +++ b/tests/consumers/trace_consumer.py @@ -13,7 +13,7 @@ analysis = json.loads(analysis_bytes) with open(sys.argv[2], encoding="utf-8") as handle: trace = json.load(handle) -if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") not in (2, 3): +if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3: raise SystemExit("unsupported analysis") if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2: raise SystemExit("unsupported trace") diff --git a/tests/consumers/validate_protocols.py b/tests/consumers/validate_protocols.py index 54fe20d..b0d0cd9 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -48,19 +48,14 @@ def main(): trace = json.loads(trace_path.read_text(encoding="utf-8")) tool = json.loads(tool_path.read_text(encoding="utf-8")) - version = analysis.get("schema_version") - if version not in (2, 3): - raise SystemExit("unsupported Analysis schema version") - analysis_schema = f"analysis-v{version}.schema.json" + analysis_schema = "analysis.schema.json" require_valid(analysis_schema, analysis, "analysis") - if version == 3: - require_invalid("analysis-v2.schema.json", analysis, "legacy schema rejects v3") require_valid("trace-v2.schema.json", trace, "trace") require_valid("tool-v1.schema.json", tool, "tool") # Negative mutations: structure, version and traversal must fail closed. bad = copy.deepcopy(analysis) - bad["schema_version"] = 999 + bad["schema_version"] = 2 require_invalid(analysis_schema, bad, "analysis unsupported version") bad = copy.deepcopy(analysis) diff --git a/tools/ci/test_release_archive.py b/tools/ci/test_release_archive.py index f7478d4..a76f640 100644 --- a/tools/ci/test_release_archive.py +++ b/tools/ci/test_release_archive.py @@ -68,14 +68,9 @@ class ReleaseArchiveContractTest(unittest.TestCase): self.assertIn('"stdlib": stdlib_info', source) self.assertIn("verify_stdlib()", source) - def test_archive_analysis_metadata_preserves_default_and_declares_each_major(self) -> None: - self.smoke.verify_analysis_metadata({"analysis": 2, "analysis_versions": [2, 3]}) - for malformed in ( - {"analysis": 3, "analysis_versions": [2, 3]}, - {"analysis": 2, "analysis_versions": [2]}, - {"analysis": 2, "analysis_versions": [2, 3, 4]}, - {"analysis": 2}, - ): + def test_archive_declares_only_current_analysis_revision(self) -> None: + self.smoke.verify_analysis_metadata({"analysis": 3}) + for malformed in ({"analysis": 2}, {"analysis": 3, "analysis_versions": [3]}, {}): with self.subTest(protocols=malformed), contextlib.redirect_stderr(io.StringIO()): with self.assertRaises(SystemExit): self.smoke.verify_analysis_metadata(malformed) diff --git a/tools/release/package.py b/tools/release/package.py index 1aa695b..968a7dd 100644 --- a/tools/release/package.py +++ b/tools/release/package.py @@ -263,8 +263,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict: "binaries": binaries, "stdlib": stdlib_info, "protocols": { - "analysis": 2, - "analysis_versions": [2, 3], + "analysis": 3, "trace": 2, "execution_events": 1, "tool": 1, diff --git a/tools/release/smoke.py b/tools/release/smoke.py index 0b5afa2..2a27c82 100644 --- a/tools/release/smoke.py +++ b/tools/release/smoke.py @@ -167,17 +167,16 @@ class Runner: fail(f"`marqdo {' '.join(args)} --json` is not JSON: {error}\n{result.stdout}") +ANALYSIS_VERSION = 3 ANALYSIS_CASES = { - 2: ("examples/multi-module/index.mq.md", "analysis_consumer.py"), - 3: ("examples/control-flow.mq.md", "analysis_v3_consumer.py"), + "simple": ("examples/multi-module/index.mq.md", ()), + "control": ("examples/control-flow.mq.md", ("--require-transfers",)), } def verify_analysis_metadata(protocols: dict) -> None: - if protocols.get("analysis") != min(ANALYSIS_CASES): - fail("RELEASE_INFO.json does not identify the default Analysis version") - if protocols.get("analysis_versions") != sorted(ANALYSIS_CASES): - fail("RELEASE_INFO.json Analysis versions do not match the archive smoke cases") + if protocols.get("analysis") != ANALYSIS_VERSION or "analysis_versions" in protocols: + fail("RELEASE_INFO.json must identify only the current Analysis revision") def run_consumer(install: Path, consumer: str, *paths: Path) -> None: @@ -193,17 +192,17 @@ def run_consumer(install: Path, consumer: str, *paths: Path) -> None: def verify_analysis_protocols(runner: Runner, install: Path, info: dict) -> None: protocols = info["protocols"] verify_analysis_metadata(protocols) - for schema_version, (source, consumer) in ANALYSIS_CASES.items(): - analysis = install / f"analysis-v{schema_version}.json" - trace = install / f"trace-for-analysis-v{schema_version}.json" + for case, (source, options) in ANALYSIS_CASES.items(): + analysis = install / f"analysis-{case}.json" + trace = install / f"trace-for-analysis-{case}.json" runner.run(["check", source, "--emit", str(analysis)]) document = json.loads(analysis.read_text(encoding="utf-8")) - if document.get("schema") != "marqdo.analysis" or document.get("schema_version") != schema_version: - fail(f"{source} did not produce Analysis v{schema_version}") + if document.get("schema") != "marqdo.analysis" or document.get("schema_version") != ANALYSIS_VERSION: + fail(f"{source} did not produce Analysis revision {ANALYSIS_VERSION}") if document.get("producer", {}).get("version") != info["product_version"]: fail("Analysis producer.version does not match the released product version") runner.run(["run", source, "--trace-file", str(trace)]) - run_consumer(install, consumer, analysis) + run_consumer(install, "analysis_consumer.py", analysis, *options) run_consumer(install, "trace_consumer.py", analysis, trace) # CI installs jsonschema. The standalone smoke can use stdlib Python. From f83d992c61b428f450bb95a3ea1c1ee652072b67 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 14:23:48 +0800 Subject: [PATCH 03/17] tool: require exact current contracts without negotiation --- crates/cli/src/tool.rs | 223 +++++++----------- crates/cli/tests/examples_r6.rs | 2 +- crates/cli/tests/tool_protocol.rs | 149 +++++------- .../0068-single-current-public-contracts.md | 4 +- .../tool-samples/sample-knowledge/tool.json | 8 +- examples/tool-samples/sample-proof/tool.json | 8 +- examples/tool-samples/sample-view/src/main.rs | 2 +- examples/tool-samples/sample-view/tool.json | 7 +- examples/tool-unknown-name/README.md | 2 +- .../tool-unknown-name/bin/marqdo-benchmark | 2 +- examples/tool-unknown-name/tool.json | 4 +- spec/cli-tool.md | 43 ++++ ...ol-v1.schema.json => cli-tool.schema.json} | 38 ++- spec/tool-v1.md | 89 ------- tests/consumers/validate_protocols.py | 6 +- tests/fixtures/tool_echo.rs | 8 +- 16 files changed, 229 insertions(+), 366 deletions(-) create mode 100644 spec/cli-tool.md rename spec/schemas/{tool-v1.schema.json => cli-tool.schema.json} (59%) delete mode 100644 spec/tool-v1.md diff --git a/crates/cli/src/tool.rs b/crates/cli/src/tool.rs index 474dc8e..1881677 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -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,19 +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::SCHEMA_VERSION], - trace: &[2], -}; +const API_REVISION: u32 = 1; const BUILTIN_COMMANDS: &[&str] = &[ "init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync", @@ -41,6 +29,7 @@ const BUILTIN_COMMANDS: &[&str] = &[ ]; #[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] struct ToolManifest { schema: String, schema_version: u32, @@ -48,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, - #[serde(default)] - analysis: Option>, - #[serde(default)] - trace: Option>, +#[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, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "read_requirement" + )] + observation: Option, } -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct RecordedCompatibility { - #[serde(default, skip_serializing_if = "Option::is_none")] - marqdo: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - analysis: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - trace: Option>, -} - -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, D::Error> { + u32::deserialize(reader).map(Some) } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -90,6 +70,7 @@ struct BundleEntry { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] struct ToolRecord { record_version: u32, command: String, @@ -100,8 +81,7 @@ struct ToolRecord { bundle_sha256: String, source: String, schema_version: u32, - #[serde(default)] - compatibility: RecordedCompatibility, + requires: Requirements, } /// `marqdo tool install `. @@ -201,11 +181,7 @@ fn install_inner(manifest_path: &Path) -> Result { 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}"))?; @@ -226,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) } } @@ -235,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) { @@ -262,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::execution_events::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 { - 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()) @@ -483,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(); @@ -568,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() { @@ -582,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 `" @@ -593,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) => { @@ -627,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) => { @@ -690,7 +629,10 @@ fn installed_records() -> Result, 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); } } @@ -698,13 +640,26 @@ fn installed_records() -> Result, String> { } fn load_record(dir: &Path) -> Result { - 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) } diff --git a/crates/cli/tests/examples_r6.rs b/crates/cli/tests/examples_r6.rs index 64f35db..0cf6306 100644 --- a/crates/cli/tests/examples_r6.rs +++ b/crates/cli/tests/examples_r6.rs @@ -133,7 +133,7 @@ fn unknown_tool_name_installs_and_dispatches() { #[test] fn public_schemas_are_valid_json_and_versioned() { - for name in ["analysis", "trace-v1", "tool-v1", "execution-events-v1"] { + for name in ["analysis", "trace-v1", "cli-tool", "execution-events-v1"] { let path = repo() .join("spec/schemas") .join(format!("{name}.schema.json")); diff --git a/crates/cli/tests/tool_protocol.rs b/crates/cli/tests/tool_protocol.rs index 7d91718..7612823 100644 --- a/crates/cli/tests/tool_protocol.rs +++ b/crates/cli/tests/tool_protocol.rs @@ -1,4 +1,4 @@ -//! 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. @@ -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(); @@ -142,7 +142,7 @@ fn write_sample_from_source(dir: &Path, command: &str) -> PathBuf { std::fs::write( &manifest, format!( - r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","compatibility":{{"marqdo":">=3.0.0-beta.1,<4.0.0","analysis":[2],"trace":[2]}}}}"# + r#"{{"schema":"marqdo.cli-tool","schema_version":1,"name":"demo.{command}","version":"0.1.0","command":"{command}","entrypoint":"{entrypoint}","requires":{{"api_revision":1,"analysis":3,"observation":1}}}}"# ), ) .unwrap(); @@ -200,7 +200,7 @@ 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}"); @@ -245,7 +245,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 +301,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 +309,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] @@ -355,58 +355,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 +463,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) - ); - } - } -} diff --git a/docs/adr/0068-single-current-public-contracts.md b/docs/adr/0068-single-current-public-contracts.md index 59ab16d..89dfcaf 100644 --- a/docs/adr/0068-single-current-public-contracts.md +++ b/docs/adr/0068-single-current-public-contracts.md @@ -27,10 +27,12 @@ requires its own compatibility policy. `run` and `call` use `--output text|json|jsonl` and `--observation-file PATH`. Capture selections and budgets apply to all observation destinations. -- Tool manifests use `marqdo.cli-tool` revision 2, with a required +- Tool manifests use `marqdo.cli-tool` with its existing revision 1, a required `requires.api_revision: 1` and optional exact Analysis and Observation requirements. Reinstall tools registered under earlier formats. The existing Tool subcommands and external dispatch suffice for this workflow. + Required fields and strict validation reject retired input at the existing + format identifier. This change introduces no new numeric protocol versions. - Keep the three current extension descriptors. Callable exports, resource rights and foreign interpreter selection have independent validation and lifecycles. Share value encoding and equivalent process transport diff --git a/examples/tool-samples/sample-knowledge/tool.json b/examples/tool-samples/sample-knowledge/tool.json index 8f9af9a..0be35cd 100644 --- a/examples/tool-samples/sample-knowledge/tool.json +++ b/examples/tool-samples/sample-knowledge/tool.json @@ -5,9 +5,9 @@ "version": "0.1.0", "command": "sample-knowledge", "entrypoint": "bin/sample-knowledge", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3, + "observation": 1 } } diff --git a/examples/tool-samples/sample-proof/tool.json b/examples/tool-samples/sample-proof/tool.json index cbe2533..2a2ec51 100644 --- a/examples/tool-samples/sample-proof/tool.json +++ b/examples/tool-samples/sample-proof/tool.json @@ -5,9 +5,9 @@ "version": "0.1.0", "command": "sample-proof", "entrypoint": "bin/sample-proof", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3, + "observation": 1 } } diff --git a/examples/tool-samples/sample-view/src/main.rs b/examples/tool-samples/sample-view/src/main.rs index 6f18309..6cd830f 100644 --- a/examples/tool-samples/sample-view/src/main.rs +++ b/examples/tool-samples/sample-view/src/main.rs @@ -48,7 +48,7 @@ fn main() { std::process::exit(1); } let version = number_field(&json, "schema_version").unwrap_or_default(); - if version != 2 { + if version != 3 { eprintln!("sample-view: unsupported Analysis version {version}"); std::process::exit(1); } diff --git a/examples/tool-samples/sample-view/tool.json b/examples/tool-samples/sample-view/tool.json index 8f5e91a..e7134d0 100644 --- a/examples/tool-samples/sample-view/tool.json +++ b/examples/tool-samples/sample-view/tool.json @@ -5,9 +5,8 @@ "version": "0.1.0", "command": "sample-view", "entrypoint": "bin/sample-view", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] + "requires": { + "api_revision": 1, + "analysis": 3 } } diff --git a/examples/tool-unknown-name/README.md b/examples/tool-unknown-name/README.md index 99147e7..b688668 100644 --- a/examples/tool-unknown-name/README.md +++ b/examples/tool-unknown-name/README.md @@ -12,7 +12,7 @@ marqdo tool remove benchmark ``` The executable receives the remaining arguments verbatim, inherits stdio/cwd, -and its exit code is propagated. `MARQDO_TOOL_PROTOCOL=1` and `MARQDO_BIN` are +and its exit code is propagated. `MARQDO_API_REVISION=1` and `MARQDO_BIN` are provided for tools that need `check --emit`/`run --trace-file`. A Tool is a user-run native process. It is **not** a C ABI plugin, a foreign diff --git a/examples/tool-unknown-name/bin/marqdo-benchmark b/examples/tool-unknown-name/bin/marqdo-benchmark index ce08edc..9be771e 100755 --- a/examples/tool-unknown-name/bin/marqdo-benchmark +++ b/examples/tool-unknown-name/bin/marqdo-benchmark @@ -1,7 +1,7 @@ #!/bin/sh # A deliberately tool-specific program: the Marqdo CLI knows no `benchmark` # command or its options. -printf 'benchmark tool: protocol=%s\n' "${MARQDO_TOOL_PROTOCOL:-unset}" +printf 'benchmark tool: protocol=%s\n' "${MARQDO_API_REVISION:-unset}" for argument in "$@"; do printf 'arg=%s\n' "$argument" done diff --git a/examples/tool-unknown-name/tool.json b/examples/tool-unknown-name/tool.json index 1080666..007e921 100644 --- a/examples/tool-unknown-name/tool.json +++ b/examples/tool-unknown-name/tool.json @@ -5,7 +5,7 @@ "version": "0.1.0", "command": "benchmark", "entrypoint": "bin/marqdo-benchmark", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0" + "requires": { + "api_revision": 1 } } diff --git a/spec/cli-tool.md b/spec/cli-tool.md new file mode 100644 index 0000000..2f6e729 --- /dev/null +++ b/spec/cli-tool.md @@ -0,0 +1,43 @@ +# Marqdo CLI Tool + +A CLI Tool is an independent executable registered as a Marqdo subcommand. +It uses public CLI commands and runs with the invoking user's OS permissions. +Plugin trust, Provider grants, Foreign grants and the language sandbox apply +only at their own boundaries. + +## Manifest + +Put `tool.json` alongside the package's executable and support files. + +```json +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "demo.viewer", + "version": "0.3.0", + "command": "demo-view", + "entrypoint": "bin/demo-view", + "requires": {"api_revision": 1, "analysis": 3, "observation": 1} +} +``` + +The [manifest schema](schemas/cli-tool.schema.json) is authoritative. +`version` identifies the tool package and uses SemVer. `api_revision` is +required. Declare `analysis` and `observation` only when the tool consumes +those contracts. Every declared requirement is a single exact integer. + +## Install and run + +Use `marqdo tool install PATH`, `marqdo tool list` and +`marqdo tool remove COMMAND`. Run this sample as `marqdo demo-view ...`. +Commands must match `^[a-z][a-z0-9-]*$` and be available. The entrypoint +must be an executable regular file within the bundle. Symlinks, special +files and root `record.json` are rejected. The CLI verifies and installs +the entire bundle atomically, then checks the installed file set and +SHA-256 digests before execution. + +The process inherits standard streams and receives the original arguments, +`MARQDO_BIN` and `MARQDO_API_REVISION`. Tool discovery is explicit through +the install directory, which may be set with `MARQDO_TOOL_HOME`. +To replace a retired registration, remove its command, rebuild the tool +with this manifest and install the rebuilt bundle. diff --git a/spec/schemas/tool-v1.schema.json b/spec/schemas/cli-tool.schema.json similarity index 59% rename from spec/schemas/tool-v1.schema.json rename to spec/schemas/cli-tool.schema.json index e8d1be4..6c7ae9e 100644 --- a/spec/schemas/tool-v1.schema.json +++ b/spec/schemas/cli-tool.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/tool-v1.schema.json", - "title": "Marqdo CLI Tool Manifest v1", + "$id": "https://marqdo.dev/schemas/cli-tool.schema.json", + "title": "Marqdo CLI Tool Manifest", "type": "object", "required": [ "schema", @@ -9,7 +9,8 @@ "name", "version", "command", - "entrypoint" + "entrypoint", + "requires" ], "properties": { "schema": { @@ -35,31 +36,24 @@ "minLength": 1, "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$" }, - "compatibility": { + "requires": { "type": "object", + "required": [ + "api_revision" + ], + "additionalProperties": false, "properties": { - "marqdo": { - "type": "string" + "api_revision": { + "const": 1 }, "analysis": { - "type": "array", - "minItems": 1, - "items": { - "type": "integer", - "minimum": 1 - } + "const": 3 }, - "trace": { - "type": "array", - "minItems": 1, - "items": { - "type": "integer", - "minimum": 1 - } + "observation": { + "const": 1 } - }, - "additionalProperties": true + } } }, - "additionalProperties": true + "additionalProperties": false } diff --git a/spec/tool-v1.md b/spec/tool-v1.md deleted file mode 100644 index 4a7967b..0000000 --- a/spec/tool-v1.md +++ /dev/null @@ -1,89 +0,0 @@ -# Marqdo CLI Tool Protocol v1 — 通用外部工具协议 - -> 状态:**Implemented / frozen protocol v1**(独立于产品版本)。核心根命令同样优先;任何官方/第三方工具一视同仁;该协议**不是** C ABI 插件协议。安装、校验、分发与协议协商均已实现并由 `crates/cli/tests/tool_protocol.rs` 覆盖。 - -## 1. 范围与不变量 - -- Core 不含具体 Tool `command` 名的注册、适配、白名单、下载地址;仅维护自身原生命令集合与用户安装的工具注册记录。 -- 任何语言写成的**独立可执行工具**均可安装;CLI 不链接其 Rust crate、不解释其业务子命令。 -- 最小实现只支持 `marqdo tool install /path/to/tool.json`、`marqdo tool list`、`marqdo tool remove `,以及未知顶层命令的已注册工具回退。 -- 无索引服务、无网络时一样能够本地安装;`marqdo tool install ` 的远程名称解析是以后独立的可选索引能力,不要求 core 自带官方/社区工具列表。 -- 工具仅能调用公开的 `marqdo` 命令/Analysis/Trace 文件协议;不得依赖私有 `marqdo-ir` 序列化、宿主内存指针或“已知官方工具名”。 - -## 2. 安装清单 - -`tool.json` 使用 UTF-8 JSON,v1 的最小规范清单示例: - -```json -{ - "schema": "marqdo.cli-tool", - "schema_version": 1, - "name": "benchmark", - "version": "0.1.0", - "command": "benchmark", - "entrypoint": "bin/marqdo-benchmark", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2] - } -} -``` - -类型:`schema` 固定字符串,`schema_version` 正整数(首版仅 1),`name`/`version`/`command`/`entrypoint` 非空字符串,`version` 必须是合法 SemVer,`compatibility.marqdo` 必须是可解析的 SemVer 范围,`analysis`、`trace` 为可选的非空正整数数组;仅当工具使用该数据协议时声明。当前开发分支提供 Analysis v2/v3 与 Trace v2。声明与对应版本集合无交集时,安装和分发会拒绝。未来可以增加可选字段,但不得改变现有字段含义。 - -`command`:建议 `^[a-z][a-z0-9-]*$`,不得与任何内置命令或保留参数冲突;同一注册表中命令唯一,名字冲突拒绝且不覆盖。`entrypoint`:包内受控相对路径,不能是绝对路径、`.`/`..` 跳出根目录、符号链接逃逸或可直接解释的任意 shell 片段。真实文件应可执行并与目标平台匹配;若扩展名或平台格式与 OS 不兼容应显式失败。 - -## 3. 注册与验证 - -本地安装流程:读取用户指定的 `tool.json` → 校验 schema、SemVer 与协议交集 → 校验 entrypoint 不越界 → 检查内置/已注册命令冲突 → 收集**整包**规范化文件清单(相对路径、大小、SHA-256,拒绝符号链接/特殊文件/非 UTF-8 路径,限制文件数与总字节)→ 以临时目录按同一清单复制 → 对 staging 重新计算清单并要求逐项一致 → 写入记录并原子 rename 发布。失败时清理 staging,不留下半安装。 - -注册记录(`record_version: 2`)包含 `command`、`name`、`version`、`entrypoint`(包内相对路径)、`bundle[]`(每文件 path/size/sha256)、`bundle_sha256`、`source`、`schema_version`、`compatibility`。`bundle_sha256` 是排序后 `path\0size\0sha256\n` 的 SHA-256。注册不是来源认证;摘要只能检查安装后未被改变。对互联网下载必须额外有可信索引给出的摘要/签名;禁止在用户未同意前自动从网络下载。 - -运行时在启动前重新计算磁盘上的整包清单,与记录逐项比较(排除根 `record.json`),并验证 entrypoint 属于该清单、记录命令与请求命令一致、版本/协议仍兼容。任何不一致拒绝而非降低校验强度。旧记录版本不复用,提示重新安装。实现优先使用正确的跨平台配置目录 API,不要把 `~` 当成可移植的用户目录。多个用户/多个版本并存属于独立目录隔离;同一个命令只能解析到一个注册项,除非未来另有显式版本选择规范。 - -## 4. 分发算法 - -输入 `marqdo `,先检查内置命令,内置优先;否则从已安装的只读注册映射查找 ``。找到则重新协商 Tool/分析/追踪协议,验证整包清单与 entrypoint,使用 `Command::new(entrypoint).args(args)` **直接启动**,从调用者原样保留 `cwd`、`stdin/stdout/stderr` 和可保留的环境(敏感环境变量策略另行安全审计),原样传播退出状态;绝不调用 `sh -c`、不拼接命令字符串。 - -工具负责自己的命令层级与帮助,如 `marqdo benchmark run .`、`marqdo benchmark --help`。CLI 不读取或修改工具业务选项。Rust `clap` 可通过单一 `external_subcommand` 捕获未知子命令,但必须保留 `OsString` 原样传参;不能让工具要求 CLI 添加 `Command::View` 等专门枚举项。不要求工具在处理 `--help` 时调用核心。未知命令时报错;即使 PATH 中存在 `marqdo-`,**没有显式注册也不能执行它**。 - -可选辅助环境:`MARQDO_BIN`(当前核心 CLI 的绝对路径),`MARQDO_TOOL_PROTOCOL=1`;仅当工具声明并协商了对应协议时,额外设置 `MARQDO_PROTOCOL_ANALYSIS` 与/或 `MARQDO_PROTOCOL_TRACE`,值是双方支持的最高版本。 -Analysis 写入器按项目内容选择版本。工具应先检查输出的 `schema_version`,支持两版的工具声明 `analysis: [2, 3]`。工具通过此路径运行 `marqdo check ... --emit ...` 和 `marqdo run ... --trace-file ...`,不拥有额外宿主内部 API。不得自动将密钥、项目能力授予记录、ABI 插件加载句柄或用户外联会话传给工具。 - -## 5. 三个独立安全域 - -1. **Tool CLI 进程**:用户主动安装并运行的原生程序,按当前用户身份执行。它**不受** Marqdo 的 `pure/project/strict` `.mq.md` 语言沙箱自动约束;工具执行不是安装后自动执行。 -2. **Marqdo 程序**:通过 `marqdo run/call` 和 `CapabilityHost` 执行,严格隔离需受支持的 OS adapter。 -3. **运行时 ABI 插件**:扩展可调用函数,必须有自己版本化 C ABI、显式信任或 isolated worker,和 Tool 注册表严格区分。 - -## 6. 向后兼容 - -`schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2, 3]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。 - -原生命令集合是保留命名空间;未来新增与社区工具冲突的新核心顶层命令属于破坏性变化,必须经过 ADR、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。 - -## 7. 正反向黑盒测试(完成标准) - -| 用例 | 期望 | -|---|---| -| `tool install` 本地清单 `benchmark` 后调用 `marqdo benchmark run .` | 无需 CLI 源码改动,可原样传参并传播退出码 | -| 将工具名改成 `lintx`,重建外部程序但不重建 CLI | 能直接注册和调用 | -| 工具没有 `analysis/trace` 兼容字段 | 可以独立使用;不强制创建分析或运行记录 | -| 工具声明 `analysis:[2]`/`trace:[2]` | 安装并分发,环境变量反映协商结果 | -| 工具声明 `analysis:[1]`、`[]` 或与支持集无交集 | 安装/分发拒绝,错误含 `tool.protocol_incompatible`,不回退猜测 | -| 工具注册名冲突 `run` 或另一已安装工具 | 拒绝,不覆盖 | -| PATH 中存在同名 `marqdo-benchmark` 但未注册 | 未知命令错误,不执行 PATH 程序 | -| 篡改已安装二进制的一个字节 | 拒绝启动,指明整包摘要不匹配 | -| 仅篡改辅助脚本、增加未列文件或删除文件 | 拒绝启动,整包清单不一致 | -| 源包包含根 `record.json` | 安装拒绝(记录文件由核心保留) | -| `entrypoint` 是 `../outside`、绝对路径或越界符号链接 | 安装失败,无残留注册 | -| 安装时被杀/写盘失败/并发安装 | 不留下半安装或不一致的注册 | -| `marqdo tool remove benchmark` | 注册与受控安装制品删除;其他工具正常 | -| `--help`、复杂 Unicode 参数和 stdin/stdout | 工具获得原样参数/流,核心不解释私有业务语义 | - -验收同时要求 `marqdo-cli` **不包含** `view/knowledge/prove/benchmark` 的特殊分发匹配、下载 URL、业务参数类型及平台分支。把测试工具迁移至新的仓库,并在不同机器上单独编译安装后仍可通过本协议。 - -## 8. 参考 - -- Cargo External Tools: https://doc.rust-lang.org/cargo/reference/external-tools.html —— 可扩展子命令而无需修改核心。 -- kubectl plugins: https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/ —— 独立可执行文件、自动分发的经验;其默认 PATH 信任模型不直接沿用。 diff --git a/tests/consumers/validate_protocols.py b/tests/consumers/validate_protocols.py index b0d0cd9..c5c0ab7 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -51,7 +51,7 @@ def main(): analysis_schema = "analysis.schema.json" require_valid(analysis_schema, analysis, "analysis") require_valid("trace-v2.schema.json", trace, "trace") - require_valid("tool-v1.schema.json", tool, "tool") + require_valid("cli-tool.schema.json", tool, "tool") # Negative mutations: structure, version and traversal must fail closed. bad = copy.deepcopy(analysis) @@ -76,11 +76,11 @@ def main(): bad = copy.deepcopy(tool) bad["entrypoint"] = "../outside" - require_invalid("tool-v1.schema.json", bad, "tool traversal entrypoint") + require_invalid("cli-tool.schema.json", bad, "tool traversal entrypoint") bad = copy.deepcopy(tool) bad["version"] = "not semver" - require_invalid("tool-v1.schema.json", bad, "tool invalid version") + require_invalid("cli-tool.schema.json", bad, "tool invalid version") print( "validated analysis/trace/tool artifacts " diff --git a/tests/fixtures/tool_echo.rs b/tests/fixtures/tool_echo.rs index 35e4dcc..2d20cf1 100644 --- a/tests/fixtures/tool_echo.rs +++ b/tests/fixtures/tool_echo.rs @@ -13,14 +13,8 @@ fn main() { } println!( "protocol={}", - std::env::var("MARQDO_TOOL_PROTOCOL").unwrap_or_default() + std::env::var("MARQDO_API_REVISION").unwrap_or_default() ); - if let Ok(value) = std::env::var("MARQDO_PROTOCOL_ANALYSIS") { - println!("analysis={value}"); - } - if let Ok(value) = std::env::var("MARQDO_PROTOCOL_TRACE") { - println!("trace={value}"); - } let mut stdin = String::new(); let _ = std::io::stdin().read_to_string(&mut stdin); if !stdin.is_empty() { From 404d559b869ee87632e974eb2cc807972a9759bd Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 24 Nov 2026 15:30:18 +0800 Subject: [PATCH 04/17] observation: deliver one execution event sequence to stream and snapshot --- .github/workflows/ci.yml | 57 +- README.md | 19 +- crates/cli/Cargo.toml | 4 +- crates/cli/src/analysis.rs | 8 +- crates/cli/src/commands.rs | 101 +-- crates/cli/src/commands/run.rs | 398 ++------ crates/cli/src/commands/sandbox.rs | 13 +- crates/cli/src/main.rs | 134 +-- .../{execution_events.rs => observation.rs} | 293 ++++-- crates/cli/src/tool.rs | 2 +- crates/cli/src/trace.rs | 144 --- ...lysis_trace.rs => analysis_observation.rs} | 61 +- crates/cli/tests/callable_resolution.rs | 18 +- crates/cli/tests/examples_r6.rs | 32 +- crates/cli/tests/http_over_tcp.rs | 18 +- crates/cli/tests/integration_cli.rs | 154 ++-- .../{execution_events.rs => observation.rs} | 195 ++-- crates/cli/tests/p2_closure.rs | 59 +- crates/cli/tests/print_routing.rs | 4 +- crates/cli/tests/provider_cli.rs | 77 +- crates/cli/tests/resource_streams.rs | 96 +- crates/cli/tests/stdlib_http.rs | 11 +- crates/cli/tests/stdlib_product.rs | 113 ++- crates/cli/tests/stdlib_table.rs | 11 +- crates/cli/tests/support/observation.rs | 58 ++ crates/cli/tests/tool_protocol.rs | 42 +- crates/marqdo-host/src/host.rs | 172 +--- crates/marqdo-host/src/host/dispatch.rs | 28 +- crates/marqdo-host/src/host/effects.rs | 44 - crates/marqdo-host/src/host/resource_ops.rs | 73 +- .../marqdo-host/src/host/resource_requests.rs | 109 +-- crates/marqdo-host/src/lib.rs | 4 +- crates/marqdo-host/src/observe.rs | 14 +- crates/marqdo-host/src/trace.rs | 180 ---- crates/marqdo-runtime/src/builtins_impl.rs | 14 +- crates/marqdo-runtime/src/interpreter.rs | 72 +- docs/STATUS.md | 14 +- docs/adr/0006-cli-contract.md | 3 + docs/adr/0013-generic-cli-tool-protocol.md | 3 + docs/adr/0015-public-analysis-trace-v1.md | 3 + ...time-observability-and-execution-events.md | 3 + docs/adr/0067-structured-control-flow.md | 3 + docs/architecture/CURRENT.md | 55 +- docs/contributor-guide.md | 13 +- docs/developers/README.md | 2 +- docs/developers/analysis-observation.md | 43 + docs/developers/analysis-trace.md | 121 --- docs/developers/compatibility.md | 2 +- docs/developers/quickstart.md | 8 +- docs/developers/release-limits.md | 2 +- docs/developers/tools.md | 4 +- .../tool-samples/sample-knowledge/src/main.rs | 19 +- .../tool-samples/sample-knowledge/tool.json | 3 +- .../tool-samples/sample-proof/src/main.rs | 27 +- examples/tool-samples/sample-view/src/main.rs | 4 +- spec/execution-events-v1.md | 340 ------- spec/observation.md | 78 ++ spec/schemas/execution-events-v1.schema.json | 291 ------ spec/schemas/observation-event.schema.json | 855 ++++++++++++++++++ spec/schemas/observation-file.schema.json | 122 +++ spec/schemas/trace-v1.schema.json | 55 -- spec/schemas/trace-v2.schema.json | 86 -- spec/trace-v1.md | 74 -- spec/trace-v2.md | 119 --- tests/consumers/execution_events_consumer.py | 145 --- .../execution-events/invalid/bad-chunk.json | 1 - .../execution-events/invalid/bad-span.json | 1 - .../invalid/bad-terminal.json | 1 - .../invalid/empty-run-id.json | 1 - .../invalid/missing-payload.json | 1 - .../execution-events/invalid/missing-seq.json | 1 - .../invalid/negative-seq.json | 1 - .../invalid/unknown-major.json | 1 - .../execution-events/valid/full.jsonl | 14 - .../execution-events/valid/minimal.jsonl | 6 - .../README.md | 8 +- .../basic.mq.md | 0 .../observation/invalid/bad-chunk.json | 1 + .../observation/invalid/bad-span.json | 1 + .../observation/invalid/bad-terminal.json | 1 + .../observation/invalid/empty-run-id.json | 1 + .../observation/invalid/missing-payload.json | 1 + .../observation/invalid/missing-seq.json | 1 + .../observation/invalid/negative-seq.json | 1 + .../observation/invalid/unknown-major.json | 1 + .../realtime.mq.md | 0 .../structure.mq.md | 0 .../fixtures/observation/valid/full.jsonl | 14 + .../fixtures/observation/valid/minimal.jsonl | 6 + .../values.mq.md | 0 tests/consumers/observation_consumer.py | 216 +++++ tests/consumers/trace_consumer.py | 53 -- tests/consumers/validate_protocols.py | 30 +- tests/security/run-lane.sh | 13 +- tools/release/cold-install.sh | 5 +- tools/release/package.py | 3 +- tools/release/smoke.py | 87 +- 97 files changed, 2672 insertions(+), 3128 deletions(-) rename crates/cli/src/{execution_events.rs => observation.rs} (63%) delete mode 100644 crates/cli/src/trace.rs rename crates/cli/tests/{analysis_trace.rs => analysis_observation.rs} (90%) rename crates/cli/tests/{execution_events.rs => observation.rs} (86%) create mode 100644 crates/cli/tests/support/observation.rs delete mode 100644 crates/marqdo-host/src/host/effects.rs delete mode 100644 crates/marqdo-host/src/trace.rs create mode 100644 docs/developers/analysis-observation.md delete mode 100644 docs/developers/analysis-trace.md delete mode 100644 spec/execution-events-v1.md create mode 100644 spec/observation.md delete mode 100644 spec/schemas/execution-events-v1.schema.json create mode 100644 spec/schemas/observation-event.schema.json create mode 100644 spec/schemas/observation-file.schema.json delete mode 100644 spec/schemas/trace-v1.schema.json delete mode 100644 spec/schemas/trace-v2.schema.json delete mode 100644 spec/trace-v1.md delete mode 100644 spec/trace-v2.md delete mode 100644 tests/consumers/execution_events_consumer.py delete mode 100644 tests/consumers/fixtures/execution-events/invalid/bad-chunk.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/bad-span.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/bad-terminal.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/empty-run-id.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/missing-payload.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/missing-seq.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/negative-seq.json delete mode 100644 tests/consumers/fixtures/execution-events/invalid/unknown-major.json delete mode 100644 tests/consumers/fixtures/execution-events/valid/full.jsonl delete mode 100644 tests/consumers/fixtures/execution-events/valid/minimal.jsonl rename tests/consumers/fixtures/{execution-events => observation}/README.md (73%) rename tests/consumers/fixtures/{execution-events => observation}/basic.mq.md (100%) create mode 100644 tests/consumers/fixtures/observation/invalid/bad-chunk.json create mode 100644 tests/consumers/fixtures/observation/invalid/bad-span.json create mode 100644 tests/consumers/fixtures/observation/invalid/bad-terminal.json create mode 100644 tests/consumers/fixtures/observation/invalid/empty-run-id.json create mode 100644 tests/consumers/fixtures/observation/invalid/missing-payload.json create mode 100644 tests/consumers/fixtures/observation/invalid/missing-seq.json create mode 100644 tests/consumers/fixtures/observation/invalid/negative-seq.json create mode 100644 tests/consumers/fixtures/observation/invalid/unknown-major.json rename tests/consumers/fixtures/{execution-events => observation}/realtime.mq.md (100%) rename tests/consumers/fixtures/{execution-events => observation}/structure.mq.md (100%) create mode 100644 tests/consumers/fixtures/observation/valid/full.jsonl create mode 100644 tests/consumers/fixtures/observation/valid/minimal.jsonl rename tests/consumers/fixtures/{execution-events => observation}/values.mq.md (100%) create mode 100644 tests/consumers/observation_consumer.py delete mode 100644 tests/consumers/trace_consumer.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d98c1c..4071633 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,16 +61,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 \ @@ -108,21 +108,34 @@ jobs: ./target/debug/marqdo check examples/multi-module/index.mq.md --refs \ --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-simple.json /tmp/trace-v2.json examples/tool-unknown-name/tool.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/trace_consumer.py \ - /tmp/analysis-simple.json /tmp/trace-v2.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-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-control.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json + /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/trace_consumer.py /tmp/analysis-control.json /tmp/control-trace-v2.json - python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl + 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 cross-platform: name: runtime contract (${{ matrix.os }}) @@ -154,7 +167,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 @@ -162,9 +175,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: | @@ -180,16 +193,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: diff --git a/README.md b/README.md index 3f79c57..2a1bd1a 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ marqdo init demo cd demo marqdo check index.mq.md marqdo run index.mq.md # executes ## @exec main -marqdo run index.mq.md --event-stream jsonl # live Execution Events v1 NDJSON +marqdo 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 @@ -232,11 +232,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: @@ -356,15 +355,15 @@ 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); JSON Schemas in [`spec/schemas/`](spec/schemas/). * [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS` workflow. @@ -432,7 +431,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 ``` diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index f364534..f58f8d4 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -28,10 +28,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 } diff --git a/crates/cli/src/analysis.rs b/crates/cli/src/analysis.rs index 93d7fe1..e239f1b 100644 --- a/crates/cli/src/analysis.rs +++ b/crates/cli/src/analysis.rs @@ -76,11 +76,9 @@ fn encode(project: &LoadedProject) -> Result, String> { .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"")) +/// SHA-256 of the exact emitted Analysis bytes. +pub fn digest(project: &LoadedProject) -> Result { + encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes))) } /// Atomically write the projection. An error must not leave a stale success diff --git a/crates/cli/src/commands.rs b/crates/cli/src/commands.rs index f0003da..b33a93b 100644 --- a/crates/cli/src/commands.rs +++ b/crates/cli/src/commands.rs @@ -29,6 +29,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}; @@ -217,25 +218,6 @@ fn resolve_link( } } -/// 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 +229,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::(&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 +257,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 +298,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::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 +334,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), } } @@ -544,7 +531,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 +540,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 }); diff --git a/crates/cli/src/commands/run.rs b/crates/cli/src/commands/run.rs index ff57ef2..76fff9e 100644 --- a/crates/cli/src/commands/run.rs +++ b/crates/cli/src/commands/run.rs @@ -4,46 +4,59 @@ //! 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, 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; + } + // Open before preparation so option, compile and authorization failures + // can still publish a rejection on the requested observation destination. + let strict_destination_rejected = settings.mode == "strict" + && (observation.output == OutputFormat::Jsonl || observation.file.is_some()); + let mut destinations = observation.clone(); + if strict_destination_rejected { + destinations.file = None; + } + let events = if destinations.enabled() { + match ObservationSession::open(&destinations) { + Ok(events) => Some(events), + Err(error) => return transport_failure(&error), } } else { - match prepare_project(file, json, &settings.plugins) { - Ok(prepared) => prepared, - Err(code) => return code, - } + None + }; + let stream = events.as_ref(); + if strict_destination_rejected { + return fail( + stream, + "strict", + "strict.unsupported_grant", + "strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations", + 2, + ); + } + let named_args = match named_args { + Ok(args) => args, + Err(message) => return fail(stream, "prepare", "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), }; let extension_sources = prepared.loaded.extension_sources.clone(); let project = prepared.loaded; @@ -64,16 +77,8 @@ 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(&project.diagnostics)); + eprintln!("error: refusing to run a project with compile errors"); return 1; } let warnings: Vec = project @@ -82,21 +87,13 @@ pub fn execute( .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 +112,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 +133,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 +143,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 +160,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 +169,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 +177,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 +191,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 +205,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 +225,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 +240,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,17 +248,16 @@ 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 @@ -344,12 +266,9 @@ pub fn execute( { 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 +281,6 @@ pub fn execute( ) { return fail( stream, - json, - command_name, "authorization", "ext.plugin_load_failed", &message, @@ -376,8 +293,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 +308,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 +326,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 = named_args .iter() @@ -435,7 +342,10 @@ 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 = match crate::analysis::digest(&project) { + Ok(digest) => digest, + Err(error) => return fail(Some(stream), "prepare", "cli.analysis_failed", &error, 1), + }; if let Err(error) = stream.started( &entry, mode.as_str(), @@ -445,7 +355,7 @@ pub fn execute( return transport_failure(&error); } } - let mut result = run_with_limits( + let result = run_with_limits( &project.program, &mut host, &project.entry, @@ -453,128 +363,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 +412,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. diff --git a/crates/cli/src/commands/sandbox.rs b/crates/cli/src/commands/sandbox.rs index 382032f..f3e3154 100644 --- a/crates/cli/src/commands/sandbox.rs +++ b/crates/cli/src/commands/sandbox.rs @@ -49,12 +49,6 @@ pub struct SandboxSettings { pub allow_provider: Vec, /// Explicit trust decision for in-process native plugin loading. pub trust_native_plugin: bool, - /// Optional Trace v2 output path. - pub trace_file: Option, - /// Trace event budget override (0 = unlimited). - pub trace_max_events: Option, - /// Trace approximate byte budget override (0 = unlimited). - pub trace_max_bytes: Option, /// External foreign-kernel descriptor paths. pub kernels: Vec, } @@ -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(), ); diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 66e384b..6b6bdc4 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -7,16 +7,15 @@ mod analysis; mod args; mod commands; -mod execution_events; 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 +34,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, + /// 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, /// 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, /// 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, /// 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, /// 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, /// 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, } impl ObserveArgs { - fn options(&self) -> Option { - 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 +82,7 @@ impl ObserveArgs { if let Some(bytes) = self.observe_max_bytes { options.max_bytes = bytes; } - Some(options) + options } } @@ -220,15 +194,6 @@ struct SandboxArgs { /// (repeatable; wildcards are not supported). #[arg(long = "allow-provider", value_name = "NAME")] allow_provider: Vec, - /// Write a versioned Trace v2 file for this run. - #[arg(long = "trace-file", value_name = "PATH")] - trace_file: Option, - /// Override the trace event budget (0 = unlimited). - #[arg(long = "trace-max-events")] - trace_max_events: Option, - /// Override the approximate trace byte budget (0 = unlimited). - #[arg(long = "trace-max-bytes")] - trace_max_bytes: Option, /// Register an external foreign-kernel provider (repeatable). #[arg(long = "kernel", value_name = "PATH")] kernel: Vec, @@ -259,9 +224,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 +235,6 @@ struct RunArgs { file: Option, #[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 +250,6 @@ struct CallArgs { args: Vec, #[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, } @@ -514,36 +464,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), diff --git a/crates/cli/src/execution_events.rs b/crates/cli/src/observation.rs similarity index 63% rename from crates/cli/src/execution_events.rs rename to crates/cli/src/observation.rs index ccb7b73..a6d01c9 100644 --- a/crates/cli/src/execution_events.rs +++ b/crates/cli/src/observation.rs @@ -1,15 +1,9 @@ -//! 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}; @@ -18,19 +12,27 @@ use marqdo_host::{ ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, }; -use marqdo_value::{RuntimeError, Value}; +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, /// Exact local-variable names selected with `--observe-variable`. pub variables: Vec, /// 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>, +pub struct ObservationSession { + inner: Rc>, 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 { 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, - run_id: String, - seq: u64, +struct Snapshot { + staging: tempfile::NamedTempFile, + path: Option, } -impl JsonlWriter { +impl Snapshot { + fn open(options: &ObservationOptions) -> Result, 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, + 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::(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, diff --git a/crates/cli/src/tool.rs b/crates/cli/src/tool.rs index 1881677..adcb4d0 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -252,7 +252,7 @@ fn validate_requirements(requires: &Requirements) -> Result<(), String> { ( "observation", requires.observation, - crate::execution_events::SCHEMA_VERSION, + crate::observation::SCHEMA_VERSION, ), ] { if let Some(requested) = requested { diff --git a/crates/cli/src/trace.rs b/crates/cli/src/trace.rs deleted file mode 100644 index 54d1b86..0000000 --- a/crates/cli/src/trace.rs +++ /dev/null @@ -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 = 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(()) -} diff --git a/crates/cli/tests/analysis_trace.rs b/crates/cli/tests/analysis_observation.rs similarity index 90% rename from crates/cli/tests/analysis_trace.rs rename to crates/cli/tests/analysis_observation.rs index fd504ff..99b14b7 100644 --- a/crates/cli/tests/analysis_trace.rs +++ b/crates/cli/tests/analysis_observation.rs @@ -1,5 +1,8 @@ -//! Public Analysis and Trace black-box contracts (spec/analysis.md, -//! spec/trace-v1.md). +//! Public Analysis and Observation black-box contracts (spec/analysis.md, +//! spec/observation.md). + +#[path = "support/observation.rs"] +pub mod observation; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -271,7 +274,7 @@ print(1) } #[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 +287,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 +301,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 +338,7 @@ fn failed_check_removes_stale_analysis() { } #[test] -fn trace_records_calls_effects_and_status_without_secrets() { +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 +347,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 +363,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,14 +392,18 @@ 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] @@ -453,12 +465,13 @@ fn multi_arm_branch_preserves_analysis_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); } } diff --git a/crates/cli/tests/callable_resolution.rs b/crates/cli/tests/callable_resolution.rs index 39a082f..fc0de4e 100644 --- a/crates/cli/tests/callable_resolution.rs +++ b/crates/cli/tests/callable_resolution.rs @@ -4,6 +4,8 @@ //! 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/observation.rs"] +pub mod observation; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -187,11 +189,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 +484,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 +531,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 +637,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(), ); diff --git a/crates/cli/tests/examples_r6.rs b/crates/cli/tests/examples_r6.rs index 0cf6306..32676ee 100644 --- a/crates/cli/tests/examples_r6.rs +++ b/crates/cli/tests/examples_r6.rs @@ -1,6 +1,9 @@ //! R6 integration examples that do not require an official external repo. #![cfg(unix)] +#[path = "support/observation.rs"] +pub mod observation; + use std::path::Path; use std::process::{Command, Output}; @@ -51,13 +54,13 @@ fn mqmd_stdlib_print_output_matches_builtin_print() { #[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 +70,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] @@ -133,7 +140,12 @@ fn unknown_tool_name_installs_and_dispatches() { #[test] fn public_schemas_are_valid_json_and_versioned() { - for name in ["analysis", "trace-v1", "cli-tool", "execution-events-v1"] { + for name in [ + "analysis", + "observation-event", + "cli-tool", + "observation-file", + ] { let path = repo() .join("spec/schemas") .join(format!("{name}.schema.json")); diff --git a/crates/cli/tests/http_over_tcp.rs b/crates/cli/tests/http_over_tcp.rs index 496651f..915c6b0 100644 --- a/crates/cli/tests/http_over_tcp.rs +++ b/crates/cli/tests/http_over_tcp.rs @@ -1,5 +1,8 @@ //! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint. +#[path = "support/observation.rs"] +pub mod observation; + use std::io::{Read, Write}; use std::net::TcpListener; use std::path::Path; @@ -89,7 +92,14 @@ import: ); 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"]) + .args([ + "run", + "index.mq.md", + "--allow-net", + "127.0.0.1", + "--output", + "json", + ]) .current_dir(dir.path()) .env( "MARQDO_STDLIB_DIR", @@ -110,8 +120,10 @@ 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"); diff --git a/crates/cli/tests/integration_cli.rs b/crates/cli/tests/integration_cli.rs index 72c9bb0..4ed93b6 100644 --- a/crates/cli/tests/integration_cli.rs +++ b/crates/cli/tests/integration_cli.rs @@ -9,6 +9,9 @@ //! Temporary directories live under the OS temp directory and are removed on //! drop; the repository itself is never modified. +#[path = "support/observation.rs"] +pub mod observation; + use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; @@ -253,16 +256,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 +300,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 +335,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 +443,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 +455,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 +475,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 +498,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 +527,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 +555,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 +563,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 +584,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 +604,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] @@ -923,11 +973,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"] @@ -1171,22 +1221,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 +1244,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] diff --git a/crates/cli/tests/execution_events.rs b/crates/cli/tests/observation.rs similarity index 86% rename from crates/cli/tests/execution_events.rs rename to crates/cli/tests/observation.rs index c20aa7f..a79c9fb 100644 --- a/crates/cli/tests/execution_events.rs +++ b/crates/cli/tests/observation.rs @@ -1,9 +1,9 @@ -//! 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. use std::fs; use std::io::{BufRead, BufReader, Read}; @@ -124,7 +124,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 +174,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 +194,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 +210,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 +219,7 @@ fn structure_fixture_attributes_repeated_recursive_frames() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-max-events", "1000", @@ -287,7 +289,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 +304,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 +313,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 +325,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 +339,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 +392,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 +421,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 +436,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 +459,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 +472,7 @@ fn value_observation_is_exact_and_requires_text_consent() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-variable", "visible_count", @@ -498,7 +499,7 @@ fn value_observation_is_exact_and_requires_text_consent() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-variable", "secret_token", @@ -519,7 +520,7 @@ fn value_observation_is_exact_and_requires_text_consent() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-variable", "secret_token", @@ -554,10 +555,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 +568,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 +623,7 @@ fn structural_budget_truncates_without_losing_critical_events() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-max-events", "5", @@ -637,7 +648,7 @@ fn output_budget_still_fails_the_run_and_emits_no_chunk() { &[ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--max-output", "3", @@ -663,7 +674,7 @@ fn live_chunks_arrive_while_the_program_is_still_running() { .args([ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-max-events", "20", @@ -716,7 +727,7 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() { .args([ "run", "index.mq.md", - "--event-stream", + "--output", "jsonl", "--observe-max-events", "10", @@ -811,9 +822,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 +834,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 +861,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,10 +873,6 @@ 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); diff --git a/crates/cli/tests/p2_closure.rs b/crates/cli/tests/p2_closure.rs index c6d17ae..12be670 100644 --- a/crates/cli/tests/p2_closure.rs +++ b/crates/cli/tests/p2_closure.rs @@ -1,5 +1,8 @@ //! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host. +#[path = "support/observation.rs"] +pub mod observation; + use std::path::{Path, PathBuf}; use std::process::Command; @@ -70,7 +73,14 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() { ); } let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args(["run", path.to_str().unwrap(), "--mode", "pure", "--json"]) + .args([ + "run", + path.to_str().unwrap(), + "--mode", + "pure", + "--output", + "json", + ]) .current_dir(repo_root()) .output() .expect("run marqdo"); @@ -82,14 +92,15 @@ 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" ); @@ -100,7 +111,14 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() { 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"]) + .args([ + "run", + path.to_str().unwrap(), + "--mode", + "pure", + "--output", + "json", + ]) .current_dir(repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .output() @@ -112,8 +130,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() { 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"] + assert_eq!(report["run"]["status"], "ok"); + let items = observation::terminal(&report)["value"]["items"] .as_array() .expect("table test list"); assert_eq!(items.len(), 9); @@ -133,14 +151,24 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() { ) .unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args(["run", foreign.to_str().unwrap(), "--mode", "pure", "--json"]) + .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( @@ -149,11 +177,18 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() { ) .unwrap(); let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args(["run", plugin.to_str().unwrap(), "--mode", "pure", "--json"]) + .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"); } diff --git a/crates/cli/tests/print_routing.rs b/crates/cli/tests/print_routing.rs index 67405d9..409cd2f 100644 --- a/crates/cli/tests/print_routing.rs +++ b/crates/cli/tests/print_routing.rs @@ -52,7 +52,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 +69,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"), diff --git a/crates/cli/tests/provider_cli.rs b/crates/cli/tests/provider_cli.rs index f3db429..9e39f85 100644 --- a/crates/cli/tests/provider_cli.rs +++ b/crates/cli/tests/provider_cli.rs @@ -15,6 +15,8 @@ //! 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/observation.rs"] +pub mod observation; use std::fs; use std::path::{Path, PathBuf}; @@ -417,17 +419,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("") + 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 +468,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 +480,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 +490,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 +535,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 +564,8 @@ fn prov_03_grant_without_manifest_is_never_discovered() { "index.mq.md", "--allow-provider", "demo.sensor", - "--json", + "--output", + "json", ], &marker, ); @@ -603,7 +606,8 @@ fn prov_04_duplicate_kind_across_providers_is_rejected_before_spawn() { "demo.one", "--allow-provider", "demo.two", - "--json", + "--output", + "json", ], &marker, ); @@ -636,7 +640,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 +652,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 +698,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 +742,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 +781,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 +813,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 +849,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 +885,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 +923,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() { manifest_arg, "--allow-provider", "demo.sensor", - "--json", + "--output", + "json", ], &marker, ); @@ -932,7 +946,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() { manifest_arg, "--allow-provider", "demo.sensor", - "--json", + "--output", + "json", ], &marker, ); @@ -953,7 +968,8 @@ fn prov_10_pure_and_strict_preflight_refuse_provider_flags() { manifest_arg, "--allow-provider", "*", - "--json", + "--output", + "json", ], &marker, ); @@ -992,7 +1008,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 +1024,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}" diff --git a/crates/cli/tests/resource_streams.rs b/crates/cli/tests/resource_streams.rs index b444523..40a18f4 100644 --- a/crates/cli/tests/resource_streams.rs +++ b/crates/cli/tests/resource_streams.rs @@ -1,5 +1,8 @@ //! End-to-end resource stream tests through the CLI. +#[path = "support/observation.rs"] +pub mod observation; + use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; @@ -80,7 +83,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 +99,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 +158,8 @@ fn project_file_stream_writes_on_close_then_reads_back() { "out.bin", "--allow-read", "out.bin", - "--json", + "--output", + "json", ], ); assert_eq!( @@ -158,8 +169,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 +237,8 @@ fn file_copy_is_written_in_mqmd_through_chunked_streams() { "data.txt", "--allow-write", "out.bin", - "--json", + "--output", + "json", ], ); assert_eq!( @@ -234,8 +248,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 +303,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 +319,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 +337,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 +366,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 +378,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 +427,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 +435,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 +469,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 +481,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); diff --git a/crates/cli/tests/stdlib_http.rs b/crates/cli/tests/stdlib_http.rs index 6706f42..570400b 100644 --- a/crates/cli/tests/stdlib_http.rs +++ b/crates/cli/tests/stdlib_http.rs @@ -1,5 +1,8 @@ //! CM-A08/P5 stdlib HTTP framing module tests. +#[path = "support/observation.rs"] +pub mod observation; + use std::path::Path; use std::process::Command; @@ -15,7 +18,7 @@ fn repo_root() -> std::path::PathBuf { #[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"]) + .args(["run", "tests/http.mq.md", "--output", "json"]) .current_dir(repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .output() @@ -27,8 +30,10 @@ fn stdlib_http_parses_chunked_responses_and_builds_requests() { 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!(report["run"]["status"], "ok"); + let items = observation::terminal(&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"); diff --git a/crates/cli/tests/stdlib_product.rs b/crates/cli/tests/stdlib_product.rs index be201c5..6b64505 100644 --- a/crates/cli/tests/stdlib_product.rs +++ b/crates/cli/tests/stdlib_product.rs @@ -5,6 +5,9 @@ //! user import path (`std:` + the verified bundle), not through a conformance //! fixture or a Rust shortcut. +#[path = "support/observation.rs"] +pub mod observation; + use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -130,7 +133,7 @@ fn run_product_test(file: &TestFile) -> serde_json::Value { .args(["run"]) .arg(stdlib_dir().join("tests").join(&file.name)) .args(file.args.iter()) - .args(["--json"]) + .args(["--output", "json"]) .current_dir(stdlib_dir()) .env("MARQDO_STDLIB_DIR", stdlib_dir()) .envs( @@ -196,9 +199,10 @@ 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["run"]["status"], "ok", "{}", file.name); assert_eq!( - report["stdout"], file.stdout, + observation::text(&report, "stdout.chunk"), + file.stdout, "{} wrote unexpected stdout", file.name ); @@ -214,7 +218,9 @@ fn fs_test_exercises_the_file_operation_surface() { .find(|file| file.name == "fs.mq.md") .expect("fs test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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); @@ -244,7 +250,9 @@ fn json_test_parses_and_formats_nested_values() { .find(|file| file.name == "json.mq.md") .expect("json test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&report)["value"]["items"] + .as_array() + .expect("list"); assert_eq!(items[0]["value"], true); assert_eq!(items[1]["decimal"], "1"); assert_eq!(items[2]["value"], "说\"好"); @@ -269,7 +277,9 @@ fn csv_test_parses_and_formats_quoted_rows() { .find(|file| file.name == "csv.mq.md") .expect("csv test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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"], "甲"); @@ -298,7 +308,9 @@ fn path_test_joins_and_normalizes_project_paths() { .find(|file| file.name == "path.mq.md") .expect("path test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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"); @@ -318,7 +330,9 @@ fn regex_test_matches_anchors_classes_and_search() { .find(|file| file.name == "regex.mq.md") .expect("regex test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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); @@ -347,7 +361,9 @@ fn datetime_test_formats_and_parses_utc_instants() { .find(|file| file.name == "datetime.mq.md") .expect("datetime test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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"); @@ -365,7 +381,9 @@ fn clock_test_reports_project_mode_unix_millis() { .find(|file| file.name == "clock.mq.md") .expect("clock test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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); @@ -379,7 +397,9 @@ fn env_test_reads_only_granted_names() { .find(|file| file.name == "env.mq.md") .expect("env test"), ); - let items = report["value"]["items"].as_array().expect("list"); + 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]["value"], true); @@ -396,7 +416,9 @@ fn process_test_runs_an_explicitly_granted_program() { .find(|file| file.name == "process.mq.md") .expect("process test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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")) @@ -420,7 +442,9 @@ fn random_test_reads_bounded_entropy() { .find(|file| file.name == "random.mq.md") .expect("random test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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); @@ -436,7 +460,9 @@ fn compress_test_round_trips_gzip_text() { .find(|file| file.name == "compress.mq.md") .expect("compress test"), ); - let items = report["value"]["items"].as_array().expect("list"); + 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]["value"], true); @@ -451,7 +477,9 @@ fn format_test_pins_value_semantics_and_handle_observation() { .find(|file| file.name == "format.mq.md") .expect("format test"), ); - let items = report["value"]["items"].as_array().expect("list"); + let items = observation::terminal(&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}"); @@ -473,12 +501,30 @@ fn text_and_utf8_tests_agree_on_the_byte_encoding() { .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); + assert_eq!( + observation::terminal(&text)["value"]["items"][0]["decimal"], + "2" + ); + assert_eq!( + observation::terminal(&text)["value"]["items"][1]["decimal"], + "195" + ); + assert_eq!( + observation::terminal(&text)["value"]["items"][2]["decimal"], + "169" + ); + assert_eq!( + observation::terminal(&utf8)["value"]["items"][0]["decimal"], + "2" + ); + assert_eq!( + observation::terminal(&utf8)["value"]["items"][1]["value"], + "é" + ); + assert_eq!( + observation::terminal(&utf8)["value"]["items"][2]["value"], + false + ); } #[test] @@ -489,8 +535,14 @@ fn stream_and_console_use_the_resource_endpoints() { .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"); + assert_eq!( + observation::terminal(&stream)["value"]["items"][0]["value"], + true + ); + assert_eq!( + observation::terminal(&stream)["value"]["items"][1]["decimal"], + "7" + ); let console = run_product_test( product_tests() @@ -498,14 +550,21 @@ fn stream_and_console_use_the_resource_endpoints() { .find(|file| file.name == "console.mq.md") .expect("console test"), ); - assert_eq!(console["value"]["items"][0]["value"], true); - assert_eq!(console["value"]["items"][1]["value"], "hello"); + assert_eq!( + observation::terminal(&console)["value"]["items"][0]["value"], + true + ); + assert_eq!( + observation::terminal(&console)["value"]["items"][1]["value"], + "hello" + ); assert!( - console["trace"] + console["events"] .as_array() .unwrap() .iter() - .any(|event| event["op"] == "resource.read" || event["op"] == "resource.open"), + .any(|event| event["payload"]["operation"] == "resource.read" + || event["payload"]["operation"] == "resource.open"), "console test did not go through a resource endpoint" ); } diff --git a/crates/cli/tests/stdlib_table.rs b/crates/cli/tests/stdlib_table.rs index 75692c1..a1ca0a1 100644 --- a/crates/cli/tests/stdlib_table.rs +++ b/crates/cli/tests/stdlib_table.rs @@ -1,5 +1,8 @@ //! CM-A08 table stdlib module tests. +#[path = "support/observation.rs"] +pub mod observation; + use std::path::Path; use std::process::Command; @@ -14,7 +17,7 @@ fn repo_root() -> std::path::PathBuf { fn run_table_self_test() -> serde_json::Value { let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) - .args(["run", "tests/table.mq.md", "--json"]) + .args(["run", "tests/table.mq.md", "--output", "json"]) .current_dir(repo_root().join("stdlib")) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib")) .output() @@ -35,8 +38,10 @@ fn rows(value: &serde_json::Value) -> &Vec { #[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!(report["run"]["status"], "ok"); + let items = observation::terminal(&report)["value"]["items"] + .as_array() + .expect("list"); assert_eq!(items.len(), 9); assert_eq!(items[0]["header"], serde_json::json!(["分数"])); diff --git a/crates/cli/tests/support/observation.rs b/crates/cli/tests/support/observation.rs new file mode 100644 index 0000000..782bf30 --- /dev/null +++ b/crates/cli/tests/support/observation.rs @@ -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 { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = Vec::new(); + let bytes: Vec = 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 +} diff --git a/crates/cli/tests/tool_protocol.rs b/crates/cli/tests/tool_protocol.rs index 7612823..566a982 100644 --- a/crates/cli/tests/tool_protocol.rs +++ b/crates/cli/tests/tool_protocol.rs @@ -8,6 +8,8 @@ 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); @@ -137,20 +139,18 @@ 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}","requires":{{"api_revision":1,"analysis":3,"observation":1}}}}"# - ), - ) - .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"); @@ -170,7 +170,11 @@ fn independent_sample_tools_consume_public_analysis_and_trace() { .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"]) + .args([ + "run", + "examples/multi-module/index.mq.md", + "--observation-file", + ]) .arg(&trace) .current_dir(&root) .output() @@ -207,15 +211,15 @@ fn independent_sample_tools_consume_public_analysis_and_trace() { 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 +227,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]); diff --git a/crates/marqdo-host/src/host.rs b/crates/marqdo-host/src/host.rs index 6162228..2872f7a 100644 --- a/crates/marqdo-host/src/host.rs +++ b/crates/marqdo-host/src/host.rs @@ -7,7 +7,7 @@ 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, @@ -31,11 +31,9 @@ use crate::provider_worker::WorkerResourceProvider; use crate::resource::{ is_core_resource_kind, ResourceProvider, ResourceRead, 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; @@ -182,29 +180,10 @@ pub trait Host { /// Take the buffered program output. fn take_output(&mut self) -> Vec; - /// 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, - _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`. + /// any observation event when there is no capture destination. fn observation_enabled(&self) -> bool { false } @@ -252,8 +231,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 +257,6 @@ pub struct StdHost { resources: ResourceTable, /// Registered in-process providers keyed by resource kind (ADR-0033). resource_providers: BTreeMap, - semantic_events: Vec, - next_event_seq: u64, - trace_state: TraceState, observation: Option, observation_error: Option, } @@ -331,7 +305,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 +319,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, } @@ -502,22 +472,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 { self.broker_audit @@ -536,13 +490,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 +564,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 +729,8 @@ impl Host for StdHost { max_bytes: usize, ctx: &ExecutionContext, ) -> Result { - 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 +740,6 @@ impl Host for StdHost { bytes: &[u8], ctx: &ExecutionContext, ) -> Result { - 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 +762,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 +771,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 +784,8 @@ impl Host for StdHost { handle: ResourceHandle, ctx: &ExecutionContext, ) -> Result { - 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 +885,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 +1033,6 @@ impl Host for StdHost { fn take_output(&mut self) -> Vec { 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, - 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 { diff --git a/crates/marqdo-host/src/host/dispatch.rs b/crates/marqdo-host/src/host/dispatch.rs index 0064bf3..7f96641 100644 --- a/crates/marqdo-host/src/host/dispatch.rs +++ b/crates/marqdo-host/src/host/dispatch.rs @@ -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 } diff --git a/crates/marqdo-host/src/host/effects.rs b/crates/marqdo-host/src/host/effects.rs deleted file mode 100644 index 2735f62..0000000 --- a/crates/marqdo-host/src/host/effects.rs +++ /dev/null @@ -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); - } -} diff --git a/crates/marqdo-host/src/host/resource_ops.rs b/crates/marqdo-host/src/host/resource_ops.rs index 095d5a9..5674f27 100644 --- a/crates/marqdo-host/src/host/resource_ops.rs +++ b/crates/marqdo-host/src/host/resource_ops.rs @@ -38,7 +38,6 @@ impl StdHost { rights: &[String], ctx: &ExecutionContext, ) -> Result { - 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)) } } diff --git a/crates/marqdo-host/src/host/resource_requests.rs b/crates/marqdo-host/src/host/resource_requests.rs index d0e815f..7408383 100644 --- a/crates/marqdo-host/src/host/resource_requests.rs +++ b/crates/marqdo-host/src/host/resource_requests.rs @@ -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, ctx: &ExecutionContext, ) -> Result { - 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("resource.request", "ok", ctx); Ok(result) } _ => { diff --git a/crates/marqdo-host/src/lib.rs b/crates/marqdo-host/src/lib.rs index d05d8ff..867d19b 100644 --- a/crates/marqdo-host/src/lib.rs +++ b/crates/marqdo-host/src/lib.rs @@ -1,4 +1,4 @@ -//! CapabilityHost: capability checks, resource budgets, effect tracing and the +//! CapabilityHost: capability checks, resource budgets, observation and the //! only bridge to math, foreign kernels, files and plugins. //! //! Blueprint §9 and §7.3: every side effect goes through this boundary, checks @@ -17,7 +17,6 @@ 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::{ @@ -39,4 +38,3 @@ pub use resource::{ is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider, CORE_RESOURCE_KINDS, }; -pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation}; diff --git a/crates/marqdo-host/src/observe.rs b/crates/marqdo-host/src/observe.rs index a457aa2..00efa72 100644 --- a/crates/marqdo-host/src/observe.rs +++ b/crates/marqdo-host/src/observe.rs @@ -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 @@ -202,6 +202,7 @@ pub enum ObservationEvent<'a> { }, /// The host completed a controlled effect attempt. Effect { + frame_id: Option, operation: &'a str, result_code: &'a str, module_id: &'a str, @@ -247,7 +248,7 @@ pub enum LoopTransfer { } impl LoopTransfer { - /// The event kind in Trace and Execution Events. + /// The event kind in Observation. pub fn event_kind(self) -> &'static str { match self { Self::Break => "control.break", @@ -258,10 +259,15 @@ impl LoopTransfer { /// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`]. /// -/// Every variant carries an `Option`; observation of values and -/// structural events only happens while a frame identity exists. +/// 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, + }, /// A `return` statement committed (before the call exits). Return { frame_id: Option, diff --git a/crates/marqdo-host/src/trace.rs b/crates/marqdo-host/src/trace.rs deleted file mode 100644 index 2ec7cf9..0000000 --- a/crates/marqdo-host/src/trace.rs +++ /dev/null @@ -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, - /// 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, - /// 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, - module: impl Into, - span: Option, - duration: Duration, - result: impl Into, - ) { - 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, -} - -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, - /// Logical module owning `span`. - pub module_id: Option, - /// Source span, when known. - pub span: Option, - /// Non-sensitive detail (`ok`, `true`, `int`, an error code). - pub detail: Option, -} diff --git a/crates/marqdo-runtime/src/builtins_impl.rs b/crates/marqdo-runtime/src/builtins_impl.rs index 436c8ca..10dfc81 100644 --- a/crates/marqdo-runtime/src/builtins_impl.rs +++ b/crates/marqdo-runtime/src/builtins_impl.rs @@ -160,12 +160,7 @@ pub(crate) fn dispatch( let handle = interpreter .memory_mut() .create(initial_pages, max_pages, span)?; - interpreter.record_memory_event( - "memory.new", - &module, - span, - &format!("initial_pages={initial_pages} max_pages={max_pages}"), - ); + interpreter.observe_memory_effect("memory.new", &module, span)?; Ok(Value::Memory(handle)) } "memory.size" => { @@ -191,12 +186,7 @@ pub(crate) fn dispatch( }; let pages = page_count(take(&bound, "pages", builtin, span)?, span)?; let old_pages = interpreter.memory_mut().grow(handle, pages, span)?; - interpreter.record_memory_event( - "memory.grow", - &module, - span, - &format!("pages={pages} old_pages={old_pages}"), - ); + interpreter.observe_memory_effect("memory.grow", &module, span)?; Ok(pages_value(old_pages, span)?) } "list.append" => { diff --git a/crates/marqdo-runtime/src/interpreter.rs b/crates/marqdo-runtime/src/interpreter.rs index c7ce55e..8b3e7e8 100644 --- a/crates/marqdo-runtime/src/interpreter.rs +++ b/crates/marqdo-runtime/src/interpreter.rs @@ -178,13 +178,6 @@ impl<'a> Interpreter<'a> { if self.depth + 1 > 0 { self.host.check_stack(self.depth + 1, call_span)?; } - self.host.record_semantic( - "call.enter", - Some(&trace_id), - Some(&trace_module), - call_span, - None, - ); let bound = match self.bind_args(function, args, call_span) { Ok(bound) => bound, Err(mut error) => { @@ -245,13 +238,6 @@ impl<'a> Interpreter<'a> { Ok(Some(_)) => "return", Err(error) => error.code(), }; - self.host.record_semantic( - "call.exit", - Some(&trace_id), - Some(&trace_module), - call_span, - Some(status), - ); let close = self .host .observation_end_frame(frame_id, status, &trace_module, call_span); @@ -428,13 +414,6 @@ impl<'a> Interpreter<'a> { (Flow::Continue(*span), LoopTransfer::Continue) }; let module = frame.function.module.canonical(); - self.host.record_semantic( - transfer.event_kind(), - Some(&frame.function.to_string()), - Some(&module), - Some(*span), - None, - ); if self.observe { self.host .observe_runtime(RuntimeObservation::LoopTransfer { @@ -449,13 +428,6 @@ impl<'a> Interpreter<'a> { Stmt::Return { value, span } => { let value = self.eval_expr(value, frame)?; let module = frame.function.module.canonical(); - self.host.record_semantic( - "return", - Some(&frame.function.to_string()), - Some(&module), - Some(*span), - Some(value.type_name()), - ); if self.observe { self.host.observe_runtime(RuntimeObservation::Return { frame_id: frame.id, @@ -480,13 +452,6 @@ impl<'a> Interpreter<'a> { )); }; let module = frame.function.module.canonical(); - self.host.record_semantic( - "branch.eval", - Some(&frame.function.to_string()), - Some(&module), - Some(arm.condition_span), - Some(if condition { "true" } else { "false" }), - ); if self.observe { self.host.observe_runtime(RuntimeObservation::BranchEval { frame_id: frame.id, @@ -519,13 +484,6 @@ impl<'a> Interpreter<'a> { )); }; let module = frame.function.module.canonical(); - self.host.record_semantic( - "loop.iteration", - Some(&frame.function.to_string()), - Some(&module), - Some(*condition_span), - Some(if value { "continue" } else { "exit" }), - ); if self.observe { self.host .observe_runtime(RuntimeObservation::LoopIteration { @@ -594,15 +552,7 @@ impl<'a> Interpreter<'a> { )); }; self.memory.write(handle, &offset, byte, span)?; - let module = frame.function.module.canonical(); - self.host.record_semantic( - "memory.write", - Some(&frame.function.to_string()), - Some(&module), - span, - Some("byte"), - ); - Ok(()) + self.observe_memory_effect("memory.write", &frame.function.module, span) } fn eval_args( @@ -905,17 +855,21 @@ impl<'a> Interpreter<'a> { &mut self.memory } - /// Record a semantic event for a builtin that is not a host operation. - pub(crate) fn record_memory_event( + /// Publish a committed local memory operation without its data or address. + pub(crate) fn observe_memory_effect( &mut self, - kind: &str, + operation: &str, module: &ModuleId, span: Option, - detail: &str, - ) { - let module = module.canonical(); - self.host - .record_semantic(kind, None, Some(&module), span, Some(detail)); + ) -> Result<(), RuntimeError> { + if self.observe { + self.host.observe_runtime(RuntimeObservation::Effect { + operation, + module_id: &module.canonical(), + span, + })?; + } + Ok(()) } /// Open a resource/stream through the host boundary. diff --git a/docs/STATUS.md b/docs/STATUS.md index 7643b62..f167d02 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -32,6 +32,14 @@ minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The candidate SHA before publication. The release record below refers to the published beta. +## Current protocol integration + +[ADR-0068](adr/0068-single-current-public-contracts.md) governs the work +for [issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8). Current +developer inputs are [Analysis](../spec/analysis.md), +[Observation](../spec/observation.md) and the [CLI Tool](../spec/cli-tool.md). +The earlier release records below describe their tagged binaries. + ## 0. Beta release record — `3.0.0-beta.1` ### 0.1 Product, version axes and scope @@ -107,7 +115,7 @@ historical and superseded by the release-SHA manifest. This section records work **after** the `v3.0.0-beta.1` tag. It is not part of the tagged beta archive and no new release tag has been created. The design input is RFC-OBS-0001 (issue `#1`), the frozen decision is ADR-0059 and the -normative contract is [`spec/execution-events-v1.md`](../spec/execution-events-v1.md). +normative contract is [the beta-era event contract](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/execution-events-v1.md). Executed evidence for this section is [`evidence/2026-11-22-execution-events-v1.md`](evidence/2026-11-22-execution-events-v1.md). @@ -273,7 +281,7 @@ execution segment. Binding inference joins only reachable control exits. The [runnable example](../examples/control-flow.mq.md) uses ordinary Markdown list containers. -[Analysis v3](../spec/analysis-v3.md) represents the loop transfer statements. +[the shipped rc.2 Analysis contract](https://git.cflmy.cn/cflmy/marqdo-cli/src/tag/v3.0.0-rc.2/spec/analysis-v3.md) represents the loop transfer statements. Other documents continue to emit v2. Trace v2 and Execution Events v1 expose the new control events. The published beta evidence applies to its original SHA. The maintainer selected phase A for RC.2. List iteration @@ -672,7 +680,7 @@ Consumer evidence: ```bash ./target/debug/marqdo check examples/multi-module/index.mq.md --refs --emit /tmp/a.json -./target/debug/marqdo run examples/multi-module/index.mq.md --trace-file /tmp/t.json +./target/debug/marqdo run examples/multi-module/index.mq.md --observation-file /tmp/observation.json python3 tests/consumers/analysis_consumer.py /tmp/a.json python3 tests/consumers/trace_consumer.py /tmp/a.json /tmp/t.json ``` diff --git a/docs/adr/0006-cli-contract.md b/docs/adr/0006-cli-contract.md index 2674906..ca0f5f8 100644 --- a/docs/adr/0006-cli-contract.md +++ b/docs/adr/0006-cli-contract.md @@ -1,5 +1,8 @@ # ADR-0006: CLI output, exit-code and JSON contract +> Historical public protocol sections. Current Analysis, runtime output and +> Tool contracts are specified by [ADR-0068](0068-single-current-public-contracts.md). + Status: **Accepted** Date: 2026-11-20 diff --git a/docs/adr/0013-generic-cli-tool-protocol.md b/docs/adr/0013-generic-cli-tool-protocol.md index 50ba729..80e138c 100644 --- a/docs/adr/0013-generic-cli-tool-protocol.md +++ b/docs/adr/0013-generic-cli-tool-protocol.md @@ -1,5 +1,8 @@ # ADR-0013: Generic external CLI Tool Protocol v1 +> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes +> the public contracts described in this record. + Status: **Accepted** Date: 2026-11-20 diff --git a/docs/adr/0015-public-analysis-trace-v1.md b/docs/adr/0015-public-analysis-trace-v1.md index cc23fc3..604cdbc 100644 --- a/docs/adr/0015-public-analysis-trace-v1.md +++ b/docs/adr/0015-public-analysis-trace-v1.md @@ -1,5 +1,8 @@ # ADR-0015: Public Analysis v1 and Trace v1 +> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes +> the public contracts described in this record. + Status: **Accepted** Date: 2026-11-20 diff --git a/docs/adr/0059-runtime-observability-and-execution-events.md b/docs/adr/0059-runtime-observability-and-execution-events.md index 9f01d15..badda6e 100644 --- a/docs/adr/0059-runtime-observability-and-execution-events.md +++ b/docs/adr/0059-runtime-observability-and-execution-events.md @@ -1,5 +1,8 @@ # ADR-0059: Runtime observability and Execution Events v1 +> Historical. [ADR-0068](0068-single-current-public-contracts.md) supersedes +> the public contracts described in this record. + - **Status:** Accepted - **Date:** 2026-11-22 - **Decision owners:** CLI, runtime and host maintainers diff --git a/docs/adr/0067-structured-control-flow.md b/docs/adr/0067-structured-control-flow.md index f158016..f1b0d32 100644 --- a/docs/adr/0067-structured-control-flow.md +++ b/docs/adr/0067-structured-control-flow.md @@ -1,5 +1,8 @@ # ADR-0067 — Multi-arm branches and nearest-loop control +> Historical public protocol sections. Current Analysis, runtime output and +> Tool contracts are specified by [ADR-0068](0068-single-current-public-contracts.md). + Status: Accepted for development. Release inclusion requires a maintainer decision and the applicable same-SHA release gates. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index 8796a3a..60fc153 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -27,14 +27,6 @@ replace `spec/` or a recorded test log. > [`spec/extension-selection.md`](../../spec/extension-selection.md), > [`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md). > -> **Post-baseline observability (ADR-0059, RFC-OBS-0001).** After the tagged -> baseline the tree adds Execution Events v1: a typed host observation facade, -> real-commit stdout/stderr chunks, run-unique call frames and explicitly -> selected bounded values over `run/call --event-stream jsonl`. Analysis v2 and -> Trace v2 are unchanged. This is locally tested on the post-baseline tree -> ([`../STATUS.md`](../STATUS.md) §0.5) and is not part of the tagged beta -> archive or its same-SHA evidence. -> > **Post-baseline core/extension boundary (RFC-EXT-0003, ADR-0060–0063).** The > core call surface no longer owns the domain math kernel (`math.*` removed; > `crates/marqdo-math` deleted; ADR-0061), sibling heading mode inheritance is @@ -58,13 +50,36 @@ replace `spec/` or a recorded test log. > **Structured control flow (RFC-CTRL-0005).** > [ADR-0067](../adr/0067-structured-control-flow.md) extends the payload parser > and branch mapper, adds nearest-loop execution transfers and makes binding -> inference path-sensitive. Analysis chooses v2 or v3 according to the -> statements it emits. The interpreter owns the transfers and reports them -> through the existing observation facade. +> inference path-sensitive. Analysis projects the same branch and loop +> structure for every module. The interpreter reports transfers through Host +> observation. -Protocol architecture and pre-stable replacement rules are recorded in -[ADR-0068](../adr/0068-single-current-public-contracts.md). Check the -[implementation status](../STATUS.md) for rollout and release evidence. +## Public boundaries and pre-stable changes + +[ADR-0068](../adr/0068-single-current-public-contracts.md) records the policy +for replacing public interfaces before the first stable release. + +| Boundary | Owner | Current contract | +|---|---|---| +| Static facts | CLI Analysis projection of the prepared project | [Analysis](../../spec/analysis.md) | +| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) | +| Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) | +| Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) | +| Values and package identities | Value Wire and project lock | [Value Wire](../../spec/value-wire.md), [Extension selection and lock](../../spec/extension-selection.md) | + +`check --emit analysis.json` projects static facts from the prepared project. +`run` and `call` execute the same prepared program through the CapabilityHost. +`--output jsonl` provides live events and `--observation-file run.json` saves +the same event sequence from that invocation. Consumers verify the exact +Analysis bytes before marking execution spans in source. + +When replacing a contract, update its producer, specification, schema, real +consumers, fixtures and CI in one integration. Every required field and format +identifier should correspond to a check at the boundary. Reject obsolete +inputs with a corrective action. Keep historical formats in Git. Review +grants, budgets, file integrity, source attribution and privacy independently +of the transport change. Check the [implementation status](../STATUS.md) +for executed evidence and release gates. ## 1. Four state dimensions @@ -74,7 +89,7 @@ platform". | Dimension | Current state | Source | |---|---|---| -| Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; post-baseline Execution Events v1 (ADR-0059), core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` | +| Implemented | Rust workspace: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool, Analysis and Observation, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` | | Tested locally | `cargo test --workspace --locked`, `cargo fmt --all -- --check`, `clippy -D warnings`, release archive smoke and an independent `ubuntu:24.04` cold-install run on the RFC-EXT-0003 tree (Linux x86_64); exact counts and logs are in `docs/STATUS.md` §0.6 and the RFC-EXT-0003 evidence file. Historical baselines stay in earlier sections. | `docs/STATUS.md` §0.6, `docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md` | | Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` | | Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 | @@ -96,7 +111,7 @@ execution: Value / MemoryStore / evaluator / budgets (computes; does not own stdout or file handles) | controlled platform API: open/read/write/close + non-streaming requests - capability / budget / audit / trace + capability / budget / audit / observation stdio / file / tcp / OS adapters explicitly registered providers (in-process / worker / C ABI) | @@ -127,8 +142,8 @@ Layer rules: 5. Callable Plugin and Resource Provider share one registry/authorization/audit mechanism, but keep different capability types. 6. CLI policy/commands are `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; - host open-path/providers/effects/dispatch are - `host/{resource_ops,providers,effects,dispatch}.rs`; process execution is + host open-path/providers/dispatch are + `host/{resource_ops,providers,dispatch}.rs`; process execution is `process.rs`. These are child modules, not new crates or a second backend. ## 3. Dependency direction and public contracts @@ -150,7 +165,7 @@ review RFC, not a new crate per provider. | Public contract | API (`.mq.md`) | State | Tests | |---|---|---|---| | stdio stdin | `resource.open("stdio","stdin",["read"])`, `resource.read`, `resource.close`; one run-scoped cursor | implemented, read-only | `resource_streams`, `p2_closure`, `tests/conformance` | -| Execution Events v1 | `run/call --event-stream jsonl`; `--observe-variable`, `--observe-parameter`, `--observe-text-values` | implemented P0/P1 (post-beta); P2 memory metadata deferred; strict refuses the option | `execution_events` CLI, `observation` host/runtime, `execution_events_consumer.py` | +| Observation | `run/call --output jsonl`, `--output json` or `--observation-file PATH` | one event sequence and capture policy | `observation`, `analysis_observation`, `observation_consumer.py` | | stdio stdout | `resource.open("stdio","stdout",["write"])`, `resource.write`, `resource.close`; separate output budget | implemented | `stdlib_bundle`, `print_routing`, `resource_streams` | | stdio stderr | `resource.open("stdio","stderr",["write"])`; separate from stdout and CLI diagnostics | implemented | `resource_streams`, `stdlib_product` | | project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` | @@ -205,7 +220,7 @@ that a phase is complete. | P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open | | P1 | No file watch or binary `read_at` | open; future Resource Operation extension | | P1 | JSON/CSV product parsers are implemented with depth bound and multi-value/multi-row; no incremental streaming parser | open | -| P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,effects,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design | +| P1 | CLI split into `commands/{sandbox,run,check,inspect,init,package,tool}.rs`; host split into `host/{resource_ops,providers,dispatch}.rs` plus `process.rs`; `commands.rs` keeps shared project/runtime helpers and `host.rs` keeps the `Host` trait methods and capability checks | split; shared helpers and trait methods remain by design | | P2 | HTTP/1.1 framing is byte-exact; HTTP/2, trailers and transfer decoding remain open | open | | P2 | DNS, UDP, TCP listener and TLS client endpoints are implemented; no TLS server/mTLS or custom-CA CLI | open | | P2 | `std:path`, pure+host regex, `std:datetime`, `std:clock`, `std:env`, `std:process`, `std:random` and gzip compression are implemented; no streaming/zstd/brotli | open | diff --git a/docs/contributor-guide.md b/docs/contributor-guide.md index 0553e04..e4588c5 100644 --- a/docs/contributor-guide.md +++ b/docs/contributor-guide.md @@ -47,11 +47,9 @@ marqdo-cli/ │ ├── plugin-abi.md C ABI v1, SDK, host lifecycle │ ├── math.md removed core math outlook + migration (ADR-0061) │ ├── foreign.md Python/Node kernel protocol -│ ├── tool-v1.md generic external Tool Protocol v1 -│ ├── analysis-v2.md public Analysis v2 projection (v1 historical) -│ ├── analysis-v3.md projection for projects with loop transfers -│ ├── trace-v2.md public Trace v2 projection (v1 historical) -│ └── trace-v1.md public Trace v1 event stream +│ ├── cli-tool.md external command registration and dispatch +│ ├── analysis.md current static projection +│ └── observation.md live events and snapshots ├── crates/ │ ├── marqdo-span/ Span, LineCol, LineIndex (leaf) │ ├── marqdo-value/ Value, diagnostics, errors, wire encoding @@ -310,9 +308,8 @@ capability flags shown above). See [`STATUS.md`](STATUS.md). `docs/NEXT_RELEASE_CI_CONVERGENCE.md` are **Historical/Superseded** planning input (their banners link the RFC); `docs/STABLE_RELEASE_IMPLEMENTATION.md` is the authoritative next-phase/release plan. None describes implemented - behavior. `spec/tool-v1.md` is a candidate protocol until an ADR and - implementation tests land. Never cite a proposed or historical document as - evidence that a feature exists. + behavior. Use the current contracts and [ADR-0068](adr/0068-single-current-public-contracts.md) + when replacing a public interface. * Changes to language semantics, AST mapping, wire format, plugin ABI, package/lock format, authorization defaults or public CLI behavior require an **Accepted ADR** (or superseding one) plus spec updates and tests. Use the diff --git a/docs/developers/README.md b/docs/developers/README.md index 1a342be..ad11e2c 100644 --- a/docs/developers/README.md +++ b/docs/developers/README.md @@ -32,7 +32,7 @@ markdown profile `marqdo.md.v1`. Trace v2. 4. [extensions.md](extensions.md) — plugins, foreign kernels, resource providers, extension selection and lock v4. -5. [analysis-trace.md](analysis-trace.md) — the public static/dynamic data +5. [analysis-observation.md](analysis-observation.md) — the public static/dynamic data contracts, Execution Events v1 and digest binding. 6. [compatibility.md](compatibility.md) — version axes, platform matrix and the prerelease policy. diff --git a/docs/developers/analysis-observation.md b/docs/developers/analysis-observation.md new file mode 100644 index 0000000..891b3fb --- /dev/null +++ b/docs/developers/analysis-observation.md @@ -0,0 +1,43 @@ +# Analysis and Observation + +Run the same public CLI that users install. + +```sh +marqdo check index.mq.md --emit ./analysis.json +marqdo call index.mq.md main --output jsonl --observation-file ./run.json +``` + +A tool can use [Analysis](../../spec/analysis.md) to locate functions, imports, +references, resources and calls. Validate its identifier before walking the +module and statement arrays. Use the original UTF-8 bytes for offsets and +digest checks. The format is the same for a simple document and one using +structured loop transfers. + +[Observation](../../spec/observation.md) carries frames, control flow, committed +output and the final result. Consume JSONL for live updates, or use +`--output json` for one JSON snapshot on stdout. The snapshot's `events` +array has the same objects as the live stream. The first event opens the run +and the terminal event gives its outcome. Treat a stream that ends before a +terminal as incomplete. Base64 decode each stdout and stderr chunk and verify +its byte count. Read the typed return from `run.completed.payload.value`. + +Before highlighting source locations, compare the `run.started` root and +SHA-256 of the exact Analysis artifact, then check the source file digest. +A different report or edited source requires a fresh check and run. +The repository's independent consumer implements both delivery modes. + +```sh +python3 tests/consumers/observation_consumer.py ./run.json --snapshot \ + --analysis ./analysis.json --source-root . +``` + +Value capture uses exact names and explicit Text consent. Use +`--observe-variable NAME` and `--observe-parameter NAME` only for the +values the feature needs. Request `--observe-text-values` when the caller +has opted into this disclosure. Program output and explicit returned values +can themselves contain sensitive data. + +Update integrations that previously used the retired run/call JSON, +Trace or Execution Events options. Use the commands above, remove the old +reader, and rebuild and reinstall the Tool with the +[current manifest](../../spec/cli-tool.md). diff --git a/docs/developers/analysis-trace.md b/docs/developers/analysis-trace.md deleted file mode 100644 index 62c930d..0000000 --- a/docs/developers/analysis-trace.md +++ /dev/null @@ -1,121 +0,0 @@ -# Analysis and Trace v2 consumers - -Both are public, versioned JSON artifacts. A consumer must read them as files, -never link Marqdo's Rust internals or depend on `inspect --ir`. - -## Analysis v2 and v3 (static) - -```bash -marqdo check index.mq.md --emit ./analysis.json -``` - -- Write atomically; only publish after `check` exits 0. `--refs` is an - independent Markdown-link check and can make `check` fail; on failure the emit - target is removed. Do not generate a consumer artifact with - `check --refs --emit` without checking the exit code. -- `schema: "marqdo.analysis"`. The writer emits `schema_version: 2` for - projects without loop transfers and `3` when a function body contains - `break` or `continue`. Check the version before walking function bodies. - Both versions encode `else if` in the ordered `branch.arms` array. -- Top level: `producer` (`name`, `version` = product version, - `markdown_profile`), `project`, `modules`, `diagnostics`. -- `project`: `root_id` (`root:@` for manifest projects), - `identity_kind`, `lock_digest` (`""` without a lock), `stdlib` - (`version`, `digest`, `instance_id`; may be null). -- `modules[]`: `id`, `package_instance_id`, `relative_path`, `source_digest`, - `units`, `functions`, `imports`, `references`, `calls`, `resources`. - Diagnostics are top-level, not per-module. -- Byte offsets are UTF-8 source offsets. Stable index keys are logical package - instance ids, never absolute paths. -- `check` does not load plugin libraries, start kernels/providers or execute the - program. -- Contracts: [Analysis v2](../../spec/analysis-v2.md) and - [Analysis v3](../../spec/analysis-v3.md). Each links to its schema. - The independent consumers in `tests/consumers/` check the version and - decode the public nodes. - -View must render the **original Markdown** and use Analysis only to correlate -source offsets/heading units/callable mapping. Knowledge must use heading -anchors, links, resources, package identity and source digests; it must not -assume a `@knowledge` unit has runtime effects. Prove must map only the public -proveable subset and distinguish `proved / disproved / unknown / unsupported`; -a proof certificate needs matching source digest, semantics and contract -identity. - -## Trace v2 (dynamic) - -```bash -marqdo run index.mq.md --trace-file ./trace.json -``` - -- `schema: "marqdo.trace"`, `schema_version: 2`. -- `source.analysis_digest` must equal SHA-256 of the **Analysis JSON bytes** for - the same project/projection configuration. A mismatch means the trace is - stale; do not bind it to the new source. `run --trace-file` does not emit - Analysis itself. -- Event kinds: `call.enter`, `call.exit`, `branch.eval`, `loop.iteration`, - `control.break`, `control.continue`, `return`, `effect` and possibly - `trace.truncated`. Sourced events carry a - module id and a UTF-8 span. -- Defaults are 100,000 events / 32 MiB; `--trace-max-events` and - `--trace-max-bytes` adjust them (`0` = unlimited). A consumer must tolerate - truncation and must not assume the trace is complete. -- Trace records no argument values, secrets or file contents. -- Contract: `spec/trace-v2.md`; schema: - `spec/schemas/trace-v2.schema.json`; consumer: - `tests/consumers/trace_consumer.py`. - -## Execution Events v1 (live) - -```bash -marqdo run index.mq.md --event-stream jsonl -marqdo call index.mq.md main --arg n=5 --event-stream jsonl -marqdo run index.mq.md --event-stream jsonl --trace-file ./trace.json -``` - -- `schema: "marqdo.execution-events"`, `schema_version: 1`. This is a separate - protocol from Analysis/Trace and has its own version axis. -- While active, the CLI stdout is a **pure NDJSON channel**: one JSON object per - line, `seq` starts at 0 and is strictly increasing. Program stdout/stderr are - only `stdout.chunk`/`stderr.chunk` events with `encoding: "base64"`, - `data_base64` and a matching `byte_count`. Concatenated decoded bytes equal a - normal run's output; invalid UTF-8/NUL/binary bytes are preserved. -- `stream.opened` is always seq 0. A run then has at most one `run.started` and - exactly one terminal event (`run.completed`, `run.failed`, `run.rejected`) on - a complete stream. An EOF without a terminal event is `incomplete` - (SIGKILL/crash/broken pipe); never synthesize success. -- `run.started.source` contains `root_id` and the `sha256:` digest of the exact - Analysis bytes. `--trace-file` may be combined; both writers share one - opaque run id, and Trace v2 remains atomic and value-free. -- Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`), - `return`, `branch.eval`, `loop.iteration`, `control.break`, - `control.continue` and `effect`. Frames identify call - instances, not functions; a failed argument binding creates no frame. -- Values are off by default (`value_state: not_requested`). - `--observe-variable NAME` and `--observe-parameter NAME` are exact-name - selections. `Int`/`Float`/`Bool` are bounded by - `--observe-max-value-bytes` (default 256); selected `Text` is `redacted` until - `--observe-text-values` is also passed. Containers, `Memory`, resources and - plugin handles are `unsupported`; handles are never serialized. -- Structural/value events have a separate budget - (`--observe-max-events`, `--observe-max-bytes`; defaults 100 000 / 16 MiB). - Exhaustion emits one `observation.truncated` and still delivers stdout/stderr - and the terminal event. A broken output pipe fails the run with - `observe.transport_failed`; it never keeps executing side effects silently. -- `--event-stream` is mutually exclusive with `--json`, rejected by - `check`/`inspect`/`fmt`/`tool`, and currently rejected by `--mode strict` - (fail-closed, no downgrade). It is not a capability grant. -- Contract: [`../../spec/execution-events-v1.md`](../../spec/execution-events-v1.md); - schema: `spec/schemas/execution-events-v1.schema.json`; consumer: - `tests/consumers/execution_events_consumer.py`; fixtures and Rust gate: - `tests/consumers/fixtures/execution-events/` and - `crates/cli/tests/execution_events.rs`. - -## Consumer rules - -1. Reject unknown schema majors; there is no silent "use latest" fallback. -2. Verify `source.analysis_digest` against the actual Analysis file bytes. -3. Verify `source.root_id`/package identity; do not key on absolute paths. -4. Be deterministic and offline; never execute `.mq.md` yourself, never invent - host effects, and never inherit Marqdo grants. -5. Report an unsupported/stale artifact explicitly; do not silently downgrade. diff --git a/docs/developers/compatibility.md b/docs/developers/compatibility.md index da4a949..4ba55d6 100644 --- a/docs/developers/compatibility.md +++ b/docs/developers/compatibility.md @@ -38,7 +38,7 @@ Strict is Linux-only and probe-gated. Plugin/provider worker transports are not OS sandboxes. `pure`/`project` are execution modes, not security boundaries. Execution Events v1 is a live observation protocol: it is not a capability grant, values are off by default, and `--mode strict` currently refuses -`--event-stream` explicitly (no downgrade). +`--output jsonl` explicitly (no downgrade). ## Language compatibility diff --git a/docs/developers/quickstart.md b/docs/developers/quickstart.md index 3d02aaa..e3820af 100644 --- a/docs/developers/quickstart.md +++ b/docs/developers/quickstart.md @@ -48,7 +48,7 @@ marqdo call index.mq.md main ``` `run` executes the entry function (`main` by default) and prints program output; -`call` prints the returned value. Use `--json` for machine-readable +`call` prints the returned value. Use `--output json` for machine-readable results (`{"command":"run","success":true,...}`), including embedded program stdout and diagnostics. @@ -76,8 +76,8 @@ stdout and diagnostics. ```bash marqdo check index.mq.md --json -marqdo run index.mq.md --json -marqdo call index.mq.md main --json +marqdo run index.mq.md --output json +marqdo call index.mq.md main --output json ``` ## 5. Where next @@ -85,6 +85,6 @@ marqdo call index.mq.md main --json - Publish/consume a pure library: [libraries.md](libraries.md). - Build an external tool: [tools.md](tools.md). - Plugins, kernels, providers: [extensions.md](extensions.md). -- Analysis/Trace consumers: [analysis-trace.md](analysis-trace.md). +- Analysis/Trace consumers: [analysis-observation.md](analysis-observation.md). - Version axes and platform support: [compatibility.md](compatibility.md). - Beta limitations: [release-limits.md](release-limits.md). diff --git a/docs/developers/release-limits.md b/docs/developers/release-limits.md index ecbecd1..3ca0437 100644 --- a/docs/developers/release-limits.md +++ b/docs/developers/release-limits.md @@ -84,7 +84,7 @@ an untrusted Git URL does not make the code trustworthy. * Not implemented: memory region/budget metadata (OBS-06/P2), raw memory content, breakpoints/stepping/time travel, and a bidirectional debug protocol. Do not infer a debugger from this protocol. -* `--mode strict` currently rejects `--event-stream` explicitly; there is no +* `--mode strict` currently rejects `--output jsonl` explicitly; there is no silent fallback to `project`. * The live lane is tested on Linux x86_64; macOS/Windows are unverified for this option for this candidate. diff --git a/docs/developers/tools.md b/docs/developers/tools.md index cae09d4..a3b693a 100644 --- a/docs/developers/tools.md +++ b/docs/developers/tools.md @@ -5,7 +5,7 @@ product command. A tool is a **separate executable** registered by the user; the CLI only dispatches unknown top-level commands to registered tools and never scans `PATH` for a guessed name. -Normative contract: [`../../spec/tool-v1.md`](../../spec/tool-v1.md) +Normative contract: [`../../spec/cli-tool.md`](../../spec/cli-tool.md) (implemented and frozen for protocol v1). ## 1. Package layout @@ -106,7 +106,7 @@ stream to its own SSE/websocket transport; the CLI never implements HTTP/SSE. This option is unavailable under `--mode strict` in the current tree and the tool must surface that refusal instead of pretending real-time support. -See [analysis-trace.md](analysis-trace.md) for fields and digest rules. Do not +See [analysis-observation.md](analysis-observation.md) for fields and digest rules. Do not depend on `inspect --ir`: that JSON is not a frozen cross-repository protocol. The `view` tool renders the **original Markdown**, not the Analysis JSON; the Analysis is an index, not a replacement for the source text. diff --git a/examples/tool-samples/sample-knowledge/src/main.rs b/examples/tool-samples/sample-knowledge/src/main.rs index 08ad2cb..36f6525 100644 --- a/examples/tool-samples/sample-knowledge/src/main.rs +++ b/examples/tool-samples/sample-knowledge/src/main.rs @@ -1,4 +1,4 @@ -//! Independent Tool Protocol v1 consumer: reads a small part of Trace v2. +//! Independent Tool Protocol v1 consumer: reads a small part of Analysis. use std::fs; @@ -27,11 +27,11 @@ fn main() { let args: Vec = std::env::args().skip(1).collect(); let path = args .iter() - .position(|arg| arg == "--trace") + .position(|arg| arg == "--analysis") .and_then(|index| args.get(index + 1)) .or_else(|| args.first()) .unwrap_or_else(|| { - eprintln!("usage: sample-knowledge --trace "); + eprintln!("usage: sample-knowledge --analysis "); std::process::exit(2); }); let json = fs::read_to_string(path).unwrap_or_else(|error| { @@ -39,16 +39,15 @@ fn main() { std::process::exit(1); }); let schema = string_field(&json, "schema").unwrap_or_default(); - if schema != "marqdo.trace" { - eprintln!("sample-knowledge: expected marqdo.trace, got {schema:?}"); + if schema != "marqdo.analysis" { + eprintln!("sample-knowledge: expected marqdo.analysis, got {schema:?}"); std::process::exit(1); } let version = number_field(&json, "schema_version").unwrap_or_default(); - if version != 2 { - eprintln!("sample-knowledge: unsupported Trace version {version}"); + if version != 3 { + eprintln!("sample-knowledge: unsupported Analysis version {version}"); std::process::exit(1); } - let status = string_field(&json, "status").unwrap_or_default(); - let events = json.matches("\"seq\"").count(); - println!("sample-knowledge schema={schema} version={version} events={events} status={status}"); + let references = json.matches("\"references\"").count(); + println!("sample-knowledge schema={schema} version={version} reference_sets={references}"); } diff --git a/examples/tool-samples/sample-knowledge/tool.json b/examples/tool-samples/sample-knowledge/tool.json index 0be35cd..1596da5 100644 --- a/examples/tool-samples/sample-knowledge/tool.json +++ b/examples/tool-samples/sample-knowledge/tool.json @@ -7,7 +7,6 @@ "entrypoint": "bin/sample-knowledge", "requires": { "api_revision": 1, - "analysis": 3, - "observation": 1 + "analysis": 3 } } diff --git a/examples/tool-samples/sample-proof/src/main.rs b/examples/tool-samples/sample-proof/src/main.rs index 168ec2b..606c36b 100644 --- a/examples/tool-samples/sample-proof/src/main.rs +++ b/examples/tool-samples/sample-proof/src/main.rs @@ -1,4 +1,4 @@ -//! Independent Tool Protocol v1 consumer: binds Analysis v2 and Trace v2. +//! Independent Tool Protocol v1 consumer: reads an Analysis and Observation source binding. use std::fs; @@ -22,38 +22,39 @@ fn read(path: &str, label: &str) -> String { fn main() { let args: Vec = std::env::args().skip(1).collect(); let mut analysis = None; - let mut trace = None; + let mut snapshot = None; let mut index = 0; while index + 1 < args.len() { match args[index].as_str() { "--analysis" => analysis = Some(args[index + 1].clone()), - "--trace" => trace = Some(args[index + 1].clone()), + "--observation" => snapshot = Some(args[index + 1].clone()), _ => {} } index += 2; } - let (Some(analysis), Some(trace)) = (analysis, trace) else { - eprintln!("usage: sample-proof --analysis --trace "); + let (Some(analysis), Some(snapshot)) = (analysis, snapshot) else { + eprintln!("usage: sample-proof --analysis --observation "); std::process::exit(2); }; let analysis = read(&analysis, "analysis"); - let trace = read(&trace, "trace"); + let snapshot = read(&snapshot, "snapshot"); if string_field(&analysis, "schema") != Some("marqdo.analysis") { eprintln!("sample-proof: analysis schema mismatch"); std::process::exit(1); } - if string_field(&trace, "schema") != Some("marqdo.trace") { - eprintln!("sample-proof: trace schema mismatch"); + if string_field(&snapshot, "schema") != Some("marqdo.observation") { + eprintln!("sample-proof: snapshot schema mismatch"); std::process::exit(1); } - if string_field(&trace, "status") != Some("ok") { - eprintln!("sample-proof: trace did not complete successfully"); + let run = snapshot.rsplit_once("\"run\"").map(|(_, run)| run).unwrap_or_default(); + if string_field(run, "status") != Some("ok") { + eprintln!("sample-proof: snapshot did not complete successfully"); std::process::exit(1); } - let digest = string_field(&trace, "analysis_digest").unwrap_or_default(); + let digest = string_field(&snapshot, "analysis_digest").unwrap_or_default(); if !digest.starts_with("sha256:") { - eprintln!("sample-proof: trace is not bound to an analysis digest"); + eprintln!("sample-proof: snapshot is not bound to an analysis digest"); std::process::exit(1); } - println!("sample-proof bound=true digest={digest}"); + println!("sample-proof claimed_digest={digest}"); } diff --git a/examples/tool-samples/sample-view/src/main.rs b/examples/tool-samples/sample-view/src/main.rs index 6cd830f..be21304 100644 --- a/examples/tool-samples/sample-view/src/main.rs +++ b/examples/tool-samples/sample-view/src/main.rs @@ -1,4 +1,4 @@ -//! Independent Tool Protocol v1 consumer: reads a small part of Analysis v2. +//! Independent Tool Protocol v1 consumer: reads a small part of Analysis. //! //! This is a test fixture, not a hard-coded CLI command. Build it with //! `rustc --edition 2021`, package it with `tool.json`, install it, and invoke @@ -35,7 +35,7 @@ fn main() { .and_then(|index| args.get(index + 1)) .or_else(|| args.first()) .unwrap_or_else(|| { - eprintln!("usage: sample-view --analysis "); + eprintln!("usage: sample-view --analysis "); std::process::exit(2); }); let json = fs::read_to_string(path).unwrap_or_else(|error| { diff --git a/spec/execution-events-v1.md b/spec/execution-events-v1.md deleted file mode 100644 index ca086ca..0000000 --- a/spec/execution-events-v1.md +++ /dev/null @@ -1,340 +0,0 @@ -# Execution Events v1 - -Status: **implemented by `marqdo run/call --event-stream jsonl`** (P0 and P1 of -RFC-OBS-0001). It is an independent public protocol: it is not Analysis v2, -not Trace v2 and not Tool Protocol v1. The decision record is -[ADR-0059](../docs/adr/0059-runtime-observability-and-execution-events.md); the -design input is [RFC-OBS-0001](../docs/architecture/RFC-OBS-0001-runtime-observability.md). - -## 1. Transport and negotiation - -* Media type: `application/x-ndjson` (JSON Lines). One complete UTF-8 JSON - object per line, terminated by `\n`; no unescaped newline occurs inside an - event. -* The stream uses the CLI stdout as a **dedicated machine channel**. While - `--event-stream jsonl` is active, the program's `stdout` and `stderr` are - carried only as `stdout.chunk` / `stderr.chunk` events and are not written - raw to stdout. Human diagnostics may still go to OS stderr. -* `--event-stream jsonl` is available only on `run` and `call`. It is - mutually exclusive with `--json`; `check`, `inspect`, `fmt`, `tool` and the - other static commands reject the option. `--trace-file` may be combined. -* `--mode strict` currently rejects `--event-stream` with a structured - `run.rejected` (`strict.unsupported_grant`); there is no silent downgrade to - `project`. -* The consumer checks the negotiated protocol from `stream.opened` - (`schema` + `schema_version`). Consumers **must reject unknown major - versions**, and must not silently treat another major as v1. -* A consumer that cannot read the stream (slow, closed pipe, killed process) - may see a truncated final line or no terminal event. It must report - `incomplete`; it must never synthesize a successful terminal event. - -## 2. Envelope - -Every normal line has exactly these top-level fields: - -```json -{ - "schema": "marqdo.execution-events", - "schema_version": 1, - "run_id": "12345-1700000000000000000", - "seq": 2, - "kind": "call.enter", - "payload": {} -} -``` - -| Field | Type | Meaning | -|---|---|---| -| `schema` | string | Always `marqdo.execution-events`. | -| `schema_version` | integer | Major version; currently `1`. | -| `run_id` | string | Opaque identity of this one run. Never an OS PID used as a cross-run identity. Different for every invocation, including repeated runs in one process. | -| `seq` | integer | Global, strictly increasing, starts at 0, assigned by one dispatcher. `seq` is the event sequence, not a frame or iteration identity. | -| `kind` | string | Stable namespaced event name. New kinds are additive; consumers ignore unknown kinds. | -| `payload` | object | Kind-specific object defined below. Unknown optional fields are ignored. | - -Event ordering is the order of admission to the single dispatcher. Independent -OS streams (for example a foreign subprocess writing its own fd) do not have a -portable physical ordering and are not part of this protocol. - -## 3. Lifecycle and event kinds - -Exactly one `stream.opened` is written when the JSONL writer is initialized, -before project preparation. At most one `run.started` is written. On success or -failure there is exactly one terminal event, and no event is written after it. -The normal order is: - -```text -stream.opened (seq 0) - -> run.rejected (prepare/authorization/compile failure) - or run.started -> ... -> run.completed | run.failed -``` - -`run.completed`, `run.failed` and `run.rejected` are the only terminal events. -`SIGKILL`, a crash or a broken pipe may leave the stream without a terminal -event; that is a legitimate `incomplete` boundary. - -### 3.1 `stream.opened` (base, seq 0) - -Required payload fields: - -```json -{ - "producer": {"name": "marqdo", "version": "3.0.0-beta.1"}, - "protocol": {"name": "marqdo.execution-events", "schema_version": 1}, - "observation": { - "level": "structural", - "values": false, - "selected_variables": [], - "selected_parameters": [], - "allow_text_values": false - }, - "limits": { - "max_observation_events": 100000, - "max_observation_bytes": 16777216, - "max_value_bytes": 256 - } -} -``` - -`observation.level` is `base`, `structural` or `values`. It reports what the -producer is willing to publish, not a security grant. `stream.opened` does not -carry a source identity because no project has been prepared yet. - -### 3.2 `run.started` (base) - -Required payload fields: `entry`, `mode`, `source`; optional -`started_unix_ms` for diagnostics only. - -```json -{ - "entry": "root:demo@0.1.0::index.mq.md::main", - "mode": "project", - "source": { - "root_id": "root:demo@0.1.0", - "analysis_digest": "sha256:<64 lowercase hex>" - }, - "started_unix_ms": 1763800000000 -} -``` - -`source.analysis_digest` is `sha256:` plus the SHA-256 of the **exact bytes** -of the [Analysis file](analysis-v3.md) produced for the same project and projection -configuration (not a re-serialization of the in-memory IR). If the source -changes, existing events become stale; consumers must not render them onto the -new source. - -### 3.3 `stdout.chunk` / `stderr.chunk` (base) - -Required payload fields: - -```json -{"encoding": "base64", "data_base64": "5byA5aeL5paH5pysCg==", "byte_count": 13} -``` - -* `encoding` is `base64` (standard alphabet, padded). -* `data_base64` is the byte-exact data. Invalid UTF-8, NUL, binary bytes and - split multi-byte characters are preserved. -* `byte_count` equals the decoded byte length. A consumer must verify it. -* Chunks are bounded (implementation maximum 64 KiB before base64 encoding); - a larger host write is split into consecutive chunks in order. -* These events are emitted at the host's real commit point: bytes are exactly - those accepted by the host output budget. A rejected write emits nothing. -* All committed chunk events precede the terminal event. Concatenating the - decoded bytes must equal the bytes a normal run writes to stdout/stderr for - the same arguments and grants. - -### 3.4 Structural events (structural) - -| Kind | Required payload fields | -|---|---| -| `call.enter` | `frame_id`, `parent_frame_id`, `function_id`, `module_id`, `span` | -| `call.exit` | `frame_id`, `status`, `module_id`, `span` | -| `return` | `frame_id`, `value_type`, `module_id`, `span` | -| `branch.eval` | `frame_id`, `result`, `module_id`, `span` | -| `loop.iteration` | `frame_id`, `decision`, `module_id`, `span` | -| `control.break`, `control.continue` | `frame_id`, `module_id`, non-null `span` | -| `effect` | `operation`, `result_code`, `module_id`, `span` | - -* `frame_id` is an opaque run-unique string (`f1`, `f2`, ...). It identifies - one call instance, not a function and not a source location. -* `parent_frame_id` is `null` for the entry frame, otherwise the direct - caller's `frame_id`. -* A frame is announced by `call.enter` only **after** argument binding - succeeded. A binding failure produces no frame. Every entered frame that is - not cut off by transport loss/truncation gets exactly one `call.exit`; - `return` (when present) precedes `call.exit`. -* `call.exit.status` is `ok`, `return`, or a stable runtime error code. -* `branch.eval.result` is a JSON boolean. `loop.iteration.decision` is - `continue` (body will execute) or `exit` (condition was false). The event is - emitted once per condition evaluation; iteration indices are not part of v1. -* `control.break` and `control.continue` report an executed transfer at - its carrier span. The frame stays active. A continue precedes the next - condition check, and a break skips further checks of the loop it exits. - The structural event budget applies to both events. -* `effect.result_code` is a non-sensitive result summary (for example `ok` or a - stable error code). It never carries effect arguments or file contents. -* `module_id` is a logical package module id; `span` is - `{"start": , "end": }` in UTF-8 source offsets, or `null`. A - span must belong to the declared module. - -Example: - -```json -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"r1","seq":3,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}} -``` - -### 3.5 Value observation events (values) - -`variable.assigned` required payload fields: `frame_id`, `name`, -`value_type`, `module_id`, `span`, `value_state`; optional `value` when -`value_state` is `observed` or `truncated`. - -`parameter.observed` required payload fields: `frame_id`, `name`, `source`, -`value_type`, `module_id`, `span`, `value_state`; optional `value`. `source` -is `provided` or `default` (a source default is a real runtime value but not a -user-provided argument). - -`value_state` is one of: - -| State | Meaning | -|---|---| -| `not_requested` | The name was not selected for observation; no value is encoded. | -| `redacted` | The name was selected but policy hides the value (for example `Text` without `--observe-text-values`). | -| `truncated` | The value was encoded but exceeded `max_value_bytes`; `value` is the safe prefix. | -| `unsupported` | The value type is not a v1 scalar; only its type is reported. | -| `observed` | The scalar value is encoded normally. | - -Value encoding reuses the `marqdo.value.v1` wire representation of the value: -`{"type":"int","decimal":"42"}`, `{"type":"float","value":1.5}`, -`{"type":"bool","value":true}`, `{"type":"text","value":"..."}`. For a -truncated text the object also carries `"truncated": true` and -`"original_byte_count": `. Text truncation never splits a UTF-8 scalar. -Lists, maps, tables, formulas, code, memory, resources and plugin handles are -`unsupported`; they are never recursed into and handles are never serialized. -A text value is never published without the explicit -`--observe-text-values` consent, even when the name was selected. A -`--observe-max-value-bytes` value of `0` means unlimited; otherwise text is -cut only at a UTF-8 scalar boundary and marked `truncated`. - -`variable.assigned` is emitted only after the assignment was actually -committed. It never re-evaluates the right-hand side and never back-fills the -final value of a variable into an earlier assignment. - -### 3.6 `observation.truncated` (any) - -Required payload fields: `reason`, `limit`, `written`, `dropped`. `reason` is -`event_budget` or `byte_budget`. It is emitted at most once per run, only when -the structural/value observation budget is exhausted. It does not stop -stdout/stderr events or the terminal event. `dropped` may be `null` when the -producer cannot know the exact count. - -### 3.7 Terminal events (base) - -`run.completed`: - -```json -{"status":"ok","value":{"type":"int","decimal":"10"}} -``` - -`run.failed`: - -```json -{"status":"error","error":{"code":"runtime.type","message":"safe diagnostic message","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":120,"end":141}}} -``` - -`run.rejected`: - -```json -{"status":"rejected","phase":"prepare","error":{"code":"frontmatter.invalid","message":"safe diagnostic message"}} -``` - -* `run.completed.value` uses the same wire encoding as `run/call --json`. -* `run.failed.error.code` reuses the existing stable runtime error family; the - message is the same safe diagnostic text already printed to humans. It does - not add argument values, secrets, file contents or memory bytes. -* `run.rejected.phase` is `options`, `prepare`, `compile`, `authorization` or - `strict`. It distinguishes failures before execution started. -* A terminal event is written only after all committed chunk events. A - `run.completed` does not claim the consumer has read or displayed the bytes. - -## 4. Budgets, backpressure and failure - -Three separate resources exist and are never conflated: - -1. **Execution budgets** (`--fuel`, `--timeout`, `--max-output`, memory - budgets). Observation never widens them. A rejected host output write emits - no chunk event. -2. **Observable structural/value budget.** Defaults are 100 000 events and - 16 MiB, adjustable with `--observe-max-events` / `--observe-max-bytes` - (`0` = unlimited). Exhaustion truncates only these events and emits - `observation.truncated`. -3. **Critical transport events.** `stream.opened`, `run.started`, stdout/stderr - chunks and the terminal event are not dropped by the structural budget. - -Writes are synchronous and bounded. A slow consumer exerts IO backpressure on -the run; the CLI must not accumulate an unbounded queue or spawn an unbounded -event thread. If the JSONL writer fails (closed pipe, write error), the run -must fail with `observe.transport_failed`, return a non-zero exit status and -stop a program that would otherwise keep producing side effects. The CLI must -not write a partial JSON line after a failure. Side effects that already -happened are not rolled back and must not be claimed as rolled back. - -If event transport is truncated but still writable (structural budget), the -program's language behavior, return value, output bytes and capability -authorization are unchanged. - -## 5. Value policy and security - -* Event mode is not a capability grant and cannot enable network, filesystem, - process, foreign, provider or plugin access. `pure`, `project` and `strict` - keep their documented policy; if a project extension is rejected in a mode, - event mode is rejected for the same reason. -* Observation is off by default. Type/status metadata is the default; raw - values require an explicit exact-name selection. Text requires a second - explicit consent. Selection is not automatic from a manifest, View setting - or environment. -* Program stdout/stderr may contain secrets by the program's own intent; the - protocol preserves bytes and does not promise automatic redaction of program - output. -* Trace v2 and Analysis never gain argument/local values, handles, memory - bytes or new secret-bearing fields through this protocol. -* A third-party extension's raw OS stdout/stderr must not pollute the JSONL - channel. Such output remains external process data: it is either captured by - the controlled host transport or the combination is unsupported/fail-closed. - In particular, an in-process **native plugin** can write fd 1 directly, so an - event-mode run that selects one is rejected with - `ext.event_stream_unsupported_native_plugin` before loading; use a worker - plugin or disable event mode. -* Tests use synthetic sentinel values and assert that unselected values never - appear in the stream, Trace or `--json`. - -## 6. Relation to Analysis and Trace v2 - -| Artifact | Relation | -|---|---| -| Analysis v2/v3 | Static only. `run.started.source` binds to its exact bytes via `analysis_digest`. Events never replace it. | -| Trace v2 | Unchanged schema/version and privacy promise. In a combined run both writers share the CLI-generated `run_id`; Trace v2 gains no frame/value fields and is still published atomically after the run. | -| Tool Protocol v1 | Unchanged. A consumer invokes the released binary via `MARQDO_BIN` and negotiates by reading `stream.opened`; `tool.json` does not implicitly advertise an `events` field. | -| View SSE | Implemented by the View repository by adapting this JSONL stream. The CLI implements no HTTP/SSE. | - -## 7. Versioning and compatibility - -* Independent major version `1`, not tied to the product version or Trace v2. -* Additive optional fields and new event kinds are allowed in v1. Changing a - required field's meaning, ordering guarantees, redaction promise, source - digest definition or making private data public by default requires a new - major. -* Consumers must ignore unknown `kind` and unknown optional fields, and must - reject unknown `schema_version` majors. -* `--help`, `docs/developers/analysis-trace.md`, - `docs/developers/compatibility.md` and `COMPATIBILITY.md` list the protocol - and its exact option names. - -## 8. Test fixtures and consumers - -* Schema: [`schemas/execution-events-v1.schema.json`](schemas/execution-events-v1.schema.json). -* Independent consumer: `tests/consumers/execution_events_consumer.py`. -* Fixtures: `tests/consumers/fixtures/execution-events/`. -* Rust gate: `crates/cli/tests/execution_events.rs` runs the real binary and - checks envelope, sequence, base64 byte fidelity, terminal behavior, - redaction, frames, traces and output purity. diff --git a/spec/observation.md b/spec/observation.md new file mode 100644 index 0000000..db849af --- /dev/null +++ b/spec/observation.md @@ -0,0 +1,78 @@ +# Marqdo Observation + +`run` and `call` execute once through the interpreter and capability Host. +The Host emits typed observations at execution boundaries. The CLI assigns +one run ID and one sequence and serializes each public event once. + +```sh +marqdo call index.mq.md calculate --arg n=3 --output jsonl +marqdo call index.mq.md calculate --arg n=3 --output json +marqdo call index.mq.md calculate --arg n=3 --output jsonl --observation-file run.json +marqdo check index.mq.md --emit analysis.json +``` + +Text is the default output. JSONL flushes each event to stdout as it occurs. +JSON writes one snapshot to stdout after the run. `--observation-file` +atomically publishes a snapshot through a private temporary file in the +destination directory. On Unix the published file is private to the caller. +Every destination in one invocation receives the same events. Diagnostics +use OS stderr. Captured program stdout and stderr are byte events, with +standard padded base64 and a decoded byte count. Both may contain sensitive +program output. Machine destinations refuse in-process native plugins. +Strict mode supports text and JSON stdout through its isolation supervisor. +Live and file destinations are rejected in strict mode. + +## Event contract + +Each object has `schema: "marqdo.observation"`, `schema_version: 1`, an +opaque `run_id`, zero-based contiguous `seq`, `kind` and `payload`. See +the [event schema](schemas/observation-event.schema.json) for the exact +fields. Reject other format identifiers, unknown kinds and invalid payloads. + +- `stream.opened` is first, with producer, capture policy and budget limits. +- `run.started` binds an entry, mode and source. `source.root_id` and + `source.analysis_digest` identify the exact Analysis JSON emitted by + `check --emit` for the same project and static options. The digest is + SHA-256 over the file bytes, including formatting. Before highlighting a + source span, validate the binding, module source digest and original UTF-8 + half-open byte range. A changed source or Analysis invalidates attribution. +- `call.enter` identifies the call instance and its parent. `call.exit` + closes that same instance. Call carriers belong to the caller module. + Parameter spans identify declarations in the called module. +- `branch.eval`, `loop.iteration`, `control.break`, `control.continue`, + `return` and `effect` record actual execution in order. An effect + includes its operation, result code and source location where available. +- `parameter.observed` and `variable.assigned` carry names, types and + source locations. Values are omitted by default. Select exact names + with `--observe-parameter` and `--observe-variable`. Selected Text also + requires `--observe-text-values`. The same consent applies to file and + stream. Only supported scalars are recorded. Memory, resources and plugin + handles are never included. +- `observation.truncated` reports the first exhausted observation budget. + Structural and selected-value events may stop at that point. Lifecycle + and committed byte chunks remain subject to their own execution and + output limits. The interpreter continues under unchanged program limits. +- `run.completed` contains the explicit return using [Value Wire](value-wire.md). + A result containing a non-transferable handle has a null wire value and + identifies its type. An explicit result, like a program print, can itself + contain sensitive data. `run.failed` follows a started run and contains + the error. `run.rejected` reports failure before start. A complete run + has exactly one terminal event, last. EOF or interrupted delivery without + a terminal is incomplete. + +## Snapshot contract + +The [snapshot schema](schemas/observation-file.schema.json) describes a +JSON object with the same format identifier, `run` metadata, `capture` +metadata, and `events` validated against the event schema. The `run.id` +matches every event, `run.source` matches the start event or is null, +and `run.status` agrees with the terminal. `capture.truncated` matches +the truncation event or is null. A supervisor that cannot obtain complete +child output may report an incomplete stdout snapshot without a terminal. +An interrupted file write does not replace the previously published file. +EOF during an interrupted stream can leave a partial final line. + +Validate schema, sequence, lifecycle and source binding before using +the artifact. A structurally truncated run has a terminal but lacks some +execution events. An incomplete delivery provides no evidence about +the final execution outcome. diff --git a/spec/schemas/execution-events-v1.schema.json b/spec/schemas/execution-events-v1.schema.json deleted file mode 100644 index 3b9c95b..0000000 --- a/spec/schemas/execution-events-v1.schema.json +++ /dev/null @@ -1,291 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/execution-events-v1.schema.json", - "title": "Marqdo Execution Events v1", - "description": "One line of the marqdo.execution-events v1 NDJSON stream.", - "type": "object", - "required": ["schema", "schema_version", "run_id", "seq", "kind", "payload"], - "properties": { - "schema": {"const": "marqdo.execution-events"}, - "schema_version": {"const": 1}, - "run_id": {"type": "string", "minLength": 1}, - "seq": {"type": "integer", "minimum": 0}, - "kind": {"type": "string", "minLength": 1}, - "payload": {"type": "object"} - }, - "additionalProperties": true, - "allOf": [ - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "stream.opened"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["producer", "protocol", "observation", "limits"], - "properties": { - "producer": { - "type": "object", - "required": ["name", "version"], - "properties": { - "name": {"const": "marqdo"}, - "version": {"type": "string", "minLength": 1} - }, - "additionalProperties": true - }, - "protocol": { - "type": "object", - "required": ["name", "schema_version"], - "properties": { - "name": {"const": "marqdo.execution-events"}, - "schema_version": {"const": 1} - }, - "additionalProperties": true - }, - "observation": { - "type": "object", - "required": ["level", "values", "selected_variables", "selected_parameters", "allow_text_values"], - "properties": { - "level": {"enum": ["base", "structural", "values"]}, - "values": {"type": "boolean"}, - "selected_variables": {"type": "array", "items": {"type": "string"}}, - "selected_parameters": {"type": "array", "items": {"type": "string"}}, - "allow_text_values": {"type": "boolean"} - }, - "additionalProperties": true - }, - "limits": { - "type": "object", - "required": ["max_observation_events", "max_observation_bytes", "max_value_bytes"], - "properties": { - "max_observation_events": {"type": "integer", "minimum": 0}, - "max_observation_bytes": {"type": "integer", "minimum": 0}, - "max_value_bytes": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "run.started"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["entry", "mode", "source"], - "properties": { - "entry": {"type": "string", "minLength": 1}, - "mode": {"enum": ["pure", "project", "strict"]}, - "source": { - "type": "object", - "required": ["root_id", "analysis_digest"], - "properties": { - "root_id": {"type": "string", "pattern": "^(root:|sha256:[0-9a-f]{64}$)"}, - "analysis_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"} - }, - "additionalProperties": true - }, - "started_unix_ms": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"enum": ["stdout.chunk", "stderr.chunk"]}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["encoding", "data_base64", "byte_count"], - "properties": { - "encoding": {"const": "base64"}, - "data_base64": {"type": "string", "contentEncoding": "base64"}, - "byte_count": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "call.enter"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["frame_id", "parent_frame_id", "function_id", "module_id", "span"], - "properties": { - "frame_id": {"type": "string", "pattern": "^f[0-9]+$"}, - "parent_frame_id": {"oneOf": [{"type": "null"}, {"type": "string", "pattern": "^f[0-9]+$"}]}, - "function_id": {"type": "string", "minLength": 1}, - "module_id": {"type": "string", "minLength": 1}, - "span": {"$ref": "#/$defs/span"} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"enum": ["call.exit", "return", "branch.eval", "loop.iteration", "effect"]}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["module_id", "span"], - "properties": { - "frame_id": {"type": "string", "pattern": "^f[0-9]+$"}, - "status": {"type": "string", "minLength": 1}, - "value_type": {"type": "string", "minLength": 1}, - "result": {"type": "boolean"}, - "decision": {"enum": ["continue", "exit"]}, - "operation": {"type": "string", "minLength": 1}, - "result_code": {"type": "string", "minLength": 1}, - "module_id": {"type": "string", "minLength": 1}, - "span": {"$ref": "#/$defs/span"} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"enum": ["control.break", "control.continue"]}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["frame_id", "module_id", "span"], - "properties": { - "frame_id": {"type": "string", "pattern": "^f[0-9]+$"}, - "module_id": {"type": "string", "minLength": 1}, - "span": {"type": "object", "$ref": "#/$defs/span"} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"enum": ["variable.assigned", "parameter.observed"]}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["frame_id", "name", "value_type", "module_id", "span", "value_state"], - "properties": { - "frame_id": {"type": "string", "pattern": "^f[0-9]+$"}, - "name": {"type": "string", "minLength": 1}, - "source": {"enum": ["provided", "default"]}, - "value_type": {"type": "string", "minLength": 1}, - "module_id": {"type": "string", "minLength": 1}, - "span": {"$ref": "#/$defs/span"}, - "value_state": {"enum": ["not_requested", "redacted", "truncated", "unsupported", "observed"]}, - "value": {"type": ["object", "null"]} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "observation.truncated"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["reason", "limit", "written", "dropped"], - "properties": { - "reason": {"enum": ["event_budget", "byte_budget"]}, - "limit": {"type": "integer", "minimum": 0}, - "written": {"type": "integer", "minimum": 0}, - "dropped": {"type": ["integer", "null"], "minimum": 0} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "run.completed"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["status", "value"], - "properties": { - "status": {"const": "ok"}, - "value": {"type": "object"} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "run.failed"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["status", "error"], - "properties": { - "status": {"const": "error"}, - "error": {"$ref": "#/$defs/error"} - }, - "additionalProperties": true - } - } - } - }, - { - "if": {"required": ["kind"], "properties": {"kind": {"const": "run.rejected"}}}, - "then": { - "properties": { - "payload": { - "type": "object", - "required": ["status", "phase", "error"], - "properties": { - "status": {"const": "rejected"}, - "phase": {"enum": ["options", "prepare", "compile", "authorization", "strict"]}, - "error": {"$ref": "#/$defs/error"} - }, - "additionalProperties": true - } - } - } - } - ], - "$defs": { - "span": { - "oneOf": [ - {"type": "null"}, - { - "type": "object", - "required": ["start", "end"], - "properties": { - "start": {"type": "integer", "minimum": 0}, - "end": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - ] - }, - "error": { - "type": "object", - "required": ["code", "message"], - "properties": { - "code": {"type": "string", "minLength": 1}, - "message": {"type": "string"}, - "module_id": {"type": ["string", "null"]}, - "span": {"$ref": "#/$defs/span"} - }, - "additionalProperties": true - } - } -} diff --git a/spec/schemas/observation-event.schema.json b/spec/schemas/observation-event.schema.json new file mode 100644 index 0000000..11c0154 --- /dev/null +++ b/spec/schemas/observation-event.schema.json @@ -0,0 +1,855 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://marqdo.dev/schemas/observation-event.schema.json", + "title": "Marqdo Observation Event", + "description": "One event shared by live JSONL and JSON snapshots.", + "type": "object", + "required": [ + "schema", + "schema_version", + "run_id", + "seq", + "kind", + "payload" + ], + "properties": { + "schema": { + "const": "marqdo.observation" + }, + "schema_version": { + "const": 1 + }, + "run_id": { + "type": "string", + "minLength": 1 + }, + "seq": { + "type": "integer", + "minimum": 0 + }, + "kind": { + "enum": [ + "stream.opened", + "run.started", + "call.enter", + "observation.truncated", + "run.completed", + "run.failed", + "run.rejected", + "stdout.chunk", + "stderr.chunk", + "call.exit", + "return", + "branch.eval", + "loop.iteration", + "effect", + "control.break", + "control.continue", + "variable.assigned", + "parameter.observed" + ] + }, + "payload": { + "type": "object" + } + }, + "additionalProperties": false, + "allOf": [ + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "stream.opened" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "producer", + "observation", + "limits" + ], + "properties": { + "producer": { + "type": "object", + "required": [ + "name", + "version" + ], + "properties": { + "name": { + "const": "marqdo" + }, + "version": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": true + }, + "observation": { + "type": "object", + "required": [ + "level", + "values", + "selected_variables", + "selected_parameters", + "allow_text_values" + ], + "properties": { + "level": { + "enum": [ + "base", + "structural", + "values" + ] + }, + "values": { + "type": "boolean" + }, + "selected_variables": { + "type": "array", + "items": { + "type": "string" + } + }, + "selected_parameters": { + "type": "array", + "items": { + "type": "string" + } + }, + "allow_text_values": { + "type": "boolean" + } + }, + "additionalProperties": true + }, + "limits": { + "type": "object", + "required": [ + "max_observation_events", + "max_observation_bytes", + "max_value_bytes" + ], + "properties": { + "max_observation_events": { + "type": "integer", + "minimum": 0 + }, + "max_observation_bytes": { + "type": "integer", + "minimum": 0 + }, + "max_value_bytes": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": true + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "run.started" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "entry", + "mode", + "source" + ], + "properties": { + "entry": { + "type": "string", + "minLength": 1 + }, + "mode": { + "enum": [ + "pure", + "project", + "strict" + ] + }, + "source": { + "type": "object", + "required": [ + "root_id", + "analysis_digest" + ], + "properties": { + "root_id": { + "type": "string", + "pattern": "^(root:|sha256:[0-9a-f]{64}$)" + }, + "analysis_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } + }, + "additionalProperties": true + }, + "started_unix_ms": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "enum": [ + "stdout.chunk", + "stderr.chunk" + ] + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "encoding", + "data_base64", + "byte_count" + ], + "properties": { + "encoding": { + "const": "base64" + }, + "data_base64": { + "type": "string", + "contentEncoding": "base64" + }, + "byte_count": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "call.enter" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "frame_id", + "parent_frame_id", + "function_id", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "parent_frame_id": { + "oneOf": [ + { + "type": "null" + }, + { + "type": "string", + "pattern": "^f[0-9]+$" + } + ] + }, + "function_id": { + "type": "string", + "minLength": 1 + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "call.exit" + } + } + }, + "then": { + "properties": { + "payload": { + "required": [ + "frame_id", + "status", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "status": { + "type": "string", + "minLength": 1 + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": false + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "return" + } + } + }, + "then": { + "properties": { + "payload": { + "required": [ + "frame_id", + "value_type", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "value_type": { + "type": "string", + "minLength": 1 + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": false + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "branch.eval" + } + } + }, + "then": { + "properties": { + "payload": { + "required": [ + "frame_id", + "result", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "result": { + "type": "boolean" + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": false + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "loop.iteration" + } + } + }, + "then": { + "properties": { + "payload": { + "required": [ + "frame_id", + "decision", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "decision": { + "enum": [ + "continue", + "exit" + ] + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": false + } + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "effect" + } + } + }, + "then": { + "properties": { + "payload": { + "required": [ + "frame_id", + "operation", + "result_code", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": [ + "string", + "null" + ], + "pattern": "^f[0-9]+$" + }, + "operation": { + "type": "string", + "minLength": 1 + }, + "result_code": { + "type": "string", + "minLength": 1 + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": false + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "enum": [ + "control.break", + "control.continue" + ] + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "frame_id", + "module_id", + "span" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "type": "object", + "$ref": "#/$defs/span" + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "enum": [ + "variable.assigned", + "parameter.observed" + ] + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "frame_id", + "name", + "value_type", + "module_id", + "span", + "value_state" + ], + "properties": { + "frame_id": { + "type": "string", + "pattern": "^f[0-9]+$" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "source": { + "enum": [ + "provided", + "default" + ] + }, + "value_type": { + "type": "string", + "minLength": 1 + }, + "module_id": { + "type": "string", + "minLength": 1 + }, + "span": { + "$ref": "#/$defs/span" + }, + "value_state": { + "enum": [ + "not_requested", + "redacted", + "truncated", + "unsupported", + "observed" + ] + }, + "value": { + "type": [ + "object", + "null" + ] + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "observation.truncated" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "reason", + "limit", + "written", + "dropped" + ], + "properties": { + "reason": { + "enum": [ + "event_budget", + "byte_budget" + ] + }, + "limit": { + "type": "integer", + "minimum": 0 + }, + "written": { + "type": "integer", + "minimum": 0 + }, + "dropped": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "run.completed" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "status", + "value", + "value_type" + ], + "properties": { + "status": { + "const": "ok" + }, + "value": { + "type": [ + "object", + "null" + ] + }, + "value_type": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "run.failed" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "status", + "error" + ], + "properties": { + "status": { + "const": "error" + }, + "error": { + "$ref": "#/$defs/error" + } + }, + "additionalProperties": true + } + } + } + }, + { + "if": { + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "run.rejected" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "required": [ + "status", + "phase", + "error" + ], + "properties": { + "status": { + "const": "rejected" + }, + "phase": { + "enum": [ + "options", + "prepare", + "compile", + "authorization", + "strict" + ] + }, + "error": { + "$ref": "#/$defs/error" + } + }, + "additionalProperties": true + } + } + } + } + ], + "$defs": { + "span": { + "oneOf": [ + { + "type": "null" + }, + { + "type": "object", + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "integer", + "minimum": 0 + }, + "end": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": true + } + ] + }, + "error": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string" + }, + "module_id": { + "type": [ + "string", + "null" + ] + }, + "span": { + "$ref": "#/$defs/span" + } + }, + "additionalProperties": true + } + } +} diff --git a/spec/schemas/observation-file.schema.json b/spec/schemas/observation-file.schema.json new file mode 100644 index 0000000..4324a9f --- /dev/null +++ b/spec/schemas/observation-file.schema.json @@ -0,0 +1,122 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://marqdo.dev/schemas/observation-file.schema.json", + "title": "Marqdo Observation Snapshot", + "type": "object", + "required": [ + "schema", + "schema_version", + "run", + "capture", + "events" + ], + "additionalProperties": false, + "properties": { + "schema": { + "const": "marqdo.observation" + }, + "schema_version": { + "const": 1 + }, + "run": { + "type": "object", + "required": [ + "id", + "status", + "source" + ], + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "status": { + "enum": [ + "ok", + "error", + "rejected", + "incomplete" + ] + }, + "source": { + "type": [ + "object", + "null" + ], + "if": { + "type": "object" + }, + "then": { + "required": [ + "root_id", + "analysis_digest" + ], + "additionalProperties": false, + "properties": { + "root_id": { + "type": "string", + "minLength": 1 + }, + "analysis_digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } + } + } + } + } + }, + "capture": { + "type": "object", + "required": [ + "level", + "values", + "selected_variables", + "selected_parameters", + "allow_text_values", + "truncated" + ], + "additionalProperties": false, + "properties": { + "level": { + "enum": [ + "structural", + "values" + ] + }, + "values": { + "type": "boolean" + }, + "selected_variables": { + "type": "array", + "items": { + "type": "string" + } + }, + "selected_parameters": { + "type": "array", + "items": { + "type": "string" + } + }, + "allow_text_values": { + "type": "boolean" + }, + "truncated": { + "type": [ + "object", + "null" + ] + } + } + }, + "events": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "observation-event.schema.json" + } + } + } +} diff --git a/spec/schemas/trace-v1.schema.json b/spec/schemas/trace-v1.schema.json deleted file mode 100644 index 63da3a5..0000000 --- a/spec/schemas/trace-v1.schema.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/trace-v1.schema.json", - "title": "Marqdo Trace v1", - "type": "object", - "required": ["schema", "schema_version", "run", "source", "events"], - "properties": { - "schema": {"const": "marqdo.trace"}, - "schema_version": {"const": 1}, - "run": { - "type": "object", - "required": ["id", "entry", "status"], - "properties": { - "id": {"type": "string"}, - "entry": {"type": "string"}, - "status": {"type": "string"} - }, - "additionalProperties": true - }, - "source": { - "type": "object", - "required": ["root_id", "analysis_digest"], - "properties": { - "root_id": {"type": "string"}, - "analysis_digest": {"type": "string"} - }, - "additionalProperties": true - }, - "events": { - "type": "array", - "items": { - "type": "object", - "required": ["seq", "kind"], - "properties": { - "seq": {"type": "integer", "minimum": 0}, - "kind": {"type": "string"}, - "function_id": {"type": ["string", "null"]}, - "module": {"type": ["string", "null"]}, - "span": { - "type": ["object", "null"], - "properties": { - "start": {"type": "integer", "minimum": 0}, - "end": {"type": "integer", "minimum": 0} - } - }, - "detail": {"type": ["string", "null"]}, - "operation": {"type": "string"}, - "duration_micros": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - } - }, - "additionalProperties": true -} diff --git a/spec/schemas/trace-v2.schema.json b/spec/schemas/trace-v2.schema.json deleted file mode 100644 index 0d0697c..0000000 --- a/spec/schemas/trace-v2.schema.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://marqdo.dev/schemas/trace-v2.schema.json", - "title": "Marqdo Trace v2", - "type": "object", - "required": ["schema", "schema_version", "run", "source", "limits", "truncated", "events"], - "properties": { - "schema": {"const": "marqdo.trace"}, - "schema_version": {"const": 2}, - "run": { - "type": "object", - "required": ["id", "entry", "status"], - "properties": { - "id": {"type": "string", "minLength": 1}, - "entry": {"type": "string", "minLength": 1}, - "status": {"type": "string", "minLength": 1} - }, - "additionalProperties": true - }, - "source": { - "type": "object", - "required": ["root_id", "analysis_digest"], - "properties": { - "root_id": {"type": "string", "pattern": "^(root:|sha256:[0-9a-f]{64}$)"}, - "analysis_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"} - }, - "additionalProperties": true - }, - "limits": { - "type": "object", - "required": ["max_events", "max_bytes"], - "properties": { - "max_events": {"type": "integer", "minimum": 0}, - "max_bytes": {"type": "integer", "minimum": 0} - }, - "additionalProperties": false - }, - "truncated": { - "oneOf": [ - {"type": "null"}, - { - "type": "object", - "required": ["reason", "limit", "written"], - "properties": { - "reason": {"enum": ["event_budget", "byte_budget"]}, - "limit": {"type": "integer", "minimum": 0}, - "written": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - ] - }, - "events": { - "type": "array", - "items": { - "type": "object", - "required": ["seq", "kind", "module_id", "span", "detail"], - "properties": { - "seq": {"type": "integer", "minimum": 0}, - "kind": {"type": "string", "minLength": 1}, - "function_id": {"type": ["string", "null"]}, - "module_id": {"type": ["string", "null"]}, - "span": { - "oneOf": [ - {"type": "null"}, - { - "type": "object", - "required": ["start", "end"], - "properties": { - "start": {"type": "integer", "minimum": 0}, - "end": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - ] - }, - "detail": {"type": ["string", "null"]}, - "operation": {"type": "string"}, - "duration_micros": {"type": "integer", "minimum": 0} - }, - "additionalProperties": true - } - } - }, - "additionalProperties": true -} diff --git a/spec/trace-v1.md b/spec/trace-v1.md deleted file mode 100644 index a84c1df..0000000 --- a/spec/trace-v1.md +++ /dev/null @@ -1,74 +0,0 @@ -# Marqdo Trace v1 - -Status: **superseded by [Trace v2](trace-v2.md); never released, do not write -v1.** Kept as history. - -## 1. Invariants - -* Tracing is observation, not execution. Only `run`/`call` can produce a trace; - `check`, `inspect` and `tool list` never execute a document. -* Events come from the interpreter (`call.*`, `branch.eval`, - `loop.iteration`, `return`) and the host (`effect`). -* The writer is atomic: a failed run does not leave a partially written JSON - file; an error run still records the terminal status if execution started. -* No argument values, secrets, plugin handles or file contents are recorded. - Effect detail is a result summary (`ok` or a stable error code). -* `--trace` keeps its existing human/JSON effect output; `--trace-file` is the - versioned artifact and does not redefine `--trace`. - -## 2. Shape - -```json -{ - "schema": "marqdo.trace", - "schema_version": 1, - "run": {"id": "pid-nanos", "entry": "root:default::index.mq.md::main", "status": "ok"}, - "source": {"root_id": "sha256:...", "analysis_digest": "sha256:..."}, - "events": [ - {"seq": 0, "kind": "call.enter", "function_id": "root:default::index.mq.md::main", "span": null, "detail": null}, - {"seq": 1, "kind": "effect", "module": "root:default::index.mq.md", "span": {"start": 40, "end": 52}, "detail": "ok", "operation": "print", "duration_micros": 3}, - {"seq": 2, "kind": "call.exit", "function_id": "root:default::index.mq.md::main", "span": null, "detail": "ok"} - ] -} -``` - -`seq` is globally increasing within one run (semantic and effect events share -the counter). `run.status` is `ok` or a stable runtime error code. Span fields -use UTF-8 byte offsets into the source identified by `source.root_id` and -`source.analysis_digest`. - -## 3. Event kinds - -| kind | detail | Meaning | -|---|---|---| -| `call.enter` | null | function entry; `function_id` is canonical | -| `call.exit` | `ok` / `return` / error code | function exit | -| `return` | value type name | explicit `return` statement; no value content | -| `branch.eval` | `true` / `false` | `if` condition for an `if/else/end` group | -| `loop.iteration` | `continue` / `exit` | `while` condition for a `while/end` group | -| `effect` | result summary | a `HostOp` effect; `operation` names it | - -Future event kinds are additive. Consumers must ignore unknown kinds rather -than guessing their semantics. - -## 4. Staleness - -`source.analysis_digest` is the digest of the Analysis v1 projection built -from the same loaded project. If a consumer compares it with a newer analysis -and the digest differs, the trace is `stale` and must not be presented as the -current document's execution. - -## 5. Privacy and limits - -* Values and secrets are never serialized into a trace. -* Foreign/plugin effects record only the operation and success/error summary. -* A trace file can be large for long loops; the current implementation has no - event-count cap, but consumers must stream/limit. A future version may add a - bounded mode. -* A failed/aborted run records the status it reached; it is never marked - successful. - -## 6. Not included - -Interactive breakpoints, a debug server, time travel, notebook sessions, -WebSocket streaming and full argument-value capture are out of scope for v1. diff --git a/spec/trace-v2.md b/spec/trace-v2.md deleted file mode 100644 index ca983b8..0000000 --- a/spec/trace-v2.md +++ /dev/null @@ -1,119 +0,0 @@ -# Marqdo Trace v2 - -Status: **implemented by `marqdo run/call --trace-file ` (S2).** -Supersedes Trace v1; v1 was never released and is kept as history. - -## 1. Invariants - -* Tracing is observation, not execution. Only `run`/`call` produce a trace; - `check`, `inspect` and `tool list` never execute a document. -* Events come from the interpreter (`call.*`, `branch.eval`, - `loop.iteration`, `control.break`, `control.continue`, `return`) and the host (`effect`). Both share one sequence. -* The writer is atomic; an error run still records its terminal status. -* No argument values, secrets, handles or file contents are recorded. -* Trace capacity is a bounded observation budget. Reaching it truncates the - trace; it never changes `run.status` or the program’s execution result. - Execution budgets (`--fuel`, `--timeout`, ...) remain separate and still - produce `resource.exhausted`. - -## 2. Shape - -```json -{ - "schema": "marqdo.trace", - "schema_version": 2, - "run": {"id": "pid-nanos", "entry": "root:q@0.1.0::index.mq.md::main", "status": "ok"}, - "source": {"root_id": "root:q@0.1.0", "analysis_digest": "sha256:<64 hex>"}, - "limits": {"max_events": 100000, "max_bytes": 33554432}, - "truncated": null, - "events": [ - {"seq": 0, "kind": "call.enter", "function_id": "root:q@0.1.0::index.mq.md::main", - "module_id": "root:q@0.1.0::index.mq.md", "span": null, "detail": null}, - {"seq": 1, "kind": "effect", "module_id": "dep:p@0.1.0#::index.mq.md", - "span": {"start": 40, "end": 52}, "detail": "ok", "operation": "print", - "duration_micros": 3} - ] -} -``` - -`seq` is globally increasing. `run.status` is `ok` or a stable runtime error -code. Every span-bearing event has a `module_id`; the span is a UTF-8 byte -offset range in that module. `source` only carries project identity and the -Analysis digest; it does not identify the span owner. - -`source.root_id` is the emitted Analysis `project.root_id` -(`root:@` or `sha256:`). -`source.analysis_digest` is `sha256:` plus the SHA-256 of the exact Analysis -bytes produced for the same project with the same projection configuration. -The [Analysis writer](analysis-v3.md) selects v2 or v3 from the project. -A consumer verifies it by hashing the Analysis file. - -`truncated` is `null` or: - -```json -{"reason": "event_budget", "limit": 20, "written": 20} -``` - -`reason` is `event_budget` or `byte_budget`. When truncation occurs, the final -event is `{"kind":"trace.truncated","detail":,"module_id":null, -"span":null,"seq":}`. - -## 3. Event kinds and span owners - -| kind | detail | `module_id` owner | -|---|---|---| -| `call.enter` | null | caller module (entry call: callee) | -| `call.exit` | `ok` / `return` / error code | caller module (entry call: callee) | -| `return` | value type name | current function’s module | -| `branch.eval` | `true` / `false` | current function’s module | -| `loop.iteration` | `continue` / `exit` | current function’s module | -| `control.break` | null | current function’s module | -| `control.continue` | null | current function’s module | -| `effect` | result summary | module from `ExecutionContext` | -| `trace.truncated` | `event_budget` / `byte_budget` | null | - -The explicit transfer events carry the keyword carrier span. `control.continue` -precedes the next evaluation of the enclosing loop condition. `control.break` -leaves that loop without a further condition evaluation. - -`function_id` is always the canonical callee function id. Future kinds are -additive; consumers must ignore unknown kinds. `effect.operation` names the -`HostOp` (`print`, `fs.read`, ...). - -## 4. Capacity - -Defaults: 100 000 events and 32 MiB approximate serialized size. `0` means -unlimited for either limit. `run`/`call` expose `--trace-max-events` and -`--trace-max-bytes`; these are options on existing commands, not new commands. -The host stops accepting events once a limit is reached; the writer also -enforces the byte limit on the final serialized document, dropping trailing -events and recording `byte_budget`. Semantic recording is disabled entirely -when no trace was requested. - -The `trace` array in `run --json` uses the same budget. - -## 5. Staleness - -A trace is stale when its `source.analysis_digest` differs from the digest of -the Analysis emitted for the current document. Consumers must not present a -stale trace as current. Moving a project does not change the manifest identity -or digest; changing executable source does. - -## 6. Worker transport limits - -Plugin worker frames are a 4-byte big-endian length plus JSON, capped at -8 MiB (`8 * 1024 * 1024`). The wire request/result/capability caps are aligned -to `8 MiB - 4096`; error frames remain 1 MiB. A partial header, zero/oversized -length, truncated payload or invalid JSON is a protocol error. A clean EOF is -distinct from a protocol failure. The host marks a worker dead after a transport -failure and never reuses its stdin. - -## 7. Compatibility and tests - -* Consumers must reject unknown `schema_version` and validate `module_id` - against Analysis modules. -* JSON Schema: `spec/schemas/trace-v2.schema.json`. -* `tests/consumers/trace_consumer.py` verifies identity, digest and event - module references. -* CLI tests cover call/effect events, no-secret redaction, error terminal - status, and event-budget truncation without changing the run status. diff --git a/tests/consumers/execution_events_consumer.py b/tests/consumers/execution_events_consumer.py deleted file mode 100644 index f7487cd..0000000 --- a/tests/consumers/execution_events_consumer.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python3 -"""Black-box consumer for Marqdo Execution Events v1 (RFC-OBS-0001). - -This is an independent consumer: it imports only the Python standard library -and the `jsonschema` package, never the Rust workspace, and it consumes the -output of a released `marqdo` binary (or a checked-in fixture). - -Usage: - execution_events_consumer.py EVENTS.jsonl - execution_events_consumer.py - # read stdin - execution_events_consumer.py --schema-check FILE.jsonl - -Checks: - * every line is one JSON object validated against - `spec/schemas/execution-events-v1.schema.json`; - * `stream.opened` is first (seq 0), `run.started` occurs at most once, - exactly one terminal event on a complete stream, nothing follows it; - * `seq` is contiguous and strictly increasing; - * `run_id` and protocol/schema are consistent across lines; - * `stdout.chunk`/`stderr.chunk` base64 decodes and `byte_count` matches; - * an unknown schema major is rejected, never treated as v1. - -Exit status 0 means the stream validated. 2 means invalid input, 3 means an -incomplete stream (no terminal event; a legal boundary after SIGKILL/EOF). -""" -import base64 -import binascii -import json -import pathlib -import sys - -from jsonschema import Draft202012Validator - -ROOT = pathlib.Path(__file__).resolve().parents[2] -SCHEMA_PATH = ROOT / "spec" / "schemas" / "execution-events-v1.schema.json" -SCHEMA = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) -Draft202012Validator.check_schema(SCHEMA) -VALIDATOR = Draft202012Validator(SCHEMA) - -SCHEMA_NAME = "marqdo.execution-events" -SCHEMA_VERSION = 1 -TERMINALS = {"run.completed", "run.failed", "run.rejected"} - - -class Invalid(Exception): - pass - - -def parse_line(number, raw): - try: - event = json.loads(raw) - except json.JSONDecodeError as error: - raise Invalid(f"line {number}: not JSON: {error}") from error - if not isinstance(event, dict): - raise Invalid(f"line {number}: event is not a JSON object") - errors = sorted(VALIDATOR.iter_errors(event), key=str) - if errors: - raise Invalid(f"line {number}: schema: {errors[0].message}") - return event - - -def check_chunk(event): - payload = event["payload"] - if payload.get("encoding") != "base64": - raise Invalid(f"seq {event['seq']}: unsupported chunk encoding") - try: - data = base64.b64decode(payload["data_base64"], validate=True) - except (binascii.Error, ValueError) as error: - raise Invalid(f"seq {event['seq']}: data_base64 is not valid base64: {error}") from error - if len(data) != payload["byte_count"]: - raise Invalid( - f"seq {event['seq']}: byte_count={payload['byte_count']} but decoded {len(data)} bytes" - ) - return data - - -def consume(lines, require_terminal=True): - events = [parse_line(number, raw) for number, raw in enumerate(lines, start=1)] - if not events: - raise Invalid("empty stream") - - first = events[0] - if first["kind"] != "stream.opened": - raise Invalid("first event must be stream.opened") - if first["seq"] != 0: - raise Invalid("stream.opened must have seq 0") - if first["schema"] != SCHEMA_NAME or first["schema_version"] != SCHEMA_VERSION: - raise Invalid("stream.opened does not negotiate marqdo.execution-events v1") - - run_id = first["run_id"] - chunks = bytearray() - terminal = None - started = 0 - for index, event in enumerate(events): - seq = event["seq"] - if seq != index: - raise Invalid(f"seq {seq} at line {index + 1}; expected {index}") - if event["schema"] != SCHEMA_NAME or event["schema_version"] != SCHEMA_VERSION: - raise Invalid(f"seq {seq}: inconsistent schema negotiation") - if event["run_id"] != run_id: - raise Invalid(f"seq {seq}: run_id changed within one stream") - if terminal is not None: - raise Invalid(f"seq {seq}: event follows terminal {terminal}") - if event["kind"] == "run.started": - started += 1 - if started > 1: - raise Invalid("more than one run.started") - if event["kind"] in TERMINALS: - terminal = event["kind"] - if event["kind"] in ("stdout.chunk", "stderr.chunk"): - chunks.extend(check_chunk(event)) - - if require_terminal and terminal is None: - return 3, f"incomplete stream: {len(events)} events, no terminal event" - if terminal == "run.completed" and started != 1: - raise Invalid("run.completed requires exactly one preceding run.started") - if terminal == "run.failed" and started != 1: - raise Invalid("run.failed requires exactly one preceding run.started") - if terminal == "run.rejected" and started != 0: - raise Invalid("run.rejected must not be preceded by run.started") - return 0, ( - f"ok: {len(events)} events, terminal={terminal}, " - f"stdout+stderr bytes={len(chunks)}" - ) - - -def main(argv): - if len(argv) != 2: - raise SystemExit(__doc__) - target = argv[1] - if target == "-": - lines = [line for line in sys.stdin.read().splitlines() if line.strip()] - else: - text = pathlib.Path(target).read_text(encoding="utf-8") - lines = [line for line in text.splitlines() if line.strip()] - try: - status, message = consume(lines) - except Invalid as error: - raise SystemExit(f"execution events consumer: INVALID: {error}") - print(f"execution events consumer: {message}") - raise SystemExit(status) - - -if __name__ == "__main__": - main(sys.argv) diff --git a/tests/consumers/fixtures/execution-events/invalid/bad-chunk.json b/tests/consumers/fixtures/execution-events/invalid/bad-chunk.json deleted file mode 100644 index 2851bba..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/bad-chunk.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","byte_count":13}} diff --git a/tests/consumers/fixtures/execution-events/invalid/bad-span.json b/tests/consumers/fixtures/execution-events/invalid/bad-span.json deleted file mode 100644 index 31c0e72..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/bad-span.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"m","span":{"start":1}}} diff --git a/tests/consumers/fixtures/execution-events/invalid/bad-terminal.json b/tests/consumers/fixtures/execution-events/invalid/bad-terminal.json deleted file mode 100644 index 17a5f6e..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/bad-terminal.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok"}} diff --git a/tests/consumers/fixtures/execution-events/invalid/empty-run-id.json b/tests/consumers/fixtures/execution-events/invalid/empty-run-id.json deleted file mode 100644 index b32daa8..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/empty-run-id.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/execution-events/invalid/missing-payload.json b/tests/consumers/fixtures/execution-events/invalid/missing-payload.json deleted file mode 100644 index df74bf3..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/missing-payload.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened"} diff --git a/tests/consumers/fixtures/execution-events/invalid/missing-seq.json b/tests/consumers/fixtures/execution-events/invalid/missing-seq.json deleted file mode 100644 index 1985012..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/missing-seq.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/execution-events/invalid/negative-seq.json b/tests/consumers/fixtures/execution-events/invalid/negative-seq.json deleted file mode 100644 index e8a41ea..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/negative-seq.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":-1,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/execution-events/invalid/unknown-major.json b/tests/consumers/fixtures/execution-events/invalid/unknown-major.json deleted file mode 100644 index 34045ec..0000000 --- a/tests/consumers/fixtures/execution-events/invalid/unknown-major.json +++ /dev/null @@ -1 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":2,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/execution-events/valid/full.jsonl b/tests/consumers/fixtures/execution-events/valid/full.jsonl deleted file mode 100644 index 006fd80..0000000 --- a/tests/consumers/fixtures/execution-events/valid/full.jsonl +++ /dev/null @@ -1,14 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"values","values":true,"selected_variables":["visible_count"],"selected_parameters":["n"],"allow_text_values":false},"limits":{"max_observation_events":100,"max_observation_bytes":1048576,"max_value_bytes":256}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"parameter.observed","payload":{"frame_id":"f1","name":"n","source":"provided","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":null,"value_state":"observed","value":{"type":"int","decimal":"5"}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"visible_count","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":80,"end":100},"value_state":"observed","value":{"type":"int","decimal":"42"}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"secret_token","value_type":"Text","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":110,"end":150},"value_state":"redacted"}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":6,"kind":"branch.eval","payload":{"frame_id":"f1","result":true,"module_id":"root:demo@0.1.0::index.mq.md","span":{"start":160,"end":170}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":7,"kind":"loop.iteration","payload":{"frame_id":"f1","decision":"continue","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":180,"end":190}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":8,"kind":"effect","payload":{"operation":"print","result_code":"ok","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":200,"end":210}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":9,"kind":"stderr.chunk","payload":{"encoding":"base64","data_base64":"AA==","byte_count":1}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":10,"kind":"return","payload":{"frame_id":"f1","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":220,"end":230}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":11,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":null}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":12,"kind":"observation.truncated","payload":{"reason":"event_budget","limit":100,"written":100,"dropped":null}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":13,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"42"}}} diff --git a/tests/consumers/fixtures/execution-events/valid/minimal.jsonl b/tests/consumers/fixtures/execution-events/valid/minimal.jsonl deleted file mode 100644 index 985e8a1..0000000 --- a/tests/consumers/fixtures/execution-events/valid/minimal.jsonl +++ /dev/null @@ -1,6 +0,0 @@ -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.execution-events","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","data_base64":"5byA5aeL5paH5pysCg==","byte_count":13}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":10,"end":20}}} -{"schema":"marqdo.execution-events","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"10"}}} diff --git a/tests/consumers/fixtures/execution-events/README.md b/tests/consumers/fixtures/observation/README.md similarity index 73% rename from tests/consumers/fixtures/execution-events/README.md rename to tests/consumers/fixtures/observation/README.md index e432fb8..2db9210 100644 --- a/tests/consumers/fixtures/execution-events/README.md +++ b/tests/consumers/fixtures/observation/README.md @@ -1,8 +1,8 @@ -# Execution Events v1 fixtures +# Observation fixtures These are the minimal executable fixtures from RFC-OBS-0001 §13 plus the schema-validation fixtures used by -[`execution_events_consumer.py`](../../execution_events_consumer.py). +[`observation_consumer.py`](../../observation_consumer.py). | File | Purpose | |---|---| @@ -16,6 +16,6 @@ schema-validation fixtures used by The `.mq.md` files are inputs to the released CLI: ```bash -marqdo run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl -python3 tests/consumers/execution_events_consumer.py /tmp/events.jsonl +marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl +python3 tests/consumers/observation_consumer.py /tmp/events.jsonl ``` diff --git a/tests/consumers/fixtures/execution-events/basic.mq.md b/tests/consumers/fixtures/observation/basic.mq.md similarity index 100% rename from tests/consumers/fixtures/execution-events/basic.mq.md rename to tests/consumers/fixtures/observation/basic.mq.md diff --git a/tests/consumers/fixtures/observation/invalid/bad-chunk.json b/tests/consumers/fixtures/observation/invalid/bad-chunk.json new file mode 100644 index 0000000..62bcd18 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/bad-chunk.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","byte_count":13}} diff --git a/tests/consumers/fixtures/observation/invalid/bad-span.json b/tests/consumers/fixtures/observation/invalid/bad-span.json new file mode 100644 index 0000000..1e66384 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/bad-span.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"m","span":{"start":1}}} diff --git a/tests/consumers/fixtures/observation/invalid/bad-terminal.json b/tests/consumers/fixtures/observation/invalid/bad-terminal.json new file mode 100644 index 0000000..00de3af --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/bad-terminal.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok"}} diff --git a/tests/consumers/fixtures/observation/invalid/empty-run-id.json b/tests/consumers/fixtures/observation/invalid/empty-run-id.json new file mode 100644 index 0000000..683bd34 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/empty-run-id.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/observation/invalid/missing-payload.json b/tests/consumers/fixtures/observation/invalid/missing-payload.json new file mode 100644 index 0000000..8cc4538 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/missing-payload.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened"} diff --git a/tests/consumers/fixtures/observation/invalid/missing-seq.json b/tests/consumers/fixtures/observation/invalid/missing-seq.json new file mode 100644 index 0000000..40c2c79 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/missing-seq.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/observation/invalid/negative-seq.json b/tests/consumers/fixtures/observation/invalid/negative-seq.json new file mode 100644 index 0000000..63a8f16 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/negative-seq.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":-1,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/observation/invalid/unknown-major.json b/tests/consumers/fixtures/observation/invalid/unknown-major.json new file mode 100644 index 0000000..a2cd8e3 --- /dev/null +++ b/tests/consumers/fixtures/observation/invalid/unknown-major.json @@ -0,0 +1 @@ +{"schema":"marqdo.observation","schema_version":2,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"protocol":{"name":"marqdo.observation","schema_version":1},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} diff --git a/tests/consumers/fixtures/execution-events/realtime.mq.md b/tests/consumers/fixtures/observation/realtime.mq.md similarity index 100% rename from tests/consumers/fixtures/execution-events/realtime.mq.md rename to tests/consumers/fixtures/observation/realtime.mq.md diff --git a/tests/consumers/fixtures/execution-events/structure.mq.md b/tests/consumers/fixtures/observation/structure.mq.md similarity index 100% rename from tests/consumers/fixtures/execution-events/structure.mq.md rename to tests/consumers/fixtures/observation/structure.mq.md diff --git a/tests/consumers/fixtures/observation/valid/full.jsonl b/tests/consumers/fixtures/observation/valid/full.jsonl new file mode 100644 index 0000000..4724931 --- /dev/null +++ b/tests/consumers/fixtures/observation/valid/full.jsonl @@ -0,0 +1,14 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"observation":{"level":"values","values":true,"selected_variables":["visible_count"],"selected_parameters":["n"],"allow_text_values":false},"limits":{"max_observation_events":100,"max_observation_bytes":1048576,"max_value_bytes":256}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"parameter.observed","payload":{"frame_id":"f1","name":"n","source":"provided","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":null,"value_state":"observed","value":{"type":"int","decimal":"5"}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"visible_count","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":80,"end":100},"value_state":"observed","value":{"type":"int","decimal":"42"}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"variable.assigned","payload":{"frame_id":"f1","name":"secret_token","value_type":"Text","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":110,"end":150},"value_state":"redacted"}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":6,"kind":"branch.eval","payload":{"frame_id":"f1","result":true,"module_id":"root:demo@0.1.0::index.mq.md","span":{"start":160,"end":170}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":7,"kind":"loop.iteration","payload":{"frame_id":"f1","decision":"continue","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":180,"end":190}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":8,"kind":"effect","payload":{"operation":"print","result_code":"ok","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":200,"end":210},"frame_id":"f1"}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":9,"kind":"stderr.chunk","payload":{"encoding":"base64","data_base64":"AA==","byte_count":1}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":10,"kind":"return","payload":{"frame_id":"f1","value_type":"Int","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":220,"end":230}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":11,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":null}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":12,"kind":"observation.truncated","payload":{"reason":"event_budget","limit":100,"written":100,"dropped":null}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":13,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"42"},"value_type":"Int"}} diff --git a/tests/consumers/fixtures/observation/valid/minimal.jsonl b/tests/consumers/fixtures/observation/valid/minimal.jsonl new file mode 100644 index 0000000..8702e42 --- /dev/null +++ b/tests/consumers/fixtures/observation/valid/minimal.jsonl @@ -0,0 +1,6 @@ +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":0,"kind":"stream.opened","payload":{"producer":{"name":"marqdo","version":"3.0.0-beta.1"},"observation":{"level":"structural","values":false,"selected_variables":[],"selected_parameters":[],"allow_text_values":false},"limits":{"max_observation_events":100000,"max_observation_bytes":16777216,"max_value_bytes":256}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":1,"kind":"run.started","payload":{"entry":"root:demo@0.1.0::index.mq.md::main","mode":"project","source":{"root_id":"root:demo@0.1.0","analysis_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"started_unix_ms":1763800000000}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":2,"kind":"call.enter","payload":{"frame_id":"f1","parent_frame_id":null,"function_id":"root:demo@0.1.0::index.mq.md::main","module_id":"root:demo@0.1.0::index.mq.md","span":null}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":3,"kind":"stdout.chunk","payload":{"encoding":"base64","data_base64":"5byA5aeL5paH5pysCg==","byte_count":13}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":4,"kind":"call.exit","payload":{"frame_id":"f1","status":"return","module_id":"root:demo@0.1.0::index.mq.md","span":{"start":10,"end":20}}} +{"schema":"marqdo.observation","schema_version":1,"run_id":"run-fixture-1","seq":5,"kind":"run.completed","payload":{"status":"ok","value":{"type":"int","decimal":"10"},"value_type":"Int"}} diff --git a/tests/consumers/fixtures/execution-events/values.mq.md b/tests/consumers/fixtures/observation/values.mq.md similarity index 100% rename from tests/consumers/fixtures/execution-events/values.mq.md rename to tests/consumers/fixtures/observation/values.mq.md diff --git a/tests/consumers/observation_consumer.py b/tests/consumers/observation_consumer.py new file mode 100644 index 0000000..0d119a6 --- /dev/null +++ b/tests/consumers/observation_consumer.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Consume real Marqdo observation output using public contracts only.""" +import argparse +import base64 +import binascii +import hashlib +import json +import pathlib +import sys + +SCHEMAS = pathlib.Path(__file__).resolve().parents[2] / "spec" / "schemas" +EVENT_SCHEMA = json.loads((SCHEMAS / "observation-event.schema.json").read_text()) +SCHEMA = "marqdo.observation" +KINDS = set(EVENT_SCHEMA["properties"]["kind"]["enum"]) +TERMINALS = {"run.completed": "ok", "run.failed": "error", "run.rejected": "rejected"} + + +class Invalid(Exception): + pass + + +def current_document(value): + return ( + isinstance(value, dict) + and value.get("schema") == SCHEMA + and type(value.get("schema_version")) is int + and value["schema_version"] == 1 + ) + + +def check_source(source, events, analysis_path, source_root): + raw = analysis_path.read_bytes() + report = json.loads(raw) + if report.get("schema") != "marqdo.analysis" or report.get("schema_version") != 3: + raise Invalid("unsupported Analysis format") + expected = "sha256:" + hashlib.sha256(raw).hexdigest() + if source is None or source["analysis_digest"] != expected: + raise Invalid("Analysis digest mismatch") + if source["root_id"] != report["project"]["root_id"]: + raise Invalid("Analysis project identity mismatch") + + modules = {module["id"]: module for module in report["modules"]} + checked_sources = {} + for event in events: + payload = event["payload"] + functions = [payload["function_id"]] if "function_id" in payload else [] + for function in functions: + if function.rsplit("::", 1)[0] not in modules: + raise Invalid("unknown function module") + if "module_id" not in payload: + continue + module_id = payload["module_id"] + if module_id not in modules: + raise Invalid("unknown event module") + span = payload.get("span") + if span is not None and not 0 <= span["start"] <= span["end"]: + raise Invalid("invalid event span") + if source_root is None or not module_id.startswith("root:"): + continue + if module_id not in checked_sources: + module = modules[module_id] + path = (source_root / module["relative_path"]).resolve() + if not path.is_relative_to(source_root): + raise Invalid("root source path escaped its checkout") + data = path.read_bytes() + if hashlib.sha256(data).hexdigest() != module["source_digest"]: + raise Invalid(f"source digest mismatch for {module['relative_path']}") + checked_sources[module_id] = data + if span is not None: + data = checked_sources[module_id] + if span["end"] > len(data): + raise Invalid("event span exceeds source length") + try: + data[span["start"]:span["end"]].decode("utf-8") + except UnicodeDecodeError as error: + raise Invalid("event span splits UTF-8") from error + + +def check_chunk(payload): + if payload["encoding"] != "base64": + raise Invalid("unsupported chunk encoding") + try: + raw = base64.b64decode(payload["data_base64"], validate=True) + except (binascii.Error, ValueError) as error: + raise Invalid("invalid base64 chunk") from error + if len(raw) != payload["byte_count"]: + raise Invalid("chunk byte count mismatch") + return len(raw) + + +def consume(events, snapshot=None, analysis=None, source_root=None): + if not isinstance(events, list) or not events: + raise Invalid("expected an opening event") + first = events[0] + if not current_document(first) or first.get("kind") != "stream.opened": + raise Invalid("expected current Observation opening event") + run_id = first.get("run_id") + if not isinstance(run_id, str) or not run_id: + raise Invalid("invalid run identity") + source = None + terminal = None + truncation = None + chunks = 0 + stack = [] + seen = set() + for seq, event in enumerate(events): + if ( + not current_document(event) + or event.get("run_id") != run_id + or type(event.get("seq")) is not int + or event["seq"] != seq + or event.get("kind") not in KINDS + or not isinstance(event.get("payload"), dict) + ): + raise Invalid(f"invalid event envelope at sequence {seq}") + kind = event["kind"] + payload = event["payload"] + if terminal is not None: + raise Invalid("event after terminal") + if seq == 0: + continue + if kind == "run.started" and seq == 1: + source = payload["source"] + if not isinstance(source, dict): + raise Invalid("missing source binding") + continue + if kind == "run.rejected" and seq == 1: + terminal = TERMINALS[kind] + elif source is None or kind in ("run.started", "stream.opened", "run.rejected"): + raise Invalid("invalid run lifecycle") + elif kind in TERMINALS: + terminal = TERMINALS[kind] + elif kind in ("stdout.chunk", "stderr.chunk"): + chunks += check_chunk(payload) + elif kind == "observation.truncated": + if truncation is not None: + raise Invalid("duplicate truncation marker") + truncation = payload + elif truncation is not None: + raise Invalid("structural event after truncation") + elif kind == "call.enter": + frame = payload["frame_id"] + if frame in seen or payload["parent_frame_id"] != (stack[-1] if stack else None): + raise Invalid("invalid call frame parent or reused frame identity") + seen.add(frame) + stack.append(frame) + elif kind == "call.exit": + if not stack or payload["frame_id"] != stack.pop(): + raise Invalid("mismatched call exit") + elif payload.get("frame_id") is not None and ( + not stack or payload["frame_id"] != stack[-1] + ): + raise Invalid("observation outside its owning frame") + if terminal is not None and payload["status"] != terminal: + raise Invalid("terminal status mismatch") + + if terminal is not None and truncation is None and stack: + raise Invalid("unclosed frame") + if snapshot is not None: + run = snapshot["run"] + capture = snapshot["capture"] + if ( + run["id"] != run_id + or run["source"] != source + or run["status"] != (terminal or "incomplete") + or capture["truncated"] != truncation + or {key: value for key, value in capture.items() if key != "truncated"} + != first["payload"]["observation"] + ): + raise Invalid("snapshot metadata disagrees with its events") + if analysis is not None: + check_source(source, events, analysis, source_root) + if terminal is None: + return 3, f"incomplete: {len(events)} events, no terminal" + return 0, f"{terminal}: {len(events)} events, {chunks} output bytes" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", help="path or - for stdin") + parser.add_argument("--snapshot", action="store_true", help="read the JSON snapshot root") + parser.add_argument("--analysis", type=pathlib.Path) + parser.add_argument("--validate-schema", action="store_true") + parser.add_argument("--source-root", type=lambda path: pathlib.Path(path).resolve()) + args = parser.parse_args() + try: + text = sys.stdin.read() if args.input == "-" else pathlib.Path(args.input).read_text() + if args.snapshot: + snapshot = json.loads(text) + if not current_document(snapshot): + raise Invalid("unsupported Observation snapshot") + events = snapshot["events"] + else: + snapshot = None + if text and not text.endswith("\n"): + print("incomplete: interrupted JSONL record", file=sys.stderr) + return 3 + events = [json.loads(line) for line in text.split("\n")[:-1]] + if args.validate_schema: + from validate_protocols import require_valid + + if snapshot is not None: + require_valid("observation-file.schema.json", snapshot, "snapshot") + else: + for index, event in enumerate(events): + require_valid("observation-event.schema.json", event, f"seq {index}") + status, message = consume(events, snapshot, args.analysis, args.source_root) + print(message) + return status + except (Invalid, KeyError, TypeError, ValueError, OSError) as error: + print(f"invalid Observation: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/consumers/trace_consumer.py b/tests/consumers/trace_consumer.py deleted file mode 100644 index bc719b7..0000000 --- a/tests/consumers/trace_consumer.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python3 -"""Independent Trace v2 consumer: no Marqdo/Rust imports.""" -import hashlib -import json -import sys - -if len(sys.argv) != 3: - raise SystemExit("usage: trace_consumer.py ANALYSIS.json TRACE.json") - -with open(sys.argv[1], "rb") as handle: - analysis_bytes = handle.read() -analysis = json.loads(analysis_bytes) -with open(sys.argv[2], encoding="utf-8") as handle: - trace = json.load(handle) - -if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3: - raise SystemExit("unsupported analysis") -if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2: - raise SystemExit("unsupported trace") - -modules = {module["id"]: module for module in analysis["modules"]} -if trace["source"]["root_id"] != analysis["project"]["root_id"]: - raise SystemExit("trace/analysis root mismatch") -expected = "sha256:" + hashlib.sha256(analysis_bytes).hexdigest() -if trace["source"]["analysis_digest"] != expected: - raise SystemExit("analysis digest mismatch") - -truncated = trace.get("truncated") -if truncated is not None and truncated.get("reason") not in ("event_budget", "byte_budget"): - raise SystemExit("bad truncation reason") - -previous = None -events = trace["events"] -for event in events: - seq = event["seq"] - if previous is not None and seq <= previous: - raise SystemExit("sequence is not increasing") - previous = seq - span = event.get("span") - if span is not None and (span["start"] > span["end"]): - raise SystemExit("bad span") - module_id = event.get("module_id") - if module_id is not None and module_id not in modules: - raise SystemExit("event references an unknown module") - function_id = event.get("function_id") - if function_id is not None: - owner = function_id.rsplit("::", 1)[0] - if owner not in modules: - raise SystemExit("function id references an unknown module") - -if truncated is not None and events and events[-1].get("kind") != "trace.truncated": - raise SystemExit("truncated trace has no terminal marker") -print("events=" + str(len(events))) diff --git a/tests/consumers/validate_protocols.py b/tests/consumers/validate_protocols.py index c5c0ab7..9add902 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -10,6 +10,7 @@ import pathlib import sys from jsonschema import Draft202012Validator +from referencing import Registry, Resource ROOT = pathlib.Path(__file__).resolve().parents[2] SCHEMA_DIR = ROOT / "spec" / "schemas" @@ -23,7 +24,9 @@ def load_schema(name): def validator(schema): - return Draft202012Validator(schema) + event = load_schema("observation-event.schema.json") + registry = Registry().with_resource(event["$id"], Resource.from_contents(event)) + return Draft202012Validator(schema, registry=registry) def require_valid(schema_name, document, label): @@ -41,16 +44,16 @@ def require_invalid(schema_name, document, label): def main(): if len(sys.argv) != 4: raise SystemExit( - "usage: validate_protocols.py ANALYSIS.json TRACE.json TOOL.json" + "usage: validate_protocols.py ANALYSIS.json OBSERVATION.json TOOL.json" ) - analysis_path, trace_path, tool_path = map(pathlib.Path, sys.argv[1:]) + analysis_path, observation_path, tool_path = map(pathlib.Path, sys.argv[1:]) analysis = json.loads(analysis_path.read_text(encoding="utf-8")) - trace = json.loads(trace_path.read_text(encoding="utf-8")) + observation = json.loads(observation_path.read_text(encoding="utf-8")) tool = json.loads(tool_path.read_text(encoding="utf-8")) analysis_schema = "analysis.schema.json" require_valid(analysis_schema, analysis, "analysis") - require_valid("trace-v2.schema.json", trace, "trace") + require_valid("observation-file.schema.json", observation, "observation") require_valid("cli-tool.schema.json", tool, "tool") # Negative mutations: structure, version and traversal must fail closed. @@ -66,13 +69,16 @@ def main(): bad["modules"][0]["resources"] = 3 require_invalid(analysis_schema, bad, "analysis resources integer") - bad = copy.deepcopy(trace) + bad = copy.deepcopy(observation) bad["events"][0]["seq"] = "zero" - require_invalid("trace-v2.schema.json", bad, "trace event sequence type") + require_invalid("observation-file.schema.json", bad, "observation event sequence type") - bad = copy.deepcopy(trace) - bad["truncated"] = {"reason": "made_up", "limit": 1, "written": 1} - require_invalid("trace-v2.schema.json", bad, "trace truncation reason") + bad = copy.deepcopy(observation) + bad["events"][0]["schema"] = "marqdo.execution-events" + require_invalid("observation-file.schema.json", bad, "retired event format") + bad = copy.deepcopy(tool) + bad["requires"]["analysis"] = [3] + require_invalid("cli-tool.schema.json", bad, "tool version requirement array") bad = copy.deepcopy(tool) bad["entrypoint"] = "../outside" @@ -83,8 +89,8 @@ def main(): require_invalid("cli-tool.schema.json", bad, "tool invalid version") print( - "validated analysis/trace/tool artifacts " - f"({len(analysis['modules'])} modules, {len(trace['events'])} events)" + "validated analysis/observation/tool artifacts " + f"({len(analysis['modules'])} modules, {len(observation['events'])} events)" ) diff --git a/tests/security/run-lane.sh b/tests/security/run-lane.sh index 18e0a03..3caa1bc 100755 --- a/tests/security/run-lane.sh +++ b/tests/security/run-lane.sh @@ -78,8 +78,8 @@ echo "== positive CLI contract ==" "$bin" run examples/hello.mq.md --mode strict | grep -q "你好,Marqdo" "$bin" call examples/factorial.mq.md 数学.阶乘 --arg n=5 --mode strict | grep -qx "120" "$bin" run examples/multi-module/index.mq.md --mode strict >/dev/null -"$bin" run examples/hello.mq.md --mode strict --json | python3 -c \ - 'import json,sys; d=json.load(sys.stdin); assert d["success"] is True' +"$bin" run examples/hello.mq.md --mode strict --output json | python3 -c \ + 'import json,sys; d=json.load(sys.stdin); assert d["run"]["status"] == "ok"' echo "== strict language resources are console-only ==" mkdir -p .cache/security @@ -141,7 +141,8 @@ reject --allow-write 'data/**' reject --allow-net 127.0.0.1 reject --trust-native-plugin --plugin examples/plugin-demo/build reject --kernel examples/kernel-mock/kernel.json -reject --trace-file /tmp/marqdo-trace.json +reject --observation-file /tmp/marqdo-observation.json +reject --output jsonl echo "== @knowledge payloads stay inert under strict ==" rm -f .cache/security/knowledge-side-effect.txt @@ -174,7 +175,7 @@ fi # exactly one parseable document with the stable code. forged_json="$(mktemp)" set +e -MARQDO_STRICT_ACTIVE=1 "$bin" run examples/hello.mq.md --mode strict --json >"$forged_json" 2>/dev/null +MARQDO_STRICT_ACTIVE=1 "$bin" run examples/hello.mq.md --mode strict --output json >"$forged_json" 2>/dev/null code=$? set -e if [ "$code" -ne 1 ]; then @@ -188,9 +189,9 @@ import sys with open(sys.argv[1], encoding="utf-8") as handle: document = json.load(handle) -if document.get("success") is not False: +if document["run"]["status"] != "rejected": raise SystemExit(f"forged marker JSON is not a failure: {document}") -if document.get("code") != "strict.identity_invalid": +if document["events"][-1]["payload"]["error"]["code"] != "strict.identity_invalid": raise SystemExit(f"forged marker JSON code drifted: {document}") PY rm -f "$forged_json" diff --git a/tools/release/cold-install.sh b/tools/release/cold-install.sh index f92d108..8f2e03c 100644 --- a/tools/release/cold-install.sh +++ b/tools/release/cold-install.sh @@ -37,12 +37,13 @@ docker run --rm --network none --user 65534:65534 \ ./marqdo run examples/hello.mq.md | grep -F "你好,Marqdo" ./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json ./marqdo check examples/control-flow.mq.md --emit /tmp/control-analysis.json + grep -Eq "\"schema_version\"[[:space:]]*:[[:space:]]*3" /tmp/analysis.json grep -Eq "\"schema_version\"[[:space:]]*:[[:space:]]*3" /tmp/control-analysis.json test "$(./marqdo call examples/control-flow.mq.md main)" = 5 ./marqdo call examples/math-library-demo.mq.md main test "$(./marqdo call examples/factorial.mq.md 阶乘 --arg n=5)" = 120 - ./marqdo run tests/consumers/fixtures/execution-events/basic.mq.md \ - --event-stream jsonl >/tmp/events.jsonl + ./marqdo run tests/consumers/fixtures/observation/basic.mq.md \ + --output jsonl >/tmp/events.jsonl tail -n 1 /tmp/events.jsonl | grep -Eq "\"kind\"[[:space:]]*:[[:space:]]*\"run.completed\"" mv stdlib stdlib.hidden if ./marqdo run examples/hello.mq.md >/tmp/missing-stdlib.log 2>&1; then diff --git a/tools/release/package.py b/tools/release/package.py index 968a7dd..f646c78 100644 --- a/tools/release/package.py +++ b/tools/release/package.py @@ -264,8 +264,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict: "stdlib": stdlib_info, "protocols": { "analysis": 3, - "trace": 2, - "execution_events": 1, + "observation": 1, "tool": 1, "plugin_abi": "1.x", "foreign_wire": 1, diff --git a/tools/release/smoke.py b/tools/release/smoke.py index 2a27c82..668149a 100644 --- a/tools/release/smoke.py +++ b/tools/release/smoke.py @@ -160,11 +160,12 @@ class Runner: return result def json(self, args: list[str]) -> dict: - result = self.run([*args, "--json"]) + flags = ["--output", "json"] if args[0] in ("run", "call") else ["--json"] + result = self.run([*args, *flags]) try: return json.loads(result.stdout) except json.JSONDecodeError as error: - fail(f"`marqdo {' '.join(args)} --json` is not JSON: {error}\n{result.stdout}") + fail(f"`marqdo {' '.join([*args, *flags])}` is not JSON: {error}\n{result.stdout}") ANALYSIS_VERSION = 3 @@ -194,21 +195,21 @@ def verify_analysis_protocols(runner: Runner, install: Path, info: dict) -> None verify_analysis_metadata(protocols) for case, (source, options) in ANALYSIS_CASES.items(): analysis = install / f"analysis-{case}.json" - trace = install / f"trace-for-analysis-{case}.json" + snapshot = install / f"observation-{case}.json" runner.run(["check", source, "--emit", str(analysis)]) document = json.loads(analysis.read_text(encoding="utf-8")) if document.get("schema") != "marqdo.analysis" or document.get("schema_version") != ANALYSIS_VERSION: fail(f"{source} did not produce Analysis revision {ANALYSIS_VERSION}") if document.get("producer", {}).get("version") != info["product_version"]: fail("Analysis producer.version does not match the released product version") - runner.run(["run", source, "--trace-file", str(trace)]) + runner.run(["run", source, "--observation-file", str(snapshot)]) run_consumer(install, "analysis_consumer.py", analysis, *options) - run_consumer(install, "trace_consumer.py", analysis, trace) + run_consumer(install, "observation_consumer.py", "--snapshot", snapshot, "--analysis", analysis) # CI installs jsonschema. The standalone smoke can use stdlib Python. if importlib.util.find_spec("jsonschema") is not None: run_consumer( - install, "validate_protocols.py", analysis, trace, + install, "validate_protocols.py", analysis, snapshot, install / "examples" / "tool-unknown-name" / "tool.json", ) @@ -290,51 +291,25 @@ def main(argv: list[str]) -> int: verify_analysis_protocols(runner, install, info) runner.run(["check", "examples/multi-module/index.mq.md", "--refs"]) - # Execution Events v1: the released binary's live NDJSON stream, - # validated by the independent consumer shipped in the archive. + # Verify both observation destinations from the same installed run. run_help = runner.run(["run", "--help"]).stdout - if "--event-stream" not in run_help or "--observe-variable" not in run_help: - fail("run --help does not advertise Execution Events v1 options") - live = runner.run( - [ - "run", - "tests/consumers/fixtures/execution-events/basic.mq.md", - "--event-stream", - "jsonl", - ] - ) - events_path = install / "execution-events.jsonl" + if any(flag not in run_help for flag in ("--output", "--observation-file", "--observe-variable")): + fail("run --help is missing current observation options") + snapshot = install / "observation.json" + live = runner.run([ + "run", "tests/consumers/fixtures/observation/basic.mq.md", + "--output", "jsonl", "--observation-file", str(snapshot), + ]) + events_path = install / "observation.jsonl" events_path.write_text(live.stdout, encoding="utf-8") - events = [ - json.loads(line) - for line in live.stdout.splitlines() - if line.strip() - ] - if not events or events[0].get("kind") != "stream.opened": - fail("Execution Events stream does not start with stream.opened") - if events[0].get("payload", {}).get("producer", {}).get("version") != version: - fail("Execution Events producer.version does not match the product version") - if events[0].get("schema_version") != info["protocols"].get("execution_events"): - fail("Execution Events schema_version does not match RELEASE_INFO.json") - if events[-1].get("kind") != "run.completed": - fail("Execution Events stream has no successful terminal event") - validate_events = subprocess.run( - [ - sys.executable, - str(install / "tests" / "consumers" / "execution_events_consumer.py"), - str(events_path), - ], - capture_output=True, - text=True, - ) - if validate_events.returncode != 0: - if "jsonschema" in validate_events.stderr and "ModuleNotFoundError" in validate_events.stderr: - print("smoke: note: jsonschema is not installed; Execution Events schema validation skipped") - else: - fail( - "execution_events_consumer.py failed:\n" - f"{validate_events.stdout}\n{validate_events.stderr}" - ) + events = [json.loads(line) for line in live.stdout.strip("\n").split("\n")] + if events != json.loads(snapshot.read_bytes())["events"]: + fail("live events differ from the same run's snapshot") + if events[0]["payload"]["producer"]["version"] != version: + fail("Observation producer version does not match the archive") + if events[0]["schema_version"] != info["protocols"].get("observation"): + fail("Observation revision does not match RELEASE_INFO.json") + run_consumer(install, "observation_consumer.py", events_path) # Tool Protocol v1: install and dispatch an independent process. runner.run(["tool", "install", "examples/tool-unknown-name/tool.json"]) @@ -407,15 +382,17 @@ def main(argv: list[str]) -> int: "demo.sensor", ] ) - if not provider_run.get("success"): + if provider_run["run"]["status"] != "ok": fail(f"provider run was not successful: {provider_run}") reads = [ - event - for event in provider_run.get("trace", []) - if event.get("op") == "resource.read" + event["payload"] + for event in provider_run["events"] + if event["kind"] == "effect" and event["payload"]["operation"] == "resource.read" ] - if not reads or "count=5" not in str(reads[-1].get("result")): - fail(f"provider read did not report five bytes: {reads}") + if not reads or reads[-1]["result_code"] != "ok": + fail(f"provider read did not succeed: {reads}") + if provider_run["events"][-1]["payload"]["value"] != {"type": "int", "decimal": "5"}: + fail("provider demo did not return its five-byte read count") runner.run( [ "run", From bf141a1f26a2c8d9d1e6650d7af9813d86e4bda9 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 16:55:19 +0800 Subject: [PATCH 05/17] worker: share one bounded transport across plugin and provider workers --- Cargo.lock | 13 +- Cargo.toml | 2 + README.md | 3 +- crates/cli/tests/architecture_boundaries.rs | 37 ++ crates/marqdo-host/Cargo.toml | 1 + crates/marqdo-host/src/plugin_worker.rs | 184 +++++----- crates/marqdo-host/src/provider_worker.rs | 91 +++-- crates/marqdo-plugin-abi/Cargo.toml | 1 + crates/marqdo-plugin-abi/src/worker.rs | 100 ++---- crates/marqdo-provider-worker/Cargo.toml | 1 + crates/marqdo-provider-worker/src/main.rs | 40 +-- crates/marqdo-worker-ipc/Cargo.toml | 12 + crates/marqdo-worker-ipc/src/lib.rs | 370 ++++++++++++++++++++ docs/architecture/CURRENT.md | 11 +- spec/plugin-abi.md | 5 +- spec/resource-provider-v2.md | 4 +- spec/worker-ipc.md | 100 ++++++ 17 files changed, 719 insertions(+), 256 deletions(-) create mode 100644 crates/marqdo-worker-ipc/Cargo.toml create mode 100644 crates/marqdo-worker-ipc/src/lib.rs create mode 100644 spec/worker-ipc.md diff --git a/Cargo.lock b/Cargo.lock index ac0d060..39c2a2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" @@ -491,6 +491,7 @@ dependencies = [ "marqdo-sandbox", "marqdo-span", "marqdo-value", + "marqdo-worker-ipc", "rcgen", "regex", "rustls", @@ -545,6 +546,7 @@ dependencies = [ "libloading", "marqdo-span", "marqdo-value", + "marqdo-worker-ipc", "serde", "serde_json", "serde_yaml", @@ -569,6 +571,7 @@ dependencies = [ "marqdo-host", "marqdo-sandbox", "marqdo-value", + "marqdo-worker-ipc", "serde_json", "tempfile", ] @@ -618,6 +621,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "marqdo-worker-ipc" +version = "3.0.0-rc.2" +dependencies = [ + "serde_json", + "thiserror", +] + [[package]] name = "memchr" version = "2.8.3" diff --git a/Cargo.toml b/Cargo.toml index c54d882..b9c7be5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ 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-runtime", @@ -35,6 +36,7 @@ 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-runtime = { path = "crates/marqdo-runtime" } marqdo-package = { path = "crates/marqdo-package" } diff --git a/README.md b/README.md index 2a1bd1a..2404f1e 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,8 @@ tests/ conformance/negative corpus (see tests/README.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), [`cli-tool.md`](spec/cli-tool.md), - [`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.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. diff --git a/crates/cli/tests/architecture_boundaries.rs b/crates/cli/tests/architecture_boundaries.rs index 179f436..45061d6 100644 --- a/crates/cli/tests/architecture_boundaries.rs +++ b/crates/cli/tests/architecture_boundaries.rs @@ -33,6 +33,7 @@ const WORKSPACE_CRATES: &[&str] = &[ "marqdo-foreign", "marqdo-plugin-abi", "marqdo-provider-worker", + "marqdo-worker-ipc", "marqdo-plugin-sdk", "marqdo-host", "marqdo-runtime", @@ -140,6 +141,42 @@ 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-plugin-abi/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/provider_worker.rs", + "crates/marqdo-plugin-abi/src/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")); diff --git a/crates/marqdo-host/Cargo.toml b/crates/marqdo-host/Cargo.toml index 15fe244..b8c87cf 100644 --- a/crates/marqdo-host/Cargo.toml +++ b/crates/marqdo-host/Cargo.toml @@ -13,6 +13,7 @@ libloading = { workspace = true } rustls = { workspace = true } rustls-native-certs = { workspace = true } marqdo-plugin-abi = { workspace = true } +marqdo-worker-ipc = { workspace = true } flate2 = { workspace = true } getrandom = { workspace = true } regex = { workspace = true } diff --git a/crates/marqdo-host/src/plugin_worker.rs b/crates/marqdo-host/src/plugin_worker.rs index e14fbfd..ef51df4 100644 --- a/crates/marqdo-host/src/plugin_worker.rs +++ b/crates/marqdo-host/src/plugin_worker.rs @@ -4,27 +4,30 @@ //! `__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, + response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES, + WORKER_COMMAND, }; use marqdo_plugin_abi::{ CapabilityHandler, PluginError, PluginManifest, 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>, + connection: Connection, exports: BTreeMap, dead: bool, capability_handler: Option, @@ -36,7 +39,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::>()) .finish() } @@ -77,7 +80,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 +98,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 +152,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 +175,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 +204,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 +235,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 +288,53 @@ 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}"), + ), + TransportError::Frame(other) => { + PluginError::wire("worker_frame_invalid", other.to_string()) + } } } diff --git a/crates/marqdo-host/src/provider_worker.rs b/crates/marqdo-host/src/provider_worker.rs index 9ab4980..dbfb79d 100644 --- a/crates/marqdo-host/src/provider_worker.rs +++ b/crates/marqdo-host/src/provider_worker.rs @@ -1,29 +1,34 @@ //! 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 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, - child: Child, - stdin: ChildStdin, - stdout: BufReader, + connection: Connection, } impl WorkerResourceProvider { @@ -33,7 +38,7 @@ impl WorkerResourceProvider { program: &Path, args: &[String], ) -> Result { - let mut child = Command::new(program) + let child = Command::new(program) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -49,20 +54,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 +67,11 @@ impl WorkerResourceProvider { } fn request(&mut self, request: Json) -> Result { - 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 +170,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 +185,21 @@ fn with_span(mut error: RuntimeError, span: Option) -> 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()) } diff --git a/crates/marqdo-plugin-abi/Cargo.toml b/crates/marqdo-plugin-abi/Cargo.toml index e3466cb..02fc78b 100644 --- a/crates/marqdo-plugin-abi/Cargo.toml +++ b/crates/marqdo-plugin-abi/Cargo.toml @@ -11,6 +11,7 @@ authors.workspace = true [dependencies] marqdo-span = { workspace = true } marqdo-value = { workspace = true } +marqdo-worker-ipc = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } serde_yaml = { workspace = true } diff --git a/crates/marqdo-plugin-abi/src/worker.rs b/crates/marqdo-plugin-abi/src/worker.rs index 6c6f807..58fce1f 100644 --- a/crates/marqdo-plugin-abi/src/worker.rs +++ b/crates/marqdo-plugin-abi/src/worker.rs @@ -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(reader: &mut R) -> Result, 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(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. diff --git a/crates/marqdo-provider-worker/Cargo.toml b/crates/marqdo-provider-worker/Cargo.toml index c313b72..6220776 100644 --- a/crates/marqdo-provider-worker/Cargo.toml +++ b/crates/marqdo-provider-worker/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [dependencies] libloading = { workspace = true } serde_json = { workspace = true } +marqdo-worker-ipc = { workspace = true } [dev-dependencies] marqdo-host = { path = "../marqdo-host" } diff --git a/crates/marqdo-provider-worker/src/main.rs b/crates/marqdo-provider-worker/src/main.rs index 4780c09..eca2157 100644 --- a/crates/marqdo-provider-worker/src/main.rs +++ b/crates/marqdo-provider-worker/src/main.rs @@ -5,7 +5,6 @@ //! boundary, not a sandbox: the library runs with the worker's privileges. use std::ffi::{c_char, CString}; -use std::io::{Read, Write}; use std::path::PathBuf; use libloading::Library; @@ -129,41 +128,16 @@ impl Provider { } fn read_frame() -> Result, String> { - let mut header = [0u8; 4]; - let mut read = 0usize; - while read < header.len() { - match std::io::stdin().read(&mut header[read..]) { - Ok(0) if read == 0 => return Ok(None), - Ok(0) => return Err("stdin ended inside a frame header".to_string()), - Ok(count) => read += count, - Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, - Err(error) => return Err(format!("stdin read failed: {error}")), - } - } - let length = u32::from_be_bytes(header) as usize; - if length == 0 || length > MAX_FRAME_BYTES { - return Err(format!("invalid frame length {length}")); - } - let mut payload = vec![0u8; length]; - std::io::stdin() - .read_exact(&mut payload) - .map_err(|error| format!("stdin read failed: {error}"))?; - serde_json::from_slice(&payload) - .map(Some) - .map_err(|error| format!("invalid JSON frame: {error}")) + let stdin = std::io::stdin(); + let mut input = stdin.lock(); + marqdo_worker_ipc::read_frame(&mut input, MAX_FRAME_BYTES).map_err(|error| error.to_string()) } fn write_frame(value: &Json) -> Result<(), String> { - let bytes = serde_json::to_vec(value).map_err(|error| format!("encode failed: {error}"))?; - if bytes.len() > MAX_FRAME_BYTES { - return Err("response frame is too large".to_string()); - } - let mut stdout = std::io::stdout(); - stdout - .write_all(&(bytes.len() as u32).to_be_bytes()) - .and_then(|()| stdout.write_all(&bytes)) - .and_then(|()| stdout.flush()) - .map_err(|error| format!("stdout write failed: {error}")) + let stdout = std::io::stdout(); + let mut output = stdout.lock(); + marqdo_worker_ipc::write_frame(&mut output, value, MAX_FRAME_BYTES) + .map_err(|error| error.to_string()) } fn fail(message: &str) -> Json { diff --git a/crates/marqdo-worker-ipc/Cargo.toml b/crates/marqdo-worker-ipc/Cargo.toml new file mode 100644 index 0000000..a44948f --- /dev/null +++ b/crates/marqdo-worker-ipc/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "marqdo-worker-ipc" +description = "Bounded framed JSON and child transport for Marqdo workers" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish = false + +[dependencies] +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/marqdo-worker-ipc/src/lib.rs b/crates/marqdo-worker-ipc/src/lib.rs new file mode 100644 index 0000000..b32344c --- /dev/null +++ b/crates/marqdo-worker-ipc/src/lib.rs @@ -0,0 +1,370 @@ +#![forbid(unsafe_code)] + +//! Bounded length-prefixed JSON framing and child-process transport shared by +//! persistent Marqdo workers. +//! +//! The crate owns only what is genuinely common to a plugin worker and a +//! resource-provider worker: the four-byte big-endian length prefix, the +//! maximum frame size, clean-EOF versus truncated-frame classification, a +//! single reader and writer thread, request deadlines, and process teardown. +//! Each caller still owns its own frame vocabulary, size limit, authority, +//! capability bridge and error codes. Sharing this transport does not share +//! capabilities or trust. +//! +//! Foreign kernels and CLI Tools do not use this transport: a foreign kernel +//! is a one-shot stdin/stdout wire value, and a CLI Tool is an independent +//! executable owning its standard streams. + +use std::io::{self, Read, Write}; +use std::process::Child; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError}; +use std::time::{Duration, Instant}; + +use serde_json::Value; +use thiserror::Error; + +/// Read a bounded four-byte big-endian length and JSON value. +#[derive(Debug, Error)] +pub enum FrameError { + #[error("worker frame I/O failed: {0}")] + Io(#[from] io::Error), + #[error("worker stream ended inside a frame header")] + PartialHeader, + #[error("worker frame length {0} is invalid")] + Length(usize), + #[error("worker frame declared {expected} bytes but only {actual} arrived")] + PartialPayload { expected: usize, actual: usize }, + #[error("worker frame is not valid JSON: {0}")] + InvalidJson(serde_json::Error), + #[error("cannot encode worker frame: {0}")] + Encode(serde_json::Error), +} + +/// Read one bounded frame. +/// +/// `Ok(None)` is a clean EOF at a frame boundary. A partial header, a +/// truncated payload, an invalid length or invalid JSON is a protocol error and +/// never EOF. `limit` is the caller's protocol frame budget, in bytes. +pub fn read_frame(reader: &mut impl Read, limit: usize) -> Result, FrameError> { + let mut header = [0; 4]; + let mut offset = 0; + while offset < header.len() { + match reader.read(&mut header[offset..]) { + Ok(0) if offset == 0 => return Ok(None), + Ok(0) => return Err(FrameError::PartialHeader), + Ok(count) => offset += count, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error.into()), + } + } + let expected = u32::from_be_bytes(header) as usize; + if expected == 0 || expected > limit { + return Err(FrameError::Length(expected)); + } + let mut payload = Vec::with_capacity(expected.min(64 * 1024)); + let actual = reader.take(expected as u64).read_to_end(&mut payload)?; + if actual != expected { + return Err(FrameError::PartialPayload { expected, actual }); + } + serde_json::from_slice(&payload) + .map(Some) + .map_err(FrameError::InvalidJson) +} + +/// Write and flush one frame under the peer's configured size limit. +pub fn write_frame(writer: &mut impl Write, value: &Value, limit: usize) -> Result<(), FrameError> { + let payload = serde_json::to_vec(value).map_err(FrameError::Encode)?; + if payload.len() > limit { + return Err(FrameError::Length(payload.len())); + } + let length = u32::try_from(payload.len()).map_err(|_| FrameError::Length(payload.len()))?; + writer.write_all(&length.to_be_bytes())?; + writer.write_all(&payload)?; + writer.flush()?; + Ok(()) +} + +/// Failure of one configured request/response exchange. +#[derive(Debug, Error)] +pub enum TransportError { + #[error("worker transport reached its deadline")] + Timeout, + #[error("worker transport closed")] + Closed, + #[error(transparent)] + Frame(#[from] FrameError), +} + +type WriteRequest = (Value, SyncSender>); + +/// Owns one configured child and its two dedicated protocol pipes. +/// +/// A connection is sequential: one caller drives one exchange at a time, and +/// the caller supplies the deadline for that exchange. Any transport error +/// kills and reaps the child, so a dead worker is never reused. +pub struct Connection { + child: Option, + writes: Option>, + reads: Option>>, +} + +impl Connection { + /// Attach to a child with piped stdin/stdout, closing the child on failure. + pub fn attach(child: Child, limit: usize) -> io::Result { + let mut connection = Self { + child: Some(child), + writes: None, + reads: None, + }; + if let Err(error) = connection.attach_pipes(limit) { + connection.abort(); + return Err(error); + } + Ok(connection) + } + + fn attach_pipes(&mut self, limit: usize) -> io::Result<()> { + let instance = self.child.as_mut().expect("child present"); + let mut stdin = instance + .stdin + .take() + .ok_or_else(|| io::Error::other("worker stdin unavailable"))?; + let mut stdout = instance + .stdout + .take() + .ok_or_else(|| io::Error::other("worker stdout unavailable"))?; + + let (writes, pending) = mpsc::sync_channel::(1); + std::thread::Builder::new() + .name("marqdo-worker-writer".into()) + .spawn(move || { + while let Ok((value, reply)) = pending.recv() { + if reply.send(write_frame(&mut stdin, &value, limit)).is_err() { + break; + } + } + })?; + self.writes = Some(writes); + + let (received, reads) = mpsc::sync_channel(1); + std::thread::Builder::new() + .name("marqdo-worker-reader".into()) + .spawn(move || loop { + match read_frame(&mut stdout, limit) { + Ok(Some(value)) => { + if received.send(Ok(value)).is_err() { + break; + } + } + Ok(None) => break, + Err(error) => { + let _ = received.send(Err(error)); + break; + } + } + })?; + self.reads = Some(reads); + Ok(()) + } + + /// Process id of the attached child, if it is still owned here. + pub fn id(&self) -> Option { + self.child.as_ref().map(Child::id) + } + + /// Send one frame and wait for the write to complete before the deadline. + pub fn send(&mut self, value: Value, deadline: Instant) -> Result<(), TransportError> { + let result = (|| { + let channel = self.writes.as_ref().ok_or(TransportError::Closed)?; + let (response, result) = mpsc::sync_channel(1); + let mut pending = Some((value, response)); + loop { + match channel.try_send(pending.take().expect("pending frame")) { + Ok(()) => break, + Err(TrySendError::Full(returned)) => { + pending = Some(returned); + if Instant::now() >= deadline { + return Err(TransportError::Timeout); + } + std::thread::sleep(Duration::from_millis(1)); + } + Err(TrySendError::Disconnected(_)) => return Err(TransportError::Closed), + } + } + wait(&result, deadline)?.map_err(Into::into) + })(); + if result.is_err() { + self.abort(); + } + result + } + + /// Receive one frame before the deadline. + pub fn receive(&mut self, deadline: Instant) -> Result { + let result = self + .reads + .as_ref() + .ok_or(TransportError::Closed) + .and_then(|channel| wait(channel, deadline)) + .and_then(|frame| frame.map_err(Into::into)); + if result.is_err() { + self.abort(); + } + result + } + + /// Make this peer unusable and reap the process. + pub fn abort(&mut self) { + self.writes.take(); + self.reads.take(); + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Drop for Connection { + fn drop(&mut self) { + self.abort(); + } +} + +fn wait(channel: &Receiver, deadline: Instant) -> Result { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(TransportError::Timeout); + } + channel + .recv_timeout(remaining) + .map_err(|error| match error { + RecvTimeoutError::Timeout => TransportError::Timeout, + RecvTimeoutError::Disconnected => TransportError::Closed, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn framing_distinguishes_boundary_eof_from_a_partial_record() { + let mut bytes = Vec::new(); + write_frame(&mut bytes, &json!({"ok": true}), 64).unwrap(); + let mut input = bytes.as_slice(); + assert_eq!( + read_frame(&mut input, 64).unwrap(), + Some(json!({"ok": true})) + ); + assert_eq!(read_frame(&mut input, 64).unwrap(), None); + assert!(matches!( + read_frame(&mut &bytes[..3], 64), + Err(FrameError::PartialHeader) + )); + assert!(matches!( + read_frame(&mut &bytes[..6], 64), + Err(FrameError::PartialPayload { .. }) + )); + assert!(matches!( + read_frame(&mut &[0; 4][..], 64), + Err(FrameError::Length(0)) + )); + assert!(matches!( + read_frame(&mut &bytes[..4], 4), + Err(FrameError::Length(_)) + )); + } + + #[test] + fn writing_past_the_peer_limit_is_a_frame_error() { + let mut bytes = Vec::new(); + let error = write_frame(&mut bytes, &json!({"payload": "long"}), 4).unwrap_err(); + assert!(matches!(error, FrameError::Length(_))); + assert!(bytes.is_empty()); + } + + #[cfg(unix)] + mod child { + use super::*; + use std::process::{Command, Stdio}; + + fn connection(script: &str) -> Connection { + let child = Command::new("python3") + .arg("-c") + .arg(script) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("python3 is required for worker transport tests"); + Connection::attach(child, 1024).expect("attach child") + } + + const ECHO: &str = r#" +import sys, json, struct +def read_frame(): + header = sys.stdin.buffer.read(4) + if len(header) < 4: + return None + return json.loads(sys.stdin.buffer.read(struct.unpack(">I", header)[0])) +def write_frame(value): + payload = json.dumps(value).encode() + sys.stdout.buffer.write(struct.pack(">I", len(payload)) + payload) + sys.stdout.buffer.flush() +while True: + frame = read_frame() + if frame is None: + break + write_frame({"echo": frame}) +"#; + + #[test] + fn connection_round_trips_frames_from_one_child() { + let mut connection = connection(ECHO); + let deadline = Instant::now() + Duration::from_secs(10); + connection.send(json!({"n": 1}), deadline).unwrap(); + assert_eq!( + connection.receive(deadline).unwrap(), + json!({"echo": {"n": 1}}) + ); + connection.send(json!({"n": 2}), deadline).unwrap(); + assert_eq!( + connection.receive(deadline).unwrap(), + json!({"echo": {"n": 2}}) + ); + } + + #[test] + fn a_silent_child_hits_the_request_deadline_and_is_reaped() { + let mut connection = connection("import time; time.sleep(30)"); + let deadline = Instant::now() + Duration::from_millis(200); + assert!(matches!( + connection.receive(deadline), + Err(TransportError::Timeout) + )); + assert!(connection.id().is_none()); + assert!(matches!( + connection.receive(Instant::now() + Duration::from_secs(1)), + Err(TransportError::Closed) + )); + } + + #[test] + fn clean_eof_is_closed_and_a_truncated_frame_is_a_frame_error() { + let mut silent = connection("pass"); + assert!(matches!( + silent.receive(Instant::now() + Duration::from_secs(10)), + Err(TransportError::Closed) + )); + + let mut truncated = connection( + "import sys, struct; sys.stdout.buffer.write(struct.pack('>I', 10) + b'{}'); sys.stdout.buffer.flush()", + ); + assert!(matches!( + truncated.receive(Instant::now() + Duration::from_secs(10)), + Err(TransportError::Frame(FrameError::PartialPayload { .. })) + )); + } + } +} diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index 60fc153..a8adc15 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -65,6 +65,7 @@ for replacing public interfaces before the first stable release. | Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) | | Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) | | Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) | +| Persistent worker plumbing | Plugin and provider workers share one bounded framed transport; each keeps its vocabulary, limits and authority | [Shared worker transport](../../spec/worker-ipc.md) | | Values and package identities | Value Wire and project lock | [Value Wire](../../spec/value-wire.md), [Extension selection and lock](../../spec/extension-selection.md) | `check --emit analysis.json` projects static facts from the prepared project. @@ -154,9 +155,17 @@ Current Rust dependency edges (documented, not proposed): marqdo-cli -> marqdo-runtime -> marqdo-host marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ... marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value -marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox +marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc +marqdo-plugin-abi -> marqdo-worker-ipc +marqdo-provider-worker -> marqdo-worker-ipc ``` +`marqdo-worker-ipc` depends only on `serde_json` and `thiserror`: it is the one +copy of bounded worker framing, deadlines and process teardown +([spec/worker-ipc.md](../../spec/worker-ipc.md)). It must never depend on the +host, the plugin ABI, or a worker binary; sharing plumbing must not share +capabilities. Foreign kernels and CLI Tools stay outside it. + `marqdo-runtime -> marqdo-host` is the current direction. Do not add a second execution backend or a `marqdo-stdlib` crate by implication. A future embedded runtime or a second backend needs the thin `ExecutionPort` contract described in the diff --git a/spec/plugin-abi.md b/spec/plugin-abi.md index 1663c11..627607c 100644 --- a/spec/plugin-abi.md +++ b/spec/plugin-abi.md @@ -370,7 +370,10 @@ not an OS sandbox: the worker still runs as the user. Wasm, hot unload and worke Frames are a 4-byte big-endian length followed by one JSON object (max 8 MiB). A zero/oversized length, partial header, truncated payload or invalid JSON is a protocol error; clean EOF at a frame boundary is not. The host marks the worker -dead after a transport failure and does not reuse it. +dead after a transport failure and does not reuse it. Framing, bounded reads, +deadlines and process teardown are implemented once in the +[shared worker transport](worker-ipc.md); the frame vocabulary below, the +capability limit and every grant remain owned by this boundary. Worker → host: `{"kind":"ready","exports":[...]}`. Host → worker: `{"kind":"invoke","request":}` and `{"kind":"shutdown"}`. Worker → host responses are `{"kind":"response","response":}` or diff --git a/spec/resource-provider-v2.md b/spec/resource-provider-v2.md index cd9cf91..4cf48ee 100644 --- a/spec/resource-provider-v2.md +++ b/spec/resource-provider-v2.md @@ -189,7 +189,9 @@ The helper is `marqdo-provider-worker `. It loads exactly one `c-abi-1` shared library, verifies `marqdo_resource_provider_abi_version() == 1`, and speaks the ADR-0035 framed protocol over stdin/stdout: 4-byte big-endian length + JSON, 1 MiB maximum per -frame. +frame. Framing and process plumbing come from the +[shared worker transport](worker-ipc.md); the operation vocabulary, kind rights +and token lifecycle below remain owned by this boundary. ```text {"op":"ping"} -> {"ok":true} (handshake) diff --git a/spec/worker-ipc.md b/spec/worker-ipc.md new file mode 100644 index 0000000..d4fbb3f --- /dev/null +++ b/spec/worker-ipc.md @@ -0,0 +1,100 @@ +# Shared persistent-worker transport + +Status: **implemented pre-stable internal transport**, owner crate +`crates/marqdo-worker-ipc`, introduced by +[ADR-0068](../docs/adr/0068-single-current-public-contracts.md) for issue #8. + +This document is not a public product protocol and has no `schema_version`. +It describes the one implementation of the framing and process plumbing that +the two persistent worker boundaries — the plugin worker +([plugin ABI](plugin-abi.md) §9) and the resource-provider worker +([resource provider](resource-provider-v2.md) §5) — use instead of maintaining +private copies. + +## 1. What is shared, and what is not + +Shared (`crates/marqdo-worker-ipc`): + +- the four-byte big-endian length prefix followed by one JSON value; +- maximum-frame bounding supplied by each caller (8 MiB plugins, 1 MiB + providers) and rejection of zero/oversized lengths; +- clean EOF at a frame boundary versus a partial header, truncated payload or + invalid JSON; +- one reader thread and one writer thread per child, so a caller never reads + and writes the same pipe concurrently; +- caller-supplied exchange deadlines, process kill/reap on any transport + failure, and "a dead worker is never reused"; +- structured transport errors (`Timeout`, `Closed`, `Frame`). + +Not shared — each boundary keeps its own: + +- frame vocabulary and state machine (`ready`/`invoke`/`capability_*` versus + `ping`/`open`/`read`/`write`/`close`/`shutdown`); +- frame size limit and capability/budget policy; +- authorization, grants, kind/rights checks and lifecycle; +- error codes and public observation. + +A shared transport never shares capabilities, trust or identity. Killing a +worker after a transport failure is plumbing; deciding what a worker may do is +a separate gate. + +Foreign kernels and CLI Tools are deliberately excluded. A foreign kernel is a +one-shot process whose stdout must be exactly one value-wire object +([foreign](foreign.md)); a CLI Tool is an independent executable that owns its +standard streams ([CLI tool](cli-tool.md)). Neither has a persistent framed +channel, and neither may gain one by reusing this crate. + +## 2. Framing rules + +```text ++--------------------------+---------------------------+ +| 4-byte big-endian length | exactly `length` bytes | +| (1 ..= caller limit) | of one JSON value | ++--------------------------+---------------------------+ +``` + +| Outcome | Classification | +|---|---| +| EOF before any header byte | clean `None` (not an error) | +| EOF inside the four-byte header | `FrameError::PartialHeader` | +| length `0` or above the caller limit | `FrameError::Length` | +| EOF inside the payload | `FrameError::PartialPayload` | +| payload is not UTF-8 JSON | `FrameError::InvalidJson` | +| write larger than the caller limit | `FrameError::Length` (nothing written) | + +Writers flush every frame. Readers bound the allocation before reading. There +is no negotiation, no version field and no fallback: each boundary has exactly +one current frame shape at its existing format identifier. + +## 3. Exchange and deadline rules + +The host-side `Connection` is sequential: one exchange is in flight at a time. +The caller passes an `Instant` deadline with `send`/`receive`; a missed deadline +kills and reaps the child and returns `TransportError::Timeout`. Clean EOF +before a reply returns `Closed`; a malformed frame returns `Frame` with the +classification above. Every transport error aborts the connection, so a worker +that timed out, crashed or violated framing is never reused for a later call. + +The worker side uses the same `read_frame`/`write_frame` functions on its own +stdin/stdout. Worker processes still exit non-zero on malformed input rather +than guessing at a retired format. + +## 4. Boundary-specific deadlines (current values) + +| Boundary | Handshake | One exchange | Quarantine | +|---|---|---|---| +| Plugin worker | 30 s | 10 s per invocation, covering capability round-trips | killed, `plugin.timeout` | +| Resource-provider worker | 30 s (ping) | 30 s per request | killed, host error | + +Timeouts classify a failed exchange; they do not change program semantics. +The strict sandbox decision is still made by the OS isolation adapter, never by +the fact that a worker is a child process. + +## 5. Verification + +`crates/marqdo-worker-ipc` owns the transport tests: framing round-trip, +boundary/EOF classification, oversize rejection, a live two-frame exchange, a +silent child hitting its deadline and being reaped, clean EOF, and a truncated +payload. The plugin and provider suites keep testing their own vocabulary, +grants, token lifecycle and error codes through the real worker binaries, so a +transport refactor cannot hide a behaviour change at either boundary. From 3fe1ca3c0c93b1f42ce6363f74b01c4820ded412 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:04:03 +0800 Subject: [PATCH 06/17] docs: record the single-contract policy and review gate --- AGENTS.md | 5 +- docs/STATUS.md | 47 +++- docs/architecture/CURRENT.md | 5 + .../PROTOCOL_CONVERGENCE_POLICY.md | 202 ++++++++++++++++++ docs/architecture/README.md | 5 +- docs/contributor-guide.md | 5 +- 6 files changed, 256 insertions(+), 13 deletions(-) create mode 100644 docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md diff --git a/AGENTS.md b/AGENTS.md index 52d1778..60c18fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,8 +36,9 @@ correctness and release evidence before expanding the surface. ## Pre-stable protocol changes -Read [ADR-0068](docs/adr/0068-single-current-public-contracts.md) before changing -a public boundary. Keep one current specification, producer and validator per +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 diff --git a/docs/STATUS.md b/docs/STATUS.md index f167d02..f28bd75 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -34,11 +34,39 @@ published beta. ## Current protocol integration -[ADR-0068](adr/0068-single-current-public-contracts.md) governs the work -for [issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8). Current -developer inputs are [Analysis](../spec/analysis.md), -[Observation](../spec/observation.md) and the [CLI Tool](../spec/cli-tool.md). -The earlier release records below describe their tagged binaries. +[ADR-0068](adr/0068-single-current-public-contracts.md) and the +[single-contract policy](architecture/PROTOCOL_CONVERGENCE_POLICY.md) govern +every public boundary. Current developer inputs are +[Analysis](../spec/analysis.md), [Observation](../spec/observation.md) and the +[CLI Tool](../spec/cli-tool.md); the shared persistent-worker transport is +[worker-ipc](../spec/worker-ipc.md). + +Issue [#8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) converged the +pre-stable contracts in one breaking integration, with no compatibility layer: + +- Analysis has one writer and one current `schema_version` for every project, + including projects without loop transfers. The content-driven v2/v3 selector + and the retired `spec/analysis-v*.md` documents are gone. +- Trace and Execution Events became one Observation event definition. One + execution emits one `run_id`/`seq` sequence; `--output jsonl` and + `--observation-file` deliver those same events, never a second execution or a + second numbering. The retired `--json`/`--trace-file`/`--event-stream` + options are rejected. +- CLI Tool requirements are single exact integers (`api_revision`, optional + `analysis`, optional `observation`). Version arrays and intersection + negotiation are removed; retired registrations are rejected with a reinstall + instruction. +- Plugin and resource-provider workers share one bounded framed transport + ([worker-ipc](../spec/worker-ipc.md)) while each boundary keeps its own + vocabulary, limits, capabilities and error codes. +- Extension descriptors (plugin/provider/kernel) and lock v4 keep their current + format identifiers. Retired lock versions are rejected with an explicit + `marqdo lock` regeneration instruction; there is no migrator. Renumbering an + unchanged format was explicitly rejected. + +The `spec/` tree contains only current contracts; retired specifications are in +Git history and tagged archives. The earlier release records below describe +their tagged binaries and are not current protocol claims. ## 0. Beta release record — `3.0.0-beta.1` @@ -47,9 +75,10 @@ The earlier release records below describe their tagged binaries. - Workspace/crate version, `marqdo --version` and Analysis `producer.version` are `3.0.0-beta.1`; `Cargo.lock` is committed and release builds use `--locked`. -- Independent axes are unchanged: Analysis v2, Trace v2, Tool v1, Plugin ABI +- At the tagged beta, the axes were Analysis v2, Trace v2, Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4, markdown profile - `marqdo.md.v1`; bundled stdlib stays package version `0.1.0`. + `marqdo.md.v1`; bundled stdlib stayed package version `0.1.0`. Those are + historical identifiers, not current claims. - `project.marqdo` is enforced; prerelease SemVer rules are covered by tests (`>=3.0.0,<4.0.0` does not silently accept a beta core). - Only the Linux x86_64 archive is claimed. macOS/Windows are @@ -110,7 +139,7 @@ exports reconcile exactly with the static manifest. The independent frozen-binary suite is the beta gate above; the older `6a7bb98` manifest is historical and superseded by the release-SHA manifest. -## 0.5 Post-beta addition — Execution Events v1 (unreleased) +## 0.5 Historical: post-beta Execution Events v1 (superseded by Observation) This section records work **after** the `v3.0.0-beta.1` tag. It is not part of the tagged beta archive and no new release tag has been created. The design @@ -272,7 +301,7 @@ digests. The external lane ran from a temporary fixture checkout with Cargo absent from PATH. Archive SHA-256 is `8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`. -## 0.8 Structured control flow — RFC-CTRL-0005 (RC.2 candidate) +## 0.8 Historical: structured control flow — RFC-CTRL-0005 (RC.2 snapshot) [ADR-0067](adr/0067-structured-control-flow.md) covers the phase A implementation. An `else if` carrier adds a condition arm to the existing branch IR. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index a8adc15..037ac70 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -258,10 +258,15 @@ that a phase is complete. 5. When behavior or status changes, update code + tests + `docs/STATUS.md` + this file + an evidence file in the same change. A fixture/demo is not a published stdlib API. +6. A public-boundary change must follow + [`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md): one + current contract, replace in place, reject retired inputs, no compatibility + path or version negotiation, and no version bump without a shape change. ## 7. References - [Architecture index](README.md) — RFC/ADR/evidence history. +- [Protocol convergence policy](PROTOCOL_CONVERGENCE_POLICY.md) — one-contract rules, anti-patterns and review checklist. - [Implementation status](../STATUS.md) — executed state and blockers. - [Language/frontmatter blueprint](../DEVELOPMENT_BLUEPRINT.md) — design baseline; not current status. - [3.0 prerelease plan](../MARQDO_3_0_PRERELEASE_PLAN.md) — current release policy and beta gates. diff --git a/docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md b/docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md new file mode 100644 index 0000000..1bd1128 --- /dev/null +++ b/docs/architecture/PROTOCOL_CONVERGENCE_POLICY.md @@ -0,0 +1,202 @@ +# Protocol convergence policy (pre-stable) + +Status: **current contributor policy**. Owner: architecture review. Authority: +[ADR-0068](../adr/0068-single-current-public-contracts.md), adopted for +[issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) before the first +stable release. This page is the checklist that prevents the same failure from +returning; it does not replace `spec/` or an ADR. + +## 1. The failure this policy prevents + +Before issue #8 the tree kept several competing models of the same fact: + +- Analysis chose `schema_version` 2 or 3 from the **content** of the project + (presence of `break`/`continue`), and a Tool declared an **array** of + Analysis versions and installed when the arrays intersected. Installation + succeeded while the actual output stayed unreadable for that project. +- Trace and Execution Events each defined a public representation of the same + execution, with separate writers, budgets and privacy rules. +- `spec/` still carried superseded Analysis/Trace/Events documents beside the + current ones, so a reader could not tell which contract the binary emitted. + +The root cause was not "too many JSON files". It was **maintaining a replaced +architecture as a second live path** after the architecture had changed. The +cure is one current contract per real boundary, replaced in place, with +retired inputs rejected explicitly. + +## 2. Current boundary map + +Every row has exactly one current contract. A change must keep it that way. + +| Real boundary | Current contract | Single producer / validator | Retired, kept in Git only | +|---|---|---|---| +| Markdown syntax | [`markdown-profile.md`](../../spec/markdown-profile.md) `marqdo.md.v1` | `marqdo-markdown` (frozen Comrak options) | older profiles | +| Language mapping | [`mapping.md`](../../spec/mapping.md), [`expression.ebnf`](../../spec/expression.ebnf) | `marqdo-frontend` + `marqdo-expression` | pre-RFC-LANG-0002 mapping | +| Static facts | [`analysis.md`](../../spec/analysis.md) + `analysis.schema.json` | `crates/cli/src/analysis.rs` | Analysis v1/v2/v3 split | +| Runtime facts | [`observation.md`](../../spec/observation.md) + two schemas (event, snapshot) | Host observation sink, CLI assigns `run_id`/`seq` | Trace v1/v2, Execution Events v1 | +| Installed commands | [`cli-tool.md`](../../spec/cli-tool.md) + `cli-tool.schema.json` | `crates/cli/src/tool.rs` | Tool v1 arrays/negotiation | +| C ABI | [`plugin-abi.md`](../../spec/plugin-abi.md) + C header | `marqdo-plugin-abi`, SDK | obsolete ABI major | +| Foreign kernels | [`foreign.md`](../../spec/foreign.md) wire v1 | `marqdo-foreign` (one-shot) | retired wire/versions | +| Resource providers | [`resource-provider-v2.md`](../../spec/resource-provider-v2.md) manifest v2 | CLI manifest validation + Host worker | retired manifests | +| Worker plumbing | [`worker-ipc.md`](../../spec/worker-ipc.md) (internal, no version) | `marqdo-worker-ipc` | private framing copies | +| Extension selection + lock | [`extension-selection.md`](../../spec/extension-selection.md), lock v4 | `marqdo-package` + CLI | lock v1–v3 readers/migrators | +| Values | [`value-wire.md`](../../spec/value-wire.md) | `marqdo-value::wire` | alternate encoders | + +A boundary may have **two root objects** of one contract (currently Observation +event and snapshot). Two root objects are not two protocols: they share one +event definition and one schema authority. + +## 3. Rules + +### 3.1 One current contract per boundary + +- One current format identifier, one producer, one validation path. +- No selection of a schema from project content, feature detection or runtime + state. +- No multi-version arrays, version ranges, "highest shared version", capability + probing or intersection negotiation. +- No simultaneous emission of an old and a new format, and no compatibility + adapter between two writers. + +### 3.2 Replace in place, in one integration + +- Change the producer, specification, JSON Schema, independent consumers, + fixtures and CI in the same change series. The intermediate commits on a + branch may be incomplete; a merged state may not contain two live paths. +- Delete the replaced implementation, spec and fixtures in that integration. + Git history and tagged archives are the archaeology; `spec/` is not. +- Keep the existing format identifier when the contract **shape** does not + change. Do not renumber formats for appearance, symmetry or "freshness" + (**no version bump without a shape change**). Conversely, when the shape + changes, an in-place replacement at the existing identifier is allowed + pre-stable and preferred over adding a parallel version. + +### 3.3 Reject, never migrate silently + +- Unsupported formats, versions, fields and command options fail with a + corrective action (for example "run `marqdo lock` to regenerate", "remove and + reinstall the tool"). +- No automatic upgrade of an old lock, tool record, manifest or machine output; + no field guessing; no fallback to a legacy reader; no "temporarily accept + both". +- Keep historical formats retrievable from Git and release tags, but do not let + the current binary read them. + +### 3.4 Never trade a safety invariant for convergence + +Removing a compatibility path must not remove integrity, authorization, type +checks, worker timeouts, size limits, secret handling or OS-isolation gates. +Convergence is about the fact model, not about relaxing it. When deleting code +that looks like "legacy compatibility", confirm first that it is not one of: + +- Analysis/Observation digest binding and source attribution; +- tool bundle hashing, entrypoint/path/symlink checks, command-conflict checks; +- plugin/provider artifact target/path/sha256 verification and native trust; +- capability grants, declared-vs-installed handler checks, budgets; +- strict mode fail-closed behavior and worker quarantine; +- Value Wire type fidelity and non-transferable handle rules. + +### 3.5 Preserve privacy when merging fact models + +A unified model must keep the strictest privacy default of the models it +replaces. Today value observation is off by default; selected names must be +declared; Text needs separate consent; Memory/Handle are never serialized. +Merging Trace into Observation never blesses Trace-era value exposure. + +## 4. Mandatory change procedure + +For any change to a public boundary, in order: + +1. **ADR.** Record the single target design, the boundary, the identifier + decision (keep or replace) and what is deleted. If an ADR is superseded, mark + its header Historical so no reader treats it as current. +2. **Specification in place.** Update the one current `spec/*.md` (never add a + parallel "v-next" current spec). Update the JSON Schema if one exists. + `spec/` must describe only what the current tree emits. +3. **One producer, one validator.** Delete the alternate selection logic, the + second writer, the legacy reader and their dead error paths in the same + series. `grep` is evidence: no `legacy`, `compat`, `schema_v2_or_v3`, + `shared_version`, version arrays or fallback branches may remain runnable. +4. **Fixtures and consumers.** Replace goldens with ones produced by the **real + CLI**, update the independent consumer(s), and add negative fixtures for the + retired input. Never weaken or delete a security/semantic negative test to + go green. +5. **CLI and docs.** Update `--help`, README, developer guides, examples and + release/smoke scripts. No alias for a retired option. +6. **Enforcement gate.** Add or keep a source-level check that the duplicate + cannot quietly return (see `architecture_boundaries` tests; for example the + shared worker transport test forbids reimplementing framing). +7. **Evidence.** Record the executed commands in `docs/STATUS.md` and an + evidence file with the exact SHA. A design document is not evidence. + +## 5. Anti-patterns — do not do these + +| Tempting move | Why it is rejected | Do instead | +|---|---|---| +| Keep v2 output for "simple" projects | Content-driven schema selection is the original bug | One writer, one identifier | +| Accept `analysis: [2,3]` and pick the intersection | Installs succeed when output is unreadable | One exact requirement, reject mismatch | +| Add `--legacy`, `compat`, `map_v1` or per-file switch | Reintroduces a second live architecture | Replace the current path; delete the old one | +| Keep the old writer behind a new "Unified" trait | Cosmetic abstraction over two fact models | One producer feeding all destinations | +| Rename `analysis-v3.md` to `analysis.md` only | Docs claim what code does not do | Update code, schema, fixtures, consumers together | +| Accept old lock/tool/extension silently | Hides a broken upgrade and loses integrity | Fail with an explicit regenerate/reinstall message | +| Delete security tests to make CI green | Convergence must not lower the bar | Keep/strengthen negatives | +| Renumber an unchanged format "to be safe" | Creates migration cost without a shape change | Keep the existing identifier | +| Add a second observation writer per destination | Two sources of truth for one execution | One event sequence, many destinations | +| Share worker capabilities with shared framing | Transport sharing is not authority sharing | Share framing only; keep grants per boundary | + +## 6. Review checklist + +A reviewer must be able to answer "yes" to all of these before approving a +protocol-boundary change: + +- [ ] Does this boundary still have exactly one current contract and one + producer/validator? +- [ ] Did the replaced spec/implementation/fixtures get deleted in this + integration (not scheduled "later")? +- [ ] Are retired inputs rejected with a corrective action, with no migrator, + alias, fallback or field guessing? +- [ ] Is the format identifier unchanged unless the contract shape changed? +- [ ] Do independent consumers and real-CLI fixtures validate the new artifact, + including at least one negative case? +- [ ] Are digest binding, attribution, grants, budgets, timeouts, size limits, + secret handling and strict-mode fail-closed behavior intact and tested? +- [ ] Does the privacy default stay structural, with explicit value/Text + consent? +- [ ] Are `--help`, README, developer docs, examples and release smoke updated + to the current contract only? +- [ ] Is there a source-level gate preventing the duplicate path from returning? +- [ ] Is the executed evidence recorded against a SHA (not a plan or a claim)? + +## 7. Definition of Done for a convergence change + +- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D + warnings`, `cargo test --workspace --locked` pass. +- `cargo test -p marqdo-cli --test architecture_boundaries --test + docs_consistency` pass. +- Independent consumers validate real CLI output; schema files parse; retired + options and formats are proven rejected. +- `spec/` contains no superseded current-contract document; retired ADRs carry a + Historical header; `docs/STATUS.md` names the executed evidence. +- The release archive smoke test is updated before an RC is tagged, and the RC + evidence is bound to the archive's SHA. + +## 8. Stable-release boundary + +Everything above applies **before the first stable release**. After the first +stable release a separate compatibility policy must define which contracts are +stabilized, the deprecation window and the upgrade rules. Do not import +post-stable compatibility obligations into the pre-stable tree, and do not +assume this policy authorizes breaking stable contracts later. + +## 9. Where the policy is enforced + +| Enforcement | Artifact | +|---|---| +| Absolute language/architecture rules | [`AGENTS.md`](../../AGENTS.md) | +| Public-contract decision | [ADR-0068](../adr/0068-single-current-public-contracts.md) | +| Architecture overview and boundary table | [`architecture/CURRENT.md`](CURRENT.md) | +| Normative contracts | `spec/*.md` + `spec/schemas/*.json` | +| Source-level boundary gates | `crates/cli/tests/architecture_boundaries.rs` | +| Docs/link/status gates | `crates/cli/tests/docs_consistency.rs` | +| Independent consumers | `tests/consumers/*.py` | +| Release evidence | [`STATUS.md`](../STATUS.md), `docs/evidence/`, `docs/releasing.md` | diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 5d99d6d..7fe60f4 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -5,6 +5,9 @@ Status: **index**. The single current architecture overview is input and evidence. It is not a second running-status page. - Current architecture and four state dimensions: [`CURRENT.md`](CURRENT.md). +- Public-contract convergence rules and review checklist: + [`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md) + ([ADR-0068](../adr/0068-single-current-public-contracts.md)). - **Current language contract:** [`RFC-LANG-0002-unified-semantics.md`](RFC-LANG-0002-unified-semantics.md), adopted by [ADR-0052](../adr/0052-unified-markdown-semantics.md) and @@ -21,7 +24,7 @@ input and evidence. It is not a second running-status page. |---|---|---| | [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. | | [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002. | -| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Adopted and implemented (P0/P1)** | Typed host observation, Execution Events v1 NDJSON, frame identity, selected bounded values; P2 memory metadata remains deferred. | +| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Historical: superseded by Observation (ADR-0068)** | Its event vocabulary and privacy model fed the current [Observation](../../spec/observation.md) contract; the Execution Events v1 name/options are retired. | | [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. | | [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. | | RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. | diff --git a/docs/contributor-guide.md b/docs/contributor-guide.md index e4588c5..2a4378d 100644 --- a/docs/contributor-guide.md +++ b/docs/contributor-guide.md @@ -24,6 +24,7 @@ marqdo-cli/ ├── docs/ │ ├── DEVELOPMENT_BLUEPRINT.md architecture baseline (language-mapping sections historical) │ ├── architecture/RFC-LANG-0002-unified-semantics.md current language authority +│ ├── architecture/PROTOCOL_CONVERGENCE_POLICY.md one-current-contract rules + review checklist │ ├── STABLE_RELEASE_IMPLEMENTATION.md authoritative next-phase/release plan │ ├── STATUS.md current evidence, work packages, blockers │ ├── migration/ syntax-migration rules + file inventory @@ -45,11 +46,13 @@ marqdo-cli/ │ ├── security.md modes, capabilities, budgets, trust │ ├── package-format.md marqdo.yaml / marqdo.lock / init │ ├── plugin-abi.md C ABI v1, SDK, host lifecycle +│ ├── worker-ipc.md shared persistent-worker framing/transport │ ├── math.md removed core math outlook + migration (ADR-0061) │ ├── foreign.md Python/Node kernel protocol │ ├── cli-tool.md external command registration and dispatch │ ├── analysis.md current static projection -│ └── observation.md live events and snapshots +│ ├── observation.md live events and snapshots +│ └── cli-tool.md external command registration and dispatch ├── crates/ │ ├── marqdo-span/ Span, LineCol, LineIndex (leaf) │ ├── marqdo-value/ Value, diagnostics, errors, wire encoding From 867cd72cedecbbe50a1bb98bcad95f54b4308ee8 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:04:27 +0800 Subject: [PATCH 07/17] docs: remove retired protocol names from current guides --- README.md | 2 +- docs/developers/README.md | 15 ++--- docs/developers/release-limits.md | 8 +-- docs/developers/tools.md | 99 +++++++++++++++++-------------- docs/releasing.md | 4 +- 5 files changed, 70 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 2404f1e..5b25cf9 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ release policy. > [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 diff --git a/docs/developers/README.md b/docs/developers/README.md index ad11e2c..eea4376 100644 --- a/docs/developers/README.md +++ b/docs/developers/README.md @@ -7,16 +7,17 @@ core checkout, or host memory layout. Adding a new domain function must not require a core commit. Product version for these docs: **`3.0.0-rc.2`** (Linux x86_64 candidate). -Protocol versions are independent: Analysis v2, Trace v2, Execution Events v1, -Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4, -markdown profile `marqdo.md.v1`. +Current protocol contracts: Analysis, Observation, CLI Tool, Plugin ABI v1, +Foreign wire v1, Provider manifest v2, lock v4 and markdown profile +`marqdo.md.v1`. Product, protocol and package versions are independent; see +[compatibility.md](compatibility.md). ## Pick your entry point | Goal | Use | Deliverable | |---|---|---| | AI/math/data/quantum/SKILL libraries, pure algorithms | `.mq.md` package | `index.mq.md`, `marqdo.yaml`, README, tests | -| Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool Protocol v1 | standalone executable + `tool.json` + Analysis/Trace consumer | +| Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool protocol | standalone executable + `tool.json` + Analysis/Observation consumer | | High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, SDK/header | | New foreign language backend (R/Python/Julia/…) | Foreign Kernel | `kernel.json`, executable provider, pinned environment | | Hardware/device/external-stream resources | Resource Provider v2 | `provider.json`, C ABI library, worker helper | @@ -28,12 +29,12 @@ markdown profile `marqdo.md.v1`. project. 2. [libraries.md](libraries.md) — publish a pure `.mq.md` library and consume it through a pinned Git dependency. -3. [tools.md](tools.md) — build an external Tool that consumes Analysis v2 and - Trace v2. +3. [tools.md](tools.md) — build an external Tool that consumes the current + Analysis and Observation contracts. 4. [extensions.md](extensions.md) — plugins, foreign kernels, resource providers, extension selection and lock v4. 5. [analysis-observation.md](analysis-observation.md) — the public static/dynamic data - contracts, Execution Events v1 and digest binding. + contracts and digest binding. 6. [compatibility.md](compatibility.md) — version axes, platform matrix and the prerelease policy. 7. [release-limits.md](release-limits.md) — the honest beta limitations (this diff --git a/docs/developers/release-limits.md b/docs/developers/release-limits.md index 3ca0437..5956136 100644 --- a/docs/developers/release-limits.md +++ b/docs/developers/release-limits.md @@ -57,10 +57,10 @@ Even when available: ## Compatibility and versioning -* `3.0.0-rc.2` is a **prerelease**. The changelog lists changes from the beta. -* The product version is independent of protocol versions: Analysis v2, Trace - v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider - manifest v2 and lock v4 keep their own major numbers. +* `3.0.0-rc.3` is a **prerelease**. The changelog lists changes from the beta. +* The product version is independent of protocol versions: Analysis, + Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2 + and lock v4 keep their own identifiers. * The official bundled stdlib keeps its independent package version `0.1.0`. A plugin `.mq.md` package version such as `0.1.0` is also independent. * `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer diff --git a/docs/developers/tools.md b/docs/developers/tools.md index a3b693a..c2f9dc8 100644 --- a/docs/developers/tools.md +++ b/docs/developers/tools.md @@ -1,12 +1,12 @@ -# External tools: CLI Tool Protocol v1 +# External tools: current CLI Tool protocol The core does not contain `view`, `knowledge`, `prove`, `lint` or any other product command. A tool is a **separate executable** registered by the user; the CLI only dispatches unknown top-level commands to registered tools and never scans `PATH` for a guessed name. -Normative contract: [`../../spec/cli-tool.md`](../../spec/cli-tool.md) -(implemented and frozen for protocol v1). +Normative contract: [`../../spec/cli-tool.md`](../../spec/cli-tool.md) and +[`../../spec/schemas/cli-tool.schema.json`](../../spec/schemas/cli-tool.schema.json). ## 1. Package layout @@ -20,7 +20,7 @@ marqdo-view/ examples/ ``` -`tool.json` for the `3.0.0-rc.2` candidate: +`tool.json` for the `3.0.0-rc.3` candidate: ```json { @@ -30,22 +30,19 @@ marqdo-view/ "version": "0.1.0", "command": "view", "entrypoint": "bin/marqdo-view", - "compatibility": { - "marqdo": ">=3.0.0-beta.1,<4.0.0", - "analysis": [2], - "trace": [2] - } + "requires": {"api_revision": 1, "analysis": 3, "observation": 1} } ``` -- `version` is the **tool's** SemVer. -- `compatibility.marqdo` is the **core product** range. A stable-only - `>=3.0.0,<4.0.0` does not match a beta core; opt in explicitly. The CLI - rejects a mismatched range at install and dispatch time with a - `requires marqdo …` diagnostic. -- `analysis`/`trace` are declared only if the tool consumes them; the current - development branch provides Analysis v2/v3 and Trace v2. Declare - `analysis: [2, 3]` when the reader handles both versions. +- `version` is the **tool's** SemVer. It identifies the artifact; it does not + promise compatibility with retired core protocols. +- `requires.api_revision` is required and must equal the current core revision. +- `requires.analysis` and `requires.observation` are optional. Declare one only + when the tool consumes that contract, and declare it as a **single exact + integer**; arrays, ranges and "highest shared version" negotiation do not + exist. +- A mismatched requirement fails install and dispatch with + `tool.protocol_incompatible`; there is no negotiation and no fallback. - `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`, `remove`, `lock`, `sync`, `tool`, `help`). @@ -72,11 +69,13 @@ The tool receives: | Variable | Meaning | |---|---| | `MARQDO_BIN` | absolute path of the running `marqdo` executable | -| `MARQDO_TOOL_PROTOCOL` | `1` | -| `MARQDO_PROTOCOL_ANALYSIS` | Highest shared Analysis version. Read the artifact envelope for its actual version. | -| `MARQDO_PROTOCOL_TRACE` | `2` when Trace v2 was negotiated | +| `MARQDO_API_REVISION` | the single current tool API revision (`1`) | Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`. +The retired `MARQDO_TOOL_PROTOCOL`, `MARQDO_PROTOCOL_ANALYSIS` and +`MARQDO_PROTOCOL_TRACE` variables are not exported: version selection is not +negotiated. A registration written by a retired manifest/record format is +rejected with a "remove and reinstall" diagnostic and is never rewritten. ## 3. Consume the public protocols @@ -86,28 +85,37 @@ Static input (View/Knowledge/Proof): "$MARQDO_BIN" check index.mq.md --refs --emit ./analysis.json ``` -Dynamic input: +Dynamic input uses the single Observation contract. The same run can deliver +the event stream on stdout and an atomic JSON snapshot in one invocation: ```bash -"$MARQDO_BIN" run index.mq.md --trace-file ./trace.json +# live JSONL events +"$MARQDO_BIN" run index.mq.md --output jsonl +"$MARQDO_BIN" call index.mq.md main --arg n=5 --output jsonl + +# one JSON snapshot, from the same execution +"$MARQDO_BIN" run index.mq.md --output json --observation-file ./observation.json + +# both destinations, still one execution +"$MARQDO_BIN" call index.mq.md main --arg n=5 --output jsonl \ + --observation-file ./observation.json ``` -Live dynamic input (Execution Events v1): +Consume the stdout line stream as NDJSON; do not pass another `--output` in the +same invocation. Every event carries `schema: "marqdo.observation"` and +`schema_version: 1`; read `stream.opened` for the capture policy and reject any +other format identifier. The JSON snapshot wraps the same events, so a consumer +must not treat it as a second protocol or renumber them. A tool server may +convert the stream to its own SSE/websocket transport; the CLI never implements +HTTP/SSE. Live and file destinations are rejected under `--mode strict` in the +current tree; the tool must surface that refusal instead of pretending +real-time support. The retired `--json`, `--trace-file` and `--event-stream` +options are rejected, not aliased. -```bash -"$MARQDO_BIN" run index.mq.md --event-stream jsonl -"$MARQDO_BIN" call index.mq.md main --arg n=5 --event-stream jsonl -``` - -Consume the stdout line stream as NDJSON; do not pass `--json` in the same -invocation. Negotiate by reading `stream.opened` (`marqdo.execution-events`, -`schema_version: 1`) and reject unknown majors. A tool server may convert the -stream to its own SSE/websocket transport; the CLI never implements HTTP/SSE. -This option is unavailable under `--mode strict` in the current tree and the -tool must surface that refusal instead of pretending real-time support. - -See [analysis-observation.md](analysis-observation.md) for fields and digest rules. Do not -depend on `inspect --ir`: that JSON is not a frozen cross-repository protocol. +See [analysis-observation.md](analysis-observation.md) for fields and digest rules. A +consumer must verify the exact Analysis bytes (SHA-256) and each module source +digest before attributing a span. Do not depend on `inspect --ir`: that JSON is +not a frozen cross-repository protocol. The `view` tool renders the **original Markdown**, not the Analysis JSON; the Analysis is an index, not a replacement for the source text. @@ -122,13 +130,16 @@ Checksums verify bundle integrity only; they are not publisher authentication. - Test against a **frozen** `marqdo` binary: hash it before/after the suite and fail if it changes. -- Cover the negative paths: unknown schema major, incompatible `marqdo` range, - reserved command, traversal/symlink entrypoint, tampered bundle file, missing - entrypoint, tool crash/exit-status propagation. -- Match a real Analysis v2/Trace v2 schema (`spec/schemas/`) and check - `source.analysis_digest`. -- Include README, minimal example, supported CLI product range, protocol - versions, platform matrix, reproducible artifact hashes and limitations. +- Cover the negative paths: unknown schema/schema_version, incompatible + `api_revision`/`analysis`/`observation` requirement, array requirements, + retired record format, reserved command, traversal/symlink entrypoint, + tampered bundle file, missing entrypoint, tool crash/exit-status propagation. +- Validate against the current Analysis and Observation schemas + (`spec/schemas/`) and check `source.analysis_digest` plus the module source + digest before using event spans. +- Include README, minimal example, supported CLI product range, the exact + protocol requirements, platform matrix, reproducible artifact hashes and + limitations. - The archive ships `examples/tool-samples/{sample-view,sample-knowledge,sample-proof}` as independent source examples and `examples/tool-unknown-name/` as a runnable dispatch fixture. diff --git a/docs/releasing.md b/docs/releasing.md index 14c57bc..efb57f3 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -57,7 +57,7 @@ requires re-running every gate. On that SHA: environment and limits; the 9 correctness workloads must still pass. Never report TCG/QEMU or development-container timings as G4. 8. `README`, `CHANGELOG`, `COMPATIBILITY`, `docs/STATUS`, this file, - `spec/tool-v1.md`, `spec/plugin-abi.md` and the developer docs are on the + `spec/cli-tool.md`, `spec/plugin-abi.md` and the developer docs are on the same fact baseline. No "implemented but says Proposed", no "released but says DO NOT RELEASE", no product/protocol/package version confusion. 9. Every shipped binary was actually built and smoke-tested on its claimed @@ -150,7 +150,7 @@ python3 tools/release/smoke.py \ It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib digests against `stdlib/stdlib.json` and the staged tree, offline -`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2/v3 and Trace v2 +`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis and Observation consumers, Tool install/dispatch, native + worker plugin transports, a foreign kernel, Resource Provider v2 through the shipped worker (positive, unauthorized and missing-helper fail-closed), the pure math package and optional From ca0f0799e737afbb6565647adbe8aa6912fed72b Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:05:38 +0800 Subject: [PATCH 08/17] ext: reject retired descriptor revisions without migration --- crates/cli/tests/extension_selection.rs | 56 +++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/crates/cli/tests/extension_selection.rs b/crates/cli/tests/extension_selection.rs index 9eaf69a..3537f09 100644 --- a/crates/cli/tests/extension_selection.rs +++ b/crates/cli/tests/extension_selection.rs @@ -493,3 +493,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) + ); +} From 291e521cec2be20ae03832d104cc37284122cdd0 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:12:51 +0800 Subject: [PATCH 09/17] release: prepare 3.0.0-rc.3 with the converged contracts --- CHANGELOG.md | 79 +++++++++++++++++++++++++++++-- COMPATIBILITY.md | 6 +-- Cargo.lock | 32 ++++++------- Cargo.toml | 2 +- README.md | 2 +- docs/STATUS.md | 46 +++++++++++++++++- docs/developers/README.md | 2 +- docs/developers/compatibility.md | 4 +- docs/developers/quickstart.md | 10 ++-- docs/developers/release-limits.md | 2 +- spec/analysis.md | 8 ++-- spec/security.md | 2 +- tools/release/package.py | 2 +- tools/release/smoke.py | 4 +- 14 files changed, 158 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d841134..ffe4d88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,81 @@ All notable changes to the Marqdo CLI workspace. Product version `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. +changes. Current protocol contracts are Analysis, Observation, CLI Tool, +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. + +## 3.0.0-rc.3 (candidate) + +- 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. + +### 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` and `--event-stream` options are rejected. +- **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. + +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. +- Release evidence for publication still requires the same-SHA CI pipeline and + archive smoke described in [`docs/releasing.md`](docs/releasing.md). ## 3.0.0-rc.2 (candidate) diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index d57db89..11b62d4 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -8,7 +8,7 @@ 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). -The `3.0.0-rc.2` candidate targets Linux x86_64 on glibc 2.39 and +The `3.0.0-rc.3` candidate targets Linux x86_64 on glibc 2.39 and includes the post-beta changes below. See the [RC acceptance procedure](docs/releasing.md). The platform evidence table records the beta and subsequent development verification. @@ -51,7 +51,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.3` 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). @@ -86,7 +86,7 @@ that tool. | 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.3` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. | | `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. | diff --git a/Cargo.lock b/Cargo.lock index 39c2a2f..e98b14d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "marqdo-cli" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "clap", "hex", @@ -438,7 +438,7 @@ dependencies = [ [[package]] name = "marqdo-expression" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-span", "num-bigint", @@ -449,7 +449,7 @@ dependencies = [ [[package]] name = "marqdo-foreign" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "hex", "libc", @@ -465,7 +465,7 @@ dependencies = [ [[package]] name = "marqdo-frontend" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-expression", "marqdo-ir", @@ -480,7 +480,7 @@ dependencies = [ [[package]] name = "marqdo-host" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "flate2", "getrandom 0.4.3", @@ -505,7 +505,7 @@ dependencies = [ [[package]] name = "marqdo-ir" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-expression", "marqdo-span", @@ -515,7 +515,7 @@ dependencies = [ [[package]] name = "marqdo-markdown" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "comrak", "marqdo-span", @@ -526,7 +526,7 @@ dependencies = [ [[package]] name = "marqdo-package" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "hex", "semver", @@ -540,7 +540,7 @@ dependencies = [ [[package]] name = "marqdo-plugin-abi" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "hex", "libloading", @@ -556,7 +556,7 @@ dependencies = [ [[package]] name = "marqdo-plugin-sdk" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-plugin-abi", "serde", @@ -565,7 +565,7 @@ dependencies = [ [[package]] name = "marqdo-provider-worker" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "libloading", "marqdo-host", @@ -578,7 +578,7 @@ dependencies = [ [[package]] name = "marqdo-runtime" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-expression", "marqdo-frontend", @@ -597,7 +597,7 @@ dependencies = [ [[package]] name = "marqdo-sandbox" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "libc", "serde", @@ -605,14 +605,14 @@ dependencies = [ [[package]] name = "marqdo-span" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "serde", ] [[package]] name = "marqdo-value" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "marqdo-span", "num-bigint", @@ -623,7 +623,7 @@ dependencies = [ [[package]] name = "marqdo-worker-ipc" -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" dependencies = [ "serde_json", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index b9c7be5..42dac65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ members = [ ] [workspace.package] -version = "3.0.0-rc.2" +version = "3.0.0-rc.3" edition = "2021" rust-version = "1.89" license = "Apache-2.0" diff --git a/README.md b/README.md index 5b25cf9..fe62883 100644 --- a/README.md +++ b/README.md @@ -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.3`** 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 diff --git a/docs/STATUS.md b/docs/STATUS.md index f28bd75..0f59cc9 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -26,7 +26,7 @@ as current status. ## RC candidate -The workspace reports `3.0.0-rc.2` and declares Rust 1.89 as its locked +The workspace reports `3.0.0-rc.3` and declares Rust 1.89 as its locked minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The [release procedure](releasing.md) requires a green manifest bound to the candidate SHA before publication. The release record below refers to the @@ -68,6 +68,50 @@ The `spec/` tree contains only current contracts; retired specifications are in Git history and tagged archives. The earlier release records below describe their tagged binaries and are not current protocol claims. +## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate) + +The current tree replaces the retired protocols in place, with no compatibility +path. Policy: [ADR-0068](adr/0068-single-current-public-contracts.md) and +[the convergence policy](architecture/PROTOCOL_CONVERGENCE_POLICY.md). This +section records commands executed on the candidate tree; it is local Linux +evidence, not a same-SHA CI or archive gate. + +Executed 2026-11-24 on Linux x86_64 (workspace `3.0.0-rc.3`, Rust 1.93.1): + +```text +cargo fmt --all -- --check PASS +cargo clippy --workspace --all-targets -- -D warnings PASS +cargo test --workspace --locked PASS: 601 passed, 0 failed, 2 ignored +cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed +cargo test -p marqdo-cli --test docs_consistency PASS: 5 passed +cargo test -p marqdo-cli --test observation PASS: 15 passed +cargo test -p marqdo-cli --test analysis_observation PASS: 10 passed +cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed +cargo test -p marqdo-cli --test extension_selection PASS: 14 passed +cargo test -p marqdo-worker-ipc PASS: 5 passed +``` + +Black-box consumer run against the real `target/debug/marqdo`: + +```text +check examples/multi-module/index.mq.md --refs --emit analysis.json schema marqdo.analysis/3 +run examples/multi-module/index.mq.md --observation-file snap.json schema marqdo.observation/1 +validate_protocols.py analysis.json snap.json tool.json PASS (7 modules, 333 events) +analysis_consumer.py analysis.json PASS (32 functions) +observation_consumer.py --snapshot snap.json --analysis analysis.json PASS +check tests/conformance/semantics/85-nested-loop-control.mq.md PASS +run ... --output jsonl --observation-file snapshot 66 events +observation_consumer.py stream.jsonl --validate-schema PASS (3 transfers) +snapshot["events"] == stream lines PASS +observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected +marqdo --version marqdo 3.0.0-rc.3 +``` + +Release status: the tree and developer inputs are ready for `3.0.0-rc.3`, but +publication still requires the same-SHA CI pipeline plus archive/clean-install +smoke bound to that SHA, as required by [`releasing.md`](releasing.md). Do not +tag or publish from this local evidence alone. + ## 0. Beta release record — `3.0.0-beta.1` ### 0.1 Product, version axes and scope diff --git a/docs/developers/README.md b/docs/developers/README.md index eea4376..83869a0 100644 --- a/docs/developers/README.md +++ b/docs/developers/README.md @@ -6,7 +6,7 @@ Rust structures, `marqdo-ir` internals, `inspect --ir`, relative paths into the core checkout, or host memory layout. Adding a new domain function must not require a core commit. -Product version for these docs: **`3.0.0-rc.2`** (Linux x86_64 candidate). +Product version for these docs: **`3.0.0-rc.3`** (Linux x86_64 candidate). Current protocol contracts: Analysis, Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4 and markdown profile `marqdo.md.v1`. Product, protocol and package versions are independent; see diff --git a/docs/developers/compatibility.md b/docs/developers/compatibility.md index 4ba55d6..5694c5b 100644 --- a/docs/developers/compatibility.md +++ b/docs/developers/compatibility.md @@ -6,7 +6,7 @@ This page summarizes the public support policy. The authoritative matrix is ## Version axes (do not conflate) -| Axis | `3.0.0-rc.2` value | Change rule | +| Axis | `3.0.0-rc.3` value | Change rule | |---|---|---| | Product / CLI | `3.0.0-rc.2` | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. | | Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. | @@ -42,7 +42,7 @@ grant, values are off by default, and `--mode strict` currently refuses ## Language compatibility -`3.0.0-rc.2` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source +`3.0.0-rc.3` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source (Strong-execute / Emph-return / ordered-list branch / bullet-list loop / block-quote call / first code-span signature) is **not executable**; there is no `--legacy`, syntax switch or downgrade path. Migration is a rewrite task diff --git a/docs/developers/quickstart.md b/docs/developers/quickstart.md index e3820af..da633c0 100644 --- a/docs/developers/quickstart.md +++ b/docs/developers/quickstart.md @@ -1,15 +1,15 @@ # Quickstart: install and run -Product: `3.0.0-rc.2` (Linux x86_64 candidate). Install a **release archive**, not +Product: `3.0.0-rc.3` (Linux x86_64 candidate). Install a **release archive**, not a source checkout, when you only consume Marqdo. ## 1. Install the archive ```bash -sha256sum -c marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz.sha256 -tar -xzf marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz -cd marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu -./marqdo --version # marqdo 3.0.0-rc.2 +sha256sum -c marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz.sha256 +tar -xzf marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz +cd marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu +./marqdo --version # marqdo 3.0.0-rc.3 ./marqdo --help ``` diff --git a/docs/developers/release-limits.md b/docs/developers/release-limits.md index 5956136..20334ae 100644 --- a/docs/developers/release-limits.md +++ b/docs/developers/release-limits.md @@ -1,4 +1,4 @@ -# Marqdo 3.0.0-rc.2 — known limitations +# Marqdo 3.0.0-rc.3 — known limitations This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of the release record: it defines the platform and feature scope for the release candidate. diff --git a/spec/analysis.md b/spec/analysis.md index 83d8f0a..0b5fbbd 100644 --- a/spec/analysis.md +++ b/spec/analysis.md @@ -58,7 +58,7 @@ this load: declared version, content digest and package instance id. It is an Analysis artifact can only name a bundle whose bytes matched the manifest. `AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written -by `check --emit` (pretty JSON). This is what Trace v2 binds to +by `check --emit` (pretty JSON). This is what Observation binds to `source.analysis_digest`; an independent consumer can verify it by hashing the file. Diagnostics and any configuration options that change the projection are part of that digest. @@ -121,9 +121,9 @@ never allocates a region or executes the write. ## 4. Resources -`resources` is an array, not a count. v2 projects exactly the two resource -kinds represented by `marqdo-ir::Resource`; it does not invent table, HTML or -link resources. +`resources` is an array, not a count. The projection includes exactly the +resource kinds represented by `marqdo-ir::Resource`; it does not invent table, +HTML or link resources. ```json { diff --git a/spec/security.md b/spec/security.md index 20017d1..12bb625 100644 --- a/spec/security.md +++ b/spec/security.md @@ -1,6 +1,6 @@ # Marqdo Security Model (implemented status) -Status: describes enforcement in the `3.0.0-rc.2` candidate. +Status: describes enforcement in the `3.0.0-rc.3` candidate. Normative implementation: diff --git a/tools/release/package.py b/tools/release/package.py index f646c78..b73c241 100644 --- a/tools/release/package.py +++ b/tools/release/package.py @@ -16,7 +16,7 @@ Usage (from the repository root, after python3 tools/release/package.py \ --source-sha "$(git rev-parse HEAD)" \ - --version 3.0.0-rc.2 + --version 3.0.0-rc.3 """ from __future__ import annotations diff --git a/tools/release/smoke.py b/tools/release/smoke.py index 668149a..6bc70c9 100644 --- a/tools/release/smoke.py +++ b/tools/release/smoke.py @@ -3,13 +3,13 @@ Extracts the archive into a fresh temporary directory and exercises the shipped binaries only (never the development source tree): version/help, check/run/call, -lock/sync for a path dependency, Analysis v2/v3 and Trace v2 consumers, Tool +lock/sync for a path dependency, Analysis and Observation consumers, Tool install/dispatch, native and worker plugin transports, foreign kernel, the Provider v2 worker (positive, unauthorized and missing-helper fail-closed), and strict mode when the host genuinely supports it. Usage: - python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz + python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz """ from __future__ import annotations From 93fada3d92a0200d9b1c60085a3c71a71e7195c7 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:16:05 +0800 Subject: [PATCH 10/17] evidence: record the rc.3 local protocol-convergence gate --- docs/STATUS.md | 12 ++-- ...6-11-24-rc.3-protocol-convergence-local.md | 67 +++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md diff --git a/docs/STATUS.md b/docs/STATUS.md index 0f59cc9..97294bd 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -107,10 +107,14 @@ observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected marqdo --version marqdo 3.0.0-rc.3 ``` -Release status: the tree and developer inputs are ready for `3.0.0-rc.3`, but -publication still requires the same-SHA CI pipeline plus archive/clean-install -smoke bound to that SHA, as required by [`releasing.md`](releasing.md). Do not -tag or publish from this local evidence alone. +Release status: the tree and developer inputs are ready for `3.0.0-rc.3`. The +built archive (source `291e521c`, sha256 `8a663dee…`) passed the from-archive +smoke; the local evidence is +[`evidence/2026-11-24-rc.3-protocol-convergence-local.md`](evidence/2026-11-24-rc.3-protocol-convergence-local.md). +Publication still requires the same-SHA CI pipeline plus the clean-install +container gate bound to that SHA, as required by +[`releasing.md`](releasing.md). Do not tag or publish from local evidence +alone. ## 0. Beta release record — `3.0.0-beta.1` diff --git a/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md b/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md new file mode 100644 index 0000000..d6e54a6 --- /dev/null +++ b/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md @@ -0,0 +1,67 @@ +# RC.3 protocol-convergence gate — local Linux evidence + +Date: 2026-11-24. Product: `3.0.0-rc.3` (candidate). Source SHA: +`291e521cec2be20ae03832d104cc37284122cdd0` (the release-preparation commit). +Platform: Linux x86_64, glibc 2.39, Rust 1.93.1. Profile: **local gate only**. + +This records commands actually executed for +[issue #8](https://git.cflmy.cn/cflmy/marqdo-cli/issues/8) / +[ADR-0068](../adr/0068-single-current-public-contracts.md). It is **not** a +same-SHA CI or clean-install release claim: [`releasing.md`](../releasing.md) +still requires the remote pipeline and archive/clean-install evidence bound to +the tagged SHA before publication. Do not tag or publish from this file alone. + +## Gate results + +```text +cargo fmt --all -- --check PASS +cargo clippy --workspace --all-targets -- -D warnings PASS +cargo test --workspace --locked PASS: 601 passed, 0 failed, 2 ignored +cargo test -p marqdo-cli --test architecture_boundaries PASS: 12 passed +cargo test -p marqdo-cli --test docs_consistency PASS: 5 passed +cargo test -p marqdo-cli --test observation PASS: 15 passed +cargo test -p marqdo-cli --test analysis_observation PASS: 10 passed +cargo test -p marqdo-cli --test tool_protocol PASS: 7 passed +cargo test -p marqdo-cli --test extension_selection PASS: 14 passed +cargo test -p marqdo-worker-ipc PASS: 5 passed +``` + +Independent consumers against the real debug binary (not fixtures): + +```text +validate_protocols.py analysis.json snapshot.json tool.json PASS (7 modules, 333 events) +analysis_consumer.py analysis.json PASS (32 functions) +observation_consumer.py --snapshot ... --analysis ... PASS +control-flow fixture: 66 events, 3 transfers +stream JSONL == snapshot events PASS +source digest mismatch (stale Analysis) rejected +marqdo --version marqdo 3.0.0-rc.3 +``` + +## Release archive + +Built with `python3 tools/release/package.py --source-sha +291e521cec2be20ae03832d104cc37284122cdd0 --version 3.0.0-rc.3` after +`cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker`. + +```text +archive marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz +archive sha256 8a663dee0006742d6b1364380a62e54915a0ead56fa91a1dd3c1f64a2c16fc8b +archive size 5003180 bytes +source SHA 291e521cec2be20ae03832d104cc37284122cdd0 +``` + +`python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz` +PASSED from the extracted archive only, including stdlib digest verification, +Analysis/Observation consumers, Tool install/dispatch, plugin and provider +worker paths, foreign kernel, strict fail-closed refusal on this host, and the +"bundled stdlib missing -> fail-closed" case. + +## What is still required before publishing + +1. Push `architecture/issue-8-protocols`, run the same-SHA CI pipeline + (`fmt`/`clippy`/workspace tests plus the schema/consumer and + frozen-extension jobs), and record the evidence aggregate. +2. Run the clean-install container gate against the archive bytes. +3. Tag `v3.0.0-rc.3` at the evidenced SHA and publish the archive, checksum and + release notes. Local evidence cannot be promoted to a remote claim. From 09ab131b9698f6b387dcf0d6e85a48ff4c7270ce Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:37:49 +0800 Subject: [PATCH 11/17] ci: exercise only the current Analysis and Observation contracts --- .woodpecker/main.yml | 45 ++++++++++++++++++++-------- crates/cli/tests/docs_consistency.rs | 25 ++++++++++++++++ 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 5891b37..2a685ca 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -15,20 +15,39 @@ steps: - apt-get install -y --no-install-recommends nodejs - cargo fmt --all -- --check - cargo clippy --workspace --all-targets -- -D warnings - # The provider CLI tests resolve a real provider worker next to the CLI - # binary. Build it once so the test harness does not need a nested build. - - cargo build --locked -p marqdo-provider-worker + # Provider CLI tests resolve a real provider worker next to the CLI + # binary; both binaries are also used by the black-box gates below. + - cargo build --locked -p marqdo-cli -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 + # Observation black-box contract: one real execution feeds the JSONL + # stream and the JSON snapshot, and an independent consumer validates both. + - ./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json + - ./target/debug/marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl --observation-file /tmp/observation.json > /tmp/observation.jsonl + - python3 tests/consumers/analysis_consumer.py /tmp/analysis.json + - python3 tests/consumers/observation_consumer.py /tmp/observation.jsonl --validate-schema + - python3 tests/consumers/observation_consumer.py --snapshot /tmp/observation.json --analysis /tmp/analysis.json + - ./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md --emit /tmp/control-analysis.json + - ./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md --output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl + - python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-observation.json examples/tool-unknown-name/tool.json + - python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers + - python3 tests/consumers/observation_consumer.py --snapshot /tmp/control-observation.json --analysis /tmp/control-analysis.json + - python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl --analysis /tmp/control-analysis.json --validate-schema + - | + set -eu + python3 - <<'PY' + import json, pathlib + events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()] + snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_text()) + assert snapshot["events"] == events, "stream and snapshot must be one event sequence" + PY + - | + set -eu + cp /tmp/control-analysis.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 + echo "stale Analysis was accepted" >&2 + exit 1 + fi - 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" diff --git a/crates/cli/tests/docs_consistency.rs b/crates/cli/tests/docs_consistency.rs index 2a44c30..9928878 100644 --- a/crates/cli/tests/docs_consistency.rs +++ b/crates/cli/tests/docs_consistency.rs @@ -202,3 +202,28 @@ 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"] { + 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}`" + ); + } + } +} From 4f3a9bff298bb5ecfbb9a73388c6672b4b53fc1c Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:40:54 +0800 Subject: [PATCH 12/17] docs: describe the current CI protocol gates --- crates/cli/tests/docs_consistency.rs | 6 +++++- docs/ci.md | 18 ++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/cli/tests/docs_consistency.rs b/crates/cli/tests/docs_consistency.rs index 9928878..147830a 100644 --- a/crates/cli/tests/docs_consistency.rs +++ b/crates/cli/tests/docs_consistency.rs @@ -209,7 +209,11 @@ fn has_hex_sha(text: &str) -> bool { #[test] fn ci_configuration_uses_only_current_protocols() { let root = repo_root(); - for relative in [".woodpecker/main.yml", ".github/workflows/ci.yml"] { + for relative in [ + ".woodpecker/main.yml", + ".github/workflows/ci.yml", + "docs/ci.md", + ] { let text = read(&root.join(relative)); for retired in [ "--event-stream", diff --git a/docs/ci.md b/docs/ci.md index 10d567d..12c2666 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -19,12 +19,14 @@ test: apt install curl/ca-certificates/python3/python3-jsonschema + Node.js 22 cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings - cargo build --locked -p marqdo-provider-worker + cargo build --locked -p marqdo-cli -p marqdo-provider-worker cargo test --workspace --locked - cargo run --locked -p marqdo-cli -- run \ - tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl \ - > /tmp/execution-events.jsonl - python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl + check + run tests/consumers/fixtures/observation/basic.mq.md + analysis_consumer.py / observation_consumer.py (stream + snapshot) + check + run the nested-loop control-flow conformance fixture + validate_protocols.py / analysis_consumer.py --require-transfers + observation_consumer.py (stream, snapshot, stale-Analysis rejection) + stream JSONL == snapshot events assertion cargo test -p marqdo-cli --test docs_consistency cargo test -p marqdo-cli --test architecture_boundaries cargo test -p marqdo-cli --test stdlib_product @@ -34,9 +36,13 @@ test: build (depends on test): cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - package + cold-install smoke (which now validates live Execution Events v1) + package + cold-install smoke (current Analysis/Observation contracts) ``` +The pipeline is a protocol consumer itself: it must exercise only the current +Analysis and Observation contracts. `docs_consistency::ci_configuration_uses_only_current_protocols` +fails if a retired option or consumer name returns. + Node.js 22 is required because the optional foreign-kernel tests use ES-module syntax; Debian bookworm's Node 18 fails those tests. From 33b73f41e38fea8b3cd4555044ca8a93230b6d3b Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 17:49:24 +0800 Subject: [PATCH 13/17] consumers: resolve the event schema on jsonschema before 4.18 --- tests/consumers/validate_protocols.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/tests/consumers/validate_protocols.py b/tests/consumers/validate_protocols.py index 9add902..f509729 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -10,7 +10,15 @@ import pathlib import sys from jsonschema import Draft202012Validator -from referencing import Registry, Resource + +try: + # jsonschema >= 4.18 resolves the external event schema through + # `referencing`. The CI image may ship an older jsonschema, so keep the + # standard resolver fallback: the public consumer must run on both. + from referencing import Registry, Resource +except ImportError: # pragma: no cover - exercised by the compatibility shim + Registry = None + Resource = None ROOT = pathlib.Path(__file__).resolve().parents[2] SCHEMA_DIR = ROOT / "spec" / "schemas" @@ -23,10 +31,23 @@ def load_schema(name): return schema +EVENT_SCHEMA_ID = "https://marqdo.dev/schemas/observation-event.schema.json" + + def validator(schema): event = load_schema("observation-event.schema.json") - registry = Registry().with_resource(event["$id"], Resource.from_contents(event)) - return Draft202012Validator(schema, registry=registry) + if Registry is not None: + registry = Registry().with_resource(EVENT_SCHEMA_ID, Resource.from_contents(event)) + return Draft202012Validator(schema, registry=registry) + # jsonschema < 4.18 (Debian bookworm's python3-jsonschema). + from jsonschema import RefResolver + + store = { + EVENT_SCHEMA_ID: event, + "observation-event.schema.json": event, + } + resolver = RefResolver.from_schema(schema, store=store) + return Draft202012Validator(schema, resolver=resolver) def require_valid(schema_name, document, label): From 6b509d344ea9768a7894c92429c7904ac881d80a Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 18:18:35 +0800 Subject: [PATCH 14/17] ci: split a fast contract lane from the full Rust lane --- .woodpecker/main.yml | 77 ++++++++++++++++++++++++++------------------ 1 file changed, 45 insertions(+), 32 deletions(-) diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 2a685ca..b6c7d65 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -5,6 +5,48 @@ 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 python3 python3-jsonschema + - cargo build --locked -p marqdo-cli -p marqdo-provider-worker + - | + set -euxo pipefail + ./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json + ./target/debug/marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl --observation-file /tmp/observation.json > /tmp/observation.jsonl + python3 tests/consumers/analysis_consumer.py /tmp/analysis.json + python3 tests/consumers/observation_consumer.py --validate-schema /tmp/observation.jsonl + python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/analysis.json /tmp/observation.json + ./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md --emit /tmp/control-analysis.json + ./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md --output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl + python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-observation.json examples/tool-unknown-name/tool.json + python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers + python3 tests/consumers/observation_consumer.py --snapshot --analysis /tmp/control-analysis.json /tmp/control-observation.json + python3 tests/consumers/observation_consumer.py --validate-schema --analysis /tmp/control-analysis.json /tmp/control-events.jsonl + - | + set -eu + python3 - <<'PY' + import json, pathlib + events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()] + snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_text()) + assert snapshot["events"] == events, "stream and snapshot must be one event sequence" + print("stream and snapshot share one event sequence") + PY + - | + set -eu + cp /tmp/control-analysis.json /tmp/analysis-stale.json + printf ' ' >> /tmp/analysis-stale.json + if python3 tests/consumers/observation_consumer.py --analysis /tmp/analysis-stale.json /tmp/control-events.jsonl; then + echo "stale Analysis was accepted" >&2 + exit 1 + fi + echo "stale Analysis rejected" + test: image: rust:1.100-bookworm commands: @@ -16,38 +58,9 @@ steps: - cargo fmt --all -- --check - cargo clippy --workspace --all-targets -- -D warnings # Provider CLI tests resolve a real provider worker next to the CLI - # binary; both binaries are also used by the black-box gates below. - - cargo build --locked -p marqdo-cli -p marqdo-provider-worker + # 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 - # Observation black-box contract: one real execution feeds the JSONL - # stream and the JSON snapshot, and an independent consumer validates both. - - ./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json - - ./target/debug/marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl --observation-file /tmp/observation.json > /tmp/observation.jsonl - - python3 tests/consumers/analysis_consumer.py /tmp/analysis.json - - python3 tests/consumers/observation_consumer.py /tmp/observation.jsonl --validate-schema - - python3 tests/consumers/observation_consumer.py --snapshot /tmp/observation.json --analysis /tmp/analysis.json - - ./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md --emit /tmp/control-analysis.json - - ./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md --output jsonl --observation-file /tmp/control-observation.json > /tmp/control-events.jsonl - - python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-observation.json examples/tool-unknown-name/tool.json - - python3 tests/consumers/analysis_consumer.py /tmp/control-analysis.json --require-transfers - - python3 tests/consumers/observation_consumer.py --snapshot /tmp/control-observation.json --analysis /tmp/control-analysis.json - - python3 tests/consumers/observation_consumer.py /tmp/control-events.jsonl --analysis /tmp/control-analysis.json --validate-schema - - | - set -eu - python3 - <<'PY' - import json, pathlib - events = [json.loads(line) for line in pathlib.Path("/tmp/control-events.jsonl").read_bytes().splitlines()] - snapshot = json.loads(pathlib.Path("/tmp/control-observation.json").read_text()) - assert snapshot["events"] == events, "stream and snapshot must be one event sequence" - PY - - | - set -eu - cp /tmp/control-analysis.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 - echo "stale Analysis was accepted" >&2 - exit 1 - fi - 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" @@ -66,7 +79,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 From f55559b531e18b4487d8b568c9327bf6ed703eeb Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 18:20:41 +0800 Subject: [PATCH 15/17] ci: keep the contract lane compatible with the image shell --- .woodpecker/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index b6c7d65..6ed90ac 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -16,7 +16,7 @@ steps: - apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema - cargo build --locked -p marqdo-cli -p marqdo-provider-worker - | - set -euxo pipefail + set -eux ./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json ./target/debug/marqdo run tests/consumers/fixtures/observation/basic.mq.md --output jsonl --observation-file /tmp/observation.json > /tmp/observation.jsonl python3 tests/consumers/analysis_consumer.py /tmp/analysis.json From 5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 18:32:44 +0800 Subject: [PATCH 16/17] ci: pin the converged conformance fixtures --- docs/ci.md | 12 +++++++++++- tools/ci/run_frozen_extensions.sh | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/ci.md b/docs/ci.md index 12c2666..3c0307f 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -11,9 +11,19 @@ [development-credentials.md](development-credentials.md). Do not put tokens in pipeline files or commit messages. -The default Docker pipeline runs on push and pull request: +The default Docker pipeline runs on push and pull request. A fast `contract` +lane exercises the public Analysis/Observation contracts through the real CLI +and the independent Python consumers; the full `test` lane runs the Rust gates +and the Windows cross-target compile check; `build` packages the archive, runs +the from-archive smoke and the frozen external conformance suite. ```text +contract: + cargo build --locked -p marqdo-cli -p marqdo-provider-worker + real CLI check/run over the Observation fixtures + analysis_consumer / observation_consumer / validate_protocols + stream==snapshot assertion and stale-Analysis rejection + test: rustup component add clippy rustfmt apt install curl/ca-certificates/python3/python3-jsonschema + Node.js 22 diff --git a/tools/ci/run_frozen_extensions.sh b/tools/ci/run_frozen_extensions.sh index 6e2ab6e..1bd2180 100755 --- a/tools/ci/run_frozen_extensions.sh +++ b/tools/ci/run_frozen_extensions.sh @@ -12,7 +12,7 @@ source_sha="$2" manifest="$3" root="$(cd "$(dirname "$0")/../.." && pwd)" fixture_remote=https://git.cflmy.cn/cflmy/marqdo-extension-conformance.git -fixture_sha=cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec +fixture_sha=015ff8ac15417b7ebbdb31ce2be2dab5362a1eba work="$(mktemp -d)" trap 'rm -rf -- "$work"' EXIT From 5c371a9bef04916b596678f4785e057560e87253 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 24 Nov 2026 18:49:54 +0800 Subject: [PATCH 17/17] evidence: record the same-SHA CI for the rc.3 candidate --- CHANGELOG.md | 9 ++++-- docs/STATUS.md | 28 ++++++++++++++----- ...6-11-24-rc.3-protocol-convergence-local.md | 28 +++++++++++++++++++ 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffe4d88..f59546c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,8 +78,13 @@ Migration for consumers: - `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. -- Release evidence for publication still requires the same-SHA CI pipeline and - archive smoke described in [`docs/releasing.md`](docs/releasing.md). +- Same-SHA Linux CI [pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70) + passed all lanes, produced archive sha256 + `d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37`, passed + the from-archive smoke and the frozen external conformance suite 7/7 with + fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`. +- Publication still requires the RC strict-VM and G4 performance evidence + described in [`docs/releasing.md`](docs/releasing.md). ## 3.0.0-rc.2 (candidate) diff --git a/docs/STATUS.md b/docs/STATUS.md index 97294bd..9b75995 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -107,14 +107,28 @@ observation_consumer.py stream.jsonl --analysis stale-analysis.json rejected marqdo --version marqdo 3.0.0-rc.3 ``` -Release status: the tree and developer inputs are ready for `3.0.0-rc.3`. The -built archive (source `291e521c`, sha256 `8a663dee…`) passed the from-archive -smoke; the local evidence is +Same-SHA CI on Linux x86_64 +([pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70), commit +`5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`): the fast `contract` lane, the full +Rust `test` lane (fmt, clippy, workspace tests, docs/architecture gates, Windows +cross-target compile check), `minimum-rust` and `build` all PASS. The build lane +produced `marqdo-3.0.0-rc.3-x86_64-unknown-linux-gnu.tar.gz` +(sha256 `d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37`), +passed the from-archive smoke, and passed the frozen external conformance suite +7/7 with fixtures at `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba` +(callable registry, plugin worker, foreign kernel, provider CLI, pinned package, +tool Analysis consumer, negative security). + +The detailed local log and the CI addendum are in [`evidence/2026-11-24-rc.3-protocol-convergence-local.md`](evidence/2026-11-24-rc.3-protocol-convergence-local.md). -Publication still requires the same-SHA CI pipeline plus the clean-install -container gate bound to that SHA, as required by -[`releasing.md`](releasing.md). Do not tag or publish from local evidence -alone. + +Release status: the tree, contracts, archive and same-SHA Linux CI are ready for +`3.0.0-rc.3`, but **publication is not authorized by this evidence**. The RC +profile in [`releasing.md`](releasing.md) additionally requires a same-SHA +strict-L1 PASS on a disposable VM as a non-root user and fixed-node G4 +performance evidence (or the recorded maintainer exception). Neither exists +here; the CI host truthfully reports `strict: unavailable` fail-closed. Do not +tag or publish `v3.0.0-rc.3` from this section. ## 0. Beta release record — `3.0.0-beta.1` diff --git a/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md b/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md index d6e54a6..bad0b3b 100644 --- a/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md +++ b/docs/evidence/2026-11-24-rc.3-protocol-convergence-local.md @@ -65,3 +65,31 @@ worker paths, foreign kernel, strict fail-closed refusal on this host, and the 2. Run the clean-install container gate against the archive bytes. 3. Tag `v3.0.0-rc.3` at the evidenced SHA and publish the archive, checksum and release notes. Local evidence cannot be promoted to a remote claim. + +## CI addendum — same-SHA Linux pipeline + +After this local log, the branch was pushed and ran the same-SHA Woodpecker +pipeline on commit `5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef`: +[pipeline #70](https://ci.cflmy.cn/repos/1/pipeline/70). + +```text +contract lane (real CLI + independent consumers) PASS +test lane (fmt/clippy/tests/docs/arch/stdlib) PASS +Windows cross-target compile gate PASS +minimum-rust (1.89) PASS +build lane PASS +archive sha256 d6ef6297a7ba5297af758a0b00da5c6e0f4b69f40363afc4ddc180654e70ac37 +archive source 5a89a137c7f76f6c31744a4e8f8d4dbc0af623ef +from-archive smoke PASS (stdlib digest, consumers, tools, workers, strict refusal) +frozen extensions 7/7 PASS at fixture SHA 015ff8ac15417b7ebbdb31ce2be2dab5362a1eba +``` + +The frozen extension fixture repository was updated in the same integration +(commit `015ff8ac15417b7ebbdb31ce2be2dab5362a1eba`): its tool manifest uses exact +current requirements, its consumers read the current Analysis/Observation +contracts through `--output json` / `--output jsonl` / `--observation-file`, +and no `--json`/`--trace-file`/`--event-stream` path remains. + +This satisfies the Linux CI and cross-repository evidence for the protocol +replacement. It does **not** satisfy the RC strict-VM or G4 performance gates, +so `v3.0.0-rc.3` must not be tagged on this evidence alone.