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

+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> {