observation: deliver one execution event sequence to stream and snapshot

This commit is contained in:
Codex committed 2026-11-24 15:30:18 +08:00
1 parent f83d992c61
commit 404d559b86
97 files changed
+2672 -3128

No files matched your search

+1 -3
View File
@@ -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 }
+3 -5
View File
@@ -76,11 +76,9 @@ fn encode(project: &LoadedProject) -> Result<Vec<u8>, 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<String, String> {
encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes)))
}
/// Atomically write the projection. An error must not leave a stale success
+44 -57
View File
@@ -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::<serde_json::Value>(&outcome.stdout).is_ok()
if outcome.exit_code.is_some()
&& crate::observation::is_complete_snapshot(&outcome.stdout, exit_code)
{
return StrictRoute::Forward { exit_code };
}
@@ -277,33 +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::ffi::OsString> = std::env::args_os().skip(1).collect();
let output_limit = settings
let program_output_limit = settings
.max_output
.unwrap_or(1024 * 1024)
.min(64 * 1024 * 1024);
.unwrap_or(marqdo_host::DEFAULT_OUTPUT_BYTES);
let output_limit = if observation.is_some() {
// Allow framing and runtime observations within the existing
// supervisor capture ceiling. The child's program budget still applies.
64 * 1024 * 1024
} else {
program_output_limit.min(64 * 1024 * 1024)
};
let timeout = Duration::from_secs(settings.timeout.unwrap_or(30));
let stdlib_dir = crate::stdlib::StdlibBundle::discover()
.ok()
@@ -344,11 +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 });
+97 -301
View File
@@ -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<Vec<(String, Value)>, String>,
settings: &SandboxSettings,
json: bool,
trace: bool,
observation: Option<&ObservationOptions>,
observation: &ObservationOptions,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
// Open the dedicated protocol channel before any project work so prepare
// and authorization failures can still produce `run.rejected`.
let events = match observation {
Some(options) => match EventStream::open(options) {
Ok(stream) => Some(stream),
Err(error) => {
eprintln!("error[observe.transport_failed]: {error}");
return 1;
}
},
None => None,
};
let stream = events.as_ref();
let prepared = if stream.is_some() {
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, json, command_name, "prepare", &error),
if !observation.enabled() && observation.has_capture_overrides() {
eprintln!(
"error: capture options require --output json, --output jsonl or --observation-file"
);
return 2;
}
// 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<FileDiagnostic> = 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<EvaluatedArg> = 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.
+3 -10
View File
@@ -49,12 +49,6 @@ pub struct SandboxSettings {
pub allow_provider: Vec<String>,
/// Explicit trust decision for in-process native plugin loading.
pub trust_native_plugin: bool,
/// Optional Trace v2 output path.
pub trace_file: Option<PathBuf>,
/// Trace event budget override (0 = unlimited).
pub trace_max_events: Option<usize>,
/// Trace approximate byte budget override (0 = unlimited).
pub trace_max_bytes: Option<usize>,
/// External foreign-kernel descriptor paths.
pub kernels: Vec<PathBuf>,
}
@@ -72,7 +66,7 @@ impl SandboxSettings {
/// Reject strict-mode requests that this L1 isolation level does not
/// support. Strict currently covers pure Marqdo and native Math only;
/// granting Foreign, ABI plugins, resource providers, tools or trace files
/// granting Foreign, ABI plugins, resource providers or tools
/// would require extending the supervisor contract first.
pub fn strict_preflight(&self) -> Result<(), String> {
let requested = self.allow_foreign
@@ -87,14 +81,13 @@ impl SandboxSettings {
|| !self.providers.is_empty()
|| !self.allow_provider.is_empty()
|| self.trust_native_plugin
|| !self.kernels.is_empty()
|| self.trace_file.is_some();
|| !self.kernels.is_empty();
if requested {
return Err(
"strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\
--trust-native-plugin/--kernel/--trace-file are rejected. \
--trust-native-plugin/--kernel are rejected. \
Use --mode project for those capabilities."
.to_string(),
);
+34 -100
View File
@@ -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<String>,
/// Select terminal text, a JSON observation snapshot or live JSON Lines.
#[arg(long, value_enum, default_value = "text")]
output: observation::OutputFormat,
/// Atomically save a private observation snapshot of this run.
#[arg(long, value_name = "PATH")]
observation_file: Option<PathBuf>,
/// Publish the value of one exactly named local variable (repeatable).
#[arg(
long = "observe-variable",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-variable", value_name = "NAME")]
observe_variable: Vec<String>,
/// Publish the value of one exactly named parameter (repeatable).
#[arg(
long = "observe-parameter",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-parameter", value_name = "NAME")]
observe_parameter: Vec<String>,
/// Allow selected Text values to be published (second explicit consent).
#[arg(long = "observe-text-values", requires = "event_stream")]
#[arg(long = "observe-text-values")]
observe_text_values: bool,
/// Maximum encoded source bytes for one observed value (0 = unlimited).
#[arg(
long = "observe-max-value-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-value-bytes", value_name = "BYTES")]
observe_max_value_bytes: Option<usize>,
/// Override the structural/value event budget (0 = unlimited).
#[arg(
long = "observe-max-events",
value_name = "COUNT",
requires = "event_stream"
)]
#[arg(long = "observe-max-events", value_name = "COUNT")]
observe_max_events: Option<u64>,
/// Override the approximate structural/value byte budget (0 = unlimited).
#[arg(
long = "observe-max-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-bytes", value_name = "BYTES")]
observe_max_bytes: Option<u64>,
}
impl ObserveArgs {
fn options(&self) -> Option<execution_events::ObservationOptions> {
self.event_stream.as_ref()?;
let mut options = execution_events::ObservationOptions {
fn options(&self) -> observation::ObservationOptions {
let mut options = observation::ObservationOptions {
output: self.output,
file: self.observation_file.clone(),
variables: self.observe_variable.clone(),
parameters: self.observe_parameter.clone(),
allow_text_values: self.observe_text_values,
..execution_events::ObservationOptions::default()
..observation::ObservationOptions::default()
};
if let Some(bytes) = self.observe_max_value_bytes {
options.max_value_bytes = bytes;
@@ -108,7 +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<String>,
/// Write a versioned Trace v2 file for this run.
#[arg(long = "trace-file", value_name = "PATH")]
trace_file: Option<PathBuf>,
/// Override the trace event budget (0 = unlimited).
#[arg(long = "trace-max-events")]
trace_max_events: Option<usize>,
/// Override the approximate trace byte budget (0 = unlimited).
#[arg(long = "trace-max-bytes")]
trace_max_bytes: Option<usize>,
/// Register an external foreign-kernel provider (repeatable).
#[arg(long = "kernel", value_name = "PATH")]
kernel: Vec<PathBuf>,
@@ -259,9 +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<PathBuf>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output; program stdout is embedded, never mixed.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -294,12 +250,6 @@ struct CallArgs {
args: Vec<String>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -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),
@@ -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<PathBuf>,
/// Exact local-variable names selected with `--observe-variable`.
pub variables: Vec<String>,
/// Exact parameter names selected with `--observe-parameter`.
@@ -48,6 +50,8 @@ pub struct ObservationOptions {
impl Default for ObservationOptions {
fn default() -> Self {
Self {
output: OutputFormat::Text,
file: None,
variables: Vec::new(),
parameters: Vec::new(),
allow_text_values: false,
@@ -59,6 +63,20 @@ impl Default for ObservationOptions {
}
impl ObservationOptions {
pub fn enabled(&self) -> bool {
self.output != OutputFormat::Text || self.file.is_some()
}
pub fn has_capture_overrides(&self) -> bool {
let defaults = Self::default();
!self.variables.is_empty()
|| !self.parameters.is_empty()
|| self.allow_text_values
|| self.max_value_bytes != defaults.max_value_bytes
|| self.max_events != defaults.max_events
|| self.max_bytes != defaults.max_bytes
}
/// Typed host policy for this run.
pub fn config(&self) -> ObservationConfig {
ObservationConfig {
@@ -73,15 +91,15 @@ impl ObservationOptions {
}
}
/// One run's JSONL writer, shared with the host sink.
/// One run and event sequence, shared with the host observation sink.
#[derive(Clone)]
pub struct EventStream {
inner: Rc<RefCell<JsonlWriter>>,
pub struct ObservationSession {
inner: Rc<RefCell<EventWriter>>,
config: ObservationConfig,
}
impl EventStream {
/// Open the protocol channel and write `stream.opened` as `seq: 0`.
impl ObservationSession {
/// Set up all destinations and publish the first event.
pub fn open(options: &ObservationOptions) -> Result<Self, String> {
let run_id = new_run_id();
let config = options.config();
@@ -90,10 +108,6 @@ impl EventStream {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
},
"protocol": {
"name": SCHEMA,
"schema_version": SCHEMA_VERSION,
},
"observation": {
"level": config.level(),
"values": config.values_enabled(),
@@ -107,10 +121,15 @@ impl EventStream {
"max_value_bytes": config.max_value_bytes,
},
});
let mut writer = JsonlWriter {
out: Box::new(io::stdout()),
run_id: run_id.clone(),
let mut writer = EventWriter {
output: options.output,
snapshot: Snapshot::open(options)?,
run_id,
seq: 0,
source: Json::Null,
truncated: Json::Null,
capture: opened["observation"].clone(),
failed: false,
};
writer.emit("stream.opened", opened)?;
Ok(Self {
@@ -119,11 +138,6 @@ impl EventStream {
})
}
/// Opaque run identity shared with Trace v2 when both are requested.
pub fn run_id(&self) -> String {
self.inner.borrow().run_id.clone()
}
/// Typed policy (used to install the host sink).
pub fn config(&self) -> ObservationConfig {
self.config.clone()
@@ -163,40 +177,26 @@ impl EventStream {
)
}
/// Write the successful terminal event.
/// Write the successful terminal event and its explicitly returned result.
pub fn completed(&self, value: &Value) -> Result<(), String> {
let transferable = !value.contains_memory()
&& !value.contains_resource()
&& !marqdo_host::contains_plugin_handle(value);
let wire = transferable.then(|| marqdo_value::to_wire(value));
self.emit(
"run.completed",
json!({"status": "ok", "value": marqdo_value::to_wire(value)}),
json!({"status": "ok", "value": wire, "value_type": value.type_name()}),
)
}
/// Write the failed terminal event.
pub fn failed(&self, error: &RuntimeError) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {
"code": error.code(),
"message": error.message,
"module_id": error.module_id.as_deref(),
"span": error.span.map(span_json),
}
}),
)
pub fn failed(&self, error: Json) -> Result<(), String> {
self.emit("run.failed", json!({"status": "error", "error": error}))
}
/// Write a failed terminal event for a CLI-level failure that still has a
/// stable code (for example `cli.trace_failed`).
pub fn failed_error(&self, code: &str, message: &str) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {"code": code, "message": message},
}),
)
/// Deliver a snapshot without a terminal event when isolation interrupted a run.
pub fn incomplete(&self) -> Result<(), String> {
self.inner.borrow_mut().finish_snapshot("incomplete")
}
/// Write the pre-execution rejection terminal event.
@@ -220,7 +220,7 @@ impl EventStream {
/// `ObservationSink` adapter installed into `StdHost`.
pub struct HostEventSink {
stream: EventStream,
stream: ObservationSession,
}
impl ObservationSink for HostEventSink {
@@ -231,14 +231,105 @@ impl ObservationSink for HostEventSink {
}
}
struct JsonlWriter {
out: Box<dyn Write>,
run_id: String,
seq: u64,
struct Snapshot {
staging: tempfile::NamedTempFile,
path: Option<PathBuf>,
}
impl JsonlWriter {
impl Snapshot {
fn open(options: &ObservationOptions) -> Result<Option<Self>, String> {
if options.output != OutputFormat::Json && options.file.is_none() {
return Ok(None);
}
let staging = if let Some(path) = &options.file {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create observation directory: {error}"))?;
tempfile::NamedTempFile::new_in(parent)
} else {
tempfile::NamedTempFile::new()
}
.map_err(|error| format!("cannot stage observation snapshot: {error}"))?;
let mut snapshot = Self {
staging,
path: options.file.clone(),
};
snapshot.write(b"{\"events\":[")?;
Ok(Some(snapshot))
}
fn write(&mut self, bytes: &[u8]) -> Result<(), String> {
self.staging
.write_all(bytes)
.map_err(|error| format!("cannot write observation snapshot: {error}"))
}
fn finish(mut self, metadata: Json, stdout: bool) -> Result<(), String> {
let suffix = serde_json::to_vec(&metadata)
.map_err(|error| format!("cannot encode observation metadata: {error}"))?;
self.write(b"],")?;
self.write(&suffix[1..])?;
self.write(b"\n")?;
if let Some(path) = &self.path {
self.staging
.as_file()
.sync_all()
.map_err(|error| format!("cannot sync observation snapshot: {error}"))?;
let mut file = self
.staging
.persist(path)
.map_err(|error| format!("cannot publish observation snapshot: {error}"))?;
if stdout {
write_snapshot_stdout(&mut file)?;
}
} else {
write_snapshot_stdout(self.staging.as_file_mut())?;
}
Ok(())
}
}
fn write_snapshot_stdout(file: &mut std::fs::File) -> Result<(), String> {
let mut out = io::stdout().lock();
file.rewind()
.and_then(|()| io::copy(file, &mut out))
.and_then(|_| out.flush())
.map_err(|error| format!("cannot write observation snapshot to stdout: {error}"))
}
struct EventWriter {
output: OutputFormat,
snapshot: Option<Snapshot>,
run_id: String,
seq: u64,
source: Json,
truncated: Json,
capture: Json,
failed: bool,
}
impl EventWriter {
fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> {
if self.failed {
return Err("observation transport already failed".into());
}
let result = self.deliver(kind, payload);
if result.is_err() {
self.failed = true;
self.snapshot.take();
}
result
}
fn deliver(&mut self, kind: &str, payload: Json) -> Result<(), String> {
match kind {
"run.started" => self.source = payload["source"].clone(),
"observation.truncated" => self.truncated = payload.clone(),
_ => {}
}
let event = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
@@ -247,18 +338,78 @@ impl JsonlWriter {
"kind": kind,
"payload": payload,
});
let mut line = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode execution event: {error}"))?;
line.push(b'\n');
// Flush each line: line-buffered batching would hide real-time output
// behind the run duration (RFC-OBS-0001 §5.2).
self.out
.write_all(&line)
.and_then(|()| self.out.flush())
.map_err(|error| format!("cannot write execution event stream: {error}"))?;
let mut bytes = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode observation event: {error}"))?;
if let Some(snapshot) = &mut self.snapshot {
if self.seq != 0 {
snapshot.write(b",")?;
}
snapshot.write(&bytes)?;
}
if matches!(kind, "run.completed" | "run.failed" | "run.rejected") {
self.finish_snapshot(payload["status"].as_str().expect("terminal status"))?;
}
if self.output == OutputFormat::Jsonl {
let mut out = io::stdout().lock();
bytes.push(b'\n');
out.write_all(&bytes)
.and_then(|()| out.flush())
.map_err(|error| format!("cannot write observation stream: {error}"))?;
}
self.seq += 1;
Ok(())
}
fn finish_snapshot(&mut self, status: &str) -> Result<(), String> {
let Some(snapshot) = self.snapshot.take() else {
return Ok(());
};
let mut capture = self.capture.clone();
capture["truncated"] = self.truncated.clone();
snapshot.finish(
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": self.run_id, "status": status, "source": self.source},
"capture": capture,
}),
self.output == OutputFormat::Json,
)
}
}
/// The strict supervisor forwards only a complete current snapshot.
pub fn is_complete_snapshot(bytes: &[u8], exit_code: i32) -> bool {
let Ok(snapshot) = serde_json::from_slice::<Json>(bytes) else {
return false;
};
let Some(events) = snapshot["events"].as_array() else {
return false;
};
let Some(run_id) = snapshot["run"]["id"].as_str() else {
return false;
};
let Some(last) = events.last() else {
return false;
};
let status = match last["kind"].as_str() {
Some("run.completed") if exit_code == 0 => "ok",
Some("run.failed") if exit_code != 0 => "error",
Some("run.rejected") if exit_code != 0 => "rejected",
_ => return false,
};
snapshot["schema"] == SCHEMA
&& snapshot["schema_version"] == SCHEMA_VERSION
&& snapshot["run"]["status"] == status
&& snapshot["capture"].is_object()
&& last["payload"]["status"] == status
&& events[0]["kind"] == "stream.opened"
&& events.iter().enumerate().all(|(seq, event)| {
event["schema"] == SCHEMA
&& event["schema_version"] == SCHEMA_VERSION
&& event["run_id"] == run_id
&& event["seq"] == seq
})
}
fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
@@ -365,6 +516,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
}),
),
ObservationEvent::Effect {
frame_id,
operation,
result_code,
module_id,
@@ -372,6 +524,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
} => (
"effect",
json!({
"frame_id": frame_id.map(FrameId::as_wire),
"operation": operation,
"result_code": result_code,
"module_id": module_id,
+1 -1
View File
@@ -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 {
-144
View File
@@ -1,144 +0,0 @@
//! Public Trace v2 writer (spec/trace-v2.md).
//!
//! Events come from the interpreter (semantic) and the capability host
//! (effects). No argument values, secrets or handles are recorded.
use std::path::Path;
use marqdo_host::{Host, SemanticEvent, StdHost, TraceEntry};
use serde_json::{json, Value};
use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.trace";
pub const SCHEMA_VERSION: u32 = 2;
/// Write a trace atomically for one run.
pub fn write(
project: &LoadedProject,
host: &StdHost,
entry: &str,
status: &str,
path: &Path,
run_id: Option<&str>,
) -> Result<(), String> {
// A combined `--event-stream` run shares the CLI-generated opaque run id
// with Execution Events v1; Trace v2 keeps its schema and field types.
let run_id = run_id.map(str::to_string).unwrap_or_else(|| {
format!(
"{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
)
});
let analysis_digest = crate::analysis::digest(project);
let root_id = project.identity.root_id();
let state = host.trace_state();
let mut events: Vec<Value> = host
.semantic_events()
.iter()
.map(semantic_json)
.chain(host.trace().iter().map(effect_json))
.collect();
events.sort_by_key(|event| event.get("seq").and_then(Value::as_u64).unwrap_or(u64::MAX));
let mut truncation = state.truncation.clone();
let max_bytes = state.budget.max_bytes;
let bytes = loop {
let mut all = events.clone();
if let Some(truncation) = &truncation {
let seq = all
.last()
.and_then(|event| event.get("seq"))
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1;
all.push(json!({
"seq": seq,
"kind": "trace.truncated",
"module_id": null,
"span": null,
"detail": truncation.reason,
}));
}
let trace = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": run_id, "entry": entry, "status": status},
"source": {
"root_id": root_id,
"analysis_digest": format!("sha256:{analysis_digest}"),
},
"limits": {
"max_events": state.budget.max_events,
"max_bytes": state.budget.max_bytes,
},
"truncated": truncation,
"events": all,
});
let bytes = serde_json::to_vec_pretty(&trace)
.map_err(|error| format!("cannot encode trace: {error}"))?;
if max_bytes == 0 || bytes.len() <= max_bytes || events.is_empty() {
break bytes;
}
events.pop();
if truncation.is_none() {
truncation = Some(marqdo_host::TraceTruncation {
reason: "byte_budget".to_string(),
limit: max_bytes as u64,
written: events.len() as u64,
});
}
};
atomic_write(path, &bytes)
}
fn semantic_json(event: &SemanticEvent) -> Value {
json!({
"seq": event.seq,
"kind": event.kind,
"function_id": event.function_id,
"module_id": event.module_id,
"span": event.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": event.detail,
})
}
fn effect_json(entry: &TraceEntry) -> Value {
json!({
"seq": entry.seq,
"kind": "effect",
"module_id": entry.module,
"span": entry.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": entry.result,
"operation": entry.op,
"duration_micros": entry.duration_micros,
})
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?;
let temporary = parent.join(format!(
".{}.tmp-{}",
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "trace.json".to_string()),
std::process::id()
));
std::fs::write(&temporary, bytes)
.map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("cannot publish `{}`: {error}", path.display()));
}
Ok(())
}
@@ -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);
}
}
+11 -7
View File
@@ -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(),
);
+22 -10
View File
@@ -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"));
+15 -3
View File
@@ -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");
+102 -52
View File
@@ -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]
@@ -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);
+47 -12
View File
@@ -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");
}
+2 -2
View File
@@ -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"),
+48 -29
View File
@@ -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("<missing error code>")
observation::terminal(report)["error"]["code"]
.as_str()
.expect("terminal error code")
.to_string()
}
fn map_field<'a>(report: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
&report["value"]["entries"][name]
&observation::terminal(report)["value"]["entries"][name]
}
fn cc_available() -> bool {
@@ -469,7 +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}"
+69 -27
View File
@@ -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);
+8 -3
View File
@@ -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");
+86 -27
View File
@@ -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"
);
}
+8 -3
View File
@@ -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<serde_json::Value> {
#[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!(["分数"]));
+58
View File
@@ -0,0 +1,58 @@
//! Helpers for black-box tests that inspect values or committed program bytes.
use serde_json::Value;
pub fn terminal(snapshot: &Value) -> &Value {
assert_eq!(snapshot["schema"], "marqdo.observation");
let event = snapshot["events"].as_array().unwrap().last().unwrap();
assert!(matches!(
event["kind"].as_str(),
Some("run.completed" | "run.failed" | "run.rejected")
));
&event["payload"]
}
pub fn text(snapshot: &Value, channel: &str) -> String {
let bytes = snapshot["events"]
.as_array()
.unwrap()
.iter()
.filter(|event| event["kind"] == channel)
.flat_map(|event| {
let payload = &event["payload"];
let bytes = base64_decode(payload["data_base64"].as_str().unwrap());
assert_eq!(payload["byte_count"], bytes.len());
bytes
})
.collect();
String::from_utf8(bytes).unwrap()
}
fn base64_decode(text: &str) -> Vec<u8> {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::new();
let bytes: Vec<u8> = text
.bytes()
.filter(|byte| *byte != b'=')
.map(|byte| {
ALPHABET
.iter()
.position(|item| *item == byte)
.unwrap_or_else(|| panic!("invalid base64 byte {byte}")) as u8
})
.collect();
for chunk in bytes.chunks(4) {
let mut triple = 0u32;
for (index, byte) in chunk.iter().enumerate() {
triple |= u32::from(*byte) << (18 - 6 * index);
}
out.push((triple >> 16) as u8);
if chunk.len() > 2 {
out.push((triple >> 8) as u8);
}
if chunk.len() > 3 {
out.push(triple as u8);
}
}
out
}
+26 -16
View File
@@ -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]);