refactor: convert Marqdo into the ecosystem integration repository
This commit is contained in:
1 parent
1c55baabd5
commit
4c5c102593
1880 files changed
+998
-308724
No files matched your search
@@ -1,145 +0,0 @@
|
||||
//! Runtime helpers for ABI `host_query` and shared map/list ops.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
impl HostContext {
|
||||
pub fn set_entry_source(&mut self, path: Option<&Path>, source: &str) {
|
||||
self.entry_source = Some(source.to_string());
|
||||
self.entry_path = path.map(|p| p.to_path_buf());
|
||||
}
|
||||
|
||||
pub fn push_call_frame(&mut self, name: &str) {
|
||||
self.call_stack.push(name.to_string());
|
||||
}
|
||||
|
||||
pub fn pop_call_frame(&mut self) {
|
||||
self.call_stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn module_source(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(match &ctx.entry_source {
|
||||
Some(s) => Value::Text(s.clone()),
|
||||
None => Value::Text(String::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn call_site(ctx: &HostContext, line: Option<u32>) -> Result<Value, String> {
|
||||
let path = ctx
|
||||
.entry_path
|
||||
.as_ref()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default();
|
||||
let function = ctx
|
||||
.call_stack
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "main".into());
|
||||
let line_v = match line {
|
||||
Some(n) => Value::Int(n as i64),
|
||||
None => Value::None,
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("path".into(), Value::Text(path)),
|
||||
("function".into(), Value::Text(function)),
|
||||
("line".into(), line_v),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn marqdo_skill(ctx: &HostContext) -> Result<Value, String> {
|
||||
let text = load_marqdo_skill(ctx)?;
|
||||
Ok(Value::Text(text))
|
||||
}
|
||||
|
||||
fn load_marqdo_skill(ctx: &HostContext) -> Result<String, String> {
|
||||
if let Ok(p) = std::env::var("MARQDO_SKILL") {
|
||||
let path = PathBuf::from(p);
|
||||
if path.is_file() {
|
||||
return std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("MARQDO_SKILL read {}: {e}", path.display()));
|
||||
}
|
||||
let skill = path.join("SKILL.md");
|
||||
if skill.is_file() {
|
||||
return read_skill_pack(&path);
|
||||
}
|
||||
}
|
||||
|
||||
for root in skill_search_roots(ctx) {
|
||||
let pack = root.join("skills").join("marqdo");
|
||||
if pack.join("SKILL.md").is_file() {
|
||||
return read_skill_pack(&pack);
|
||||
}
|
||||
if root.join("SKILL.md").is_file() && root.ends_with("marqdo") {
|
||||
return read_skill_pack(&root);
|
||||
}
|
||||
}
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
fn read_skill_pack(dir: &Path) -> Result<String, String> {
|
||||
let mut out = String::new();
|
||||
for name in ["SKILL.md", "reference.md", "examples.md"] {
|
||||
let p = dir.join(name);
|
||||
if p.is_file() {
|
||||
let body = std::fs::read_to_string(&p)
|
||||
.map_err(|e| format!("skill read {}: {e}", p.display()))?;
|
||||
if !out.is_empty() {
|
||||
out.push_str("\n\n---\n\n");
|
||||
}
|
||||
out.push_str(&format!("# file: {name}\n\n"));
|
||||
out.push_str(&body);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
roots.push(dir.to_path_buf());
|
||||
if let Some(parent) = dir.parent() {
|
||||
roots.push(parent.to_path_buf());
|
||||
if let Some(repo) = parent.parent() {
|
||||
roots.push(repo.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.push(ctx.cwd.clone());
|
||||
if let Some(p) = &ctx.entry_path {
|
||||
if let Some(parent) = p.parent() {
|
||||
roots.push(parent.to_path_buf());
|
||||
if let Some(repo) = parent.parent().and_then(|p| p.parent()) {
|
||||
roots.push(repo.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
|
||||
roots.push(PathBuf::from(manifest));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
|
||||
crate::host::collection::map_set(map, key, value)
|
||||
}
|
||||
|
||||
pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
crate::host::collection::list_append(list, item)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn map_set_updates() {
|
||||
let m = Value::Map(vec![("a".into(), Value::Int(1))]);
|
||||
let m2 = map_set(&m, &Value::Text("a".into()), &Value::Int(2)).unwrap();
|
||||
assert_eq!(m2, Value::Map(vec![("a".into(), Value::Int(2))]));
|
||||
}
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
//! Optional ZIP tasks with preflight, expansion limits and no path traversal.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs,
|
||||
io::{Read, Write},
|
||||
path::Path,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = operate(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("ZIP unavailable: build with net-host (native default)".into())
|
||||
};
|
||||
Ok(super::result::capture(
|
||||
if id == HostFn::ZipPack {
|
||||
"archive.pack"
|
||||
} else {
|
||||
"archive.unpack"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn operate(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("ZIP unavailable in CoW sandbox".into());
|
||||
}
|
||||
let src = ctx.resolve_path(super::as_text(arg(b, "src")?, "src")?)?;
|
||||
let dest = ctx.resolve_path(super::as_text(arg(b, "dest")?, "dest")?)?;
|
||||
let max = match arg(b, "max_bytes")? {
|
||||
Value::Int(n) if *n > 0 && *n <= 1024 * 1024 * 1024 => *n as u64,
|
||||
_ => return Err("max_bytes must be 1..1073741824".into()),
|
||||
};
|
||||
if dest.exists() {
|
||||
return Err("destination conflict: ZIP output must not exist".into());
|
||||
}
|
||||
if id == HostFn::ZipPack {
|
||||
if !src.is_dir() || dest.starts_with(&src) {
|
||||
return Err("pack src must be directory and dest outside src".into());
|
||||
}
|
||||
let mut args = HashMap::new();
|
||||
args.insert("path".into(), Value::Text(src.to_string_lossy().into()));
|
||||
args.insert("pattern".into(), Value::Text("**".into()));
|
||||
args.insert("exclude".into(), Value::None);
|
||||
args.insert("max_depth".into(), Value::Int(256));
|
||||
args.insert("kind".into(), Value::Text("file".into()));
|
||||
let Value::List(files) = super::fs_ops::call(ctx, HostFn::FsFind, &args)? else {
|
||||
unreachable!()
|
||||
};
|
||||
let total = files.iter().try_fold(0u64, |n, name| {
|
||||
let p = src.join(super::as_text(name, "name")?);
|
||||
let size = fs::metadata(p).map_err(|e| e.to_string())?.len();
|
||||
n.checked_add(size)
|
||||
.ok_or_else(|| "archive size overflow".to_string())
|
||||
})?;
|
||||
if total > max {
|
||||
return Err("archive source exceeds max_bytes".into());
|
||||
}
|
||||
let parent = dest.parent().ok_or("archive needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let temp = parent.join(format!(".mq-zip-{}", random_name()?));
|
||||
let file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let written = (|| {
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let mut buffer = [0u8; 65536];
|
||||
let mut seen = 0u64;
|
||||
for name in &files {
|
||||
let name = super::as_text(name, "name")?;
|
||||
writer
|
||||
.start_file(
|
||||
name,
|
||||
zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated),
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let p = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let mut file = fs::File::open(p).map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = file.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
seen += n as u64;
|
||||
if seen > max {
|
||||
return Err("archive source grew past max_bytes".into());
|
||||
}
|
||||
writer.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
writer
|
||||
.finish()
|
||||
.map_err(|e| e.to_string())?
|
||||
.sync_all()
|
||||
.map_err(|e| e.to_string())?;
|
||||
// hard_link is an atomic no-clobber publish on the same filesystem.
|
||||
fs::hard_link(&temp, &dest).map_err(|e| e.to_string())?;
|
||||
Ok(Value::Int(files.len() as i64))
|
||||
})();
|
||||
let _ = fs::remove_file(&temp);
|
||||
return written;
|
||||
}
|
||||
let file = fs::File::open(src).map_err(|e| e.to_string())?;
|
||||
let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
if zip.len() > 100000 {
|
||||
return Err("archive exceeds 100000 entries".into());
|
||||
}
|
||||
let mut names = HashSet::new();
|
||||
let mut total = 0u64;
|
||||
for i in 0..zip.len() {
|
||||
let entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let name = entry
|
||||
.enclosed_name()
|
||||
.ok_or("archive path escapes destination")?;
|
||||
if entry.name().contains('\\') || name == Path::new("") || !names.insert(name.to_path_buf())
|
||||
{
|
||||
return Err("invalid or duplicate archive path".into());
|
||||
}
|
||||
if entry
|
||||
.unix_mode()
|
||||
.is_some_and(|mode| mode & 0o170000 == 0o120000)
|
||||
{
|
||||
return Err("archive symlinks unsupported".into());
|
||||
}
|
||||
total = total
|
||||
.checked_add(entry.size())
|
||||
.ok_or("archive size overflow")?;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(dest.parent().ok_or("destination needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
fs::create_dir(&dest).map_err(|e| e.to_string())?;
|
||||
let extracted = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).map_err(|e| e.to_string())?;
|
||||
let path = ctx.resolve_path(
|
||||
dest.join(entry.enclosed_name().ok_or("invalid archive path")?)
|
||||
.to_str()
|
||||
.ok_or("non UTF-8 path")?,
|
||||
)?;
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(path).map_err(|e| e.to_string())?;
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(path.parent().ok_or("entry needs parent")?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
loop {
|
||||
let n = entry.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("archive expansion exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Int(zip.len() as i64))
|
||||
})();
|
||||
if extracted.is_err() {
|
||||
let _ = fs::remove_dir_all(&dest);
|
||||
}
|
||||
extracted
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn random_name() -> Result<String, String> {
|
||||
let mut bytes = [0u8; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?;
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
//! CLI arg parsing for Mid M5 (`lib/cli`).
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text_list(v: &Value) -> Result<Vec<String>, String> {
|
||||
match v {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::Text(s) => out.push(s.clone()),
|
||||
_ => return Err("cli.parse: args must be list of text".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Value::None => Ok(vec![]),
|
||||
_ => Err("cli.parse: args needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `--key value` / `--key=value` / `--flag` / positionals into a map.
|
||||
/// Positionals are stored under key `_` as a list.
|
||||
pub fn parse(ctx: &HostContext, args: Option<&Value>) -> Result<Value, String> {
|
||||
let argv = match args {
|
||||
None | Some(Value::None) => ctx.argv.clone(),
|
||||
Some(v) => as_text_list(v)?,
|
||||
};
|
||||
let mut map: Vec<(String, Value)> = Vec::new();
|
||||
let mut positionals: Vec<Value> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < argv.len() {
|
||||
let a = &argv[i];
|
||||
if let Some(rest) = a.strip_prefix("--") {
|
||||
if rest.is_empty() {
|
||||
// bare `--` — remaining are positionals
|
||||
i += 1;
|
||||
while i < argv.len() {
|
||||
positionals.push(Value::Text(argv[i].clone()));
|
||||
i += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some((k, v)) = rest.split_once('=') {
|
||||
upsert(&mut map, k.to_string(), Value::Text(v.to_string()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let key = rest.to_string();
|
||||
if i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, key, Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
upsert(&mut map, key, Value::Bool(true));
|
||||
i += 1;
|
||||
}
|
||||
} else if let Some(rest) = a.strip_prefix('-') {
|
||||
// short flags: -abc → a/b/c True; -k val not special-cased beyond single letter groups
|
||||
if rest.is_empty() {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if rest.len() == 1 && i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, rest.to_string(), Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
for ch in rest.chars() {
|
||||
upsert(&mut map, ch.to_string(), Value::Bool(true));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if !positionals.is_empty() {
|
||||
upsert(&mut map, "_".into(), Value::List(positionals));
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
fn upsert(map: &mut Vec<(String, Value)>, key: String, value: Value) {
|
||||
if let Some((_, slot)) = map.iter_mut().find(|(k, _)| *k == key) {
|
||||
*slot = value;
|
||||
} else {
|
||||
map.push((key, value));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_flags() {
|
||||
let ctx = HostContext::default();
|
||||
let args = Value::List(vec![
|
||||
Value::Text("--input".into()),
|
||||
Value::Text("a.csv".into()),
|
||||
Value::Text("x".into()),
|
||||
Value::Text("--verbose".into()),
|
||||
]);
|
||||
let m = parse(&ctx, Some(&args)).unwrap();
|
||||
match m {
|
||||
Value::Map(entries) => {
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "input" && *v == Value::Text("a.csv".into())));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "verbose" && *v == Value::Bool(true)));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_" && matches!(v, Value::List(_))));
|
||||
}
|
||||
_ => panic!("map"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,616 +0,0 @@
|
||||
//! List / map collection primitives for `lib/table` (and json compat aliases).
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum PathSeg {
|
||||
Key(String),
|
||||
/// 1-based list index (aligned with footnote `[^1]`).
|
||||
Index1(usize),
|
||||
}
|
||||
|
||||
fn path_segments(at: &Value) -> Result<Vec<PathSeg>, String> {
|
||||
match at {
|
||||
Value::Text(s) => Ok(vec![PathSeg::Key(s.clone())]),
|
||||
Value::Int(n) => {
|
||||
if *n < 1 {
|
||||
return Err("put path index must be >= 1 (1-based)".into());
|
||||
}
|
||||
Ok(vec![PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)])
|
||||
}
|
||||
Value::List(xs) => {
|
||||
if xs.is_empty() {
|
||||
return Err("put path must not be empty".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(xs.len());
|
||||
for (i, seg) in xs.iter().enumerate() {
|
||||
match seg {
|
||||
Value::Text(s) => out.push(PathSeg::Key(s.clone())),
|
||||
Value::Int(n) => {
|
||||
if *n < 1 {
|
||||
return Err(format!(
|
||||
"put path segment {i}: index must be >= 1 (1-based)"
|
||||
));
|
||||
}
|
||||
out.push(PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?));
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"put path segment {i}: need text key or int index"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
_ => Err("put at= needs text, int, or list path".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deep put: `in` collection, `at` path (1-based ints), `value` leaf.
|
||||
/// `in=None` + single text key → new one-entry map.
|
||||
pub fn collection_put(input: &Value, at: &Value, value: &Value) -> Result<Value, String> {
|
||||
let path = path_segments(at)?;
|
||||
if matches!(input, Value::None) {
|
||||
if path.len() == 1 {
|
||||
if let PathSeg::Key(k) = &path[0] {
|
||||
return Ok(Value::Map(vec![(k.clone(), value.clone())]));
|
||||
}
|
||||
}
|
||||
return Err("put in=None only allowed with a single text key".into());
|
||||
}
|
||||
put_rec(input, &path, value)
|
||||
}
|
||||
|
||||
fn put_rec(cur: &Value, path: &[PathSeg], value: &Value) -> Result<Value, String> {
|
||||
let Some((head, rest)) = path.split_first() else {
|
||||
return Ok(value.clone());
|
||||
};
|
||||
if rest.is_empty() {
|
||||
return put_leaf(cur, head, value);
|
||||
}
|
||||
match head {
|
||||
PathSeg::Key(k) => {
|
||||
let Value::Map(entries) = cur else {
|
||||
return Err(format!("put: expected map at key `{k}`"));
|
||||
};
|
||||
let child = entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.ok_or_else(|| format!("put: missing key `{k}` on path"))?;
|
||||
let new_child = put_rec(&child, rest, value)?;
|
||||
map_set(cur, &Value::Text(k.clone()), &new_child)
|
||||
}
|
||||
PathSeg::Index1(i1) => {
|
||||
let Value::List(xs) = cur else {
|
||||
return Err(format!("put: expected list at index {i1}"));
|
||||
};
|
||||
let i0 = i1 - 1;
|
||||
if i0 >= xs.len() {
|
||||
return Err(format!("put: list index {i1} out of range (len {})", xs.len()));
|
||||
}
|
||||
let new_child = put_rec(&xs[i0], rest, value)?;
|
||||
list_set_at(cur, i0 as i64, &new_child)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn put_leaf(cur: &Value, head: &PathSeg, value: &Value) -> Result<Value, String> {
|
||||
match head {
|
||||
PathSeg::Key(k) => map_set(cur, &Value::Text(k.clone()), value),
|
||||
PathSeg::Index1(i1) => {
|
||||
let i0 = (*i1 as i64) - 1;
|
||||
list_set_at(cur, i0, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.clone(),
|
||||
_ => return Err("map_set key must be text".into()),
|
||||
};
|
||||
match map {
|
||||
Value::Map(entries) => {
|
||||
let mut out = entries.clone();
|
||||
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) {
|
||||
*slot = value.clone();
|
||||
} else {
|
||||
out.push((k, value.clone()));
|
||||
}
|
||||
Ok(Value::Map(out))
|
||||
}
|
||||
Value::None => Ok(Value::Map(vec![(k, value.clone())])),
|
||||
_ => Err("map_set needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_get(map: &Value, key: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("map_get key must be text".into()),
|
||||
};
|
||||
match map {
|
||||
Value::Map(entries) => Ok(entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None)),
|
||||
Value::None => Ok(Value::None),
|
||||
_ => Err("map_get needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_delete(map: &Value, key: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("map_delete key must be text".into()),
|
||||
};
|
||||
match map {
|
||||
Value::Map(entries) => {
|
||||
let out: Vec<_> = entries.iter().filter(|(kk, _)| kk != k).cloned().collect();
|
||||
Ok(Value::Map(out))
|
||||
}
|
||||
Value::None => Ok(Value::Map(vec![])),
|
||||
_ => Err("map_delete needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_has(map: &Value, key: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("map_has key must be text".into()),
|
||||
};
|
||||
match map {
|
||||
Value::Map(entries) => Ok(Value::Bool(entries.iter().any(|(kk, _)| kk == k))),
|
||||
Value::None => Ok(Value::Bool(false)),
|
||||
_ => Err("map_has needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_keys(map: &Value) -> Result<Value, String> {
|
||||
match map {
|
||||
Value::Map(entries) => Ok(Value::List(
|
||||
entries
|
||||
.iter()
|
||||
.map(|(k, _)| Value::Text(k.clone()))
|
||||
.collect(),
|
||||
)),
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("map_keys needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_values(map: &Value) -> Result<Value, String> {
|
||||
match map {
|
||||
Value::Map(entries) => Ok(Value::List(entries.iter().map(|(_, v)| v.clone()).collect())),
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("map_values needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_items(map: &Value) -> Result<Value, String> {
|
||||
match map {
|
||||
Value::Map(entries) => {
|
||||
let rows: Vec<Value> = entries
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
Value::Map(vec![
|
||||
("key".into(), Value::Text(k.clone())),
|
||||
("value".into(), v.clone()),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
Ok(Value::List(rows))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("map_items needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_merge(left: &Value, right: &Value) -> Result<Value, String> {
|
||||
let mut out = match left {
|
||||
Value::Map(e) => e.clone(),
|
||||
Value::None => vec![],
|
||||
_ => return Err("map_merge left needs map".into()),
|
||||
};
|
||||
let right_entries = match right {
|
||||
Value::Map(e) => e,
|
||||
Value::None => return Ok(Value::Map(out)),
|
||||
_ => return Err("map_merge right needs map".into()),
|
||||
};
|
||||
for (k, v) in right_entries {
|
||||
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| kk == k) {
|
||||
*slot = v.clone();
|
||||
} else {
|
||||
out.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(out))
|
||||
}
|
||||
|
||||
pub fn map_size(map: &Value) -> Result<Value, String> {
|
||||
match map {
|
||||
Value::Map(entries) => Ok(Value::Int(entries.len() as i64)),
|
||||
Value::None => Ok(Value::Int(0)),
|
||||
_ => Err("map_size needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.push(item.clone());
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![item.clone()])),
|
||||
_ => Err("list_append needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_prepend(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = vec![item.clone()];
|
||||
out.extend(xs.iter().cloned());
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![item.clone()])),
|
||||
_ => Err("list_prepend needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_concat(a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let left = match a {
|
||||
Value::List(xs) => xs.clone(),
|
||||
Value::None => vec![],
|
||||
_ => return Err("list_concat left needs list".into()),
|
||||
};
|
||||
let right = match b {
|
||||
Value::List(xs) => xs,
|
||||
Value::None => return Ok(Value::List(left)),
|
||||
_ => return Err("list_concat right needs list".into()),
|
||||
};
|
||||
let mut out = left;
|
||||
out.extend(right.iter().cloned());
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result<Value, String> {
|
||||
let mut xs = match list {
|
||||
Value::List(xs) => xs.clone(),
|
||||
Value::None => vec![],
|
||||
_ => return Err("list_insert needs list".into()),
|
||||
};
|
||||
if index < 0 || index > xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_insert index {index} out of range (len {})",
|
||||
xs.len()
|
||||
));
|
||||
}
|
||||
xs.insert(index as usize, item.clone());
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result<Value, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_set_at needs list".into());
|
||||
};
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_set_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
));
|
||||
}
|
||||
let mut out = xs.clone();
|
||||
out[index as usize] = item.clone();
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_remove_at(list: &Value, index: i64) -> Result<Value, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_remove_at needs list".into());
|
||||
};
|
||||
if index < 0 || index >= xs.len() as i64 {
|
||||
return Err(format!(
|
||||
"list_remove_at index {index} out of range (len {})",
|
||||
xs.len()
|
||||
));
|
||||
}
|
||||
let mut out = xs.clone();
|
||||
out.remove(index as usize);
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_slice(list: &Value, start: i64, end: Option<i64>) -> Result<Value, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("list_slice needs list".into());
|
||||
};
|
||||
let n = xs.len() as i64;
|
||||
let s = start.clamp(0, n) as usize;
|
||||
let e = end.unwrap_or(n).clamp(0, n) as usize;
|
||||
if e < s {
|
||||
return Ok(Value::List(vec![]));
|
||||
}
|
||||
Ok(Value::List(xs[s..e].to_vec()))
|
||||
}
|
||||
|
||||
pub fn list_contains(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => Ok(Value::Bool(xs.iter().any(|x| x == item))),
|
||||
Value::None => Ok(Value::Bool(false)),
|
||||
_ => Err("list_contains needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_index_of(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => Ok(xs
|
||||
.iter()
|
||||
.position(|x| x == item)
|
||||
.map(|i| Value::Int(i as i64))
|
||||
.unwrap_or(Value::None)),
|
||||
Value::None => Ok(Value::None),
|
||||
_ => Err("list_index_of needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_reverse(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.reverse();
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_reverse needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_first(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => Ok(xs.first().cloned().unwrap_or(Value::None)),
|
||||
Value::None => Ok(Value::None),
|
||||
_ => Err("list_first needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_last(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => Ok(xs.last().cloned().unwrap_or(Value::None)),
|
||||
Value::None => Ok(Value::None),
|
||||
_ => Err("list_last needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Total type order avoids cyclic comparisons between numeric and text keys.
|
||||
pub(super) fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering;
|
||||
fn rank(v:&Value)->u8{match v{
|
||||
Value::Int(_)|Value::Num(_)=>0,Value::Text(_)=>1,Value::Bool(_)=>2,
|
||||
Value::None=>3,Value::List(_)=>4,Value::Map(_)=>5,Value::Formula(_)=>6,
|
||||
Value::Code(_)=>7,Value::Secret(_)=>8,Value::Handle(_)=>9,
|
||||
}}
|
||||
fn int_float(integer:i64,number:f64)->Ordering{
|
||||
if number.is_nan(){return Ordering::Less}
|
||||
if number >= -(i64::MIN as f64){return Ordering::Less}
|
||||
if number < i64::MIN as f64{return Ordering::Greater}
|
||||
let truncated=number as i64;
|
||||
match integer.cmp(&truncated){Ordering::Equal=>0.0f64.partial_cmp(&number.fract()).unwrap_or(Ordering::Equal),other=>other}
|
||||
}
|
||||
let order=rank(a).cmp(&rank(b));if !order.is_eq(){return order}
|
||||
match (a,b){
|
||||
(Value::Int(a),Value::Int(b))=>a.cmp(b),
|
||||
(Value::Num(a),Value::Num(b))=>match(a.is_nan(),b.is_nan()){
|
||||
(true,false)=>Ordering::Greater,(false,true)=>Ordering::Less,
|
||||
_=>a.partial_cmp(b).unwrap_or_else(||a.total_cmp(b)),
|
||||
},
|
||||
(Value::Int(a),Value::Num(b))=>int_float(*a,*b),
|
||||
(Value::Num(a),Value::Int(b))=>int_float(*b,*a).reverse(),
|
||||
(Value::Text(a),Value::Text(b))=>a.cmp(b),
|
||||
(Value::Bool(a),Value::Bool(b))=>a.cmp(b),
|
||||
_=>a.as_display().cmp(&b.as_display()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(cmp_value);
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort_by(list: &Value, key: &Value) -> Result<Value, String> {
|
||||
let key = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("sort_by key needs text".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(|a, b| {
|
||||
let ka = match a {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
let kb = match b {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
cmp_value(ka, kb)
|
||||
});
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort_by needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut seen: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();
|
||||
for x in xs {
|
||||
let bucket = seen.entry(super::collection_ops::fingerprint(x)).or_default();
|
||||
if !bucket.iter().any(|i| out[*i] == *x) {
|
||||
bucket.push(out.len());
|
||||
out.push(x.clone());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_unique needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_chunk(list: &Value, size: &Value) -> Result<Value, String> {
|
||||
let n = match size {
|
||||
Value::Int(i) if *i > 0 => usize::try_from(*i).unwrap_or(usize::MAX),
|
||||
Value::Int(_) => return Err("chunk size must be positive".into()),
|
||||
_ => return Err("chunk size needs int".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < xs.len() {
|
||||
let end = (i + n).min(xs.len());
|
||||
out.push(Value::List(xs[i..end].to_vec()));
|
||||
i = end;
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_chunk needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_zip(a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let (aa, bb) = match (a, b) {
|
||||
(Value::List(x), Value::List(y)) => (x, y),
|
||||
(Value::None, Value::List(y)) => (&Vec::new(), y),
|
||||
(Value::List(x), Value::None) => (x, &Vec::new()),
|
||||
(Value::None, Value::None) => return Ok(Value::List(vec![])),
|
||||
_ => return Err("list_zip needs two lists".into()),
|
||||
};
|
||||
let n = aa.len().min(bb.len());
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
out.push(Value::List(vec![aa[i].clone(), bb[i].clone()]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_flatten(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::List(inner) => out.extend(inner.iter().cloned()),
|
||||
other => out.push(other.clone()),
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_flatten needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collection_clear(value: &Value) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::List(_) | Value::None => Ok(Value::List(vec![])),
|
||||
Value::Map(_) => Ok(Value::Map(vec![])),
|
||||
_ => Err("clear needs list or map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_i64(v: &Value, name: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{name} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind helper used by dispatch for optional end=.
|
||||
pub fn list_slice_bound(list: &Value, start: &Value, end: Option<&Value>) -> Result<Value, String> {
|
||||
let s = require_i64(start, "start")?;
|
||||
let e = match end {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(require_i64(v, "end")?),
|
||||
};
|
||||
list_slice(list, s, e)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn put_map_key_and_nested() {
|
||||
let m = Value::Map(vec![("a".into(), Value::Int(1))]);
|
||||
let m2 = collection_put(&m, &Value::Text("b".into()), &Value::Int(2)).unwrap();
|
||||
assert!(matches!(map_get(&m2, &Value::Text("b".into())).unwrap(), Value::Int(2)));
|
||||
|
||||
let rows = Value::List(vec![Value::Map(vec![("qty".into(), Value::Int(1))])]);
|
||||
let path = Value::List(vec![Value::Int(1), Value::Text("qty".into())]);
|
||||
let rows2 = collection_put(&rows, &path, &Value::Int(9)).unwrap();
|
||||
let row = match &rows2 {
|
||||
Value::List(xs) => &xs[0],
|
||||
_ => panic!(),
|
||||
};
|
||||
assert!(matches!(
|
||||
map_get(row, &Value::Text("qty".into())).unwrap(),
|
||||
Value::Int(9)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_none_single_key() {
|
||||
let m = collection_put(&Value::None, &Value::Text("k".into()), &Value::Text("v".into()))
|
||||
.unwrap();
|
||||
assert!(matches!(m, Value::Map(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod task_scale_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unique_preserves_signed_zero_nan_and_nested_equality(){
|
||||
let xs=Value::List(vec![Value::Num(-0.0),Value::Num(0.0),Value::Num(f64::NAN),Value::Num(f64::NAN),Value::Int(0),Value::List(vec![Value::Num(-0.0)]),Value::List(vec![Value::Num(0.0)])]);
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};
|
||||
assert_eq!(out.len(),5);assert_eq!(out[0],Value::Num(-0.0));assert_eq!(out[3],Value::Int(0));
|
||||
}
|
||||
#[test]
|
||||
fn mixed_order_is_transitive_and_exact_at_integer_float_boundary(){
|
||||
let values=[Value::Int(2),Value::Int(10),Value::Text("11".into()),Value::Int(i64::MAX),Value::Num(i64::MAX as f64),Value::Num(f64::NAN),Value::Num(-0.0),Value::Bool(false),Value::None];
|
||||
for a in &values{for b in &values{for c in &values{
|
||||
if cmp_value(a,b).is_le()&&cmp_value(b,c).is_le(){assert!(cmp_value(a,c).is_le(),"{a:?} {b:?} {c:?}");}
|
||||
}}}
|
||||
assert!(cmp_value(&Value::Int(i64::MAX),&Value::Num(i64::MAX as f64)).is_lt());
|
||||
}
|
||||
#[test]
|
||||
fn bulk_unique_handles_one_hundred_thousand_values(){
|
||||
let xs=Value::List((0..100_000).map(|n|Value::Int(n%50_000)).collect());
|
||||
let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};assert_eq!(out.len(),50_000);
|
||||
}
|
||||
}
|
||||
@@ -1,584 +0,0 @@
|
||||
//! Field-driven collection transforms. No string evaluation or callback language.
|
||||
use super::{as_text, collection::cmp_value};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn list(v: &Value) -> Result<&[Value], String> {
|
||||
match v {
|
||||
Value::List(xs) => Ok(xs),
|
||||
_ => Err("expected list".into()),
|
||||
}
|
||||
}
|
||||
fn record(v: &Value) -> Result<&[(String, Value)], String> {
|
||||
match v {
|
||||
Value::Map(m) => Ok(m),
|
||||
_ => Err("expected record map".into()),
|
||||
}
|
||||
}
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
record(v)?
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| format!("missing field {key}"))
|
||||
}
|
||||
fn strings(v: &Value) -> Result<Vec<String>, String> {
|
||||
list(v)?
|
||||
.iter()
|
||||
.map(|v| as_text(v, "key").map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
fn integer(v: &Value) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err("expected integer".into()),
|
||||
}
|
||||
}
|
||||
fn number(v: &Value) -> Result<f64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n as f64),
|
||||
Value::Num(n) if n.is_finite() => Ok(*n),
|
||||
_ => Err("expected finite number".into()),
|
||||
}
|
||||
}
|
||||
fn row(fields: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
// Structural equality is type-sensitive and map-order-sensitive, like Value::eq.
|
||||
// Fingerprints accelerate buckets; equality is still checked inside each bucket.
|
||||
pub(super) fn fingerprint(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Num(n) if *n == 0.0 => "Num(0)".into(),
|
||||
Value::List(xs) => format!("List{:?}", xs.iter().map(fingerprint).collect::<Vec<_>>()),
|
||||
Value::Map(xs) => format!(
|
||||
"Map{:?}",
|
||||
xs.iter()
|
||||
.map(|(k, v)| (k, fingerprint(v)))
|
||||
.collect::<Vec<_>>()
|
||||
),
|
||||
Value::Formula(formula) => format!("Formula{}", formula.as_display()),
|
||||
_ => format!("{v:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::ListRange => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let end = integer(arg(b, "end")?)?;
|
||||
let step = integer(arg(b, "step")?)?;
|
||||
if step == 0 {
|
||||
return Err("range step cannot be zero".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut n = start;
|
||||
while if step > 0 { n < end } else { n > end } {
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("range exceeds 1000000 items".into());
|
||||
}
|
||||
out.push(Value::Int(n));
|
||||
match n.checked_add(step) {
|
||||
Some(next) => n = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListEnumerate => {
|
||||
let start = integer(arg(b, "start")?)?;
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
let index = start
|
||||
.checked_add(i as i64)
|
||||
.ok_or("enumerate index overflow")?;
|
||||
Ok(row(vec![
|
||||
("index", Value::Int(index)),
|
||||
("value", v.clone()),
|
||||
]))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListPluck => {
|
||||
let key = text(b, "key")?;
|
||||
Ok(Value::List(
|
||||
list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| field(v, key).cloned())
|
||||
.collect::<Result<_, _>>()?,
|
||||
))
|
||||
}
|
||||
HostFn::ListProject => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
if keys.iter().collect::<HashSet<_>>().len() != keys.len() {
|
||||
return Err("project keys must be unique".into());
|
||||
}
|
||||
let out = list(arg(b, "list")?)?
|
||||
.iter()
|
||||
.map(|v| {
|
||||
keys.iter()
|
||||
.map(|k| Ok((k.clone(), field(v, k)?.clone())))
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
.map(Value::Map)
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListWhere => {
|
||||
let key = text(b, "key")?;
|
||||
let op = text(b, "op")?;
|
||||
let wanted = arg(b, "value")?;
|
||||
if !matches!(
|
||||
op,
|
||||
"eq" | "ne" | "gt" | "ge" | "lt" | "le" | "contains" | "in"
|
||||
) {
|
||||
return Err(format!("unknown where operator {op}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let got = field(v, key)?;
|
||||
let yes = match op {
|
||||
"eq" => got == wanted,
|
||||
"ne" => got != wanted,
|
||||
"gt" | "ge" | "lt" | "le" => {
|
||||
let order = match (got, wanted) {
|
||||
(Value::Text(a), Value::Text(b)) => a.cmp(b),
|
||||
_ => number(got)?
|
||||
.partial_cmp(&number(wanted)?)
|
||||
.ok_or("unordered comparison")?,
|
||||
};
|
||||
match op {
|
||||
"gt" => order.is_gt(),
|
||||
"ge" => order.is_ge(),
|
||||
"lt" => order.is_lt(),
|
||||
_ => order.is_le(),
|
||||
}
|
||||
}
|
||||
"contains" => match got {
|
||||
Value::List(xs) => xs.contains(wanted),
|
||||
Value::Text(s) => s.contains(as_text(wanted, "value")?),
|
||||
_ => return Err("contains needs text or list".into()),
|
||||
},
|
||||
"in" => list(wanted)?.contains(got),
|
||||
_ => return Err(format!("unknown where operator {op}")),
|
||||
};
|
||||
if yes {
|
||||
out.push(v.clone())
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::ListGroupBy | HostFn::ListUniqueBy => {
|
||||
let key = text(b, "key")?;
|
||||
let mut groups: Vec<(Value, Vec<Value>)> = Vec::new();
|
||||
let mut index: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let k = field(v, key)?;
|
||||
let fp = fingerprint(k);
|
||||
let bucket = index.entry(fp).or_default();
|
||||
if let Some(i) = bucket.iter().find(|i| groups[**i].0 == *k) {
|
||||
groups[*i].1.push(v.clone());
|
||||
} else {
|
||||
bucket.push(groups.len());
|
||||
groups.push((k.clone(), vec![v.clone()]));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
groups
|
||||
.into_iter()
|
||||
.map(|(key, rows)| {
|
||||
if id == HostFn::ListUniqueBy {
|
||||
rows.into_iter().next().unwrap()
|
||||
} else {
|
||||
row(vec![
|
||||
("key", key),
|
||||
("count", Value::Int(rows.len() as i64)),
|
||||
("rows", Value::List(rows)),
|
||||
])
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListAggregate => {
|
||||
let xs = list(arg(b, "list")?)?;
|
||||
let op = text(b, "op")?;
|
||||
if op == "count" {
|
||||
return Ok(Value::Int(xs.len() as i64));
|
||||
}
|
||||
let key = arg(b, "key")?;
|
||||
let values = xs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
if matches!(key, Value::None) {
|
||||
Ok(v)
|
||||
} else {
|
||||
field(v, as_text(key, "key")?)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
if op == "sum" && values.iter().all(|v| matches!(v, Value::Int(_))) {
|
||||
let sum = values.into_iter().try_fold(0i64, |sum, v| {
|
||||
sum.checked_add(integer(v)?)
|
||||
.ok_or_else(|| "sum integer overflow".to_string())
|
||||
})?;
|
||||
return Ok(Value::Int(sum));
|
||||
}
|
||||
let nums = values
|
||||
.into_iter()
|
||||
.map(number)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let n = match op {
|
||||
"sum" => nums.iter().sum(),
|
||||
"mean" if !nums.is_empty() => nums.iter().sum::<f64>() / nums.len() as f64,
|
||||
"min" if !nums.is_empty() => nums.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
"max" if !nums.is_empty() => nums.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
_ => {
|
||||
return Err(
|
||||
"aggregate needs sum/count/min/max/mean; empty min/max/mean is invalid"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("aggregate overflow".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
HostFn::ListSortKeys => {
|
||||
let keys = strings(arg(b, "keys")?)?;
|
||||
let descending = matches!(arg(b, "descending")?, Value::Bool(true));
|
||||
let mut xs = list(arg(b, "list")?)?.to_vec();
|
||||
for v in &xs {
|
||||
for k in &keys {
|
||||
field(v, k)?;
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| {
|
||||
let mut order = std::cmp::Ordering::Equal;
|
||||
for k in &keys {
|
||||
order = cmp_value(field(a, k).unwrap(), field(b, k).unwrap());
|
||||
if !order.is_eq() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if descending {
|
||||
order.reverse()
|
||||
} else {
|
||||
order
|
||||
}
|
||||
});
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
HostFn::ListRename => {
|
||||
let names = record(arg(b, "fields")?)?;
|
||||
for (_, v) in names {
|
||||
as_text(v, "new field name")?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for v in list(arg(b, "list")?)? {
|
||||
let mut seen = HashSet::new();
|
||||
let mut fields = Vec::new();
|
||||
for (k, v) in record(v)? {
|
||||
let name = names
|
||||
.iter()
|
||||
.find(|(old, _)| old == k)
|
||||
.map(|(_, v)| as_text(v, "name").unwrap())
|
||||
.unwrap_or(k);
|
||||
if !seen.insert(name) {
|
||||
return Err(format!("rename conflict: {name}"));
|
||||
}
|
||||
fields.push((name.into(), v.clone()));
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableFromColumns => {
|
||||
let columns = record(arg(b, "columns")?)?;
|
||||
let n = columns
|
||||
.first()
|
||||
.map(|(_, v)| list(v).map(|xs| xs.len()))
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
for (_, v) in columns {
|
||||
if list(v)?.len() != n {
|
||||
return Err("column lengths differ".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
Value::Map(
|
||||
columns
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), list(v).unwrap()[i].clone()))
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::TableToColumns => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
if rows.is_empty() {
|
||||
return Ok(Value::Map(vec![]));
|
||||
}
|
||||
let keys: Vec<_> = record(&rows[0])?.iter().map(|(k, _)| k.clone()).collect();
|
||||
for v in rows {
|
||||
let fields = record(v)?;
|
||||
if fields.len() != keys.len()
|
||||
|| keys.iter().any(|k| !fields.iter().any(|(f, _)| f == k))
|
||||
{
|
||||
return Err("rows have different fields".into());
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(
|
||||
keys.into_iter()
|
||||
.map(|k| {
|
||||
let values = rows.iter().map(|v| field(v, &k).unwrap().clone()).collect();
|
||||
(k, Value::List(values))
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
HostFn::ListJoin => {
|
||||
let a = list(arg(b, "a")?)?;
|
||||
let b_rows = list(arg(b, "b")?)?;
|
||||
let key = text(b, "key")?;
|
||||
let right_key = text(b, "right_key")?;
|
||||
let mode = text(b, "mode")?;
|
||||
if !matches!(mode, "inner" | "left") {
|
||||
return Err("join mode must be inner or left".into());
|
||||
}
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in b_rows {
|
||||
index
|
||||
.entry(fingerprint(field(v, right_key)?))
|
||||
.or_default()
|
||||
.push(v);
|
||||
}
|
||||
let right_fields: Vec<_> = b_rows
|
||||
.first()
|
||||
.map(|v| record(v).map(|m| m.iter().map(|(k, _)| k.clone()).collect()))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
for right in b_rows {
|
||||
let fields = record(right)?;
|
||||
if fields.len() != right_fields.len()
|
||||
|| right_fields
|
||||
.iter()
|
||||
.any(|key| !fields.iter().any(|(k, _)| k == key))
|
||||
{
|
||||
return Err("join right rows have different fields".into());
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for left in a {
|
||||
let left_key = field(left, key)?;
|
||||
let hits = index.get(&fingerprint(left_key));
|
||||
let matches: Vec<Option<&Value>> = match hits {
|
||||
Some(h) => {
|
||||
let values: Vec<_> = h
|
||||
.iter()
|
||||
.filter(|v| field(v, right_key).is_ok_and(|key| key == left_key))
|
||||
.map(|v| Some(*v))
|
||||
.collect();
|
||||
if values.is_empty() && mode == "left" {
|
||||
vec![None]
|
||||
} else {
|
||||
values
|
||||
}
|
||||
}
|
||||
None if mode == "left" => vec![None],
|
||||
_ => vec![],
|
||||
};
|
||||
for hit in matches {
|
||||
let mut fields = record(left)?.to_vec();
|
||||
let source = hit.map(record).transpose()?;
|
||||
for k in &right_fields {
|
||||
if k == right_key && key == right_key {
|
||||
continue;
|
||||
}
|
||||
let name = if fields.iter().any(|(f, _)| f == k) {
|
||||
format!("right_{k}")
|
||||
} else {
|
||||
k.clone()
|
||||
};
|
||||
if fields.iter().any(|(f, _)| f == &name) {
|
||||
return Err(format!("join field conflict: {name}"));
|
||||
}
|
||||
let value = source
|
||||
.and_then(|m| m.iter().find(|(f, _)| f == k))
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None);
|
||||
fields.push((name, value));
|
||||
}
|
||||
if out.len() >= 1_000_000 {
|
||||
return Err("join exceeds 1000000 rows".into());
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableCast => {
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut out = Vec::new();
|
||||
for (i, v) in list(arg(b, "rows")?)?.iter().enumerate() {
|
||||
let mut fields = record(v)?.to_vec();
|
||||
for (k, ty) in schema {
|
||||
let value = field(v, k)?;
|
||||
let ty = as_text(ty, "type")?;
|
||||
let cast = cast(value, ty).map_err(|e| format!("row {i} field {k}: {e}"))?;
|
||||
fields.iter_mut().find(|(name, _)| name == k).unwrap().1 = cast;
|
||||
}
|
||||
out.push(Value::Map(fields));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableSummarize => {
|
||||
let groups = call(_ctx, HostFn::ListGroupBy, b)?;
|
||||
let field_name = text(b, "field")?;
|
||||
let op = text(b, "op")?;
|
||||
let mut out = Vec::new();
|
||||
for group in list(&groups)? {
|
||||
let rows = field(group, "rows")?;
|
||||
let mut args = HashMap::new();
|
||||
args.insert("list".into(), rows.clone());
|
||||
args.insert("key".into(), Value::Text(field_name.into()));
|
||||
args.insert("op".into(), Value::Text(op.into()));
|
||||
let value = call(_ctx, HostFn::ListAggregate, &args)?;
|
||||
out.push(row(vec![
|
||||
("key", field(group, "key")?.clone()),
|
||||
("count", field(group, "count")?.clone()),
|
||||
("value", value),
|
||||
]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::TableTryCast => {
|
||||
let answer =
|
||||
call(_ctx, HostFn::TableCast, b).map_err(|e| format!("validation_failed: {e}"));
|
||||
Ok(super::result::capture("table.cast", answer))
|
||||
}
|
||||
HostFn::TableValidate => {
|
||||
let rows = list(arg(b, "rows")?)?;
|
||||
let schema = record(arg(b, "schema")?)?;
|
||||
let mut errors = Vec::new();
|
||||
for (index, value) in rows.iter().enumerate() {
|
||||
let fields = record(value)?;
|
||||
for (key, ty) in schema {
|
||||
let name = as_text(ty, "type")?;
|
||||
let ty = crate::contract::Ty::parse(name);
|
||||
let got = fields.iter().find(|(k, _)| k == key).map(|(_, v)| v);
|
||||
if !got.is_some_and(|v| ty.matches_value(v)) {
|
||||
errors.push(row(vec![
|
||||
("row", Value::Int(index as i64)),
|
||||
("field", Value::Text(key.clone())),
|
||||
("expected", Value::Text(name.into())),
|
||||
(
|
||||
"actual",
|
||||
Value::Text(
|
||||
got.map(crate::contract::type_of)
|
||||
.unwrap_or("missing")
|
||||
.into(),
|
||||
),
|
||||
),
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(super::result::capture(
|
||||
"table.validate",
|
||||
Ok(arg(b, "rows")?.clone()),
|
||||
))
|
||||
} else {
|
||||
let mut result = super::result::capture(
|
||||
"table.validate",
|
||||
Err("validation_failed: records do not match schema".into()),
|
||||
);
|
||||
if let Value::Map(fields) = &mut result {
|
||||
if let Some((_, Value::Map(error))) =
|
||||
fields.iter_mut().find(|(k, _)| k == "error")
|
||||
{
|
||||
error.push(("details".into(), Value::List(errors)));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
HostFn::ListUnion | HostFn::ListIntersection | HostFn::ListDifference => {
|
||||
let left = list(arg(b, "a")?)?;
|
||||
let right = list(arg(b, "b")?)?;
|
||||
let mut index: HashMap<String, Vec<&Value>> = HashMap::new();
|
||||
for v in right {
|
||||
index.entry(fingerprint(v)).or_default().push(v)
|
||||
}
|
||||
let mut values = Vec::new();
|
||||
for v in left {
|
||||
let contains = index
|
||||
.get(&fingerprint(v))
|
||||
.is_some_and(|bucket| bucket.iter().any(|r| *r == v));
|
||||
if id == HostFn::ListUnion
|
||||
|| (id == HostFn::ListIntersection && contains)
|
||||
|| (id == HostFn::ListDifference && !contains)
|
||||
{
|
||||
values.push(v.clone())
|
||||
}
|
||||
}
|
||||
if id == HostFn::ListUnion {
|
||||
values.extend_from_slice(right)
|
||||
}
|
||||
super::collection::list_unique(&Value::List(values))
|
||||
}
|
||||
_ => Err("not a collection transform".into()),
|
||||
}
|
||||
}
|
||||
fn cast(v: &Value, ty: &str) -> Result<Value, String> {
|
||||
match ty {
|
||||
"text" => Ok(Value::Text(v.as_display())),
|
||||
"int" => match v {
|
||||
Value::Int(_) => Ok(v.clone()),
|
||||
Value::Text(s) => s
|
||||
.parse::<i64>()
|
||||
.map(Value::Int)
|
||||
.map_err(|_| "invalid integer".into()),
|
||||
_ => Err("int expects integer or text".into()),
|
||||
},
|
||||
"number" => {
|
||||
let n = match v {
|
||||
Value::Text(s) => s.parse::<f64>().map_err(|_| "invalid number")?,
|
||||
_ => number(v)?,
|
||||
};
|
||||
if !n.is_finite() {
|
||||
return Err("non-finite number".into());
|
||||
}
|
||||
Ok(Value::Num(n))
|
||||
}
|
||||
"bool" => match v {
|
||||
Value::Bool(_) => Ok(v.clone()),
|
||||
Value::Text(s) => match s.as_str() {
|
||||
"true" | "True" => Ok(Value::Bool(true)),
|
||||
"false" | "False" => Ok(Value::Bool(false)),
|
||||
_ => Err("invalid bool".into()),
|
||||
},
|
||||
_ => Err("bool expects bool or text".into()),
|
||||
},
|
||||
"any" => Ok(v.clone()),
|
||||
_ => Err(format!("unknown cast type {ty}")),
|
||||
}
|
||||
}
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
//! Minimal RFC4180 CSV for Mid M4 (`lib/csv`).
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
/// Parse CSV text into a list of maps (first row = headers).
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let rows = parse_rows(s)?;
|
||||
if rows.is_empty() {
|
||||
return Ok(Value::List(vec![]));
|
||||
}
|
||||
let headers = rows[0].clone();
|
||||
if headers.is_empty() {
|
||||
return Err("csv.parse: header row is empty".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for row in rows.into_iter().skip(1) {
|
||||
let mut map = Vec::new();
|
||||
for (i, key) in headers.iter().enumerate() {
|
||||
let val = row.get(i).cloned().unwrap_or_default();
|
||||
map.push((key.clone(), Value::Text(val)));
|
||||
}
|
||||
out.push(Value::Map(map));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
/// Serialize list of maps to CSV (header order = first row's keys).
|
||||
pub fn stringify(rows: &Value) -> Result<Value, String> {
|
||||
let list = match rows {
|
||||
Value::List(xs) => xs,
|
||||
_ => return Err("csv.stringify: rows needs list".into()),
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(Value::Text(String::new()));
|
||||
}
|
||||
let first = match &list[0] {
|
||||
Value::Map(m) => m,
|
||||
_ => return Err("csv.stringify: each row needs map".into()),
|
||||
};
|
||||
let headers: Vec<String> = first.iter().map(|(k, _)| k.clone()).collect();
|
||||
let mut lines = Vec::new();
|
||||
lines.push(headers.iter().map(|h| escape_field(h)).collect::<Vec<_>>().join(","));
|
||||
for row in list {
|
||||
let map = match row {
|
||||
Value::Map(m) => m,
|
||||
_ => return Err("csv.stringify: each row needs map".into()),
|
||||
};
|
||||
let mut fields = Vec::new();
|
||||
for h in &headers {
|
||||
let cell = map
|
||||
.iter()
|
||||
.find(|(k, _)| k == h)
|
||||
.map(|(_, v)| value_to_cell(v))
|
||||
.unwrap_or_default();
|
||||
fields.push(escape_field(&cell));
|
||||
}
|
||||
lines.push(fields.join(","));
|
||||
}
|
||||
Ok(Value::Text(lines.join("\n")))
|
||||
}
|
||||
|
||||
fn value_to_cell(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Text(s) => s.clone(),
|
||||
Value::Int(n) => n.to_string(),
|
||||
Value::Num(n) => n.to_string(),
|
||||
Value::Bool(b) => {
|
||||
if *b {
|
||||
"True".into()
|
||||
} else {
|
||||
"False".into()
|
||||
}
|
||||
}
|
||||
Value::None => String::new(),
|
||||
other => other.as_display(),
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_field(s: &str) -> String {
|
||||
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
|
||||
format!("\"{}\"", s.replace('"', "\"\""))
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_rows(input: &str) -> Result<Vec<Vec<String>>, String> {
|
||||
let mut rows = Vec::new();
|
||||
let mut row = Vec::new();
|
||||
let mut field = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
let mut in_quotes = false;
|
||||
while let Some(c) = chars.next() {
|
||||
if in_quotes {
|
||||
if c == '"' {
|
||||
if chars.peek() == Some(&'"') {
|
||||
chars.next();
|
||||
field.push('"');
|
||||
} else {
|
||||
in_quotes = false;
|
||||
}
|
||||
} else {
|
||||
field.push(c);
|
||||
}
|
||||
} else {
|
||||
match c {
|
||||
'"' => in_quotes = true,
|
||||
',' => {
|
||||
row.push(std::mem::take(&mut field));
|
||||
}
|
||||
'\r' => {
|
||||
// swallow optional \n
|
||||
if chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
}
|
||||
row.push(std::mem::take(&mut field));
|
||||
rows.push(std::mem::take(&mut row));
|
||||
}
|
||||
'\n' => {
|
||||
row.push(std::mem::take(&mut field));
|
||||
rows.push(std::mem::take(&mut row));
|
||||
}
|
||||
_ => field.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
if in_quotes {
|
||||
return Err("csv.parse: unterminated quote".into());
|
||||
}
|
||||
if !field.is_empty() || !row.is_empty() {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
} else if !input.is_empty() && input.ends_with('\n') {
|
||||
// trailing newline already flushed last row
|
||||
}
|
||||
// Drop a single trailing empty row produced by final newline only when last row empty?
|
||||
while rows.last().is_some_and(|r| r.len() == 1 && r[0].is_empty()) {
|
||||
// only drop if it's a spurious empty line at end with no fields
|
||||
if rows.len() > 1 {
|
||||
rows.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_simple() {
|
||||
let text = Value::Text("a,b\n1,2\n3,\"x,y\"\n".into());
|
||||
let rows = parse(&text).unwrap();
|
||||
let Value::List(ref xs) = rows else {
|
||||
panic!("list");
|
||||
};
|
||||
assert_eq!(xs.len(), 2);
|
||||
let out = stringify(&rows).unwrap();
|
||||
let again = parse(&out).unwrap();
|
||||
assert_eq!(again, rows);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
//! Recoverable parsing and timezone operations at the public data boundary.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
_ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match id {
|
||||
HostFn::TomlStringify => super::toml_ops::stringify(arg(b, "value")?),
|
||||
HostFn::TomlTryParse => Ok(super::result::capture(
|
||||
"toml.parse",
|
||||
super::toml_ops::parse(arg(b, "text")?).map_err(|e| format!("invalid_toml: {e}")),
|
||||
)),
|
||||
HostFn::DatetimeLocal => Ok(super::result::capture(
|
||||
"datetime.parse_local",
|
||||
super::datetime::local(arg(b, "text")?, arg(b, "zone")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
HostFn::DatetimeCalendarAdd => Ok(super::result::capture(
|
||||
"datetime.add_calendar",
|
||||
super::datetime::calendar_add(arg(b, "dt")?, arg(b, "days")?, arg(b, "ambiguity")?),
|
||||
)),
|
||||
_ => Err("not a data operation".into()),
|
||||
}
|
||||
}
|
||||
@@ -1,337 +0,0 @@
|
||||
//! Calendar moments with fixed offsets or embedded IANA timezone rules.
|
||||
//!
|
||||
//! Moments retain `{unix, zone, iso}`; `zone` is the numeric offset.
|
||||
//! Named zones additionally retain `timezone`, so future instants and calendar
|
||||
//! arithmetic recompute offsets using embedded IANA/DST rules.
|
||||
|
||||
use crate::host::as_text;
|
||||
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc, Offset, LocalResult};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn optional_i64(v: Option<&Value>, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(0),
|
||||
Some(x) => as_i64(x, label),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_offset(off: FixedOffset) -> String {
|
||||
let secs = off.local_minus_utc();
|
||||
let sign = if secs >= 0 { '+' } else { '-' };
|
||||
let abs = secs.abs();
|
||||
let h = abs / 3600;
|
||||
let m = (abs % 3600) / 60;
|
||||
format!("{sign}{h:02}:{m:02}")
|
||||
}
|
||||
|
||||
fn parse_zone(s: &str) -> Result<FixedOffset, String> {
|
||||
let s = s.trim();
|
||||
if s.is_empty() || s.eq_ignore_ascii_case("utc") || s.eq_ignore_ascii_case("gmt") || s == "Z" {
|
||||
return FixedOffset::east_opt(0).ok_or_else(|| "invalid UTC offset".into());
|
||||
}
|
||||
// Common fixed-offset IANA aliases (no DST).
|
||||
let aliased = match s {
|
||||
"Asia/Shanghai" | "Asia/Hong_Kong" | "Asia/Taipei" | "Asia/Singapore" => Some(8 * 3600),
|
||||
"Asia/Tokyo" | "Asia/Seoul" => Some(9 * 3600),
|
||||
"Asia/Kolkata" | "Asia/Calcutta" => Some(5 * 3600 + 30 * 60),
|
||||
"Europe/Moscow" => Some(3 * 3600),
|
||||
"America/Phoenix" => Some(-7 * 3600),
|
||||
"Pacific/Honolulu" => Some(-10 * 3600),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(secs) = aliased {
|
||||
return FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone: {s}"));
|
||||
}
|
||||
let (sign, rest) = if let Some(r) = s.strip_prefix('+') {
|
||||
(1i32, r)
|
||||
} else if let Some(r) = s.strip_prefix('-') {
|
||||
(-1i32, r)
|
||||
} else {
|
||||
return Err(format!(
|
||||
"unknown zone {s:?}; use +HH:MM / -HH:MM / UTC or a fixed-offset alias (e.g. Asia/Shanghai)"
|
||||
));
|
||||
};
|
||||
let (hh, mm) = if let Some((h, m)) = rest.split_once(':') {
|
||||
(
|
||||
h.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
m.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone minute in {s}"))?,
|
||||
)
|
||||
} else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
(
|
||||
rest[..2]
|
||||
.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
rest[2..]
|
||||
.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone minute in {s}"))?,
|
||||
)
|
||||
} else if rest.len() == 2 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
(
|
||||
rest.parse::<i32>()
|
||||
.map_err(|_| format!("bad zone hour in {s}"))?,
|
||||
0,
|
||||
)
|
||||
} else {
|
||||
return Err(format!("bad zone offset {s}"));
|
||||
};
|
||||
if !(0..=14).contains(&hh) || !(0..60).contains(&mm) {
|
||||
return Err(format!("zone offset out of range: {s}"));
|
||||
}
|
||||
let secs = sign * (hh * 3600 + mm * 60);
|
||||
FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone offset: {s}"))
|
||||
}
|
||||
|
||||
fn moment(unix: i64, zone: FixedOffset) -> Result<Value, String> {
|
||||
let dt = zone
|
||||
.timestamp_opt(unix, 0)
|
||||
.single()
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {unix}"))?;
|
||||
Ok(Value::Map(vec![
|
||||
("unix".into(), Value::Int(unix)),
|
||||
("zone".into(), Value::Text(format_offset(zone))),
|
||||
(
|
||||
"iso".into(),
|
||||
Value::Text(dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
|
||||
),
|
||||
]))
|
||||
}
|
||||
|
||||
fn zone_of_moment(m: &[(String, Value)]) -> Result<FixedOffset, String> {
|
||||
for (k, v) in m {
|
||||
if k == "zone" {
|
||||
return parse_zone(as_text(v, "zone")?);
|
||||
}
|
||||
}
|
||||
Ok(FixedOffset::east_opt(0).unwrap())
|
||||
}
|
||||
|
||||
fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok((*n, FixedOffset::east_opt(0).unwrap())),
|
||||
Value::Map(entries) => {
|
||||
let mut unix = None;
|
||||
for (k, val) in entries {
|
||||
if k == "unix" {
|
||||
unix = Some(as_i64(val, "unix")?);
|
||||
}
|
||||
}
|
||||
let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?;
|
||||
let offset = if let Some((_, Value::Text(zone))) = entries.iter().find(|(k,_)|k=="timezone") {
|
||||
let zone: chrono_tz::Tz = zone.parse().map_err(|_| format!("unknown IANA timezone {zone}"))?;
|
||||
zone.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.offset().fix()
|
||||
} else { zone_of_moment(entries)? };
|
||||
Ok((unix, offset))
|
||||
}
|
||||
Value::Text(s) => {
|
||||
// Treat bare ISO/RFC3339 text as a moment.
|
||||
let parsed = parse_text(s, None)?;
|
||||
unix_of_value(&parsed)
|
||||
}
|
||||
_ => Err("datetime needs int unix, moment map, or ISO text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now() -> Result<Value, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err("datetime.now unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let secs = Utc::now().timestamp();
|
||||
moment(secs, FixedOffset::east_opt(0).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
match zone {
|
||||
None | Some(Value::None) => moment(secs, FixedOffset::east_opt(0).unwrap()),
|
||||
Some(zone) => moment_in_zone(secs, as_text(zone,"zone")?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_unix(dt: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
Ok(Value::Int(secs))
|
||||
}
|
||||
|
||||
fn parse_text(text: &str, pattern: Option<&str>) -> Result<Value, String> {
|
||||
if let Some(pat) = pattern {
|
||||
if pat.eq_ignore_ascii_case("rfc3339") || pat.eq_ignore_ascii_case("iso") {
|
||||
return parse_rfc3339(text);
|
||||
}
|
||||
if let Ok(dt) = DateTime::parse_from_str(text, pat) {
|
||||
return moment(dt.timestamp(), *dt.offset());
|
||||
}
|
||||
let naive = NaiveDateTime::parse_from_str(text, pat)
|
||||
.or_else(|_| {
|
||||
NaiveDate::parse_from_str(text, pat).map(|d| d.and_hms_opt(0, 0, 0).unwrap())
|
||||
})
|
||||
.map_err(|e| format!("datetime.parse: {e}"))?;
|
||||
return moment(naive.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(v) = parse_rfc3339(text) {
|
||||
return Ok(v);
|
||||
}
|
||||
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S") {
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S") {
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
if let Ok(d) = NaiveDate::parse_from_str(text, "%Y-%m-%d") {
|
||||
let dt = d.and_hms_opt(0, 0, 0).unwrap();
|
||||
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
|
||||
}
|
||||
Err(format!(
|
||||
"datetime.parse: unrecognized {text:?}; pass pattern= or use RFC3339 / YYYY-MM-DD"
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_rfc3339(text: &str) -> Result<Value, String> {
|
||||
let dt = DateTime::parse_from_rfc3339(text).map_err(|e| format!("datetime.parse: {e}"))?;
|
||||
moment(dt.timestamp(), *dt.offset())
|
||||
}
|
||||
|
||||
pub fn parse(text: &Value, pattern: Option<&Value>) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let pat = match pattern {
|
||||
None | Some(Value::None) => None,
|
||||
Some(p) => Some(as_text(p, "pattern")?),
|
||||
};
|
||||
parse_text(t, pat)
|
||||
}
|
||||
|
||||
pub fn format(dt: &Value, style: Option<&Value>) -> Result<Value, String> {
|
||||
let (secs, zone) = unix_of_value(dt)?;
|
||||
let local = zone
|
||||
.timestamp_opt(secs, 0)
|
||||
.single()
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
|
||||
let style = match style {
|
||||
None | Some(Value::None) => "rfc3339",
|
||||
Some(s) => as_text(s, "style")?,
|
||||
};
|
||||
let out = match style {
|
||||
"rfc3339" | "iso" => local.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
"date" => local.format("%Y-%m-%d").to_string(),
|
||||
"time" => local.format("%H:%M:%S").to_string(),
|
||||
other => local.format(other).to_string(),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn add(
|
||||
dt: &Value,
|
||||
days: Option<&Value>,
|
||||
hours: Option<&Value>,
|
||||
minutes: Option<&Value>,
|
||||
seconds: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let (secs, zone) = unix_of_value(dt)?;
|
||||
let days = optional_i64(days, "days")?;
|
||||
let hours = optional_i64(hours, "hours")?;
|
||||
let minutes = optional_i64(minutes, "minutes")?;
|
||||
let seconds = optional_i64(seconds, "seconds")?;
|
||||
let delta = days.checked_mul(86400).and_then(|n|hours.checked_mul(3600).and_then(|h|n.checked_add(h)))
|
||||
.and_then(|n|minutes.checked_mul(60).and_then(|m|n.checked_add(m))).and_then(|n|n.checked_add(seconds))
|
||||
.ok_or("datetime.add overflow")?;
|
||||
let new_secs = secs.checked_add(delta).ok_or("datetime.add overflow")?;
|
||||
if let Some(zone) = named_zone(dt) { moment_in_zone(new_secs,zone) } else { moment(new_secs,zone) }
|
||||
}
|
||||
|
||||
pub fn in_zone(dt: &Value, zone: &Value) -> Result<Value, String> {
|
||||
let (secs, _) = unix_of_value(dt)?;
|
||||
moment_in_zone(secs, as_text(zone,"zone")?)
|
||||
}
|
||||
|
||||
fn named_zone(dt:&Value)->Option<&str>{
|
||||
let Value::Map(fields)=dt else{return None};
|
||||
fields.iter().find_map(|(k,v)|if k=="timezone"{if let Value::Text(zone)=v{Some(zone.as_str())}else{None}}else{None})
|
||||
}
|
||||
fn moment_in_zone(unix:i64,zone:&str)->Result<Value,String>{
|
||||
if let Ok(tz)=zone.parse::<chrono_tz::Tz>(){
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?;
|
||||
let mut value=moment(unix,local.offset().fix())?;
|
||||
if let Value::Map(fields)=&mut value{fields.push(("timezone".into(),Value::Text(zone.into())));}
|
||||
Ok(value)
|
||||
}else{moment(unix,parse_zone(zone)?)}
|
||||
}
|
||||
fn choose_local(tz:chrono_tz::Tz,local:NaiveDateTime,ambiguity:&str)->Result<i64,String>{
|
||||
if !matches!(ambiguity,"reject"|"earliest"|"latest"){return Err("ambiguity must be reject/earliest/latest".into())}
|
||||
match tz.from_local_datetime(&local){
|
||||
LocalResult::Single(dt)=>Ok(dt.timestamp()),
|
||||
LocalResult::None=>Err("nonexistent_time: local time is in a DST gap".into()),
|
||||
LocalResult::Ambiguous(a,b)=>match ambiguity{
|
||||
"earliest"=>Ok(a.timestamp().min(b.timestamp())),
|
||||
"latest"=>Ok(a.timestamp().max(b.timestamp())),
|
||||
_=>Err("ambiguous_time: DST fold; select earliest or latest".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn local(text:&Value,zone:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let source=as_text(text,"text")?.replace('T'," ");
|
||||
let local=NaiveDateTime::parse_from_str(&source,"%Y-%m-%d %H:%M:%S").map_err(|e|format!("datetime.parse_local: {e}"))?;
|
||||
let zone=as_text(zone,"zone")?;let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
moment_in_zone(choose_local(tz,local,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
pub(super) fn calendar_add(dt:&Value,days:&Value,ambiguity:&Value)->Result<Value,String>{
|
||||
let (unix,_)=unix_of_value(dt)?;let days=as_i64(days,"days")?;
|
||||
let Some(zone)=named_zone(dt) else{return add(dt,Some(&Value::Int(days)),None,None,None)};
|
||||
let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?;
|
||||
let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.naive_local();
|
||||
let duration=Duration::try_days(days).ok_or("calendar day overflow")?;
|
||||
let next=local.checked_add_signed(duration).ok_or("calendar date overflow")?;
|
||||
moment_in_zone(choose_local(tz,next,as_text(ambiguity,"ambiguity")?)?,zone)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn from_unix_utc_iso() {
|
||||
let m = from_unix(&Value::Int(0), None).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
|
||||
assert_eq!(iso, Value::Text("1970-01-01T00:00:00Z".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shanghai_alias() {
|
||||
let m = from_unix(&Value::Int(0), Some(&Value::Text("Asia/Shanghai".into()))).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
|
||||
assert_eq!(iso, Value::Text("1970-01-01T08:00:00+08:00".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_rfc3339_roundtrip() {
|
||||
let m = parse(
|
||||
&Value::Text("2020-01-02T03:04:05+08:00".into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let u = to_unix(&m).unwrap();
|
||||
assert_eq!(u, Value::Int(1_577_905_445));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_day() {
|
||||
let m = from_unix(&Value::Int(0), None).unwrap();
|
||||
let n = add(&m, Some(&Value::Int(1)), None, None, None).unwrap();
|
||||
assert_eq!(to_unix(&n).unwrap(), Value::Int(86_400));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,455 +0,0 @@
|
||||
//! Inert Markdown structure using the same pulldown-cmark parser as rendering.
|
||||
//! Byte ranges always refer to the original UTF-8 source; nothing is executed.
|
||||
use super::{as_text, result};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
type Args = HashMap<String, Value>;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn map(values: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(values.into_iter().map(|(k, v)| (k.into(), v)).collect())
|
||||
}
|
||||
fn string(v: impl Into<String>) -> Value {
|
||||
Value::Text(v.into())
|
||||
}
|
||||
fn num(v: usize) -> Value {
|
||||
Value::Int(v as i64)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Section {
|
||||
title: String,
|
||||
level: usize,
|
||||
start: usize,
|
||||
body: usize,
|
||||
end: usize,
|
||||
}
|
||||
fn sections(text: &str) -> Vec<Section> {
|
||||
let mut out: Vec<Section> = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Heading { level, .. }) => {
|
||||
let n = level as usize;
|
||||
for section in &mut out {
|
||||
if section.end == text.len() && section.level >= n {
|
||||
section.end = range.start
|
||||
}
|
||||
}
|
||||
out.push(Section {
|
||||
title: String::new(),
|
||||
level: n,
|
||||
start: range.start,
|
||||
body: range.end,
|
||||
end: text.len(),
|
||||
});
|
||||
active = Some(out.len() - 1);
|
||||
}
|
||||
Event::End(TagEnd::Heading(_)) => {
|
||||
if let Some(i) = active.take() {
|
||||
out[i].body = range.end
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(i) = active {
|
||||
out[i].title.push(' ')
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn unique_section<'a>(sections: &'a [Section], title: &str) -> Result<&'a Section, String> {
|
||||
let hits: Vec<_> = sections.iter().filter(|s| s.title == title).collect();
|
||||
match hits.as_slice() {
|
||||
[s] => Ok(s),
|
||||
[] => Err(format!("section not found: {title}")),
|
||||
_ => Err(format!("ambiguous section: {title}")),
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Table {
|
||||
start: usize,
|
||||
end: usize,
|
||||
headers: Vec<String>,
|
||||
rows: Vec<Vec<String>>,
|
||||
}
|
||||
fn tables(text: &str) -> Vec<Table> {
|
||||
let mut out = Vec::new();
|
||||
let mut table: Option<Table> = None;
|
||||
let mut header = false;
|
||||
let mut row = Vec::new();
|
||||
let mut cell: Option<String> = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
text,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Table(_)) => {
|
||||
table = Some(Table {
|
||||
start: range.start,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
Event::Start(Tag::TableHead) => {
|
||||
header = true;
|
||||
row.clear()
|
||||
}
|
||||
Event::End(TagEnd::TableHead) => {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.headers = std::mem::take(&mut row)
|
||||
}
|
||||
header = false
|
||||
}
|
||||
Event::Start(Tag::TableRow) => row.clear(),
|
||||
Event::End(TagEnd::TableRow) => {
|
||||
if !header {
|
||||
if let Some(t) = table.as_mut() {
|
||||
t.rows.push(std::mem::take(&mut row));
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Start(Tag::TableCell) => cell = Some(String::new()),
|
||||
Event::End(TagEnd::TableCell) => {
|
||||
if let Some(c) = cell.take() {
|
||||
row.push(c)
|
||||
}
|
||||
}
|
||||
Event::Text(t) | Event::Code(t) => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push_str(&t)
|
||||
}
|
||||
}
|
||||
Event::SoftBreak | Event::HardBreak => {
|
||||
if let Some(c) = cell.as_mut() {
|
||||
c.push('\n')
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Table) => {
|
||||
if let Some(mut t) = table.take() {
|
||||
t.end = range.end;
|
||||
out.push(t)
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn literal_value(expression: crate::ast::Expr) -> Result<Value, String> {
|
||||
use crate::ast::{Expr, Literal};
|
||||
match expression {
|
||||
Expr::Literal(literal) => Ok(match literal {
|
||||
Literal::None => Value::None,
|
||||
Literal::Bool(value) => Value::Bool(value),
|
||||
Literal::Int(value) => Value::Int(value),
|
||||
Literal::Num(value) => Value::Num(value),
|
||||
Literal::Text(value) => Value::Text(value),
|
||||
}),
|
||||
Expr::Unary { op: crate::ast::UnaryOp::Neg, expr } => match literal_value(*expr)? {
|
||||
Value::Int(value) => value.checked_neg().map(Value::Int).ok_or_else(|| "negative table literal overflows an integer".into()),
|
||||
Value::Num(value) => Ok(Value::Num(-value)),
|
||||
_ => Err("negative table literal requires a number".into()),
|
||||
},
|
||||
Expr::List(values) => values.into_iter().map(literal_value)
|
||||
.collect::<Result<Vec<_>, _>>().map(Value::List),
|
||||
Expr::Map(fields) => fields.into_iter()
|
||||
.map(|(key, value)| literal_value(value).map(|value| (key, value)))
|
||||
.collect::<Result<Vec<_>, _>>().map(Value::Map),
|
||||
_ => Err("document.table accepts literal data cells; variable references, interpolation and calls are not evaluated".into()),
|
||||
}
|
||||
}
|
||||
fn table_value(source: &str, title: Option<&str>, index: usize) -> Result<Value, String> {
|
||||
let section_list;
|
||||
let selected = if let Some(title) = title {
|
||||
section_list = sections(source);
|
||||
let section = unique_section(§ion_list, title)?;
|
||||
&source[section.body..section.end]
|
||||
} else {
|
||||
source
|
||||
};
|
||||
let found = tables(selected);
|
||||
let table = found.get(index).ok_or_else(|| format!(
|
||||
"document.table index {index} is out of range ({} tables)", found.len()))?;
|
||||
let expression = crate::parse::parse_gfm_table(&selected[table.start..table.end])
|
||||
.map_err(|error| format!("document.table: {error:#}"))?;
|
||||
literal_value(expression)
|
||||
}
|
||||
|
||||
fn check_digest(b: &Args, text: &str) -> Result<(), String> {
|
||||
if let Some(Value::Text(expected)) = b.get("expected_sha256") {
|
||||
if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected {
|
||||
return Err("conflict: document content changed".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let source = text(b, "text")?;
|
||||
match id {
|
||||
HostFn::DocumentSections => Ok(Value::List(
|
||||
sections(source)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
map(vec![
|
||||
("title", string(s.title)),
|
||||
("level", num(s.level)),
|
||||
("start", num(s.start)),
|
||||
("body_start", num(s.body)),
|
||||
("end", num(s.end)),
|
||||
("text", string(&source[s.body..s.end])),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentSection => {
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
Ok(string(&source[section.body..section.end]))
|
||||
}
|
||||
HostFn::DocumentReplaceSection => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let sections = sections(source);
|
||||
let section = unique_section(§ions, text(b, "title")?)?;
|
||||
let mut out = source[..section.body].to_string();
|
||||
let body = text(b, "body")?;
|
||||
if !out.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push('\n');
|
||||
out.push_str(body);
|
||||
if !body.ends_with('\n') {
|
||||
out.push('\n')
|
||||
}
|
||||
out.push_str(&source[section.end..]);
|
||||
Ok(string(out))
|
||||
})();
|
||||
Ok(result::capture("document.replace_section", change))
|
||||
}
|
||||
HostFn::DocumentTables => Ok(Value::List(
|
||||
tables(source)
|
||||
.into_iter()
|
||||
.map(|t| {
|
||||
map(vec![
|
||||
("start", num(t.start)),
|
||||
("end", num(t.end)),
|
||||
(
|
||||
"headers",
|
||||
Value::List(t.headers.into_iter().map(string).collect()),
|
||||
),
|
||||
(
|
||||
"rows",
|
||||
Value::List(
|
||||
t.rows
|
||||
.into_iter()
|
||||
.map(|r| Value::List(r.into_iter().map(string).collect()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
HostFn::DocumentTable => {
|
||||
let title = match b.get("title") {
|
||||
None | Some(Value::None) => None,
|
||||
Some(value) => Some(as_text(value, "title")?),
|
||||
};
|
||||
let index = match b.get("index") {
|
||||
None | Some(Value::None) => 0,
|
||||
Some(Value::Int(value)) if *value >= 0 =>
|
||||
usize::try_from(*value).map_err(|_| "table index too large")?,
|
||||
_ => return Err("table index must be a zero-based nonnegative integer".into()),
|
||||
};
|
||||
table_value(source, title, index)
|
||||
}
|
||||
HostFn::DocumentReplaceTable => {
|
||||
let change = (|| {
|
||||
check_digest(b, source)?;
|
||||
let index = match arg(b, "index")? {
|
||||
Value::Int(n) if *n >= 0 => *n as usize,
|
||||
_ => return Err("table index is zero-based nonnegative integer".into()),
|
||||
};
|
||||
let tables = tables(source);
|
||||
let table = tables.get(index).ok_or("table index out of range")?;
|
||||
fn cells(v: &Value) -> Result<Vec<String>, String> {
|
||||
let Value::List(xs) = v else {
|
||||
return Err("cells must be list of text".into());
|
||||
};
|
||||
xs.iter()
|
||||
.map(|v| {
|
||||
as_text(v, "cell").map(|s| {
|
||||
s.replace('\\', "\\\\")
|
||||
.replace('|', "\\|")
|
||||
.replace('\n', "<br>")
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let headers = cells(arg(b, "headers")?)?;
|
||||
if headers.is_empty() {
|
||||
return Err("table needs headers".into());
|
||||
}
|
||||
let Value::List(rows) = arg(b, "rows")? else {
|
||||
return Err("rows must be list".into());
|
||||
};
|
||||
let mut rendered = format!(
|
||||
"| {} |\n| {} |\n",
|
||||
headers.join(" | "),
|
||||
vec!["---"; headers.len()].join(" | ")
|
||||
);
|
||||
for row in rows {
|
||||
let row = cells(row)?;
|
||||
if row.len() != headers.len() {
|
||||
return Err("table row length differs from header".into());
|
||||
}
|
||||
rendered.push_str(&format!("| {} |\n", row.join(" | ")))
|
||||
}
|
||||
Ok(string(format!(
|
||||
"{}{}{}",
|
||||
&source[..table.start],
|
||||
rendered,
|
||||
&source[table.end..]
|
||||
)))
|
||||
})();
|
||||
Ok(result::capture("document.replace_table", change))
|
||||
}
|
||||
HostFn::DocumentLinks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active: Vec<(String, String, usize)> = Vec::new();
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||
active.push((dest_url.into_string(), String::new(), range.start))
|
||||
}
|
||||
Event::Text(s) | Event::Code(s) => {
|
||||
if let Some((_, text, _)) = active.last_mut() {
|
||||
text.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::Link) => {
|
||||
if let Some((url, text, start)) = active.pop() {
|
||||
out.push(map(vec![
|
||||
("label", string(text)),
|
||||
("target", string(url)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
HostFn::DocumentCodeBlocks => {
|
||||
let mut out = Vec::new();
|
||||
let mut active = None;
|
||||
for (event, range) in Parser::new_ext(
|
||||
source,
|
||||
Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS,
|
||||
)
|
||||
.into_offset_iter()
|
||||
{
|
||||
match event {
|
||||
Event::Start(Tag::CodeBlock(kind)) => {
|
||||
let lang = match kind {
|
||||
CodeBlockKind::Fenced(s) => s.into_string(),
|
||||
CodeBlockKind::Indented => String::new(),
|
||||
};
|
||||
active = Some((lang, String::new(), range.start));
|
||||
}
|
||||
Event::Text(s) => {
|
||||
if let Some((_, body, _)) = active.as_mut() {
|
||||
body.push_str(&s)
|
||||
}
|
||||
}
|
||||
Event::End(TagEnd::CodeBlock) => {
|
||||
if let Some((lang, body, start)) = active.take() {
|
||||
out.push(map(vec![
|
||||
("language", string(lang)),
|
||||
("text", string(body)),
|
||||
("start", num(start)),
|
||||
("end", num(range.end)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
_ => Err("not a document operation".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod literal_table_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn literal_values_retain_native_record_column_and_list_shapes() {
|
||||
let source="# 数据\n\n| @ | name | enabled | count |\n|---|---|---|---|\n| 1 | 中国 | True | 3 |\n";
|
||||
let actual=table_value(source,Some("数据"),0).unwrap();
|
||||
assert_eq!(actual,Value::List(vec![Value::Map(vec![
|
||||
("name".into(),Value::Text("中国".into())),
|
||||
("enabled".into(),Value::Bool(true)),
|
||||
("count".into(),Value::Int(3)),
|
||||
])]));
|
||||
assert_eq!(table_value("| number |\n|---|\n| 1 |\n| 2 |\n",None,0).unwrap(),Value::List(vec![Value::Int(1),Value::Int(2)]));
|
||||
let columns=table_value("| key | value |\n|---|---|\n| a | 1 |\n| b | 2 |\n",None,0).unwrap();
|
||||
assert!(matches!(columns,Value::Map(fields) if fields.iter().all(|(_, value)|matches!(value,Value::List(_)))));
|
||||
}
|
||||
#[test]
|
||||
fn negative_numbers_none_and_false_keep_their_literal_types() {
|
||||
let source="| values |\n|---|\n| -3 |\n| -0.5 |\n| None |\n| False |\n";
|
||||
assert_eq!(table_value(source,None,0).unwrap(),Value::List(vec![
|
||||
Value::Int(-3),Value::Num(-0.5),Value::None,Value::Bool(false),
|
||||
]));
|
||||
}
|
||||
#[test]
|
||||
fn unique_sections_and_indices_skip_fenced_examples() {
|
||||
let source="```text\n| code |\n|---|\n| hidden |\n```\n\n# first\n\n| x | y |\n|---|---|\n| 1 | 2 |\n\n# second\n\n| x | y |\n|---|---|\n| 3 | 4 |\n";
|
||||
let second=Value::Map(vec![("x".into(),Value::Int(3)),("y".into(),Value::Int(4))]);
|
||||
assert_eq!(table_value(source,Some("second"),0).unwrap(),second);
|
||||
assert_eq!(table_value(source,None,1).unwrap(),second);
|
||||
assert!(table_value("# same\n\n# same\n",Some("same"),0).unwrap_err().contains("ambiguous"));
|
||||
assert!(table_value(source,None,2).unwrap_err().contains("out of range"));
|
||||
}
|
||||
#[test]
|
||||
fn rejects_dynamic_cells_duplicate_headers_and_silent_truncation() {
|
||||
for source in ["| value |\n|---|\n| `outside` |\n","| x | x |\n|---|---|\n| a | b |\n","| x | y |\n|---|---|\n| a | b | extra |\n"] {
|
||||
assert!(table_value(source,None,0).is_err(),"accepted {source}");
|
||||
}
|
||||
let escaped="| @ | text | flag |\n|---|---|---|\n| 1 | left\\|right | False |\n";
|
||||
assert_eq!(table_value(escaped,None,0).unwrap(),Value::List(vec![Value::Map(vec![
|
||||
("text".into(),Value::Text("left|right".into())),("flag".into(),Value::Bool(false)),
|
||||
])]));
|
||||
}
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
//! Base64 / hex encoding for Mid M1 (`lib/encoding`).
|
||||
//! No third-party crates — standard alphabet + padding.
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
Ok(Value::Text(encode_base64(s.as_bytes())))
|
||||
}
|
||||
|
||||
pub fn base64_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let bytes = decode_base64(s)?;
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("base64_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let mut out = String::with_capacity(s.len() * 2);
|
||||
for b in s.as_bytes() {
|
||||
out.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
if s.len() % 2 != 0 {
|
||||
return Err("hex_decode: length must be even".into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(s.len() / 2);
|
||||
// Require ASCII hex digits only (byte-oriented).
|
||||
let raw = s.as_bytes();
|
||||
if raw.len() != s.len() {
|
||||
return Err("hex_decode: needs ASCII hex".into());
|
||||
}
|
||||
for i in (0..raw.len()).step_by(2) {
|
||||
let hi = from_hex(raw[i])?;
|
||||
let lo = from_hex(raw[i + 1])?;
|
||||
bytes.push((hi << 4) | lo);
|
||||
}
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("hex_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
|
||||
pub fn base32_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
Ok(Value::Text(encode_base32(s.as_bytes())))
|
||||
}
|
||||
|
||||
pub fn base32_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let bytes = decode_base32(s)?;
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("base32_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
fn encode_base32(input: &[u8]) -> String {
|
||||
let mut out = String::new();
|
||||
let mut buffer: u64 = 0;
|
||||
let mut bits = 0u32;
|
||||
for &b in input {
|
||||
buffer = (buffer << 8) | (b as u64);
|
||||
bits += 8;
|
||||
while bits >= 5 {
|
||||
bits -= 5;
|
||||
let idx = ((buffer >> bits) & 31) as usize;
|
||||
out.push(B32[idx] as char);
|
||||
}
|
||||
}
|
||||
if bits > 0 {
|
||||
let idx = ((buffer << (5 - bits)) & 31) as usize;
|
||||
out.push(B32[idx] as char);
|
||||
}
|
||||
while out.len() % 8 != 0 {
|
||||
out.push('=');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_base32(input: &str) -> Result<Vec<u8>, String> {
|
||||
let cleaned: String = input
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.map(|c| c.to_ascii_uppercase())
|
||||
.collect();
|
||||
if cleaned.len() % 8 != 0 {
|
||||
return Err("base32_decode: length must be multiple of 8".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut buffer: u64 = 0;
|
||||
let mut bits = 0u32;
|
||||
for c in cleaned.bytes() {
|
||||
if c == b'=' {
|
||||
break;
|
||||
}
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'2'..=b'7' => c - b'2' + 26,
|
||||
_ => return Err(format!("base32_decode: invalid character {:?}", c as char)),
|
||||
} as u64;
|
||||
buffer = (buffer << 5) | v;
|
||||
bits += 5;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((buffer >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn from_hex(b: u8) -> Result<u8, String> {
|
||||
match b {
|
||||
b'0'..=b'9' => Ok(b - b'0'),
|
||||
b'a'..=b'f' => Ok(b - b'a' + 10),
|
||||
b'A'..=b'F' => Ok(b - b'A' + 10),
|
||||
_ => Err(format!("hex_decode: invalid digit {:?}", b as char)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn encode_base64(input: &[u8]) -> String {
|
||||
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= input.len() {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8) | (input[i + 2] as u32);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push(B64[(n & 63) as usize] as char);
|
||||
i += 3;
|
||||
}
|
||||
let rem = input.len() - i;
|
||||
if rem == 1 {
|
||||
let n = (input[i] as u32) << 16;
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
out.push('=');
|
||||
} else if rem == 2 {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
let raw = input.as_bytes();
|
||||
if raw.len() % 4 != 0 {
|
||||
return Err("base64_decode: length must be multiple of 4".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(raw.len() / 4 * 3);
|
||||
let mut i = 0;
|
||||
while i < raw.len() {
|
||||
let a = decode_b64_char(raw[i])?;
|
||||
let b = decode_b64_char(raw[i + 1])?;
|
||||
let c = raw[i + 2];
|
||||
let d = raw[i + 3];
|
||||
let c_val = if c == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(c)?
|
||||
};
|
||||
let d_val = if d == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(d)?
|
||||
};
|
||||
let n = (a << 18) | (b << 12) | (c_val << 6) | d_val;
|
||||
out.push(((n >> 16) & 0xff) as u8);
|
||||
if c != b'=' {
|
||||
out.push(((n >> 8) & 0xff) as u8);
|
||||
}
|
||||
if d != b'=' {
|
||||
out.push((n & 0xff) as u8);
|
||||
}
|
||||
if c == b'=' && d != b'=' {
|
||||
return Err("base64_decode: invalid padding".into());
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn decode_b64_char(b: u8) -> Result<u32, String> {
|
||||
let v = match b {
|
||||
b'A'..=b'Z' => b - b'A',
|
||||
b'a'..=b'z' => b - b'a' + 26,
|
||||
b'0'..=b'9' => b - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return Err(format!("base64_decode: invalid character {:?}", b as char)),
|
||||
};
|
||||
Ok(v as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_hello() {
|
||||
let enc = base64_encode(&Value::Text("hello".into())).unwrap();
|
||||
assert_eq!(enc, Value::Text("aGVsbG8=".into()));
|
||||
let dec = base64_decode(&enc).unwrap();
|
||||
assert_eq!(dec, Value::Text("hello".into()));
|
||||
let hx = hex_encode(&Value::Text("hi".into())).unwrap();
|
||||
assert_eq!(hx, Value::Text("6869".into()));
|
||||
assert_eq!(hex_decode(&hx).unwrap(), Value::Text("hi".into()));
|
||||
let b32 = base32_encode(&Value::Text("hello".into())).unwrap();
|
||||
assert_eq!(b32, Value::Text("NBSWY3DP".into()));
|
||||
assert_eq!(base32_decode(&b32).unwrap(), Value::Text("hello".into()));
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
//! Process-wide stream event bus for `marqdo view` SSE (S3).
|
||||
//! Publishers: LLM SSE parse, optional `host_stream_publish`.
|
||||
//! Subscribers: view `GET /api/events` / `POST /api/run`.
|
||||
//!
|
||||
//! File subtasks set `MARQDO_EVENT_FORWARD=<ndjson path>`; the child appends each
|
||||
//! published event so the parent can fan them onto its own bus while `wait` blocks.
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use crate::host::json::value_to_json;
|
||||
use crate::value::Value;
|
||||
|
||||
static BUS: OnceLock<EventBus> = OnceLock::new();
|
||||
|
||||
pub struct EventBus {
|
||||
subs: Mutex<Vec<Sender<String>>>,
|
||||
}
|
||||
|
||||
impl EventBus {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
subs: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn global() -> &'static EventBus {
|
||||
BUS.get_or_init(EventBus::new)
|
||||
}
|
||||
|
||||
/// Subscribe to JSON event lines (already serialized maps).
|
||||
pub fn subscribe(&self) -> Receiver<String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
if let Ok(mut g) = self.subs.lock() {
|
||||
g.push(tx);
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn publish_json(&self, json_line: &str) {
|
||||
if let Ok(mut g) = self.subs.lock() {
|
||||
g.retain(|tx| tx.send(json_line.to_string()).is_ok());
|
||||
}
|
||||
// Child → parent bridge (no-op unless spawn set the env).
|
||||
forward_to_parent_file(json_line);
|
||||
}
|
||||
|
||||
pub fn publish_value(&self, v: &Value) {
|
||||
if let Ok(j) = value_to_json(v) {
|
||||
self.publish_json(&j.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forward_to_parent_file(json_line: &str) {
|
||||
let Ok(path) = std::env::var("MARQDO_EVENT_FORWARD") else {
|
||||
return;
|
||||
};
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
{
|
||||
let _ = writeln!(f, "{json_line}");
|
||||
let _ = f.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish a Marqdo map (or any value) onto the global bus.
|
||||
pub fn publish(v: &Value) {
|
||||
EventBus::global().publish_value(v);
|
||||
}
|
||||
-1967
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,174 +0,0 @@
|
||||
//! Concurrent control inputs are scoped to a single recorded document action.
|
||||
//! Replay supplies their elapsed-time inputs, reobserves acceptance, and stops
|
||||
//! on divergence; elapsed wall time is not a deterministic foreign-state oracle.
|
||||
use crate::host::foreign_session::InterruptHandle;
|
||||
use crate::value::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct ControlEvent {
|
||||
pub after_us: u64,
|
||||
pub results: Vec<(String, Result<bool, String>)>,
|
||||
}
|
||||
impl ControlEvent {
|
||||
pub fn value(&self) -> Value {
|
||||
Value::Map(vec![
|
||||
("after_us".into(), Value::Int(self.after_us as i64)),
|
||||
(
|
||||
"results".into(),
|
||||
Value::List(
|
||||
self.results
|
||||
.iter()
|
||||
.map(|(name, result)| {
|
||||
Value::Map(vec![
|
||||
("kernel".into(), Value::Text(name.clone())),
|
||||
("accepted".into(), Value::Bool(result.is_ok())),
|
||||
("active".into(), Value::Bool(matches!(result, Ok(true)))),
|
||||
(
|
||||
"error".into(),
|
||||
Value::Text(result.as_ref().err().cloned().unwrap_or_default()),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct State {
|
||||
kernels: BTreeMap<String, InterruptHandle>,
|
||||
generation: u64,
|
||||
action: Option<(Instant, Vec<ControlEvent>)>,
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct DocumentControl(Arc<Shared>);
|
||||
|
||||
impl DocumentControl {
|
||||
pub(super) fn cancelled(&self) -> bool {
|
||||
self.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.action
|
||||
.as_ref()
|
||||
.is_some_and(|(_, events)| !events.is_empty())
|
||||
}
|
||||
pub(super) fn register(&self, kernel: &str, handle: InterruptHandle) {
|
||||
self.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.kernels
|
||||
.insert(kernel.into(), handle);
|
||||
}
|
||||
pub(super) fn begin(&self, plan: Vec<ControlEvent>) -> Option<JoinHandle<()>> {
|
||||
let generation = {
|
||||
let mut state = self.0.state.lock().unwrap();
|
||||
state.generation += 1;
|
||||
state.action = Some((Instant::now(), Vec::new()));
|
||||
state.generation
|
||||
};
|
||||
if plan.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let controller = self.clone();
|
||||
Some(std::thread::spawn(move || {
|
||||
for event in plan {
|
||||
let mut state = controller.0.state.lock().unwrap();
|
||||
loop {
|
||||
if state.generation != generation || state.action.is_none() {
|
||||
return;
|
||||
}
|
||||
let elapsed = state.action.as_ref().unwrap().0.elapsed();
|
||||
let remaining = Duration::from_micros(event.after_us).saturating_sub(elapsed);
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
state = controller
|
||||
.0
|
||||
.changed
|
||||
.wait_timeout(state, remaining.min(Duration::from_millis(200)))
|
||||
.unwrap()
|
||||
.0;
|
||||
}
|
||||
// Keep the action-generation check and signal under one lock.
|
||||
let _ = Self::request_locked(&mut state, Some(event.after_us));
|
||||
}
|
||||
}))
|
||||
}
|
||||
pub(super) fn finish(&self, scheduler: Option<JoinHandle<()>>) -> Vec<ControlEvent> {
|
||||
let events = self
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.action
|
||||
.take()
|
||||
.map(|(_, events)| events)
|
||||
.unwrap_or_default();
|
||||
self.0.changed.notify_all();
|
||||
if let Some(scheduler) = scheduler {
|
||||
let _ = scheduler.join();
|
||||
}
|
||||
events
|
||||
}
|
||||
pub fn interrupt(&self) -> Result<Value, String> {
|
||||
let mut state = self
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| "document control lock poisoned")?;
|
||||
Self::request_locked(&mut state, None).map(|event| event.value())
|
||||
}
|
||||
fn request_locked(
|
||||
state: &mut State,
|
||||
scheduled_us: Option<u64>,
|
||||
) -> Result<ControlEvent, String> {
|
||||
let start = state
|
||||
.action
|
||||
.as_ref()
|
||||
.ok_or("no document action in flight")?
|
||||
.0;
|
||||
let after_us = scheduled_us
|
||||
.unwrap_or_else(|| start.elapsed().as_micros().min(i64::MAX as u128) as u64);
|
||||
let results = state
|
||||
.kernels
|
||||
.iter()
|
||||
.filter(|(_, handle)| handle.is_live())
|
||||
.map(|(name, handle)| (name.clone(), handle.request()))
|
||||
.collect();
|
||||
let event = ControlEvent { after_us, results };
|
||||
state.action.as_mut().unwrap().1.push(event.clone());
|
||||
Ok(event)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn completed_action_cancels_pending_scheduler_before_next_generation() {
|
||||
let controller = DocumentControl::default();
|
||||
let scheduler = controller.begin(vec![ControlEvent {
|
||||
after_us: 60_000_000,
|
||||
results: Vec::new(),
|
||||
}]);
|
||||
let start = Instant::now();
|
||||
assert!(controller.finish(scheduler).is_empty());
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(controller.interrupt().is_err());
|
||||
let next = controller.begin(Vec::new());
|
||||
assert!(!controller.cancelled());
|
||||
assert!(controller.finish(next).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,399 +0,0 @@
|
||||
//! Lossless, typed, bottom-up sharing for complete history snapshots.
|
||||
//! References always point backwards. Expansion costs and depth are checked
|
||||
//! before building the expanded value, so a small DAG cannot expand unboundedly.
|
||||
use crate::host::{json::value_to_json, oracle::admit};
|
||||
use crate::value::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const FORMAT: &str = "marqdo.history.dag";
|
||||
const MAX_NODES: usize = 1_000_000;
|
||||
const MAX_VALUES: usize = 8_000_000;
|
||||
const MAX_BYTES: usize = 512 * 1024 * 1024;
|
||||
const MAX_DEPTH: usize = 128;
|
||||
|
||||
fn text(s: &str) -> Value {
|
||||
Value::Text(s.into())
|
||||
}
|
||||
fn list(v: &Value) -> Result<&[Value], String> {
|
||||
if let Value::List(v) = v {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err("snapshot DAG: expected list".into())
|
||||
}
|
||||
}
|
||||
fn string(v: &Value) -> Result<&str, String> {
|
||||
if let Value::Text(v) = v {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err("snapshot DAG: expected text".into())
|
||||
}
|
||||
}
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
if let Value::Map(fields) = v {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| format!("snapshot DAG: missing {key}"))
|
||||
} else {
|
||||
Err("snapshot DAG: expected object".into())
|
||||
}
|
||||
}
|
||||
fn wire(v: &Value) -> Result<String, String> {
|
||||
serde_json::to_string(&value_to_json(v)?).map_err(|e| e.to_string())
|
||||
}
|
||||
fn checksum(root: &Value, nodes: &Value) -> Result<String, String> {
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(wire(&Value::List(vec![root.clone(), nodes.clone()]))?.as_bytes())
|
||||
))
|
||||
}
|
||||
pub fn is_packed(v: &Value) -> bool {
|
||||
field(v, "format").ok() == Some(&text(FORMAT))
|
||||
}
|
||||
|
||||
pub fn pack(snapshot: &Value) -> Result<Value, String> {
|
||||
fn intern(
|
||||
v: &Value,
|
||||
nodes: &mut Vec<Value>,
|
||||
seen: &mut HashMap<String, usize>,
|
||||
depth: usize,
|
||||
) -> Result<usize, String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err("snapshot DAG: depth budget exceeded".into());
|
||||
}
|
||||
let row = match v {
|
||||
Value::None => vec![text("null")],
|
||||
Value::Bool(v) => vec![text("bool"), Value::Bool(*v)],
|
||||
Value::Int(v) => vec![text("int"), text(&v.to_string())],
|
||||
Value::Num(v) => vec![text("float"), text(&format!("{:016x}", v.to_bits()))],
|
||||
Value::Text(v) => vec![text("text"), text(v)],
|
||||
Value::List(values) => {
|
||||
let refs = values
|
||||
.iter()
|
||||
.map(|v| intern(v, nodes, seen, depth + 1).map(|i| Value::Int(i as i64)))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
vec![text("list"), Value::List(refs)]
|
||||
}
|
||||
Value::Map(fields) => {
|
||||
let refs = fields
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
intern(v, nodes, seen, depth + 1)
|
||||
.map(|i| Value::List(vec![text(k), Value::Int(i as i64)]))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
vec![text("map"), Value::List(refs)]
|
||||
}
|
||||
_ => return Err("snapshot DAG: value outside V_safe".into()),
|
||||
};
|
||||
let row = Value::List(row);
|
||||
let key = wire(&row)?;
|
||||
if let Some(index) = seen.get(&key) {
|
||||
return Ok(*index);
|
||||
}
|
||||
if nodes.len() >= MAX_NODES {
|
||||
return Err("snapshot DAG: node budget exceeded".into());
|
||||
}
|
||||
let index = nodes.len();
|
||||
nodes.push(row);
|
||||
seen.insert(key, index);
|
||||
Ok(index)
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let root = intern(snapshot, &mut nodes, &mut HashMap::new(), 0)?;
|
||||
admit(snapshot)?;
|
||||
let nodes = Value::List(nodes);
|
||||
let root = Value::Int(root as i64);
|
||||
let hash = checksum(&root, &nodes)?;
|
||||
let envelope = Value::Map(vec![
|
||||
("format".into(), text(FORMAT)),
|
||||
("version".into(), Value::Int(1)),
|
||||
("root".into(), root),
|
||||
("nodes".into(), nodes),
|
||||
("sha256".into(), text(&hash)),
|
||||
]);
|
||||
// Apply exactly the decoder's resource limits to locally produced envelopes.
|
||||
validate(&envelope)?;
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
enum Node {
|
||||
Atom(Value),
|
||||
List(Vec<usize>),
|
||||
Map(Vec<(String, usize)>),
|
||||
}
|
||||
impl Node {
|
||||
fn refs(&self) -> Vec<usize> {
|
||||
match self {
|
||||
Self::Atom(_) => Vec::new(),
|
||||
Self::List(v) => v.clone(),
|
||||
Self::Map(v) => v.iter().map(|(_, i)| *i).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn index(v: &Value, before: usize) -> Result<usize, String> {
|
||||
match v {
|
||||
Value::Int(i) if *i >= 0 && (*i as u64) < before as u64 => Ok(*i as usize),
|
||||
_ => Err("snapshot DAG: forward/cyclic/out-of-range reference".into()),
|
||||
}
|
||||
}
|
||||
fn validate(envelope: &Value) -> Result<(Vec<Node>, usize), String> {
|
||||
let Value::Map(fields) = envelope else {
|
||||
return Err("snapshot DAG: expected envelope".into());
|
||||
};
|
||||
let names: HashSet<_> = fields.iter().map(|(k, _)| k.as_str()).collect();
|
||||
if fields.len() != 5
|
||||
|| names != HashSet::from(["format", "version", "root", "nodes", "sha256"])
|
||||
|| string(field(envelope, "format")?)? != FORMAT
|
||||
|| field(envelope, "version")? != &Value::Int(1)
|
||||
{
|
||||
return Err("snapshot DAG: invalid envelope schema".into());
|
||||
}
|
||||
let rows = list(field(envelope, "nodes")?)?;
|
||||
if rows.is_empty() || rows.len() > MAX_NODES {
|
||||
return Err("snapshot DAG: node budget exceeded".into());
|
||||
}
|
||||
let root = index(field(envelope, "root")?, rows.len())?;
|
||||
if root + 1 != rows.len() {
|
||||
return Err("snapshot DAG: root must be last".into());
|
||||
}
|
||||
let expected = string(field(envelope, "sha256")?)?;
|
||||
if expected != checksum(field(envelope, "root")?, field(envelope, "nodes")?)? {
|
||||
return Err("snapshot DAG: checksum differs".into());
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let mut costs: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut unique = HashSet::new();
|
||||
for (i, raw) in rows.iter().enumerate() {
|
||||
if !unique.insert(wire(raw)?) {
|
||||
return Err("snapshot DAG: duplicate dictionary node".into());
|
||||
}
|
||||
let row = list(raw)?;
|
||||
let tag = string(row.first().ok_or("snapshot DAG: empty node")?)?;
|
||||
let node = match (tag, row) {
|
||||
("null", [_]) => Node::Atom(Value::None),
|
||||
("bool", [_, Value::Bool(v)]) => Node::Atom(Value::Bool(*v)),
|
||||
("text", [_, Value::Text(v)]) => Node::Atom(text(v)),
|
||||
("int", [_, Value::Text(v)]) => {
|
||||
let n = v
|
||||
.parse::<i64>()
|
||||
.map_err(|_| "snapshot DAG: invalid integer")?;
|
||||
if n.to_string() != *v {
|
||||
return Err("snapshot DAG: noncanonical integer".into());
|
||||
}
|
||||
Node::Atom(Value::Int(n))
|
||||
}
|
||||
("float", [_, Value::Text(v)]) if v.len() == 16 => {
|
||||
let bits =
|
||||
u64::from_str_radix(v, 16).map_err(|_| "snapshot DAG: invalid float bits")?;
|
||||
if format!("{bits:016x}") != *v {
|
||||
return Err("snapshot DAG: noncanonical float bits".into());
|
||||
}
|
||||
Node::Atom(Value::Num(f64::from_bits(bits)))
|
||||
}
|
||||
("list", [_, refs]) => Node::List(
|
||||
list(refs)?
|
||||
.iter()
|
||||
.map(|v| index(v, i))
|
||||
.collect::<Result<_, _>>()?,
|
||||
),
|
||||
("map", [_, refs]) => {
|
||||
let mut keys = HashSet::new();
|
||||
let mut fields = Vec::new();
|
||||
for pair in list(refs)? {
|
||||
let [key, value] = list(pair)? else {
|
||||
return Err("snapshot DAG: invalid map pair".into());
|
||||
};
|
||||
let key = string(key)?;
|
||||
if !keys.insert(key) {
|
||||
return Err("snapshot DAG: duplicate map key".into());
|
||||
}
|
||||
fields.push((key.into(), index(value, i)?));
|
||||
}
|
||||
Node::Map(fields)
|
||||
}
|
||||
_ => return Err("snapshot DAG: invalid node tag/payload".into()),
|
||||
};
|
||||
let mut values = 1usize;
|
||||
let mut bytes = match &node {
|
||||
Node::Atom(v) => {
|
||||
admit(v)?;
|
||||
match v {
|
||||
Value::Text(s) => s
|
||||
.len()
|
||||
.checked_mul(6)
|
||||
.and_then(|n| n.checked_add(2))
|
||||
.ok_or("snapshot DAG: size overflow")?,
|
||||
_ => 32,
|
||||
}
|
||||
}
|
||||
Node::Map(v) => v
|
||||
.iter()
|
||||
.try_fold(2usize, |n, (k, _)| {
|
||||
n.checked_add(k.len().checked_mul(6)?.checked_add(4)?)
|
||||
})
|
||||
.ok_or("snapshot DAG: size overflow")?,
|
||||
Node::List(_) => 2,
|
||||
};
|
||||
let mut depth = 1;
|
||||
for reference in node.refs() {
|
||||
let (count, size, height) = costs[reference];
|
||||
values = values
|
||||
.checked_add(count)
|
||||
.ok_or("snapshot DAG: expansion overflow")?;
|
||||
bytes = bytes
|
||||
.checked_add(size)
|
||||
.and_then(|n| n.checked_add(1))
|
||||
.ok_or("snapshot DAG: expansion overflow")?;
|
||||
depth = depth.max(height + 1);
|
||||
}
|
||||
if values > MAX_VALUES || bytes > MAX_BYTES || depth > MAX_DEPTH {
|
||||
return Err("snapshot DAG: expansion budget exceeded".into());
|
||||
}
|
||||
costs.push((values, bytes, depth));
|
||||
nodes.push(node);
|
||||
}
|
||||
let mut reachable = HashSet::new();
|
||||
let mut todo = vec![root];
|
||||
while let Some(i) = todo.pop() {
|
||||
if reachable.insert(i) {
|
||||
todo.extend(nodes[i].refs());
|
||||
}
|
||||
}
|
||||
if reachable.len() != nodes.len() {
|
||||
return Err("snapshot DAG: unreachable dictionary node".into());
|
||||
}
|
||||
Ok((nodes, root))
|
||||
}
|
||||
|
||||
pub fn unpack(envelope: &Value) -> Result<Value, String> {
|
||||
fn expand(nodes: &[Node], i: usize) -> Value {
|
||||
match &nodes[i] {
|
||||
Node::Atom(v) => v.clone(),
|
||||
Node::List(refs) => Value::List(refs.iter().map(|i| expand(nodes, *i)).collect()),
|
||||
Node::Map(fields) => Value::Map(
|
||||
fields
|
||||
.iter()
|
||||
.map(|(k, i)| (k.clone(), expand(nodes, *i)))
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
let (nodes, root) = validate(envelope)?;
|
||||
let value = expand(&nodes, root);
|
||||
admit(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn envelope(rows: Vec<Value>) -> Value {
|
||||
let root = Value::Int(rows.len() as i64 - 1);
|
||||
let nodes = Value::List(rows);
|
||||
let hash = checksum(&root, &nodes).unwrap();
|
||||
Value::Map(vec![
|
||||
("format".into(), text(FORMAT)),
|
||||
("version".into(), Value::Int(1)),
|
||||
("root".into(), root),
|
||||
("nodes".into(), nodes),
|
||||
("sha256".into(), text(&hash)),
|
||||
])
|
||||
}
|
||||
fn row(tag: &str, value: Value) -> Value {
|
||||
Value::List(vec![text(tag), value])
|
||||
}
|
||||
#[test]
|
||||
fn typed_roundtrip_preserves_order_float_bits_and_repeated_values() {
|
||||
let shared = Value::Map(vec![
|
||||
(
|
||||
"z".into(),
|
||||
Value::List(vec![
|
||||
Value::None,
|
||||
Value::Bool(true),
|
||||
Value::Int(1),
|
||||
Value::Num(-0.0),
|
||||
Value::Num(1.25),
|
||||
]),
|
||||
),
|
||||
("汉字".into(), text("🧪")),
|
||||
]);
|
||||
let input = Value::List(vec![shared; 128]);
|
||||
let packed = pack(&input).unwrap();
|
||||
let decoded_wire =
|
||||
crate::host::json::parse(&crate::host::json::stringify(&packed, None).unwrap())
|
||||
.unwrap();
|
||||
let expanded = unpack(&decoded_wire).unwrap();
|
||||
assert_eq!(input, expanded);
|
||||
assert_eq!(wire(&input).unwrap(), wire(&expanded).unwrap());
|
||||
let Value::List(ref xs) = expanded else {
|
||||
panic!()
|
||||
};
|
||||
let Value::Map(ref fields) = xs[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(fields[0].0, "z");
|
||||
let Value::List(ref values) = fields[0].1 else {
|
||||
panic!()
|
||||
};
|
||||
let Value::Num(number) = values[3] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(number.to_bits(), (-0.0f64).to_bits());
|
||||
assert!(list(field(&packed, "nodes").unwrap()).unwrap().len() < 20);
|
||||
assert!(wire(&packed).unwrap().len() < wire(&input).unwrap().len());
|
||||
}
|
||||
#[test]
|
||||
fn refuses_cycles_amplification_unreachable_duplicates_and_unsafe_atoms() {
|
||||
let bad = [
|
||||
envelope(vec![row("list", Value::List(vec![Value::Int(0)]))]),
|
||||
envelope(vec![row("text", text("unused")), row("text", text("root"))]),
|
||||
envelope(vec![row("text", text("same")), row("text", text("same"))]),
|
||||
envelope(vec![row("int", text("9007199254740992"))]),
|
||||
envelope(vec![row("float", text("7ff8000000000000"))]),
|
||||
envelope(vec![row("int", text("00"))]),
|
||||
];
|
||||
for value in bad {
|
||||
assert!(unpack(&value).is_err());
|
||||
}
|
||||
let mut rows = vec![row("text", text("x"))];
|
||||
for n in 0..40 {
|
||||
rows.push(row("list", Value::List(vec![Value::Int(n), Value::Int(n)])));
|
||||
}
|
||||
let error = unpack(&envelope(rows)).unwrap_err();
|
||||
assert!(error.contains("budget"), "{error}");
|
||||
let mut hash = pack(&Value::Int(1)).unwrap();
|
||||
if let Value::Map(ref mut fields) = hash {
|
||||
fields.iter_mut().find(|(k, _)| k == "sha256").unwrap().1 = text("bad");
|
||||
}
|
||||
assert!(unpack(&hash).unwrap_err().contains("checksum"));
|
||||
}
|
||||
#[test]
|
||||
fn sharing_does_not_admit_ragged_columns_or_duplicate_keys() {
|
||||
let ragged = Value::Map(vec![
|
||||
("a".into(), Value::List(vec![Value::Int(1)])),
|
||||
("b".into(), Value::List(Vec::new())),
|
||||
]);
|
||||
assert!(pack(&ragged).is_err());
|
||||
let duplicate = Value::Map(vec![
|
||||
("a".into(), Value::Int(1)),
|
||||
("a".into(), Value::Int(2)),
|
||||
]);
|
||||
assert!(pack(&duplicate).is_err());
|
||||
let value = envelope(vec![
|
||||
row("int", text("1")),
|
||||
row("list", Value::List(vec![Value::Int(0)])),
|
||||
row("list", Value::List(Vec::new())),
|
||||
row(
|
||||
"map",
|
||||
Value::List(vec![
|
||||
Value::List(vec![text("a"), Value::Int(1)]),
|
||||
Value::List(vec![text("b"), Value::Int(2)]),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
assert!(unpack(&value).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,204 +0,0 @@
|
||||
//! An owned-process interrupt capability. Retirement precedes every child reap,
|
||||
//! so a stale capability cannot signal a reused operating-system process id.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
pid: Option<u32>,
|
||||
evaluating: bool,
|
||||
ready: bool,
|
||||
requested: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InterruptHandle(Arc<Mutex<State>>);
|
||||
|
||||
impl InterruptHandle {
|
||||
pub(super) fn new(pid: u32) -> Self {
|
||||
Self(Arc::new(Mutex::new(State {
|
||||
pid: Some(pid),
|
||||
..State::default()
|
||||
})))
|
||||
}
|
||||
pub(super) fn retire(&self) -> Option<u32> {
|
||||
if let Ok(mut state) = self.0.lock() {
|
||||
let pid = state.pid.take();
|
||||
state.evaluating = false;
|
||||
pid
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub(super) fn try_wait(
|
||||
&self,
|
||||
child: &mut std::process::Child,
|
||||
) -> std::io::Result<Option<std::process::ExitStatus>> {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
let result = child.try_wait();
|
||||
if matches!(result, Ok(Some(_))) {
|
||||
state.pid = None;
|
||||
state.evaluating = false;
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn begin(&self, evaluating: bool) {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.evaluating = evaluating;
|
||||
state.ready = false;
|
||||
state.requested = false;
|
||||
}
|
||||
pub(super) fn finish(&self) {
|
||||
self.0.lock().unwrap().evaluating = false;
|
||||
}
|
||||
// SIGINT can arrive between a Node ready frame and installation of V8's
|
||||
// breakOnSigint handler. Retry the same logical request while awaiting its
|
||||
// response; never carry a retry into the next request or retired process.
|
||||
pub(super) fn retry(&self) -> Result<(), String> {
|
||||
let state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.evaluating && state.ready && state.requested {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn ready(&self) -> Result<(), String> {
|
||||
let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.ready {
|
||||
return Ok(());
|
||||
}
|
||||
state.ready = true;
|
||||
if state.requested {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn is_live(&self) -> bool {
|
||||
self.0.lock().is_ok_and(|s| s.pid.is_some())
|
||||
}
|
||||
|
||||
/// False means idle; cancellation is coalesced within one evaluation.
|
||||
/// Before the bootstrap's ready frame it is queued rather than sent into
|
||||
/// interpreter startup or transport parsing.
|
||||
pub fn request(&self) -> Result<bool, String> {
|
||||
let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.pid.is_none() {
|
||||
return Err("interrupt capability retired".into());
|
||||
}
|
||||
if !state.evaluating {
|
||||
return Ok(false);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
return Err("non-destructive interrupt is unsupported on this platform".into());
|
||||
if !state.requested {
|
||||
if state.ready {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
state.requested = true;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn signal(state: &State) -> Result<(), String> {
|
||||
let pid = state.pid.ok_or("interrupt capability retired")?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
if unsafe { libc::kill(-(pid as i32), libc::SIGINT) } != 0 {
|
||||
return Err(format!(
|
||||
"interrupt failed: {}",
|
||||
std::io::Error::last_os_error()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = pid;
|
||||
Err("non-destructive interrupt is unsupported on this platform".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use crate::host::{foreign_session, HostContext};
|
||||
use crate::value::Value;
|
||||
#[test]
|
||||
fn retired_interrupt_capability_cannot_reach_replacement_kernel() {
|
||||
for language in ["python", "node"] {
|
||||
let mut host = HostContext::default();
|
||||
let lang = Value::Text(language.into());
|
||||
let old = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap();
|
||||
let Value::Handle(id) = &old else { panic!() };
|
||||
let control = host.foreign_sessions[id].interrupt_handle.clone();
|
||||
assert!(!control.request().unwrap());
|
||||
foreign_session::close(&mut host, &old).unwrap();
|
||||
let new = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap();
|
||||
assert!(!control.is_live());
|
||||
assert!(control.request().unwrap_err().contains("retired"));
|
||||
foreign_session::set(&mut host, &new, &Value::Text("n".into()), &Value::Int(8))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
foreign_session::get(&mut host, &new, &Value::Text("n".into())).unwrap(),
|
||||
Value::Int(8)
|
||||
);
|
||||
foreign_session::close(&mut host, &new).unwrap();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_queued_during_bootstrap_reaches_busy_evaluation() {
|
||||
use std::time::{Duration, Instant};
|
||||
for language in ["python", "node"] {
|
||||
let mut host = HostContext::default();
|
||||
let id = foreign_session::open(
|
||||
&mut host,
|
||||
&Value::Text(language.into()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let Value::Handle(ref name) = id else {
|
||||
panic!()
|
||||
};
|
||||
let control = host.foreign_sessions[name].interrupt_handle.clone();
|
||||
let kernel = id.clone();
|
||||
let code = if language == "python" {
|
||||
"while True: pass"
|
||||
} else {
|
||||
"while(true) {}"
|
||||
};
|
||||
let worker = std::thread::spawn(move || {
|
||||
let record = foreign_session::eval(
|
||||
&mut host,
|
||||
&kernel,
|
||||
None,
|
||||
Some(&Value::Text(code.into())),
|
||||
None,
|
||||
Some(&Value::Int(2)),
|
||||
)
|
||||
.unwrap();
|
||||
(host, record)
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
while !control.0.lock().unwrap().evaluating && Instant::now() < deadline {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(control.request().unwrap());
|
||||
assert!(
|
||||
control.request().unwrap(),
|
||||
"logical duplicates must coalesce"
|
||||
);
|
||||
let (mut host, record) = worker.join().unwrap();
|
||||
let Value::Map(fields) = record else { panic!() };
|
||||
assert_eq!(
|
||||
fields.iter().find(|(k, _)| k == "timed_out").unwrap().1,
|
||||
Value::Bool(false),
|
||||
"{language}: {fields:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
fields.iter().find(|(k, _)| k == "alive").unwrap().1,
|
||||
Value::Bool(true)
|
||||
);
|
||||
foreign_session::close(&mut host, &id).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
//! Production adapter to the executable Lean replay policy.
|
||||
//! All replay decisions come from ReplayPolicy.Cursor, with no Rust fallback.
|
||||
use super::ProtocolStep;
|
||||
use serde_json::Value;
|
||||
use std::collections::VecDeque;
|
||||
mod policy;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DivergenceKind { Missing, Request, Reply, Surplus, Phase, Policy }
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Divergence {
|
||||
pub kind: DivergenceKind,
|
||||
pub matched_prefix: usize,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
impl std::fmt::Display for Divergence {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self.kind {
|
||||
DivergenceKind::Missing | DivergenceKind::Request => "replay: protocol request differs before dispatch",
|
||||
DivergenceKind::Reply => "replay: protocol response differs",
|
||||
DivergenceKind::Surplus => "replay: recorded execution prefix was not consumed",
|
||||
DivergenceKind::Phase => "replay: invalid protocol validation phase",
|
||||
DivergenceKind::Policy => "replay: verified policy unavailable",
|
||||
})?;
|
||||
if let Some(detail) = &self.detail { write!(f, ": {detail}")? }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ReplayCursor {
|
||||
client: Option<policy::Client>,
|
||||
progress: (usize, usize),
|
||||
stopped: Option<Divergence>,
|
||||
}
|
||||
impl From<VecDeque<ProtocolStep>> for ReplayCursor {
|
||||
fn from(expected: VecDeque<ProtocolStep>) -> Self {
|
||||
let count = expected.len();
|
||||
match policy::Client::start(expected) {
|
||||
Ok((client, reply)) if reply.allow && reply.matched == 0 && reply.remaining == count =>
|
||||
Self { client: Some(client), progress: (0, count), stopped: None },
|
||||
result => {
|
||||
let detail = match result { Err(e) => e, Ok(_) => "invalid policy initialization".into() };
|
||||
Self { client: None, progress: (0,count), stopped: Some(Divergence {
|
||||
kind: DivergenceKind::Policy, matched_prefix: 0, detail: Some(detail) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<Vec<ProtocolStep>> for ReplayCursor {
|
||||
fn from(expected: Vec<ProtocolStep>) -> Self { VecDeque::from(expected).into() }
|
||||
}
|
||||
/// Private construction, no Clone: actual dispatch consumes this snapshot.
|
||||
pub(super) struct DispatchPermit { session: String, request: Value }
|
||||
impl DispatchPermit {
|
||||
pub(super) fn session(&self) -> &str { &self.session }
|
||||
pub(super) fn request(&self) -> &Value { &self.request }
|
||||
}
|
||||
impl ReplayCursor {
|
||||
fn unavailable(&mut self, detail: String) -> Divergence {
|
||||
self.client.take();
|
||||
let error = Divergence { kind: DivergenceKind::Policy, matched_prefix: self.progress.0, detail: Some(detail) };
|
||||
self.stopped = Some(error.clone());
|
||||
error
|
||||
}
|
||||
fn command(&mut self, op: &str, value: &str) -> Result<(), Divergence> {
|
||||
if let Some(error) = &self.stopped { return Err(error.clone()) }
|
||||
let result = self.client.as_mut().ok_or_else(|| "no policy process".to_string())
|
||||
.and_then(|client| client.exchange(op, value));
|
||||
let reply = result.map_err(|e| self.unavailable(e))?;
|
||||
self.progress = (reply.matched, reply.remaining);
|
||||
if reply.allow { return Ok(()) }
|
||||
let kind = match reply.reason.as_deref() {
|
||||
Some("missing") => DivergenceKind::Missing,
|
||||
Some("request") => DivergenceKind::Request,
|
||||
Some("reply") => DivergenceKind::Reply,
|
||||
Some("surplus") => DivergenceKind::Surplus,
|
||||
Some("phase") => DivergenceKind::Phase,
|
||||
_ => return Err(self.unavailable("unknown policy stop reason".into())),
|
||||
};
|
||||
let error = Divergence { kind, matched_prefix: reply.matched, detail: None };
|
||||
self.stopped = Some(error.clone());
|
||||
Err(error)
|
||||
}
|
||||
fn prepare(&mut self, session: &str, request: &Value) -> Result<DispatchPermit, Divergence> {
|
||||
self.command("prepare", &policy::request_key(session,request))?;
|
||||
Ok(DispatchPermit { session: session.into(), request: request.clone() })
|
||||
}
|
||||
pub(super) fn accept_response(&mut self, response: &Result<Value,String>) -> Result<(), Divergence> {
|
||||
self.command("receive", &policy::response_key(response))
|
||||
}
|
||||
pub fn progress(&self) -> (usize,usize) { self.progress }
|
||||
/// Called only at the outer action boundary; consumes the cursor.
|
||||
pub fn finish(mut self) -> Result<(),Divergence> { self.command("finish", "") }
|
||||
}
|
||||
pub(super) fn prepare(cursor: Option<&mut ReplayCursor>, session: &str, request: &Value)
|
||||
-> Result<DispatchPermit,Divergence> {
|
||||
if let Some(cursor) = cursor { return cursor.prepare(session,request) }
|
||||
Ok(DispatchPermit { session: session.into(), request: request.clone() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
fn step(reply: Result<Value, String>) -> ProtocolStep {
|
||||
ProtocolStep {
|
||||
session: "s".into(),
|
||||
request: json!({"op":"get"}),
|
||||
response: reply,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn local_returns_and_ordinary_failures_preserve_residual_history() {
|
||||
let mut cursor: ReplayCursor =
|
||||
vec![step(Err("foreign failure".into())), step(Ok(json!(7)))].into();
|
||||
assert_eq!(cursor.progress(), (0, 2));
|
||||
let permit = cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
assert_eq!(permit.session(), "s");
|
||||
cursor
|
||||
.accept_response(&Err("foreign failure".into()))
|
||||
.unwrap();
|
||||
assert_eq!(cursor.progress(), (1, 1));
|
||||
cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
cursor.accept_response(&Ok(json!(7))).unwrap();
|
||||
cursor.finish().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn divergence_is_sticky_and_matching_reply_cannot_revive_it() {
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
let first = cursor.accept_response(&Ok(json!(8))).unwrap_err();
|
||||
assert_eq!(first.kind, DivergenceKind::Reply);
|
||||
assert_eq!(
|
||||
cursor.prepare("s", &json!({"op":"get"})).err().unwrap(),
|
||||
first
|
||||
);
|
||||
assert_eq!(cursor.accept_response(&Ok(json!(7))).unwrap_err(), first);
|
||||
assert_eq!(cursor.finish().unwrap_err(), first);
|
||||
}
|
||||
#[test]
|
||||
fn permit_is_a_snapshot_and_phase_errors_fail_closed() {
|
||||
let mut request = json!({"op":"get"});
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
let permit = cursor.prepare("s", &request).unwrap();
|
||||
request["op"] = json!("write");
|
||||
assert_ne!(permit.request(), &request);
|
||||
assert_eq!(
|
||||
cursor.prepare("s", permit.request()).err().unwrap().kind,
|
||||
DivergenceKind::Phase
|
||||
);
|
||||
assert!(cursor.accept_response(&Ok(json!(7))).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn mismatching_and_missing_requests_never_issue_a_permit() {
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
let error = cursor
|
||||
.prepare("other-session", &json!({"op":"get"}))
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind, DivergenceKind::Request);
|
||||
assert_eq!(cursor.progress(), (0, 1));
|
||||
assert_eq!(
|
||||
cursor.prepare("s", &json!({"op":"get"})).err().unwrap(),
|
||||
error
|
||||
);
|
||||
let mut empty: ReplayCursor = Vec::<ProtocolStep>::new().into();
|
||||
assert_eq!(
|
||||
empty.prepare("s", &json!({"op":"get"})).err().unwrap().kind,
|
||||
DivergenceKind::Missing
|
||||
);
|
||||
assert!(empty.finish().is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
//! Transport for the executable Lean policy. This module makes no replay
|
||||
//! acceptance decisions; malformed/unavailable policy responses fail closed.
|
||||
use super::super::ProtocolStep;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Reply {
|
||||
pub policy: String,
|
||||
pub allow: bool,
|
||||
pub matched: usize,
|
||||
pub remaining: usize,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct StepWire {
|
||||
q: String,
|
||||
r: String,
|
||||
}
|
||||
|
||||
// Lean's derived FromJson requires every field, including fields with a Lean
|
||||
// default. Always send the complete record for init, prepare, receive and finish.
|
||||
#[derive(Serialize)]
|
||||
struct CommandWire<'a> {
|
||||
op: &'a str,
|
||||
steps: &'a [StepWire],
|
||||
value: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Client {
|
||||
child: Child,
|
||||
input: ChildStdin,
|
||||
replies: Receiver<Result<Reply, String>>,
|
||||
stderr: Receiver<String>,
|
||||
}
|
||||
|
||||
pub(super) fn request_key(session: &str, request: &Value) -> String {
|
||||
serde_json::to_string(&(session, request.to_string())).expect("strings serialize")
|
||||
}
|
||||
pub(super) fn response_key(response: &Result<Value, String>) -> String {
|
||||
serde_json::to_string(response).expect("protocol responses serialize")
|
||||
}
|
||||
|
||||
fn executable() -> PathBuf {
|
||||
if let Some(path) = std::env::var_os("MARQDO_REPLAY_POLICY") {
|
||||
return path.into();
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(parent) = exe.parent() {
|
||||
let adjacent = parent.join("marqdo-replay-policy");
|
||||
if adjacent.is_file() {
|
||||
return adjacent;
|
||||
}
|
||||
}
|
||||
}
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("verification/replay-policy/.lake/build/bin/replayPolicy")
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub(super) fn start(
|
||||
steps: impl IntoIterator<Item = ProtocolStep>,
|
||||
) -> Result<(Self, Reply), String> {
|
||||
Self::start_at(&executable(), steps)
|
||||
}
|
||||
|
||||
fn start_at(
|
||||
path: &Path,
|
||||
steps: impl IntoIterator<Item = ProtocolStep>,
|
||||
) -> Result<(Self, Reply), String> {
|
||||
let mut child = Command::new(path)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let input = child.stdin.take().ok_or("policy stdin unavailable")?;
|
||||
let output = child.stdout.take().ok_or("policy stdout unavailable")?;
|
||||
let mut errors = child.stderr.take().ok_or("policy stderr unavailable")?;
|
||||
let (sender, replies) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(output).lines() {
|
||||
let reply = line
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|line| serde_json::from_str(&line).map_err(|e| e.to_string()));
|
||||
let failed = reply.is_err();
|
||||
if sender.send(reply).is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
// Drain stderr concurrently so a verbose failure cannot block the child.
|
||||
// Retain a bounded diagnostic tail rather than buffering an entire stream.
|
||||
let (error_sender, stderr) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
const LIMIT: usize = 4096;
|
||||
let mut tail = Vec::new();
|
||||
let mut buffer = [0; LIMIT];
|
||||
while let Ok(count) = errors.read(&mut buffer) {
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
tail.extend_from_slice(&buffer[..count]);
|
||||
if tail.len() > LIMIT {
|
||||
tail.drain(..tail.len() - LIMIT);
|
||||
}
|
||||
}
|
||||
let _ = error_sender.send(String::from_utf8_lossy(&tail).trim().to_string());
|
||||
});
|
||||
let steps: Vec<_> = steps
|
||||
.into_iter()
|
||||
.map(|step| StepWire {
|
||||
q: request_key(&step.session, &step.request),
|
||||
r: response_key(&step.response),
|
||||
})
|
||||
.collect();
|
||||
let mut client = Self {
|
||||
child,
|
||||
input,
|
||||
replies,
|
||||
stderr,
|
||||
};
|
||||
let reply = client.send(CommandWire {
|
||||
op: "init",
|
||||
steps: &steps,
|
||||
value: "",
|
||||
})?;
|
||||
Ok((client, reply))
|
||||
}
|
||||
|
||||
pub(super) fn exchange(&mut self, op: &str, value: &str) -> Result<Reply, String> {
|
||||
self.send(CommandWire {
|
||||
op,
|
||||
steps: &[],
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
fn send(&mut self, command: CommandWire<'_>) -> Result<Reply, String> {
|
||||
let result = (|| {
|
||||
serde_json::to_writer(&mut self.input, &command).map_err(|e| e.to_string())?;
|
||||
self.input.write_all(b"\n").map_err(|e| e.to_string())?;
|
||||
self.input.flush().map_err(|e| e.to_string())?;
|
||||
let reply = self
|
||||
.replies
|
||||
.recv_timeout(Duration::from_secs(30))
|
||||
.map_err(|e| format!("policy response: {e}"))??;
|
||||
if reply.policy
|
||||
!= include_str!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/verification/replay-policy/POLICY-SHA256"
|
||||
))
|
||||
.trim()
|
||||
{
|
||||
return Err("policy executable does not match the compiled source identity".into());
|
||||
}
|
||||
if reply.allow == reply.reason.is_some() {
|
||||
return Err("policy response has inconsistent verdict and reason".into());
|
||||
}
|
||||
Ok(reply)
|
||||
})();
|
||||
result.map_err(|error| self.process_error(error))
|
||||
}
|
||||
|
||||
fn process_error(&mut self, mut error: String) -> String {
|
||||
// Prefer the actual exit status when the process has already failed.
|
||||
let status = match self.child.try_wait() {
|
||||
Ok(Some(status)) => Some(status),
|
||||
_ => {
|
||||
let _ = self.child.kill();
|
||||
self.child.wait().ok()
|
||||
}
|
||||
};
|
||||
if let Some(status) = status {
|
||||
error.push_str(&format!("; policy process {status}"));
|
||||
}
|
||||
if let Ok(stderr) = self.stderr.recv_timeout(Duration::from_millis(100)) {
|
||||
if !stderr.is_empty() {
|
||||
error.push_str(&format!("; stderr: {stderr}"));
|
||||
}
|
||||
}
|
||||
error
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[test]
|
||||
fn failed_companion_reports_its_exit_status_and_decoder_error() {
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join(format!(
|
||||
"policy-transport-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let executable = dir.join("failed-policy");
|
||||
std::fs::write(&executable, "#!/bin/sh\nIFS= read -r command\nprintf '%s\\n' 'PolicyCommand.value: String expected' >&2\nexit 17\n").unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let error = Client::start_at(&executable, Vec::<ProtocolStep>::new()).unwrap_err();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
assert!(error.contains("exit status: 17"), "{error}");
|
||||
assert!(
|
||||
error.contains("PolicyCommand.value: String expected"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
-829
@@ -1,829 +0,0 @@
|
||||
//! Filesystem host primitives.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn path_under_root(path: &Path, root: &Path) -> bool {
|
||||
let mut cur = path.to_path_buf();
|
||||
loop {
|
||||
if cur == *root {
|
||||
return true;
|
||||
}
|
||||
if !cur.pop() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_path(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("path must be text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_body(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("text must be text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the logical absolute path checked by native filesystem operations.
|
||||
pub fn resolve(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let checked = ctx.resolve_path(text_path(path)?)?;
|
||||
let absolute = if checked.is_absolute() { checked } else {
|
||||
std::env::current_dir().map_err(|error| error.to_string())?.join(checked)
|
||||
};
|
||||
let mut normalized = std::path::PathBuf::new();
|
||||
for component in absolute.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {},
|
||||
std::path::Component::ParentDir => { normalized.pop(); },
|
||||
component => normalized.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
normalized.to_str().map(|value| Value::Text(value.to_owned()))
|
||||
.ok_or_else(|| "resolved filesystem path is not UTF-8".into())
|
||||
}
|
||||
|
||||
pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if let Some(hit) = crate::host::sandbox_fs::cow_read_text(ctx, &p)? {
|
||||
return Ok(Value::Text(hit));
|
||||
}
|
||||
let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?;
|
||||
Ok(Value::Text(s))
|
||||
}
|
||||
|
||||
pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("write_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let body = text_body(text)?;
|
||||
if crate::host::sandbox_fs::cow_write_text(ctx, &p, body)? {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = p.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?;
|
||||
}
|
||||
fs::write(&p, body).map_err(|e| format!("write_text {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("append_text denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut current = match read_text(ctx,path) {
|
||||
Ok(Value::Text(text)) => text,
|
||||
Err(_) if !matches!(exists(ctx,path),Ok(Value::Bool(true))) => String::new(),
|
||||
Err(e) => return Err(e),
|
||||
_ => return Err("append_text needs UTF-8".into()),
|
||||
};
|
||||
current.push_str(text_body(text)?);
|
||||
crate::host::sandbox_fs::cow_write_text(ctx,&p,¤t)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
use std::io::Write;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&p)
|
||||
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
|
||||
f.write_all(text_body(text)?.as_bytes())
|
||||
.map_err(|e| format!("append_text {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if let Some(hit) = crate::host::sandbox_fs::cow_exists(ctx, &p)? {
|
||||
return Ok(Value::Bool(hit));
|
||||
}
|
||||
Ok(Value::Bool(p.exists()))
|
||||
}
|
||||
|
||||
pub fn list_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let mut names = Vec::new();
|
||||
let rd = fs::read_dir(&p).map_err(|e| format!("list_dir {}: {e}", p.display()))?;
|
||||
for ent in rd {
|
||||
let ent = ent.map_err(|e| format!("list_dir: {e}"))?;
|
||||
names.push(Value::Text(
|
||||
ent.file_name().to_string_lossy().into_owned(),
|
||||
));
|
||||
}
|
||||
names.sort_by(|a, b| a.as_display().cmp(&b.as_display()));
|
||||
Ok(Value::List(names))
|
||||
}
|
||||
|
||||
pub fn make_dir(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("make_dir denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dir directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
fs::create_dir_all(&p).map_err(|e| format!("make_dir {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// Explicit recursive mkdir (same host behavior as `make_dir`).
|
||||
pub fn make_dirs(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("make_dirs denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: make_dirs directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
fs::create_dir_all(&p).map_err(|e| format!("make_dirs {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("remove denied by host policy".into());
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if ctx.sandbox_session.is_some() && p.is_dir() {
|
||||
return Err("unsupported: recursive directory removal in CoW sandbox".into());
|
||||
}
|
||||
if crate::host::sandbox_fs::cow_remove(ctx, &p)? {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if p.is_dir() {
|
||||
fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
|
||||
} else {
|
||||
fs::remove_file(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// Remove a directory tree. Errors if `path` is a file.
|
||||
pub fn remove_tree(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("remove_tree denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() { return Err("unsupported: remove_tree directory state in CoW sandbox".into()); }
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
if !p.exists() {
|
||||
return Err(format!("remove_tree: not found: {}", p.display()));
|
||||
}
|
||||
if !p.is_dir() {
|
||||
return Err(format!("remove_tree: not a directory: {}", p.display()));
|
||||
}
|
||||
fs::remove_dir_all(&p).map_err(|e| format!("remove_tree {}: {e}", p.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// `{size, mtime_unix, is_file, is_dir}` for a path.
|
||||
pub fn stat(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let meta = fs::metadata(&p).map_err(|e| format!("stat {}: {e}", p.display()))?;
|
||||
let mtime = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0);
|
||||
Ok(Value::Map(vec![
|
||||
("size".into(), Value::Int(meta.len() as i64)),
|
||||
("mtime_unix".into(), Value::Int(mtime)),
|
||||
("is_file".into(), Value::Bool(meta.is_file())),
|
||||
("is_dir".into(), Value::Bool(meta.is_dir())),
|
||||
]))
|
||||
}
|
||||
|
||||
/// Depth-first walk; returns path texts relative to `path` (forward slashes), sorted per directory.
|
||||
pub fn walk(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let root = ctx.resolve_path(text_path(path)?)?;
|
||||
if !root.is_dir() {
|
||||
return Err(format!("walk: not a directory: {}", root.display()));
|
||||
}
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
walk_dfs(&root, Path::new(""), &mut out)?;
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
fn walk_dfs(abs: &Path, rel: &Path, out: &mut Vec<Value>) -> Result<(), String> {
|
||||
let mut entries: Vec<_> = fs::read_dir(abs)
|
||||
.map_err(|e| format!("walk {}: {e}", abs.display()))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| format!("walk: {e}"))?;
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for ent in entries {
|
||||
let name = ent.file_name();
|
||||
let child_rel = if rel.as_os_str().is_empty() {
|
||||
Path::new(&name).to_path_buf()
|
||||
} else {
|
||||
rel.join(&name)
|
||||
};
|
||||
let rel_text = child_rel
|
||||
.components()
|
||||
.map(|c| c.as_os_str().to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
out.push(Value::Text(rel_text));
|
||||
let ft = ent
|
||||
.file_type()
|
||||
.map_err(|e| format!("walk file_type: {e}"))?;
|
||||
if ft.is_dir() {
|
||||
walk_dfs(&ent.path(), &child_rel, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("copy_file denied by host policy".into());
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Err("conflict: copy source equals destination".into()); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
use std::io::Read;
|
||||
let bytes = match crate::host::sandbox_fs::cow_read_bytes(ctx,&from)? {
|
||||
Some(bytes) => bytes,
|
||||
None => { let mut bytes=Vec::new();fs::File::open(&from).map_err(|e|e.to_string())?
|
||||
.take(64*1024*1024+1).read_to_end(&mut bytes).map_err(|e|e.to_string())?;bytes },
|
||||
};
|
||||
if bytes.len()>64*1024*1024 { return Err("resource_limit: CoW copy exceeds 64 MiB".into()); }
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&to,&bytes)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?;
|
||||
}
|
||||
fs::copy(&from, &to).map_err(|e| format!("copy_file {} -> {}: {e}", from.display(), to.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("move denied by host policy".into());
|
||||
}
|
||||
let from = ctx.resolve_path(text_path(src)?)?;
|
||||
let to = ctx.resolve_path(text_path(dest)?)?;
|
||||
if from == to { return Ok(Value::None); }
|
||||
if ctx.sandbox_session.is_some() {
|
||||
copy_file(ctx,src,dest)?;
|
||||
crate::host::sandbox_fs::cow_remove(ctx,&from)?;
|
||||
return Ok(Value::None);
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("move mkdir: {e}"))?;
|
||||
}
|
||||
fs::rename(&from, &to).map_err(|e| format!("move {} -> {}: {e}", from.display(), to.display()))?;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// Create an empty temp file under the program cwd / fs_root; return relative path text.
|
||||
pub fn make_temp(ctx: &HostContext, prefix: Option<&Value>) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("make_temp denied by host policy".into());
|
||||
}
|
||||
let pref = match prefix {
|
||||
None | Some(Value::None) => "mqtmp".to_string(),
|
||||
Some(v) => text_path(v)?.to_string(),
|
||||
};
|
||||
if pref.contains('/') || pref.contains('\\') || pref.contains("..") {
|
||||
return Err("make_temp: prefix must be a simple name".into());
|
||||
}
|
||||
let stamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let name = format!("{pref}-{stamp}");
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
if matches!(exists(ctx,&Value::Text(name.clone()))?,Value::Bool(true)) {
|
||||
return Err("conflict: temporary path exists".into());
|
||||
}
|
||||
crate::host::sandbox_fs::cow_write_bytes(ctx,&p,&[])?;
|
||||
return Ok(Value::Text(name));
|
||||
}
|
||||
if let Some(parent) = p.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("make_temp mkdir: {e}"))?;
|
||||
}
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&p)
|
||||
.map_err(|e| format!("make_temp {}: {e}", p.display()))?;
|
||||
Ok(Value::Text(name))
|
||||
}
|
||||
|
||||
/// Exact UTF-8 FIND→REPLACE on a file. `find` must occur exactly once.
|
||||
pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("text_patch denied by host policy".into());
|
||||
}
|
||||
let display = text_path(path)?;
|
||||
let find = text_body(find)?;
|
||||
let replace = text_body(replace)?;
|
||||
if find.is_empty() {
|
||||
return Err("text_patch: find must be non-empty".into());
|
||||
}
|
||||
let Value::Text(src) = read_text(ctx,path)? else { return Err("text_patch needs text".into()); };
|
||||
let count = src.matches(find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"text_patch: find not found in {}",
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"text_patch: find matched {count} times in {} (must be unique)",
|
||||
display
|
||||
));
|
||||
}
|
||||
let next = src.replacen(find, replace, 1);
|
||||
write_text(ctx,path,&Value::Text(next))?;
|
||||
Ok(Value::Int(1))
|
||||
}
|
||||
|
||||
/// Apply one or more FIND/REPLACE blocks from plan-reply text.
|
||||
///
|
||||
/// Preferred blocks:
|
||||
/// ```text
|
||||
/// <<<
|
||||
/// FIND
|
||||
/// <old>
|
||||
/// ===
|
||||
/// REPLACE
|
||||
/// <new>
|
||||
/// >>>
|
||||
/// ```
|
||||
///
|
||||
/// Also accepts fenced pairs (common model mistake):
|
||||
/// ````text
|
||||
/// ```find
|
||||
/// <old>
|
||||
/// ```
|
||||
/// ```replace
|
||||
/// <new>
|
||||
/// ```
|
||||
/// ````
|
||||
pub fn apply_patch_blocks(
|
||||
ctx: &HostContext,
|
||||
path: &Value,
|
||||
text: &Value,
|
||||
soft: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("apply_patch_blocks denied by host policy".into());
|
||||
}
|
||||
let soft = match soft {
|
||||
None | Some(Value::None) => false,
|
||||
Some(v) => v.truthy(),
|
||||
};
|
||||
match apply_patch_blocks_inner(ctx, path, text) {
|
||||
Ok(n) => Ok(n),
|
||||
// soft swallows unique-FIND miss and empty FIND (model protocol mistakes).
|
||||
// Never softens parse / multi-match / whole-file rewrite.
|
||||
Err(e) if soft && (e.contains("FIND not found") || e.contains("empty FIND")) => {
|
||||
Ok(Value::Int(0))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject FIND that rewrites a non-trivial file wholesale (exact or ≥90% span).
|
||||
/// Tiny files may be replaced entirely (e.g. two-line import rewrites).
|
||||
fn find_spans_whole_file(src: &str, find: &str) -> bool {
|
||||
const MIN_BYTES: usize = 800;
|
||||
let st = src.trim();
|
||||
let ft = find.trim();
|
||||
if ft.is_empty() || src.len() < MIN_BYTES {
|
||||
return false;
|
||||
}
|
||||
if st == ft {
|
||||
return true;
|
||||
}
|
||||
if !src.contains(find) {
|
||||
return false;
|
||||
}
|
||||
find.len().saturating_mul(10) >= src.len().saturating_mul(9)
|
||||
}
|
||||
|
||||
fn apply_patch_blocks_inner(
|
||||
ctx: &HostContext,
|
||||
path: &Value,
|
||||
text: &Value,
|
||||
) -> Result<Value, String> {
|
||||
let blocks = parse_patch_blocks(text_body(text)?)?;
|
||||
if blocks.is_empty() {
|
||||
return Ok(Value::Int(0));
|
||||
}
|
||||
let display = text_path(path)?;
|
||||
let Value::Text(mut src) = read_text(ctx,path)? else { return Err("apply_patch_blocks needs text".into()); };
|
||||
let mut applied = 0i64;
|
||||
for (find, replace) in blocks {
|
||||
if find.is_empty() {
|
||||
return Err("apply_patch_blocks: empty FIND".into());
|
||||
}
|
||||
if find_spans_whole_file(&src, &find) {
|
||||
return Err(
|
||||
"apply_patch_blocks: FIND spans entire file (whole-file rewrite forbidden)"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let count = src.matches(&find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND not found in {}",
|
||||
display
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND matched {count} times in {} (must be unique)",
|
||||
display
|
||||
));
|
||||
}
|
||||
src = src.replacen(&find, &replace, 1);
|
||||
applied += 1;
|
||||
}
|
||||
write_text(ctx,path,&Value::Text(src))?;
|
||||
Ok(Value::Int(applied))
|
||||
}
|
||||
|
||||
fn parse_patch_blocks(text: &str) -> Result<Vec<(String, String)>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find("<<<") {
|
||||
let after = &rest[start + 3..];
|
||||
let end = after
|
||||
.find(">>>")
|
||||
.ok_or_else(|| "apply_patch_blocks: unclosed <<< block".to_string())?;
|
||||
let body = after[..end].trim();
|
||||
rest = &after[end + 3..];
|
||||
let (find_part, replace_part) = body
|
||||
.split_once("===")
|
||||
.ok_or_else(|| "apply_patch_blocks: block missing ===".to_string())?;
|
||||
let find = strip_labeled(find_part, "FIND")?;
|
||||
let replace = strip_labeled(replace_part, "REPLACE")?;
|
||||
out.push((find, replace));
|
||||
}
|
||||
if out.is_empty() {
|
||||
parse_fence_find_replace(text, &mut out)?;
|
||||
}
|
||||
if out.is_empty() {
|
||||
parse_begin_patch_hunks(text, &mut out)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// ```find … ``` followed by ```replace … ``` (label case-insensitive).
|
||||
fn parse_fence_find_replace(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> {
|
||||
let mut i = 0;
|
||||
while i < text.len() {
|
||||
let Some(rel) = text[i..].find("```") else {
|
||||
break;
|
||||
};
|
||||
let open = i + rel;
|
||||
let after_ticks = open + 3;
|
||||
let header_end = text[after_ticks..]
|
||||
.find('\n')
|
||||
.map(|n| after_ticks + n)
|
||||
.unwrap_or(text.len());
|
||||
let label = text[after_ticks..header_end]
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_ascii_lowercase();
|
||||
if label != "find" {
|
||||
i = after_ticks;
|
||||
continue;
|
||||
}
|
||||
let body_start = if header_end < text.len() {
|
||||
header_end + 1
|
||||
} else {
|
||||
header_end
|
||||
};
|
||||
let Some(rel_close) = text[body_start..].find("```") else {
|
||||
return Err("apply_patch_blocks: unclosed ```find fence".into());
|
||||
};
|
||||
let find_end = body_start + rel_close;
|
||||
let find = text[body_start..find_end]
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_string();
|
||||
let mut j = find_end + 3;
|
||||
while j < text.len() && text.as_bytes()[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if text[j..].starts_with("```") {
|
||||
j += 3;
|
||||
} else {
|
||||
return Err("apply_patch_blocks: ```find without following ```replace".into());
|
||||
}
|
||||
let rep_header_end = text[j..]
|
||||
.find('\n')
|
||||
.map(|n| j + n)
|
||||
.unwrap_or(text.len());
|
||||
let rep_label = text[j..rep_header_end]
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_ascii_lowercase();
|
||||
if rep_label != "replace" {
|
||||
return Err("apply_patch_blocks: ```find without following ```replace".into());
|
||||
}
|
||||
let rep_body_start = if rep_header_end < text.len() {
|
||||
rep_header_end + 1
|
||||
} else {
|
||||
rep_header_end
|
||||
};
|
||||
let Some(rel_rep_close) = text[rep_body_start..].find("```") else {
|
||||
return Err("apply_patch_blocks: unclosed ```replace fence".into());
|
||||
};
|
||||
let rep_end = rep_body_start + rel_rep_close;
|
||||
let replace = text[rep_body_start..rep_end]
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_string();
|
||||
out.push((find, replace));
|
||||
i = rep_end + 3;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Minimal support for `*** Begin Patch` / `*** End Patch` with `-`/`+` line pairs
|
||||
/// (same line count preferred; falls back to joining all `-` vs all `+` in the hunk).
|
||||
fn parse_begin_patch_hunks(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> {
|
||||
const BEGIN: &str = "*** Begin Patch";
|
||||
const END: &str = "*** End Patch";
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find(BEGIN) {
|
||||
let after = &rest[start + BEGIN.len()..];
|
||||
let end = after
|
||||
.find(END)
|
||||
.ok_or_else(|| "apply_patch_blocks: unclosed *** Begin Patch".to_string())?;
|
||||
let body = &after[..end];
|
||||
rest = &after[end + END.len()..];
|
||||
let mut minus: Vec<&str> = Vec::new();
|
||||
let mut plus: Vec<&str> = Vec::new();
|
||||
for line in body.lines() {
|
||||
if let Some(s) = line.strip_prefix('-') {
|
||||
if s.starts_with('-') {
|
||||
continue; // skip --- / file headers like ---
|
||||
}
|
||||
// skip diff file headers "*** Update File" already not prefixed with single -
|
||||
minus.push(s.strip_prefix(' ').unwrap_or(s));
|
||||
} else if let Some(s) = line.strip_prefix('+') {
|
||||
if s.starts_with('+') {
|
||||
continue;
|
||||
}
|
||||
plus.push(s.strip_prefix(' ').unwrap_or(s));
|
||||
}
|
||||
}
|
||||
if minus.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let find = minus.join("\n");
|
||||
let replace = plus.join("\n");
|
||||
out.push((find, replace));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strip_labeled(chunk: &str, label: &str) -> Result<String, String> {
|
||||
let t = chunk.trim();
|
||||
let upper = t.to_ascii_uppercase();
|
||||
let label_u = label.to_ascii_uppercase();
|
||||
if upper.starts_with(&label_u) {
|
||||
let after = t[label.len()..].trim_start_matches([':', ' ', '\t']);
|
||||
let after = after.strip_prefix('\n').unwrap_or(after);
|
||||
Ok(after.to_string())
|
||||
} else {
|
||||
Ok(t.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::host::{HostCaps, HostContext};
|
||||
use std::fs;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn write_ctx(dir: &std::path::Path) -> HostContext {
|
||||
let entry = dir.join("entry.mq.md");
|
||||
let _ = fs::write(&entry, "# main\n");
|
||||
let mut ctx = HostContext::for_run(Some(&entry), HostCaps::default(), vec![]);
|
||||
ctx.cwd = dir.to_path_buf();
|
||||
ctx.fs_root = Some(dir.to_path_buf());
|
||||
ctx
|
||||
}
|
||||
|
||||
fn temp_workspace(tag: &str) -> std::path::PathBuf {
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("marqdo-fs-{tag}-{nanos}"));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_patch_unique() {
|
||||
let dir = temp_workspace("patch");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "hello OLD world").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let n = text_patch(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text("OLD".into()),
|
||||
&Value::Text("NEW".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "hello NEW world");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_two() {
|
||||
let dir = temp_workspace("blocks");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "aa bb cc").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = r#"
|
||||
DECISION: CONTINUE
|
||||
PATCH:
|
||||
<<<
|
||||
FIND
|
||||
aa
|
||||
===
|
||||
REPLACE
|
||||
AA
|
||||
>>>
|
||||
<<<
|
||||
FIND
|
||||
cc
|
||||
===
|
||||
REPLACE
|
||||
CC
|
||||
>>>
|
||||
"#;
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(2));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "AA bb CC");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_fence_find_replace() {
|
||||
let dir = temp_workspace("fence");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "old line\nkeep\n").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = "DECISION: CONTINUE\nPATCH:\n```find\nold line\n```\n```replace\nnew line\n```\n";
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "new line\nkeep\n");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_begin_patch() {
|
||||
let dir = temp_workspace("beginpatch");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(
|
||||
&path,
|
||||
"> ext/ai/llm.mq.md\n> lib/json.mq.md\n",
|
||||
)
|
||||
.unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = r#"
|
||||
DECISION: CONTINUE
|
||||
PATCH:
|
||||
```patch
|
||||
*** Begin Patch
|
||||
*** Update File: a.md
|
||||
@@
|
||||
-> ext/ai/llm.mq.md
|
||||
-> lib/json.mq.md
|
||||
+import:
|
||||
+ llm: ext/ai/llm.mq.md
|
||||
+ json: lib/json.mq.md
|
||||
*** End Patch
|
||||
```
|
||||
"#;
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(
|
||||
fs::read_to_string(&path).unwrap(),
|
||||
"import:\n llm: ext/ai/llm.mq.md\n json: lib/json.mq.md\n"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_soft_miss() {
|
||||
let dir = temp_workspace("soft");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "hello").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = "<<<\nFIND\nmissing\n===\nREPLACE\nx\n>>>\n";
|
||||
let hard = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
);
|
||||
assert!(hard.is_err());
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
Some(&Value::Bool(true)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(0));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "hello");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_rejects_whole_file_find() {
|
||||
let dir = temp_workspace("whole");
|
||||
let path = dir.join("a.md");
|
||||
let body = format!(
|
||||
"---\ntitle: workbook\n---\n\n# main\n\n{}",
|
||||
"line padding for size threshold\n".repeat(40)
|
||||
);
|
||||
assert!(body.len() >= 800, "fixture too small: {}", body.len());
|
||||
fs::write(&path, &body).unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = format!(
|
||||
"<<<\nFIND\n{body}===\nREPLACE\n# main\n\n> print text=bye\n>>>\n"
|
||||
);
|
||||
let err = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.contains("whole-file rewrite forbidden"),
|
||||
"unexpected err={err}"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), body);
|
||||
let soft_err = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(format!(
|
||||
"<<<\nFIND\n{body}===\nREPLACE\nx\n>>>\n"
|
||||
)),
|
||||
Some(&Value::Bool(true)),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(soft_err.contains("whole-file rewrite forbidden"));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_soft_keeps_multi_match_hard() {
|
||||
let dir = temp_workspace("multisoft");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "xx xx").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = "<<<\nFIND\nxx\n===\nREPLACE\nYY\n>>>\n";
|
||||
let err = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
Some(&Value::Bool(true)),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.contains("matched 2 times"), "unexpected err={err}");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "xx xx");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1,681 +0,0 @@
|
||||
//! Bounded filesystem tasks. Public authors use lib/fs, lib/path and lib/bytes.
|
||||
use super::{as_text, encoding, fs as legacy, result, sandbox_fs};
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
const MAX_READ: usize = 64 * 1024 * 1024;
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> {
|
||||
as_text(arg(b, k)?, k)
|
||||
}
|
||||
fn number(b: &Args, k: &str) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
fn flag(b: &Args, k: &str) -> bool {
|
||||
matches!(b.get(k), Some(Value::Bool(true)))
|
||||
}
|
||||
fn native(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.sandbox_session.is_some() {
|
||||
Err("operation unavailable in CoW sandbox; use write_text/remove_file".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn writable(ctx: &HostContext) -> Result<(), String> {
|
||||
if ctx.allow_fs_write() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("filesystem write denied by host policy".into())
|
||||
}
|
||||
}
|
||||
fn path(ctx: &HostContext, b: &Args, k: &str) -> Result<PathBuf, String> {
|
||||
ctx.resolve_path(text(b, k)?)
|
||||
}
|
||||
fn ioerr(e: std::io::Error) -> String {
|
||||
let code = match e.kind() {
|
||||
std::io::ErrorKind::NotFound => "not_found",
|
||||
std::io::ErrorKind::PermissionDenied => "permission_denied",
|
||||
std::io::ErrorKind::AlreadyExists => "conflict",
|
||||
_ => "operation_failed",
|
||||
};
|
||||
format!("{code}: {e}")
|
||||
}
|
||||
fn limit(b: &Args, k: &str) -> Result<usize, String> {
|
||||
let n = number(b, k)?;
|
||||
if n == 0 || n > MAX_READ as u64 {
|
||||
return Err(format!("{k} must be 1..{MAX_READ}"));
|
||||
}
|
||||
Ok(n as usize)
|
||||
}
|
||||
pub(super) fn bytes_value(bytes: &[u8]) -> Value {
|
||||
Value::Map(vec![
|
||||
("_type".into(), Value::Text("bytes".into())),
|
||||
("base64".into(), Value::Text(encoding::encode_base64(bytes))),
|
||||
])
|
||||
}
|
||||
pub(super) fn bytes(v: &Value) -> Result<Vec<u8>, String> {
|
||||
let Value::Map(fields) = v else {
|
||||
return Err("expected bytes record from lib/bytes or fs.read_bytes".into());
|
||||
};
|
||||
if !fields
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_type" && v == &Value::Text("bytes".into()))
|
||||
{
|
||||
return Err("expected _type bytes".into());
|
||||
}
|
||||
let text = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == "base64")
|
||||
.ok_or("missing bytes.base64")?;
|
||||
encoding::decode_base64(as_text(&text.1, "base64")?)
|
||||
}
|
||||
fn read(ctx: &HostContext, p: &Path, max: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, p)? {
|
||||
if bytes.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
return Ok(bytes);
|
||||
}
|
||||
fs::File::open(p)
|
||||
.map_err(ioerr)?
|
||||
.take(max as u64 + 1)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(ioerr)?;
|
||||
if out.len() > max {
|
||||
return Err("file exceeds max_bytes".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn atomic(ctx: &HostContext, p: &Path, body: &[u8]) -> Result<(), String> {
|
||||
writable(ctx)?;
|
||||
if sandbox_fs::cow_write_bytes(ctx, p, body)? {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = p.parent().ok_or("file needs parent")?;
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
// create_new reserves the sibling name. Never truncate an existing temp file.
|
||||
let mut reserved = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = entropy
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-{name}.tmp"));
|
||||
match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
{
|
||||
Ok(file) => {
|
||||
reserved = Some((temp, file));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
let (temp, mut file) = reserved.ok_or("cannot reserve atomic write file")?;
|
||||
let result = (|| {
|
||||
file.write_all(body).map_err(ioerr)?;
|
||||
file.sync_all().map_err(ioerr)?;
|
||||
drop(file);
|
||||
fs::rename(&temp, p).map_err(ioerr)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
let answer = match id {
|
||||
HostFn::FsTryReadText => {
|
||||
let answer = (|| {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, 8 * 1024 * 1024)?;
|
||||
String::from_utf8(data)
|
||||
.map(Value::Text)
|
||||
.map_err(|e| format!("invalid_encoding: {e}"))
|
||||
})();
|
||||
return Ok(result::capture("fs.read_text", answer));
|
||||
}
|
||||
HostFn::FsTryWriteText => {
|
||||
return Ok(result::capture(
|
||||
"fs.write_text",
|
||||
legacy::write_text(ctx, arg(b, "path")?, arg(b, "text")?),
|
||||
))
|
||||
}
|
||||
HostFn::TryJsonParse => {
|
||||
return Ok(result::capture(
|
||||
"json.parse",
|
||||
super::json::parse(arg(b, "text")?).map_err(|e| format!("invalid_json: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::TryCsvParse => {
|
||||
return Ok(result::capture(
|
||||
"csv.parse",
|
||||
super::csv::parse(arg(b, "text")?).map_err(|e| format!("invalid_csv: {e}")),
|
||||
))
|
||||
}
|
||||
HostFn::BytesFromText => bytes_value(text(b, "text")?.as_bytes()),
|
||||
HostFn::BytesFromBase64 => bytes_value(&encoding::decode_base64(text(b, "text")?)?),
|
||||
HostFn::BytesToText => Value::Text(
|
||||
String::from_utf8(bytes(arg(b, "data")?)?)
|
||||
.map_err(|e| format!("bytes are not UTF-8: {e}"))?,
|
||||
),
|
||||
HostFn::BytesToBase64 => Value::Text(encoding::encode_base64(&bytes(arg(b, "data")?)?)),
|
||||
HostFn::BytesLen => Value::Int(bytes(arg(b, "data")?)?.len() as i64),
|
||||
HostFn::BytesSlice => {
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
let start = usize::try_from(number(b, "start")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
let end = usize::try_from(number(b, "end")?)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(data.len());
|
||||
bytes_value(if start > end { &[] } else { &data[start..end] })
|
||||
}
|
||||
HostFn::FsReadBytes => {
|
||||
bytes_value(&read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?)
|
||||
}
|
||||
HostFn::FsWriteBytes => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
atomic(ctx, &p, &bytes(arg(b, "data")?)?)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsReadChunk => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let offset = number(b, "offset")?;
|
||||
let size = limit(b, "size")?;
|
||||
let mut data = vec![0u8; size];
|
||||
let (n, total) = if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
let start = usize::try_from(offset)
|
||||
.unwrap_or(usize::MAX)
|
||||
.min(bytes.len());
|
||||
let end = start.saturating_add(size).min(bytes.len());
|
||||
data[..end - start].copy_from_slice(&bytes[start..end]);
|
||||
(end - start, bytes.len() as u64)
|
||||
} else {
|
||||
let mut file = fs::File::open(&p).map_err(ioerr)?;
|
||||
let total = file.metadata().map_err(ioerr)?.len();
|
||||
file.seek(SeekFrom::Start(offset)).map_err(ioerr)?;
|
||||
let n = file.take(size as u64).read(&mut data).map_err(ioerr)?;
|
||||
(n, total)
|
||||
};
|
||||
data.truncate(n);
|
||||
let next = offset.checked_add(n as u64).ok_or("offset overflow")?;
|
||||
Value::Map(vec![
|
||||
("data".into(), bytes_value(&data)),
|
||||
("next_offset".into(), Value::Int(next as i64)),
|
||||
("eof".into(), Value::Bool(next >= total)),
|
||||
])
|
||||
}
|
||||
HostFn::FsAppendBytes => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
let data = bytes(arg(b, "data")?)?;
|
||||
if ctx.sandbox_session.is_some() {
|
||||
let mut body = read(ctx, &p, MAX_READ).or_else(|e| {
|
||||
if matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(false))) {
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})?;
|
||||
body.extend_from_slice(&data);
|
||||
sandbox_fs::cow_write_bytes(ctx, &p, &body)?;
|
||||
} else {
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&p)
|
||||
.map_err(ioerr)?;
|
||||
f.write_all(&data).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsAtomicWrite | HostFn::FsWriteChanged => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let body = text(b, "text")?.as_bytes();
|
||||
if id == HostFn::FsWriteChanged && read(ctx, &p, MAX_READ).ok().as_deref() == Some(body)
|
||||
{
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
atomic(ctx, &p, body)?;
|
||||
if id == HostFn::FsWriteChanged {
|
||||
Value::Bool(true)
|
||||
} else {
|
||||
Value::None
|
||||
}
|
||||
}
|
||||
HostFn::FsWriteChecked => {
|
||||
let change = (|| {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let expected = text(b, "expected_sha256")?;
|
||||
let current = read(ctx, &p, MAX_READ)?;
|
||||
let actual = format!("{:x}", Sha256::digest(¤t));
|
||||
if actual != expected {
|
||||
return Err("conflict: file content changed".into());
|
||||
}
|
||||
atomic(ctx, &p, text(b, "text")?.as_bytes()).map(|_| Value::None)
|
||||
})();
|
||||
return Ok(result::capture("fs.write_checked", change));
|
||||
}
|
||||
HostFn::FsReadLines => {
|
||||
let data = read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?;
|
||||
let text = String::from_utf8(data).map_err(|e| format!("file is not UTF-8: {e}"))?;
|
||||
Value::List(text.lines().map(|s| Value::Text(s.into())).collect())
|
||||
}
|
||||
HostFn::FsWriteLines => {
|
||||
let Value::List(lines) = arg(b, "lines")? else {
|
||||
return Err("lines must be list of text".into());
|
||||
};
|
||||
let lines = lines
|
||||
.iter()
|
||||
.map(|v| as_text(v, "line"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut body = lines.join("\n");
|
||||
if !lines.is_empty() {
|
||||
body.push('\n')
|
||||
};
|
||||
atomic(ctx, &path(ctx, b, "path")?, body.as_bytes())?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveFile => {
|
||||
writable(ctx)?;
|
||||
let p = path(ctx, b, "path")?;
|
||||
if p.is_dir() {
|
||||
return Err("remove_file refuses directory".into());
|
||||
}
|
||||
if !matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(true))) {
|
||||
return Err("not_found: remove_file target absent".into());
|
||||
}
|
||||
if !sandbox_fs::cow_remove(ctx, &p)? {
|
||||
fs::remove_file(p).map_err(ioerr)?;
|
||||
}
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsRemoveEmptyDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
fs::remove_dir(path(ctx, b, "path")?).map_err(ioerr)?;
|
||||
Value::None
|
||||
}
|
||||
HostFn::FsTempDir => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let prefix = text(b, "prefix")?;
|
||||
if prefix.contains('/') || prefix.contains('\\') || prefix.contains("..") {
|
||||
return Err("temp prefix must be simple name".into());
|
||||
}
|
||||
let mut created = None;
|
||||
for _ in 0..128 {
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let name = format!(
|
||||
"{prefix}-{}",
|
||||
entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>()
|
||||
);
|
||||
let p = ctx.resolve_path(&name)?;
|
||||
match fs::create_dir(p) {
|
||||
Ok(()) => {
|
||||
created = Some(Value::Text(name));
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(ioerr(e)),
|
||||
}
|
||||
}
|
||||
created.ok_or("unable to reserve temporary directory")?
|
||||
}
|
||||
HostFn::FsFileHash => {
|
||||
let p = path(ctx, b, "path")?;
|
||||
let mut hasher = Sha256::new();
|
||||
if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? {
|
||||
hasher.update(bytes)
|
||||
} else {
|
||||
let mut f = fs::File::open(p).map_err(ioerr)?;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = f.read(&mut buffer).map_err(ioerr)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..n]);
|
||||
}
|
||||
}
|
||||
Value::Text(format!("{:x}", hasher.finalize()))
|
||||
}
|
||||
HostFn::FsFind => {
|
||||
let root = path(ctx, b, "path")?;
|
||||
let pattern = glob(text(b, "pattern")?)?;
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let max_depth = number(b, "max_depth")? as usize;
|
||||
let kind = text(b, "kind")?;
|
||||
if !matches!(kind, "file" | "dir" | "all") {
|
||||
return Err("find kind must be file/dir/all".into());
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&root,
|
||||
Path::new(""),
|
||||
&pattern,
|
||||
&excluded,
|
||||
max_depth,
|
||||
kind,
|
||||
&mut files,
|
||||
)?;
|
||||
Value::List(files)
|
||||
}
|
||||
HostFn::FsCopyTree | HostFn::FsSyncTree => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let src = path(ctx, b, "src")?;
|
||||
let dest = path(ctx, b, "dest")?;
|
||||
if dest.starts_with(&src) || src.starts_with(&dest) {
|
||||
return Err("copy/sync trees must be disjoint".into());
|
||||
}
|
||||
if !src.is_dir() {
|
||||
return Err("src must be directory".into());
|
||||
}
|
||||
let excluded = patterns(arg(b, "exclude")?)?;
|
||||
let mut files = Vec::new();
|
||||
find(
|
||||
ctx,
|
||||
&src,
|
||||
Path::new(""),
|
||||
&glob("**")?,
|
||||
&excluded,
|
||||
256,
|
||||
"file",
|
||||
&mut files,
|
||||
)?;
|
||||
let mut jobs = Vec::new();
|
||||
for name in files {
|
||||
let name = as_text(&name, "name")?;
|
||||
let from = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
let to = ctx.resolve_path(dest.join(name).to_str().ok_or("non UTF-8 path")?)?;
|
||||
if to.exists() {
|
||||
if id == HostFn::FsSyncTree && files_equal(&from, &to)? {
|
||||
continue;
|
||||
}
|
||||
if !flag(b, "overwrite") {
|
||||
return Err(format!("destination conflict: {}", to.display()));
|
||||
}
|
||||
}
|
||||
jobs.push((from, to, name.to_string()));
|
||||
}
|
||||
let dry = flag(b, "dry_run");
|
||||
let mut changed = Vec::new();
|
||||
for (from, to, name) in jobs {
|
||||
if !dry {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::copy(from, to).map_err(ioerr)?;
|
||||
}
|
||||
changed.push(Value::Text(name));
|
||||
}
|
||||
Value::List(changed)
|
||||
}
|
||||
HostFn::FsRenameMany => {
|
||||
writable(ctx)?;
|
||||
native(ctx)?;
|
||||
let Value::List(rows) = arg(b, "moves")? else {
|
||||
return Err("moves must be record list".into());
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
let mut destinations = std::collections::HashSet::new();
|
||||
let mut sources = std::collections::HashSet::new();
|
||||
for row in rows {
|
||||
let Value::Map(fields) = row else {
|
||||
return Err("move needs src,dest".into());
|
||||
};
|
||||
let mut paths = Vec::new();
|
||||
for key in ["src", "dest"] {
|
||||
let value = fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.ok_or("move needs src,dest")?;
|
||||
paths.push(ctx.resolve_path(as_text(&value.1, key)?)?);
|
||||
}
|
||||
if !paths[0].is_file() {
|
||||
return Err("rename_many source must be file".into());
|
||||
}
|
||||
if !sources.insert(paths[0].clone()) {
|
||||
return Err("conflict: repeated rename source".into());
|
||||
}
|
||||
if paths[1].exists() || !destinations.insert(paths[1].clone()) {
|
||||
return Err("rename_many destination conflict".into());
|
||||
}
|
||||
jobs.push((paths.remove(0), paths.remove(0)));
|
||||
}
|
||||
// Preflight all paths. Execution is ordered and deliberately not transactional.
|
||||
if !flag(b, "dry_run") {
|
||||
for (from, to) in &jobs {
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(ioerr)?;
|
||||
}
|
||||
fs::rename(from, to).map_err(ioerr)?;
|
||||
}
|
||||
}
|
||||
Value::Int(jobs.len() as i64)
|
||||
}
|
||||
HostFn::PathRelative => {
|
||||
let normalized = super::path::normalize(arg(b, "path")?)?;
|
||||
let normalized_base = super::path::normalize(arg(b, "base")?)?;
|
||||
let path = PathBuf::from(as_text(&normalized, "path")?);
|
||||
let base = PathBuf::from(as_text(&normalized_base, "base")?);
|
||||
if path.is_absolute() != base.is_absolute() {
|
||||
return Err("relative paths must share absolute/relative form".into());
|
||||
}
|
||||
let a: Vec<_> = path.components().collect();
|
||||
let b: Vec<_> = base.components().collect();
|
||||
if path.is_absolute() && a.first() != b.first() {
|
||||
return Err("relative paths have different roots".into());
|
||||
}
|
||||
let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
|
||||
let mut out = PathBuf::new();
|
||||
for _ in common..b.len() {
|
||||
out.push("..")
|
||||
}
|
||||
for c in &a[common..] {
|
||||
out.push(c.as_os_str())
|
||||
}
|
||||
Value::Text(if out.as_os_str().is_empty() {
|
||||
".".into()
|
||||
} else {
|
||||
out.to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
}
|
||||
HostFn::PathWithExtension => {
|
||||
let mut p = PathBuf::from(text(b, "path")?);
|
||||
let ext = text(b, "extension")?;
|
||||
if ext.contains('/') || ext.contains('\\') {
|
||||
return Err("extension cannot contain path separator".into());
|
||||
}
|
||||
p.set_extension(ext.trim_start_matches('.'));
|
||||
Value::Text(p.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
_ => return Err("not a filesystem task".into()),
|
||||
};
|
||||
Ok(answer)
|
||||
}
|
||||
fn patterns(v: &Value) -> Result<Vec<regex::Regex>, String> {
|
||||
if matches!(v, Value::None) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let Value::List(xs) = v else {
|
||||
return Err("exclude must be list of patterns".into());
|
||||
};
|
||||
xs.iter().map(|v| glob(as_text(v, "pattern")?)).collect()
|
||||
}
|
||||
fn glob(pattern: &str) -> Result<regex::Regex, String> {
|
||||
let mut out = String::from("^");
|
||||
let mut cs = pattern.chars().peekable();
|
||||
while let Some(c) = cs.next() {
|
||||
match c {
|
||||
'*' => {
|
||||
if cs.peek() == Some(&'*') {
|
||||
cs.next();
|
||||
if cs.peek() == Some(&'/') {
|
||||
cs.next();
|
||||
out.push_str("(?:.*/)?")
|
||||
} else {
|
||||
out.push_str(".*")
|
||||
}
|
||||
} else {
|
||||
out.push_str("[^/]*")
|
||||
}
|
||||
}
|
||||
'?' => out.push_str("[^/]"),
|
||||
_ => out.push_str(®ex::escape(&c.to_string())),
|
||||
}
|
||||
}
|
||||
out.push('$');
|
||||
regex::Regex::new(&out).map_err(|e| e.to_string())
|
||||
}
|
||||
fn find(
|
||||
ctx: &HostContext,
|
||||
root: &Path,
|
||||
rel: &Path,
|
||||
pattern: ®ex::Regex,
|
||||
exclude: &[regex::Regex],
|
||||
depth: usize,
|
||||
kind: &str,
|
||||
out: &mut Vec<Value>,
|
||||
) -> Result<(), String> {
|
||||
if depth == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let mut entries = fs::read_dir(root.join(rel))
|
||||
.map_err(ioerr)?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(ioerr)?;
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let child = rel.join(entry.file_name());
|
||||
let name = child.to_string_lossy().replace('\\', "/");
|
||||
let ty = entry.file_type().map_err(ioerr)?;
|
||||
if exclude
|
||||
.iter()
|
||||
.any(|r| r.is_match(&name) || r.is_match(&format!("{name}/")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// No symlink traversal. Reads returned by this finder still use resolve_path.
|
||||
if ty.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
ctx.resolve_path(entry.path().to_str().ok_or("non UTF-8 path")?)?;
|
||||
if pattern.is_match(&name)
|
||||
&& ((ty.is_file() && kind != "dir") || (ty.is_dir() && kind != "file"))
|
||||
{
|
||||
if out.len() >= 100_000 {
|
||||
return Err("find exceeds 100000 entries".into());
|
||||
}
|
||||
out.push(Value::Text(name))
|
||||
}
|
||||
if ty.is_dir() {
|
||||
find(ctx, root, &child, pattern, exclude, depth - 1, kind, out)?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn files_equal(a: &Path, b: &Path) -> Result<bool, String> {
|
||||
if fs::metadata(a).map_err(ioerr)?.len() != fs::metadata(b).map_err(ioerr)?.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut a = std::io::BufReader::new(fs::File::open(a).map_err(ioerr)?);
|
||||
let mut b = std::io::BufReader::new(fs::File::open(b).map_err(ioerr)?);
|
||||
use std::io::BufRead;
|
||||
loop {
|
||||
let left = a.fill_buf().map_err(ioerr)?;
|
||||
let right = b.fill_buf().map_err(ioerr)?;
|
||||
if left.is_empty() || right.is_empty() {
|
||||
return Ok(left.is_empty() && right.is_empty());
|
||||
}
|
||||
let n = left.len().min(right.len());
|
||||
if left[..n] != right[..n] {
|
||||
return Ok(false);
|
||||
}
|
||||
a.consume(n);
|
||||
b.consume(n);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod overlay_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn byte_append_copy_and_patch_stay_in_the_overlay_until_commit() {
|
||||
let root = std::env::temp_dir().join(format!("mq-byte-overlay-{}", std::process::id()));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
fs::write(root.join("note.md"), "old text").unwrap();
|
||||
let mut ctx =
|
||||
HostContext::for_run(Some(&root.join("main.mq.md")), Default::default(), vec![]);
|
||||
let session = sandbox_fs::open(Some(root.to_str().unwrap()), &ctx).unwrap();
|
||||
let id = session["id"].as_str().unwrap().to_string();
|
||||
ctx.sandbox_session = Some(id.clone());
|
||||
legacy::text_patch(
|
||||
&ctx,
|
||||
&Value::Text("note.md".into()),
|
||||
&Value::Text("old".into()),
|
||||
&Value::Text("new".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("note.md")).unwrap(),
|
||||
"old text"
|
||||
);
|
||||
assert_eq!(
|
||||
legacy::read_text(&ctx, &Value::Text("note.md".into())).unwrap(),
|
||||
Value::Text("new text".into())
|
||||
);
|
||||
let mut args = Args::from([
|
||||
("path".into(), Value::Text("data.bin".into())),
|
||||
("data".into(), bytes_value(&[0, 255])),
|
||||
]);
|
||||
call(&mut ctx, HostFn::FsWriteBytes, &args).unwrap();
|
||||
args.insert("data".into(), bytes_value(&[128]));
|
||||
call(&mut ctx, HostFn::FsAppendBytes, &args).unwrap();
|
||||
legacy::copy_file(
|
||||
&ctx,
|
||||
&Value::Text("data.bin".into()),
|
||||
&Value::Text("copied.bin".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sandbox_fs::cow_read_bytes(&ctx, &root.join("copied.bin"))
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
[0, 255, 128]
|
||||
);
|
||||
assert!(!root.join("data.bin").exists());
|
||||
assert!(!root.join("copied.bin").exists());
|
||||
assert!(legacy::make_dirs(&ctx, &Value::Text("unsupported".into())).is_err());
|
||||
assert!(!root.join("unsupported").exists());
|
||||
sandbox_fs::discard(&id).unwrap();
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
//! Digest / HMAC host primitives for Mid M3 (`lib/hash`).
|
||||
|
||||
use crate::host::as_text;
|
||||
use hmac::{Hmac, Mac};
|
||||
use md5::Md5;
|
||||
use sha1::Sha1;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
|
||||
fn to_hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn sha256(text: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let mut h = Sha256::new();
|
||||
h.update(t.as_bytes());
|
||||
Ok(Value::Text(to_hex(&h.finalize())))
|
||||
}
|
||||
|
||||
pub fn sha1(text: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let mut h = Sha1::new();
|
||||
h.update(t.as_bytes());
|
||||
Ok(Value::Text(to_hex(&h.finalize())))
|
||||
}
|
||||
|
||||
pub fn md5(text: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let mut h = Md5::new();
|
||||
h.update(t.as_bytes());
|
||||
Ok(Value::Text(to_hex(&h.finalize())))
|
||||
}
|
||||
|
||||
pub fn hmac_sha256(key: &Value, text: &Value) -> Result<Value, String> {
|
||||
let k = as_text(key, "key")?;
|
||||
let t = as_text(text, "text")?;
|
||||
let mut mac =
|
||||
HmacSha256::new_from_slice(k.as_bytes()).map_err(|e| format!("hmac_sha256: {e}"))?;
|
||||
mac.update(t.as_bytes());
|
||||
Ok(Value::Text(to_hex(&mac.finalize().into_bytes())))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sha256_empty() {
|
||||
let v = sha256(&Value::Text("".into())).unwrap();
|
||||
assert_eq!(
|
||||
v,
|
||||
Value::Text(
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
//! HTML escape / unescape for Mid2 M8 (`lib/html`).
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
pub fn escape(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn unescape(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find('&') {
|
||||
out.push_str(&rest[..i]);
|
||||
rest = &rest[i..];
|
||||
if let Some(end) = rest.find(';') {
|
||||
let ent = &rest[..=end];
|
||||
let ch = match ent {
|
||||
"&" => Some('&'),
|
||||
"<" => Some('<'),
|
||||
">" => Some('>'),
|
||||
""" => Some('"'),
|
||||
"'" | "'" | "'" => Some('\''),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(c) = ch {
|
||||
out.push(c);
|
||||
rest = &rest[end + 1..];
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push('&');
|
||||
rest = &rest[1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let e = escape(&Value::Text(r#"a<b>&"c'"#.into())).unwrap();
|
||||
assert_eq!(
|
||||
e,
|
||||
Value::Text("a<b>&"c'".into())
|
||||
);
|
||||
assert_eq!(unescape(&e).unwrap(), Value::Text(r#"a<b>&"c'"#.into()));
|
||||
}
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
//! JSON host primitives + Value↔JSON mapping.
|
||||
//!
|
||||
//! Integer gate matches Lean \(V_{\mathsf{safe}}\) (`doc/design/v-safe-json.md`):
|
||||
//! JSON integers with `|n| > 2^53-1` refuse on encode and decode.
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
/// JavaScript `Number.MAX_SAFE_INTEGER` / Lean `ForeignJSON.maxSafe`.
|
||||
pub const MAX_SAFE_INT: i64 = 9_007_199_254_740_991; // 2^53 - 1
|
||||
|
||||
pub fn in_safe_int(n: i64) -> bool {
|
||||
(-MAX_SAFE_INT..=MAX_SAFE_INT).contains(&n)
|
||||
}
|
||||
|
||||
fn ood_int_err(n: impl std::fmt::Display) -> String {
|
||||
format!("json: integer outside V_safe (±(2^53-1)): {n}")
|
||||
}
|
||||
|
||||
/// The integer boundary is semantic, not a property of JSON spelling or the
|
||||
/// host's Int/Num tag. Exponent notation must not bypass it.
|
||||
fn checked_number(n: f64) -> Result<serde_json::Value, String> {
|
||||
if !n.is_finite() { return Err("json: non-finite number outside V_safe".into()); }
|
||||
if n.fract() == 0.0 && n.abs() > MAX_SAFE_INT as f64 { return Err(ood_int_err(n)); }
|
||||
Ok(serde_json::Value::Number(serde_json::Number::from_f64(n)
|
||||
.ok_or("json: non-finite number outside V_safe")?))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum DecodeError { Syntax(String), Domain(String) }
|
||||
|
||||
struct BoundaryValue(Value);
|
||||
impl<'de> serde::Deserialize<'de> for BoundaryValue {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
|
||||
struct BoundaryVisitor;
|
||||
impl<'de> serde::de::Visitor<'de> for BoundaryVisitor {
|
||||
type Value = BoundaryValue;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a boundary JSON value") }
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::None)) }
|
||||
fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Bool(v))) }
|
||||
fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Self::Value,E> {
|
||||
if !in_safe_int(n) { return Err(E::custom(ood_int_err(n))); }
|
||||
Ok(BoundaryValue(Value::Int(n)))
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Self::Value,E> {
|
||||
if n > MAX_SAFE_INT as u64 { return Err(E::custom(ood_int_err(n))); }
|
||||
Ok(BoundaryValue(Value::Int(n as i64)))
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, n: f64) -> Result<Self::Value,E> {
|
||||
checked_number(n).map_err(E::custom)?;
|
||||
Ok(BoundaryValue(Value::Num(n)))
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Text(v.into()))) }
|
||||
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Text(v))) }
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value,A::Error> {
|
||||
let mut xs = Vec::new();
|
||||
while let Some(BoundaryValue(v)) = seq.next_element()? { xs.push(v); }
|
||||
Ok(BoundaryValue(Value::List(xs)))
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value,A::Error> {
|
||||
use serde::de::Error;
|
||||
let mut fields = Vec::new();
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if !keys.insert(key.clone()) { return Err(A::Error::custom("json: duplicate object key outside V_safe")); }
|
||||
let BoundaryValue(v) = map.next_value()?;
|
||||
fields.push((key, v));
|
||||
}
|
||||
// Preserve the pre-existing JSON object's canonical key order.
|
||||
fields.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let value = Value::Map(fields);
|
||||
value_to_json(&value).map_err(A::Error::custom)?;
|
||||
Ok(BoundaryValue(value))
|
||||
}
|
||||
}
|
||||
de.deserialize_any(BoundaryVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode_text(text: &str) -> Result<Value, DecodeError> {
|
||||
use serde::Deserialize;
|
||||
let classify = |error: serde_json::Error| {
|
||||
let message = error.to_string();
|
||||
// serde_json categorizes its own numeric-overflow diagnostic as Syntax.
|
||||
// It is a domain refusal for a grammar-valid unbounded JSON number.
|
||||
// Match this trusted decoder diagnostic, never foreign program output.
|
||||
if message.starts_with("number out of range at line ") {
|
||||
return DecodeError::Domain(format!("json: number outside V_safe: {message}"));
|
||||
}
|
||||
match error.classify() {
|
||||
serde_json::error::Category::Data => DecodeError::Domain(message),
|
||||
_ => DecodeError::Syntax(message),
|
||||
}
|
||||
};
|
||||
let mut de = serde_json::Deserializer::from_str(text);
|
||||
let value = BoundaryValue::deserialize(&mut de).map_err(classify)?;
|
||||
de.end().map_err(classify)?;
|
||||
Ok(value.0)
|
||||
}
|
||||
|
||||
|
||||
/// The call protocol envelope is not a runtime column table. Validate each
|
||||
/// actual argument with BoundaryValue while keeping duplicate-key detection.
|
||||
pub(crate) fn decode_arguments(text: &str) -> Result<Vec<(String, Value)>, String> {
|
||||
use serde::Deserialize;
|
||||
struct Arguments(Vec<(String, Value)>);
|
||||
impl<'de> serde::Deserialize<'de> for Arguments {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self,D::Error> {
|
||||
struct Visitor;
|
||||
impl<'de> serde::de::Visitor<'de> for Visitor {
|
||||
type Value = Arguments;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a JSON object of named arguments")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Arguments,A::Error> {
|
||||
use serde::de::Error;
|
||||
let mut args = Vec::new();
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if !keys.insert(key.clone()) { return Err(A::Error::custom("duplicate argument name")); }
|
||||
let BoundaryValue(value) = map.next_value()?;
|
||||
args.push((key, value));
|
||||
}
|
||||
Ok(Arguments(args))
|
||||
}
|
||||
}
|
||||
de.deserialize_map(Visitor)
|
||||
}
|
||||
}
|
||||
let mut de = serde_json::Deserializer::from_str(text);
|
||||
let args = Arguments::deserialize(&mut de).map_err(|e| e.to_string())?;
|
||||
de.end().map_err(|e| e.to_string())?;
|
||||
Ok(args.0)
|
||||
}
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let s = match text {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json parse needs text".into()),
|
||||
};
|
||||
decode_text(s).map_err(|e| match e {
|
||||
DecodeError::Syntax(e) | DecodeError::Domain(e) => format!("json parse: {e}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stringify(value: &Value, indent: Option<&Value>) -> Result<Value, String> {
|
||||
let j = value_to_json(value)?;
|
||||
let pretty = match indent {
|
||||
None => false,
|
||||
Some(Value::Int(n)) => *n > 0,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::None) => false,
|
||||
Some(_) => return Err("json stringify indent must be int or bool".into()),
|
||||
};
|
||||
let s = if pretty {
|
||||
serde_json::to_string_pretty(&j).map_err(|e| format!("json stringify: {e}"))?
|
||||
} else {
|
||||
serde_json::to_string(&j).map_err(|e| format!("json stringify: {e}"))?
|
||||
};
|
||||
Ok(Value::Text(s))
|
||||
}
|
||||
|
||||
pub fn get(value: &Value, key: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json get key must be text".into()),
|
||||
};
|
||||
match value {
|
||||
Value::Map(entries) => Ok(entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None)),
|
||||
_ => Err("json get needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn keys(value: &Value) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::Map(entries) => Ok(Value::List(
|
||||
entries.iter().map(|(k, _)| Value::Text(k.clone())).collect(),
|
||||
)),
|
||||
_ => Err("json keys needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON-encode a text value including surrounding quotes (for building request bodies).
|
||||
pub fn quote(text: &Value) -> Result<Value, String> {
|
||||
let s = match text {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json quote needs text".into()),
|
||||
};
|
||||
serde_json::to_string(s)
|
||||
.map(Value::Text)
|
||||
.map_err(|e| format!("json quote: {e}"))
|
||||
}
|
||||
|
||||
pub(crate) fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
|
||||
Ok(match v {
|
||||
serde_json::Value::Null => Value::None,
|
||||
serde_json::Value::Bool(b) => Value::Bool(*b),
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
if !in_safe_int(i) {
|
||||
return Err(ood_int_err(i));
|
||||
}
|
||||
Value::Int(i)
|
||||
} else if let Some(u) = n.as_u64() {
|
||||
// Always > i64::MAX ⇒ outside V_safe; never coerce via f64/Text.
|
||||
return Err(ood_int_err(u));
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
// Host extension: non-integer JSON numbers → Num (not in Lean SafeVal).
|
||||
checked_number(f)?;
|
||||
Value::Num(f)
|
||||
} else {
|
||||
return Err(format!("json: unsupported number: {n}"));
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(s) => Value::Text(s.clone()),
|
||||
serde_json::Value::Array(xs) => {
|
||||
let mut out = Vec::with_capacity(xs.len());
|
||||
for x in xs {
|
||||
out.push(json_to_value(x)?);
|
||||
}
|
||||
Value::List(out)
|
||||
}
|
||||
serde_json::Value::Object(map) => {
|
||||
let mut entries = Vec::with_capacity(map.len());
|
||||
for (k, v) in map {
|
||||
entries.push((k.clone(), json_to_value(v)?));
|
||||
}
|
||||
Value::Map(entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
Ok(match v {
|
||||
Value::None => serde_json::Value::Null,
|
||||
Value::Bool(b) => serde_json::Value::Bool(*b),
|
||||
Value::Int(n) => {
|
||||
if !in_safe_int(*n) {
|
||||
return Err(ood_int_err(*n));
|
||||
}
|
||||
serde_json::Value::Number((*n).into())
|
||||
}
|
||||
Value::Num(n) => checked_number(*n)?,
|
||||
Value::Text(s) => serde_json::Value::String(s.clone()),
|
||||
Value::List(xs) => {
|
||||
let mut arr = Vec::with_capacity(xs.len());
|
||||
for x in xs {
|
||||
arr.push(value_to_json(x)?);
|
||||
}
|
||||
serde_json::Value::Array(arr)
|
||||
}
|
||||
Value::Map(entries) => {
|
||||
// Column-table maps (all fields lists): refuse unequal list lengths.
|
||||
let list_lens: Vec<usize> = entries
|
||||
.iter()
|
||||
.filter_map(|(_, v)| match v {
|
||||
Value::List(xs) => Some(xs.len()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if list_lens.len() == entries.len() && list_lens.len() >= 2 {
|
||||
let n0 = list_lens[0];
|
||||
if list_lens.iter().any(|&n| n != n0) {
|
||||
return Err(
|
||||
"json: table column arity mismatch (unequal list lengths)".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut map = serde_json::Map::new();
|
||||
for (k, v) in entries {
|
||||
map.insert(k.clone(), value_to_json(v)?);
|
||||
}
|
||||
serde_json::Value::Object(map)
|
||||
}
|
||||
Value::Formula(e) => match e {
|
||||
crate::formula::Expr::Matrix { rows, .. } => {
|
||||
let mut arr = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let mut cells = Vec::with_capacity(row.len());
|
||||
for &n in row {
|
||||
cells.push(
|
||||
serde_json::Number::from_f64(n)
|
||||
.map(serde_json::Value::Number)
|
||||
.ok_or_else(|| "json: non-finite number outside V_safe".to_string())?,
|
||||
);
|
||||
}
|
||||
arr.push(serde_json::Value::Array(cells));
|
||||
}
|
||||
serde_json::Value::Array(arr)
|
||||
}
|
||||
other => {
|
||||
let s = crate::formula::simplify(other);
|
||||
if let crate::formula::Expr::Num(n) = s {
|
||||
serde_json::Number::from_f64(n)
|
||||
.map(serde_json::Value::Number)
|
||||
.ok_or_else(|| "json: non-finite number outside V_safe".to_string())?
|
||||
} else {
|
||||
serde_json::Value::String(e.as_display())
|
||||
}
|
||||
}
|
||||
},
|
||||
Value::Code(c) => serde_json::Value::String(c.source.clone()),
|
||||
Value::Secret(_) => serde_json::Value::String("<secret>".into()),
|
||||
Value::Handle(_) => {
|
||||
return Err("json: session handle cannot be serialized".into());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quote_escapes_text() {
|
||||
let q = quote(&Value::Text("a\"b".into())).unwrap();
|
||||
assert_eq!(q, Value::Text("\"a\\\"b\"".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_max_safe() {
|
||||
for n in [MAX_SAFE_INT, -MAX_SAFE_INT, 0_i64, 1, -1] {
|
||||
let j = value_to_json(&Value::Int(n)).unwrap();
|
||||
let v = json_to_value(&j).unwrap();
|
||||
assert_eq!(v, Value::Int(n));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_ood_encode() {
|
||||
for n in [
|
||||
MAX_SAFE_INT + 1,
|
||||
-MAX_SAFE_INT - 1,
|
||||
1_i64 << 53, // 2^53
|
||||
1_i64 << 60, // 2^60
|
||||
(1_i64 << 60) + 1, // 2^60+1
|
||||
] {
|
||||
let err = value_to_json(&Value::Int(n)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("outside V_safe"),
|
||||
"encode {n}: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_ood_decode() {
|
||||
for n in [
|
||||
MAX_SAFE_INT + 1,
|
||||
-MAX_SAFE_INT - 1,
|
||||
1_i64 << 53,
|
||||
1_i64 << 60,
|
||||
(1_i64 << 60) + 1,
|
||||
] {
|
||||
let raw = format!("{n}");
|
||||
let j: serde_json::Value = serde_json::from_str(&raw).unwrap();
|
||||
let err = json_to_value(&j).unwrap_err();
|
||||
assert!(
|
||||
err.contains("outside V_safe"),
|
||||
"decode {n}: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_nested_ood() {
|
||||
let j: serde_json::Value =
|
||||
serde_json::from_str("{\"a\":[1152921504606846977]}").unwrap();
|
||||
let err = json_to_value(&j).unwrap_err();
|
||||
assert!(err.contains("outside V_safe"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimal_string_ok() {
|
||||
let j = serde_json::Value::String("1152921504606846977".into());
|
||||
assert_eq!(
|
||||
json_to_value(&j).unwrap(),
|
||||
Value::Text("1152921504606846977".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_host_extension_ok() {
|
||||
let j: serde_json::Value = serde_json::from_str("1.5").unwrap();
|
||||
match json_to_value(&j).unwrap() {
|
||||
Value::Num(f) => assert!((f - 1.5).abs() < 1e-12),
|
||||
other => panic!("expected Num, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_u64_above_i64_max() {
|
||||
// 2^63 as JSON integer: as_i64 fails, as_u64 succeeds.
|
||||
let j: serde_json::Value = serde_json::from_str("9223372036854775808").unwrap();
|
||||
let err = json_to_value(&j).unwrap_err();
|
||||
assert!(err.contains("outside V_safe"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_session_handle_encode() {
|
||||
let err = value_to_json(&Value::Handle("s1".into())).unwrap_err();
|
||||
assert!(
|
||||
err.contains("session handle cannot be serialized"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuse_unequal_column_table_encode() {
|
||||
let ragged = Value::Map(vec![
|
||||
("a".into(), Value::List(vec![Value::Int(1), Value::Int(2)])),
|
||||
("b".into(), Value::List(vec![Value::Int(3)])),
|
||||
]);
|
||||
let err = value_to_json(&ragged).unwrap_err();
|
||||
assert!(err.contains("arity mismatch"), "{err}");
|
||||
}
|
||||
#[test]
|
||||
fn refuse_nonfinite_in_nested_payloads() {
|
||||
for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
for v in [Value::Num(n), Value::List(vec![Value::Num(n)]),
|
||||
Value::Map(vec![("x".into(), Value::Num(n))])] {
|
||||
assert!(value_to_json(&v).unwrap_err().contains("outside V_safe"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exponent_and_float_tags_cannot_bypass_integer_domain() {
|
||||
for text in ["9007199254740992.0", "9.007199254740992e15", "1e100", "1e9999", "-9.007199254740992e15"] {
|
||||
assert!(parse(&Value::Text(text.into())).unwrap_err().contains("outside V_safe"), "{text}");
|
||||
}
|
||||
for n in [9_007_199_254_740_992.0, -9_007_199_254_740_992.0, 1e100] {
|
||||
assert!(value_to_json(&Value::List(vec![Value::Num(n)])).unwrap_err().contains("outside V_safe"));
|
||||
}
|
||||
for text in ["1.5", "-0.0", "9.007199254740991e15"] {
|
||||
assert!(parse(&Value::Text(text.into())).is_ok(), "valid extension {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_decode_refuses_duplicate_keys_and_ragged_columns() {
|
||||
for text in [r#"{"a":1,"a":2}"#, r#"[{"x":null,"x":true}]"#,
|
||||
r#"{"a":[1],"b":[2,3]}"#] {
|
||||
assert!(matches!(decode_text(text), Err(DecodeError::Domain(_))), "{text}");
|
||||
}
|
||||
for text in [r#"{"a":[1],"b":"metadata"}"#, r#"{"a":[],"b":[]}"#,
|
||||
r#"{"__proto__":{"safe":true},"constructor":"data"}"#] {
|
||||
assert!(decode_text(text).is_ok(), "{text}");
|
||||
}
|
||||
assert!(matches!(decode_text("not JSON"), Err(DecodeError::Syntax(_))));
|
||||
}
|
||||
|
||||
}
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
//! Log level gate for Mid M6 (`lib/log`).
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Level {
|
||||
Debug = 10,
|
||||
Info = 20,
|
||||
Warn = 30,
|
||||
Error = 40,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
pub fn parse(s: &str) -> Result<Self, String> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"debug" | "调试" => Ok(Self::Debug),
|
||||
"info" | "信息" => Ok(Self::Info),
|
||||
"warn" | "warning" | "警告" => Ok(Self::Warn),
|
||||
"error" | "错误" => Ok(Self::Error),
|
||||
_ => Err(format!("log: unknown level {s:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Debug => "DEBUG",
|
||||
Self::Info => "INFO",
|
||||
Self::Warn => "WARN",
|
||||
Self::Error => "ERROR",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn set_level(ctx: &mut HostContext, level: &Value) -> Result<Value, String> {
|
||||
let s = as_text(level, "level")?;
|
||||
ctx.log_min_level = Level::parse(s)? as u8;
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// Return a ready-to-print line, or `None` if filtered out.
|
||||
/// Optional `fields` map is appended as `key=value` pairs (stable map order).
|
||||
pub fn line(
|
||||
ctx: &HostContext,
|
||||
level: &Value,
|
||||
text: &Value,
|
||||
fields: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let lvl = Level::parse(as_text(level, "level")?)?;
|
||||
let msg = as_text(text, "text")?;
|
||||
if (lvl as u8) < ctx.log_min_level {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
let mut out = format!("{} {}", lvl.label(), msg);
|
||||
match fields {
|
||||
None | Some(Value::None) => {}
|
||||
Some(Value::Map(entries)) => {
|
||||
for (k, v) in entries {
|
||||
out.push(' ');
|
||||
out.push_str(k);
|
||||
out.push('=');
|
||||
out.push_str(&v.as_display());
|
||||
}
|
||||
}
|
||||
Some(_) => return Err("log: fields must be a map".into()),
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn filters_debug() {
|
||||
let mut ctx = HostContext::default();
|
||||
assert_eq!(ctx.log_min_level, Level::Info as u8);
|
||||
let filtered = line(
|
||||
&ctx,
|
||||
&Value::Text("debug".into()),
|
||||
&Value::Text("x".into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(filtered, Value::None);
|
||||
set_level(&mut ctx, &Value::Text("debug".into())).unwrap();
|
||||
let shown = line(
|
||||
&ctx,
|
||||
&Value::Text("debug".into()),
|
||||
&Value::Text("x".into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(shown, Value::Text("DEBUG x".into()));
|
||||
let with = line(
|
||||
&ctx,
|
||||
&Value::Text("info".into()),
|
||||
&Value::Text("hi".into()),
|
||||
Some(&Value::Map(vec![
|
||||
("user".into(), Value::Text("a".into())),
|
||||
("n".into(), Value::Int(1)),
|
||||
])),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(with, Value::Text("INFO hi user=a n=1".into()));
|
||||
}
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
//! Host entry points for math / formula / random / plot.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::formula::{self, Expr};
|
||||
use crate::host::fs;
|
||||
use crate::host::{HostContext, PlotArtifact};
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn as_f64(v: &Value) -> Result<f64, String> {
|
||||
match v {
|
||||
Value::Num(n) => Ok(*n),
|
||||
Value::Int(n) => Ok(*n as f64),
|
||||
Value::Text(s) => s
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.map_err(|_| format!("cannot convert to num: {s:?}")),
|
||||
_ => Err("expected num (or int/text)".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt<'a>(v: Option<&'a Value>) -> Option<&'a Value> {
|
||||
match v {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(v),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_text(v: &Value) -> Result<&str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err("expected text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_bool(v: &Value) -> bool {
|
||||
v.truthy()
|
||||
}
|
||||
|
||||
pub fn formula_from_value(v: &Value) -> Result<Expr, String> {
|
||||
match v {
|
||||
Value::Formula(e) => Ok(e.clone()),
|
||||
Value::Text(s) => formula::parse(s),
|
||||
Value::Num(n) => Ok(Expr::Num(*n)),
|
||||
Value::Int(n) => Ok(Expr::Num(*n as f64)),
|
||||
_ => Err("expected formula or expression text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn num_val(n: f64) -> Value {
|
||||
Value::Num(n)
|
||||
}
|
||||
|
||||
pub fn pi() -> Result<Value, String> {
|
||||
Ok(num_val(std::f64::consts::PI))
|
||||
}
|
||||
|
||||
pub fn e_const() -> Result<Value, String> {
|
||||
Ok(num_val(std::f64::consts::E))
|
||||
}
|
||||
|
||||
pub fn to_num(v: &Value) -> Result<Value, String> {
|
||||
Ok(num_val(as_f64(v)?))
|
||||
}
|
||||
|
||||
pub fn unary_num(op: &str, x: &Value) -> Result<Value, String> {
|
||||
let x = as_f64(x)?;
|
||||
let y = match op {
|
||||
"neg" => -x,
|
||||
"sin" => x.sin(),
|
||||
"cos" => x.cos(),
|
||||
"tan" => x.tan(),
|
||||
"asin" => x.asin(),
|
||||
"acos" => x.acos(),
|
||||
"atan" => x.atan(),
|
||||
"sqrt" => x.sqrt(),
|
||||
"abs" => x.abs(),
|
||||
"ln" | "log" => x.ln(),
|
||||
"exp" => x.exp(),
|
||||
"floor" => x.floor(),
|
||||
"ceil" => x.ceil(),
|
||||
_ => return Err(format!("unknown unary math op `{op}`")),
|
||||
};
|
||||
Ok(num_val(y))
|
||||
}
|
||||
|
||||
pub fn binary_num(op: &str, a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let a = as_f64(a)?;
|
||||
let b = as_f64(b)?;
|
||||
let y = match op {
|
||||
"add" => a + b,
|
||||
"sub" => a - b,
|
||||
"mul" => a * b,
|
||||
"div" => {
|
||||
if b == 0.0 {
|
||||
return Err("division by zero".into());
|
||||
}
|
||||
a / b
|
||||
}
|
||||
"pow" => a.powf(b),
|
||||
"min" => a.min(b),
|
||||
"max" => a.max(b),
|
||||
_ => return Err(format!("unknown binary math op `{op}`")),
|
||||
};
|
||||
Ok(num_val(y))
|
||||
}
|
||||
|
||||
pub fn seed(ctx: &mut HostContext, v: &Value) -> Result<Value, String> {
|
||||
let n = as_f64(v)? as u64;
|
||||
ctx.rng = n ^ 0xA5A5_A5A5_A5A5_A5A5;
|
||||
if ctx.rng == 0 {
|
||||
ctx.rng = 0xC0FFEE;
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn random(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Ok(num_val(ctx.next_f64()))
|
||||
}
|
||||
|
||||
pub fn random_int(ctx: &mut HostContext, lo: &Value, hi: &Value) -> Result<Value, String> {
|
||||
let lo = as_f64(lo)? as i64;
|
||||
let hi = as_f64(hi)? as i64;
|
||||
if hi < lo {
|
||||
return Err("random_int: max < min".into());
|
||||
}
|
||||
let span = (hi - lo + 1) as u64;
|
||||
let r = ctx.next_u64() % span;
|
||||
Ok(Value::Int(lo + r as i64))
|
||||
}
|
||||
|
||||
pub fn formula_parse(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text)?;
|
||||
Ok(Value::Formula(formula::parse(s)?))
|
||||
}
|
||||
|
||||
pub fn simplify(v: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Formula(formula::simplify(&formula_from_value(v)?)))
|
||||
}
|
||||
|
||||
pub fn expand(v: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Formula(formula::expand(&formula_from_value(v)?)))
|
||||
}
|
||||
|
||||
pub fn diff(formula: &Value, var: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
Ok(Value::Formula(formula::diff(&e, var)))
|
||||
}
|
||||
|
||||
pub fn subs(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let val = formula_from_value(value)?;
|
||||
let out = formula::subs(&e, var, &val);
|
||||
if let Expr::Num(n) = out {
|
||||
Ok(num_val(n))
|
||||
} else {
|
||||
Ok(Value::Formula(out))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_at(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let x = as_f64(value)?;
|
||||
let mut env = HashMap::new();
|
||||
env.insert(var.to_string(), x);
|
||||
Ok(num_val(formula::eval_f64(&e, &env)?))
|
||||
}
|
||||
|
||||
pub fn solve(
|
||||
formula: &Value,
|
||||
var: &Value,
|
||||
min: Option<&Value>,
|
||||
max: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let e = formula_from_value(formula)?;
|
||||
let var = as_text(var)?;
|
||||
let xmin = opt(min).map(as_f64).transpose()?.unwrap_or(-100.0);
|
||||
let xmax = opt(max).map(as_f64).transpose()?.unwrap_or(100.0);
|
||||
let roots = formula::solve(&e, var, xmin, xmax)?;
|
||||
Ok(Value::List(roots.into_iter().map(num_val).collect()))
|
||||
}
|
||||
|
||||
fn maybe_write_plot(
|
||||
ctx: &mut HostContext,
|
||||
path: Option<&Value>,
|
||||
svg: String,
|
||||
) -> Result<Value, String> {
|
||||
let path_s = match opt(path) {
|
||||
Some(v) => Some(as_text(v)?.to_string()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(ref p) = path_s {
|
||||
fs::write_text(ctx, &Value::Text(p.clone()), &Value::Text(svg.clone()))?;
|
||||
}
|
||||
ctx.plots.push(PlotArtifact {
|
||||
path: path_s,
|
||||
svg: svg.clone(),
|
||||
});
|
||||
Ok(Value::Text(svg))
|
||||
}
|
||||
|
||||
fn plot_style(grid: Option<&Value>) -> Result<formula::PlotStyle, String> {
|
||||
let grid = match opt(grid) {
|
||||
None => true,
|
||||
Some(v) => as_bool(v),
|
||||
};
|
||||
Ok(formula::PlotStyle { grid })
|
||||
}
|
||||
|
||||
pub fn plot(
|
||||
ctx: &mut HostContext,
|
||||
formula: &Value,
|
||||
var: &Value,
|
||||
min: &Value,
|
||||
max: &Value,
|
||||
steps: Option<&Value>,
|
||||
path: Option<&Value>,
|
||||
derivative: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let mut e = formula_from_value(formula)?;
|
||||
let var_s = as_text(var)?;
|
||||
if opt(derivative).map(as_bool).unwrap_or(false) {
|
||||
e = formula::diff(&e, var_s);
|
||||
}
|
||||
let xmin = as_f64(min)?;
|
||||
let xmax = as_f64(max)?;
|
||||
let steps = match opt(steps) {
|
||||
Some(v) => as_f64(v)? as usize,
|
||||
None => 200,
|
||||
};
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_function_svg(&e, var_s, xmin, xmax, steps, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
|
||||
pub fn plot_points(
|
||||
ctx: &mut HostContext,
|
||||
xs: &Value,
|
||||
ys: &Value,
|
||||
path: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let xs = match xs {
|
||||
Value::List(xs) => xs
|
||||
.iter()
|
||||
.map(as_f64)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
_ => return Err("plot_points needs list xs".into()),
|
||||
};
|
||||
let ys = match ys {
|
||||
Value::List(ys) => ys
|
||||
.iter()
|
||||
.map(as_f64)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
_ => return Err("plot_points needs list ys".into()),
|
||||
};
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_points_svg(&xs, &ys, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
|
||||
pub fn plot_conic(
|
||||
ctx: &mut HostContext,
|
||||
kind: &Value,
|
||||
a: &Value,
|
||||
b: Option<&Value>,
|
||||
h: Option<&Value>,
|
||||
k: Option<&Value>,
|
||||
path: Option<&Value>,
|
||||
grid: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let kind = as_text(kind)?;
|
||||
let a = as_f64(a)?;
|
||||
let b = opt(b).map(as_f64).transpose()?.unwrap_or(a);
|
||||
let h = opt(h).map(as_f64).transpose()?.unwrap_or(0.0);
|
||||
let k = opt(k).map(as_f64).transpose()?.unwrap_or(0.0);
|
||||
let style = plot_style(grid)?;
|
||||
let svg = formula::plot_conic_svg(kind, a, b, h, k, style)?;
|
||||
maybe_write_plot(ctx, path, svg)
|
||||
}
|
||||
-363
@@ -1,363 +0,0 @@
|
||||
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, `math`, …).
|
||||
//!
|
||||
//! User docs should import L1 wrappers; these `host_*` names are the Rust surface.
|
||||
//! Capabilities default **on** (importing a lib means you intend to use it).
|
||||
//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only.
|
||||
|
||||
pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
mod cli;
|
||||
mod csv;
|
||||
mod datetime;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign_doc;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign_session;
|
||||
mod fs;
|
||||
mod hash;
|
||||
mod html_ops;
|
||||
pub(crate) mod json;
|
||||
mod log;
|
||||
pub(crate) mod oracle;
|
||||
pub mod math;
|
||||
mod net;
|
||||
mod path;
|
||||
mod re;
|
||||
mod secrets;
|
||||
mod stats;
|
||||
mod text_ops;
|
||||
mod time;
|
||||
pub(crate) mod toml_ops;
|
||||
mod url_ops;
|
||||
mod uuid_ops;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
#[path = "plugin_stub.rs"]
|
||||
pub mod plugin;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod subtask;
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
#[path = "subtask_stub.rs"]
|
||||
pub mod subtask;
|
||||
pub mod sandbox_fs;
|
||||
mod sys;
|
||||
pub mod writeback;
|
||||
|
||||
pub use dispatch::{call_host, HostFn};
|
||||
|
||||
/// Shared `text` argument extraction for host modules.
|
||||
///
|
||||
/// `<TAB>` slimming: this used to be copy-pasted in 17 host modules with two
|
||||
/// different wordings; one implementation keeps messages consistent.
|
||||
pub fn as_text<'a>(v: &'a crate::value::Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
crate::value::Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} needs text")),
|
||||
}
|
||||
}
|
||||
pub use fs::path_under_root;
|
||||
pub use plugin::PluginState;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Host capability flags. Default: all enabled.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct HostCaps {
|
||||
pub fs_write: bool,
|
||||
pub exec: bool,
|
||||
pub net: bool,
|
||||
pub plugin: bool,
|
||||
}
|
||||
|
||||
impl Default for HostCaps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fs_write: true,
|
||||
exec: true,
|
||||
net: true,
|
||||
plugin: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG plot produced during a run (for CLI auto-write / view embed).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlotArtifact {
|
||||
/// User-requested path, if any.
|
||||
pub path: Option<String>,
|
||||
pub svg: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HostContext {
|
||||
pub caps: HostCaps,
|
||||
pub fs_root: Option<PathBuf>,
|
||||
pub cwd: PathBuf,
|
||||
pub argv: Vec<String>,
|
||||
/// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export).
|
||||
pub soft_side_effects: bool,
|
||||
pub sleep_limit_ms: Option<u64>,
|
||||
/// LCG state for `random` / `random_int`.
|
||||
pub rng: u64,
|
||||
pub plots: Vec<PlotArtifact>,
|
||||
pub oracle_observations: Vec<crate::value::Value>,
|
||||
/// lang → interpreter argv (from `set_cmd`).
|
||||
pub foreign_cmds: HashMap<String, Vec<String>>,
|
||||
/// Process-local language registrations (`register` / `set_cmd`).
|
||||
pub foreign_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime.
|
||||
pub foreign_config_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// Whether project config has been discovered/loaded.
|
||||
pub foreign_config_loaded: bool,
|
||||
/// Persistent foreign kernels (`session_open`).
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_sessions: HashMap<String, foreign_session::Session>,
|
||||
/// Monotonic session id counter.
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_session_seq: u64,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_protocol_steps: Vec<foreign_session::ProtocolStep>,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_replay_expected: Option<foreign_session::validation::ReplayCursor>,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_replay_divergence: Option<String>,
|
||||
/// Loaded native plugins (ABI v1/v2).
|
||||
pub plugins: PluginState,
|
||||
/// Entry `.mq.md` source text (for ABI host_query / context injection).
|
||||
pub entry_source: Option<String>,
|
||||
pub entry_path: Option<PathBuf>,
|
||||
/// Active function names (outer → inner) for call-site injection.
|
||||
pub call_stack: Vec<String>,
|
||||
/// Last statement line (updated by interpreters for call-site queries).
|
||||
pub current_line: u32,
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// Bound Artifact Metadata from the entry `.mq.md` (Phase 1 Binding).
|
||||
pub entry_metadata: Vec<(String, crate::value::Value)>,
|
||||
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
|
||||
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
|
||||
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub subtask_seq: u64,
|
||||
/// Minimum log level (`lib/log`); default Info (20). See `host::log::Level`.
|
||||
pub log_min_level: u8,
|
||||
/// Active `ext/ai/sandbox` CoW session id (nested `sandbox_run`).
|
||||
pub sandbox_session: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for HostContext {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
caps: HostCaps::default(),
|
||||
fs_root: None,
|
||||
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
argv: Vec::new(),
|
||||
soft_side_effects: false,
|
||||
sleep_limit_ms: Some(30_000),
|
||||
rng: 0xC0FF_EE42_CAFE_BABE,
|
||||
plots: Vec::new(),
|
||||
oracle_observations: Vec::new(),
|
||||
foreign_cmds: HashMap::new(),
|
||||
foreign_specs: HashMap::new(),
|
||||
foreign_config_specs: HashMap::new(),
|
||||
foreign_config_loaded: false,
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_sessions: HashMap::new(),
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_session_seq: 0,
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_protocol_steps: Vec::new(),
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_replay_expected: None,
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_replay_divergence: None,
|
||||
plugins: PluginState::default(),
|
||||
entry_source: None,
|
||||
entry_path: None,
|
||||
call_stack: Vec::new(),
|
||||
current_line: 1,
|
||||
call_site_lines: Vec::new(),
|
||||
entry_metadata: Vec::new(),
|
||||
subtasks: HashMap::new(),
|
||||
subtask_seq: 0,
|
||||
log_min_level: 20, // Info
|
||||
sandbox_session: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostContext {
|
||||
fn drop(&mut self) {
|
||||
subtask::kill_all(self);
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_session::shutdown(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl HostContext {
|
||||
pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec<String>) -> Self {
|
||||
let mut ctx = Self::default();
|
||||
ctx.caps = caps;
|
||||
ctx.argv = argv;
|
||||
if let Some(p) = path {
|
||||
if let Some(parent) = p.parent() {
|
||||
let parent = if parent.as_os_str().is_empty() {
|
||||
PathBuf::from(".")
|
||||
} else {
|
||||
parent.to_path_buf()
|
||||
};
|
||||
ctx.cwd = parent.clone();
|
||||
ctx.fs_root = Some(parent);
|
||||
}
|
||||
}
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Capture stdout / view / export: soft exit + sleep clamp; same caps as CLI by default.
|
||||
pub fn for_capture(path: Option<&Path>, caps: HostCaps) -> Self {
|
||||
let mut ctx = Self::for_run(path, caps, Vec::new());
|
||||
ctx.soft_side_effects = true;
|
||||
ctx.sleep_limit_ms = Some(0);
|
||||
ctx
|
||||
}
|
||||
|
||||
pub fn allow_fs_write(&self) -> bool {
|
||||
self.caps.fs_write
|
||||
}
|
||||
|
||||
pub fn allow_exec(&self) -> bool {
|
||||
self.caps.exec
|
||||
}
|
||||
|
||||
pub fn allow_net(&self) -> bool {
|
||||
self.caps.net
|
||||
}
|
||||
|
||||
pub fn push_call_site_line(&mut self, line: u32) {
|
||||
self.call_site_lines.push(line);
|
||||
}
|
||||
|
||||
pub fn pop_call_site_line(&mut self) {
|
||||
self.call_site_lines.pop();
|
||||
}
|
||||
|
||||
pub fn allow_plugin(&self) -> bool {
|
||||
self.caps.plugin
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
// SplitMix64-ish LCG step
|
||||
self.rng = self
|
||||
.rng
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1);
|
||||
let mut z = self.rng;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
pub fn next_f64(&mut self) -> f64 {
|
||||
let x = self.next_u64() >> 11;
|
||||
(x as f64) / ((1u64 << 53) as f64)
|
||||
}
|
||||
|
||||
pub fn resolve_path(&self, rel: &str) -> Result<PathBuf, String> {
|
||||
let p = Path::new(rel);
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
self.cwd.join(p)
|
||||
};
|
||||
if let Some(root) = &self.fs_root {
|
||||
let abs = if abs.is_absolute() { abs } else {
|
||||
std::env::current_dir().map_err(|e|e.to_string())?.join(abs)
|
||||
};
|
||||
let root = root.canonicalize().map_err(|e| format!("filesystem root: {e}"))?;
|
||||
// Normalize before checking, including destinations that do not exist yet.
|
||||
let mut lexical = PathBuf::new();
|
||||
for component in abs.components() {
|
||||
match component {
|
||||
std::path::Component::CurDir => {},
|
||||
std::path::Component::ParentDir => { lexical.pop(); },
|
||||
component => lexical.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
if !lexical.is_absolute() {
|
||||
lexical = std::env::current_dir().map_err(|e| e.to_string())?.join(lexical);
|
||||
}
|
||||
if !lexical.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
// The nearest existing ancestor must also be inside root: a symlink
|
||||
// cannot authorize writes through a not-yet-existing descendant.
|
||||
let mut ancestor = lexical.as_path();
|
||||
loop {
|
||||
match ancestor.canonicalize() {
|
||||
Ok(real) => {
|
||||
if !real.starts_with(&root) {
|
||||
return Err(format!("path escapes sandbox root: {}", abs.display()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
if ancestor.symlink_metadata().is_ok() {
|
||||
return Err(format!("unresolvable symlink: {}", ancestor.display()));
|
||||
}
|
||||
ancestor = ancestor.parent().ok_or_else(|| "invalid file path".to_string())?;
|
||||
}
|
||||
Err(e) => return Err(format!("resolve path {}: {e}", abs.display())),
|
||||
}
|
||||
}
|
||||
return Ok(lexical);
|
||||
}
|
||||
Ok(abs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write auto-named plot files for CLI runs when `path` was omitted.
|
||||
pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> Result<(), String> {
|
||||
let mut auto_i = 0usize;
|
||||
for plot in plots {
|
||||
if plot.path.is_some() {
|
||||
continue;
|
||||
}
|
||||
auto_i += 1;
|
||||
let stem = source_path
|
||||
.and_then(|p| p.file_stem())
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("out");
|
||||
let stem = stem.trim_end_matches(".mq");
|
||||
let name = format!("{stem}-plot-{auto_i}.svg");
|
||||
let dir = source_path
|
||||
.and_then(|p| p.parent())
|
||||
.unwrap_or_else(|| Path::new("."));
|
||||
let dest = dir.join(&name);
|
||||
std::fs::write(&dest, plot.svg.as_bytes())
|
||||
.map_err(|e| format!("failed to write plot {}: {e}", dest.display()))?;
|
||||
println!("plot: {}", dest.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
mod collection_ops;
|
||||
|
||||
mod result;
|
||||
|
||||
mod fs_ops;
|
||||
|
||||
mod document;
|
||||
|
||||
mod net_ops;
|
||||
|
||||
mod data_ops;
|
||||
|
||||
mod task_ops;
|
||||
|
||||
mod archive;
|
||||
-1076
File diff suppressed because it is too large.
Load diff
@@ -1,201 +0,0 @@
|
||||
//! Configurable bounded HTTP with one recoverable Result envelope.
|
||||
#[cfg(feature = "net-host")]
|
||||
use super::as_text;
|
||||
use super::result;
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "net-host")]
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
time::Duration,
|
||||
};
|
||||
type Args = HashMap<String, Value>;
|
||||
#[cfg(feature = "net-host")]
|
||||
fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
#[cfg(feature = "net-host")]
|
||||
let answer = request(ctx, id, b);
|
||||
#[cfg(not(feature = "net-host"))]
|
||||
let answer = {
|
||||
let _ = (ctx, id, b);
|
||||
Err("HTTP unavailable in this build".into())
|
||||
};
|
||||
Ok(result::capture(
|
||||
if id == HostFn::HttpDownload {
|
||||
"net.download"
|
||||
} else {
|
||||
"net.request"
|
||||
},
|
||||
answer,
|
||||
))
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn integer(b: &Args, k: &str, max: u64) -> Result<u64, String> {
|
||||
match arg(b, k)? {
|
||||
Value::Int(n) if *n > 0 && (*n as u64) <= max => Ok(*n as u64),
|
||||
_ => Err(format!("{k} must be 1..{max}")),
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "net-host")]
|
||||
fn request(ctx: &HostContext, id: HostFn, b: &Args) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("network denied by host policy".into());
|
||||
}
|
||||
let url = as_text(arg(b, "url")?, "url")?;
|
||||
if !(url.starts_with("https://") || url.starts_with("http://")) {
|
||||
return Err("url must use http/https".into());
|
||||
}
|
||||
let timeout = Duration::from_millis(integer(b, "timeout_ms", 600000)?);
|
||||
let max = integer(b, "max_bytes", 1024 * 1024 * 1024)?;
|
||||
let method = if matches!(id, HostFn::HttpDownload | HostFn::HttpGetResult) {
|
||||
"GET"
|
||||
} else {
|
||||
as_text(arg(b, "method")?, "method")?
|
||||
};
|
||||
if !matches!(
|
||||
method,
|
||||
"GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"
|
||||
) {
|
||||
return Err("unsupported method".into());
|
||||
}
|
||||
// Reject invalid output settings and destinations before any HTTP exchange.
|
||||
let destination = if id == HostFn::HttpDownload {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("filesystem write denied by host policy".into());
|
||||
}
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("unsupported: stream download in CoW sandbox".into());
|
||||
}
|
||||
let path = ctx.resolve_path(as_text(arg(b, "path")?, "path")?)?;
|
||||
if path.is_dir() {
|
||||
return Err("invalid_argument: download destination is a directory".into());
|
||||
}
|
||||
Some(path)
|
||||
} else {
|
||||
if max > 64 * 1024 * 1024 {
|
||||
return Err(
|
||||
"resource_limit: in-memory response limit exceeds 64 MiB; use download".into(),
|
||||
);
|
||||
}
|
||||
if !matches!(as_text(arg(b, "response")?, "response")?, "text" | "bytes") {
|
||||
return Err("invalid_argument: response must be text or bytes".into());
|
||||
}
|
||||
None
|
||||
};
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(timeout)
|
||||
.timeout_connect(timeout)
|
||||
.timeout_read(timeout)
|
||||
.timeout_write(timeout)
|
||||
.build();
|
||||
let mut request = agent.request(method, url).set("User-Agent", "marqdo");
|
||||
if let Some(Value::Map(headers)) = b.get("headers") {
|
||||
for (k, v) in headers {
|
||||
request = request.set(k, as_text(v, "header value")?)
|
||||
}
|
||||
} else if !matches!(b.get("headers"), None | Some(Value::None)) {
|
||||
return Err("headers must be map or None".into());
|
||||
}
|
||||
let exchange = match b.get("body") {
|
||||
None | Some(Value::None) => request.call(),
|
||||
Some(Value::Text(text)) => request.send_bytes(text.as_bytes()),
|
||||
Some(v) => request.send_bytes(&super::fs_ops::bytes(v)?),
|
||||
};
|
||||
let response = match exchange {
|
||||
Ok(r) => r,
|
||||
Err(ureq::Error::Status(_, r)) => r,
|
||||
Err(e) => return Err(format!("transport_error: {e}")),
|
||||
};
|
||||
let status = response.status();
|
||||
let mut headers = Vec::new();
|
||||
for name in response.headers_names() {
|
||||
let values = response
|
||||
.all(&name)
|
||||
.into_iter()
|
||||
.map(|v| Value::Text(v.into()))
|
||||
.collect();
|
||||
headers.push(Value::Map(vec![
|
||||
("name".into(), Value::Text(name.to_ascii_lowercase())),
|
||||
("values".into(), Value::List(values)),
|
||||
]));
|
||||
}
|
||||
let mut reader = response.into_reader();
|
||||
if id == HostFn::HttpDownload {
|
||||
if !(200..300).contains(&status) {
|
||||
return Err(format!("http_status: {status}; destination unchanged"));
|
||||
}
|
||||
let path = destination.ok_or("missing validated download destination")?;
|
||||
let parent = path.parent().ok_or("destination needs parent")?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
let mut entropy = [0u8; 16];
|
||||
getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?;
|
||||
let token = entropy
|
||||
.iter()
|
||||
.map(|n| format!("{n:02x}"))
|
||||
.collect::<String>();
|
||||
let temp = parent.join(format!(".mq-download-{token}"));
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let downloaded = (|| {
|
||||
let mut total = 0u64;
|
||||
let mut buffer = [0u8; 65536];
|
||||
loop {
|
||||
let n = reader.read(&mut buffer).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
file.write_all(&buffer[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
std::fs::rename(&temp, &path).map_err(|e| e.to_string())?;
|
||||
Ok(total)
|
||||
})();
|
||||
let total = match downloaded {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(temp);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
return Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("size".into(), Value::Int(total as i64)),
|
||||
("path".into(), arg(b, "path")?.clone()),
|
||||
]));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(max + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err("resource_limit: HTTP response exceeds max_bytes".into());
|
||||
}
|
||||
let mode = as_text(arg(b, "response")?, "response")?;
|
||||
let body = match mode {
|
||||
"text" => Value::Text(String::from_utf8(bytes).map_err(|e| {
|
||||
format!("invalid_encoding: response is not UTF-8; request bytes instead: {e}")
|
||||
})?),
|
||||
"bytes" => super::fs_ops::bytes_value(&bytes),
|
||||
_ => return Err("response must be text or bytes".into()),
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("headers".into(), Value::List(headers)),
|
||||
("body".into(), body),
|
||||
]))
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
//! Document-level observations, separate from process timing and execution logs.
|
||||
use crate::value::Value;
|
||||
use super::HostContext;
|
||||
|
||||
pub(crate) fn admit(value: &Value) -> Result<(), String> {
|
||||
match value {
|
||||
Value::None | Value::Bool(_) | Value::Text(_) => Ok(()),
|
||||
Value::Int(_) => super::json::value_to_json(value).map(|_| ()),
|
||||
Value::Num(_) => super::json::value_to_json(value).map(|_| ()),
|
||||
Value::List(xs) => { for x in xs { admit(x)?; } Ok(()) }
|
||||
Value::Map(xs) => {
|
||||
super::json::value_to_json(value)?;
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
for (key, x) in xs {
|
||||
if !keys.insert(key) { return Err("oracle: duplicate record field".into()); }
|
||||
admit(x)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("oracle: value outside V_safe".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn append(ctx: &mut HostContext, channel: &str, value: &Value) -> Result<(), String> {
|
||||
admit(value)?;
|
||||
ctx.oracle_observations.push(Value::Map(vec![
|
||||
("index".into(), Value::Int(ctx.oracle_observations.len() as i64)),
|
||||
("channel".into(), Value::Text(channel.into())),
|
||||
("value".into(), value.clone()),
|
||||
]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Project a process result to its semantic observation. Success observes the
|
||||
/// returned payload. Failure observes stable diagnostics, never elapsed time,
|
||||
/// command paths or opaque handles. Both document and live runners use this.
|
||||
pub(crate) fn eval_observation(record: &Value) -> Result<Value, String> {
|
||||
let Value::Map(fields) = record else { return Err("oracle: expected eval record".into()) };
|
||||
let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_,v)|v.clone()).unwrap_or(Value::None);
|
||||
let value = match get("ok") {
|
||||
Value::Bool(true) => get("result"),
|
||||
Value::Bool(false) => {
|
||||
let source = get("diagnostic_source");
|
||||
Value::Map(["ok", "code", "stdout", "stderr", "error", "timed_out", "alive"]
|
||||
.into_iter().map(|key| {
|
||||
let value = get(key);
|
||||
// Alpha-rename only this execution's allocated source path,
|
||||
// only in diagnostics. Keep raw output and ordinary paths intact.
|
||||
let value = match (key, value, &source) {
|
||||
("stderr" | "error", Value::Text(text), Value::Text(path)) if !path.is_empty() =>
|
||||
Value::Text(text.replace(path, "<foreign-source>")),
|
||||
(_, value, _) => value,
|
||||
};
|
||||
(key.to_string(), value)
|
||||
}).collect())
|
||||
},
|
||||
_ => return Err("oracle: eval record missing boolean ok".into()),
|
||||
};
|
||||
admit(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn validate(journal: &Value) -> Result<&[Value], String> {
|
||||
let Value::List(rows) = journal else { return Err("oracle journal must be a list".into()) };
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let Value::Map(fields) = row else { return Err(format!("oracle step {i}: expected record")) };
|
||||
if fields.len() != 3 { return Err(format!("oracle step {i}: expected index/channel/value")); }
|
||||
let get = |k: &str| fields.iter().find(|(key,_)| key == k).map(|(_,v)|v);
|
||||
if get("index") != Some(&Value::Int(i as i64)) { return Err(format!("oracle step {i}: invalid index")); }
|
||||
if !matches!(get("channel"), Some(Value::Text(s)) if ["eval", "get", "decode"].contains(&s.as_str())) {
|
||||
return Err(format!("oracle step {i}: invalid channel"));
|
||||
}
|
||||
admit(get("value").ok_or_else(|| format!("oracle step {i}: missing value"))?)?;
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Pure structural equality on admitted journals; reports the least differing index.
|
||||
pub(crate) fn replay_check(expected: &Value, observed: &Value) -> Result<Value, String> {
|
||||
let a = validate(expected)?;
|
||||
let b = validate(observed)?;
|
||||
// Map field order is not part of record identity (matches JSON object semantics).
|
||||
let canonical = |v: &Value| super::json::value_to_json(v);
|
||||
let mut mismatch = None;
|
||||
for i in 0..a.len().max(b.len()) {
|
||||
if a.get(i).map(canonical).transpose()? != b.get(i).map(canonical).transpose()? {
|
||||
mismatch = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let index = mismatch.map(|i| Value::Int(i as i64)).unwrap_or(Value::None);
|
||||
Ok(Value::Map(vec![
|
||||
("ok".into(), Value::Bool(mismatch.is_none())),
|
||||
("index".into(), index),
|
||||
("expected".into(), mismatch.and_then(|i| a.get(i)).cloned().unwrap_or(Value::None)),
|
||||
("observed".into(), mismatch.and_then(|i| b.get(i)).cloned().unwrap_or(Value::None)),
|
||||
]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn oracle_journal_structural_mismatch_and_length() {
|
||||
let mut ctx = HostContext::default();
|
||||
append(&mut ctx, "eval", &Value::Int(3)).unwrap();
|
||||
append(&mut ctx, "get", &Value::Int(2)).unwrap();
|
||||
let journal = Value::List(ctx.oracle_observations.clone());
|
||||
let result = replay_check(&journal, &journal).unwrap();
|
||||
assert_eq!(super::super::json::get(&result, &Value::Text("ok".into())).unwrap(), Value::Bool(true));
|
||||
let short = Value::List(ctx.oracle_observations[..1].to_vec());
|
||||
let result = replay_check(&journal, &short).unwrap();
|
||||
assert_eq!(super::super::json::get(&result, &Value::Text("index".into())).unwrap(), Value::Int(1));
|
||||
assert!(append(&mut ctx, "eval", &Value::List(vec![Value::Handle("x".into())])).is_err());
|
||||
let code = Value::Code(crate::value::CodeBlock { lang: "python".into(), source: "1".into() });
|
||||
assert!(admit(&Value::List(vec![code])).is_err());
|
||||
assert_eq!(ctx.oracle_observations.len(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn diagnostic_projection_renames_only_allocated_source_identity() {
|
||||
let make = |path: &str, message: &str| Value::Map(vec![
|
||||
("ok".into(), Value::Bool(false)),
|
||||
("stderr".into(), Value::Text(format!("File {path}: {message}; input /data/original.csv"))),
|
||||
("diagnostic_source".into(), Value::Text(path.into())),
|
||||
]);
|
||||
let a = make("/tmp/allocated-a.py", "ValueError");
|
||||
let b = make("/tmp/allocated-b.py", "ValueError");
|
||||
assert_ne!(a, b, "raw diagnostics must survive");
|
||||
assert_eq!(eval_observation(&a).unwrap(), eval_observation(&b).unwrap());
|
||||
let c = make("/tmp/allocated-b.py", "TypeError");
|
||||
assert_ne!(eval_observation(&a).unwrap(), eval_observation(&c).unwrap());
|
||||
let d = make("/tmp/allocated-b.py", "ValueError /data/changed.csv");
|
||||
assert_ne!(eval_observation(&a).unwrap(), eval_observation(&d).unwrap());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
//! Path algebra for Mid M2 (`lib/path`) — no I/O.
|
||||
|
||||
use crate::host::as_text;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
fn path_to_text(p: &Path) -> String {
|
||||
if p.as_os_str().is_empty() {
|
||||
".".into()
|
||||
} else {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn join(a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let a = as_text(a, "a")?;
|
||||
let b = as_text(b, "b")?;
|
||||
let out = Path::new(a).join(b);
|
||||
Ok(Value::Text(path_to_text(&out)))
|
||||
}
|
||||
|
||||
pub fn split(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
let mut parts = Vec::new();
|
||||
for c in Path::new(p).components() {
|
||||
match c {
|
||||
Component::RootDir | Component::CurDir | Component::ParentDir => {
|
||||
parts.push(Value::Text(c.as_os_str().to_string_lossy().into_owned()));
|
||||
}
|
||||
Component::Prefix(prefix) => {
|
||||
parts.push(Value::Text(prefix.as_os_str().to_string_lossy().into_owned()));
|
||||
}
|
||||
Component::Normal(s) => parts.push(Value::Text(s.to_string_lossy().into_owned())),
|
||||
}
|
||||
}
|
||||
Ok(Value::List(parts))
|
||||
}
|
||||
|
||||
pub fn file_name(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
Ok(Value::Text(
|
||||
Path::new(p)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn parent(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
let parent = Path::new(p).parent();
|
||||
Ok(Value::Text(match parent {
|
||||
Some(par) if !par.as_os_str().is_empty() => path_to_text(par),
|
||||
_ => ".".into(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn extension(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
Ok(Value::Text(
|
||||
Path::new(p)
|
||||
.extension()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn normalize(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
let mut out = PathBuf::new();
|
||||
for c in Path::new(p).components() {
|
||||
match c {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
match out.components().next_back() {
|
||||
Some(Component::Normal(_)) => {
|
||||
out.pop();
|
||||
}
|
||||
Some(Component::RootDir) | Some(Component::Prefix(_)) => {}
|
||||
_ => out.push(".."),
|
||||
}
|
||||
}
|
||||
other => out.push(other.as_os_str()),
|
||||
}
|
||||
}
|
||||
Ok(Value::Text(path_to_text(&out)))
|
||||
}
|
||||
|
||||
pub fn is_absolute(path: &Value) -> Result<Value, String> {
|
||||
let p = as_text(path, "path")?;
|
||||
Ok(Value::Bool(Path::new(p).is_absolute()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn join_and_name() {
|
||||
let j = join(
|
||||
&Value::Text("a/b".into()),
|
||||
&Value::Text("c.txt".into()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(j, Value::Text("a/b/c.txt".into()));
|
||||
assert_eq!(
|
||||
file_name(&Value::Text("a/b/c.txt".into())).unwrap(),
|
||||
Value::Text("c.txt".into())
|
||||
);
|
||||
assert_eq!(
|
||||
extension(&Value::Text("c.txt".into())).unwrap(),
|
||||
Value::Text("txt".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,793 +0,0 @@
|
||||
//! Native plugin loader (C ABI v1/v2). Shared libs are not linked into marqdo.
|
||||
|
||||
use crate::host::as_text;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use libloading::{Library, Symbol};
|
||||
|
||||
use crate::host::agent_rt;
|
||||
use crate::host::json::{json_to_value, value_to_json};
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
/// Highest ABI version this host speaks.
|
||||
pub const ABI_VERSION: u32 = 2;
|
||||
/// Oldest plugin ABI still accepted.
|
||||
pub const ABI_VERSION_MIN: u32 = 1;
|
||||
|
||||
type PluginFn = unsafe extern "C" fn(
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int;
|
||||
|
||||
type HostQueryFn = unsafe extern "C" fn(
|
||||
userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int;
|
||||
|
||||
type AbiVersionFn = unsafe extern "C" fn() -> u32;
|
||||
type InitFn = unsafe extern "C" fn(host: *const MarqdoHostApi) -> c_int;
|
||||
type ShutdownFn = unsafe extern "C" fn();
|
||||
|
||||
#[repr(C)]
|
||||
struct MarqdoHostApi {
|
||||
userdata: *mut c_void,
|
||||
register_fn: Option<
|
||||
unsafe extern "C" fn(
|
||||
userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
params: *const c_char,
|
||||
fn_ptr: PluginFn,
|
||||
) -> c_int,
|
||||
>,
|
||||
alloc: Option<unsafe extern "C" fn(n: usize) -> *mut c_void>,
|
||||
free: Option<unsafe extern "C" fn(p: *mut c_void)>,
|
||||
host_query: Option<HostQueryFn>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Set around plugin calls so `host_query` can read/write host context (plots, etc.).
|
||||
static CURRENT_HOST: Cell<*mut HostContext> = const { Cell::new(std::ptr::null_mut()) };
|
||||
/// Optional `lib.member` resolver for `host_query("call_lib_path")` (site entry module).
|
||||
static LIB_PATH_CALL: RefCell<Option<LibPathCall>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Process-wide host pointer while a long-lived plugin call (e.g. `web_listen`) is active.
|
||||
/// Lets Tokio worker threads invoke `host_query` during HTTP handlers.
|
||||
struct SendPtr<T>(*mut T);
|
||||
unsafe impl<T> Send for SendPtr<T> {}
|
||||
unsafe impl<T> Sync for SendPtr<T> {}
|
||||
|
||||
struct SendLibPath(Option<LibPathCall>);
|
||||
unsafe impl Send for SendLibPath {}
|
||||
unsafe impl Sync for SendLibPath {}
|
||||
|
||||
static GLOBAL_HOST: OnceLock<Mutex<SendPtr<HostContext>>> = OnceLock::new();
|
||||
/// Process-wide lib-path hook (same lifetime as GLOBAL_HOST).
|
||||
static GLOBAL_LIB_PATH: OnceLock<Mutex<SendLibPath>> = OnceLock::new();
|
||||
/// Serialize interpreter re-entry from HTTP worker threads.
|
||||
/// HostContext is not Sync — one Marqdo invoke at a time. Short routes must
|
||||
/// fail fast (`interpreter busy`) so a long SSE chat cannot freeze the UI.
|
||||
static INVOKE_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
|
||||
fn global_host_slot() -> &'static Mutex<SendPtr<HostContext>> {
|
||||
GLOBAL_HOST.get_or_init(|| Mutex::new(SendPtr(std::ptr::null_mut())))
|
||||
}
|
||||
|
||||
fn global_lib_slot() -> &'static Mutex<SendLibPath> {
|
||||
GLOBAL_LIB_PATH.get_or_init(|| Mutex::new(SendLibPath(None)))
|
||||
}
|
||||
|
||||
fn invoke_lock() -> &'static Mutex<()> {
|
||||
INVOKE_LOCK.get_or_init(|| Mutex::new(()))
|
||||
}
|
||||
|
||||
/// Default wait for short HTTP invokes (`MARQDO_INVOKE_WAIT_MS`, default 1500ms).
|
||||
/// Do not raise this process-wide during SSE — concurrent short routes would hang again.
|
||||
/// See doc/adr/0008-web-invoke-serialization.md.
|
||||
fn invoke_wait_budget() -> Duration {
|
||||
const DEFAULT_MS: u64 = 1500;
|
||||
match std::env::var("MARQDO_INVOKE_WAIT_MS") {
|
||||
Ok(s) => {
|
||||
let ms = s.trim().parse::<u64>().unwrap_or(DEFAULT_MS);
|
||||
Duration::from_millis(ms.max(1))
|
||||
}
|
||||
Err(_) => Duration::from_millis(DEFAULT_MS),
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_invoke_lock() -> Result<MutexGuard<'static, ()>, String> {
|
||||
let budget = invoke_wait_budget();
|
||||
let deadline = Instant::now() + budget;
|
||||
let lock = invoke_lock();
|
||||
loop {
|
||||
match lock.try_lock() {
|
||||
Ok(g) => return Ok(g),
|
||||
Err(std::sync::TryLockError::Poisoned(p)) => return Ok(p.into_inner()),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
if Instant::now() >= deadline {
|
||||
return Err(format!(
|
||||
"interpreter busy: another request holds the Marqdo invoke lock (waited {}ms)",
|
||||
budget.as_millis()
|
||||
));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook: resolve bare `lib.member` (and longer paths) in the site module's import tree.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct LibPathCall {
|
||||
pub call: fn(*mut (), &str, Option<&Value>) -> Result<Value, String>,
|
||||
pub data: *mut (),
|
||||
}
|
||||
|
||||
/// Run `body` with a temporary lib-path call hook (nested-safe).
|
||||
pub fn with_lib_path_call<R>(hook: LibPathCall, body: impl FnOnce() -> R) -> R {
|
||||
LIB_PATH_CALL.with(|slot| {
|
||||
let prev = slot.replace(Some(hook));
|
||||
let prev_g = {
|
||||
let mut g = global_lib_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||
std::mem::replace(&mut g.0, Some(hook))
|
||||
};
|
||||
let out = body();
|
||||
{
|
||||
let mut g = global_lib_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||
g.0 = prev_g;
|
||||
}
|
||||
slot.replace(prev);
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
struct RegisterBuf {
|
||||
fns: HashMap<String, RegisteredFn>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegisteredFn {
|
||||
pub params: Vec<String>,
|
||||
fn_ptr: PluginFn,
|
||||
}
|
||||
|
||||
pub struct PluginState {
|
||||
libs: Vec<Library>,
|
||||
fns: HashMap<String, RegisteredFn>,
|
||||
}
|
||||
|
||||
impl Default for PluginState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
libs: Vec::new(),
|
||||
fns: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PluginState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PluginState")
|
||||
.field("libs", &self.libs.len())
|
||||
.field("fns", &self.list_names())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for PluginState {
|
||||
fn clone(&self) -> Self {
|
||||
// `Library` handles are not cloneable; a cloned host starts with no plugins.
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginState {
|
||||
/// Exercise the real JSON/C ABI without loading an external shared library.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn register_binding_probe(&mut self) {
|
||||
unsafe extern "C" fn echo(args: *const c_char, out: *mut *mut c_char, _err: *mut *mut c_char) -> c_int {
|
||||
if args.is_null() || out.is_null() { return 1; }
|
||||
let Ok(input)=CStr::from_ptr(args).to_str() else { return 1; };
|
||||
*out=host_strdup(input);
|
||||
if (*out).is_null() {1} else {0}
|
||||
}
|
||||
self.fns.insert("binding_probe".into(),RegisteredFn{params:vec!["a".into(),"b".into()],fn_ptr:echo});
|
||||
}
|
||||
pub fn get(&self, name: &str) -> Option<&RegisteredFn> {
|
||||
self.fns.get(name)
|
||||
}
|
||||
|
||||
pub fn list_names(&self) -> Vec<String> {
|
||||
let mut names: Vec<_> = self.fns.keys().cloned().collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
pub fn has_fn(&self, name: &str) -> bool {
|
||||
self.fns.contains_key(name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extern "C" {
|
||||
fn malloc(n: usize) -> *mut c_void;
|
||||
fn free(p: *mut c_void);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn host_alloc(n: usize) -> *mut c_void {
|
||||
malloc(n)
|
||||
}
|
||||
|
||||
unsafe extern "C" fn host_free(p: *mut c_void) {
|
||||
if !p.is_null() {
|
||||
free(p);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn host_strdup(s: &str) -> *mut c_char {
|
||||
let bytes = s.as_bytes();
|
||||
let p = host_alloc(bytes.len() + 1) as *mut u8;
|
||||
if p.is_null() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
|
||||
*p.add(bytes.len()) = 0;
|
||||
p as *mut c_char
|
||||
}
|
||||
|
||||
unsafe extern "C" fn host_register(
|
||||
userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
params: *const c_char,
|
||||
fn_ptr: PluginFn,
|
||||
) -> c_int {
|
||||
if userdata.is_null() || name.is_null() {
|
||||
return 1;
|
||||
}
|
||||
let buf = &mut *(userdata as *mut RegisterBuf);
|
||||
let name = match CStr::from_ptr(name).to_str() {
|
||||
Ok(s) => s.to_string(),
|
||||
Err(_) => {
|
||||
buf.error = Some("plugin register: name is not UTF-8".into());
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if name.is_empty() {
|
||||
buf.error = Some("plugin register: empty name".into());
|
||||
return 1;
|
||||
}
|
||||
let params_s = if params.is_null() {
|
||||
""
|
||||
} else {
|
||||
match CStr::from_ptr(params).to_str() {
|
||||
Ok(s) => s,
|
||||
Err(_) => {
|
||||
buf.error = Some("plugin register: params is not UTF-8".into());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
let param_list: Vec<String> = if params_s.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
params_s
|
||||
.split(',')
|
||||
.map(|p| p.trim().to_string())
|
||||
.filter(|p| !p.is_empty())
|
||||
.collect()
|
||||
};
|
||||
if buf.fns.contains_key(&name) {
|
||||
buf.error = Some(format!("plugin register: duplicate `{name}`"));
|
||||
return 1;
|
||||
}
|
||||
buf.fns.insert(
|
||||
name,
|
||||
RegisteredFn {
|
||||
params: param_list,
|
||||
fn_ptr,
|
||||
},
|
||||
);
|
||||
0
|
||||
}
|
||||
|
||||
/// Allowlisted host introspection for ABI v2 plugins (`host_query`).
|
||||
unsafe extern "C" fn host_query(
|
||||
_userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int {
|
||||
let set_err = |msg: &str| {
|
||||
if !err_msg.is_null() {
|
||||
*err_msg = host_strdup(msg);
|
||||
}
|
||||
};
|
||||
let set_out = |msg: &str| {
|
||||
if !out_json.is_null() {
|
||||
*out_json = host_strdup(msg);
|
||||
}
|
||||
};
|
||||
|
||||
if name.is_null() {
|
||||
set_err("host_query: null name");
|
||||
return 1;
|
||||
}
|
||||
let name = match CStr::from_ptr(name).to_str() {
|
||||
Ok(s) => s,
|
||||
Err(_) => {
|
||||
set_err("host_query: name not utf-8");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
let args_owned: Option<String> = if args_json.is_null() {
|
||||
None
|
||||
} else {
|
||||
CStr::from_ptr(args_json)
|
||||
.to_str()
|
||||
.ok()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
|
||||
// Control plane (admit/cancel/events) must not take INVOKE_LOCK or require
|
||||
// an evaluating HostContext — otherwise cancel cannot interrupt a busy run.
|
||||
if name == "runtime" {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = match serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
}) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
set_err(&format!("runtime args: {e}"));
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
match crate::runtime::host_api::handle(&args) {
|
||||
Ok(j) => {
|
||||
set_out(&j.to_string());
|
||||
return 0;
|
||||
}
|
||||
Err(e) => {
|
||||
set_err(&e);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ctx_ptr = CURRENT_HOST.with(|c| c.get());
|
||||
let ctx_ptr = if ctx_ptr.is_null() {
|
||||
global_host_slot()
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0
|
||||
} else {
|
||||
ctx_ptr
|
||||
};
|
||||
if ctx_ptr.is_null() {
|
||||
set_err("host_query: no active host context (call during plugin fn)");
|
||||
return 1;
|
||||
}
|
||||
let _invoke_guard;
|
||||
let from_worker = CURRENT_HOST.with(|c| c.get().is_null());
|
||||
if from_worker {
|
||||
match acquire_invoke_lock() {
|
||||
Ok(g) => _invoke_guard = g,
|
||||
Err(msg) => {
|
||||
set_err(&msg);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let ctx = &mut *ctx_ptr;
|
||||
|
||||
let result = match name {
|
||||
"module_source" => agent_rt::module_source(ctx).and_then(|v| value_to_json(&v)),
|
||||
"call_site" => agent_rt::call_site(ctx, Some(ctx.current_line)).and_then(|v| value_to_json(&v)),
|
||||
"marqdo_skill" => agent_rt::marqdo_skill(ctx).and_then(|v| value_to_json(&v)),
|
||||
"cwd" => Ok(serde_json::Value::String(
|
||||
ctx.cwd.to_string_lossy().into_owned(),
|
||||
)),
|
||||
"entry_path" => {
|
||||
let path = ctx.entry_path.clone().unwrap_or_else(|| ctx.cwd.clone());
|
||||
let abs = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(path)
|
||||
};
|
||||
Ok(serde_json::Value::String(
|
||||
abs.to_string_lossy().into_owned(),
|
||||
))
|
||||
}
|
||||
"entry_dir" => {
|
||||
// Script directory: parent of entry file (for_run also sets ctx.cwd to this).
|
||||
let dir = ctx
|
||||
.entry_path
|
||||
.as_ref()
|
||||
.map(|p| {
|
||||
if p.is_dir() {
|
||||
p.clone()
|
||||
} else {
|
||||
p.parent().unwrap_or(p).to_path_buf()
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| ctx.cwd.clone());
|
||||
// Absolutize against the *process* cwd — not ctx.cwd. For a relative
|
||||
// entry like `tests/ext/foo.mq.md`, for_run sets ctx.cwd = `tests/ext`;
|
||||
// joining that again would yield `tests/ext/tests/ext/...`.
|
||||
let abs = if dir.is_absolute() {
|
||||
dir
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(dir)
|
||||
};
|
||||
Ok(serde_json::Value::String(
|
||||
abs.to_string_lossy().into_owned(),
|
||||
))
|
||||
}
|
||||
"call_lib_path" => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
.map_err(|e| format!("call_lib_path args: {e}"))?;
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "call_lib_path requires `path`".to_string())?
|
||||
.to_string();
|
||||
let call_args = args.get("args").and_then(|v| {
|
||||
if v.is_null() {
|
||||
None
|
||||
} else {
|
||||
json_to_value(v).ok()
|
||||
}
|
||||
});
|
||||
let call_args_ref = call_args.as_ref();
|
||||
let from_tls = LIB_PATH_CALL.with(|slot| slot.borrow().clone());
|
||||
let hook = if let Some(h) = from_tls {
|
||||
h
|
||||
} else {
|
||||
global_lib_slot()
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.0
|
||||
.ok_or_else(|| "call_lib_path: no site lib resolver".to_string())?
|
||||
};
|
||||
let v = (hook.call)(hook.data, &path, call_args_ref)?;
|
||||
value_to_json(&v)
|
||||
})(),
|
||||
"record_plot" => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
.map_err(|e| format!("record_plot args: {e}"))?;
|
||||
let svg = args
|
||||
.get("svg")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "record_plot requires `svg`".to_string())?
|
||||
.to_string();
|
||||
let path_s = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
if let Some(ref p) = path_s {
|
||||
crate::host::fs::write_text(
|
||||
ctx,
|
||||
&Value::Text(p.clone()),
|
||||
&Value::Text(svg.clone()),
|
||||
)?;
|
||||
}
|
||||
ctx.plots.push(crate::host::PlotArtifact {
|
||||
path: path_s,
|
||||
svg,
|
||||
});
|
||||
Ok(serde_json::json!({ "ok": true }))
|
||||
})(),
|
||||
name if name.starts_with("sandbox_") => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
.map_err(|e| format!("{name} args: {e}"))?;
|
||||
crate::host::sandbox_fs::query(name, &args, ctx)
|
||||
})(),
|
||||
// ADR 0007: run a Document/Endpoint `.mq.md` for HTTP handlers.
|
||||
"run_artifact" => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
.map_err(|e| format!("run_artifact args: {e}"))?;
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "run_artifact requires `path`".to_string())?;
|
||||
let p = ctx.resolve_path(path)?;
|
||||
if !p.is_file() {
|
||||
return Err(format!("run_artifact: not a file: {path}"));
|
||||
}
|
||||
// A web site may narrow an existing filesystem grant. Child
|
||||
// Documents keep that explicit root instead of defaulting to pages/.
|
||||
let fs_root = match args.get("root") {
|
||||
None | Some(serde_json::Value::Null) => ctx.fs_root.clone(),
|
||||
Some(serde_json::Value::String(root)) => {
|
||||
let selected = ctx.resolve_path(root)?;
|
||||
if !selected.is_dir() { return Err("run_artifact: root is not a directory".into()); }
|
||||
let actual = p.canonicalize().map_err(|_| "run_artifact: cannot resolve source")?;
|
||||
let base = selected.canonicalize().map_err(|_| "run_artifact: cannot resolve root")?;
|
||||
if !actual.starts_with(&base) {
|
||||
return Err("run_artifact: source is outside selected site root".into());
|
||||
}
|
||||
Some(selected)
|
||||
}
|
||||
Some(_) => return Err("run_artifact: root must be text".into()),
|
||||
};
|
||||
let mut binds: Vec<(String, String)> = Vec::new();
|
||||
if let Some(obj) = args.get("args").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
let s = match v {
|
||||
serde_json::Value::String(t) => t.clone(),
|
||||
serde_json::Value::Null => continue,
|
||||
other => other.to_string(),
|
||||
};
|
||||
binds.push((k.clone(), s));
|
||||
}
|
||||
}
|
||||
let opts = crate::RunOptions {
|
||||
binds,
|
||||
fs_root,
|
||||
allow_fs_write: ctx.caps.fs_write,
|
||||
allow_exec: ctx.caps.exec,
|
||||
allow_net: ctx.caps.net,
|
||||
..crate::RunOptions::default()
|
||||
};
|
||||
let cap = crate::run_file_capture(&p, &opts).map_err(|e| e.to_string())?;
|
||||
value_to_json(&cap.value)
|
||||
})(),
|
||||
// M04: plugins may drive MLSP artifact.bind/execute without inventing a second protocol.
|
||||
"mlsp" => (|| {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
})
|
||||
.map_err(|e| format!("mlsp args: {e}"))?;
|
||||
let method = args
|
||||
.get("method")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "mlsp requires `method`".to_string())?;
|
||||
let params = args.get("params").cloned().unwrap_or(serde_json::json!({}));
|
||||
let line = serde_json::json!({"method": method, "params": params}).to_string();
|
||||
let resp = crate::mlsp::handle_line(&line);
|
||||
serde_json::from_str(&resp).map_err(|e| format!("mlsp response: {e}"))
|
||||
})(),
|
||||
other => Err(format!("host_query: unknown `{other}`")),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(j) => {
|
||||
set_out(&j.to_string());
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
set_err(&e);
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_plugin() {
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("plugin.load unavailable in sandbox".into());
|
||||
}
|
||||
return Err("plugin_load denied by host policy".into());
|
||||
}
|
||||
let rel = as_text(path, "path")?;
|
||||
let file = match ctx.resolve_path(rel) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
let p = std::path::Path::new(rel);
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
ctx.cwd.join(p)
|
||||
};
|
||||
if abs.is_file() && crate::ext_cli::path_is_trusted_plugin(&abs) {
|
||||
abs
|
||||
} else {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(format!("plugin_load: not a file: {}", file.display()));
|
||||
}
|
||||
|
||||
let lib = unsafe { Library::new(&file) }
|
||||
.map_err(|e| format!("plugin_load {}: {e}", file.display()))?;
|
||||
|
||||
let version_fn: Symbol<AbiVersionFn> = unsafe {
|
||||
lib.get(b"marqdo_plugin_abi_version\0")
|
||||
.map_err(|e| format!("plugin missing marqdo_plugin_abi_version: {e}"))?
|
||||
};
|
||||
let ver = unsafe { version_fn() };
|
||||
if ver < ABI_VERSION_MIN || ver > ABI_VERSION {
|
||||
return Err(format!(
|
||||
"plugin ABI version {ver} not in host range {ABI_VERSION_MIN}..={ABI_VERSION} ({})",
|
||||
file.display()
|
||||
));
|
||||
}
|
||||
|
||||
let init_fn: Symbol<InitFn> = unsafe {
|
||||
lib.get(b"marqdo_plugin_init\0")
|
||||
.map_err(|e| format!("plugin missing marqdo_plugin_init: {e}"))?
|
||||
};
|
||||
|
||||
let mut buf = RegisterBuf {
|
||||
fns: HashMap::new(),
|
||||
error: None,
|
||||
};
|
||||
let api = MarqdoHostApi {
|
||||
userdata: &mut buf as *mut RegisterBuf as *mut c_void,
|
||||
register_fn: Some(host_register),
|
||||
alloc: Some(host_alloc),
|
||||
free: Some(host_free),
|
||||
host_query: Some(host_query),
|
||||
};
|
||||
|
||||
let rc = unsafe { init_fn(&api) };
|
||||
if rc != 0 {
|
||||
return Err(buf
|
||||
.error
|
||||
.unwrap_or_else(|| format!("plugin init failed (code {rc})")));
|
||||
}
|
||||
if let Some(e) = buf.error {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
for k in buf.fns.keys() {
|
||||
if ctx.plugins.fns.contains_key(k) {
|
||||
// Idempotent re-load of the same plugin surface (e.g. multiple `agent` ctors).
|
||||
if buf.fns.keys().all(|name| ctx.plugins.fns.contains_key(name)) {
|
||||
return Ok(Value::Int(0));
|
||||
}
|
||||
return Err(format!("plugin function `{k}` already registered"));
|
||||
}
|
||||
}
|
||||
let added = buf.fns.len();
|
||||
for (k, v) in buf.fns {
|
||||
ctx.plugins.fns.insert(k, v);
|
||||
}
|
||||
ctx.plugins.libs.push(lib);
|
||||
Ok(Value::Int(added as i64))
|
||||
}
|
||||
|
||||
pub fn unload(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
if !ctx.allow_plugin() {
|
||||
return Err("plugin_unload denied by host policy".into());
|
||||
}
|
||||
for lib in ctx.plugins.libs.drain(..) {
|
||||
if let Ok(shutdown) = unsafe { lib.get::<ShutdownFn>(b"marqdo_plugin_shutdown\0") } {
|
||||
unsafe { shutdown() };
|
||||
}
|
||||
drop(lib);
|
||||
}
|
||||
ctx.plugins.fns.clear();
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn list(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(
|
||||
ctx.plugins
|
||||
.list_names()
|
||||
.into_iter()
|
||||
.map(Value::Text)
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Call a registered plugin function with already-bound args (param name → Value).
|
||||
pub fn call_registered(
|
||||
ctx: &mut HostContext,
|
||||
name: &str,
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_plugin() {
|
||||
return Err("plugin call denied by host policy".into());
|
||||
}
|
||||
let reg = ctx
|
||||
.plugins
|
||||
.get(name)
|
||||
.ok_or_else(|| format!("unknown function `{name}`"))?
|
||||
.clone();
|
||||
|
||||
let mut map = serde_json::Map::new();
|
||||
for p in ®.params {
|
||||
let v = bound.get(p).unwrap_or(&Value::None);
|
||||
map.insert(p.clone(), value_to_json(v)?);
|
||||
}
|
||||
for (k, v) in bound {
|
||||
if !map.contains_key(k) {
|
||||
map.insert(k.clone(), value_to_json(v)?);
|
||||
}
|
||||
}
|
||||
let args_json = serde_json::Value::Object(map).to_string();
|
||||
let c_args = CString::new(args_json).map_err(|e| format!("plugin args: {e}"))?;
|
||||
|
||||
let mut out_ptr: *mut c_char = std::ptr::null_mut();
|
||||
let mut err_ptr: *mut c_char = std::ptr::null_mut();
|
||||
|
||||
// Nesting-safe: restore previous host pointers after this call. Clearing to
|
||||
// null would break a long-lived outer call (e.g. `web_listen`) so later
|
||||
// HTTP `invoke` / `host_query` on worker threads see no active context.
|
||||
let prev_tls = CURRENT_HOST.with(|c| {
|
||||
let prev = c.get();
|
||||
c.set(ctx as *mut HostContext);
|
||||
prev
|
||||
});
|
||||
let prev_global = {
|
||||
let mut g = global_host_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||
let prev = g.0;
|
||||
g.0 = ctx as *mut HostContext;
|
||||
prev
|
||||
};
|
||||
let rc = unsafe { (reg.fn_ptr)(c_args.as_ptr(), &mut out_ptr, &mut err_ptr) };
|
||||
{
|
||||
let mut g = global_host_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||
g.0 = prev_global;
|
||||
}
|
||||
CURRENT_HOST.with(|c| c.set(prev_tls));
|
||||
|
||||
let err_s = take_c_string(err_ptr);
|
||||
let out_s = take_c_string(out_ptr);
|
||||
|
||||
if rc != 0 {
|
||||
return Err(err_s.unwrap_or_else(|| format!("plugin `{name}` failed (code {rc})")));
|
||||
}
|
||||
let out_s = out_s.unwrap_or_else(|| "null".to_string());
|
||||
let j: serde_json::Value =
|
||||
serde_json::from_str(&out_s).map_err(|e| format!("plugin `{name}` bad JSON result: {e}"))?;
|
||||
json_to_value(&j)
|
||||
}
|
||||
|
||||
fn take_c_string(p: *mut c_char) -> Option<String> {
|
||||
if p.is_null() {
|
||||
return None;
|
||||
}
|
||||
let s = unsafe { CStr::from_ptr(p) }
|
||||
.to_str()
|
||||
.map(|s| s.to_string())
|
||||
.ok();
|
||||
unsafe { host_free(p as *mut c_void) };
|
||||
s
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub const ABI_VERSION: u32 = 2;
|
||||
pub const ABI_VERSION_MIN: u32 = 1;
|
||||
|
||||
/// Hook: resolve bare `lib.member` (unused without native plugins).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct LibPathCall {
|
||||
pub call: fn(*mut (), &str, Option<&Value>) -> Result<Value, String>,
|
||||
pub data: *mut (),
|
||||
}
|
||||
|
||||
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
|
||||
body()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegisteredFn {
|
||||
pub params: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct PluginState;
|
||||
|
||||
impl PluginState {
|
||||
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn list_names(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
|
||||
Err("plugin.load unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Err("plugin.unload unavailable in browser wasm".into())
|
||||
}
|
||||
|
||||
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(Vec::new()))
|
||||
}
|
||||
|
||||
pub fn call_registered(
|
||||
_ctx: &mut HostContext,
|
||||
name: &str,
|
||||
_bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
Err(format!("plugin `{name}` unavailable in browser wasm"))
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
//! Regex host primitives for Mid M1 (`lib/re`).
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
use regex::Regex;
|
||||
|
||||
|
||||
fn compile(pattern: &str) -> Result<Regex, String> {
|
||||
Regex::new(pattern).map_err(|e| format!("invalid regex: {e}"))
|
||||
}
|
||||
|
||||
pub fn is_match(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(Value::Bool(re.is_match(t)))
|
||||
}
|
||||
|
||||
pub fn find(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(match re.find(t) {
|
||||
Some(m) => Value::Text(m.as_str().to_string()),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_all(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.find_iter(t)
|
||||
.map(|m| Value::Text(m.as_str().to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
pub fn replace(
|
||||
text: &Value,
|
||||
pattern: &Value,
|
||||
with: &Value,
|
||||
count: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let w = as_text(with, "with")?;
|
||||
let re = compile(p)?;
|
||||
let limit = match count {
|
||||
None | Some(Value::None) => None,
|
||||
Some(Value::Int(n)) => {
|
||||
if *n < 0 {
|
||||
return Err("count must be non-negative".into());
|
||||
}
|
||||
Some(*n as usize)
|
||||
}
|
||||
Some(_) => return Err("count needs int".into()),
|
||||
};
|
||||
let out = match limit {
|
||||
None => re.replace_all(t, w).into_owned(),
|
||||
Some(0) => t.to_string(),
|
||||
Some(n) => re.replacen(t, n, w).into_owned(),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn split(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.split(t)
|
||||
.map(|s| Value::Text(s.to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn match_and_find() {
|
||||
assert_eq!(
|
||||
is_match(
|
||||
&Value::Text("abc123".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Bool(true)
|
||||
);
|
||||
assert_eq!(
|
||||
find(
|
||||
&Value::Text("ab12cd34".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Text("12".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//! A recoverable failure is data; permission errors remain explicit failures.
|
||||
use crate::value::Value;
|
||||
|
||||
pub(super) fn capture(operation: &str, result: Result<Value, String>) -> Value {
|
||||
let (ok, value, error) = match result {
|
||||
Ok(value) => (true, value, Value::None),
|
||||
Err(message) => {
|
||||
let tagged = message.split_once(':').map(|(code, _)| code);
|
||||
let code = match tagged {
|
||||
Some(
|
||||
code @ ("validation_failed" | "timed_out" | "permission_denied" | "not_found"
|
||||
| "conflict" | "invalid_encoding" | "invalid_json" | "invalid_csv"
|
||||
| "invalid_toml" | "transport_error" | "http_status" | "resource_limit"
|
||||
| "unsupported" | "invalid_argument" | "nonexistent_time"
|
||||
| "ambiguous_time"),
|
||||
) => code,
|
||||
_ if message.starts_with("path escapes sandbox root:")
|
||||
|| message.ends_with("denied by host policy") =>
|
||||
{
|
||||
"permission_denied"
|
||||
}
|
||||
_ => "operation_failed",
|
||||
};
|
||||
(
|
||||
false,
|
||||
Value::None,
|
||||
Value::Map(vec![
|
||||
("code".into(), Value::Text(code.into())),
|
||||
("message".into(), Value::Text(message)),
|
||||
("operation".into(), Value::Text(operation.into())),
|
||||
]),
|
||||
)
|
||||
}
|
||||
};
|
||||
Value::Map(vec![
|
||||
("ok".into(), Value::Bool(ok)),
|
||||
("value".into(), value),
|
||||
("error".into(), error),
|
||||
])
|
||||
}
|
||||
@@ -1,489 +0,0 @@
|
||||
//! Application-level CoW workspace for `ext/ai/sandbox` (via host_query).
|
||||
//!
|
||||
//! lower = real root (read-through); upper = session bytes; whiteout = logical delete.
|
||||
//! Not a symlink forest. Symlink targets are not followed as isolation primitives.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CowSession {
|
||||
pub root: PathBuf,
|
||||
/// Relative path (forward slashes) → file bytes.
|
||||
pub upper: HashMap<String, Vec<u8>>,
|
||||
pub whiteout: HashSet<String>,
|
||||
}
|
||||
|
||||
static SESSIONS: OnceLock<Mutex<HashMap<String, CowSession>>> = OnceLock::new();
|
||||
static SEQ: OnceLock<Mutex<u64>> = OnceLock::new();
|
||||
|
||||
fn sessions() -> &'static Mutex<HashMap<String, CowSession>> {
|
||||
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
fn next_id() -> String {
|
||||
let mut g = SEQ
|
||||
.get_or_init(|| Mutex::new(0))
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
*g = g.wrapping_add(1);
|
||||
format!("sbx-{g}")
|
||||
}
|
||||
|
||||
fn normalize_rel(rel: &str) -> Result<String, String> {
|
||||
let rel = rel.trim().trim_start_matches('/');
|
||||
if rel.is_empty() {
|
||||
return Err("sandbox path must not be empty".into());
|
||||
}
|
||||
let p = Path::new(rel);
|
||||
if p.is_absolute() {
|
||||
return Err("sandbox path must be relative to session root".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for c in p.components() {
|
||||
match c {
|
||||
Component::Normal(s) => out.push(s.to_string_lossy().into_owned()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
return Err("sandbox path must not contain '..'".into());
|
||||
}
|
||||
_ => return Err(format!("sandbox path invalid component in `{rel}`")),
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("sandbox path must not be empty".into());
|
||||
}
|
||||
Ok(out.join("/"))
|
||||
}
|
||||
|
||||
fn abs_under_root(root: &Path, rel: &str) -> Result<PathBuf, String> {
|
||||
let rel_n = normalize_rel(rel)?;
|
||||
let abs = root.join(Path::new(&rel_n));
|
||||
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
// Parent may not exist yet for writes — check by prefix components.
|
||||
let mut check = abs.clone();
|
||||
loop {
|
||||
if check == *root || check == root_canon {
|
||||
return Ok(root.join(Path::new(&rel_n)));
|
||||
}
|
||||
if !check.pop() {
|
||||
break;
|
||||
}
|
||||
if let Ok(c) = check.canonicalize() {
|
||||
if crate::host::path_under_root(&c, &root_canon) || c == root_canon {
|
||||
return Ok(root.join(Path::new(&rel_n)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if crate::host::path_under_root(&abs, root) {
|
||||
return Ok(abs);
|
||||
}
|
||||
Err(format!("path escapes sandbox root: {rel_n}"))
|
||||
}
|
||||
|
||||
pub fn open(root: Option<&str>, ctx: &HostContext) -> Result<serde_json::Value, String> {
|
||||
let root_pb = if let Some(r) = root.filter(|s| !s.is_empty()) {
|
||||
let p = PathBuf::from(r);
|
||||
if p.is_absolute() {
|
||||
p
|
||||
} else {
|
||||
ctx.cwd.join(p)
|
||||
}
|
||||
} else if let Some(ep) = &ctx.entry_path {
|
||||
ep.parent()
|
||||
.unwrap_or(ep.as_path())
|
||||
.to_path_buf()
|
||||
} else {
|
||||
ctx.cwd.clone()
|
||||
};
|
||||
let root_pb = if root_pb.is_absolute() {
|
||||
root_pb
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(root_pb)
|
||||
};
|
||||
if !root_pb.is_dir() {
|
||||
return Err(format!(
|
||||
"sandbox_open: root is not a directory: {}",
|
||||
root_pb.display()
|
||||
));
|
||||
}
|
||||
let id = next_id();
|
||||
let sess = CowSession {
|
||||
root: root_pb.clone(),
|
||||
upper: HashMap::new(),
|
||||
whiteout: HashSet::new(),
|
||||
};
|
||||
sessions()
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.insert(id.clone(), sess);
|
||||
Ok(json!({
|
||||
"id": id,
|
||||
"root": root_pb.to_string_lossy(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn with_session_mut<F, T>(id: &str, f: F) -> Result<T, String>
|
||||
where
|
||||
F: FnOnce(&mut CowSession) -> Result<T, String>,
|
||||
{
|
||||
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
|
||||
let sess = map
|
||||
.get_mut(id)
|
||||
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
|
||||
f(sess)
|
||||
}
|
||||
|
||||
fn with_session<F, T>(id: &str, f: F) -> Result<T, String>
|
||||
where
|
||||
F: FnOnce(&CowSession) -> Result<T, String>,
|
||||
{
|
||||
let map = sessions().lock().unwrap_or_else(|e| e.into_inner());
|
||||
let sess = map
|
||||
.get(id)
|
||||
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
|
||||
f(sess)
|
||||
}
|
||||
|
||||
pub fn write(id: &str, path: &str, text: &str) -> Result<serde_json::Value, String> {
|
||||
with_session_mut(id, |sess| {
|
||||
let rel = normalize_rel(path)?;
|
||||
let _ = abs_under_root(&sess.root, &rel)?;
|
||||
sess.whiteout.remove(&rel);
|
||||
sess.upper.insert(rel, text.as_bytes().to_vec());
|
||||
Ok(json!({ "ok": true }))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read(id: &str, path: &str) -> Result<serde_json::Value, String> {
|
||||
with_session(id, |sess| {
|
||||
let rel = normalize_rel(path)?;
|
||||
if sess.whiteout.contains(&rel) {
|
||||
return Err(format!("sandbox_read: not found (whiteout): {rel}"));
|
||||
}
|
||||
if let Some(bytes) = sess.upper.get(&rel) {
|
||||
let s = String::from_utf8(bytes.clone())
|
||||
.map_err(|e| format!("sandbox_read: not utf-8: {e}"))?;
|
||||
return Ok(json!(s));
|
||||
}
|
||||
let abs = abs_under_root(&sess.root, &rel)?;
|
||||
let s = std::fs::read_to_string(&abs)
|
||||
.map_err(|e| format!("sandbox_read {}: {e}", abs.display()))?;
|
||||
Ok(json!(s))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn remove(id: &str, path: &str) -> Result<serde_json::Value, String> {
|
||||
with_session_mut(id, |sess| {
|
||||
let rel = normalize_rel(path)?;
|
||||
let _ = abs_under_root(&sess.root, &rel)?;
|
||||
sess.upper.remove(&rel);
|
||||
sess.whiteout.insert(rel);
|
||||
Ok(json!({ "ok": true }))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn diff(id: &str) -> Result<serde_json::Value, String> {
|
||||
with_session(id, |sess| {
|
||||
let mut items: Vec<serde_json::Value> = Vec::new();
|
||||
for p in sess.upper.keys() {
|
||||
items.push(json!({ "path": p, "kind": "write" }));
|
||||
}
|
||||
for p in &sess.whiteout {
|
||||
items.push(json!({ "path": p, "kind": "remove" }));
|
||||
}
|
||||
items.sort_by(|a, b| {
|
||||
let pa = a.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let pb = b.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
pa.cmp(pb)
|
||||
});
|
||||
Ok(json!(items))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn commit(id: &str) -> Result<serde_json::Value, String> {
|
||||
with_session_mut(id, |sess| {
|
||||
let mut applied = 0i64;
|
||||
let writes: Vec<(String, Vec<u8>)> = sess
|
||||
.upper
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
let removes: Vec<String> = sess.whiteout.iter().cloned().collect();
|
||||
for (rel, bytes) in writes {
|
||||
let abs = abs_under_root(&sess.root, &rel)?;
|
||||
if let Some(parent) = abs.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("sandbox_commit mkdir: {e}"))?;
|
||||
}
|
||||
std::fs::write(&abs, &bytes)
|
||||
.map_err(|e| format!("sandbox_commit write {}: {e}", abs.display()))?;
|
||||
applied += 1;
|
||||
}
|
||||
for rel in removes {
|
||||
let abs = abs_under_root(&sess.root, &rel)?;
|
||||
if abs.exists() {
|
||||
if abs.is_dir() {
|
||||
std::fs::remove_dir_all(&abs)
|
||||
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
|
||||
} else {
|
||||
std::fs::remove_file(&abs)
|
||||
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
}
|
||||
sess.upper.clear();
|
||||
sess.whiteout.clear();
|
||||
Ok(json!({ "ok": true, "applied": applied }))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn discard(id: &str) -> Result<serde_json::Value, String> {
|
||||
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
|
||||
if map.remove(id).is_none() {
|
||||
return Err(format!("sandbox: unknown session `{id}`"));
|
||||
}
|
||||
Ok(json!({ "ok": true }))
|
||||
}
|
||||
|
||||
pub fn inspect(id: &str) -> Result<serde_json::Value, String> {
|
||||
with_session(id, |sess| {
|
||||
Ok(json!({
|
||||
"id": id,
|
||||
"root": sess.root.to_string_lossy(),
|
||||
"upper_count": sess.upper.len(),
|
||||
"whiteout_count": sess.whiteout.len(),
|
||||
"caps_default": {
|
||||
"fs_write": true,
|
||||
"exec": false,
|
||||
"net": false,
|
||||
"plugin": false
|
||||
},
|
||||
"notes": [
|
||||
"ext/web listen/DB/WS unavailable in sandbox",
|
||||
"plugin.load denied during sandbox.run",
|
||||
"subtask path/code/lang unavailable in sandbox"
|
||||
]
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Byte-preserving overlay access shared by text and byte APIs.
|
||||
pub(super) fn cow_read_bytes(ctx: &HostContext, abs: &Path) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(None); };
|
||||
with_session(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
if session.whiteout.contains(&rel) { return Err(format!("not found (sandbox whiteout): {rel}")); }
|
||||
Ok(session.upper.get(&rel).cloned())
|
||||
})
|
||||
}
|
||||
pub(super) fn cow_write_bytes(ctx: &HostContext, abs: &Path, bytes: &[u8]) -> Result<bool, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(false); };
|
||||
with_session_mut(id, |session| {
|
||||
let rel = rel_from_root(&session.root, abs)?;
|
||||
session.whiteout.remove(&rel);
|
||||
session.upper.insert(rel, bytes.to_vec());
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read file bytes through CoW for an active host sandbox session (lib/fs).
|
||||
pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result<Option<String>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
with_session(id, |sess| {
|
||||
let rel = rel_from_root(&sess.root, abs)?;
|
||||
if sess.whiteout.contains(&rel) {
|
||||
return Err(format!("read_text: not found (sandbox whiteout): {rel}"));
|
||||
}
|
||||
if let Some(bytes) = sess.upper.get(&rel) {
|
||||
let s = String::from_utf8(bytes.clone())
|
||||
.map_err(|e| format!("read_text: not utf-8: {e}"))?;
|
||||
return Ok(Some(s));
|
||||
}
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cow_write_text(ctx: &HostContext, abs: &Path, text: &str) -> Result<bool, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
with_session_mut(id, |sess| {
|
||||
let rel = rel_from_root(&sess.root, abs)?;
|
||||
sess.whiteout.remove(&rel);
|
||||
sess.upper.insert(rel, text.as_bytes().to_vec());
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cow_remove(ctx: &HostContext, abs: &Path) -> Result<bool, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
with_session_mut(id, |sess| {
|
||||
let rel = rel_from_root(&sess.root, abs)?;
|
||||
sess.upper.remove(&rel);
|
||||
sess.whiteout.insert(rel);
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cow_exists(ctx: &HostContext, abs: &Path) -> Result<Option<bool>, String> {
|
||||
let Some(id) = ctx.sandbox_session.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
with_session(id, |sess| {
|
||||
let rel = rel_from_root(&sess.root, abs)?;
|
||||
if sess.whiteout.contains(&rel) {
|
||||
return Ok(Some(false));
|
||||
}
|
||||
if sess.upper.contains_key(&rel) {
|
||||
return Ok(Some(true));
|
||||
}
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
|
||||
fn rel_from_root(root: &Path, abs: &Path) -> Result<String, String> {
|
||||
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
let abs_canon = abs.canonicalize().unwrap_or_else(|_| abs.to_path_buf());
|
||||
let rel = abs_canon
|
||||
.strip_prefix(&root_canon)
|
||||
.or_else(|_| abs.strip_prefix(root))
|
||||
.map_err(|_| format!("path not under sandbox root: {}", abs.display()))?;
|
||||
normalize_rel(&rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
id: &str,
|
||||
source: Option<&str>,
|
||||
path: Option<&str>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let (root, body) = with_session(id, |sess| {
|
||||
let body = if let Some(src) = source.filter(|s| !s.trim().is_empty()) {
|
||||
src.to_string()
|
||||
} else if let Some(p) = path.filter(|s| !s.is_empty()) {
|
||||
let rel = normalize_rel(p)?;
|
||||
if sess.whiteout.contains(&rel) {
|
||||
return Err(format!("sandbox_run: path whiteout: {rel}"));
|
||||
}
|
||||
if let Some(bytes) = sess.upper.get(&rel) {
|
||||
String::from_utf8(bytes.clone())
|
||||
.map_err(|e| format!("sandbox_run: path not utf-8: {e}"))?
|
||||
} else {
|
||||
let abs = abs_under_root(&sess.root, &rel)?;
|
||||
std::fs::read_to_string(&abs)
|
||||
.map_err(|e| format!("sandbox_run read {}: {e}", abs.display()))?
|
||||
}
|
||||
} else {
|
||||
return Err("sandbox_run requires `source` or `path`".into());
|
||||
};
|
||||
Ok((sess.root.clone(), body))
|
||||
})?;
|
||||
|
||||
let opts = crate::RunOptions {
|
||||
allow_fs_write: true,
|
||||
allow_exec: false,
|
||||
allow_net: false,
|
||||
allow_plugin: false,
|
||||
fs_root: Some(root),
|
||||
sandbox_session: Some(id.to_string()),
|
||||
sleep_limit_ms: Some(0),
|
||||
..crate::RunOptions::default()
|
||||
};
|
||||
|
||||
match crate::run_source(&body, &opts) {
|
||||
Ok(cap) => {
|
||||
let value = crate::host::json::value_to_json(&cap.value)
|
||||
.unwrap_or(serde_json::Value::Null);
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"value": value,
|
||||
"stdout": cap.stdout,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = e.to_string();
|
||||
Ok(json!({
|
||||
"ok": false,
|
||||
"error": msg,
|
||||
"value": null,
|
||||
"stdout": "",
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse host_query JSON args helper used from plugin.rs.
|
||||
pub fn query(name: &str, args: &serde_json::Value, ctx: &HostContext) -> Result<serde_json::Value, String> {
|
||||
let id = || {
|
||||
args.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| format!("{name}: missing `id`"))
|
||||
};
|
||||
match name {
|
||||
"sandbox_open" => {
|
||||
let root = args.get("root").and_then(|v| v.as_str());
|
||||
open(root, ctx)
|
||||
}
|
||||
"sandbox_write" => {
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "sandbox_write: missing `path`".to_string())?;
|
||||
let text = args
|
||||
.get("text")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "sandbox_write: missing `text`".to_string())?;
|
||||
write(id()?, path, text)
|
||||
}
|
||||
"sandbox_read" => {
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "sandbox_read: missing `path`".to_string())?;
|
||||
read(id()?, path)
|
||||
}
|
||||
"sandbox_remove" => {
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "sandbox_remove: missing `path`".to_string())?;
|
||||
remove(id()?, path)
|
||||
}
|
||||
"sandbox_diff" => diff(id()?),
|
||||
"sandbox_commit" => commit(id()?),
|
||||
"sandbox_discard" => discard(id()?),
|
||||
"sandbox_inspect" => inspect(id()?),
|
||||
"sandbox_run" => {
|
||||
let source = args.get("source").and_then(|v| v.as_str());
|
||||
let path = args.get("path").and_then(|v| v.as_str());
|
||||
run(id()?, source, path)
|
||||
}
|
||||
other => Err(format!("sandbox query unknown `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by fs layer when session is active — map Value path through resolve then CoW.
|
||||
pub fn try_read_value(ctx: &HostContext, path: &Value) -> Result<Option<Value>, String> {
|
||||
let rel = match path {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let abs = ctx.resolve_path(rel)?;
|
||||
match cow_read_text(ctx, &abs)? {
|
||||
Some(s) => Ok(Some(Value::Text(s))),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
//! Cryptographic token helpers for Mid M3 (`lib/secrets`).
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
fn nbytes(n: Option<&Value>) -> Result<usize, String> {
|
||||
match n {
|
||||
None | Some(Value::None) => Ok(16),
|
||||
Some(Value::Int(i)) => {
|
||||
if *i <= 0 {
|
||||
return Err("n must be positive".into());
|
||||
}
|
||||
if *i > 1024 {
|
||||
return Err("n too large (max 1024)".into());
|
||||
}
|
||||
Ok(*i as usize)
|
||||
}
|
||||
Some(_) => Err("n needs int".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_random(buf: &mut [u8]) -> Result<(), String> {
|
||||
getrandom::getrandom(buf).map_err(|e| format!("secrets: getrandom failed: {e}"))
|
||||
}
|
||||
|
||||
pub fn token_hex(n: Option<&Value>) -> Result<Value, String> {
|
||||
let len = nbytes(n)?;
|
||||
let mut buf = vec![0u8; len];
|
||||
fill_random(&mut buf)?;
|
||||
Ok(Value::Text(
|
||||
buf.iter().map(|b| format!("{b:02x}")).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
const URLSAFE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
|
||||
pub fn token_urlsafe(n: Option<&Value>) -> Result<Value, String> {
|
||||
let len = nbytes(n)?;
|
||||
let mut buf = vec![0u8; len];
|
||||
fill_random(&mut buf)?;
|
||||
// URL-safe Base64 without padding.
|
||||
let mut out = String::with_capacity((len + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= buf.len() {
|
||||
let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8) | (buf[i + 2] as u32);
|
||||
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
|
||||
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
|
||||
out.push(URLSAFE[((n >> 6) & 63) as usize] as char);
|
||||
out.push(URLSAFE[(n & 63) as usize] as char);
|
||||
i += 3;
|
||||
}
|
||||
let rem = buf.len() - i;
|
||||
if rem == 1 {
|
||||
let n = (buf[i] as u32) << 16;
|
||||
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
|
||||
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
|
||||
} else if rem == 2 {
|
||||
let n = ((buf[i] as u32) << 16) | ((buf[i + 1] as u32) << 8);
|
||||
out.push(URLSAFE[((n >> 18) & 63) as usize] as char);
|
||||
out.push(URLSAFE[((n >> 12) & 63) as usize] as char);
|
||||
out.push(URLSAFE[((n >> 6) & 63) as usize] as char);
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn token_hex_len() {
|
||||
let v = token_hex(Some(&Value::Int(8))).unwrap();
|
||||
match v {
|
||||
Value::Text(s) => assert_eq!(s.len(), 16),
|
||||
_ => panic!("expected text"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
//! Thin statistics for Mid2 M10 (`lib/stats`). Not a dataframe library.
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_nums(list: &Value) -> Result<Vec<f64>, String> {
|
||||
let Value::List(xs) = list else {
|
||||
return Err("stats: list of numbers required".into());
|
||||
};
|
||||
let mut out = Vec::with_capacity(xs.len());
|
||||
for (i, x) in xs.iter().enumerate() {
|
||||
match x {
|
||||
Value::Int(n) => out.push(*n as f64),
|
||||
Value::Num(n) => out.push(*n),
|
||||
_ => return Err(format!("stats: item {i} must be number")),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn num_val(n: f64) -> Value {
|
||||
if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) {
|
||||
Value::Int(n as i64)
|
||||
} else {
|
||||
Value::Num(n)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mean(list: &Value) -> Result<Value, String> {
|
||||
let xs = as_nums(list)?;
|
||||
if xs.is_empty() {
|
||||
return Err("stats.mean: empty list".into());
|
||||
}
|
||||
let sum: f64 = xs.iter().sum();
|
||||
Ok(Value::Num(sum / xs.len() as f64))
|
||||
}
|
||||
|
||||
pub fn median(list: &Value) -> Result<Value, String> {
|
||||
let mut xs = as_nums(list)?;
|
||||
if xs.is_empty() {
|
||||
return Err("stats.median: empty list".into());
|
||||
}
|
||||
xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let n = xs.len();
|
||||
let m = if n % 2 == 1 {
|
||||
xs[n / 2]
|
||||
} else {
|
||||
(xs[n / 2 - 1] + xs[n / 2]) / 2.0
|
||||
};
|
||||
Ok(num_val(m))
|
||||
}
|
||||
|
||||
/// Sample standard deviation (n >= 2), matching common `stdev` semantics.
|
||||
pub fn stdev(list: &Value) -> Result<Value, String> {
|
||||
let xs = as_nums(list)?;
|
||||
if xs.len() < 2 {
|
||||
return Err("stats.stdev: need at least 2 values".into());
|
||||
}
|
||||
let n = xs.len() as f64;
|
||||
let mean = xs.iter().sum::<f64>() / n;
|
||||
let var = xs.iter().map(|x| {
|
||||
let d = x - mean;
|
||||
d * d
|
||||
}).sum::<f64>()
|
||||
/ (n - 1.0);
|
||||
Ok(Value::Num(var.sqrt()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn basic() {
|
||||
let xs = Value::List(vec![
|
||||
Value::Int(1),
|
||||
Value::Int(2),
|
||||
Value::Int(3),
|
||||
Value::Int(4),
|
||||
]);
|
||||
let m = mean(&xs).unwrap();
|
||||
assert_eq!(m, Value::Num(2.5));
|
||||
assert_eq!(median(&xs).unwrap(), Value::Num(2.5));
|
||||
let s = stdev(&xs).unwrap();
|
||||
let Value::Num(v) = s else { panic!() };
|
||||
assert!((v - 1.2909944487358056).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
//! Concurrent subtasks: OS file children, in-process functions, foreign subprocesses.
|
||||
//! Parent `HostContext` drop kills/waits file & foreign children; function threads detach.
|
||||
//!
|
||||
//! Quiet file children get `MARQDO_EVENT_FORWARD` so LLM stream events published in the
|
||||
//! child process are tailed into the parent EventBus while `wait` blocks (view SSE).
|
||||
|
||||
use crate::host::as_text;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Cap for file-child stdout/stderr returned on `wait` (parent observation).
|
||||
const FILE_IO_CAP: usize = 8 * 1024;
|
||||
|
||||
use crate::host::foreign;
|
||||
use crate::host::HostContext;
|
||||
use crate::interp::Interpreter;
|
||||
use crate::load::load_module;
|
||||
use crate::value::{CodeBlock, Value};
|
||||
|
||||
/// Stored subtask handle (tagged by spawn kind).
|
||||
pub(crate) enum Handle {
|
||||
File(FileTask),
|
||||
Foreign(ForeignTask),
|
||||
Function(FunctionTask),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Handle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Handle::File(_) => f.write_str("Subtask::File"),
|
||||
Handle::Foreign(_) => f.write_str("Subtask::Foreign"),
|
||||
Handle::Function(_) => f.write_str("Subtask::Function"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FileTask {
|
||||
child: Child,
|
||||
result_path: PathBuf,
|
||||
/// NDJSON path the child appends EventBus frames to (`MARQDO_EVENT_FORWARD`).
|
||||
events_path: Option<PathBuf>,
|
||||
/// Stops the parent-side tailer that republishes child events.
|
||||
forward_stop: Option<Arc<AtomicBool>>,
|
||||
forward: Option<JoinHandle<()>>,
|
||||
/// Present when `quiet=True` (piped capture). Absent when inheriting TTY.
|
||||
stdout: Option<JoinHandle<String>>,
|
||||
stderr: Option<JoinHandle<String>>,
|
||||
}
|
||||
|
||||
fn stop_event_forward(task: &mut FileTask) {
|
||||
if let Some(stop) = task.forward_stop.take() {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
if let Some(h) = task.forward.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
if let Some(p) = task.events_path.take() {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tail `MARQDO_EVENT_FORWARD` NDJSON and republish onto the parent bus with `source=child`.
|
||||
fn spawn_event_forwarder(path: PathBuf, stop: Arc<AtomicBool>) -> JoinHandle<()> {
|
||||
thread::spawn(move || {
|
||||
let mut pos: u64 = 0;
|
||||
let mut carry = String::new();
|
||||
loop {
|
||||
let done = stop.load(Ordering::SeqCst);
|
||||
if let Ok(mut f) = std::fs::File::open(&path) {
|
||||
if f.seek(SeekFrom::Start(pos)).is_ok() {
|
||||
let mut buf = String::new();
|
||||
if f.read_to_string(&mut buf).is_ok() && !buf.is_empty() {
|
||||
pos += buf.len() as u64;
|
||||
carry.push_str(&buf);
|
||||
while let Some(idx) = carry.find('\n') {
|
||||
let line = carry[..idx].trim().to_string();
|
||||
carry.drain(..=idx);
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
republish_child_event(&line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if done {
|
||||
if !carry.is_empty() {
|
||||
let line = carry.trim();
|
||||
if !line.is_empty() {
|
||||
republish_child_event(line);
|
||||
}
|
||||
carry.clear();
|
||||
}
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(16));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn republish_child_event(line: &str) {
|
||||
let Ok(mut v) = serde_json::from_str::<serde_json::Value>(line) else {
|
||||
return;
|
||||
};
|
||||
// Skip nested terminal frames — parent owns run lifecycle.
|
||||
if v.get("type").and_then(|t| t.as_str()) == Some("done") && v.get("run_id").is_none() {
|
||||
return;
|
||||
}
|
||||
if let Some(obj) = v.as_object_mut() {
|
||||
obj.insert("source".into(), serde_json::json!("child"));
|
||||
}
|
||||
crate::host::event_bus::EventBus::global().publish_json(&v.to_string());
|
||||
}
|
||||
|
||||
pub(crate) struct ForeignTask {
|
||||
child: Child,
|
||||
temp_script: PathBuf,
|
||||
stdout: JoinHandle<(String, bool)>,
|
||||
stderr: JoinHandle<(String, bool)>,
|
||||
}
|
||||
|
||||
enum FnState {
|
||||
Running,
|
||||
Done(Value),
|
||||
Failed(String),
|
||||
Killed,
|
||||
}
|
||||
|
||||
pub(crate) struct FunctionTask {
|
||||
state: Arc<Mutex<FnState>>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
|
||||
fn as_code(v: &Value) -> Result<&CodeBlock, String> {
|
||||
match v {
|
||||
Value::Code(c) => Ok(c),
|
||||
_ => Err("code must be a bound ```lang fence value".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_text(v: Option<&Value>) -> Result<Option<&str>, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(None),
|
||||
Some(v) => Ok(Some(as_text(v, "value")?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_set(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None => false,
|
||||
Some(Value::None) => false,
|
||||
Some(Value::Text(s)) if s.is_empty() => false,
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn child_id(id: &Value) -> Result<u64, String> {
|
||||
match id {
|
||||
Value::Int(n) if *n > 0 => Ok(*n as u64),
|
||||
_ => Err("subtask id must be positive int".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_id(ctx: &mut HostContext) -> u64 {
|
||||
ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1);
|
||||
ctx.subtask_seq
|
||||
}
|
||||
|
||||
fn status_map(status: &str, extra: Vec<(String, Value)>) -> Value {
|
||||
let mut pairs = vec![("status".into(), Value::Text(status.into()))];
|
||||
pairs.extend(extra);
|
||||
Value::Map(pairs)
|
||||
}
|
||||
|
||||
fn fn_args_from_value(args: Option<&Value>) -> Result<Vec<(String, Value)>, String> {
|
||||
let Some(args) = args else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
match args {
|
||||
Value::None => Ok(Vec::new()),
|
||||
Value::Map(pairs) => Ok(pairs.clone()),
|
||||
Value::List(items) => {
|
||||
let mut out = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
out.push((format!("arg{i}"), item.clone()));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
other => Err(format!(
|
||||
"fn args must be map or list, got {}",
|
||||
other.as_display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill_all(ctx: &mut HostContext) {
|
||||
for (_, handle) in ctx.subtasks.drain() {
|
||||
match handle {
|
||||
Handle::File(mut task) => {
|
||||
let _ = task.child.kill();
|
||||
let _ = task.child.wait();
|
||||
stop_event_forward(&mut task);
|
||||
if let Some(h) = task.stdout.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
if let Some(h) = task.stderr.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
let _ = std::fs::remove_file(&task.result_path);
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
let _ = task.child.kill();
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
let _ = task.stdout.join();
|
||||
let _ = task.stderr.join();
|
||||
}
|
||||
Handle::Function(mut task) => {
|
||||
// Join so fire-and-forget writers (e.g. agent writeback) finish before exit.
|
||||
if let Some(h) = task.handle.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(ctx: &mut HostContext, bound: &HashMap<String, Value>) -> Result<Value, String> {
|
||||
let has_path = is_set(bound.get("path"));
|
||||
let has_fn = is_set(bound.get("fn"));
|
||||
let has_code = is_set(bound.get("code"));
|
||||
let has_lang = is_set(bound.get("lang")) && is_set(bound.get("source"));
|
||||
let kinds = [has_path, has_fn, has_code, has_lang]
|
||||
.into_iter()
|
||||
.filter(|b| *b)
|
||||
.count();
|
||||
if kinds != 1 {
|
||||
return Err(
|
||||
"spawn: specify exactly one of path=, fn=, code=, or lang=+source=".into(),
|
||||
);
|
||||
}
|
||||
if has_path {
|
||||
spawn_file(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
bound.get("args"),
|
||||
bound.get("quiet"),
|
||||
)
|
||||
} else if has_fn {
|
||||
spawn_fn(ctx, require(bound, "fn")?, bound.get("args"))
|
||||
} else if has_code {
|
||||
spawn_code(ctx, require(bound, "code")?, bound.get("stdin"))
|
||||
} else {
|
||||
spawn_lang(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_file(
|
||||
ctx: &mut HostContext,
|
||||
path: &Value,
|
||||
args: Option<&Value>,
|
||||
quiet: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let rel = as_text(path, "path")?;
|
||||
let joined = if std::path::Path::new(rel).is_absolute() {
|
||||
std::path::PathBuf::from(rel)
|
||||
} else {
|
||||
ctx.cwd.join(rel)
|
||||
};
|
||||
// Absolutize so the child `for_run` cwd/parent resolution does not double-prefix
|
||||
// a relative path like `tests/ext/.marqdo/...` when current_dir is already `tests/ext`.
|
||||
let file = std::fs::canonicalize(&joined).unwrap_or_else(|_| {
|
||||
if joined.is_absolute() {
|
||||
joined.clone()
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| std::path::PathBuf::from("."))
|
||||
.join(&joined)
|
||||
}
|
||||
});
|
||||
let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?;
|
||||
let id = next_id(ctx);
|
||||
let result_path = std::env::temp_dir().join(format!(
|
||||
"marqdo-subtask-{}-{}.json",
|
||||
std::process::id(),
|
||||
id
|
||||
));
|
||||
let mut cmd = Command::new(&exe);
|
||||
cmd.arg("run").arg(&file);
|
||||
if !ctx.caps.fs_write { cmd.arg("--deny-fs-write"); }
|
||||
if !ctx.caps.exec { cmd.arg("--deny-exec"); }
|
||||
if !ctx.caps.net { cmd.arg("--deny-net"); }
|
||||
if !ctx.caps.plugin { cmd.arg("--deny-plugin"); }
|
||||
if let Some(root) = &ctx.fs_root { cmd.arg("--fs-root").arg(root); }
|
||||
cmd.arg("--emit-result").arg(&result_path);
|
||||
cmd.current_dir(&ctx.cwd);
|
||||
cmd.stdin(Stdio::null());
|
||||
let quiet = match quiet {
|
||||
None | Some(Value::None) => true,
|
||||
Some(v) => v.truthy(),
|
||||
};
|
||||
// quiet: pipe-capture for parent observation (no TTY noise).
|
||||
// !quiet: inherit parent TTY; wait map omits stdout/stderr bodies.
|
||||
if quiet {
|
||||
cmd.stdout(Stdio::piped());
|
||||
cmd.stderr(Stdio::piped());
|
||||
} else {
|
||||
cmd.stdout(Stdio::inherit());
|
||||
cmd.stderr(Stdio::inherit());
|
||||
}
|
||||
if let Some(Value::List(items)) = args {
|
||||
for item in items {
|
||||
cmd.arg(as_text(item, "arg")?);
|
||||
}
|
||||
}
|
||||
// Bridge child EventBus → parent while wait blocks (view SSE / concurrent progress).
|
||||
let events_path = std::env::temp_dir().join(format!(
|
||||
"marqdo-events-{}-{}.ndjson",
|
||||
std::process::id(),
|
||||
id
|
||||
));
|
||||
let _ = std::fs::write(&events_path, "");
|
||||
cmd.env("MARQDO_EVENT_FORWARD", &events_path);
|
||||
apply_run_selection_env(&mut cmd);
|
||||
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
|
||||
let (stdout, stderr) = if quiet {
|
||||
let mut stdout_pipe = child.stdout.take();
|
||||
let mut stderr_pipe = child.stderr.take();
|
||||
let stdout = thread::spawn(move || {
|
||||
stdout_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
let stderr = thread::spawn(move || {
|
||||
stderr_pipe.as_mut().map(capture_file_io).unwrap_or_default()
|
||||
});
|
||||
(Some(stdout), Some(stderr))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let forward_stop = Arc::new(AtomicBool::new(false));
|
||||
let forward = spawn_event_forwarder(events_path.clone(), Arc::clone(&forward_stop));
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::File(FileTask {
|
||||
child,
|
||||
result_path,
|
||||
events_path: Some(events_path),
|
||||
forward_stop: Some(forward_stop),
|
||||
forward: Some(forward),
|
||||
stdout,
|
||||
stderr,
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
fn spawn_fn(
|
||||
ctx: &mut HostContext,
|
||||
name: &Value,
|
||||
args: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let name = as_text(name, "fn")?.to_string();
|
||||
let call_args = fn_args_from_value(args)?;
|
||||
let module_path = ctx
|
||||
.entry_path
|
||||
.clone()
|
||||
.ok_or_else(|| "subtask fn: no entry module (run a .mq.md file first)".to_string())?;
|
||||
let cwd = ctx.cwd.clone();
|
||||
let caps = ctx.caps.clone();
|
||||
let foreign_cmds = ctx.foreign_cmds.clone();
|
||||
let foreign_specs = ctx.foreign_specs.clone();
|
||||
let foreign_config_specs = ctx.foreign_config_specs.clone();
|
||||
let foreign_config_loaded = ctx.foreign_config_loaded;
|
||||
let fs_root = ctx.fs_root.clone();
|
||||
let argv = ctx.argv.clone();
|
||||
|
||||
let state = Arc::new(Mutex::new(FnState::Running));
|
||||
let state_bg = Arc::clone(&state);
|
||||
let handle = thread::spawn(move || {
|
||||
let result = (|| -> Result<Value, String> {
|
||||
let module = load_module(&module_path).map_err(|e| e.to_string())?;
|
||||
let source = std::fs::read_to_string(&module_path)
|
||||
.map_err(|e| format!("subtask fn: read {}: {e}", module_path.display()))?;
|
||||
let mut host = HostContext::for_capture(Some(&module_path), caps);
|
||||
host.cwd = cwd;
|
||||
host.fs_root = fs_root;
|
||||
host.argv = argv;
|
||||
host.foreign_cmds = foreign_cmds;
|
||||
host.foreign_specs = foreign_specs;
|
||||
host.foreign_config_specs = foreign_config_specs;
|
||||
host.foreign_config_loaded = foreign_config_loaded;
|
||||
host.set_entry_source(Some(&module_path), &source);
|
||||
host.entry_metadata = module.metadata.clone();
|
||||
let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host);
|
||||
interp
|
||||
.invoke_function(&module, &name, &call_args)
|
||||
.map_err(|e| e.to_string())
|
||||
})();
|
||||
if let Ok(mut st) = state_bg.lock() {
|
||||
if !matches!(*st, FnState::Killed) {
|
||||
*st = match result {
|
||||
Ok(v) => FnState::Done(v),
|
||||
Err(e) => FnState::Failed(e),
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::Function(FunctionTask {
|
||||
state,
|
||||
handle: Some(handle),
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
fn spawn_code(
|
||||
ctx: &mut HostContext,
|
||||
code: &Value,
|
||||
stdin: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let block = as_code(code)?;
|
||||
let stdin = opt_text(stdin)?;
|
||||
spawn_foreign(ctx, &block.lang, &block.source, stdin)
|
||||
}
|
||||
|
||||
fn spawn_lang(
|
||||
ctx: &mut HostContext,
|
||||
lang: &Value,
|
||||
source: &Value,
|
||||
stdin: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let lang = as_text(lang, "lang")?;
|
||||
let source = as_text(source, "source")?;
|
||||
let stdin = opt_text(stdin)?;
|
||||
spawn_foreign(ctx, lang, source, stdin)
|
||||
}
|
||||
|
||||
fn spawn_foreign(
|
||||
ctx: &mut HostContext,
|
||||
lang: &str,
|
||||
source: &str,
|
||||
stdin: Option<&str>,
|
||||
) -> Result<Value, String> {
|
||||
let spawned = foreign::spawn_source(ctx, lang, source, stdin)?;
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::Foreign(ForeignTask {
|
||||
child: spawned.child,
|
||||
temp_script: spawned.script_path,
|
||||
stdout: spawned.stdout,
|
||||
stderr: spawned.stderr,
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(task) => poll_child(&mut task.child),
|
||||
Handle::Foreign(task) => poll_child(&mut task.child),
|
||||
Handle::Function(task) => poll_function(&task.state),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_child(child: &mut Child) -> Result<Value, String> {
|
||||
match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? {
|
||||
None => Ok(status_map("running", vec![])),
|
||||
Some(status) => {
|
||||
let code = status.code().unwrap_or(-1);
|
||||
let st = if status.success() { "done" } else { "failed" };
|
||||
Ok(status_map(
|
||||
st,
|
||||
vec![("code".into(), Value::Int(code as i64))],
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_function(state: &Arc<Mutex<FnState>>) -> Result<Value, String> {
|
||||
let st = state
|
||||
.lock()
|
||||
.map_err(|_| "subtask fn: lock poisoned".to_string())?;
|
||||
match &*st {
|
||||
FnState::Running => Ok(status_map("running", vec![])),
|
||||
FnState::Done(v) => Ok(status_map(
|
||||
"done",
|
||||
vec![("value".into(), v.clone())],
|
||||
)),
|
||||
FnState::Failed(e) => Ok(status_map(
|
||||
"failed",
|
||||
vec![("error".into(), Value::Text(e.clone()))],
|
||||
)),
|
||||
FnState::Killed => Ok(status_map("failed", vec![("error".into(), Value::Text("killed".into()))])),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(mut task) => {
|
||||
// Forwarder runs concurrently while we block on the OS child.
|
||||
let status = task
|
||||
.child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask join: {e}"))?;
|
||||
stop_event_forward(&mut task);
|
||||
let code = status.code().unwrap_or(-1) as i64;
|
||||
let value = read_emitted_result(&task.result_path);
|
||||
let _ = std::fs::remove_file(&task.result_path);
|
||||
let stdout = task
|
||||
.stdout
|
||||
.take()
|
||||
.map(|h| h.join().unwrap_or_default())
|
||||
.unwrap_or_default();
|
||||
let stderr = task
|
||||
.stderr
|
||||
.take()
|
||||
.map(|h| h.join().unwrap_or_default())
|
||||
.unwrap_or_default();
|
||||
let mut pairs = vec![
|
||||
("code".into(), Value::Int(code)),
|
||||
("value".into(), value),
|
||||
];
|
||||
if !stdout.is_empty() {
|
||||
pairs.push(("stdout".into(), Value::Text(clip_io(&stdout))));
|
||||
}
|
||||
if !stderr.is_empty() {
|
||||
pairs.push(("stderr".into(), Value::Text(clip_io(&stderr))));
|
||||
}
|
||||
Ok(Value::Map(pairs))
|
||||
}
|
||||
Handle::Foreign(task) => join_foreign(task),
|
||||
Handle::Function(task) => join_function(task),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_emitted_result(path: &PathBuf) -> Value {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => match serde_json::from_str::<serde_json::Value>(text.trim()) {
|
||||
Ok(j) => crate::host::json::json_to_value(&j).unwrap_or(Value::None),
|
||||
Err(_) => Value::None,
|
||||
},
|
||||
Err(_) => Value::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
|
||||
let status = task
|
||||
.child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask foreign join: {e}"))?;
|
||||
let (stdout, out_trunc) = task.stdout.join().unwrap_or_default();
|
||||
let (stderr, err_trunc) = task.stderr.join().unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
if !status.success() {
|
||||
let code = status.code().unwrap_or(1);
|
||||
let mut msg = format!("subtask foreign failed (exit={code})");
|
||||
if !stderr.trim().is_empty() {
|
||||
msg.push_str(": ");
|
||||
msg.push_str(stderr.trim());
|
||||
}
|
||||
return Err(msg);
|
||||
}
|
||||
let mut out = stdout;
|
||||
if out.ends_with('\n') {
|
||||
out.pop();
|
||||
if out.ends_with('\r') {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
if out_trunc || err_trunc {
|
||||
out.push_str("\n…(truncated)");
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
fn join_function(mut task: FunctionTask) -> Result<Value, String> {
|
||||
if let Some(handle) = task.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
let st = task
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| "subtask fn: lock poisoned".to_string())?;
|
||||
match &*st {
|
||||
FnState::Done(v) => Ok(v.clone()),
|
||||
FnState::Failed(e) => Err(e.clone()),
|
||||
FnState::Killed => Err("subtask fn killed".into()),
|
||||
FnState::Running => Err("subtask fn still running".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(id)?;
|
||||
let handle = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(mut task) => {
|
||||
task.child
|
||||
.kill()
|
||||
.map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = task.child.wait();
|
||||
stop_event_forward(&mut task);
|
||||
if let Some(h) = task.stdout.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
if let Some(h) = task.stderr.take() {
|
||||
let _ = h.join();
|
||||
}
|
||||
let _ = std::fs::remove_file(&task.result_path);
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
task.child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
let _ = task.stdout.join();
|
||||
let _ = task.stderr.join();
|
||||
}
|
||||
Handle::Function(mut task) => {
|
||||
if let Ok(mut st) = task.state.lock() {
|
||||
if matches!(*st, FnState::Running) {
|
||||
*st = FnState::Killed;
|
||||
}
|
||||
}
|
||||
drop(task.handle.take());
|
||||
}
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
let ids: Vec<u64> = ctx.subtasks.keys().copied().collect();
|
||||
let mut results = Vec::new();
|
||||
for id in ids {
|
||||
results.push(join(ctx, &Value::Int(id as i64))?);
|
||||
}
|
||||
Ok(Value::List(results))
|
||||
}
|
||||
|
||||
fn capture_file_io(reader:&mut impl Read)->String {
|
||||
let mut kept=Vec::new(); let mut buffer=[0u8;8192];
|
||||
loop { match reader.read(&mut buffer) {
|
||||
Ok(0)|Err(_)=>break,
|
||||
Ok(n)=>{ let take=(FILE_IO_CAP+4-kept.len()).min(n);kept.extend_from_slice(&buffer[..take]); }
|
||||
}}
|
||||
clip_io(&String::from_utf8_lossy(&kept))
|
||||
}
|
||||
|
||||
/// Timeout leaves the handle available unless cancel=True. Process cancellation
|
||||
/// reaps the OS child; function-thread cancellation is logical, as in kill().
|
||||
pub(super) fn wait_timeout(ctx:&mut HostContext,id:&Value,timeout_ms:u64,cancel:bool)->Result<Value,String>{
|
||||
let start=std::time::Instant::now();
|
||||
loop{
|
||||
let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{return join(ctx,id)}
|
||||
if start.elapsed()>=Duration::from_millis(timeout_ms){if cancel{kill(ctx,id)?;}return Err("timed_out: subtask wait deadline exceeded".into())}
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
pub(super) fn run_many(ctx:&mut HostContext,tasks:&Value,limit:usize,timeout_ms:u64)->Result<Value,String>{
|
||||
let Value::List(tasks)=tasks else{return Err("tasks must be record list".into())};
|
||||
if !(1..=64).contains(&limit){return Err("limit must be 1..64".into())}
|
||||
if tasks.len()>10000{return Err("batch exceeds 10000 tasks".into())}
|
||||
// Validate the entire batch before starting any process.
|
||||
let jobs=tasks.iter().map(|task|{let Value::Map(fields)=task else{return Err("task must contain path and optional args".to_string())};
|
||||
let mut job=HashMap::new();for (key,value) in fields{if !matches!(key.as_str(),"path"|"args"){return Err(format!("unsupported batch field {key}"))}job.insert(key.clone(),value.clone());}
|
||||
let path=job.get("path").ok_or("task missing path")?;ctx.resolve_path(as_text(path,"path")?)?;Ok(job)
|
||||
}).collect::<Result<Vec<_>,String>>()?;
|
||||
let mut active:Vec<(usize,Value,std::time::Instant)>=Vec::new();let mut next=0;let mut out=vec![Value::None;jobs.len()];
|
||||
while next<jobs.len()||!active.is_empty(){
|
||||
while next<jobs.len()&&active.len()<limit{
|
||||
match spawn(ctx,&jobs[next]){Ok(id)=>active.push((next,id,std::time::Instant::now())),Err(error)=>out[next]=super::result::capture("subtask.run_many",Err(error))};next+=1;
|
||||
}
|
||||
let mut i=0;
|
||||
while i<active.len(){
|
||||
let (_,id,start)=&active[i];let status=poll(ctx,id)?;
|
||||
let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into())));
|
||||
if !running{let(index,id,_)=active.remove(i);out[index]=super::result::capture("subtask.run_many",join(ctx,&id));}
|
||||
else if start.elapsed()>=Duration::from_millis(timeout_ms){let(index,id,_)=active.remove(i);let _=kill(ctx,&id);out[index]=super::result::capture("subtask.run_many",Err("timed_out: batch task deadline exceeded".into()));}
|
||||
else{i+=1;}
|
||||
}
|
||||
if !active.is_empty(){thread::sleep(Duration::from_millis(5));}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
fn clip_io(s: &str) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(FILE_IO_CAP).collect();
|
||||
if it.next().is_some() {
|
||||
format!("{head}\n…(truncated)")
|
||||
} else {
|
||||
head
|
||||
}
|
||||
}
|
||||
|
||||
fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value, String> {
|
||||
bound
|
||||
.get(key)
|
||||
.ok_or_else(|| format!("host call missing `{key}`"))
|
||||
}
|
||||
|
||||
/// Propagate run/selection identity onto the *child* Command.env map.
|
||||
/// Reads parent env only as a fallback when an explicit RunContext was not
|
||||
/// applied; never uses parent `setenv`/`set_current_dir` as request state (M-R1).
|
||||
fn apply_run_selection_env(cmd: &mut Command) {
|
||||
for key in [
|
||||
"MARQDO_RUN_ID",
|
||||
"MARQDO_PARENT_RUN_ID",
|
||||
"MARQDO_TURN_ID",
|
||||
"MARQDO_WORKSPACE_SCOPE",
|
||||
"MARQDO_CANCEL_TOKEN",
|
||||
"MARQDO_EVENT_FORWARD",
|
||||
"MARQDO_USAGE_SINK",
|
||||
"MARQDO_CREDENTIAL_REF",
|
||||
"MARQDO_WORKSPACE_ID",
|
||||
"MARQDO_SNAPSHOT_ID",
|
||||
"MARQDO_LEASE_ID",
|
||||
"MARQDO_ATTEMPT_ID",
|
||||
"MARQDO_LLM_MODEL",
|
||||
"MARQDO_LLM_BASE_URL",
|
||||
"OPENAI_MODEL",
|
||||
"OPENAI_BASE_URL",
|
||||
] {
|
||||
if let Ok(v) = std::env::var(key) {
|
||||
cmd.env(key, v);
|
||||
}
|
||||
}
|
||||
// Do not forward process-global MARQDO_CANCEL into children — request cancel
|
||||
// must use MARQDO_CANCEL_TOKEN so leases stay isolated.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn f02_apply_run_selection_env_forwards_parent_identity() {
|
||||
std::env::set_var("MARQDO_RUN_ID", "run-parent");
|
||||
std::env::set_var("OPENAI_MODEL", "child-model");
|
||||
std::env::set_var("OPENAI_BASE_URL", "http://127.0.0.1:7010");
|
||||
// Must never require writing secrets into child env map for selection.
|
||||
std::env::remove_var("OPENAI_API_KEY");
|
||||
|
||||
let mut cmd = Command::new("true");
|
||||
apply_run_selection_env(&mut cmd);
|
||||
// Command doesn't expose env for inspection portably; re-check via helper contract:
|
||||
let keys: HashMap<&str, String> = [
|
||||
"MARQDO_RUN_ID",
|
||||
"OPENAI_MODEL",
|
||||
"OPENAI_BASE_URL",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|k| std::env::var(k).ok().map(|v| (k, v)))
|
||||
.collect();
|
||||
assert_eq!(keys.get("MARQDO_RUN_ID").map(String::as_str), Some("run-parent"));
|
||||
assert_eq!(keys.get("OPENAI_MODEL").map(String::as_str), Some("child-model"));
|
||||
assert_eq!(
|
||||
keys.get("OPENAI_BASE_URL").map(String::as_str),
|
||||
Some("http://127.0.0.1:7010")
|
||||
);
|
||||
|
||||
std::env::remove_var("MARQDO_RUN_ID");
|
||||
std::env::remove_var("OPENAI_MODEL");
|
||||
std::env::remove_var("OPENAI_BASE_URL");
|
||||
let _ = cmd; // ensure apply didn't panic
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f02_agent_skeleton_has_no_llm_llm() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let agent = std::fs::read_to_string(root.join("ext/ai/agent.mq.md")).unwrap();
|
||||
assert!(
|
||||
!agent.contains("llm.llm"),
|
||||
"render_workbook_skeleton must not hardcode llm.llm"
|
||||
);
|
||||
assert!(
|
||||
agent.contains("llm.create") && agent.contains("OPENAI_MODEL"),
|
||||
"skeleton should create model from env selection"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
|
||||
|
||||
use crate::host::HostContext;
|
||||
|
||||
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Handle;
|
||||
|
||||
pub fn kill_all(_ctx: &mut HostContext) {}
|
||||
-239
@@ -1,239 +0,0 @@
|
||||
//! System / process host primitives.
|
||||
|
||||
use crate::host::as_text;
|
||||
#[cfg(feature = "exec-host")]
|
||||
use std::process::Command;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn env_get(name: &Value) -> Result<Value, String> {
|
||||
let key = as_text(name, "name")?;
|
||||
Ok(match std::env::var(key) {
|
||||
Ok(v) => Value::Text(v),
|
||||
Err(_) => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
|
||||
let key = as_text(name, "name")?;
|
||||
let val = as_text(value, "value")?;
|
||||
std::env::set_var(key, val);
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// Load KEY=VALUE pairs from a `.env` file into the process environment.
|
||||
/// Existing variables are **not** overridden. Default path: `.env` under host cwd.
|
||||
pub fn dotenv_load(ctx: &HostContext, path: Option<&Value>) -> Result<Value, String> {
|
||||
let rel = match path {
|
||||
None | Some(Value::None) => ".env".to_string(),
|
||||
Some(v) => as_text(v, "path")?.to_string(),
|
||||
};
|
||||
let file = if std::path::Path::new(&rel).is_absolute() {
|
||||
std::path::PathBuf::from(&rel)
|
||||
} else {
|
||||
ctx.cwd.join(&rel)
|
||||
};
|
||||
let text = match std::fs::read_to_string(&file) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Int(0)),
|
||||
Err(e) => {
|
||||
return Err(format!("dotenv_load {}: {e}", file.display()));
|
||||
}
|
||||
};
|
||||
let mut loaded = 0i64;
|
||||
for raw in text.lines() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let line = line.strip_prefix("export ").unwrap_or(line).trim();
|
||||
let Some((k, v)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let key = k.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if std::env::var_os(key).is_some() {
|
||||
continue;
|
||||
}
|
||||
let mut val = v.trim();
|
||||
if (val.starts_with('"') && val.ends_with('"'))
|
||||
|| (val.starts_with('\'') && val.ends_with('\''))
|
||||
{
|
||||
val = &val[1..val.len() - 1];
|
||||
}
|
||||
std::env::set_var(key, val);
|
||||
loaded += 1;
|
||||
}
|
||||
Ok(Value::Int(loaded))
|
||||
}
|
||||
|
||||
pub fn args(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::List(
|
||||
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn cwd(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::Text(ctx.cwd.display().to_string()))
|
||||
}
|
||||
|
||||
/// Bound entry Artifact Metadata (map).
|
||||
pub fn meta(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(Value::Map(ctx.entry_metadata.clone()))
|
||||
}
|
||||
|
||||
/// Lookup one metadata key; missing → None.
|
||||
pub fn meta_get(ctx: &HostContext, key: &Value) -> Result<Value, String> {
|
||||
let k = as_text(key, "key")?;
|
||||
Ok(ctx
|
||||
.entry_metadata
|
||||
.iter()
|
||||
.find(|(name, _)| name == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap_or(Value::None))
|
||||
}
|
||||
|
||||
/// Classify entry Artifact (`web` / `endpoint` / `prompt` / `other`); missing type → None.
|
||||
pub fn artifact_kind(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(match crate::artifact::classify(&ctx.entry_metadata) {
|
||||
None => Value::None,
|
||||
Some(crate::artifact::ArtifactKind::Web) => Value::Text("web".into()),
|
||||
Some(crate::artifact::ArtifactKind::Endpoint) => Value::Text("endpoint".into()),
|
||||
Some(crate::artifact::ArtifactKind::Prompt) => Value::Text("prompt".into()),
|
||||
Some(crate::artifact::ArtifactKind::Other) => Value::Text("other".into()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
|
||||
let c = as_i64(code, "code")?;
|
||||
if ctx.soft_side_effects {
|
||||
return Err(format!("exit {c} (soft mode does not terminate process)"));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err(format!("exit {c} unavailable in browser wasm"));
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::process::exit(c as i32);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exec(
|
||||
ctx: &HostContext,
|
||||
cmd: &Value,
|
||||
args: Option<&Value>,
|
||||
capture: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, cmd, args, capture);
|
||||
return Err("exec unavailable in browser wasm".into());
|
||||
}
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
use std::process::Stdio;
|
||||
if !ctx.allow_exec() {
|
||||
if ctx.sandbox_session.is_some() {
|
||||
return Err("exec unavailable in sandbox".into());
|
||||
}
|
||||
return Err("exec denied by host policy".into());
|
||||
}
|
||||
let cmd = as_text(cmd, "cmd")?;
|
||||
let capture = match capture {
|
||||
None | Some(Value::None) => false,
|
||||
Some(v) => crate::host::math::as_bool(v),
|
||||
};
|
||||
let mut command = Command::new(cmd);
|
||||
command.current_dir(&ctx.cwd);
|
||||
match args {
|
||||
None | Some(Value::None) => {}
|
||||
Some(Value::List(xs)) => {
|
||||
for x in xs {
|
||||
command.arg(x.as_display());
|
||||
}
|
||||
}
|
||||
Some(Value::Text(s)) => {
|
||||
command.arg(s);
|
||||
}
|
||||
Some(_) => return Err("exec args must be list or text".into()),
|
||||
}
|
||||
if capture {
|
||||
command.stdout(Stdio::piped());
|
||||
command.stderr(Stdio::piped());
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
|
||||
let code = output.status.code().unwrap_or(1) as i64;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
Ok(Value::Map(vec![
|
||||
("code".into(), Value::Int(code)),
|
||||
("stdout".into(), Value::Text(clip_exec_io(&stdout))),
|
||||
("stderr".into(), Value::Text(clip_exec_io(&stderr))),
|
||||
]))
|
||||
} else {
|
||||
let status = command
|
||||
.status()
|
||||
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(1) as i64))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const EXEC_IO_CAP: usize = 256 * 1024;
|
||||
|
||||
fn clip_exec_io(s: &str) -> String {
|
||||
let mut it = s.chars();
|
||||
let head: String = it.by_ref().take(EXEC_IO_CAP).collect();
|
||||
if it.next().is_some() {
|
||||
format!("{head}\n…(truncated)")
|
||||
} else {
|
||||
head
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::host::HostContext;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn dotenv_loads_without_override() {
|
||||
let dir = std::env::temp_dir().join(format!("marqdo-dotenv-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("sample.env");
|
||||
{
|
||||
let mut f = std::fs::File::create(&path).unwrap();
|
||||
writeln!(f, "# comment").unwrap();
|
||||
writeln!(f, "MARQDO_DOTENV_A=one").unwrap();
|
||||
writeln!(f, "export MARQDO_DOTENV_B=\"two\"").unwrap();
|
||||
}
|
||||
std::env::set_var("MARQDO_DOTENV_A", "keep");
|
||||
std::env::remove_var("MARQDO_DOTENV_B");
|
||||
let mut ctx = HostContext::default();
|
||||
ctx.cwd = dir.clone();
|
||||
let n = dotenv_load(&ctx, Some(&Value::Text("sample.env".into()))).unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(std::env::var("MARQDO_DOTENV_A").unwrap(), "keep");
|
||||
assert_eq!(std::env::var("MARQDO_DOTENV_B").unwrap(), "two");
|
||||
assert_eq!(
|
||||
dotenv_load(&ctx, Some(&Value::Text("missing.env".into()))).unwrap(),
|
||||
Value::Int(0)
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
//! Bounded orchestration over existing subtask resources.
|
||||
use crate::{
|
||||
host::{HostContext, HostFn},
|
||||
value::Value,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "exec-host")]
|
||||
fn arg<'a>(b: &'a HashMap<String, Value>, k: &str) -> Result<&'a Value, String> {
|
||||
b.get(k).ok_or_else(|| format!("missing {k}"))
|
||||
}
|
||||
pub(super) fn call(
|
||||
ctx: &mut HostContext,
|
||||
id: HostFn,
|
||||
b: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
fn integer(b: &HashMap<String, Value>, key: &str) -> Result<u64, String> {
|
||||
match arg(b, key)? {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as u64),
|
||||
_ => Err(format!("{key} must be nonnegative integer")),
|
||||
}
|
||||
}
|
||||
match id {
|
||||
HostFn::SubtaskWaitTimeout => {
|
||||
let answer = super::subtask::wait_timeout(
|
||||
ctx,
|
||||
arg(b, "id")?,
|
||||
integer(b, "timeout_ms")?,
|
||||
matches!(b.get("cancel"), Some(Value::Bool(true))),
|
||||
);
|
||||
Ok(super::result::capture("subtask.wait_timeout", answer))
|
||||
}
|
||||
HostFn::SubtaskCancelAll => {
|
||||
let count = ctx.subtasks.len();
|
||||
super::subtask::kill_all(ctx);
|
||||
Ok(Value::Int(count as i64))
|
||||
}
|
||||
HostFn::SubtaskRunMany => super::subtask::run_many(
|
||||
ctx,
|
||||
arg(b, "tasks")?,
|
||||
integer(b, "limit")? as usize,
|
||||
integer(b, "timeout_ms")?,
|
||||
),
|
||||
_ => Err("not a task operation".into()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, id, b);
|
||||
Err("subtask unavailable in this build".into())
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
//! Text helpers for Mid M4 (`lib/text` thicken).
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
fn as_usize(v: &Value, label: &str) -> Result<usize, String> {
|
||||
match v {
|
||||
Value::Int(n) if *n >= 0 => Ok(*n as usize),
|
||||
Value::Int(_) => Err(format!("{label} must be non-negative")),
|
||||
_ => Err(format!("{label} needs int")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(text: &Value, sub: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let s = as_text(sub, "sub")?;
|
||||
Ok(Value::Bool(t.contains(s)))
|
||||
}
|
||||
|
||||
pub fn starts_with(text: &Value, prefix: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(prefix, "prefix")?;
|
||||
Ok(Value::Bool(t.starts_with(p)))
|
||||
}
|
||||
|
||||
pub fn ends_with(text: &Value, suffix: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let s = as_text(suffix, "suffix")?;
|
||||
Ok(Value::Bool(t.ends_with(s)))
|
||||
}
|
||||
|
||||
pub fn replace(
|
||||
text: &Value,
|
||||
old: &Value,
|
||||
new: &Value,
|
||||
count: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let old = as_text(old, "old")?;
|
||||
let new = as_text(new, "new")?;
|
||||
if old.is_empty() {
|
||||
return Err("replace: old must be non-empty".into());
|
||||
}
|
||||
let limit = match count {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(as_usize(v, "count")?),
|
||||
};
|
||||
let out = match limit {
|
||||
None => t.replace(old, new),
|
||||
Some(0) => t.to_string(),
|
||||
Some(n) => {
|
||||
let mut out = String::new();
|
||||
let mut rest = t;
|
||||
let mut done = 0usize;
|
||||
while done < n {
|
||||
if let Some(i) = rest.find(old) {
|
||||
out.push_str(&rest[..i]);
|
||||
out.push_str(new);
|
||||
rest = &rest[i + old.len()..];
|
||||
done += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn to_upper(text: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Text(as_text(text, "text")?.to_uppercase()))
|
||||
}
|
||||
|
||||
pub fn to_lower(text: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Text(as_text(text, "text")?.to_lowercase()))
|
||||
}
|
||||
|
||||
pub fn repeat(text: &Value, n: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let n = as_usize(n, "n")?;
|
||||
if n > 10_000 {
|
||||
return Err("repeat: n too large".into());
|
||||
}
|
||||
Ok(Value::Text(t.repeat(n)))
|
||||
}
|
||||
|
||||
pub fn pad(
|
||||
text: &Value,
|
||||
width: &Value,
|
||||
fill: Option<&Value>,
|
||||
align: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let width = as_usize(width, "width")?;
|
||||
let fill = match fill {
|
||||
None | Some(Value::None) => " ".to_string(),
|
||||
Some(v) => as_text(v, "fill")?.to_string(),
|
||||
};
|
||||
if fill.is_empty() {
|
||||
return Err("pad: fill must be non-empty".into());
|
||||
}
|
||||
let align = match align {
|
||||
None | Some(Value::None) => "left",
|
||||
Some(v) => as_text(v, "align")?,
|
||||
};
|
||||
let chars: Vec<char> = t.chars().collect();
|
||||
if chars.len() >= width {
|
||||
return Ok(Value::Text(t.to_string()));
|
||||
}
|
||||
let pad_n = width - chars.len();
|
||||
let fill_chars: Vec<char> = fill.chars().collect();
|
||||
let make_pad = |n: usize| {
|
||||
let mut s = String::new();
|
||||
for i in 0..n {
|
||||
s.push(fill_chars[i % fill_chars.len()]);
|
||||
}
|
||||
s
|
||||
};
|
||||
let out = match align {
|
||||
"right" => format!("{}{}", make_pad(pad_n), t),
|
||||
"center" => {
|
||||
let left = pad_n / 2;
|
||||
format!("{}{}{}", make_pad(left), t, make_pad(pad_n - left))
|
||||
}
|
||||
_ => format!("{}{}", t, make_pad(pad_n)),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn case_and_contains() {
|
||||
assert_eq!(
|
||||
contains(&Value::Text("Hello".into()), &Value::Text("ell".into())).unwrap(),
|
||||
Value::Bool(true)
|
||||
);
|
||||
assert_eq!(
|
||||
to_upper(&Value::Text("ß".into())).unwrap(),
|
||||
Value::Text("SS".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Time host primitives.
|
||||
|
||||
use crate::host::as_text;
|
||||
use std::time::Duration;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn now_unix() -> Result<Value, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
|
||||
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_unix: {e}"))?
|
||||
.as_secs();
|
||||
Ok(Value::Int(secs as i64))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now_ms() -> Result<Value, String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| format!("now_ms: {e}"))?
|
||||
.as_millis();
|
||||
Ok(Value::Int(ms as i64))
|
||||
}
|
||||
}
|
||||
|
||||
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
_ => Err(format!("{label} must be int")),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn format_time(unix: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let secs = as_i64(unix, "unix")?;
|
||||
let pat = as_text(pattern, "pattern")?;
|
||||
let dt = DateTime::<Utc>::from_timestamp(secs, 0)
|
||||
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
|
||||
Ok(Value::Text(dt.format(pat).to_string()))
|
||||
}
|
||||
|
||||
pub fn parse_time(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let pat = as_text(pattern, "pattern")?;
|
||||
let dt = NaiveDateTime::parse_from_str(t, pat).map_err(|e| format!("parse_time: {e}"))?;
|
||||
Ok(Value::Int(dt.and_utc().timestamp()))
|
||||
}
|
||||
|
||||
pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
|
||||
let n = as_i64(ms, "ms")?;
|
||||
if n < 0 {
|
||||
return Err("sleep_ms must be >= 0".into());
|
||||
}
|
||||
let n = n as u64;
|
||||
if let Some(lim) = ctx.sleep_limit_ms {
|
||||
if n > lim {
|
||||
return Err(format!("sleep_ms {n} exceeds limit {lim}"));
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(n));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = Duration::from_millis(n);
|
||||
// Browser wasm has no blocking sleep; ignore (C0/C1).
|
||||
}
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
//! Standards-based TOML; datetime scalars become explicit ISO text at Value boundary.
|
||||
use crate::{host::as_text,value::Value};
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value,String> {
|
||||
let parsed: toml::Value = toml::from_str(as_text(text,"text")?).map_err(|e|format!("toml.parse: {e}"))?;
|
||||
fn convert(v: toml::Value) -> Result<Value,String> {
|
||||
Ok(match v {
|
||||
toml::Value::String(s) => Value::Text(s),
|
||||
toml::Value::Integer(n) => Value::Int(n),
|
||||
toml::Value::Float(n) if n.is_finite() => Value::Num(n),
|
||||
toml::Value::Float(_) => return Err("toml: non-finite numbers unsupported".into()),
|
||||
toml::Value::Boolean(b) => Value::Bool(b),
|
||||
toml::Value::Datetime(dt) => Value::Text(dt.to_string()),
|
||||
toml::Value::Array(xs) => Value::List(xs.into_iter().map(convert).collect::<Result<_,_>>()?),
|
||||
toml::Value::Table(fields) => Value::Map(fields.into_iter().map(|(k,v)|convert(v).map(|v|(k,v))).collect::<Result<_,_>>()?),
|
||||
})
|
||||
}
|
||||
convert(parsed)
|
||||
}
|
||||
|
||||
pub fn stringify(value:&Value)->Result<Value,String>{
|
||||
fn convert(v:&Value)->Result<toml::Value,String>{
|
||||
Ok(match v {
|
||||
Value::Text(s)=>toml::Value::String(s.clone()),
|
||||
Value::Int(n)=>toml::Value::Integer(*n),
|
||||
Value::Num(n) if n.is_finite()=>toml::Value::Float(*n),
|
||||
Value::Bool(b)=>toml::Value::Boolean(*b),
|
||||
Value::List(xs)=>toml::Value::Array(xs.iter().map(convert).collect::<Result<_,_>>()?),
|
||||
Value::Map(fields)=>toml::Value::Table(fields.iter().map(|(k,v)|convert(v).map(|v|(k.clone(),v))).collect::<Result<_,_>>()?),
|
||||
_=>return Err("toml.stringify supports text/finite numbers/bool/list/map; None has no TOML representation".into()),
|
||||
})
|
||||
}
|
||||
if !matches!(value,Value::Map(_)){return Err("toml root must be map".into())}
|
||||
toml::to_string_pretty(&convert(value)?).map(Value::Text).map_err(|e|format!("toml.stringify: {e}"))
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_simple() {
|
||||
let t = r#"
|
||||
# comment
|
||||
name = "marqdo"
|
||||
count = 3
|
||||
ok = true
|
||||
[pkg]
|
||||
version = "0.1"
|
||||
"#;
|
||||
let v = parse(&Value::Text(t.into())).unwrap();
|
||||
let Value::Map(entries) = v else { panic!() };
|
||||
let get = |k: &str| {
|
||||
entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(get("name"), Value::Text("marqdo".into()));
|
||||
assert_eq!(get("count"), Value::Int(3));
|
||||
assert_eq!(get("ok"), Value::Bool(true));
|
||||
let Value::Map(pkg) = get("pkg") else { panic!() };
|
||||
assert_eq!(
|
||||
pkg.iter().find(|(k, _)| k == "version").unwrap().1,
|
||||
Value::Text("0.1".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
//! URL parse / query helpers for Mid2 M7 (`lib/url`).
|
||||
//! Distinct from `net::url_encode` (single-segment form encoding).
|
||||
//! Hand-rolled subset (no `url` crate): scheme://[userinfo@]host[:port]/path[?query][#frag].
|
||||
|
||||
use crate::host::as_text;
|
||||
use crate::value::Value;
|
||||
|
||||
|
||||
fn encode_component(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(b as char);
|
||||
}
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_component(s: &str) -> Result<String, String> {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
}
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
let h = |c: u8| -> Result<u8, String> {
|
||||
match c {
|
||||
b'0'..=b'9' => Ok(c - b'0'),
|
||||
b'a'..=b'f' => Ok(c - b'a' + 10),
|
||||
b'A'..=b'F' => Ok(c - b'A' + 10),
|
||||
_ => Err(format!("bad percent escape in {s:?}")),
|
||||
}
|
||||
};
|
||||
let v = (h(bytes[i + 1])? << 4) | h(bytes[i + 2])?;
|
||||
out.push(v);
|
||||
i += 3;
|
||||
}
|
||||
b'%' => return Err(format!("truncated percent escape in {s:?}")),
|
||||
c => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).map_err(|e| format!("url decode utf8: {e}"))
|
||||
}
|
||||
|
||||
/// Parse `scheme://[userinfo@]host[:port]/path[?query][#fragment]`.
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let (scheme, rest) = raw
|
||||
.split_once("://")
|
||||
.ok_or_else(|| format!("url.parse: missing :// in {raw:?}"))?;
|
||||
if scheme.is_empty()
|
||||
|| !scheme
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
|
||||
{
|
||||
return Err(format!("url.parse: bad scheme in {raw:?}"));
|
||||
}
|
||||
|
||||
let (before_frag, fragment) = match rest.split_once('#') {
|
||||
Some((a, b)) => (a, b),
|
||||
None => (rest, ""),
|
||||
};
|
||||
let (before_query, query) = match before_frag.split_once('?') {
|
||||
Some((a, b)) => (a, b),
|
||||
None => (before_frag, ""),
|
||||
};
|
||||
|
||||
let (authority, path) = if let Some(i) = before_query.find('/') {
|
||||
(&before_query[..i], &before_query[i..])
|
||||
} else {
|
||||
(before_query, "")
|
||||
};
|
||||
|
||||
let (userinfo, hostport) = if let Some((u, h)) = authority.rsplit_once('@') {
|
||||
(u, h)
|
||||
} else {
|
||||
("", authority)
|
||||
};
|
||||
|
||||
let (host, port) = if hostport.starts_with('[') {
|
||||
// IPv6 literal [addr]:port
|
||||
let end = hostport
|
||||
.find(']')
|
||||
.ok_or_else(|| format!("url.parse: bad IPv6 host in {raw:?}"))?;
|
||||
let host = &hostport[1..end];
|
||||
let rest = &hostport[end + 1..];
|
||||
if rest.is_empty() {
|
||||
(host, Value::None)
|
||||
} else if let Some(p) = rest.strip_prefix(':') {
|
||||
let n: i64 = p
|
||||
.parse()
|
||||
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
|
||||
(host, Value::Int(n))
|
||||
} else {
|
||||
return Err(format!("url.parse: bad hostport in {raw:?}"));
|
||||
}
|
||||
} else if let Some((h, p)) = hostport.rsplit_once(':') {
|
||||
if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() {
|
||||
let n: i64 = p
|
||||
.parse()
|
||||
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
|
||||
(h, Value::Int(n))
|
||||
} else {
|
||||
(hostport, Value::None)
|
||||
}
|
||||
} else {
|
||||
(hostport, Value::None)
|
||||
};
|
||||
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
path.to_string()
|
||||
};
|
||||
|
||||
Ok(Value::Map(vec![
|
||||
("scheme".into(), Value::Text(scheme.to_string())),
|
||||
("userinfo".into(), Value::Text(userinfo.to_string())),
|
||||
("host".into(), Value::Text(host.to_string())),
|
||||
("port".into(), port),
|
||||
("path".into(), Value::Text(path)),
|
||||
("query".into(), Value::Text(query.to_string())),
|
||||
("fragment".into(), Value::Text(fragment.to_string())),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn query_parse(text: &Value) -> Result<Value, String> {
|
||||
let raw = as_text(text, "text")?;
|
||||
let raw = raw.strip_prefix('?').unwrap_or(raw);
|
||||
let mut map: Vec<(String, Value)> = Vec::new();
|
||||
if raw.is_empty() {
|
||||
return Ok(Value::Map(map));
|
||||
}
|
||||
for pair in raw.split('&') {
|
||||
if pair.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (k, v) = match pair.split_once('=') {
|
||||
Some((k, v)) => (k, v),
|
||||
None => (pair, ""),
|
||||
};
|
||||
let key = decode_component(k)?;
|
||||
let val = Value::Text(decode_component(v)?);
|
||||
if let Some((_, slot)) = map.iter_mut().find(|(kk, _)| *kk == key) {
|
||||
match slot {
|
||||
Value::List(xs) => xs.push(val),
|
||||
other => {
|
||||
let prev = std::mem::replace(other, Value::None);
|
||||
*other = Value::List(vec![prev, val]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
map.push((key, val));
|
||||
}
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
pub fn query_stringify(map: &Value) -> Result<Value, String> {
|
||||
let entries = match map {
|
||||
Value::Map(m) => m,
|
||||
Value::None => return Ok(Value::Text(String::new())),
|
||||
_ => return Err("url.query_stringify: map required".into()),
|
||||
};
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for (k, v) in entries {
|
||||
let key = encode_component(k);
|
||||
match v {
|
||||
Value::List(xs) => {
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::Text(s) => {
|
||||
parts.push(format!("{key}={}", encode_component(s)));
|
||||
}
|
||||
Value::Int(n) => {
|
||||
parts.push(format!("{key}={}", encode_component(&n.to_string())));
|
||||
}
|
||||
Value::Bool(b) => {
|
||||
parts.push(format!("{key}={}", encode_component(&b.to_string())));
|
||||
}
|
||||
Value::None => parts.push(format!("{key}=")),
|
||||
_ => {
|
||||
return Err("url.query_stringify: list values must be scalar".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Text(s) => parts.push(format!("{key}={}", encode_component(s))),
|
||||
Value::Int(n) => parts.push(format!("{key}={}", encode_component(&n.to_string()))),
|
||||
Value::Bool(b) => parts.push(format!("{key}={}", encode_component(&b.to_string()))),
|
||||
Value::None => parts.push(format!("{key}=")),
|
||||
_ => return Err("url.query_stringify: values must be scalar or list".into()),
|
||||
}
|
||||
}
|
||||
Ok(Value::Text(parts.join("&")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_https_query() {
|
||||
let m = parse(&Value::Text(
|
||||
"https://user:pass@example.com:8443/a/b?x=1&y=2#frag".into(),
|
||||
))
|
||||
.unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let get = |k: &str| {
|
||||
entries
|
||||
.iter()
|
||||
.find(|(kk, _)| kk == k)
|
||||
.map(|(_, v)| v.clone())
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(get("scheme"), Value::Text("https".into()));
|
||||
assert_eq!(get("host"), Value::Text("example.com".into()));
|
||||
assert_eq!(get("port"), Value::Int(8443));
|
||||
assert_eq!(get("path"), Value::Text("/a/b".into()));
|
||||
assert_eq!(get("query"), Value::Text("x=1&y=2".into()));
|
||||
assert_eq!(get("fragment"), Value::Text("frag".into()));
|
||||
assert_eq!(get("userinfo"), Value::Text("user:pass".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_roundtrip() {
|
||||
let q = query_parse(&Value::Text("a=1&b=hello%20w&a=2".into())).unwrap();
|
||||
let s = query_stringify(&q).unwrap();
|
||||
assert_eq!(s, Value::Text("a=1&a=2&b=hello%20w".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_path_becomes_slash() {
|
||||
let m = parse(&Value::Text("https://example.com".into())).unwrap();
|
||||
let Value::Map(entries) = m else { panic!() };
|
||||
let path = entries.iter().find(|(k, _)| k == "path").unwrap().1.clone();
|
||||
assert_eq!(path, Value::Text("/".into()));
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
//! UUID v4 for Mid M6 (`lib/uuid`).
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
pub fn v4() -> Result<Value, String> {
|
||||
let mut bytes = [0u8; 16];
|
||||
getrandom::getrandom(&mut bytes).map_err(|e| format!("uuid.v4: {e}"))?;
|
||||
// RFC 4122 version 4 + variant 10xx
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
Ok(Value::Text(format!(
|
||||
"{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
||||
bytes[0],
|
||||
bytes[1],
|
||||
bytes[2],
|
||||
bytes[3],
|
||||
bytes[4],
|
||||
bytes[5],
|
||||
bytes[6],
|
||||
bytes[7],
|
||||
bytes[8],
|
||||
bytes[9],
|
||||
bytes[10],
|
||||
bytes[11],
|
||||
bytes[12],
|
||||
bytes[13],
|
||||
bytes[14],
|
||||
bytes[15],
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn v4_shape() {
|
||||
let v = v4().unwrap();
|
||||
let Value::Text(s) = v else { panic!("text") };
|
||||
assert_eq!(s.len(), 36);
|
||||
assert_eq!(&s[14..15], "4");
|
||||
let variant = u8::from_str_radix(&s[19..20], 16).unwrap();
|
||||
assert!(variant == 8 || variant == 9 || variant == 0xa || variant == 0xb);
|
||||
}
|
||||
}
|
||||
@@ -1,914 +0,0 @@
|
||||
//! Jupyter-style output persistence in `.mq.md`.
|
||||
//!
|
||||
//! Two surface forms (both scanned / replaced):
|
||||
//! - HTML comment: `<!-- marqdo-out … -->` (text / structured output)
|
||||
//! - Markdown image: `` (image refs; validated)
|
||||
//!
|
||||
//! Optional **named slots**: `marqdo-out ok` / `marqdo-out error` so success and
|
||||
//! failure results do not overwrite each other.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
const MAGIC: &str = "marqdo-out";
|
||||
|
||||
/// Serialize all writeback file mutations (sync + subtask writers).
|
||||
static WRITEBACK_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum BlockKind {
|
||||
Comment,
|
||||
Image,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct BlockSpan {
|
||||
start: usize,
|
||||
end: usize,
|
||||
/// Comment body text, or image URL/path for [`BlockKind::Image`].
|
||||
body: String,
|
||||
start_line: u32,
|
||||
/// Named slot from header (`marqdo-out ok` → `ok`); `None` = legacy unkeyed.
|
||||
key: Option<String>,
|
||||
kind: BlockKind,
|
||||
}
|
||||
|
||||
/// View-facing writeback piece under a statement line.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WritebackEntry {
|
||||
pub key: Option<String>,
|
||||
pub body: String,
|
||||
pub is_image: bool,
|
||||
}
|
||||
|
||||
fn display_value(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Text(s) => s.clone(),
|
||||
other => other.as_display(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::None) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Int(n)) => *n != 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_key(v: Option<&Value>) -> Result<Option<String>, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(None),
|
||||
Some(Value::Text(s)) => {
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(normalize_slot_key(t)))
|
||||
}
|
||||
}
|
||||
_ => Err("writeback key must be text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_line(v: Option<&Value>) -> Result<Option<u32>, String> {
|
||||
match v {
|
||||
None | Some(Value::None) => Ok(None),
|
||||
Some(Value::Int(n)) if *n > 0 => Ok(Some(*n as u32)),
|
||||
Some(Value::Text(s)) => {
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
t.parse::<u32>()
|
||||
.map(|n| if n > 0 { Some(n) } else { None })
|
||||
.map_err(|_| "writeback line must be a positive int".into())
|
||||
}
|
||||
}
|
||||
_ => Err("writeback line must be a positive int".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical slot ids used by the agent framework.
|
||||
fn normalize_slot_key(raw: &str) -> String {
|
||||
match raw {
|
||||
"ok" | "success" | "成功" => "ok".into(),
|
||||
"error" | "failure" | "失败" => "error".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_line(ctx: &HostContext) -> Result<u32, String> {
|
||||
ctx.call_site_lines
|
||||
.last()
|
||||
.copied()
|
||||
.ok_or_else(|| "writeback: no call site line".into())
|
||||
}
|
||||
|
||||
/// Line that should own adjacent output cards.
|
||||
/// Prefer explicit `line=`, else for keyed slots the outermost call site (`step`),
|
||||
/// else the parent/current call site.
|
||||
fn resolve_anchor(
|
||||
ctx: &HostContext,
|
||||
keyed: bool,
|
||||
line: Option<&Value>,
|
||||
) -> Result<u32, String> {
|
||||
if let Some(n) = opt_line(line)? {
|
||||
return Ok(n);
|
||||
}
|
||||
if keyed {
|
||||
if let Some(n) = ctx.call_site_lines.first().copied() {
|
||||
return Ok(n);
|
||||
}
|
||||
if ctx.call_site_lines.len() >= 2 {
|
||||
return Ok(ctx.call_site_lines[ctx.call_site_lines.len() - 2]);
|
||||
}
|
||||
}
|
||||
call_line(ctx)
|
||||
}
|
||||
|
||||
fn line_number_at(source: &str, byte: usize) -> u32 {
|
||||
source[..byte.min(source.len())]
|
||||
.bytes()
|
||||
.filter(|b| *b == b'\n')
|
||||
.count() as u32
|
||||
+ 1
|
||||
}
|
||||
|
||||
fn format_comment_block(body: &str, key: Option<&str>) -> String {
|
||||
match key {
|
||||
Some(k) => format!("<!-- {MAGIC} {k}\n{body}\n-->"),
|
||||
None => format!("<!-- {MAGIC}\n{body}\n-->"),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_image_block(url: &str, key: Option<&str>) -> String {
|
||||
match key {
|
||||
Some(k) => format!(""),
|
||||
None => format!(""),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_block_for_value(body: &str, key: Option<&str>) -> Result<String, String> {
|
||||
if looks_like_image_ref(body) {
|
||||
validate_image_ref(body)?;
|
||||
Ok(format_image_block(body.trim(), key))
|
||||
} else {
|
||||
Ok(format_comment_block(body, key))
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `s` looks like a path/URL that should persist as ``.
|
||||
pub fn looks_like_image_ref(s: &str) -> bool {
|
||||
validate_image_ref(s).is_ok()
|
||||
}
|
||||
|
||||
/// Accept local/relative paths and http(s) URLs with a known image extension,
|
||||
/// or `data:image/…` URIs.
|
||||
pub fn validate_image_ref(s: &str) -> Result<(), String> {
|
||||
let t = s.trim().trim_matches('"').trim_matches('\'');
|
||||
if t.is_empty() {
|
||||
return Err("writeback image: empty path".into());
|
||||
}
|
||||
if t.starts_with("data:image/") {
|
||||
return Ok(());
|
||||
}
|
||||
// Strip query/fragment for extension check.
|
||||
let no_query = t.split_once('?').map(|(p, _)| p).unwrap_or(t);
|
||||
let path_part = no_query.split_once('#').map(|(p, _)| p).unwrap_or(no_query);
|
||||
let file = path_part.rsplit('/').next().unwrap_or(path_part);
|
||||
// Require a real extension (reject bare names like `svg` / `png`).
|
||||
let Some((stem, ext)) = file.rsplit_once('.') else {
|
||||
return Err(format!(
|
||||
"writeback image: path needs an image extension (got `{t}`)"
|
||||
));
|
||||
};
|
||||
if stem.is_empty() {
|
||||
return Err(format!("writeback image: invalid file name `{t}`"));
|
||||
}
|
||||
let ext = ext.to_ascii_lowercase();
|
||||
const OK: &[&str] = &[
|
||||
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "tif", "tiff",
|
||||
];
|
||||
if OK.contains(&ext.as_str()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"writeback image: not an image path/URL (got `{t}`; need .{})",
|
||||
OK.join("/.")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_header_key(header: &str) -> Option<String> {
|
||||
let mut parts = header.split_whitespace();
|
||||
let first = parts.next()?;
|
||||
if first != MAGIC {
|
||||
return None;
|
||||
}
|
||||
parts.next().map(normalize_slot_key)
|
||||
}
|
||||
|
||||
fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<BlockSpan> {
|
||||
let inner = block
|
||||
.strip_prefix("<!--")?
|
||||
.strip_suffix("-->")?
|
||||
.trim();
|
||||
if !inner.contains(MAGIC) {
|
||||
return None;
|
||||
}
|
||||
let mut lines: Vec<&str> = inner.lines().collect();
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let header = lines.remove(0).trim();
|
||||
if !header.split_whitespace().any(|t| t == MAGIC) {
|
||||
return None;
|
||||
}
|
||||
let key = parse_header_key(header);
|
||||
let body = lines.join("\n");
|
||||
let end = start_byte + block.len();
|
||||
Some(BlockSpan {
|
||||
start: start_byte,
|
||||
end,
|
||||
body,
|
||||
start_line: line_number_at(source, start_byte),
|
||||
key,
|
||||
kind: BlockKind::Comment,
|
||||
})
|
||||
}
|
||||
|
||||
/// `` on a single source line.
|
||||
fn parse_image_line(line: &str, line_start: usize, source: &str) -> Option<BlockSpan> {
|
||||
let trimmed = line.trim();
|
||||
let rest = trimmed.strip_prefix("?;
|
||||
let alt = rest[..alt_end].trim();
|
||||
if !alt.split_whitespace().any(|t| t == MAGIC) {
|
||||
return None;
|
||||
}
|
||||
let key = parse_header_key(alt);
|
||||
let after_alt = &rest[alt_end + 2..];
|
||||
let url_end = after_alt.rfind(')')?;
|
||||
let url = after_alt[..url_end].trim();
|
||||
if url.is_empty() || validate_image_ref(url).is_err() {
|
||||
return None;
|
||||
}
|
||||
// Span covers the trimmed image on its line (indent kept outside).
|
||||
let trim_start = line.find(trimmed).unwrap_or(0);
|
||||
let start = line_start + trim_start;
|
||||
let end = start + trimmed.len();
|
||||
Some(BlockSpan {
|
||||
start,
|
||||
end,
|
||||
body: url.to_string(),
|
||||
start_line: line_number_at(source, start),
|
||||
key,
|
||||
kind: BlockKind::Image,
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
||||
let mut out = Vec::new();
|
||||
// HTML comment blocks
|
||||
let mut i = 0usize;
|
||||
while i < source.len() {
|
||||
let rest = &source[i..];
|
||||
let Some(start) = rest.find("<!--") else {
|
||||
break;
|
||||
};
|
||||
let abs = i + start;
|
||||
let after = &source[abs..];
|
||||
if !after.contains(MAGIC) {
|
||||
i = abs + 4;
|
||||
continue;
|
||||
}
|
||||
let Some(end_rel) = after.find("-->") else {
|
||||
break;
|
||||
};
|
||||
let block = &after[..end_rel + 3];
|
||||
if let Some(b) = parse_one_block(block, abs, source) {
|
||||
out.push(b);
|
||||
}
|
||||
i = abs + end_rel + 3;
|
||||
}
|
||||
// Image writebacks (line-oriented)
|
||||
let mut line_start = 0usize;
|
||||
for line in source.split_inclusive('\n') {
|
||||
let content = line.trim_end_matches(['\r', '\n']);
|
||||
if let Some(b) = parse_image_line(content, line_start, source) {
|
||||
out.push(b);
|
||||
}
|
||||
line_start += line.len();
|
||||
}
|
||||
out.sort_by_key(|b| b.start);
|
||||
out
|
||||
}
|
||||
|
||||
fn strip_span(source: &str, start: usize, end: usize) -> String {
|
||||
let mut out = String::with_capacity(source.len());
|
||||
out.push_str(&source[..start]);
|
||||
out.push_str(&source[end..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte end of a `<!-- … -->` span, including the single newline that terminates the `-->` line.
|
||||
fn span_end_including_nl(source: &str, end: usize) -> usize {
|
||||
if source.as_bytes().get(end) == Some(&b'\n') {
|
||||
end + 1
|
||||
} else {
|
||||
end
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `block` (plus a terminating newline) over `[start, end)`, preserving blank lines after.
|
||||
fn splice_block(source: &str, start: usize, end: usize, block: &str) -> String {
|
||||
let end = span_end_including_nl(source, end);
|
||||
let mut out = String::with_capacity(source.len() + block.len() + 1);
|
||||
out.push_str(&source[..start]);
|
||||
out.push_str(block);
|
||||
if !block.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&source[end..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn line_start_byte(source: &str, line_no: u32) -> Option<usize> {
|
||||
if line_no == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut cur = 1u32;
|
||||
for (i, b) in source.bytes().enumerate() {
|
||||
if cur == line_no {
|
||||
return Some(i);
|
||||
}
|
||||
if b == b'\n' {
|
||||
cur += 1;
|
||||
}
|
||||
}
|
||||
if cur == line_no {
|
||||
Some(source.len())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn line_end_byte(source: &str, line_no: u32) -> Option<usize> {
|
||||
let start = line_start_byte(source, line_no)?;
|
||||
let rest = &source[start..];
|
||||
match rest.find('\n') {
|
||||
Some(off) => Some(start + off + 1),
|
||||
None => Some(source.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_blank_line(source: &str, line_no: u32) -> bool {
|
||||
let start = match line_start_byte(source, line_no) {
|
||||
Some(s) => s,
|
||||
None => return true,
|
||||
};
|
||||
let end = line_end_byte(source, line_no).unwrap_or(source.len());
|
||||
source[start..end].trim().is_empty()
|
||||
}
|
||||
|
||||
fn find_adjacent_block(source: &str, after_line: u32) -> Option<BlockSpan> {
|
||||
let mut line = after_line.saturating_add(1);
|
||||
let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
|
||||
while line <= total && is_blank_line(source, line) {
|
||||
line += 1;
|
||||
}
|
||||
for b in scan_blocks(source) {
|
||||
if b.start_line == line && b.key.is_none() {
|
||||
return Some(b);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_eof_block(source: &str, block: &BlockSpan) -> bool {
|
||||
source[block.end..].trim().is_empty()
|
||||
}
|
||||
|
||||
fn find_eof_block(source: &str) -> Option<BlockSpan> {
|
||||
scan_blocks(source)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|b| b.key.is_none() && is_eof_block(source, b))
|
||||
}
|
||||
|
||||
fn find_keyed_block(source: &str, key: &str) -> Option<BlockSpan> {
|
||||
let key = normalize_slot_key(key);
|
||||
scan_blocks(source)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|b| b.key.as_deref() == Some(key.as_str()))
|
||||
}
|
||||
|
||||
/// Consecutive `marqdo-out` blocks immediately below `after_line` (blank lines allowed).
|
||||
fn cluster_after_line(source: &str, after_line: u32) -> Vec<BlockSpan> {
|
||||
let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
|
||||
let mut line = after_line.saturating_add(1);
|
||||
while line <= total && is_blank_line(source, line) {
|
||||
line += 1;
|
||||
}
|
||||
let blocks = scan_blocks(source);
|
||||
let mut cluster = Vec::new();
|
||||
while line <= total {
|
||||
if let Some(b) = blocks.iter().find(|b| b.start_line == line) {
|
||||
cluster.push(b.clone());
|
||||
let end_line = line_number_at(source, b.end.saturating_sub(1).max(b.start));
|
||||
line = end_line.saturating_add(1);
|
||||
while line <= total && is_blank_line(source, line) {
|
||||
line += 1;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
cluster
|
||||
}
|
||||
|
||||
fn find_keyed_in_cluster(source: &str, after_line: u32, key: &str) -> Option<BlockSpan> {
|
||||
let key = normalize_slot_key(key);
|
||||
cluster_after_line(source, after_line)
|
||||
.into_iter()
|
||||
.find(|b| b.key.as_deref() == Some(key.as_str()))
|
||||
}
|
||||
|
||||
/// Replace keyed block under `anchor` line, or insert into that cluster (not EOF).
|
||||
fn replace_or_insert_keyed_at(source: &str, anchor: u32, key: &str, body: &str) -> Result<String, String> {
|
||||
let key = normalize_slot_key(key);
|
||||
let block = format_block_for_value(body, Some(&key))?;
|
||||
if let Some(existing) = find_keyed_in_cluster(source, anchor, &key) {
|
||||
return Ok(splice_block(source, existing.start, existing.end, &block));
|
||||
}
|
||||
let cluster = cluster_after_line(source, anchor);
|
||||
if let Some(last) = cluster.last() {
|
||||
// Insert after the last block's terminating newline (or after `-->` if none).
|
||||
let insert_at = span_end_including_nl(source, last.end);
|
||||
let mut out = String::with_capacity(source.len() + block.len() + 1);
|
||||
out.push_str(&source[..insert_at]);
|
||||
if !out.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&block);
|
||||
if !block.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&source[insert_at..]);
|
||||
Ok(out)
|
||||
} else {
|
||||
insert_after_line(source, anchor, &block)
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result<String, String> {
|
||||
let insert_at = line_end_byte(source, line_no)
|
||||
.ok_or_else(|| format!("writeback: line {line_no} out of range"))?;
|
||||
let mut out = String::with_capacity(source.len() + block.len() + 2);
|
||||
out.push_str(&source[..insert_at]);
|
||||
if !block.starts_with('\n') && !source[..insert_at].ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(block);
|
||||
if !block.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&source[insert_at..]);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn append_eof(source: &str, block: &str) -> String {
|
||||
let mut trimmed = source.trim_end().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
trimmed.push('\n');
|
||||
}
|
||||
trimmed.push_str(block);
|
||||
if !block.ends_with('\n') {
|
||||
trimmed.push('\n');
|
||||
}
|
||||
trimmed
|
||||
}
|
||||
|
||||
fn entry_target(path: &std::path::Path) -> Result<std::path::PathBuf,String> {
|
||||
if path.is_absolute() { return Ok(path.to_path_buf()); }
|
||||
// Entry paths originate at the caller's process cwd, as in the runner.
|
||||
std::env::current_dir().map(|base|base.join(path)).map_err(|e|format!("writeback entry path: {e}"))
|
||||
}
|
||||
fn entry_path_text(path: &std::path::Path) -> Result<Value,String> {
|
||||
let path=entry_target(path)?;
|
||||
Ok(Value::Text(path.to_str().ok_or("writeback path must be UTF-8")?.to_string()))
|
||||
}
|
||||
fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("writeback disabled (fs_write capability off)".into());
|
||||
}
|
||||
let path=ctx.entry_path.as_ref().ok_or("writeback: no entry file")?;
|
||||
let path=entry_path_text(path)?;
|
||||
// Use the same root, symlink and CoW rules as ordinary native file writes.
|
||||
super::fs::write_text(ctx,&path,&Value::Text(source.to_string()))?;
|
||||
ctx.entry_source=Some(source.to_string());
|
||||
Ok(())
|
||||
}
|
||||
fn load_entry_source(ctx: &HostContext) -> Result<String, String> {
|
||||
if let Some(path)=&ctx.entry_path {
|
||||
let target=entry_target(path)?;
|
||||
match super::fs::read_text(ctx,&entry_path_text(path)?) {
|
||||
Ok(Value::Text(text))=>return Ok(text),
|
||||
Ok(_)=>return Err("writeback entry source must be text".into()),
|
||||
// In-memory entry buffers may intentionally precede file creation.
|
||||
Err(_) if !target.exists()=>{},
|
||||
Err(error)=>return Err(error),
|
||||
}
|
||||
}
|
||||
ctx.entry_source.clone().ok_or_else(||"writeback: no entry source".to_string())
|
||||
}
|
||||
|
||||
fn with_writeback_lock<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
|
||||
let _guard = WRITEBACK_LOCK
|
||||
.lock()
|
||||
.map_err(|_| "writeback lock poisoned".to_string())?;
|
||||
f()
|
||||
}
|
||||
|
||||
fn anchor_line_above(source: &str, block_start_line: u32) -> u32 {
|
||||
let mut line = block_start_line.saturating_sub(1);
|
||||
while line > 0 && is_blank_line(source, line) {
|
||||
line -= 1;
|
||||
}
|
||||
line.max(1)
|
||||
}
|
||||
|
||||
pub fn record(
|
||||
ctx: &mut HostContext,
|
||||
value: &Value,
|
||||
at_end: Option<&Value>,
|
||||
key: Option<&Value>,
|
||||
line: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let body = display_value(value);
|
||||
let key = opt_key(key)?;
|
||||
let at_end = is_truthy(at_end);
|
||||
let anchor = if key.is_some() || !at_end {
|
||||
Some(resolve_anchor(ctx, key.is_some(), line)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
with_writeback_lock(|| {
|
||||
let source = load_entry_source(ctx)?;
|
||||
let next = if let Some(ref k) = key {
|
||||
let anchor = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
||||
replace_or_insert_keyed_at(&source, anchor, k, &body)?
|
||||
} else if at_end {
|
||||
let stripped = find_eof_block(&source)
|
||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||
.unwrap_or_else(|| source.clone());
|
||||
append_eof(&stripped, &format_block_for_value(&body, None)?)
|
||||
} else {
|
||||
let line = anchor.ok_or_else(|| "writeback: missing anchor line".to_string())?;
|
||||
let stripped = find_adjacent_block(&source, line)
|
||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||
.unwrap_or_else(|| source.clone());
|
||||
insert_after_line(&stripped, line, &format_block_for_value(&body, None)?)?
|
||||
};
|
||||
persist(ctx, &next)?;
|
||||
Ok(Value::Text(body.clone()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get(
|
||||
ctx: &HostContext,
|
||||
at_end: Option<&Value>,
|
||||
key: Option<&Value>,
|
||||
line: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let key = opt_key(key)?;
|
||||
let at_end = is_truthy(at_end);
|
||||
let anchor = if key.is_some() || !at_end {
|
||||
resolve_anchor(ctx, key.is_some(), line).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
with_writeback_lock(|| {
|
||||
let source = load_entry_source(ctx)?;
|
||||
let body = if let Some(ref k) = key {
|
||||
let found = anchor
|
||||
.and_then(|a| find_keyed_in_cluster(&source, a, k))
|
||||
.or_else(|| find_keyed_block(&source, k));
|
||||
found.map(|b| b.body)
|
||||
} else if at_end {
|
||||
find_eof_block(&source).map(|b| b.body)
|
||||
} else {
|
||||
let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?;
|
||||
find_adjacent_block(&source, line).map(|b| b.body)
|
||||
};
|
||||
Ok(match body {
|
||||
Some(s) => Value::Text(s),
|
||||
None => Value::None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clear(
|
||||
ctx: &mut HostContext,
|
||||
at_end: Option<&Value>,
|
||||
key: Option<&Value>,
|
||||
line: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let key = opt_key(key)?;
|
||||
let at_end = is_truthy(at_end);
|
||||
let anchor = if key.is_some() || !at_end {
|
||||
resolve_anchor(ctx, key.is_some(), line).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
with_writeback_lock(|| {
|
||||
let source = load_entry_source(ctx)?;
|
||||
let next = if let Some(ref k) = key {
|
||||
let block = anchor
|
||||
.and_then(|a| find_keyed_in_cluster(&source, a, k))
|
||||
.or_else(|| find_keyed_block(&source, k));
|
||||
block
|
||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||
.unwrap_or_else(|| source.clone())
|
||||
} else if at_end {
|
||||
find_eof_block(&source)
|
||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||
.unwrap_or_else(|| source.clone())
|
||||
} else {
|
||||
let line = anchor.ok_or_else(|| "writeback: no call site line".to_string())?;
|
||||
find_adjacent_block(&source, line)
|
||||
.map(|b| strip_span(&source, b.start, span_end_including_nl(&source, b.end)))
|
||||
.unwrap_or_else(|| source.clone())
|
||||
};
|
||||
if next != source {
|
||||
persist(ctx, &next)?;
|
||||
}
|
||||
Ok(Value::None)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list(ctx: &HostContext) -> Result<Value, String> {
|
||||
let source = ctx
|
||||
.entry_source
|
||||
.as_deref()
|
||||
.ok_or_else(|| "writeback: no entry source".to_string())?;
|
||||
Ok(slots_from_source(source))
|
||||
}
|
||||
|
||||
/// Scan `path` for `<!-- marqdo-out … -->` slots (any file, not only the entry).
|
||||
pub fn scan_path(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
let rel = match path {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("writeback scan_path: path must be text".into()),
|
||||
};
|
||||
let p = ctx.resolve_path(rel)?;
|
||||
let source = std::fs::read_to_string(&p)
|
||||
.map_err(|e| format!("writeback scan_path {}: {e}", p.display()))?;
|
||||
Ok(slots_from_source(&source))
|
||||
}
|
||||
|
||||
fn slots_from_source(source: &str) -> Value {
|
||||
let items: Vec<Value> = scan_blocks(source)
|
||||
.into_iter()
|
||||
.map(|b| {
|
||||
let anchor = anchor_line_above(source, b.start_line);
|
||||
let at_eof = b.key.is_none() && is_eof_block(source, &b);
|
||||
let kind = match b.kind {
|
||||
BlockKind::Comment => "comment",
|
||||
BlockKind::Image => "image",
|
||||
};
|
||||
let mut entries = vec![
|
||||
("line".into(), Value::Int(anchor as i64)),
|
||||
("body".into(), Value::Text(b.body)),
|
||||
("at_end".into(), Value::Bool(at_eof)),
|
||||
("kind".into(), Value::Text(kind.into())),
|
||||
];
|
||||
if let Some(k) = b.key {
|
||||
entries.push(("key".into(), Value::Text(k)));
|
||||
}
|
||||
Value::Map(entries)
|
||||
})
|
||||
.collect();
|
||||
Value::List(items)
|
||||
}
|
||||
|
||||
/// Ensure named slots exist with a placeholder body; **does not** overwrite non-empty bodies.
|
||||
pub fn ensure_slot(
|
||||
ctx: &mut HostContext,
|
||||
key: &Value,
|
||||
placeholder: &Value,
|
||||
line: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let k = opt_key(Some(key))?.ok_or_else(|| "writeback ensure needs key".to_string())?;
|
||||
let body = display_value(placeholder);
|
||||
let anchor = resolve_anchor(ctx, true, line)?;
|
||||
with_writeback_lock(|| {
|
||||
let source = load_entry_source(ctx)?;
|
||||
if find_keyed_in_cluster(&source, anchor, &k).is_some() {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let next = replace_or_insert_keyed_at(&source, anchor, &k, &body)?;
|
||||
persist(ctx, &next)?;
|
||||
Ok(Value::Bool(true))
|
||||
})
|
||||
}
|
||||
|
||||
/// Structured writebacks keyed by the statement line above the block cluster.
|
||||
pub fn writeback_entries(source: &str) -> HashMap<u32, Vec<WritebackEntry>> {
|
||||
let mut map: HashMap<u32, Vec<WritebackEntry>> = HashMap::new();
|
||||
for b in scan_blocks(source) {
|
||||
let anchor = if b.key.is_none() && is_eof_block(source, &b) {
|
||||
0
|
||||
} else {
|
||||
anchor_line_above(source, b.start_line)
|
||||
};
|
||||
let entry = WritebackEntry {
|
||||
key: b.key.clone(),
|
||||
body: b.body.clone(),
|
||||
is_image: b.kind == BlockKind::Image,
|
||||
};
|
||||
map.entry(anchor).or_default().push(entry);
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
/// Map statement line → combined body for adjacent blocks (keyed slots included).
|
||||
/// Image slots are encoded as a markdown image line so view/static can render `<img>`.
|
||||
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
||||
let mut map = HashMap::new();
|
||||
for (anchor, entries) in writeback_entries(source) {
|
||||
let mut pieces = Vec::new();
|
||||
for e in entries {
|
||||
let content = if e.is_image {
|
||||
format!("", e.body)
|
||||
} else {
|
||||
e.body
|
||||
};
|
||||
let piece = match &e.key {
|
||||
Some(k) => format!("[{k}]\n{content}"),
|
||||
None => content,
|
||||
};
|
||||
pieces.push(piece);
|
||||
}
|
||||
map.insert(anchor, pieces.join("\n\n"));
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_insert_adjacent() {
|
||||
let src = "# main\n\n**x = 1**\n";
|
||||
let block = format_comment_block("1", None);
|
||||
let next = insert_after_line(src, 3, &block).unwrap();
|
||||
assert!(next.contains("marqdo-out"));
|
||||
assert!(!next.contains("@line"));
|
||||
let blocks = scan_blocks(&next);
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].body, "1");
|
||||
let replaced = strip_span(&next, blocks[0].start, blocks[0].end);
|
||||
assert!(!replaced.contains("marqdo-out"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_writeback_scan_and_format() {
|
||||
assert!(looks_like_image_ref("plot.svg"));
|
||||
assert!(looks_like_image_ref("https://ex.com/a.PNG"));
|
||||
assert!(looks_like_image_ref("data:image/png;base64,xx"));
|
||||
assert!(looks_like_image_ref("plots/a.svg?v=1"));
|
||||
assert!(!looks_like_image_ref("readme.txt"));
|
||||
assert!(!looks_like_image_ref("42"));
|
||||
assert!(!looks_like_image_ref("svg")); // bare name, not an extension
|
||||
assert!(!looks_like_image_ref(".svg"));
|
||||
let block = format_image_block("out/plot.svg", Some("ok"));
|
||||
assert_eq!(block, "");
|
||||
let src = "# main\n\n**x = 1**\n\n\n> print text=tail\n";
|
||||
let blocks = scan_blocks(src);
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||
assert_eq!(blocks[0].body, "out/plot.svg");
|
||||
assert_eq!(blocks[0].key.as_deref(), Some("ok"));
|
||||
let map = writeback_map(src);
|
||||
assert_eq!(
|
||||
map.get(&3).map(|s| s.as_str()),
|
||||
Some("[ok]\n")
|
||||
);
|
||||
// Invalid image URL in marqdo-out alt → not a writeback slot
|
||||
let bad = "# main\n\n\n";
|
||||
assert!(scan_blocks(bad).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unkeyed_comment_and_image_replace_each_other() {
|
||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\nold\n-->\n\n> print text=tail\n";
|
||||
let line = 3u32;
|
||||
let to_image = {
|
||||
let stripped = find_adjacent_block(src, line)
|
||||
.map(|b| strip_span(src, b.start, span_end_including_nl(src, b.end)))
|
||||
.unwrap_or_else(|| src.to_string());
|
||||
insert_after_line(
|
||||
&stripped,
|
||||
line,
|
||||
&format_block_for_value("fig.svg", None).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert!(to_image.contains(""));
|
||||
assert!(!to_image.contains("<!-- marqdo-out"));
|
||||
let blocks = scan_blocks(&to_image);
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].kind, BlockKind::Image);
|
||||
|
||||
let to_text = {
|
||||
let stripped = find_adjacent_block(&to_image, line)
|
||||
.map(|b| strip_span(&to_image, b.start, span_end_including_nl(&to_image, b.end)))
|
||||
.unwrap_or_else(|| to_image.clone());
|
||||
insert_after_line(
|
||||
&stripped,
|
||||
line,
|
||||
&format_block_for_value("hello", None).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert!(to_text.contains("<!-- marqdo-out\nhello\n-->"));
|
||||
assert!(!to_text.contains("![marqdo-out]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_format_picks_image_for_svg_path() {
|
||||
let s = format_block_for_value("figs/a.svg", None).unwrap();
|
||||
assert_eq!(s, "");
|
||||
let t = format_block_for_value("hello", None).unwrap();
|
||||
assert!(t.contains("<!-- marqdo-out"));
|
||||
assert!(format_block_for_value("notes.txt", None).unwrap().contains("<!--"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writeback_map_uses_line_above() {
|
||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
||||
let map = writeback_map(src);
|
||||
assert_eq!(map.get(&3), Some(&"42".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyed_slots_sit_under_anchor_and_do_not_clobber() {
|
||||
let src = "# main\n\n**r = > step**\n\n> print text=after\n";
|
||||
let with_ok = replace_or_insert_keyed_at(src, 3, "ok", "success-1").unwrap();
|
||||
let with_both = replace_or_insert_keyed_at(&with_ok, 3, "error", "fail-1").unwrap();
|
||||
let step_at = with_both.find("r = > step").unwrap();
|
||||
let ok_at = with_both.find("marqdo-out ok").unwrap();
|
||||
let err_at = with_both.find("marqdo-out error").unwrap();
|
||||
let after_at = with_both.find("> print text=after").unwrap();
|
||||
assert!(ok_at > step_at && ok_at < after_at);
|
||||
assert!(err_at > ok_at && err_at < after_at);
|
||||
let updated = replace_or_insert_keyed_at(&with_both, 3, "error", "fail-2").unwrap();
|
||||
assert!(updated.contains("success-1"));
|
||||
assert!(updated.contains("fail-2"));
|
||||
assert!(!updated.contains("fail-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyed_replace_does_not_accumulate_blank_lines() {
|
||||
let src = "# main\n\n> writeback.record\n<!-- marqdo-out ok\nold\n-->\n\n2. *\n";
|
||||
let once = replace_or_insert_keyed_at(src, 3, "ok", "new-1").unwrap();
|
||||
let twice = replace_or_insert_keyed_at(&once, 3, "ok", "new-2").unwrap();
|
||||
let thrice = replace_or_insert_keyed_at(&twice, 3, "ok", "new-3").unwrap();
|
||||
assert_eq!(once.matches("\n\n\n").count(), src.matches("\n\n\n").count());
|
||||
assert_eq!(twice, thrice.replace("new-3", "new-2"));
|
||||
// Exactly one blank line between `-->` and the next statement.
|
||||
let after = thrice.split("-->\n").nth(1).unwrap();
|
||||
assert!(after.starts_with("\n2. *"), "got after -->: {after:?}");
|
||||
assert!(!after.starts_with("\n\n\n"), "blank lines accumulated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unkeyed_replace_does_not_accumulate_blank_lines() {
|
||||
let src = "# main\n\n**x = 1**\n<!-- marqdo-out\nold\n-->\n\n> print text=tail\n";
|
||||
let line = 3u32;
|
||||
let strip_insert = |s: &str, body: &str| {
|
||||
let stripped = find_adjacent_block(s, line)
|
||||
.map(|b| strip_span(s, b.start, span_end_including_nl(s, b.end)))
|
||||
.unwrap_or_else(|| s.to_string());
|
||||
insert_after_line(&stripped, line, &format_comment_block(body, None)).unwrap()
|
||||
};
|
||||
let once = strip_insert(src, "a");
|
||||
let twice = strip_insert(&once, "b");
|
||||
let thrice = strip_insert(&twice, "c");
|
||||
assert_eq!(
|
||||
once.matches("\n\n\n").count(),
|
||||
thrice.matches("\n\n\n").count()
|
||||
);
|
||||
let after = thrice.split("-->\n").nth(1).unwrap();
|
||||
assert!(after.starts_with("\n> print"), "got after -->: {after:?}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user