Make file subtasks return #main value and expose it as plan.result.
Quiet spawn still hides child stdout; workbooks solidify to **returns**, agent-kb lives in the plugin, and multi-step follows OKF file relay rather than print-based answers. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fbece725e1
commit
d1b33c78c6
55 files changed
+3498
-169
No files matched your search
+348
-27
@@ -1,4 +1,4 @@
|
||||
//! OKF-compatible catalog generation: `marqdo catalog` / `sync`.
|
||||
//! OKF-compatible catalog generation: `marqdo catalog` / `sync` (O1+O3).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -19,6 +19,25 @@ struct ModuleInfo {
|
||||
title: String,
|
||||
imports: Vec<String>,
|
||||
exports: Vec<String>,
|
||||
/// Optional OKF trust fields copied from source frontmatter.
|
||||
verified_by: Option<String>,
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
struct ConceptInfo {
|
||||
/// Relative id e.g. `concepts/tasks/<sig>`
|
||||
id: String,
|
||||
concept_type: String,
|
||||
title: String,
|
||||
status: String,
|
||||
resource: Option<String>,
|
||||
skill: Option<String>,
|
||||
description: Option<String>,
|
||||
verified_by: Option<String>,
|
||||
/// Absolute path of source concept page (to copy).
|
||||
abs: PathBuf,
|
||||
/// Relative path under out_dir e.g. `concepts/tasks/x.md`
|
||||
out_rel: String,
|
||||
}
|
||||
|
||||
pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
|
||||
@@ -31,17 +50,20 @@ pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
|
||||
opts.path.clone()
|
||||
};
|
||||
let root = root.canonicalize().unwrap_or(root);
|
||||
let out_canon = opts.out_dir.canonicalize().unwrap_or(opts.out_dir.clone());
|
||||
|
||||
let mut files = Vec::new();
|
||||
if opts.path.is_file() {
|
||||
files.push(opts.path.canonicalize().unwrap_or(opts.path.clone()));
|
||||
} else {
|
||||
collect_mq_md(&root, &root, &mut files)?;
|
||||
collect_mq_md(&root, &root, &out_canon, &mut files)?;
|
||||
files.sort();
|
||||
}
|
||||
|
||||
fs::create_dir_all(opts.out_dir.join("modules"))
|
||||
.with_context(|| format!("create {}", opts.out_dir.display()))?;
|
||||
fs::create_dir_all(opts.out_dir.join("concepts"))
|
||||
.with_context(|| format!("create concepts under {}", opts.out_dir.display()))?;
|
||||
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
let mut modules = Vec::new();
|
||||
@@ -53,6 +75,10 @@ pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
|
||||
.unwrap_or(abs)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
// Skip agent-kb resources (executable skills) from Module table — they appear as concepts.
|
||||
if rel.contains("/.marqdo/agent-kb/") || rel.starts_with(".marqdo/agent-kb/") {
|
||||
continue;
|
||||
}
|
||||
match inspect_file(abs, &rel) {
|
||||
Ok(info) => modules.push(info),
|
||||
Err(e) => {
|
||||
@@ -62,22 +88,36 @@ pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let catalog_yaml = render_catalog_yaml(&modules, version);
|
||||
let mut concepts = Vec::new();
|
||||
collect_agent_concepts(&root, &out_canon, &mut concepts)?;
|
||||
concepts.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
|
||||
for c in &concepts {
|
||||
let dest = opts.out_dir.join(&c.out_rel);
|
||||
if let Some(p) = dest.parent() {
|
||||
fs::create_dir_all(p)?;
|
||||
}
|
||||
let body = fs::read_to_string(&c.abs)
|
||||
.with_context(|| format!("read concept {}", c.abs.display()))?;
|
||||
fs::write(&dest, body)?;
|
||||
}
|
||||
|
||||
let catalog_yaml = render_catalog_yaml(&modules, &concepts, version);
|
||||
fs::write(opts.out_dir.join("catalog.yaml"), catalog_yaml)?;
|
||||
|
||||
let index_md = render_index_md(&modules, version);
|
||||
let index_md = render_index_md(&modules, &concepts, version);
|
||||
fs::write(opts.out_dir.join("index.md"), index_md)?;
|
||||
|
||||
for m in &modules {
|
||||
let stem = m.resource.replace('/', "__").replace('\\', "__");
|
||||
let stem = stem.trim_end_matches(".mq.md");
|
||||
let stem = module_stem(&m.resource);
|
||||
let path = opts.out_dir.join("modules").join(format!("{stem}.md"));
|
||||
fs::write(&path, render_module_md(m, version))?;
|
||||
fs::write(&path, render_module_md(m, &modules, version))?;
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"marqdo catalog: {} module(s) → {}",
|
||||
"marqdo catalog: {} module(s), {} concept(s) → {}",
|
||||
modules.len(),
|
||||
concepts.len(),
|
||||
opts.out_dir.display()
|
||||
);
|
||||
if had_err {
|
||||
@@ -86,12 +126,30 @@ pub fn write_catalog(opts: CatalogOptions) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_mq_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
fn module_stem(resource: &str) -> String {
|
||||
resource
|
||||
.replace('/', "__")
|
||||
.replace('\\', "__")
|
||||
.trim_end_matches(".mq.md")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn collect_mq_md(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
out_canon: &Path,
|
||||
out: &mut Vec<PathBuf>,
|
||||
) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let p = entry.path();
|
||||
if p.is_dir() {
|
||||
collect_mq_md(root, &p, out)?;
|
||||
if let Ok(canon) = p.canonicalize() {
|
||||
if canon == *out_canon {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
collect_mq_md(root, &p, out_canon, out)?;
|
||||
} else if p
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
@@ -104,14 +162,100 @@ fn collect_mq_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Find `**/.marqdo/agent-kb/concepts/**/*.md` under scan root.
|
||||
fn collect_agent_concepts(
|
||||
root: &Path,
|
||||
out_canon: &Path,
|
||||
out: &mut Vec<ConceptInfo>,
|
||||
) -> Result<()> {
|
||||
walk_for_concepts(root, root, out_canon, out)
|
||||
}
|
||||
|
||||
fn walk_for_concepts(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
out_canon: &Path,
|
||||
out: &mut Vec<ConceptInfo>,
|
||||
) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let p = entry.path();
|
||||
if p.is_dir() {
|
||||
if let Ok(canon) = p.canonicalize() {
|
||||
if canon == *out_canon {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
walk_for_concepts(root, &p, out_canon, out)?;
|
||||
continue;
|
||||
}
|
||||
let Some(name) = p.file_name().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !name.ends_with(".md") || name.ends_with(".mq.md") {
|
||||
continue;
|
||||
}
|
||||
let rel = p
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(&p)
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let marker = "/.marqdo/agent-kb/concepts/";
|
||||
let idx = if let Some(i) = rel.find(marker) {
|
||||
i + marker.len()
|
||||
} else if let Some(rest) = rel.strip_prefix(".marqdo/agent-kb/concepts/") {
|
||||
// path relative from agent-kb concepts
|
||||
let _ = rest;
|
||||
0
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let under = if idx == 0 {
|
||||
rel.strip_prefix(".marqdo/agent-kb/concepts/")
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
} else {
|
||||
rel[idx..].to_string()
|
||||
};
|
||||
if under.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let source = fs::read_to_string(&p)?;
|
||||
let concept_type =
|
||||
extract_fm_field(&source, "type").unwrap_or_else(|| "Marqdo Concept".into());
|
||||
let title = extract_fm_field(&source, "title").unwrap_or_else(|| under.clone());
|
||||
let status = extract_fm_field(&source, "status").unwrap_or_else(|| "stable".into());
|
||||
let resource = extract_fm_field(&source, "resource");
|
||||
let skill = extract_fm_field(&source, "skill");
|
||||
let description = extract_fm_field(&source, "description");
|
||||
let verified_by = extract_nested_by(&source, "verified");
|
||||
let id = format!("concepts/{}", under.trim_end_matches(".md"));
|
||||
let out_rel = format!("concepts/{under}");
|
||||
out.push(ConceptInfo {
|
||||
id,
|
||||
concept_type,
|
||||
title,
|
||||
status,
|
||||
resource,
|
||||
skill,
|
||||
description,
|
||||
verified_by,
|
||||
abs: p,
|
||||
out_rel,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inspect_file(abs: &Path, rel: &str) -> Result<ModuleInfo> {
|
||||
let source = fs::read_to_string(abs)?;
|
||||
let imports = extract_frontmatter_imports(&source);
|
||||
let title = extract_frontmatter_title(&source)
|
||||
.unwrap_or_else(|| rel.trim_end_matches(".mq.md").to_string());
|
||||
let verified_by = extract_nested_by(&source, "verified");
|
||||
let sources = extract_fm_list(&source, "sources");
|
||||
|
||||
let mut exports = Vec::new();
|
||||
// Prefer parse for accurate top-level fn names
|
||||
match parse_source(&source) {
|
||||
Ok(module) => {
|
||||
for f in &module.functions {
|
||||
@@ -140,6 +284,8 @@ fn inspect_file(abs: &Path, rel: &str) -> Result<ModuleInfo> {
|
||||
title,
|
||||
imports,
|
||||
exports,
|
||||
verified_by,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -165,23 +311,100 @@ fn extract_frontmatter_imports(source: &str) -> Vec<String> {
|
||||
}
|
||||
|
||||
fn extract_frontmatter_title(source: &str) -> Option<String> {
|
||||
extract_fm_field(source, "title")
|
||||
}
|
||||
|
||||
fn extract_fm_field(source: &str, key: &str) -> Option<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return None;
|
||||
}
|
||||
let prefix = format!("{key}:");
|
||||
for line in lines.iter().skip(1) {
|
||||
let t = line.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
if let Some(v) = t.strip_prefix("title:") {
|
||||
return Some(v.trim().trim_matches('"').to_string());
|
||||
if let Some(rest) = t.strip_prefix(&prefix) {
|
||||
return Some(rest.trim().trim_matches('"').to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `verified:\n by: foo` → Some("foo")
|
||||
fn extract_nested_by(source: &str, block: &str) -> Option<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return None;
|
||||
}
|
||||
let mut in_block = false;
|
||||
for line in lines.iter().skip(1) {
|
||||
let t = line.trim_end();
|
||||
if t.trim() == "---" {
|
||||
break;
|
||||
}
|
||||
if t.trim() == format!("{block}:") || t.trim().starts_with(&format!("{block}:")) {
|
||||
// inline `verified: { by: x }` not supported; block form:
|
||||
if t.trim() == format!("{block}:") {
|
||||
in_block = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if in_block {
|
||||
let trimmed = t.trim();
|
||||
if trimmed.starts_with("by:") {
|
||||
return Some(
|
||||
trimmed
|
||||
.trim_start_matches("by:")
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if !trimmed.is_empty() && !line.starts_with(' ') && !line.starts_with('\t') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_fm_list(source: &str, key: &str) -> Vec<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut in_list = false;
|
||||
let header = format!("{key}:");
|
||||
for line in lines.iter().skip(1) {
|
||||
let t = line.trim_end();
|
||||
if t.trim() == "---" {
|
||||
break;
|
||||
}
|
||||
if t.trim() == header || t.trim() == format!("{key}: []") {
|
||||
if t.trim().ends_with("[]") {
|
||||
return Vec::new();
|
||||
}
|
||||
in_list = true;
|
||||
continue;
|
||||
}
|
||||
if in_list {
|
||||
let trimmed = t.trim();
|
||||
if let Some(rest) = trimmed.strip_prefix("- ") {
|
||||
out.push(rest.trim().trim_matches('"').to_string());
|
||||
} else if !trimmed.is_empty() && !line.starts_with(' ') && !line.starts_with('\t') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn yaml_escape(s: &str) -> String {
|
||||
if s.is_empty()
|
||||
|| s.contains(':')
|
||||
@@ -197,7 +420,20 @@ fn yaml_escape(s: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_catalog_yaml(modules: &[ModuleInfo], version: &str) -> String {
|
||||
fn import_path(imp: &str) -> &str {
|
||||
imp.split(" as ").next().unwrap_or(imp).trim()
|
||||
}
|
||||
|
||||
fn resolve_import_module<'a>(imp: &str, modules: &'a [ModuleInfo]) -> Option<&'a ModuleInfo> {
|
||||
let path = import_path(imp);
|
||||
modules.iter().find(|m| {
|
||||
m.resource == path
|
||||
|| m.resource.ends_with(path)
|
||||
|| m.resource.ends_with(&format!("/{path}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn render_catalog_yaml(modules: &[ModuleInfo], concepts: &[ConceptInfo], version: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("# GENERATED by marqdo — do not edit by hand\n");
|
||||
out.push_str("type: Marqdo Catalog\n");
|
||||
@@ -226,11 +462,47 @@ fn render_catalog_yaml(modules: &[ModuleInfo], version: &str) -> String {
|
||||
out.push_str(" kind: fn\n");
|
||||
}
|
||||
}
|
||||
if let Some(ref v) = m.verified_by {
|
||||
out.push_str(" verified:\n");
|
||||
out.push_str(&format!(" by: {}\n", yaml_escape(v)));
|
||||
}
|
||||
if !m.sources.is_empty() {
|
||||
out.push_str(" sources:\n");
|
||||
for s in &m.sources {
|
||||
out.push_str(&format!(" - {}\n", yaml_escape(s)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str("concepts:\n");
|
||||
if concepts.is_empty() {
|
||||
// keep key present for consumers
|
||||
out.push_str(" []\n");
|
||||
} else {
|
||||
for c in concepts {
|
||||
out.push_str(&format!(" - id: {}\n", yaml_escape(&c.id)));
|
||||
out.push_str(&format!(" type: {}\n", yaml_escape(&c.concept_type)));
|
||||
out.push_str(&format!(" title: {}\n", yaml_escape(&c.title)));
|
||||
out.push_str(&format!(" status: {}\n", yaml_escape(&c.status)));
|
||||
out.push_str(&format!(" page: {}\n", yaml_escape(&c.out_rel)));
|
||||
if let Some(ref r) = c.resource {
|
||||
out.push_str(&format!(" resource: {}\n", yaml_escape(r)));
|
||||
}
|
||||
if let Some(ref s) = c.skill {
|
||||
out.push_str(&format!(" skill: {}\n", yaml_escape(s)));
|
||||
}
|
||||
if let Some(ref d) = c.description {
|
||||
out.push_str(&format!(" description: {}\n", yaml_escape(d)));
|
||||
}
|
||||
if let Some(ref v) = c.verified_by {
|
||||
out.push_str(" verified:\n");
|
||||
out.push_str(&format!(" by: {}\n", yaml_escape(v)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn render_index_md(modules: &[ModuleInfo], version: &str) -> String {
|
||||
fn render_index_md(modules: &[ModuleInfo], concepts: &[ConceptInfo], version: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("---\n");
|
||||
out.push_str("type: Marqdo Catalog\n");
|
||||
@@ -240,26 +512,56 @@ fn render_index_md(modules: &[ModuleInfo], version: &str) -> String {
|
||||
out.push_str("---\n\n");
|
||||
out.push_str("# Catalog\n\n");
|
||||
out.push_str("> Generated by Marqdo. Do not edit by hand.\n\n");
|
||||
out.push_str("## Modules\n\n");
|
||||
out.push_str("| Module | Resource | Imports |\n");
|
||||
out.push_str("|--------|----------|--------|\n");
|
||||
for m in modules {
|
||||
let stem = m.resource.replace('/', "__");
|
||||
let stem = stem.trim_end_matches(".mq.md");
|
||||
let stem = module_stem(&m.resource);
|
||||
let imports_cell = if m.imports.is_empty() {
|
||||
"—".to_string()
|
||||
} else {
|
||||
m.imports
|
||||
.iter()
|
||||
.map(|i| {
|
||||
if let Some(dep) = resolve_import_module(i, modules) {
|
||||
format!(
|
||||
"[{}](modules/{}.md)",
|
||||
dep.title,
|
||||
module_stem(&dep.resource)
|
||||
)
|
||||
} else {
|
||||
format!("`{i}`")
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"| [{}](modules/{stem}.md) | `{}` | {} |\n",
|
||||
m.title,
|
||||
m.resource,
|
||||
if m.imports.is_empty() {
|
||||
"—".into()
|
||||
} else {
|
||||
m.imports.join(", ")
|
||||
}
|
||||
"| [{}](modules/{stem}.md) | `{}` | {imports_cell} |\n",
|
||||
m.title, m.resource
|
||||
));
|
||||
}
|
||||
|
||||
out.push_str("\n## Agent knowledge (OKF concepts)\n\n");
|
||||
if concepts.is_empty() {
|
||||
out.push_str("_No `.marqdo/agent-kb` concepts found under the scan root._\n");
|
||||
} else {
|
||||
out.push_str("| Concept | Type | Status | Page |\n");
|
||||
out.push_str("|---------|------|--------|------|\n");
|
||||
for c in concepts {
|
||||
out.push_str(&format!(
|
||||
"| {} | `{}` | {} | [{}]({}) |\n",
|
||||
c.title, c.concept_type, c.status, c.id, c.out_rel
|
||||
));
|
||||
}
|
||||
out.push_str(
|
||||
"\nThese pages are copied from local `agent-kb` for human browsing alongside modules.\n",
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn render_module_md(m: &ModuleInfo, version: &str) -> String {
|
||||
fn render_module_md(m: &ModuleInfo, modules: &[ModuleInfo], version: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("---\n");
|
||||
out.push_str("type: Marqdo Module\n");
|
||||
@@ -283,6 +585,16 @@ fn render_module_md(m: &ModuleInfo, version: &str) -> String {
|
||||
}
|
||||
out.push_str("generated:\n");
|
||||
out.push_str(&format!(" by: marqdo/{version}\n"));
|
||||
if let Some(ref v) = m.verified_by {
|
||||
out.push_str("verified:\n");
|
||||
out.push_str(&format!(" by: {v}\n"));
|
||||
}
|
||||
if !m.sources.is_empty() {
|
||||
out.push_str("sources:\n");
|
||||
for s in &m.sources {
|
||||
out.push_str(&format!(" - {s}\n"));
|
||||
}
|
||||
}
|
||||
out.push_str("---\n\n");
|
||||
out.push_str(&format!("# {}\n\n", m.title));
|
||||
out.push_str(&format!(
|
||||
@@ -294,7 +606,16 @@ fn render_module_md(m: &ModuleInfo, version: &str) -> String {
|
||||
out.push_str("_None_\n\n");
|
||||
} else {
|
||||
for i in &m.imports {
|
||||
out.push_str(&format!("- `{i}`\n"));
|
||||
if let Some(dep) = resolve_import_module(i, modules) {
|
||||
out.push_str(&format!(
|
||||
"- [{}]({}.md) (`{}`)\n",
|
||||
dep.title,
|
||||
module_stem(&dep.resource),
|
||||
i
|
||||
));
|
||||
} else {
|
||||
out.push_str(&format!("- `{i}`\n"));
|
||||
}
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
+26
-1
@@ -94,6 +94,9 @@ pub enum HostFn {
|
||||
SubtaskWaitAll = 92,
|
||||
WritebackEnsure = 93,
|
||||
OuterCallLine = 94,
|
||||
TextPatch = 95,
|
||||
ApplyPatchBlocks = 96,
|
||||
WritebackScanPath = 97,
|
||||
}
|
||||
|
||||
impl HostFn {
|
||||
@@ -184,6 +187,9 @@ impl HostFn {
|
||||
92 => Self::SubtaskWaitAll,
|
||||
93 => Self::WritebackEnsure,
|
||||
94 => Self::OuterCallLine,
|
||||
95 => Self::TextPatch,
|
||||
96 => Self::ApplyPatchBlocks,
|
||||
97 => Self::WritebackScanPath,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -273,6 +279,9 @@ impl HostFn {
|
||||
"host_writeback_list" | "writeback_list" => Self::WritebackList,
|
||||
"host_writeback_ensure" | "writeback_ensure" => Self::WritebackEnsure,
|
||||
"host_outer_call_line" | "outer_call_line" => Self::OuterCallLine,
|
||||
"host_text_patch" | "text_patch" => Self::TextPatch,
|
||||
"host_apply_patch_blocks" | "apply_patch_blocks" => Self::ApplyPatchBlocks,
|
||||
"host_writeback_scan_path" | "writeback_scan_path" => Self::WritebackScanPath,
|
||||
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
|
||||
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
|
||||
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
|
||||
@@ -368,6 +377,9 @@ impl HostFn {
|
||||
Self::WritebackList => "host_writeback_list",
|
||||
Self::WritebackEnsure => "host_writeback_ensure",
|
||||
Self::OuterCallLine => "host_outer_call_line",
|
||||
Self::TextPatch => "host_text_patch",
|
||||
Self::ApplyPatchBlocks => "host_apply_patch_blocks",
|
||||
Self::WritebackScanPath => "host_writeback_scan_path",
|
||||
Self::SubtaskSpawn => "host_subtask_spawn",
|
||||
Self::SubtaskPoll => "host_subtask_poll",
|
||||
Self::SubtaskJoin => "host_subtask_join",
|
||||
@@ -419,6 +431,9 @@ impl HostFn {
|
||||
Self::PluginUnload | Self::PluginList => &[],
|
||||
Self::ExtNativePath => &["name"],
|
||||
Self::OuterCallLine => &[],
|
||||
Self::TextPatch => &["path", "find", "replace"],
|
||||
Self::ApplyPatchBlocks => &["path", "text"],
|
||||
Self::WritebackScanPath => &["path"],
|
||||
Self::MapSet => &["map", "key", "value"],
|
||||
Self::ListAppend => &["list", "item"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
@@ -449,7 +464,7 @@ impl HostFn {
|
||||
&["at_end", "key", "line"]
|
||||
}
|
||||
Self::WritebackEnsure => &["placeholder", "line"],
|
||||
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin"],
|
||||
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -634,6 +649,16 @@ pub fn call_host(
|
||||
.copied()
|
||||
.unwrap_or(ctx.current_line) as i64,
|
||||
)),
|
||||
HostFn::TextPatch => fs::text_patch(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
require(bound, "find")?,
|
||||
require(bound, "replace")?,
|
||||
),
|
||||
HostFn::ApplyPatchBlocks => {
|
||||
fs::apply_patch_blocks(ctx, require(bound, "path")?, require(bound, "text")?)
|
||||
}
|
||||
HostFn::WritebackScanPath => writeback::scan_path(ctx, require(bound, "path")?),
|
||||
HostFn::WritebackRecord => writeback::record(
|
||||
ctx,
|
||||
require(bound, "value")?,
|
||||
|
||||
+185
@@ -106,3 +106,188 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
/// 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 p = ctx.resolve_path(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 src = fs::read_to_string(&p).map_err(|e| format!("text_patch {}: {e}", p.display()))?;
|
||||
let count = src.matches(find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"text_patch: find not found in {}",
|
||||
p.display()
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"text_patch: find matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
));
|
||||
}
|
||||
let next = src.replacen(find, replace, 1);
|
||||
fs::write(&p, next).map_err(|e| format!("text_patch write {}: {e}", p.display()))?;
|
||||
Ok(Value::Int(1))
|
||||
}
|
||||
|
||||
/// Apply one or more FIND/REPLACE blocks from plan-reply text.
|
||||
///
|
||||
/// Blocks:
|
||||
/// ```text
|
||||
/// <<<
|
||||
/// FIND
|
||||
/// <old>
|
||||
/// ===
|
||||
/// REPLACE
|
||||
/// <new>
|
||||
/// >>>
|
||||
/// ```
|
||||
pub fn apply_patch_blocks(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("apply_patch_blocks denied by host policy".into());
|
||||
}
|
||||
let blocks = parse_patch_blocks(text_body(text)?)?;
|
||||
if blocks.is_empty() {
|
||||
return Ok(Value::Int(0));
|
||||
}
|
||||
let p = ctx.resolve_path(text_path(path)?)?;
|
||||
let mut src = fs::read_to_string(&p).map_err(|e| format!("apply_patch_blocks {}: {e}", p.display()))?;
|
||||
let mut applied = 0i64;
|
||||
for (find, replace) in blocks {
|
||||
if find.is_empty() {
|
||||
return Err("apply_patch_blocks: empty FIND".into());
|
||||
}
|
||||
let count = src.matches(&find).count();
|
||||
if count == 0 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND not found in {}",
|
||||
p.display()
|
||||
));
|
||||
}
|
||||
if count > 1 {
|
||||
return Err(format!(
|
||||
"apply_patch_blocks: FIND matched {count} times in {} (must be unique)",
|
||||
p.display()
|
||||
));
|
||||
}
|
||||
src = src.replacen(&find, &replace, 1);
|
||||
applied += 1;
|
||||
}
|
||||
fs::write(&p, src).map_err(|e| format!("apply_patch_blocks write {}: {e}", p.display()))?;
|
||||
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));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
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())).unwrap();
|
||||
assert_eq!(n, Value::Int(2));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "AA bb CC");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -8,7 +8,7 @@ pub mod agent_rt;
|
||||
mod dispatch;
|
||||
pub mod foreign;
|
||||
mod fs;
|
||||
mod json;
|
||||
pub(crate) mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
pub mod plugin;
|
||||
@@ -78,7 +78,7 @@ pub struct HostContext {
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
|
||||
pub subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
|
||||
pub subtask_seq: u64,
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +243,9 @@ unsafe extern "C" fn host_query(
|
||||
"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(),
|
||||
)),
|
||||
other => Err(format!("host_query: unknown `{other}`")),
|
||||
};
|
||||
|
||||
|
||||
+78
-16
@@ -15,7 +15,7 @@ use crate::value::{CodeBlock, Value};
|
||||
|
||||
/// Stored subtask handle (tagged by spawn kind).
|
||||
pub(crate) enum Handle {
|
||||
File(Child),
|
||||
File(FileTask),
|
||||
Foreign(ForeignTask),
|
||||
Function(FunctionTask),
|
||||
}
|
||||
@@ -30,7 +30,12 @@ impl std::fmt::Debug for Handle {
|
||||
}
|
||||
}
|
||||
|
||||
struct ForeignTask {
|
||||
pub(crate) struct FileTask {
|
||||
child: Child,
|
||||
result_path: PathBuf,
|
||||
}
|
||||
|
||||
pub(crate) struct ForeignTask {
|
||||
child: Child,
|
||||
temp_script: PathBuf,
|
||||
stdout: JoinHandle<String>,
|
||||
@@ -44,7 +49,7 @@ enum FnState {
|
||||
Killed,
|
||||
}
|
||||
|
||||
struct FunctionTask {
|
||||
pub(crate) struct FunctionTask {
|
||||
state: Arc<Mutex<FnState>>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
@@ -121,9 +126,10 @@ fn fn_args_from_value(args: Option<&Value>) -> Result<Vec<(String, Value)>, Stri
|
||||
pub fn kill_all(ctx: &mut HostContext) {
|
||||
for (_, handle) in ctx.subtasks.drain() {
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
Handle::File(mut task) => {
|
||||
let _ = task.child.kill();
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.result_path);
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
let _ = task.child.kill();
|
||||
@@ -161,6 +167,7 @@ pub fn spawn(ctx: &mut HostContext, bound: &HashMap<String, Value>) -> Result<Va
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
bound.get("args"),
|
||||
bound.get("quiet"),
|
||||
)
|
||||
} else if has_fn {
|
||||
spawn_fn(ctx, require(bound, "fn")?, bound.get("args"))
|
||||
@@ -180,21 +187,51 @@ 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 file = if std::path::Path::new(rel).is_absolute() {
|
||||
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);
|
||||
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(),
|
||||
};
|
||||
if quiet {
|
||||
cmd.stdout(Stdio::null());
|
||||
cmd.stderr(Stdio::null());
|
||||
} 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")?);
|
||||
@@ -203,8 +240,13 @@ fn spawn_file(
|
||||
let child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
|
||||
let id = next_id(ctx);
|
||||
ctx.subtasks.insert(id, Handle::File(child));
|
||||
ctx.subtasks.insert(
|
||||
id,
|
||||
Handle::File(FileTask {
|
||||
child,
|
||||
result_path,
|
||||
}),
|
||||
);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
@@ -319,7 +361,7 @@ pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(child) => poll_child(child),
|
||||
Handle::File(task) => poll_child(&mut task.child),
|
||||
Handle::Foreign(task) => poll_child(&mut task.child),
|
||||
Handle::Function(task) => poll_function(&task.state),
|
||||
}
|
||||
@@ -364,17 +406,34 @@ pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
let status = child
|
||||
Handle::File(mut task) => {
|
||||
let status = task
|
||||
.child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask join: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
|
||||
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);
|
||||
Ok(Value::Map(vec![
|
||||
("code".into(), Value::Int(code)),
|
||||
("value".into(), value),
|
||||
]))
|
||||
}
|
||||
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
|
||||
@@ -428,9 +487,12 @@ pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match handle {
|
||||
Handle::File(mut child) => {
|
||||
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = child.wait();
|
||||
Handle::File(mut task) => {
|
||||
task.child
|
||||
.kill()
|
||||
.map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = task.child.wait();
|
||||
let _ = std::fs::remove_file(&task.result_path);
|
||||
}
|
||||
Handle::Foreign(mut task) => {
|
||||
task.child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
|
||||
+17
-1
@@ -528,6 +528,22 @@ pub fn list(ctx: &HostContext) -> Result<Value, String> {
|
||||
.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| {
|
||||
@@ -544,7 +560,7 @@ pub fn list(ctx: &HostContext) -> Result<Value, String> {
|
||||
Value::Map(entries)
|
||||
})
|
||||
.collect();
|
||||
Ok(Value::List(items))
|
||||
Value::List(items)
|
||||
}
|
||||
|
||||
/// Ensure named slots exist with a placeholder body; **does not** overwrite non-empty bodies.
|
||||
|
||||
+20
-2
@@ -75,6 +75,8 @@ pub struct RunOptions {
|
||||
pub fs_root: Option<std::path::PathBuf>,
|
||||
/// Sleep clamp when capturing (None = host default; view export uses `Some(0)`).
|
||||
pub sleep_limit_ms: Option<u64>,
|
||||
/// When set, write `# main` return value as JSON to this path (file subtasks).
|
||||
pub emit_result: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for RunOptions {
|
||||
@@ -94,6 +96,7 @@ impl Default for RunOptions {
|
||||
argv: Vec::new(),
|
||||
fs_root: None,
|
||||
sleep_limit_ms: None,
|
||||
emit_result: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,12 +184,13 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
interp.run_module(&module)?;
|
||||
let value = interp.run_module(&module)?;
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: end trace-eval ===");
|
||||
}
|
||||
let plots = interp.take_plots();
|
||||
flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?;
|
||||
emit_result_file(opts, &value)?;
|
||||
}
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(Some(path), &module)?;
|
||||
@@ -202,12 +206,13 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
vm.run(&program)?;
|
||||
let value = vm.run(&program)?;
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: end trace-eval ===");
|
||||
}
|
||||
let plots = vm.take_plots();
|
||||
flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?;
|
||||
emit_result_file(opts, &value)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +225,19 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn emit_result_file(opts: &RunOptions, value: &crate::value::Value) -> Result<()> {
|
||||
let Some(path) = &opts.emit_result else {
|
||||
return Ok(());
|
||||
};
|
||||
let json = crate::host::json::value_to_json(value).map_err(|e| anyhow::anyhow!(e))?;
|
||||
let text = serde_json::to_string(&json).map_err(|e| anyhow::anyhow!(e))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| anyhow::anyhow!(e))?;
|
||||
}
|
||||
std::fs::write(path, text).map_err(|e| anyhow::anyhow!("emit-result {}: {e}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run and capture stdout (used by `view` and tests).
|
||||
pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
let source = std::fs::read_to_string(path)
|
||||
|
||||
+24
-2
@@ -107,12 +107,17 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
return Ok(p);
|
||||
}
|
||||
}
|
||||
// Walk importer ancestors so workbooks under `.marqdo/…` still find repo `lib/`.
|
||||
if let Some(p) = find_in_ancestor_dir(from_dir, "lib", rest) {
|
||||
return Ok(p);
|
||||
}
|
||||
// Embedded stdlib: synthesize a path under lib/ for read_module_source.
|
||||
return Ok(PathBuf::from("lib").join(rest));
|
||||
}
|
||||
if rel.starts_with("ext/") {
|
||||
let rest = rel.strip_prefix("ext/").unwrap();
|
||||
for root in ext_search_roots() {
|
||||
let p = root.join(rel.strip_prefix("ext/").unwrap_or(&rel));
|
||||
let p = root.join(rest);
|
||||
// also try full ext/rel under root
|
||||
let p2 = root.join(&rel);
|
||||
if p.is_file() {
|
||||
@@ -122,11 +127,14 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
return Ok(p2);
|
||||
}
|
||||
// MARQDO_EXT is the ext root itself (contains ai/)
|
||||
let under = root.join(rel.strip_prefix("ext/").unwrap());
|
||||
let under = root.join(rest);
|
||||
if under.is_file() {
|
||||
return Ok(under);
|
||||
}
|
||||
}
|
||||
if let Some(p) = find_in_ancestor_dir(from_dir, "ext", rest) {
|
||||
return Ok(p);
|
||||
}
|
||||
}
|
||||
// Relative again with normalize
|
||||
if direct.exists() {
|
||||
@@ -135,6 +143,20 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
bail!("cannot resolve import `{rel}` from {}", from_dir.display())
|
||||
}
|
||||
|
||||
/// Look for `anchor/rest` under `from` or any parent directory (e.g. repo root `ext/ai/…`).
|
||||
fn find_in_ancestor_dir(from: &Path, anchor: &str, rest: &str) -> Option<PathBuf> {
|
||||
let mut cur = from.to_path_buf();
|
||||
loop {
|
||||
let candidate = cur.join(anchor).join(rest);
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
if !cur.pop() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lib_search_roots() -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(h) = env::var("MARQDO_LIB") {
|
||||
|
||||
@@ -60,6 +60,10 @@ enum Commands {
|
||||
/// Feed `input` from a text file (one line per call), instead of / after the terminal.
|
||||
#[arg(long, value_name = "FILE")]
|
||||
stdin_file: Option<PathBuf>,
|
||||
|
||||
/// Write `# main` return value as JSON (used by file subtasks).
|
||||
#[arg(long, value_name = "FILE")]
|
||||
emit_result: Option<PathBuf>,
|
||||
},
|
||||
/// Browse `.mq.md` structure + execution (live server or static output)
|
||||
View {
|
||||
@@ -177,6 +181,7 @@ fn try_main() -> Result<i32> {
|
||||
trace_eval,
|
||||
dump_all,
|
||||
stdin_file,
|
||||
emit_result,
|
||||
} => {
|
||||
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
|
||||
let stdin_lines = match stdin_file {
|
||||
@@ -186,6 +191,7 @@ fn try_main() -> Result<i32> {
|
||||
let mut opts = if dump_all {
|
||||
RunOptions {
|
||||
stdin_lines: stdin_lines.clone(),
|
||||
emit_result: emit_result.clone(),
|
||||
..RunOptions::dump_all()
|
||||
}
|
||||
} else {
|
||||
@@ -198,6 +204,7 @@ fn try_main() -> Result<i32> {
|
||||
trace_eval,
|
||||
backend: backend.into(),
|
||||
stdin_lines,
|
||||
emit_result,
|
||||
..RunOptions::default()
|
||||
}
|
||||
};
|
||||
|
||||
+96
-2
@@ -16,11 +16,18 @@ pub fn parse_expr(input: &str) -> Result<Expr> {
|
||||
|
||||
/// Argument / template RHS: prefer a full expression; else interpolated text.
|
||||
/// Hyphenated prose (`none-falsy`) is not parsed as subtraction.
|
||||
/// Quoted `"..."` always uses the expression parser (never the hyphen short-circuit).
|
||||
pub fn parse_value_or_interp(input: &str) -> Result<Expr> {
|
||||
let s = input.trim();
|
||||
if s.is_empty() {
|
||||
return Ok(Expr::Literal(Literal::Text(String::new())));
|
||||
}
|
||||
if s.starts_with('"') {
|
||||
return match parse_expr(s) {
|
||||
Ok(e) => Ok(e),
|
||||
Err(_) => Ok(parse_interp(s)),
|
||||
};
|
||||
}
|
||||
if has_hyphenated_prose(s) {
|
||||
return Ok(parse_interp(s));
|
||||
}
|
||||
@@ -30,6 +37,60 @@ pub fn parse_value_or_interp(input: &str) -> Result<Expr> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Call-arg / param-default values: like [`parse_value_or_interp`], but also treat a chain of
|
||||
/// unspaced `Text / Text` divisions as a single path string (`a/b`, `.marqdo/agent-kb`).
|
||||
/// Real math (`1/2`, `` `n` / 2 ``) is unchanged.
|
||||
pub fn parse_call_arg_value(input: &str) -> Result<Expr> {
|
||||
let s = input.trim();
|
||||
if s.is_empty() {
|
||||
return Ok(Expr::Literal(Literal::Text(String::new())));
|
||||
}
|
||||
if s.starts_with('"') {
|
||||
return match parse_expr(s) {
|
||||
Ok(e) => Ok(e),
|
||||
Err(_) => Ok(parse_interp(s)),
|
||||
};
|
||||
}
|
||||
if has_hyphenated_prose(s) {
|
||||
return Ok(parse_interp(s));
|
||||
}
|
||||
match parse_expr(s) {
|
||||
Ok(e) => Ok(collapse_text_div_path(e, s)),
|
||||
Err(_) => Ok(parse_interp(s)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_text_only_div_chain(e: &Expr) -> bool {
|
||||
match e {
|
||||
Expr::Literal(Literal::Text(_)) => true,
|
||||
Expr::Binary {
|
||||
op: BinaryOp::Div,
|
||||
left,
|
||||
right,
|
||||
} => is_text_only_div_chain(left) && matches!(right.as_ref(), Expr::Literal(Literal::Text(_))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn expr_has_div(e: &Expr) -> bool {
|
||||
match e {
|
||||
Expr::Binary {
|
||||
op: BinaryOp::Div, ..
|
||||
} => true,
|
||||
Expr::Binary { left, right, .. } => expr_has_div(left) || expr_has_div(right),
|
||||
Expr::Unary { expr, .. } => expr_has_div(expr),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn collapse_text_div_path(e: Expr, raw: &str) -> Expr {
|
||||
if expr_has_div(&e) && is_text_only_div_chain(&e) {
|
||||
parse_interp(raw)
|
||||
} else {
|
||||
e
|
||||
}
|
||||
}
|
||||
|
||||
fn has_hyphenated_prose(s: &str) -> bool {
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
for i in 1..chars.len().saturating_sub(1) {
|
||||
@@ -472,7 +533,7 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
|
||||
let val_raw = after_eq[..val_end].trim_end();
|
||||
args.push(Arg::Named {
|
||||
name: key,
|
||||
value: parse_value_or_interp(val_raw)?,
|
||||
value: parse_call_arg_value(val_raw)?,
|
||||
});
|
||||
args_str = after_eq[val_end..].trim_start();
|
||||
} else {
|
||||
@@ -483,7 +544,7 @@ pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
|
||||
if tok.is_empty() {
|
||||
break;
|
||||
}
|
||||
args.push(Arg::Positional(parse_value_or_interp(tok)?));
|
||||
args.push(Arg::Positional(parse_call_arg_value(tok)?));
|
||||
args_str = rest.trim_start();
|
||||
}
|
||||
}
|
||||
@@ -675,6 +736,37 @@ mod tests {
|
||||
assert!(matches!(e, Expr::Interp(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_arg_quoted_path_keeps_slashes() {
|
||||
let e = parse_call_arg_value("\".marqdo/agent-runs\"").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Literal(Literal::Text(ref s)) if s == ".marqdo/agent-runs"
|
||||
));
|
||||
let e = parse_value_or_interp("\".marqdo/agent-kb\"").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Literal(Literal::Text(ref s)) if s == ".marqdo/agent-kb"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_arg_bare_path_not_division() {
|
||||
let e = parse_call_arg_value("a/b/c").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Literal(Literal::Text(ref s)) if s == "a/b/c"
|
||||
));
|
||||
let e = parse_call_arg_value("1/2").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Binary {
|
||||
op: BinaryOp::Div,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_token_no_escape() {
|
||||
let e = parse_expr("a\\nb").unwrap();
|
||||
@@ -698,3 +790,5 @@ mod tests {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+79
-5
@@ -2,7 +2,7 @@
|
||||
|
||||
mod expr;
|
||||
|
||||
pub use expr::{parse_call_after_gt, parse_expr, parse_value_or_interp};
|
||||
pub use expr::{parse_call_after_gt, parse_call_arg_value, parse_expr, parse_value_or_interp};
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
@@ -521,14 +521,17 @@ impl<'a> Cursor<'a> {
|
||||
break;
|
||||
}
|
||||
let trimmed = l.text.trim();
|
||||
let cond_src = if let Some(rest) = strip_ordered(trimmed) {
|
||||
rest
|
||||
} else {
|
||||
let Some(num) = ordered_item_number(trimmed) else {
|
||||
break;
|
||||
};
|
||||
if ind != base_indent {
|
||||
break;
|
||||
}
|
||||
// Same-indent restart at `1.` begins a new Branch statement.
|
||||
if !arms.is_empty() && num == 1 {
|
||||
break;
|
||||
}
|
||||
let cond_src = strip_ordered(trimmed).unwrap();
|
||||
self.bump();
|
||||
|
||||
let condition = if cond_src == "*" || cond_src.is_empty() {
|
||||
@@ -673,7 +676,7 @@ fn parse_param_line(trimmed: &str) -> Option<crate::ast::Param> {
|
||||
if def_s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(parse_value_or_interp(def_s).ok()?)
|
||||
Some(parse_call_arg_value(def_s).ok()?)
|
||||
} else if after.is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -843,6 +846,25 @@ fn is_ordered_branch(trimmed: &str) -> bool {
|
||||
strip_ordered(trimmed).is_some()
|
||||
}
|
||||
|
||||
/// Leading `N` in an ordered-list item `N. …` (1-based Markdown marker).
|
||||
fn ordered_item_number(trimmed: &str) -> Option<u32> {
|
||||
let mut chars = trimmed.chars();
|
||||
let mut n: u32 = 0;
|
||||
let mut saw_digit = false;
|
||||
while let Some(c) = chars.next() {
|
||||
if let Some(d) = c.to_digit(10) {
|
||||
saw_digit = true;
|
||||
n = n.saturating_mul(10).saturating_add(d);
|
||||
continue;
|
||||
}
|
||||
if c == '.' && saw_digit {
|
||||
return Some(n);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn strip_ordered(trimmed: &str) -> Option<&str> {
|
||||
let mut chars = trimmed.chars();
|
||||
let mut saw_digit = false;
|
||||
@@ -956,6 +978,58 @@ mod tests {
|
||||
assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_branches_restart_at_one() {
|
||||
let m = parse_source(include_str!(
|
||||
"../../tests/structure/branch-consecutive.mq.md"
|
||||
))
|
||||
.unwrap();
|
||||
let branches: Vec<_> = m.functions[0]
|
||||
.body
|
||||
.iter()
|
||||
.filter(|s| matches!(s, Stmt::Branch { .. }))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
branches.len(),
|
||||
3,
|
||||
"expected three Branch stmts, got {:?}",
|
||||
m.functions[0].body
|
||||
);
|
||||
for b in &branches {
|
||||
match b {
|
||||
Stmt::Branch { arms, .. } => assert_eq!(arms.len(), 2),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
// Arm bodies must hold the prints (not leaked as sibling Calls).
|
||||
match branches[0] {
|
||||
Stmt::Branch { arms, .. } => {
|
||||
assert!(
|
||||
matches!(arms[0].body[0], Stmt::Call { .. }),
|
||||
"first arm body={:?}",
|
||||
arms[0].body
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_branches_without_blank_line() {
|
||||
let src = "# main\n\n1. True\n > print text=A\n2. *\n > print text=skip\n1. True\n > print text=B\n";
|
||||
let m = parse_source(src).unwrap();
|
||||
let branches: Vec<_> = m.functions[0]
|
||||
.body
|
||||
.iter()
|
||||
.filter(|s| matches!(s, Stmt::Branch { .. }))
|
||||
.collect();
|
||||
assert_eq!(branches.len(), 2, "got {:?}", m.functions[0].body);
|
||||
match branches[0] {
|
||||
Stmt::Branch { arms, .. } => assert_eq!(arms.len(), 2),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_formula_assign_fence() {
|
||||
let src = "# main\n\n`f` =\n$$\nx^2 - 2\n$$\n\n> print text=`f`\n";
|
||||
|
||||
Reference in new issue
Block a user