Files
marqdo-cli/crates/cli/src/commands/run.rs
T
cflmy 99789616a4 analysis: project document and program facts through one typed encoder
Replace the program-only projection with ADR-0069's typed model: exact source
and digest, the public document AST, complete heading scopes with parent/mode
origin/range, anchors, functions, imports, references, calls and resources.
Project identity now carries the entry, captured manifest/lock digests, stdlib
and the static extension identities that participated in preparation. Run and
call bind Observation to the same canonical bytes, inspect reuses the same AST,
unit and reference projectors, and the retired duplicate link resolver is
deleted. Emit refuses to overwrite inputs, directories, symlinks or hard links
and publishes through an owner-only exclusive temporary file.
2026-11-25 10:12:07 +08:00

596 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `marqdo run` execution assembly.
//!
//! Child module of `commands`: it may use the parent's project loader and
//! runtime helpers, but keeps the run session out of the command table.
use super::*;
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: Result<Vec<(String, Value)>, String>,
settings: &SandboxSettings,
observation: &ObservationOptions,
) -> i32 {
if !observation.enabled() && observation.has_capture_overrides() {
eprintln!(
"error: capture options require --output json, --output jsonl or --observation-file"
);
return 2;
}
// Strict runs project code under the isolation supervisor, which owns
// stdout. A live JSONL stream or a file destination would bypass that
// supervisor, so reject the destination before any session is opened: an
// unsupported destination must never produce a partial stream.
if settings.mode == "strict"
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some())
{
return fail(
None,
"strict",
"strict.unsupported_grant",
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
2,
);
}
// Open before preparation so option, compile and authorization failures
// can still publish a rejection on the requested observation destination.
let events = if observation.enabled() {
match ObservationSession::open(observation) {
Ok(events) => Some(events),
Err(error) => return transport_failure(&error),
}
} else {
None
};
let stream = events.as_ref();
let named_args = match named_args {
Ok(args) => args,
Err(message) => return fail(stream, "options", "cli.invalid_argument", &message, 2),
};
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
let prepared = match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, "prepare", &error),
};
if prepared.loaded.has_errors() {
if let Some(stream) = stream {
let code = prepared
.loaded
.diagnostics
.iter()
.find(|item| item.diagnostic.is_error())
.map(|item| item.diagnostic.code.clone())
.unwrap_or_else(|| "cli.compile_error".to_string());
if let Err(error) = stream.rejected(
"compile",
&code,
"refusing to run a project with compile errors",
) {
return transport_failure(&error);
}
}
eprint!("{}", output::render_text(&prepared.loaded.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
return 1;
}
// Bind the Observation snapshot to the exact bytes of the ordinary
// Analysis for these static options. Build it before moving the prepared
// program apart, but only when an observation destination is requested.
let analysis_digest = if stream.is_some() {
match crate::analysis::digest(&prepared) {
Ok(digest) => Some(digest),
Err(error) => return fail(stream, "prepare", "cli.analysis_failed", &error, 1),
}
} else {
None
};
let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded;
let static_plugins = prepared.plugins;
let warnings: Vec<FileDiagnostic> = project
.diagnostics
.iter()
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
return fail(stream, "authorization", "cli.invalid_mode", &error, 2);
}
};
// A project-declared extension is activation, not authorization, but it is
// still third-party executable code. `pure`/`strict` never activate it.
if !extension_sources.is_empty() && mode != SandboxMode::Project {
let code = if mode == SandboxMode::Strict {
"strict.unsupported_grant"
} else {
"cli.invalid_grants"
};
let message = format!(
"this project declares {} extension activation source(s) in {}; \
--mode {} cannot activate third-party extensions. Use --mode project \
with explicit grants, or remove the extensions block",
extension_sources.len(),
marqdo_package::MANIFEST_FILE,
settings.mode
);
return fail(stream, "authorization", code, &message, 2);
}
let mut kernel_paths = settings.kernels.clone();
kernel_paths.extend(
extension_sources
.iter()
.filter(|extension| extension.kind == marqdo_package::ExtensionKind::Kernel)
.map(|extension| extension.path.clone()),
);
kernel_paths.sort();
kernel_paths.dedup();
let mut provider_paths = settings.providers.clone();
provider_paths.extend(
extension_sources
.iter()
.filter(|extension| extension.kind == marqdo_package::ExtensionKind::Provider)
.map(|extension| extension.path.clone()),
);
provider_paths.sort();
provider_paths.dedup();
if mode == SandboxMode::Strict {
if let Err(error) = settings.strict_preflight() {
return fail(stream, "strict", "strict.unsupported_grant", &error, 2);
}
match marqdo_sandbox::inspect_strict_child() {
// A verified supervisor child may run project code.
Ok(StrictChildState::VerifiedChild) => {}
// Not a child: enforce capability and launch under the supervisor.
Ok(StrictChildState::NotChild) => {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(stream, "strict", error.code(), &error.to_string(), 1);
}
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, "strict", "strict.identity_invalid", &message, 1);
}
}
}
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(
stream,
"authorization",
"sandbox.unavailable",
&error.to_string(),
1,
);
}
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
return fail(stream, "authorization", "cli.invalid_grants", &error, 2);
}
};
let stdin = read_stdin();
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
if let Some(stream) = stream {
host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
if let Some(stack) = settings.stack {
host.budget.stack_limit = stack;
}
if let Some(max_output) = settings.max_output {
host.budget.max_output_bytes = max_output;
}
if let Some(timeout) = settings.timeout {
host.budget.deadline = Some(Instant::now() + Duration::from_secs(timeout));
}
for kernel_path in &kernel_paths {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
return fail(stream, "prepare", "ext.kernel_load_failed", &error, 2);
}
}
// T6: verify every selected artifact/path/hash before starting a worker or
// loading native code. Static path/signature checks happened in `prepare`.
//
// Provider selection is host assembly, not callable semantics: `check`
// never sees it. Parse and verify every `--provider` manifest, resolve the
// current target artifact, check the exact grant and reject duplicate
// names/kinds *before* any provider or plugin worker process is spawned
// (RFC-EXT-0001 §5.4.6/§18.2 T6–T7).
let providers = match provider_manifest::read_provider_manifests(&provider_paths) {
Ok(providers) => providers,
Err(error) => {
return fail_prepare(stream, "prepare", &error);
}
};
// `--provider` alone never authorizes; the exact `--allow-provider NAME`
// is required before the helper process may be started. An ungranted
// provider fails closed instead of being silently ignored.
for provider in &providers {
if !settings
.allow_provider
.iter()
.any(|grant| grant == &provider.name)
{
let error = extension_descriptors::PrepareError::load(
"permission.denied",
format!(
"resource provider `{}` was selected with --provider but is not granted; \
add --allow-provider {}",
provider.name, provider.name
),
);
return fail_prepare(stream, "authorization", &error);
}
}
// A grant that matches no selected provider is a deterministic option
// error: providers are never discovered from PATH, the working directory or
// the network.
for grant in &settings.allow_provider {
if !providers.iter().any(|provider| &provider.name == grant) {
let error = extension_descriptors::PrepareError::option(
"ext.provider_grant_unmatched",
format!(
"--allow-provider `{grant}` matches no selected --provider manifest; \
providers are never discovered automatically"
),
);
return fail_prepare(stream, "authorization", &error);
}
}
for plugin in &static_plugins.plugins {
if let Err(error) = extension_descriptors::verify_bundle_regular_file(
&plugin.base_dir,
&plugin.artifact_relative,
) {
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, "authorization", &error);
}
}
// An in-process native plugin can write directly to the inherited fds.
// Require a controlled channel before publishing observed program bytes.
if stream.is_some()
&& static_plugins
.plugins
.iter()
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native)
{
return fail(
stream,
"authorization",
"ext.observation_unsupported_native_plugin",
"observation requires a controlled output channel; use a worker plugin or text output without a snapshot",
2,
);
}
// T7: start only selected, granted and verified extensions.
for plugin in &static_plugins.plugins {
if let Err(message) = load_plugin_into_host(
&mut host,
&plugin.manifest_path,
settings.trust_native_plugin,
) {
return fail(
stream,
"authorization",
"ext.plugin_load_failed",
&message,
1,
);
}
}
// T8: exact one-to-one reconciliation with the static descriptors. Never
// synthesise a missing signature (`params: Vec::new()`) or guess an export.
if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) {
return fail(
stream,
"authorization",
"ext.plugin_binding_mismatch",
&message,
1,
);
}
// T7b: start only granted and verified provider helpers. Every manifest,
// artifact, target, grant and duplicate-kind check above already passed, so
// no worker is spawned for a provider that failed verification.
for provider in &providers {
if let Err(error) = provider_manifest::load_resource_provider_into_host(
&mut host,
provider,
&settings.allow_provider,
) {
return fail_prepare(stream, "prepare", &error);
}
}
let function_name = function.unwrap_or("main").to_string();
let entry_module = &project.program.modules[&project.entry];
if entry_module.function(&function_name).is_none() {
let message = if function.is_none() {
format!(
"{} has no callable `main`; declare an Exec H2 (`## @exec main`) or pass an \
explicit function name",
project.entry_file().path.display()
)
} else {
format!(
"no function named `{function_name}` in {}",
project.entry_file().path.display()
)
};
return fail(stream, "compile", "sem.no_entry_function", &message, 1);
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
.map(|(name, value)| EvaluatedArg::named(name.clone(), value.clone(), Span::default()))
.collect();
let memory_limits = MemoryLimits {
max_total_bytes: settings
.max_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_TOTAL_BYTES),
max_region_bytes: settings
.max_region_memory
.unwrap_or(marqdo_runtime::DEFAULT_MAX_REGION_BYTES),
};
if let Some(stream) = stream {
let entry = format!("{}::{}", project.entry, function_name);
let analysis_digest = analysis_digest.as_deref().unwrap_or_default();
if let Err(error) = stream.started(
&entry,
mode.as_str(),
&project.identity.root_id(),
analysis_digest,
) {
return transport_failure(&error);
}
}
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
&function_name,
runtime_args,
memory_limits,
);
if let Some(stream) = stream {
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);
}
}
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());
}
}
}
match result {
Ok(_) => 0,
Err(error) => {
eprint!("{}", render_runtime_error(&error, &project));
1
}
}
}
pub(super) fn transport_failure(error: &str) -> i32 {
eprintln!("error[observe.transport_failed]: {error}");
1
}
/// Report a failure before the interpreter starts.
pub(super) fn fail(
stream: Option<&ObservationSession>,
phase: &str,
code: &str,
message: &str,
exit: i32,
) -> i32 {
if let Some(stream) = stream {
if let Err(error) = stream.rejected(phase, code, message) {
return transport_failure(&error);
}
}
eprintln!("error[{code}]: {message}");
exit
}
fn fail_prepare(
stream: Option<&ObservationSession>,
phase: &str,
error: &crate::extension_descriptors::PrepareError,
) -> i32 {
fail(stream, phase, &error.code, &error.message, error.exit_code)
}
/// Compare the Host's actual plugin exports with the static manifest set.
///
/// Names, raw signatures, owners and verified artifact digests must match
/// exactly; extra, missing or altered exports fail closed with
/// `ext.plugin_binding_mismatch` and the main function never runs.
fn reconcile_plugin_exports(
static_plugins: &StaticPluginSet,
host: &StdHost,
) -> Result<(), String> {
let mut expected: std::collections::BTreeMap<String, (String, String, String)> =
std::collections::BTreeMap::new();
for plugin in &static_plugins.plugins {
for export in &plugin.exports {
expected.insert(
export.name.clone(),
(
export.signature.clone(),
plugin.artifact_sha256.clone(),
plugin.package.clone(),
),
);
}
}
let loaded = host.plugin_exports();
if loaded.len() != expected.len() {
return Err(format!(
"static plugin descriptors declare {} export(s) but the runtime loaded {}; \
refusing to execute",
expected.len(),
loaded.len()
));
}
for (name, signature, digest, package) in loaded {
let Some((expected_signature, expected_digest, expected_package)) = expected.get(&name)
else {
return Err(format!(
"runtime export `{name}` was not declared by any selected plugin manifest"
));
};
if &signature != expected_signature {
return Err(format!(
"export `{name}` signature mismatch: manifest `{expected_signature}`, runtime `{signature}`"
));
}
if &digest != expected_digest {
return Err(format!(
"export `{name}` artifact digest mismatch: manifest `{expected_digest}`, runtime `{digest}`"
));
}
if &package != expected_package {
return Err(format!(
"export `{name}` owner mismatch: manifest `{expected_package}`, runtime `{package}`"
));
}
}
Ok(())
}
/// Read piped stdin once at the composition boundary.
///
/// A terminal stdin is not read, so `marqdo run` never blocks waiting for an
/// interactive EOF. Non-terminal input is a finite pipe/file and is copied into
/// the run-scoped `stdio/stdin` resource.
fn read_stdin() -> Vec<u8> {
use std::io::{IsTerminal, Read};
let mut stdin = std::io::stdin();
if stdin.is_terminal() {
return Vec::new();
}
let mut bytes = Vec::new();
if let Err(error) = stdin.read_to_end(&mut bytes) {
eprintln!("error: cannot read stdin: {error}");
return Vec::new();
}
bytes
}
#[cfg(test)]
mod tests {
use super::*;
fn empty_host() -> StdHost {
StdHost::new(
SandboxMode::Project,
marqdo_host::Capabilities::pure(),
std::env::temp_dir(),
)
}
fn static_plugin_with_export() -> StaticPluginSet {
let descriptor = marqdo_ir::callable::CallableDescriptor {
id: marqdo_ir::callable::CallableId("plugin:demo.ext:solver.add".into()),
public_name: "solver.add".into(),
owner_package: "demo.ext".into(),
signature: marqdo_ir::callable::CallableSignature {
params: vec![
marqdo_ir::Param {
name: "a".into(),
span: Span::default(),
type_annotation: None,
default: None,
},
marqdo_ir::Param {
name: "b".into(),
span: Span::default(),
type_annotation: None,
default: None,
},
],
kind: marqdo_ir::SignatureKind::Explicit,
},
effects_requested: vec!["math.compute".into()],
origin: marqdo_ir::callable::CallableOrigin::AbiPlugin {
package: "demo.ext".into(),
export: "solver.add".into(),
},
implementation_digest: Some("a".repeat(64)),
source_span: None,
};
StaticPluginSet {
plugins: vec![crate::extension_descriptors::StaticPlugin {
manifest_path: PathBuf::from("/fixtures/demo/plugin.yaml"),
base_dir: PathBuf::from("/fixtures/demo"),
package: "demo.ext".into(),
version: "0.1.0".into(),
kind: marqdo_plugin_abi::PluginKind::Worker,
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
artifact_target: marqdo_plugin_abi::HostTarget::current()
.triple()
.to_string(),
artifact_sha256: "a".repeat(64),
artifact_relative: "build/plugin.so".into(),
exports: vec![crate::extension_descriptors::StaticPluginExport {
name: "solver.add".into(),
signature: "($a: Int, $b: Int) -> Int".into(),
descriptor,
}],
requires: Vec::new(),
}],
}
}
#[test]
fn reconcile_accepts_matching_empty_sets() {
assert!(
reconcile_plugin_exports(&StaticPluginSet::default(), &empty_host()).is_ok(),
"no selected plugin and no loaded plugin must reconcile"
);
}
#[test]
fn reconcile_rejects_missing_runtime_exports() {
let error = reconcile_plugin_exports(&static_plugin_with_export(), &empty_host())
.expect_err("a declared export that the runtime did not load must fail closed");
assert!(
error.contains("declare 1 export(s)") || error.contains("not declared"),
"{error}"
);
}
}