diff --git a/crates/cli/src/commands/check.rs b/crates/cli/src/commands/check.rs index eb3af82..5602ba4 100644 --- a/crates/cli/src/commands/check.rs +++ b/crates/cli/src/commands/check.rs @@ -11,7 +11,15 @@ pub fn check( ) -> i32 { let prepared = match prepare_project(file, json, plugins) { Ok(prepared) => prepared, - Err(code) => return code, + Err(code) => { + // A failed check never leaves a success artifact behind: a consumer + // must not be able to bind `run` to a previous Analysis after the + // project stopped loading or compiling. + if let Some(path) = emit { + let _ = std::fs::remove_file(path); + } + return code; + } }; let mut project = prepared.loaded; if refs { diff --git a/crates/cli/src/commands/run.rs b/crates/cli/src/commands/run.rs index 76fff9e..d95d2fd 100644 --- a/crates/cli/src/commands/run.rs +++ b/crates/cli/src/commands/run.rs @@ -21,16 +21,25 @@ pub fn execute( ); return 2; } + // Strict runs project code under the isolation supervisor, which owns + // stdout. A live JSONL stream or a file destination would bypass that + // supervisor, so reject the destination before any session is opened: an + // unsupported destination must never produce a partial stream. + if settings.mode == "strict" + && (observation.output == OutputFormat::Jsonl || observation.file.is_some()) + { + return fail( + None, + "strict", + "strict.unsupported_grant", + "strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations", + 2, + ); + } // Open before preparation so option, compile and authorization failures // can still publish a rejection on the requested observation destination. - let 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) { + let events = if observation.enabled() { + match ObservationSession::open(observation) { Ok(events) => Some(events), Err(error) => return transport_failure(&error), } @@ -38,15 +47,6 @@ pub fn execute( 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), diff --git a/crates/cli/tests/analysis_observation.rs b/crates/cli/tests/analysis_observation.rs index 99b14b7..36658f1 100644 --- a/crates/cli/tests/analysis_observation.rs +++ b/crates/cli/tests/analysis_observation.rs @@ -337,6 +337,31 @@ fn failed_check_removes_stale_analysis() { assert!(!target.exists(), "stale success artifact must be removed"); } +#[test] +fn check_that_cannot_load_the_project_removes_stale_analysis() { + let dir = TempDir::new("analysis-load-error"); + write(dir.path(), "index.mq.md", "## @exec main\n\n`return 1`\n"); + let target = dir.path().join("analysis.json"); + let first = cli( + dir.path(), + &["check", "index.mq.md", "--emit", target.to_str().unwrap()], + ); + assert_eq!(first.status.code(), Some(0), "{first:?}"); + assert!(target.exists()); + + // The load failure happens before the compile-error cleanup branch, so the + // remove must also cover the prepare path. + let failed = cli( + dir.path(), + &["check", "missing.mq.md", "--emit", target.to_str().unwrap()], + ); + assert_ne!(failed.status.code(), Some(0), "{failed:?}"); + assert!( + !target.exists(), + "a load failure must not leave the previous Analysis in place" + ); +} + #[test] fn snapshot_records_calls_effects_and_status_without_secrets() { let dir = TempDir::new("trace"); diff --git a/crates/cli/tests/observation.rs b/crates/cli/tests/observation.rs index a79c9fb..72b6d3e 100644 --- a/crates/cli/tests/observation.rs +++ b/crates/cli/tests/observation.rs @@ -878,3 +878,46 @@ fn loop_transfers_are_ordered_structural_events_with_source_spans() { assert_eq!(statement["span"], span); } } + +#[test] +fn strict_mode_rejects_live_and_file_destinations_before_opening_a_stream() { + let dir = TempDir::new("strict-destinations"); + dir.write("index.mq.md", BASIC); + let snapshot = dir.path().join("snapshot.json"); + let snapshot_arg = snapshot.to_str().unwrap().to_string(); + + for args in [ + vec![ + "run", + "index.mq.md", + "--mode", + "strict", + "--output", + "jsonl", + ], + vec![ + "run", + "index.mq.md", + "--mode", + "strict", + "--output", + "text", + "--observation-file", + snapshot_arg.as_str(), + ], + ] { + let output = cli(dir.path(), &args); + assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}"); + assert!( + output.stdout.is_empty(), + "a rejected strict destination must not emit a partial stream: {}", + String::from_utf8_lossy(&output.stdout) + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("strict.unsupported_grant"), "{stderr}"); + assert!( + !snapshot.exists(), + "a rejected strict destination must not publish a snapshot file" + ); + } +} diff --git a/crates/marqdo-host/src/host/resource_requests.rs b/crates/marqdo-host/src/host/resource_requests.rs index 7408383..7a989b2 100644 --- a/crates/marqdo-host/src/host/resource_requests.rs +++ b/crates/marqdo-host/src/host/resource_requests.rs @@ -516,7 +516,7 @@ impl StdHost { _ => unreachable!(), } let result = self.fs.request(name, &paths, ctx.span)?; - self.observe_effect("resource.request", "ok", ctx); + self.observe_effect(&format!("fs.{name}"), "ok", ctx); Ok(result) } _ => { diff --git a/crates/marqdo-host/src/plugin_worker.rs b/crates/marqdo-host/src/plugin_worker.rs index ef51df4..26d0902 100644 --- a/crates/marqdo-host/src/plugin_worker.rs +++ b/crates/marqdo-host/src/plugin_worker.rs @@ -333,8 +333,39 @@ fn transport_error(error: TransportError) -> PluginError { "plugin.crashed", format!("worker frame I/O failed: {error}"), ), + // The shared transport classifies an over-limit or unencodable frame + // before anything is written. Keep the boundary-specific codes the + // plugin ABI has always reported instead of flattening them into + // `worker_frame_invalid`. + TransportError::Frame(FrameError::Encode(error)) => { + PluginError::wire("worker_encode_failed", error.to_string()) + } + TransportError::Frame(FrameError::Length(length)) => PluginError::wire( + "worker_frame_too_large", + format!("worker frame is {length} bytes"), + ), TransportError::Frame(other) => { PluginError::wire("worker_frame_invalid", other.to_string()) } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transport_errors_keep_the_boundary_specific_codes() { + let too_large = transport_error(TransportError::Frame(FrameError::Length(9 * 1024 * 1024))); + assert_eq!(too_large.code, "worker_frame_too_large"); + + let over_limit = transport_error(TransportError::Frame(FrameError::PartialPayload { + expected: 10, + actual: 3, + })); + assert_eq!(over_limit.code, "worker_frame_invalid"); + + let closed = transport_error(TransportError::Closed); + assert_eq!(closed.code, "plugin.crashed"); + } +} diff --git a/crates/marqdo-host/tests/observation.rs b/crates/marqdo-host/tests/observation.rs index 115bb3b..bb6c51c 100644 --- a/crates/marqdo-host/tests/observation.rs +++ b/crates/marqdo-host/tests/observation.rs @@ -462,3 +462,76 @@ fn value_encoding_is_selected_bounded_and_handle_safe() { assert_eq!(state, ValueState::Unsupported); assert!(value.is_none()); } + +#[test] +fn filesystem_operations_report_the_concrete_effect_name() { + let dir = std::env::temp_dir().join(format!( + "marqdo-host-fs-effect-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("data.txt"), b"x").unwrap(); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + let events = Rc::new(RefCell::new(Vec::new())); + let mut host = StdHost::new( + SandboxMode::Project, + Capabilities::project().allow_read("**").allow_write("**"), + dir.clone(), + ) + .with_observation( + ObservationConfig::default(), + Box::new(Recorder { + events: Rc::clone(&events), + fail: false, + }), + ); + let ctx = context(); + for (operation, args) in [ + ("fs.exists", vec![Value::Text("data.txt".to_string())]), + ("fs.metadata", vec![Value::Text("data.txt".to_string())]), + ("fs.list", vec![Value::Text("sub".to_string())]), + ("fs.mkdir", vec![Value::Text("created".to_string())]), + ("fs.remove", vec![Value::Text("created".to_string())]), + ( + "fs.rename", + vec![ + Value::Text("data.txt".to_string()), + Value::Text("moved.txt".to_string()), + ], + ), + ] { + host.resource_request(operation, args, &ctx) + .unwrap_or_else(|error| panic!("{operation}: {error}")); + } + let operations: Vec = events + .borrow() + .iter() + .filter_map(|event| match event { + Recorded::Effect { + operation, + result_code, + } => { + assert_eq!(result_code, "ok"); + Some(operation.clone()) + } + _ => None, + }) + .collect(); + assert_eq!( + operations, + [ + "fs.exists", + "fs.metadata", + "fs.list", + "fs.mkdir", + "fs.remove", + "fs.rename", + ], + "each filesystem request must report its concrete operation" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/spec/observation.md b/spec/observation.md index db849af..d05ec25 100644 --- a/spec/observation.md +++ b/spec/observation.md @@ -30,6 +30,9 @@ 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. + The capture level is `base` (lifecycle only), `structural` (frame, branch, + loop and effect events) or `values` (explicitly selected names); the + snapshot `capture` metadata repeats the same level. - `run.started` binds an entry, mode and source. `source.root_id` and `source.analysis_digest` identify the exact Analysis JSON emitted by `check --emit` for the same project and static options. The digest is diff --git a/spec/schemas/observation-file.schema.json b/spec/schemas/observation-file.schema.json index 4324a9f..446c7d8 100644 --- a/spec/schemas/observation-file.schema.json +++ b/spec/schemas/observation-file.schema.json @@ -81,6 +81,7 @@ "properties": { "level": { "enum": [ + "base", "structural", "values" ]