Release 2.7.0: executable handbooks and native user-site workflows

This commit is contained in:
cflmy committed 2026-11-10 17:03:06 +08:00
1 parent aa0c4d0f55
commit d9aef957f7
562 files changed
+21064 -20387

No files matched your search

+21 -2
View File
@@ -117,6 +117,8 @@ pub struct CallOptions {
pub fs_root: Option<std::path::PathBuf>,
pub session: Option<String>,
pub toget: Option<String>,
/// JSON transport values are literal data, including leading $ and @.
pub literal_args: bool,
}
/// Call `function` in `path` with named arguments (pure-only, no session).
@@ -146,7 +148,7 @@ pub fn call_file_with(
)
})?;
let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) {
let mut session = if opts.session.is_some() || opts.toget.is_some() || (!opts.literal_args && args_need_session(args)) {
let id = opts
.session
.clone()
@@ -156,7 +158,9 @@ pub fn call_file_with(
None
};
let resolved = if let Some(ref mut sess) = session {
let resolved = if opts.literal_args {
args.to_vec()
} else if let Some(ref mut sess) = session {
crate::call_session::resolve_args(sess, args, backend)?
} else {
args.to_vec()
@@ -185,6 +189,9 @@ pub fn call_file_with(
opts.toget.as_deref(),
&value,
)?;
if let Some(step) = sess.steps.last_mut() {
step.literal_args = opts.literal_args;
}
crate::call_session::save_session(sess)?;
}
@@ -276,6 +283,7 @@ fn execute_source_function_with_root(
fs_root: Option<&Path>,
) -> Result<(Value, String)> {
let module = load_module(path)?;
let source = std::fs::read_to_string(path)?;
let fun = find_function_at_line(&module.functions, line).ok_or_else(|| {
call_diag(
Some(path),
@@ -297,6 +305,7 @@ fn execute_source_function_with_root(
));
}
let mut host = HostContext::for_capture(Some(path), caps);
host.set_entry_source(Some(path), &source);
if let Some(root) = fs_root {
let root = root.canonicalize()?;
if !root.is_dir() {
@@ -338,6 +347,7 @@ fn execute_source_function_with_root(
)
})?;
let mut host = HostContext::for_capture(Some(path), caps);
host.set_entry_source(Some(path), &source);
if let Some(root) = fs_root {
let root = root.canonicalize()?;
host.cwd = root.clone();
@@ -404,6 +414,13 @@ pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
Ok(out)
}
/// Decode a JSON object of literal arguments with the standard safe-JSON domain.
/// Unlike command-line $name syntax, JSON strings remain data during replay.
pub fn parse_call_args_json(source: &str) -> Result<Vec<(String, Value)>> {
crate::host::json::decode_arguments(source)
.map_err(|message| call_diag(None, 0, "call.bad_value", message))
}
fn locate_artifact<'a>(
project: &'a SemanticProject,
entry: &Path,
@@ -526,6 +543,8 @@ fn parse_literal(raw: &str) -> Result<Value, String> {
if raw.starts_with('$') || raw.starts_with('@') {
return Ok(Value::Text(raw.to_string()));
}
// Preserve the existing name=value raw-quoted text transport. Escaped,
// structured and multiline data uses the explicit --args-json channel.
if raw.len() >= 2 {
let bytes = raw.as_bytes();
if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"')
+7 -1
View File
@@ -35,6 +35,8 @@ pub struct CallStep {
pub function: String,
pub args: BTreeMap<String, serde_json::Value>,
pub effects: String,
#[serde(default, skip_serializing_if = "is_false")]
pub literal_args: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -43,6 +45,8 @@ pub struct CallStep {
pub toget: Option<String>,
}
fn is_false(value: &bool) -> bool { !*value }
fn sessions_root() -> PathBuf {
if let Ok(p) = std::env::var("MARQDO_CALL_SESSION_DIR") {
return PathBuf::from(p);
@@ -179,7 +183,7 @@ fn replay_live(session: &CallSession, backend: Backend) -> Result<BTreeMap<Strin
for (k, jv) in &step.args {
let mut val = json_to_value(jv).map_err(|e| anyhow::anyhow!(e))?;
if let Value::Text(t) = &val {
if t.starts_with('$') || t.starts_with('@') {
if !step.literal_args && (t.starts_with('$') || t.starts_with('@')) {
let key = &t[1..];
val = live
.get(key)
@@ -249,6 +253,7 @@ pub fn record_step(
function: function.to_string(),
args: arg_map,
effects: effects.as_str(),
literal_args: false,
result: if is_json_friendly(result) {
value_to_json(result).ok()
} else {
@@ -321,6 +326,7 @@ mod write_snapshot_tests {
fs::write(dir.join("log.txt"), "once").unwrap();
for backend in [Backend::Tree, Backend::Bytecode] {
let step = CallStep {
literal_args: false,
file: Path::new(env!("CARGO_MANIFEST_DIR"))
.join("lib/fs.mq.md")
.to_string_lossy()
+22 -2
View File
@@ -18,6 +18,12 @@ pub struct ExtPackage {
}
pub const CATALOG: &[ExtPackage] = &[
ExtPackage {
id: "engineering",
description: "Native process, authenticated service and archive boundaries for executable handbooks",
mq_files: &["engineering/index.mq.md", "engineering/索引.mq.md"],
native_crate: Some("marqdo_plugin_engineering"),
},
ExtPackage {
id: "llm",
description: "OpenAI-compatible chat object (ext/ai/llm)",
@@ -52,17 +58,28 @@ pub const CATALOG: &[ExtPackage] = &[
"data/cache.mq.md",
"data/db.mq.md",
"data/form.mq.md",
"data/表单.mq.md",
"data/admin.mq.md",
"data/后台.mq.md",
"data/view.mq.md",
"data/视图.mq.md",
"data/api.mq.md",
"data/storage.mq.md",
"security/index.mq.md",
"security/auth.mq.md",
"security/鉴权.mq.md",
"security/tenant.mq.md",
"security/rbac.mq.md",
"security/oidc.mq.md",
"net/index.mq.md",
"net/http.mq.md",
"net/url.mq.md",
"net/websocket.mq.md",
"net/实时.mq.md",
"web/index.mq.md",
"web/web.mq.md",
"web/head.mq.md",
"web/页头.mq.md",
"web/网页.mq.md",
"web/_capability/index.mq.md",
"web/page/index.mq.md",
@@ -169,6 +186,7 @@ pub fn native_short_name(crate_or_id: &str) -> &str {
"marqdo_plugin_llm" | "llm" => "llm",
"marqdo_plugin_quantum" | "quantum" => "quantum",
"marqdo_plugin_linalg" | "linalg" => "linalg",
"marqdo_plugin_engineering" | "engineering" => "engineering",
other => other,
}
}
@@ -190,6 +208,7 @@ pub fn native_env_var(short: &str) -> &'static str {
"llm" => "MARQDO_LLM_PLUGIN",
"quantum" => "MARQDO_QUANTUM_PLUGIN",
"linalg" => "MARQDO_LINALG_PLUGIN",
"engineering" => "MARQDO_ENGINEERING_PLUGIN",
_ => "MARQDO_AGENT_PLUGIN",
}
}
@@ -605,7 +624,7 @@ pub fn remove_ext(id: &str) -> Result<()> {
/// point at a freshly built plugin path.
pub fn installed_native_path(name: &str) -> Option<PathBuf> {
let short = native_short_name(name);
if !matches!(short, "agent" | "web" | "llm" | "quantum" | "linalg") {
if !CATALOG.iter().any(|package| package.id == short && package.native_crate.is_some()) {
return None;
}
let lib_name = native_lib_filename(short);
@@ -650,6 +669,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool {
"MARQDO_LLM_PLUGIN",
"MARQDO_QUANTUM_PLUGIN",
"MARQDO_LINALG_PLUGIN",
"MARQDO_ENGINEERING_PLUGIN",
] {
if let Ok(p) = env::var(key) {
let p = PathBuf::from(p);
@@ -659,7 +679,7 @@ pub fn path_is_trusted_plugin(path: &Path) -> bool {
}
}
}
for short in ["agent", "web", "llm", "quantum", "linalg"] {
for short in CATALOG.iter().filter_map(|p| p.native_crate).map(native_short_name) {
if let Ok(found) = find_native_plugin(short) {
let found = found.canonicalize().unwrap_or(found);
if found == path {
+10
View File
@@ -290,6 +290,8 @@ pub enum HostFn {
ListIntersection = 280,
ListDifference = 281,
TableSummarize = 282,
DocumentTable = 283,
FsResolve = 284,
}
/// Single source of truth for every host function. `<TAB>` slimming
@@ -578,6 +580,8 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[
HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] },
HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] },
HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] },
HostFnDef { id: 283, f: HostFn::DocumentTable, name: "host_document_table", required: &["text"], optional: &["title", "index"] },
HostFnDef { id: 284, f: HostFn::FsResolve, name: "host_fs_resolve", required: &["path"], optional: &[] },
];
@@ -610,6 +614,8 @@ impl HostFn {
"host_document_links" => Self::DocumentLinks,
"host_document_replace_table" => Self::DocumentReplaceTable,
"host_document_tables" => Self::DocumentTables,
"host_document_table" => Self::DocumentTable,
"host_fs_resolve" => Self::FsResolve,
"host_document_replace_section" => Self::DocumentReplaceSection,
"host_document_section" => Self::DocumentSection,
"host_document_sections" => Self::DocumentSections,
@@ -897,6 +903,8 @@ impl HostFn {
Self::DocumentLinks => &["pure"],
Self::DocumentReplaceTable => &["pure"],
Self::DocumentTables => &["pure"],
Self::DocumentTable => &["pure"],
Self::FsResolve => &["fs.read"],
Self::DocumentReplaceSection => &["pure"],
Self::DocumentSection => &["pure"],
Self::DocumentSections => &["pure"],
@@ -1206,6 +1214,7 @@ pub fn call_host(
HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound),
HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound),
HostFn::DocumentTables => super::document::call(ctx, fn_id, bound),
HostFn::DocumentTable => super::document::call(ctx, fn_id, bound),
HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound),
HostFn::DocumentSection => super::document::call(ctx, fn_id, bound),
HostFn::DocumentSections => super::document::call(ctx, fn_id, bound),
@@ -1275,6 +1284,7 @@ pub fn call_host(
HostFn::FsMakeDirs => fs::make_dirs(ctx, require(bound, "path")?),
HostFn::FsRemoveTree => fs::remove_tree(ctx, require(bound, "path")?),
HostFn::FsStat => fs::stat(ctx, require(bound, "path")?),
HostFn::FsResolve => fs::resolve(ctx, require(bound, "path")?),
HostFn::FsWalk => fs::walk(ctx, require(bound, "path")?),
HostFn::NowUnix => time::now_unix(),
HostFn::NowMs => time::now_ms(),
+97
View File
@@ -157,6 +157,46 @@ fn tables(text: &str) -> Vec<Table> {
}
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(&section_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 {
@@ -232,6 +272,19 @@ pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value
})
.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)?;
@@ -356,3 +409,47 @@ pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result<Value
_ => 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)),
])]));
}
}
+2 -2
View File
@@ -407,7 +407,7 @@ impl DocumentSession {
let entry = module
.functions
.iter()
.find(|f| f.name == "main" && f.is_object())
.find(|f| f.name == "main")
.or_else(|| {
let objs: Vec<_> = module.functions.iter().filter(|f| f.is_object()).collect();
if objs.len() == 1 {
@@ -416,7 +416,7 @@ impl DocumentSession {
None
}
})
.ok_or_else(|| "notebook: no `# main` (or sole object) to index".to_string())?;
.ok_or_else(|| "notebook: no `main` entry (or sole object) to index".to_string())?;
let mut cells = Vec::new();
let mut seen = HashSet::new();
collect_cells(&entry.body, &mut cells, &mut seen)?;
+18
View File
@@ -32,6 +32,24 @@ fn text_body(v: &Value) -> Result<&str, String> {
}
}
/// 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)? {
+35
View File
@@ -97,6 +97,41 @@ pub(crate) fn decode_text(text: &str) -> Result<Value, DecodeError> {
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(),
+18 -1
View File
@@ -530,10 +530,26 @@ unsafe extern "C" fn host_query(
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "run_artifact requires `path`".to_string())?;
let p = std::path::PathBuf::from(path);
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 {
@@ -547,6 +563,7 @@ unsafe extern "C" fn host_query(
}
let opts = crate::RunOptions {
binds,
fs_root,
allow_fs_write: ctx.caps.fs_write,
allow_exec: ctx.caps.exec,
allow_net: ctx.caps.net,
+23 -13
View File
@@ -495,28 +495,38 @@ fn append_eof(source: &str, block: &str) -> String {
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_else(|| "writeback: no entry file".to_string())?;
std::fs::write(path, source).map_err(|e| format!("writeback write {}: {e}", path.display()))?;
ctx.entry_source = Some(source.to_string());
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 {
if let Ok(text) = std::fs::read_to_string(path) {
return Ok(text);
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())
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> {
+36 -4
View File
@@ -175,6 +175,16 @@ enum Commands {
#[arg(long, default_value = "none")]
effects: String,
/// Literal named arguments as a JSON object; '-' reads stdin (no shell/argv size limit).
/// JSON strings never resolve call-session $name or @name references.
#[arg(long, value_name = "FILE_OR_STDIN")]
args_json: Option<PathBuf>,
/// Return a failing exit status when the function returns Result {ok:false}.
/// The JSON result is preserved; no effect is retried or rolled back.
#[arg(long)]
require_ok: bool,
/// Directory available to file tools; defaults to the called file directory.
#[arg(long)]
fs_root: Option<PathBuf>,
@@ -850,6 +860,8 @@ fn try_main(cli: Cli) -> Result<i32> {
file,
function,
args,
args_json,
require_ok,
json,
backend,
effects,
@@ -861,16 +873,32 @@ fn try_main(cli: Cli) -> Result<i32> {
let effects = marqdo::call::CallEffects::parse(&effects)?;
let (arg_tokens, trailing_toget) = marqdo::call::split_toget(&args)?;
let toget = toget.or(trailing_toget);
let parsed = marqdo::call::parse_call_args(&arg_tokens)?;
let literal_args = args_json.is_some();
let parsed = if let Some(input) = args_json {
use std::io::Read;
if !arg_tokens.is_empty() {
anyhow::bail!("--args-json cannot be combined with name=value arguments");
}
let mut source = String::new();
if input.as_os_str() == "-" {
std::io::stdin().take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?;
} else {
std::fs::File::open(&input)?.take(64 * 1024 * 1024 + 1).read_to_string(&mut source)?;
}
if source.len() > 64 * 1024 * 1024 { anyhow::bail!("--args-json exceeds 64 MiB"); }
marqdo::call::parse_call_args_json(&source)?
} else {
marqdo::call::parse_call_args(&arg_tokens)?
};
let session = session.or_else(|| {
if toget.is_some()
|| parsed.iter().any(|(_, v)| {
|| (!literal_args && parsed.iter().any(|(_, v)| {
matches!(
v,
marqdo::value::Value::Text(t)
if t.starts_with('$') || t.starts_with('@')
)
})
}))
{
Some(marqdo::call_session::default_session_id())
} else {
@@ -887,6 +915,7 @@ fn try_main(cli: Cli) -> Result<i32> {
fs_root,
session,
toget,
literal_args,
},
)
})();
@@ -902,7 +931,10 @@ fn try_main(cli: Cli) -> Result<i32> {
} else {
println!("{}", value.as_display());
}
Ok(0)
let failed = require_ok && matches!(&value,
marqdo::value::Value::Map(fields) if fields.iter().any(|(k,v)|
k == "ok" && matches!(v, marqdo::value::Value::Bool(false))));
Ok(if failed { 1 } else { 0 })
}
Err(err) => {
let diag = Diagnostic::find(&err).cloned().unwrap_or_else(|| {
+46 -7
View File
@@ -124,7 +124,9 @@ fn parse_call_arg_value_mode(input: &str, prefer_var: bool, allow_call: bool) ->
Err(_) => Ok(parse_interp(s)),
};
}
if has_hyphenated_prose(s) {
// Nested calls may contain hyphenated paths in their own quoted args.
// The inner argument parser still preserves plain hyphenated prose.
if has_hyphenated_prose(s) && !(allow_call && s.contains('(')) {
return Ok(parse_interp(s));
}
match parse_expr_opts(s, prefer_var, allow_call) {
@@ -577,6 +579,16 @@ impl<'a> Parser<'a> {
if !self.eat("`") {
bail!("unterminated `name`");
}
// Parse a quoted receiver's explicit method before its value.
if self.allow_paren_call && self.rest().starts_with('.') {
let call_start = start - 1;
if let Some((call, used)) = try_paren_call(&self.src[call_start..], self.prefer_var)? {
if call.receiver.is_some() {
self.i = call_start + used;
return Ok(Expr::Call(call));
}
}
}
return self.parse_index_chain(Expr::Var(name));
}
// `礼貌 [问候] x` — after quotes/ticks so `[DONE]` inside strings is safe.
@@ -1109,11 +1121,13 @@ pub fn parse_call_tail(s: &str, prefer_var: bool) -> Result<(CallExpr, usize)> {
}
let callee_tok = {
let mut parts = s.split_whitespace();
parts
.next()
.ok_or_else(|| anyhow::anyhow!("missing callee"))?
.to_string()
let mut quoted = false;
let end = s.char_indices().find_map(|(i,c)| {
if c == '`' { quoted = !quoted; }
(!quoted && (c.is_whitespace() || c == ')')).then_some(i)
}).unwrap_or(s.len());
if end == 0 { bail!("missing callee"); }
s[..end].to_string()
};
let (receiver, callee, path) = split_callee(&callee_tok);
@@ -1435,7 +1449,7 @@ fn try_named_arg(s: &str) -> Option<(String, &str)> {
}
return Some((key.to_string(), &s[i + 1..]));
}
if c.is_whitespace() {
if c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | ',' | '"' | '\'' | '`') {
return None;
}
}
@@ -1695,6 +1709,31 @@ pub fn parse_call_after_gt(after_gt: &str, prefer_var: bool) -> Result<CallExpr>
mod tests {
use super::*;
#[test]
fn occlusion_keeps_receiver_calls_and_closing_delimiters_separate() {
for source in ["[Read probabilities](`c`.probabilities())",
"[Read probabilities](> `c`.probabilities)",
"[Set angle](`c`.rotate(angle=access(m, \"angle\")))"] {
let e = parse_expr_markup(source,true,Markup::Occlusion).unwrap();
let Expr::Occluded { payload: Some(payload), .. } = e else { panic!("{source}") };
let Expr::Call(call) = *payload else { panic!("{source}") };
assert_eq!(call.receiver.as_deref(),Some("c"));
assert!(!call.callee.contains(')'));
}
assert!(parse_expr_markup("[Read file size](access(fs.stat(path=\"a\"), \"size\"))",
true,Markup::Occlusion).is_ok());
}
#[test]
fn nested_call_with_a_hyphenated_file_path_stays_executable() {
let e = parse_expr_prefer_var("toml.parse(text=fs.read_text(path=\"crates/marqdo-wasm/Cargo.toml\"))").unwrap();
let Expr::Call(c) = e else { panic!("expected outer call") };
let crate::ast::Arg::Named { value, .. } = &c.args[0] else { panic!("expected named argument") };
assert!(matches!(value, Expr::Call(_)), "{value:?}");
}
#[test]
fn bare_var_footnote_index() {
let e = parse_expr("ev[^result]").unwrap();
+68 -10
View File
@@ -13,6 +13,7 @@ pub use prose::{
};
use anyhow::{bail, Result};
use std::collections::HashSet;
use crate::ast::{
BranchArm, Expr, Function, Import, IndexKey, Literal, Module, Param, Stmt, Use,
@@ -44,7 +45,7 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
continue;
}
if is_heading(trimmed) {
functions.push(cur.parse_function(1)?);
functions.push(cur.parse_function(1, &HashSet::new())?);
} else if line.kind == LineKind::Comment {
// Intro paragraphs may still contain return-shaped italics (`返回*值*`)
// or leftover soft emphasis; executable prose belongs inside functions.
@@ -78,6 +79,18 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
Ok(module)
}
/// Parse one GFM table with the source language's cell and shape rules.
/// Document readers reject nonliteral expressions before using the value.
pub(crate) fn parse_gfm_table(source: &str) -> Result<Expr> {
let lines = classify_source(source);
let mut cursor = Cursor::new(&lines);
let table = cursor.consume_table()?;
if cursor.skip_noise() {
bail!("unexpected content after the selected GFM table");
}
Ok(table)
}
struct Cursor<'a> {
lines: &'a [ClassifiedLine],
i: usize,
@@ -282,7 +295,7 @@ impl<'a> Cursor<'a> {
Ok(())
}
fn parse_function(&mut self, min_level: u8) -> Result<Function> {
fn parse_function(&mut self, min_level: u8, inherited: &HashSet<String>) -> Result<Function> {
let line = self.bump().unwrap();
let (level, raw_name) = parse_heading(line.text.trim())
.ok_or_else(|| anyhow::anyhow!("{}:1: expected heading", line.line_no))?;
@@ -317,7 +330,13 @@ impl<'a> Cursor<'a> {
if is_heading(trimmed) {
let (nl, _) = parse_heading(trimmed).unwrap();
if nl > level {
fun.children.push(self.parse_function(level + 1)?);
let mut visible = inherited.clone();
let mut unused_reads = HashSet::new();
let mut unused_declarations = Vec::new();
collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations);
visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone()));
visible.extend(fun.params.iter().map(|param| param.name.clone()));
fun.children.push(self.parse_function(level + 1, &visible)?);
continue;
}
break;
@@ -369,7 +388,13 @@ impl<'a> Cursor<'a> {
if is_heading(trimmed) {
let (nl, _) = parse_heading(trimmed).unwrap();
if nl > level {
fun.children.push(self.parse_function(level + 1)?);
let mut visible = inherited.clone();
let mut unused_reads = HashSet::new();
let mut unused_declarations = Vec::new();
collect_names_needing_input(&fun.body, &mut visible, &mut unused_reads, &HashSet::new(), &mut unused_declarations);
visible.extend(prose_decls.iter().map(|(name, _, _)| name.clone()));
visible.extend(fun.params.iter().map(|param| param.name.clone()));
fun.children.push(self.parse_function(level + 1, &visible)?);
continue;
}
break;
@@ -445,7 +470,7 @@ impl<'a> Cursor<'a> {
// 契约提取(T2.1)必须在升参推断**之前**:契约表的单元不污染推断。
extract_function_contract(&mut fun, self.lines)?;
merge_inferred_params(&mut fun, &prose_decls)?;
merge_inferred_params(&mut fun, &prose_decls, inherited)?;
Ok(fun)
}
@@ -2104,11 +2129,15 @@ fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Re
fn merge_inferred_params(
fun: &mut Function,
prose_decls: &[(String, Option<String>, u32)],
inherited: &HashSet<String>,
) -> Result<()> {
use std::collections::HashSet;
let mut needs_input = HashSet::new();
let mut bound = HashSet::new();
// Captured entry/object bindings are available before the child body.
// An explicit prose input still shadows an outer binding of the same name.
let explicit: HashSet<_> = prose_decls.iter().map(|(name, _, _)| name.clone()).collect();
let mut bound: HashSet<_> = inherited.difference(&explicit).cloned().collect();
let mut assign_decls = Vec::new();
// Defaults execute before the body. Reads used only there still require
// declared inputs; later body assignments cannot satisfy those reads.
@@ -2129,6 +2158,8 @@ fn merge_inferred_params(
&mut assign_decls,
);
needs_input.retain(|name| !inherited.contains(name) || explicit.contains(name));
// Declaration order is source order: backtick mentions and first assignment
// left-hand sides. An assignment promotes only when its right-hand side (or a
// later read) still needs an external value.
@@ -2211,7 +2242,7 @@ fn collect_names_needing_input(
let mut reads = std::collections::HashSet::new();
collect_reads_expr(value, &mut reads);
for r in reads {
if !bound.contains(&r) {
if !bound.contains(&r) && !loop_items.contains(&r) {
needs.insert(r);
}
}
@@ -2220,7 +2251,7 @@ fn collect_names_needing_input(
let mut reads = std::collections::HashSet::new();
collect_reads_call(call, &mut reads);
for r in reads {
if !bound.contains(&r) {
if !bound.contains(&r) && !loop_items.contains(&r) {
needs.insert(r);
}
}
@@ -2229,7 +2260,7 @@ fn collect_names_needing_input(
let mut reads = std::collections::HashSet::new();
collect_reads_expr(value, &mut reads);
for r in reads {
if !bound.contains(&r) {
if !bound.contains(&r) && !loop_items.contains(&r) {
needs.insert(r);
}
}
@@ -2242,7 +2273,7 @@ fn collect_names_needing_input(
let mut reads = std::collections::HashSet::new();
collect_reads_expr(c, &mut reads);
for r in reads {
if !bound.contains(&r) {
if !bound.contains(&r) && !loop_items.contains(&r) {
needs.insert(r);
}
}
@@ -2931,3 +2962,30 @@ mod escaped_gfm_cell_tests {
assert!(format!("{:?}", module.functions[0].body).contains("source|skill"));
}
}
#[cfg(test)]
mod lexical_input_tests {
use super::*;
#[test]
fn child_updates_capture_existing_entry_state_without_extra_inputs() {
let source="# main\n\n**count = 0**\n\n## bump\n\nWe **count = count + 1** and return *count*.\n";
let module=parse_source(source).unwrap();
assert!(module.functions[0].children[0].params.is_empty());
}
#[test]
fn explicit_prose_inputs_can_shadow_parent_bindings() {
let source="# main\n\n**count = 0**\n\n## add\n\nUse `count` for this independent call.\nReturn *(count + 1)*.\n";
let module=parse_source(source).unwrap();
let params=&module.functions[0].children[0].params;
assert_eq!(params.len(),1);
assert_eq!(params[0].name,"count");
}
#[test]
fn reading_a_loop_item_in_a_branch_does_not_promote_a_later_local() {
let source="## select\n\nUse `values`.\n- [Inspect values](for values as item)\n 1. `item` != \"\"\n We **output = item**.\n\nWe **item = \"done\"** and return *item*.\n";
let module=parse_source(source).unwrap();
let params=&module.functions[0].params;
assert_eq!(params.len(),1);
assert_eq!(params[0].name,"values");
}
}
+27 -1
View File
@@ -292,7 +292,7 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> {
if let Some(stripped) = after.strip_prefix('=') {
// Quoted defaults may contain prose delimiters, glob stars or spaces.
// Keep the same quoted literal accepted by explicit parameter defaults.
let def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() {
let mut def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() {
let mut escaped = false;
stripped
.char_indices()
@@ -316,6 +316,13 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> {
})
.unwrap_or(stripped.len())
};
// English sentence punctuation belongs to narration after a literal.
// Keep quoted strings, dotted names and decimal syntax unchanged.
if let Some(literal) = stripped[..def_end].strip_suffix('.') {
if matches!(literal, "True" | "False" | "true" | "false" | "None" | "真" | "假" | "无" | "空") {
def_end -= 1;
}
}
let default = stripped[..def_end].to_string();
let next = after_tick + 1 + def_end;
return Some((
@@ -389,6 +396,25 @@ mod tests {
}
}
#[test]
fn sentence_period_after_boolean_or_none_is_not_part_of_the_default() {
for (line, expected) in [
("Use `flag`=False. Continue.", "False"),
("Use `flag`=True.", "True"),
("Use `value`=None.", "None"),
("使用`值`=假. 继续。", "假"),
("Use `text`=\"False.\".", "\"False.\""),
("Use `text`=module.value.", "module.value."),
("Use `rate`=0.5.", "0.5."),
] {
let bits = scan_prose_line(line);
match &bits[..] {
[ProseBit::Decl { default: Some(actual), .. }] => assert_eq!(actual, expected, "{line}"),
_ => panic!("unexpected prose scan: {bits:?}"),
}
}
}
#[test]
fn quoted_defaults_keep_delimiters_and_escaped_quotes() {
let line = r#"输入 `pattern`="**";`mime`="text/plain;charset=utf-8";`label`="a, b \"quoted\""。"#;
+7 -1
View File
@@ -4032,6 +4032,12 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
"stream",
"Streaming in the panel below…".to_string(),
)
} else if vm.library_document {
(
"pending",
"module",
"这是可调用模块,未自动执行。通过 marqdo call 选择函数并提供参数。".to_string(),
)
} else if vm.ok {
(
"ok",
@@ -4047,7 +4053,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
} else {
("fail", "fail", escape(&vm.stderr))
};
let stdin_panel = if vm.input_prompts.is_empty() {
let stdin_panel = if vm.library_document || vm.input_prompts.is_empty() {
String::new()
} else {
let placeholder = vm.input_prompts.join("\n");
+21 -3
View File
@@ -430,9 +430,18 @@ pub(crate) fn build_file_view_with_exec(
Vec::new(),
),
};
// Named tools are readable modules, not failed programs. Preserve actual
// execution for main, object entries and Artifact declarations.
let library_document = module_opt.as_ref().is_some_and(|module| {
!module.functions.is_empty()
&& module.functions.iter().all(|f| !f.is_object() && f.name != "main")
&& !module.metadata_raw.iter().any(|(key, _)| key == "type" || key == "类型")
});
let effective = effective_stdin(&source, stdin_lines);
let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source);
let show_stream = module_opt.as_ref().map(uses_stream_panel).unwrap_or(false);
let awaiting_input = !library_document
&& awaiting_preset_input(&input_prompts, stdin_lines, &source);
let show_stream = !library_document
&& module_opt.as_ref().map(uses_stream_panel).unwrap_or(false);
// Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`.
let auto_stream = live
&& show_stream
@@ -454,6 +463,14 @@ pub(crate) fn build_file_view_with_exec(
Vec::new(),
String::from(r#"<p class="vars-skipped">skipped</p>"#),
)
} else if library_document {
(
String::new(),
String::new(),
true,
Vec::new(),
String::from(r#"<p class="vars-skipped">Choose a named function with marqdo call.</p>"#),
)
} else if awaiting_input || auto_stream {
(
String::new(),
@@ -481,7 +498,7 @@ pub(crate) fn build_file_view_with_exec(
}
};
// Re-read after run so writeback slots / workbook edits show in Structure.
if execute && !awaiting_input && !auto_stream {
if execute && !library_document && !awaiting_input && !auto_stream {
if let Ok(next) = fs::read_to_string(abs) {
source = next;
}
@@ -579,6 +596,7 @@ pub(crate) fn build_file_view_with_exec(
stdout,
stderr,
ok,
library_document,
preset_stdin: effective.join("\n"),
input_prompts,
awaiting_input,
+2
View File
@@ -30,6 +30,8 @@ pub struct FileViewModel {
pub stdout: String,
pub stderr: String,
pub ok: bool,
/// A callable-only module has no automatic program entry.
pub library_document: bool,
/// Text shown in the live-view preset stdin box.
pub preset_stdin: String,
/// One entry per `input` / `输入` call (prompt text; may be empty).