RFC-GPL-0004: enforce core boundaries and frozen external conformance #5

Merged
cflmy merged 5 commits from rfc-gpl-0004 into master 2026-11-22 20:48:12 +08:00
21 changed files with 1210 additions and 753 deletions

No files matched your search

+28 -3
View File
@@ -183,9 +183,33 @@ jobs:
assert document["code"] == "strict.probe_unavailable", document
PY
frozen-extensions:
name: frozen Linux archive and external extensions
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build and check the frozen archive
shell: bash
run: |
set -euo pipefail
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
- uses: actions/upload-artifact@v4
with:
name: frozen-extension-evidence-${{ github.sha }}
path: dist/frozen-extension-evidence.json
if-no-files-found: error
release-evidence:
name: release evidence manifest
needs: [test, schema, cross-platform]
needs: [test, schema, cross-platform, frozen-extensions]
if: always()
runs-on: ubuntu-latest
steps:
@@ -197,6 +221,7 @@ jobs:
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
LINUX_RESULT: ${{ needs.test.result }}
SCHEMA_RESULT: ${{ needs.schema.result }}
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
PORTABLE_RESULT: ${{ needs.cross-platform.result }}
run: |
set -euo pipefail
@@ -209,7 +234,7 @@ jobs:
}
linux="$(state "$LINUX_RESULT")"
portable="$(state "$PORTABLE_RESULT")"
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ]; then
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
linux="FAIL"
fi
python3 tools/ci/release_evidence.py --target-sha "$TARGET_SHA" --out "docs/evidence/ci/$TARGET_SHA/manifest.json" --gate "linux=$linux:$TARGET_SHA:$RUN_URL" --gate "windows=$portable:$TARGET_SHA:$RUN_URL" --gate "macos=$portable:$TARGET_SHA:$RUN_URL" --gate "strict_vm=UNVERIFIED::${{ github.server_url }}/${{ github.repository }}/actions/workflows/security-linux.yml" --gate "performance=UNVERIFIED::"
@@ -235,7 +260,7 @@ jobs:
release-candidate:
name: release candidate artifact (${{ matrix.os }})
needs: [test, schema, cross-platform]
needs: [test, schema, cross-platform, frozen-extensions]
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
strategy:
fail-fast: false
+4
View File
@@ -36,6 +36,8 @@ steps:
image: rust:1.100-bookworm
depends_on: [test]
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 build-essential
# Release archives must ship both binaries: the provider worker is the
# only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
@@ -48,3 +50,5 @@ steps:
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
cat dist/frozen-extension-evidence.json
+32
View File
@@ -569,3 +569,35 @@ fn dispatch() -> i32 {
}
}
}
#[cfg(test)]
#[test]
fn top_level_commands_are_reviewed() {
use clap::CommandFactory;
let cli = Cli::command();
let mut names: Vec<_> = cli
.get_subcommands()
.map(|command| command.get_name())
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"__plugin-worker",
"add",
"call",
"check",
"fmt",
"init",
"inspect",
"lock",
"plugin",
"remove",
"run",
"sync",
"tool"
],
"review changes under ADR-0064"
);
}
+116 -116
View File
@@ -314,26 +314,90 @@ fn callable_binding_is_the_only_static_resolution_path() {
);
}
/// RFC-EXT-0001 §14.2/S4: no business-domain builtin or host-op branch may be
/// added for an ecosystem feature. These must be implemented as `.mq.md`,
/// plugin exports or provider streams.
/// ADR-0064 freezes the core catalogue until a new language primitive is reviewed.
#[test]
fn no_business_domain_builtins_or_host_ops() {
let root = repo_root();
let builtins = read(&root.join("crates/marqdo-ir/src/builtins.rs"));
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
for forbidden in ["quantum.", "ai.chat", "vendor.", "demo.sensor", "marqdo."] {
assert!(
!builtins.contains(forbidden),
"business builtin namespace `{forbidden}` must not exist"
);
}
assert!(
!host.contains("\"demo.sensor\""),
"provider kinds must be data, not host-op string branches"
fn builtin_names_and_aliases_are_reviewed() {
let builtins = marqdo_ir::builtins::BUILTINS;
let mut names: Vec<_> = builtins
.iter()
.flat_map(|builtin| std::iter::once(builtin.name).chain(builtin.aliases.iter().copied()))
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"float",
"foreign.call",
"foreign.run",
"fs.read",
"fs.write",
"int",
"len",
"list.append",
"list.concat",
"map.get",
"map.has",
"map.keys",
"map.remove",
"map.set",
"memory.grow",
"memory.new",
"memory.size",
"print",
"ref",
"resource.accept",
"resource.close",
"resource.open",
"resource.read",
"resource.request",
"resource.write",
"str",
"table",
"table.cell",
"table.columns",
"table.row",
"text.codepoints",
"text.from_codepoint",
"type",
"小数",
"打印",
"整数",
"文本",
"类型",
"表",
"长度",
],
"review changes under ADR-0064"
);
}
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
const _: fn(marqdo_host::HostOp) = |operation| match operation {
marqdo_host::HostOp::ForeignRun
| marqdo_host::HostOp::ForeignCall
| marqdo_host::HostOp::FsRead
| marqdo_host::HostOp::FsWrite
| marqdo_host::HostOp::PluginInvoke => (),
};
const _: fn(marqdo_value::Value) = |value| match value {
marqdo_value::Value::Unit
| marqdo_value::Value::None
| marqdo_value::Value::Bool(_)
| marqdo_value::Value::Int(_)
| marqdo_value::Value::Float(_)
| marqdo_value::Value::Text(_)
| marqdo_value::Value::List(_)
| marqdo_value::Value::Map(_)
| marqdo_value::Value::Table(_)
| marqdo_value::Value::Formula(_)
| marqdo_value::Value::Code(_)
| marqdo_value::Value::FunctionRef(_)
| marqdo_value::Value::PluginHandle(_)
| marqdo_value::Value::Memory(_)
| marqdo_value::Value::Resource(_) => (),
};
/// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not
/// hard-coded runtime names. Recompute the canonical metadata digest.
#[test]
@@ -386,110 +450,46 @@ fn official_stdlib_public_aliases_are_verified_metadata() {
}
}
/// Reviewed ownership of every `Host::resource_request` operation
/// (`docs/architecture/resource-operations.md`, ADR-0062).
///
/// The gate extracts the literal operation names dispatched inside
/// `resource_request` and compares them with this reviewed allowlist. Adding a new
/// domain operation requires updating the architecture doc, the ADR and this list —
/// a bare source change cannot silently widen the core/resource boundary.
/// The outer match in the compatibility dispatcher is the operation catalogue.
#[test]
fn resource_request_operation_allowlist_is_reviewed() {
use std::collections::BTreeSet;
const DOMAIN_OPERATIONS: &[&str] = &[
"process.run",
"regex.match",
"regex.captures",
"compress.gzip",
"compress.gunzip",
"random.bytes",
"env.get",
"clock.now",
];
const FS_OPERATIONS: &[&str] = &[
"read_at", "append", "walk", "exists", "metadata", "list", "mkdir", "remove", "rename",
];
let source = read(&repo_root().join("crates/marqdo-host/src/host.rs"));
let impl_start = source
.find("impl Host for StdHost {")
.expect("StdHost must implement Host");
let start = source[impl_start..]
.find(" fn resource_request(")
.expect("StdHost::resource_request must exist")
+ impl_start;
let rest = &source[start + 1..];
let end = rest
.find("\n fn consume_fuel(")
.expect("resource_request must end before consume_fuel");
let body = &rest[..end];
let mut domain = BTreeSet::new();
for line in body.lines() {
let mut cursor = line;
while let Some(index) = cursor.find("operation == \"") {
let text = &cursor[index + "operation == \"".len()..];
let name = text.split('"').next().expect("operation literal");
domain.insert(name.to_string());
cursor = &text[name.len()..];
}
}
let expected_domain: BTreeSet<String> = DOMAIN_OPERATIONS
.iter()
.map(|name| (*name).to_string())
let source = read(&repo_root().join("crates/marqdo-host/src/host/resource_requests.rs"));
let dispatch = source
.split_once(" match operation {\n")
.expect("closed operation dispatch")
.1
.split_once("\n _ =>")
.expect("unknown operations must reach a rejection arm")
.0;
let mut names: Vec<_> = dispatch
.lines()
.filter_map(|line| line.strip_prefix(" "))
.filter(|line| line.starts_with('"') || line.starts_with('|'))
.flat_map(|line| line.split('"').skip(1).step_by(2))
.collect();
names.sort_unstable();
assert_eq!(
domain, expected_domain,
"new/changed resource_request domain operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist"
);
assert!(
body.contains("strip_prefix(\"fs.\")"),
"the fs.* operation group must stay the only unprefixed dispatch path"
);
let mut fs = BTreeSet::new();
for line in body.lines() {
let mut cursor = line;
while let Some(index) = cursor.find("name == \"") {
let text = &cursor[index + "name == \"".len()..];
let name = text.split('"').next().expect("fs operation literal");
fs.insert(name.to_string());
cursor = &text[name.len()..];
}
}
// The remaining fs operations are grouped in the arity match block.
let arity_start = body
.find("let expected = match name {")
.expect("fs arity match block");
let arity_end = body[arity_start..]
.find(" };")
.expect("fs arity match block end");
for line in body[arity_start..arity_start + arity_end].lines() {
let Some(arrow) = line.find("=>") else {
continue;
};
let mut in_quote = false;
let mut name = String::new();
for ch in line[..arrow].chars() {
if ch == '"' {
if in_quote && !name.is_empty() {
fs.insert(name.clone());
}
name.clear();
in_quote = !in_quote;
} else if in_quote {
name.push(ch);
}
}
}
let expected_fs: BTreeSet<String> = FS_OPERATIONS
.iter()
.map(|name| (*name).to_string())
.collect();
assert_eq!(
fs, expected_fs,
"new/changed fs.* resource operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist"
names,
[
"clock.now",
"compress.gunzip",
"compress.gzip",
"env.get",
"fs.append",
"fs.exists",
"fs.list",
"fs.metadata",
"fs.mkdir",
"fs.read_at",
"fs.remove",
"fs.rename",
"fs.walk",
"process.run",
"random.bytes",
"regex.captures",
"regex.match",
],
"review changes under ADR-0062 and ADR-0064"
);
}
+3 -613
View File
@@ -5,10 +5,9 @@
//! execution, not at parse/compile time.
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::time::{Duration, Instant};
use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
@@ -39,6 +38,7 @@ mod dispatch;
mod effects;
mod providers;
mod resource_ops;
mod resource_requests;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -751,14 +751,6 @@ impl StdHost {
}
}
fn result_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
impl Host for StdHost {
fn invoke(
&mut self,
@@ -911,609 +903,7 @@ impl Host for StdHost {
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource operations are available only in project mode",
));
}
if args.iter().any(Value::contains_memory) || args.iter().any(Value::contains_resource) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"resource operations accept only Text path arguments",
));
}
if operation == "process.run" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `process.run` expects 2 arguments, got {}",
args.len()
),
));
}
let program_type = args[0].type_name();
let Value::Text(program) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a Text program, got {program_type}"
),
));
};
let args_type = args[1].type_name();
let Value::List(values) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a List of Text arguments, got {args_type}"
),
));
};
let mut program_args = Vec::with_capacity(values.len());
for value in values {
let value_type = value.type_name();
let Value::Text(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!("process arguments must be Text, got {value_type}"),
));
};
program_args.push(value);
}
self.capabilities.check_process(&program, ctx.span)?;
let result = crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
return Ok(result);
}
if operation == "regex.match" || operation == "regex.captures" {
if operation == "regex.match" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `regex.match` expects 2 arguments, got {}",
args.len()
),
));
}
} else if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `regex.captures` expects 2 arguments, got {}",
args.len()
),
));
}
let pattern_type = args[0].type_name();
let Value::Text(pattern) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} pattern must be Text, got {pattern_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} text must be Text, got {text_type}"),
));
};
let regex = match regex::Regex::new(&pattern) {
Ok(regex) => regex,
Err(error) => {
return Ok(result_error(
"regex.invalid",
&format!("invalid regular expression: {error}"),
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" {
map.insert("value".to_string(), Value::Bool(regex.is_match(&text)));
} else {
let mut payload = BTreeMap::new();
let captures = regex.captures(&text);
payload.insert("matched".to_string(), Value::Bool(captures.is_some()));
let groups = match captures {
Some(captures) => captures
.iter()
.map(|group| match group {
Some(group) => Value::text(group.as_str()),
None => Value::None,
})
.collect(),
None => Vec::new(),
};
payload.insert("groups".to_string(), Value::List(groups));
map.insert("value".to_string(), Value::Map(payload));
}
return Ok(Value::Map(map));
}
if operation == "compress.gzip" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gzip` expects 1 argument, got {}",
args.len()
),
));
}
let text_type = args[0].type_name();
let Value::Text(text) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gzip expects Text, got {text_type}"),
));
};
if text.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gzip input exceeds 8 MiB",
));
}
let mut encoder =
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(text.as_bytes()).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let bytes = encoder.finish().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
return Ok(Value::Map(map));
}
if operation == "compress.gunzip" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gunzip` expects 1 argument, got {}",
args.len()
),
));
}
let list_type = args[0].type_name();
let Value::List(values) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gunzip expects List<Int>, got {list_type}"),
));
};
if values.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gunzip input exceeds 8 MiB",
));
}
let mut bytes = Vec::with_capacity(values.len());
for value in values {
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
"compress.gunzip bytes must be Int",
));
};
let Some(byte) = value.to_string().parse::<u8>().ok() else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("`{value}` is not a byte in 0..=255"),
));
};
bytes.push(byte);
}
let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
let mut output = Vec::new();
if let Err(error) = decoder
.by_ref()
.take(8 * 1024 * 1024 + 1)
.read_to_end(&mut output)
{
return Ok(result_error(
"compress.invalid",
&format!("gunzip failed: {error}"),
));
}
if output.len() > 8 * 1024 * 1024 {
return Ok(result_error(
"compress.too_large",
"gunzip output exceeds 8 MiB",
));
}
let text = match String::from_utf8(output) {
Ok(text) => text,
Err(_) => {
return Ok(result_error(
"compress.not_utf8",
"gunzip output is not UTF-8",
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text));
return Ok(Value::Map(map));
}
if operation == "random.bytes" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `random.bytes` expects 1 argument, got {}",
args.len()
),
));
}
let count = match &args[0] {
Value::Int(value) => value
.to_string()
.parse::<usize>()
.ok()
.filter(|count| (1..=65536).contains(count)),
_ => None,
};
let Some(count) = count else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
"random.bytes requires an Int in 1..=65536",
));
};
self.capabilities.check_random(ctx.span)?;
let mut bytes = vec![0u8; count];
getrandom::fill(&mut bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("OS entropy is unavailable: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
return Ok(Value::Map(map));
}
if operation == "env.get" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `env.get` expects 1 argument, got {}",
args.len()
),
));
}
let value_type = args[0].type_name();
let Value::Text(name) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("resource operation `env.get` expects a Text name, got {value_type}"),
));
};
self.capabilities.check_env(&name, ctx.span)?;
let mut map = BTreeMap::new();
match std::env::var(&name) {
Ok(value) => {
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(value));
}
Err(std::env::VarError::NotPresent) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_found"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not set")),
);
}
Err(std::env::VarError::NotUnicode(_)) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_unicode"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not valid UTF-8")),
);
}
}
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
return Ok(Value::Map(map));
}
if operation == "clock.now" {
if !args.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `clock.now` expects 0 arguments, got {}",
args.len()
),
));
}
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("system clock is before the Unix epoch: {error}"),
)
})?
.as_millis()
.min(i64::MAX as u128) as i64;
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis));
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
return Ok(Value::Map(map));
}
let Some(name) = operation.strip_prefix("fs.") else {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("unsupported resource operation `{operation}`"),
));
};
if name == "read_at" {
if args.len() != 3 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.read_at` expects 3 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at path must be Text, got {path_type}"),
));
};
let offset = match &args[1] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at offset must be Int, got {}", other.type_name()),
))
}
};
let length = match &args[2] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at length must be Int, got {}", other.type_name()),
))
}
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self
.fs
.request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
return Ok(result);
}
if name == "append" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.append` expects 2 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append path must be Text, got {path_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append text must be Text, got {text_type}"),
));
};
self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
return Ok(result);
}
if name == "walk" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.walk` expects 1 argument, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.walk path must be Text, got {path_type}"),
));
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
return Ok(result);
}
let expected = match name {
"exists" | "metadata" | "list" | "mkdir" | "remove" => 1,
"rename" => 2,
other => {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("unsupported filesystem operation `{other}`"),
))
}
};
if args.len() != expected {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects {expected} argument(s), got {}",
args.len()
),
));
}
let mut paths = Vec::with_capacity(args.len());
for value in args {
let value_type = value.type_name();
let Value::Text(path) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `{operation}` expects Text paths, got {value_type}"
),
));
};
paths.push(path);
}
match name {
"exists" | "metadata" | "list" => {
self.capabilities.check_read(&paths[0], ctx.span)?;
}
"mkdir" | "remove" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
}
"rename" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
self.capabilities.check_write(&paths[1], ctx.span)?;
}
_ => unreachable!(),
}
let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect("resource.request", ctx, started, &format!("fs.{name}"));
Ok(result)
self.request_compatibility_operation(operation, args, ctx)
}
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
@@ -0,0 +1,626 @@
//! Closed compatibility catalogue for non-streaming resource operations (ADR-0062).
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value};
impl StdHost {
pub(super) fn request_compatibility_operation(
&mut self,
operation: &str,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource operations are available only in project mode",
));
}
if args.iter().any(Value::contains_memory) || args.iter().any(Value::contains_resource) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"resource operations accept only Text path arguments",
));
}
match operation {
"process.run" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `process.run` expects 2 arguments, got {}",
args.len()
),
));
}
let program_type = args[0].type_name();
let Value::Text(program) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a Text program, got {program_type}"
),
));
};
let args_type = args[1].type_name();
let Value::List(values) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a List of Text arguments, got {args_type}"
),
));
};
let mut program_args = Vec::with_capacity(values.len());
for value in values {
let value_type = value.type_name();
let Value::Text(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!("process arguments must be Text, got {value_type}"),
));
};
program_args.push(value);
}
self.capabilities.check_process(&program, ctx.span)?;
let result =
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
Ok(result)
}
"regex.match" | "regex.captures" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects 2 arguments, got {}",
args.len()
),
));
}
let pattern_type = args[0].type_name();
let Value::Text(pattern) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} pattern must be Text, got {pattern_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} text must be Text, got {text_type}"),
));
};
let regex = match regex::Regex::new(&pattern) {
Ok(regex) => regex,
Err(error) => {
return Ok(result_error(
"regex.invalid",
&format!("invalid regular expression: {error}"),
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" {
map.insert("value".to_string(), Value::Bool(regex.is_match(&text)));
} else {
let mut payload = BTreeMap::new();
let captures = regex.captures(&text);
payload.insert("matched".to_string(), Value::Bool(captures.is_some()));
let groups = match captures {
Some(captures) => captures
.iter()
.map(|group| match group {
Some(group) => Value::text(group.as_str()),
None => Value::None,
})
.collect(),
None => Vec::new(),
};
payload.insert("groups".to_string(), Value::List(groups));
map.insert("value".to_string(), Value::Map(payload));
}
Ok(Value::Map(map))
}
"compress.gzip" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gzip` expects 1 argument, got {}",
args.len()
),
));
}
let text_type = args[0].type_name();
let Value::Text(text) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gzip expects Text, got {text_type}"),
));
};
if text.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gzip input exceeds 8 MiB",
));
}
let mut encoder =
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(text.as_bytes()).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let bytes = encoder.finish().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
Ok(Value::Map(map))
}
"compress.gunzip" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gunzip` expects 1 argument, got {}",
args.len()
),
));
}
let list_type = args[0].type_name();
let Value::List(values) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gunzip expects List<Int>, got {list_type}"),
));
};
if values.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gunzip input exceeds 8 MiB",
));
}
let mut bytes = Vec::with_capacity(values.len());
for value in values {
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
"compress.gunzip bytes must be Int",
));
};
let Some(byte) = value.to_string().parse::<u8>().ok() else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("`{value}` is not a byte in 0..=255"),
));
};
bytes.push(byte);
}
let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
let mut output = Vec::new();
if let Err(error) = decoder
.by_ref()
.take(8 * 1024 * 1024 + 1)
.read_to_end(&mut output)
{
return Ok(result_error(
"compress.invalid",
&format!("gunzip failed: {error}"),
));
}
if output.len() > 8 * 1024 * 1024 {
return Ok(result_error(
"compress.too_large",
"gunzip output exceeds 8 MiB",
));
}
let text = match String::from_utf8(output) {
Ok(text) => text,
Err(_) => {
return Ok(result_error(
"compress.not_utf8",
"gunzip output is not UTF-8",
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text));
Ok(Value::Map(map))
}
"random.bytes" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `random.bytes` expects 1 argument, got {}",
args.len()
),
));
}
let count = match &args[0] {
Value::Int(value) => value
.to_string()
.parse::<usize>()
.ok()
.filter(|count| (1..=65536).contains(count)),
_ => None,
};
let Some(count) = count else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
"random.bytes requires an Int in 1..=65536",
));
};
self.capabilities.check_random(ctx.span)?;
let mut bytes = vec![0u8; count];
getrandom::fill(&mut bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("OS entropy is unavailable: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
Ok(Value::Map(map))
}
"env.get" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `env.get` expects 1 argument, got {}",
args.len()
),
));
}
let value_type = args[0].type_name();
let Value::Text(name) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `env.get` expects a Text name, got {value_type}"
),
));
};
self.capabilities.check_env(&name, ctx.span)?;
let mut map = BTreeMap::new();
match std::env::var(&name) {
Ok(value) => {
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(value));
}
Err(std::env::VarError::NotPresent) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_found"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not set")),
);
}
Err(std::env::VarError::NotUnicode(_)) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_unicode"));
map.insert(
"message".to_string(),
Value::text(format!(
"environment variable `{name}` is not valid UTF-8"
)),
);
}
}
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
Ok(Value::Map(map))
}
"clock.now" => {
if !args.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `clock.now` expects 0 arguments, got {}",
args.len()
),
));
}
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("system clock is before the Unix epoch: {error}"),
)
})?
.as_millis()
.min(i64::MAX as u128) as i64;
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis));
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
Ok(Value::Map(map))
}
"fs.read_at" => {
if args.len() != 3 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.read_at` expects 3 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at path must be Text, got {path_type}"),
));
};
let offset = match &args[1] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at offset must be Int, got {}", other.type_name()),
))
}
};
let length = match &args[2] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at length must be Int, got {}", other.type_name()),
))
}
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self
.fs
.request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
Ok(result)
}
"fs.append" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.append` expects 2 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append path must be Text, got {path_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append text must be Text, got {text_type}"),
));
};
self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
Ok(result)
}
"fs.walk" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.walk` expects 1 argument, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.walk path must be Text, got {path_type}"),
));
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
Ok(result)
}
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
let name = &operation["fs.".len()..];
let expected = if name == "rename" { 2 } else { 1 };
if args.len() != expected {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects {expected} argument(s), got {}",
args.len()
),
));
}
let mut paths = Vec::with_capacity(args.len());
for value in args {
let value_type = value.type_name();
let Value::Text(path) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `{operation}` expects Text paths, got {value_type}"
),
));
};
paths.push(path);
}
match name {
"exists" | "metadata" | "list" => {
self.capabilities.check_read(&paths[0], ctx.span)?;
}
"mkdir" | "remove" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
}
"rename" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
self.capabilities.check_write(&paths[1], ctx.span)?;
}
_ => unreachable!(),
}
let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect(
"resource.request",
ctx,
started,
&format!("fs.{name}"),
);
Ok(result)
}
_ => {
let message = match operation.strip_prefix("fs.") {
Some(name) => format!("unsupported filesystem operation `{name}`"),
None => format!("unsupported resource operation `{operation}`"),
};
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
message,
))
}
}
}
}
fn result_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
+38
View File
@@ -218,6 +218,44 @@ commit and recorded with exact hashes in
(7/7 PASS, CLI sha256 `e684ed26…` matching the archive). This is local evidence,
not a same-SHA CI pipeline or a tagged release; platform claim remains Linux x86_64.
## 0.7 Post-beta stable core review — RFC-GPL-0004 (unreleased)
- [ADR-0064](adr/0064-stable-core-extension-boundary.md) requires an accepted ADR,
spec updates, evidence from three unrelated use cases and positive and negative
cases for a core surface change. Tests check the current Builtin names and
aliases, HostOp and Value variants, top-level CLI commands and the exact
`resource.request` catalogue.
- The compatibility dispatcher lives in
`crates/marqdo-host/src/host/resource_requests.rs`. The Host still checks
project mode, operation grants and argument shapes. Existing names and
protocol versions apply. Math and Foreign follow ADR-0061 and ADR-0063.
- The Linux jobs in Woodpecker and GitHub run
`tools/ci/run_frozen_extensions.sh` against the release archive. The fixed
cross-repository fixture covers pure package, Callable Worker, Foreign
Kernel, Provider Worker and Tool. It also includes
[`marqdo-net`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance/src/commit/cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec/marqdo-net)
for bounded HTTP(S) and live SSE and
[`marqdo-agent`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance/src/commit/cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec/marqdo-agent)
for a sequential conversation with caller-authorized local tools. The gate
checks the CLI (including its embedded plugin Worker) and the sibling
Provider Worker digests against the archive and after the fixture run.
- The Resource Control and Task milestones start with proposed
[ADR-0065](adr/0065-resource-control-vnext.md) and
[ADR-0066](adr/0066-structured-tasks-v1.md). Provider control, readiness,
in-flight cancellation, parallel Agent, DB/QPU examples and Buffer
Exchange remain follow-up work. Buffer Exchange first needs measurements
of repeated container updates, resource I/O and Worker wire copies.
The post-beta work does not qualify a new tag or stable release.
Local Linux x86_64 evidence for implementation commit `3bc7267` passed
formatting, Clippy with warnings denied, the workspace (587 passed, 2 ignored),
the CLI suite (215 passed), and the CI tool tests (30 passed). The release archive
passed its installation smoke test. The [frozen archive manifest](evidence/extension/3bc726790fdcee3694fc0b56adbcfd0c6c645275/manifest.json)
records 7/7 conformance groups and 6/6 reference cases with both executable
digests. The external lane ran from a temporary fixture checkout with Cargo
absent from PATH. Archive SHA-256 is
`8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`.
## 1. Historical: pre-beta remote baseline and evidence
> **Historical record.** Everything in §1 onward was executed before the
@@ -0,0 +1,42 @@
# ADR-0064 — Stable core and extension boundary
Status: Accepted for the post-beta development line. Input is [RFC-GPL-0004,
issue #4](https://git.cflmy.cn/cflmy/marqdo-cli/issues/4).
## Decision
The frontend owns the single Markdown-to-IR mapping and static callable binding.
The runtime owns evaluation and run-local state. The Capability Host owns
authority, resource identity, budgets and observable effects. Tool v1 dispatches
independent processes. Domain code goes in a Marqdo package, a Callable Plugin,
a Resource Provider, a Foreign Kernel, or a Tool, according to which existing
interface it needs.
Keep the core surface inventory under review. A change to the builtin catalogue,
HostOp, Value or top-level command set requires a new accepted ADR, the relevant
specification changes, and evidence from at least three unrelated use cases
that need the same primitive. Include a working composition example or explain
why the existing interfaces cannot express one. Describe authority, ownership,
cleanup, performance, compatibility, and positive and negative tests.
The reviewed resource operations remain governed by ADR-0062 and Foreign F-A
by ADR-0063.
The Linux check builds the release CLI and its shipped provider worker, installs
the archive, and runs a pinned external conformance repository against it.
The evidence identifies the core and fixture commits and the executable
digests. New extension use cases should enter that repository first. The
stock package, Worker Callable, Foreign Kernel, Resource Provider, and
registered Tool cases continue to exercise the same prebuilt CLI.
Feature work that depends on new runtime primitives follows
[Resource Control](0065-resource-control-vnext.md) and
[Task v1](0066-structured-tasks-v1.md) as independent milestones. Each proposal
has its own adoption and acceptance criteria. HTTP and model-specific behavior
belongs to independent reference packages using the published interfaces.
## Consequences
Extension packages depend on public contracts. The source and ABI for those
contracts keep their existing release policy. The inventory gate covers changes
to the named surfaces and the external tests cover composition at runtime.
Review still checks changes inside an existing dispatch branch.
+51
View File
@@ -0,0 +1,51 @@
# ADR-0065 — Declarative Resource Control
Status: Proposed. Follow-up to RFC-GPL-0004 §4 and ADR-0062.
## First milestone
Introduce a versioned provider contract for control on a live resource. Keep
Provider v2 stream transport and its schema supported. Select control-capable
providers explicitly through the manifest and lock, pinning both descriptor
content and the platform artifact. The check/inspect path reads declarations
without starting a worker. Dynamic action names and argument values also need
full validation at dispatch.
A manifest declares actions by resource kind. Each action has a unique name,
ordered argument shapes, a required right and a result kind. The result is
either a bounded Value Wire value or a child kind declared by the same provider.
Begin with positional arguments and a closed set of wire shapes. A handle always
selects the provider and kind that issued it. The caller cannot override either.
The dispatcher checks the live run-owned handle, provider grant, handle rights,
registered action, arity and shapes before sending a worker request. Both the
request and validated response are auditable without recording arguments.
Child creation returns an opaque provider token over the transport. The Host
validates the result envelope, kind, freshness and quota before minting a
run-owned Resource. Child rights are bounded by the action declaration and the
operator's grant. Validation and handle publication form one transaction. If
the Host cannot adopt a freshly allocated token, it releases the token or
tears down the faulted worker. It invalidates worker-owned handles on transport
failure and reaps them on run teardown. Raw host handles are excluded from all
wire values. Timeout, malformed frames and worker exit have bounded cleanup.
## Later milestone
Specify `resource.wait` separately after the control path works. Readiness
needs a monotonic deadline, a cancellation source and a bounded batch of
run-owned handles. Unsupported interests return a defined error. The
implementation must state how it interrupts each supported transport and what
happens to outstanding control requests on cancellation. A synchronous Worker
continues to provide process isolation from faults and needs a separate policy
for OS containment.
## Before acceptance
Use a counter for bounded state mutations, a queue for acknowledgments, and a
listener for child adoption. Test authorization before worker effects, unknown
actions, wrong shapes, untrusted or closed handles, repeated or mismatched
tokens, artifact substitution, malformed and oversized messages, worker loss
and teardown. Run the same stream-only Provider v2 suite on the new binary.
The initial implementation should register the three test kinds as external
fixtures. The host's closed `resource.request` catalogue remains governed by
ADR-0062.
+56
View File
@@ -0,0 +1,56 @@
# ADR-0066 — Structured Tasks and bounded Channels
Status: Proposed. Follow-up to RFC-GPL-0004 §§5, 7 and 10.
## Execution and authority
Use a shared immutable prepared program and the existing callable resolution.
Spawn initially accepts a prepared FunctionRef with positional input. Each task
has its own interpreter frames, MemoryStore and Host resources. All spawned
tasks belong to the run. Task identities are opaque and scoped to that run.
Only an owning task may join or cancel its child. Supervisors finish by
reaping all children, including when the parent itself fails.
A child gets the intersection of its parent's effective grants and a requested
subset. If the subset is omitted, the child starts with no optional effect
grants. Charge every task, including descendants, to shared run quotas for
live tasks, queued work, fuel, memory, messages and output. A child deadline
cannot exceed its parent's. Bound scheduling admission before starting any
effect. The scheduler needs a defined strategy for joins and blocking sends
with a saturated worker pool. Prove progress for nested spawn with a two-worker
limit before freezing the design.
Transfer bounded snapshots of ordinary values. At every nesting level reject
Memory, Resource, PluginHandle, task handles and channel endpoints unless a
separate typed endpoint-transfer rule is specified. FunctionRef is resolved
against the same immutable prepared program. Table, Code and Formula transfers
need size and depth accounting. Channel queues are bounded by count and bytes.
Send is initially nonblocking with a full or closed result. Receive waits
until a value, closure, deadline or cancellation. Specify channel endpoint
ownership during the prototype before choosing any public syntax.
## Join, cancellation and observations
Join returns a structured outcome for completion, ordinary child failure and
cancellation. A join wait timeout leaves the child joinable. Explicit cancel
propagates to descendants and wakes waits. Capability denials and budget
violations terminate the offending task and remain distinguishable from
ordinary application failures. No task can use Join to resume an unauthorized
effect.
Cancellation is cooperative at interpreter safe points. Bound or exclude Host
operations that cannot honor run teardown, including uncancellable native
calls. Where a worker can be interrupted, termination and reap have separate
deadlines and must account for descendants. Task and parent IDs belong to a
versioned observability contract. Ordering is defined per task, with explicit
causal links across spawn, message delivery and join.
## Before acceptance
Exercise CPU recursion, concurrent mock network calls and batch orchestration
with an independent failure, deadline and success. Test nested joins under
pool saturation, queue and budget exhaustion, resource cleanup on parent exit,
permission attenuation and rejection of nested live handles. Compare the
existing single-task behavior and performance on the same workloads. Freeze
public names, Value/Handle representation and schema versions only after this
prototype. Shared memory and async syntax need separate decisions.
+6
View File
@@ -59,3 +59,9 @@ Files: `0001`–`0050`, plus:
* `0063-foreign-kernel-transition-fa.md` — retain the permission-gated one-shot
foreign primitive as F-A; F-B removal requires a versioned generic
process/worker capability.
* [0064](0064-stable-core-extension-boundary.md) — core surface review and
frozen external conformance;
* [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful
operations and child resources;
* [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded
communication and cancellation.
+8
View File
@@ -47,6 +47,14 @@ replace `spec/` or a recorded test log.
> [`../STATUS.md`](../STATUS.md) §0.6 and
> [`../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
> **Stable core review (RFC-GPL-0004).** [ADR-0064](../adr/0064-stable-core-extension-boundary.md)
> sets the review rule for builtins, HostOp, Value and top-level commands.
> Linux CI builds a release archive and exercises its installed executables
> against a fixed commit in the external conformance repository. The
> [Resource Control](../adr/0065-resource-control-vnext.md) and
> [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed.
> See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased).
## 1. Four state dimensions
A claim is stated in exactly one of these dimensions. "Exists in the tree" is not
+4
View File
@@ -25,6 +25,7 @@ input and evidence. It is not a second running-status page.
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
| RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. |
| [RFC-GPL-0004 stable core review](https://git.cflmy.cn/cflmy/marqdo-cli/issues/4) | **Boundary adopted; protocol proposals open** | ADR-0064 records core review and a mandatory external gate. ADR-0065 and ADR-0066 propose independent Resource Control and Task work. |
The implemented first slices of these RFCs are recorded in `CURRENT.md` and
`../STATUS.md`; the RFC text itself never proves that code exists.
@@ -72,6 +73,9 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
| Detach domain math kernel | [0061](../adr/0061-detach-domain-math-kernel-from-core.md) | Accepted and implemented; `math.*` removed, pure package + ABI backend |
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
## Evidence and status
+3 -2
View File
@@ -14,8 +14,9 @@ extracts the literals from the host source and fails on any unreviewed change.
- `Memory`/resource handles never cross this API; path arguments are `Text`.
- Operation-level grants are checked before any host action (`check_process`,
`check_read`, `check_write`, `check_entropy`, `check_env`, network grants).
- The `fs.*` family is the only prefix-dispatched group; its sub-operations are
listed explicitly below.
- The compatibility dispatcher matches exact names in
`crates/marqdo-host/src/host/resource_requests.rs`. The `fs.` prefix only
distinguishes unknown-operation diagnostics.
## Reviewed operation table
@@ -0,0 +1,32 @@
{
"schema": "marqdo.extension-evidence",
"schema_version": 1,
"tested_sha": "3bc726790fdcee3694fc0b56adbcfd0c6c645275",
"cli_binary_sha256": "c2b085ccb143292084d2202becc4927cff635fac7369cade2e125aa2537a5111",
"fixture_repo_sha": "cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec",
"os": "linux",
"arch": "x86_64",
"results": {
"callable_registry": "PASS",
"plugin_worker": "PASS",
"foreign_kernel": "PASS",
"resource_provider_cli": "PASS",
"package_pinned_git": "PASS",
"tool_analysis_consumer": "PASS",
"negative_security": "PASS"
},
"commands": [
"python3 /tmp/tmp.iuUoU6thoZ/fixtures/tests/run_all.py (cwd=/tmp/tmp.iuUoU6thoZ/fixtures)"
],
"failures": [],
"unverified": [],
"provider_worker_sha256": "7266db75f52e2954b29f8f018d957e1cae3110a239f98dfe1f34b73c90c96ba2",
"reference_applications": {
"HTTP status, POST and bounded framing": "PASS",
"URL validation and denial before connect": "PASS",
"TLS with an explicit local trust root": "PASS",
"live SSE visibility and caller close": "PASS",
"socket read timeout and teardown": "PASS",
"agent tool authority and two-turn provenance": "PASS"
}
}
+9
View File
@@ -30,6 +30,15 @@
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"provider_worker_sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"reference_applications": {
"type": "object",
"minProperties": 1,
"additionalProperties": { "const": "PASS" }
},
"fixture_repo_sha": {
"type": "string",
"pattern": "^[0-9a-f]{40}$"
+7 -2
View File
@@ -208,8 +208,13 @@ resource.request(operation: Text, arguments: List) -> Result
### 3.4 Resource operations (ADR-0041)
`resource.request(operation, arguments)` is the non-streaming control plane for
operations that are not byte streams. This build registers only `fs.*`:
`resource.request(operation, arguments)` is a closed compatibility catalogue
of non-streaming operations. The [reviewed operation table](../docs/architecture/resource-operations.md)
lists every operation. New domain operations live in explicit packages, Callable
Plugins or Resource Providers. Add a core primitive only through the review
recorded in [ADR-0064](../docs/adr/0064-stable-core-extension-boundary.md).
File operations:
```text
resource.request("fs.exists", [path]) -> {ok:true, value:Bool}
+11
View File
@@ -35,3 +35,14 @@ A missing gate becomes `UNVERIFIED`. Any non-PASS required gate, a
SHA forces `DO_NOT_RELEASE`. `performance` may be `PASS` or `WARN`.
Unit tests: `python3 -m unittest discover -s tools/ci -p 'test_*.py'`.
## Frozen external extension lane
`run_frozen_extensions.sh ARCHIVE SOURCE_SHA OUTPUT_MANIFEST` fetches the
fixture revision pinned in the script and checks it out detached in a
temporary directory. It extracts the Linux archive there and uses the
release metadata to verify the source SHA and both executable digests.
The external fixture runs against that installation and the verifier checks
fresh results, all seven extension groups and the reference application cases.
GitHub CI uploads the manifest. Woodpecker prints it in the build step.
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Run the mandatory Linux lane with only the installed archive and pinned fixtures.
set -euo pipefail
if [[ $# != 3 ]]; then
echo "usage: $0 ARCHIVE SOURCE_SHA OUTPUT_MANIFEST" >&2
exit 2
fi
archive="$1"
source_sha="$2"
manifest="$3"
root="$(cd "$(dirname "$0")/../.." && pwd)"
fixture_remote=https://git.cflmy.cn/cflmy/marqdo-extension-conformance.git
fixture_sha=cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec
work="$(mktemp -d)"
trap 'rm -rf -- "$work"' EXIT
git init -q "$work/fixtures"
git -C "$work/fixtures" fetch --no-tags --depth=1 "$fixture_remote" "$fixture_sha"
git -C "$work/fixtures" checkout -q --detach "$fixture_sha"
mkdir "$work/install"
tar -xzf "$archive" -C "$work/install"
installations=("$work"/install/*)
if [[ ${#installations[@]} != 1 || ! -d "${installations[0]}" ]]; then
echo "expected one installation directory in the release archive" >&2
exit 1
fi
install="${installations[0]}"
test "$(cat "$install/SOURCE_SHA")" = "$source_sha"
test -x "$install/marqdo"
test -x "$install/marqdo-provider-worker"
python3 "$root/tools/ci/verify_extension_contracts.py" \
--source-repo "$root" --tested-sha "$source_sha" \
--cli "$install/marqdo" --release-info "$install/RELEASE_INFO.json" \
--fixtures "$work/fixtures" --out "$manifest"
@@ -65,6 +65,24 @@ class ValidateManifestTests(unittest.TestCase):
problems = evidence.validate_manifest(manifest)
self.assertTrue(any("commands" in item for item in problems), problems)
def test_reference_failure_is_rejected(self) -> None:
manifest = valid_manifest()
manifest["reference_applications"] = {"live SSE": "FAIL"}
self.assertTrue(evidence.validate_manifest(manifest))
manifest["reference_applications"] = {"live SSE": "PASS"}
self.assertEqual(evidence.validate_manifest(manifest), [])
def test_report_identity_must_match_binaries_and_fixture_commit(self) -> None:
report = {
"schema": "marqdo.ext-fixture-results",
"schema_version": 1,
"tool_sha": "a" * 40,
"cli_binary_sha256": "b" * 64,
"provider_worker_sha256": "c" * 64,
}
self.assertEqual(evidence.verify_report_identity(report, "a" * 40, "b" * 64, "c" * 64), [])
self.assertEqual(len(evidence.verify_report_identity(report, "f" * 40, "f" * 64, "f" * 64)), 3)
def test_documented_schema_is_valid_json(self) -> None:
schema_path = (
evidence.REPO
+78 -17
View File
@@ -97,6 +97,14 @@ def validate_manifest(manifest: dict) -> list[str]:
cli = manifest.get("cli_binary_sha256", "")
if not (isinstance(cli, str) and len(cli) == 64 and all(c in "0123456789abcdef" for c in cli)):
problems.append("cli_binary_sha256 must be a 64-character lowercase sha256")
if "provider_worker_sha256" in manifest:
worker = manifest["provider_worker_sha256"]
if not (isinstance(worker, str) and len(worker) == 64 and all(c in "0123456789abcdef" for c in worker)):
problems.append("provider_worker_sha256 must be a 64-character lowercase sha256")
if "reference_applications" in manifest:
references = manifest["reference_applications"]
if not isinstance(references, dict) or not references or any(value != "PASS" for value in references.values()):
problems.append("reference_applications must be a non-empty object with all cases PASS")
if manifest.get("os") not in {"linux", "macos", "windows"}:
problems.append("os must be linux, macos or windows")
results = manifest.get("results")
@@ -125,37 +133,52 @@ def validate_manifest(manifest: dict) -> list[str]:
def run_suite(fixtures: Path, cli: Path) -> tuple[bool, dict, list[str]]:
"""Run the external suite and return (ok, results, commands)."""
results: dict[str, str] = {}
commands: list[str] = []
"""Run the external suite and return its fresh raw report."""
env = dict(os.environ)
env["MARQDO_BIN"] = str(cli)
env["MARQDO_FROZEN_CLI"] = str(cli)
runner = fixtures / "tests" / "run_all.py"
if not runner.is_file():
return False, results, commands
commands.append(f"python3 {runner} (cwd={fixtures})")
return False, {}, []
commands = [f"python3 {runner} (cwd={fixtures})"]
results_path = fixtures / "evidence" / "results.json"
results_path.unlink(missing_ok=True)
completed = subprocess.run(
[sys.executable, str(runner)],
cwd=fixtures,
env=env,
capture_output=True,
text=True,
timeout=180,
)
print(completed.stdout, end="")
print(completed.stderr, end="", file=sys.stderr)
results_path = fixtures / "evidence" / "results.json"
if results_path.is_file():
with results_path.open("r", encoding="utf-8") as handle:
payload = json.load(handle)
for key, value in (payload.get("results") or {}).items():
results[key] = str(value).upper()
return completed.returncode == 0, results, commands
payload = json.loads(results_path.read_text(encoding="utf-8")) if results_path.is_file() else {}
return completed.returncode == 0, payload, commands
def verify_report_identity(
payload: dict, fixture_sha: str, cli_hash: str, worker_hash: str | None
) -> list[str]:
problems = []
if payload.get("schema") != "marqdo.ext-fixture-results" or payload.get("schema_version") != 1:
problems.append("external suite did not produce a supported results report")
if payload.get("tool_sha") != fixture_sha:
problems.append("external report fixture SHA does not match the checked-out commit")
if payload.get("cli_binary_sha256") != cli_hash:
problems.append("external report CLI hash does not match the tested executable")
if "provider_worker_sha256" in payload and payload["provider_worker_sha256"] != worker_hash:
problems.append("external report provider worker hash does not match the tested executable")
return problems
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cli", type=Path, help="Absolute/relative frozen marqdo binary")
parser.add_argument(
"--release-info", type=Path,
help="Verify the installed archive's source and binary digests and require reference results",
)
parser.add_argument("--fixtures", type=Path, help="External fixture repository root")
parser.add_argument("--source-repo", type=Path, default=REPO, help="marqdo-cli checkout")
parser.add_argument("--out", type=Path, help="Evidence manifest output path")
@@ -217,6 +240,8 @@ def main() -> int:
)
return 2
cli_before = sha256_file(cli)
worker = cli.with_name("marqdo-provider-worker")
worker_before = sha256_file(worker) if worker.is_file() else None
tested_sha = git_sha(source_repo)
if args.tested_sha and args.tested_sha != tested_sha:
print(
@@ -224,12 +249,37 @@ def main() -> int:
file=sys.stderr,
)
return 2
if args.release_info:
info = json.loads(args.release_info.read_text(encoding="utf-8"))
binaries = info.get("binaries", {})
if (
info.get("source_sha") != tested_sha
or binaries.get("marqdo", {}).get("sha256") != cli_before
or worker_before is None
or binaries.get(worker.name, {}).get("sha256") != worker_before
):
print("error: installed archive source or binary digest mismatch", file=sys.stderr)
return 1
fixture_sha = git_sha(fixtures)
ok, results, commands = run_suite(fixtures, cli)
cli_after = sha256_file(cli)
if cli_before != cli_after:
try:
ok, payload, commands = run_suite(fixtures, cli)
except (ValueError, subprocess.TimeoutExpired) as error:
print(f"error: invalid or incomplete external suite report: {error}", file=sys.stderr)
return 1
if not cli.is_file() or cli_before != sha256_file(cli):
print("error: frozen CLI hash changed during the external suite", file=sys.stderr)
return 1
if (sha256_file(worker) if worker.is_file() else None) != worker_before:
print("error: frozen provider worker hash changed during the external suite", file=sys.stderr)
return 1
if git_sha(fixtures) != fixture_sha or git_sha(source_repo) != tested_sha:
print("error: a checkout changed during the external suite", file=sys.stderr)
return 1
results = payload.get("results", {})
if not isinstance(results, dict):
print("error: external suite results must be an object", file=sys.stderr)
return 1
failures = [name for name, value in results.items() if value == "FAIL"]
unverified = [
@@ -251,13 +301,24 @@ def main() -> int:
"failures": failures,
"unverified": unverified,
}
if worker_before is not None:
manifest["provider_worker_sha256"] = worker_before
if "reference_applications" in payload:
manifest["reference_applications"] = payload["reference_applications"]
problems = validate_manifest(manifest)
problems.extend(verify_report_identity(payload, fixture_sha, cli_before, worker_before))
if args.release_info:
if "reference_applications" not in payload:
problems.append("frozen archive gate requires reference application results")
if "provider_worker_sha256" not in payload:
problems.append("frozen archive gate requires the provider worker digest")
if missing:
problems.append(f"missing external results: {', '.join(missing)}")
if unverified and not args.allow_unverified:
problems.append(
"UNSUPPORTED/SKIPPED results require --allow-unverified and an explicit report entry"
)
if not ok and not failures:
failures.append("external suite exited non-zero without structured results")
if not ok:
problems.append("external suite failed")
if problems:
for problem in problems: