From 71d29261a8b78cb71ef9aaf5651bd7916b9591ec Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 19:47:24 +0800 Subject: [PATCH] Expose loop transfers through versioned public observations --- .github/workflows/ci.yml | 13 +++ crates/cli/src/execution_events.rs | 13 +++ crates/cli/src/main.rs | 2 +- crates/cli/src/tool.rs | 31 ++++-- crates/cli/tests/analysis_trace.rs | 75 +++++++++++++ crates/cli/tests/execution_events.rs | 106 +++++++++++++++++++ crates/cli/tests/tool_protocol.rs | 11 ++ crates/marqdo-host/src/host.rs | 19 ++++ crates/marqdo-host/src/lib.rs | 2 +- crates/marqdo-host/src/observe.rs | 34 ++++++ crates/marqdo-host/tests/observation.rs | 10 ++ crates/marqdo-runtime/src/interpreter.rs | 39 +++++-- crates/marqdo-runtime/tests/interpreter.rs | 43 ++++++++ crates/marqdo-runtime/tests/observation.rs | 12 +++ spec/execution-events-v1.md | 13 ++- spec/schemas/execution-events-v1.schema.json | 17 +++ spec/tool-v1.md | 7 +- spec/trace-v2.md | 13 ++- tests/consumers/analysis_v3_consumer.py | 45 ++++++++ tests/consumers/trace_consumer.py | 2 +- tests/consumers/validate_protocols.py | 14 ++- 21 files changed, 486 insertions(+), 35 deletions(-) create mode 100644 tests/consumers/analysis_v3_consumer.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 44f19ee..c8395d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,6 +114,19 @@ jobs: python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json python3 tests/consumers/trace_consumer.py \ /tmp/analysis-v2.json /tmp/trace-v2.json + ./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md \ + --emit /tmp/analysis-v3.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 + python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl cross-platform: name: runtime contract (${{ matrix.os }}) diff --git a/crates/cli/src/execution_events.rs b/crates/cli/src/execution_events.rs index 97e579c..ccb7b73 100644 --- a/crates/cli/src/execution_events.rs +++ b/crates/cli/src/execution_events.rs @@ -351,6 +351,19 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) { "span": span.map(span_json), }), ), + ObservationEvent::LoopTransfer { + frame_id, + transfer, + module_id, + span, + } => ( + transfer.event_kind(), + json!({ + "frame_id": frame_id.as_wire(), + "module_id": module_id, + "span": span_json(span), + }), + ), ObservationEvent::Effect { operation, result_code, diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 55f6780..22881c3 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 the public Analysis v2 projection (only on successful check). + /// Write public Analysis JSON, using v3 for projects with loop transfers. #[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 d791af3..2b001b8 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -31,7 +31,10 @@ struct SupportedProtocols { const SUPPORTED: SupportedProtocols = SupportedProtocols { tool: PROTOCOL_VERSION, - analysis: &[2], + analysis: &[ + crate::analysis::BASE_VERSION, + crate::analysis::LOOP_CONTROL_VERSION, + ], trace: &[2], }; @@ -297,7 +300,7 @@ fn negotiate_protocol( let Some(requested) = requested else { return Ok(()); }; - if requested.is_empty() || !requested.iter().any(|version| supported.contains(version)) { + if shared_version(requested, supported).is_none() { return Err(format!( "tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}" )); @@ -305,6 +308,14 @@ fn negotiate_protocol( 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()) @@ -623,21 +634,21 @@ pub fn dispatch(args: &[OsString]) -> i32 { process.env("MARQDO_BIN", bin); } process.env("MARQDO_TOOL_PROTOCOL", "1"); - if record + if let Some(version) = record .compatibility .analysis - .as_ref() - .is_some_and(|versions| versions.contains(&2)) + .as_deref() + .and_then(|versions| shared_version(versions, SUPPORTED.analysis)) { - process.env("MARQDO_PROTOCOL_ANALYSIS", "2"); + process.env("MARQDO_PROTOCOL_ANALYSIS", version.to_string()); } - if record + if let Some(version) = record .compatibility .trace - .as_ref() - .is_some_and(|versions| versions.contains(&2)) + .as_deref() + .and_then(|versions| shared_version(versions, SUPPORTED.trace)) { - process.env("MARQDO_PROTOCOL_TRACE", "2"); + process.env("MARQDO_PROTOCOL_TRACE", version.to_string()); } match process.status() { Ok(status) => status.code().unwrap_or(1), diff --git a/crates/cli/tests/analysis_trace.rs b/crates/cli/tests/analysis_trace.rs index 4f0ec55..764bb3e 100644 --- a/crates/cli/tests/analysis_trace.rs +++ b/crates/cli/tests/analysis_trace.rs @@ -460,3 +460,78 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() { assert_eq!(result["value"]["decimal"], expected); } } + +#[test] +fn an_imported_loop_transfer_selects_v3_and_keeps_the_else_if_call_edge() { + let dir = TempDir::new("imported-loop"); + write( + dir.path(), + "gate.mq.md", + "## @exec enabled\n\n`while true`\n\n`break`\n\n`end`\n\n`return true`\n", + ); + write( + dir.path(), + "index.mq.md", + r#"--- +import: + gate: "./gate.mq.md" +--- + +## @exec main + +`if false` + +`return 0` + +`else if gate.enabled()` + +`return 1` + +`end` +"#, + ); + let result = cli( + dir.path(), + &["check", "index.mq.md", "--emit", "analysis.json"], + ); + assert!(result.status.success(), "{result:?}"); + let analysis: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap(); + assert_eq!(analysis["schema_version"], 3); + let root = analysis["modules"] + .as_array() + .unwrap() + .iter() + .find(|module| module["relative_path"] == "index.mq.md") + .unwrap(); + let calls = root["calls"].as_array().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["state"], "function"); + assert!(calls[0]["target"] + .as_str() + .unwrap() + .ends_with("::gate.mq.md::enabled")); +} + +#[test] +fn invalid_loop_control_rejects_check_and_does_not_execute_the_function() { + let dir = TempDir::new("invalid-loop"); + write( + dir.path(), + "index.mq.md", + "## @exec main\n\n`打印(\"unreachable output\")`\n\n`break`\n", + ); + write(dir.path(), "stale.json", "previous output"); + let checked = cli( + dir.path(), + &["check", "index.mq.md", "--emit", "stale.json", "--json"], + ); + assert_eq!(checked.status.code(), Some(1), "{checked:?}"); + assert!(String::from_utf8_lossy(&checked.stdout).contains("sem.break_outside_loop")); + assert!(!String::from_utf8_lossy(&checked.stdout).contains("unreachable output")); + assert!(!dir.path().join("stale.json").exists()); + + let run = cli(dir.path(), &["run", "index.mq.md"]); + assert_eq!(run.status.code(), Some(1), "{run:?}"); + assert!(run.stdout.is_empty()); +} diff --git a/crates/cli/tests/execution_events.rs b/crates/cli/tests/execution_events.rs index dee0ef3..c20aa7f 100644 --- a/crates/cli/tests/execution_events.rs +++ b/crates/cli/tests/execution_events.rs @@ -765,3 +765,109 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() { "expected a transport diagnostic on stderr: {stderr}" ); } + +#[test] +fn loop_transfers_are_ordered_structural_events_with_source_spans() { + use sha2::{Digest, Sha256}; + + let dir = TempDir::new("loop-transfers"); + let source = r#"## @exec main + +`索引 = 0` + +`while true` + +`索引 = 索引 + 1` + +`if 索引 == 1` + +`continue` + +`else if 索引 == 2` + +`break` + +`end` + +`end` + +`return 索引` +"#; + dir.write("index.mq.md", source); + let checked = cli( + dir.path(), + &["check", "index.mq.md", "--emit", "analysis.json"], + ); + assert!(checked.status.success(), "{checked:?}"); + let analysis_bytes = fs::read(dir.path().join("analysis.json")).unwrap(); + let analysis: Value = serde_json::from_slice(&analysis_bytes).unwrap(); + assert_eq!(analysis["schema_version"], 3); + let module = &analysis["modules"][0]; + let branch = &module["functions"][0]["body"][1]["body"][1]; + let output = cli( + dir.path(), + &[ + "run", + "index.mq.md", + "--mode", + "pure", + "--event-stream", + "jsonl", + "--trace-file", + "trace.json", + ], + ); + assert!(output.status.success(), "{output:?}"); + let events = parse_events(&output.stdout); + assert_envelope(&events); + 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["source"]["analysis_digest"], + format!("sha256:{:x}", Sha256::digest(analysis_bytes)) + ); + + let kinds = |events: &[Value]| { + events + .iter() + .filter_map(|event| match event["kind"].as_str() { + Some("loop.iteration") => Some("loop.iteration"), + Some("control.continue") => Some("control.continue"), + Some("control.break") => Some("control.break"), + Some("return") => Some("return"), + _ => None, + }) + .collect::>() + }; + let expected = [ + "loop.iteration", + "control.continue", + "loop.iteration", + "control.break", + "return", + ]; + assert_eq!(kinds(&events), expected); + let trace_events = trace["events"].as_array().unwrap(); + assert_eq!(kinds(trace_events), expected); + let frame = &events_of(&events, "call.enter")[0]["payload"]["frame_id"]; + for (index, keyword) in ["continue", "break"].iter().enumerate() { + let kind = format!("control.{keyword}"); + let carrier = format!("`{keyword}`"); + let start = source.find(&carrier).unwrap(); + let span = serde_json::json!({"start": start, "end": start + carrier.len()}); + let payload = &events_of(&events, &kind)[0]["payload"]; + assert_eq!(payload["frame_id"], *frame); + 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/tool_protocol.rs b/crates/cli/tests/tool_protocol.rs index 2189bd8..7d91718 100644 --- a/crates/cli/tests/tool_protocol.rs +++ b/crates/cli/tests/tool_protocol.rs @@ -376,6 +376,17 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() { 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 = + 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"), diff --git a/crates/marqdo-host/src/host.rs b/crates/marqdo-host/src/host.rs index f81035c..6162228 100644 --- a/crates/marqdo-host/src/host.rs +++ b/crates/marqdo-host/src/host.rs @@ -1047,6 +1047,25 @@ impl Host for StdHost { false, ) } + RuntimeObservation::LoopTransfer { + frame_id, + transfer, + module_id, + span, + } => { + let Some(frame_id) = frame_id else { + return Ok(()); + }; + self.emit_observation( + ObservationEvent::LoopTransfer { + frame_id, + transfer, + module_id, + span, + }, + false, + ) + } RuntimeObservation::VariableAssigned { frame_id, name, diff --git a/crates/marqdo-host/src/lib.rs b/crates/marqdo-host/src/lib.rs index 10dab31..d05d8ff 100644 --- a/crates/marqdo-host/src/lib.rs +++ b/crates/marqdo-host/src/lib.rs @@ -30,7 +30,7 @@ pub use handles::{contains_plugin_handle, PluginHandleTable}; pub use host::{arity, expect_text, Host, HostOp, StdHost}; pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation}; pub use observe::{ - encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError, + encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES, diff --git a/crates/marqdo-host/src/observe.rs b/crates/marqdo-host/src/observe.rs index e409932..a457aa2 100644 --- a/crates/marqdo-host/src/observe.rs +++ b/crates/marqdo-host/src/observe.rs @@ -193,6 +193,13 @@ pub enum ObservationEvent<'a> { module_id: &'a str, span: Option, }, + /// An explicit loop control statement executed. + LoopTransfer { + frame_id: FrameId, + transfer: LoopTransfer, + module_id: &'a str, + span: Span, + }, /// The host completed a controlled effect attempt. Effect { operation: &'a str, @@ -230,6 +237,25 @@ pub enum ObservationEvent<'a> { }, } +/// The action carried by a structured loop transfer observation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LoopTransfer { + /// Exit the enclosing loop. + Break, + /// Proceed to the enclosing loop's next condition check. + Continue, +} + +impl LoopTransfer { + /// The event kind in Trace and Execution Events. + pub fn event_kind(self) -> &'static str { + match self { + Self::Break => "control.break", + Self::Continue => "control.continue", + } + } +} + /// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`]. /// /// Every variant carries an `Option`; observation of values and @@ -257,6 +283,13 @@ pub enum RuntimeObservation<'a> { module_id: &'a str, span: Option, }, + /// An explicit loop control statement executed. + LoopTransfer { + frame_id: Option, + transfer: LoopTransfer, + module_id: &'a str, + span: Span, + }, /// A local variable assignment committed. VariableAssigned { frame_id: Option, @@ -498,6 +531,7 @@ pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 { } ObservationEvent::BranchEval { module_id, .. } | ObservationEvent::LoopIteration { module_id, .. } + | ObservationEvent::LoopTransfer { module_id, .. } | ObservationEvent::Effect { module_id, .. } => { add_text(module_id); if let ObservationEvent::LoopIteration { decision, .. } = event { diff --git a/crates/marqdo-host/tests/observation.rs b/crates/marqdo-host/tests/observation.rs index d3ee28a..115bb3b 100644 --- a/crates/marqdo-host/tests/observation.rs +++ b/crates/marqdo-host/tests/observation.rs @@ -58,6 +58,10 @@ enum Recorded { state: ValueState, value: Option, }, + LoopTransfer { + frame: FrameId, + kind: &'static str, + }, Effect { operation: String, result_code: String, @@ -110,6 +114,12 @@ impl From> for Recorded { frame: frame_id, decision: decision.to_string(), }, + ObservationEvent::LoopTransfer { + frame_id, transfer, .. + } => Recorded::LoopTransfer { + frame: frame_id, + kind: transfer.event_kind(), + }, ObservationEvent::Effect { operation, result_code, diff --git a/crates/marqdo-runtime/src/interpreter.rs b/crates/marqdo-runtime/src/interpreter.rs index c931425..057f2c0 100644 --- a/crates/marqdo-runtime/src/interpreter.rs +++ b/crates/marqdo-runtime/src/interpreter.rs @@ -4,7 +4,8 @@ use std::collections::BTreeMap; use marqdo_expression::{BinaryOp, Expr, RecordEntry}; use marqdo_host::{ - ExecutionContext, FrameId, Host, HostOp, ParameterSource, ResourceRead, RuntimeObservation, + ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead, + RuntimeObservation, }; use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt}; use marqdo_span::Span; @@ -71,8 +72,7 @@ struct BoundArgs { enum Flow { Next, Return(Value), - Break(Span), - Continue(Span), + LoopTransfer(LoopTransfer, Span), } /// Marqdo tree-walk interpreter. @@ -232,7 +232,7 @@ impl<'a> Interpreter<'a> { .and_then(|flow| match flow { Flow::Next => Ok(None), Flow::Return(value) => Ok(Some(value)), - Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new( + Flow::LoopTransfer(_, span) => Err(RuntimeError::new( ErrorCategory::Internal, Some(span), "loop control escaped its enclosing function", @@ -420,8 +420,31 @@ impl<'a> Interpreter<'a> { Stmt::Eval { expr, .. } => { self.eval_expr(expr, frame)?; } - Stmt::Break { span } => return Ok(Flow::Break(*span)), - Stmt::Continue { span } => return Ok(Flow::Continue(*span)), + Stmt::Break { span } | Stmt::Continue { span } => { + let transfer = if matches!(stmt, Stmt::Break { .. }) { + LoopTransfer::Break + } else { + 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 { + frame_id: frame.id, + transfer, + module_id: &module, + span: *span, + })?; + } + return Ok(Flow::LoopTransfer(transfer, *span)); + } Stmt::Return { value, span } => { let value = self.eval_expr(value, frame)?; let module = frame.function.module.canonical(); @@ -515,8 +538,8 @@ impl<'a> Interpreter<'a> { break; } match self.exec_stmts(program, body, frame)? { - Flow::Next | Flow::Continue(_) => {} - Flow::Break(_) => break, + Flow::Next | Flow::LoopTransfer(LoopTransfer::Continue, _) => {} + Flow::LoopTransfer(LoopTransfer::Break, _) => break, flow @ Flow::Return(_) => return Ok(flow), } }, diff --git a/crates/marqdo-runtime/tests/interpreter.rs b/crates/marqdo-runtime/tests/interpreter.rs index ba838da..3cd71fe 100644 --- a/crates/marqdo-runtime/tests/interpreter.rs +++ b/crates/marqdo-runtime/tests/interpreter.rs @@ -249,3 +249,46 @@ fn memory_budget_is_enforced_without_changing_the_region() { .unwrap_err(); assert_eq!(error.code(), "resource.exhausted"); } + +#[test] +fn continue_obeys_fuel_and_wall_clock_budgets() { + use std::time::{Duration, Instant}; + + let source = "## @exec main\n\n`while true`\n\n`continue`\n\n`end`\n"; + let program = build(source); + let module = ModuleId::from("index.mq.md"); + + let mut fuel_host = host(); + fuel_host.budget.fuel = 20; + let fuel = run(&program, &mut fuel_host, &module, "main", Vec::new()).unwrap_err(); + assert_eq!(fuel.code(), "resource.exhausted"); + assert!(fuel.message.contains("fuel exhausted")); + + let mut deadline_host = host(); + deadline_host.budget.fuel = u64::MAX; + deadline_host.budget.deadline = Some(Instant::now() + Duration::from_millis(25)); + let timeout = run(&program, &mut deadline_host, &module, "main", Vec::new()).unwrap_err(); + assert_eq!(timeout.code(), "resource.exhausted"); + assert!(timeout.message.contains("wall-clock time limit")); +} + +#[test] +fn malformed_ir_cannot_transfer_into_the_callers_loop() { + let source = + "## @exec child\n\n`return 1`\n\n## @exec main\n\n`while true`\n\n`child()`\n\n`end`\n"; + let mut program = build(source); + let module = ModuleId::from("index.mq.md"); + let child = program + .modules + .get_mut(&module) + .unwrap() + .functions + .iter_mut() + .find(|function| function.id.name == "child") + .unwrap(); + let span = child.body[0].span(); + child.body[0] = marqdo_ir::Stmt::Break { span }; + let error = run(&program, &mut host(), &module, "main", Vec::new()).unwrap_err(); + assert_eq!(error.category, marqdo_value::ErrorCategory::Internal); + assert_eq!(error.span, Some(span)); +} diff --git a/crates/marqdo-runtime/tests/observation.rs b/crates/marqdo-runtime/tests/observation.rs index e59fc09..0c094a6 100644 --- a/crates/marqdo-runtime/tests/observation.rs +++ b/crates/marqdo-runtime/tests/observation.rs @@ -93,6 +93,18 @@ impl ObservationSink for Recorder { source: None, decision: decision.to_string(), }, + ObservationEvent::LoopTransfer { + frame_id, transfer, .. + } => Seen { + kind: transfer.event_kind(), + frame: Some(frame_id.0), + name: String::new(), + value_type: String::new(), + state: None, + wire: None, + source: None, + decision: String::new(), + }, ObservationEvent::VariableAssigned { frame_id, name, diff --git a/spec/execution-events-v1.md b/spec/execution-events-v1.md index 118e4ba..ca086ca 100644 --- a/spec/execution-events-v1.md +++ b/spec/execution-events-v1.md @@ -118,7 +118,7 @@ Required payload fields: `entry`, `mode`, `source`; optional ``` `source.analysis_digest` is `sha256:` plus the SHA-256 of the **exact bytes** -of the Analysis v2 file produced for the same project and projection +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. @@ -152,6 +152,7 @@ Required payload fields: | `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 @@ -166,6 +167,10 @@ Required payload fields: * `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 @@ -291,7 +296,7 @@ authorization are unchanged. * 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 v2 never gain argument/local values, handles, memory +* 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 @@ -303,11 +308,11 @@ authorization are unchanged. * Tests use synthetic sentinel values and assert that unselected values never appear in the stream, Trace or `--json`. -## 6. Relation to Analysis v2 and Trace v2 +## 6. Relation to Analysis and Trace v2 | Artifact | Relation | |---|---| -| Analysis v2 | Static only. `run.started.source` binds to its exact bytes via `analysis_digest`. Events never replace it. | +| 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. | diff --git a/spec/schemas/execution-events-v1.schema.json b/spec/schemas/execution-events-v1.schema.json index 236ea74..3b9c95b 100644 --- a/spec/schemas/execution-events-v1.schema.json +++ b/spec/schemas/execution-events-v1.schema.json @@ -154,6 +154,23 @@ } } }, + { + "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": { diff --git a/spec/tool-v1.md b/spec/tool-v1.md index 3de2398..4a7967b 100644 --- a/spec/tool-v1.md +++ b/spec/tool-v1.md @@ -29,7 +29,7 @@ } ``` -类型:`schema` 固定字符串,`schema_version` 正整数(首版仅 1),`name`/`version`/`command`/`entrypoint` 非空字符串,`version` 必须是合法 SemVer,`compatibility.marqdo` 必须是可解析的 SemVer 范围,`analysis`、`trace` 为可选的非空正整数数组;仅当工具使用该数据协议时声明。当前核心提供 Analysis v2 与 Trace v2,因此声明 `[1]`(或与 `[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 不兼容应显式失败。 @@ -47,7 +47,8 @@ 工具负责自己的命令层级与帮助,如 `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=2` 与/或 `MARQDO_PROTOCOL_TRACE=2`。工具通过此路径运行 `marqdo check ... --emit ...` 和 `marqdo run ... --trace-file ...`,不拥有额外宿主内部 API。不得自动将密钥、项目能力授予记录、ABI 插件加载句柄或用户外联会话传给工具。 +可选辅助环境:`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. 三个独立安全域 @@ -57,7 +58,7 @@ ## 6. 向后兼容 -`schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。 +`schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2, 3]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。 原生命令集合是保留命名空间;未来新增与社区工具冲突的新核心顶层命令属于破坏性变化,必须经过 ADR、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。 diff --git a/spec/trace-v2.md b/spec/trace-v2.md index 1888dbc..ca983b8 100644 --- a/spec/trace-v2.md +++ b/spec/trace-v2.md @@ -8,7 +8,7 @@ Supersedes Trace v1; v1 was never released and is kept as history. * 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`, `return`) and the host (`effect`). Both share one sequence. + `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 @@ -41,10 +41,11 @@ 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 Analysis v2 `project.root_id` +`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 -v2 bytes produced for the same project with the same projection configuration. +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: @@ -66,9 +67,15 @@ event is `{"kind":"trace.truncated","detail":,"module_id":null, | `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`, ...). diff --git a/tests/consumers/analysis_v3_consumer.py b/tests/consumers/analysis_v3_consumer.py new file mode 100644 index 0000000..e532151 --- /dev/null +++ b/tests/consumers/analysis_v3_consumer.py @@ -0,0 +1,45 @@ +#!/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 e57a188..3f4a818 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") != 2: +if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") not in (2, 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 0e13d4f..54fe20d 100644 --- a/tests/consumers/validate_protocols.py +++ b/tests/consumers/validate_protocols.py @@ -48,22 +48,28 @@ def main(): trace = json.loads(trace_path.read_text(encoding="utf-8")) tool = json.loads(tool_path.read_text(encoding="utf-8")) - require_valid("analysis-v2.schema.json", analysis, "analysis") + 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" + 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 - require_invalid("analysis-v2.schema.json", bad, "analysis unsupported version") + require_invalid(analysis_schema, bad, "analysis unsupported version") bad = copy.deepcopy(analysis) bad.pop("modules", None) - require_invalid("analysis-v2.schema.json", bad, "analysis missing modules") + require_invalid(analysis_schema, bad, "analysis missing modules") bad = copy.deepcopy(analysis) bad["modules"][0]["resources"] = 3 - require_invalid("analysis-v2.schema.json", bad, "analysis resources integer") + require_invalid(analysis_schema, bad, "analysis resources integer") bad = copy.deepcopy(trace) bad["events"][0]["seq"] = "zero"