refactor: convert Marqdo into the ecosystem integration repository
ci/woodpecker/push/eco Pipeline was canceled
ci/woodpecker/pr/eco Pipeline was canceled

This commit is contained in:
cflmy committed 2026-11-26 13:19:26 +08:00
1 parent 1c55baabd5
commit 4c5c102593
1880 files changed
+998 -308724

No files matched your search

-17
View File
@@ -1,17 +0,0 @@
[package]
name = "marqdo_plugin_agent"
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo agent plugin (ABI v2 cdylib)"
publish = false
[lib]
name = "agent"
crate-type = ["cdylib"]
[dependencies]
marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" }
serde_json = "1"
pulldown-cmark = "0.12"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
-197
View File
@@ -1,197 +0,0 @@
//! Fail-closed choice parsing for small-model routing.
//! This module only extracts a value; it never resolves or executes a SKILL.
use serde_json::{json, Value};
fn canonical(s: &str) -> String {
s.trim()
.trim_matches(|c: char| matches!(c, '"' | '\'' | '`' | '“' | '”' | '‘' | '’'))
.trim()
.to_lowercase()
}
fn strip_fence(s: &str) -> &str {
let s = s.trim();
if !s.starts_with("```") {
return s;
}
let Some(start) = s.find('\n') else {
return s;
};
let body = &s[start + 1..];
let Some(end) = body.find("```") else {
return s;
};
if !body[end + 3..].trim().is_empty() {
return s;
}
body[..end].trim()
}
fn strip_label(s: &str) -> &str {
let s = s.trim();
let Some((head, tail)) = s.split_once([':', ':']) else {
return s;
};
if matches!(
head.trim().to_lowercase().as_str(),
"choice" | "option" | "selected" | "选择" | "选项" | "答案"
) {
tail.trim()
} else {
s
}
}
fn structured_reply(raw: &str) -> Option<String> {
let parsed: Value = serde_json::from_str(raw).ok()?;
if let Some(s) = parsed.as_str() {
return Some(s.to_string());
}
if let Some(list) = parsed.as_array() {
if list.len() == 1 {
return list[0].as_str().map(str::to_string);
}
return None;
}
let map = parsed.as_object()?;
// Refuse conflicting structured decisions instead of choosing first.
let values: Vec<&str> = ["choice", "selected", "option", "选择"]
.iter()
.filter_map(|key| map.get(*key).and_then(Value::as_str))
.collect();
if values.is_empty() || values.iter().any(|s| *s != values[0]) {
return None;
}
Some(values[0].to_string())
}
fn single_choice(options: &[String], reply: &str) -> Option<String> {
let raw = strip_label(strip_fence(reply));
// Structured single-choice replies are accepted only through known fields,
// and then still validated against the caller's exact allowlist.
let decoded = structured_reply(raw);
let raw = decoded.as_deref().unwrap_or(raw);
// Small models often prepend a short selection verb. Accept only the
// verb followed by a complete allowed value; explanations stay invalid.
let raw = raw.trim();
let raw = ["我选择", "我选", "I choose ", "I pick ", "选中"].iter()
.find_map(|p| raw.strip_prefix(p).map(str::trim))
.unwrap_or(raw);
let value = canonical(raw);
// Never infer a routing decision from arbitrary prose.
let matches: Vec<&String> = options
.iter()
.filter(|opt| canonical(opt) == value)
.collect();
if matches.len() == 1 {
return Some(matches[0].clone());
}
// A bare number denotes a 1-based index into the allowed list.
if let Ok(index) = value.parse::<usize>() {
if index > 0 && index <= options.len() {
return Some(options[index - 1].clone());
}
}
None
}
/// Parse one permitted option from a small model response.
/// Returns a status rather than treating arbitrary prose as a tool target.
pub fn parse_choice(args: &Value) -> Result<Value, String> {
let reply = args
.get("reply")
.and_then(Value::as_str)
.ok_or_else(|| "missing text `reply`".to_string())?;
let options = args
.get("options")
.and_then(Value::as_array)
.ok_or_else(|| "options must be an array of strings".to_string())?;
if options.is_empty() || options.len() > 64 {
return Err("options must contain 1..=64 entries".to_string());
}
let mut allowed = Vec::with_capacity(options.len());
for option in options {
let name = option
.as_str()
.ok_or_else(|| "each option must be a string".to_string())?;
if name.trim().is_empty() || name.len() > 128 {
return Err("each option must contain 1..=128 UTF-8 bytes".to_string());
}
if allowed.iter().any(|p: &String| canonical(p) == canonical(name)) {
return Err("options must be unique after normalization".to_string());
}
allowed.push(name.to_string());
}
if let Some(value) = single_choice(&allowed, reply) {
Ok(json!({"ok": true, "value": value, "status": "accepted"}))
} else {
Ok(json!({
"ok": false,
"value": null,
"status": "invalid",
"error": {
"code": "model.invalid_choice",
"category": "invalid_output",
"retryable": false,
"recovery_action": "repair_output"
}
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(reply: &str) -> Value {
parse_choice(&json!({"options": ["chat", "office"], "reply": reply})).unwrap()
}
#[test]
fn accepts_exact_label_fence_and_number() {
assert_eq!(check("chat")["value"], "chat");
assert_eq!(check(" CHAT ")["value"], "chat");
assert_eq!(check("选择:office")["value"], "office");
assert_eq!(check("```text\nchat\n```")["value"], "chat");
assert_eq!(check("2")["value"], "office");
assert_eq!(check("我选择 chat")["value"], "chat");
assert_eq!(check("I choose office")["value"], "office");
assert_eq!(check(r#"{"choice":"chat"}"#)["value"], "chat");
assert_eq!(check("[\"office\"]")["value"], "office");
assert_eq!(check("```json\n{\"selected\":\"office\"}\n```")["value"], "office");
}
#[test]
fn refuses_prose_conflicts_and_out_of_range() {
for reply in ["请选择 chat", "chat 或 office", "choice: chat,因为更合适", "3", ""] {
let result = check(reply);
assert_eq!(result["ok"], false, "accepted {reply:?}");
assert_eq!(result["value"], Value::Null);
}
}
#[test]
fn refuses_conflicting_structured_decisions() {
assert_eq!(check(r#"{"choice":"chat","option":"office"}"#)["ok"], false);
assert_eq!(check(r#"{"choice":"../private.mq.md"}"#)["ok"], false);
assert_eq!(check(r#"["chat","office"]"#)["ok"], false);
}
#[test]
fn rejects_invalid_options_before_parsing() {
for options in [
json!([]),
json!(["chat", "CHAT"]),
json!(["chat", 10]),
json!([""]),
] {
assert!(parse_choice(&json!({"options": options, "reply": "chat"})).is_err());
}
}
#[test]
fn never_extracts_arbitrary_skill_path() {
assert_eq!(check("../../private.mq.md")["ok"], false);
}
}
-266
View File
@@ -1,266 +0,0 @@
//! ContextPackV2 assemble + compact (M-A4).
use serde_json::{json, Value};
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
fn item_tokens(item: &Value) -> u64 {
item.get("token_estimate")
.and_then(|v| v.as_u64())
.unwrap_or_else(|| {
item.get("text")
.and_then(|v| v.as_str())
.map(|s| (s.chars().count() as u64).div_ceil(2))
.unwrap_or(32)
})
}
fn normalize_item(raw: &Value, default_priority: i64) -> Result<Value, String> {
let origin = raw
.get("origin")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let trust = raw
.get("trust")
.and_then(|v| v.as_str())
.unwrap_or(match origin {
"system" | "policy" => "trusted",
"user" => "user",
"tool" => "tool",
"web" => "untrusted",
_ => "unknown",
});
// External / web content must never be trust=trusted.
if matches!(origin, "web" | "tool") && trust == "trusted" {
return Err("tool/web origin cannot have trust=trusted".into());
}
Ok(json!({
"origin": origin,
"trust": trust,
"resource_ref": raw.get("resource_ref").cloned().unwrap_or(Value::Null),
"revision": raw.get("revision").cloned().unwrap_or(Value::Null),
"token_estimate": item_tokens(raw),
"priority": raw.get("priority").and_then(|v| v.as_i64()).unwrap_or(default_priority),
"role": raw.get("role").cloned().unwrap_or(json!(origin)),
"text": raw.get("text").cloned().unwrap_or(Value::Null),
"kind": raw.get("kind").cloned().unwrap_or(json!("content")),
"retain": raw.get("retain").and_then(|v| v.as_bool()).unwrap_or(false),
}))
}
/// Build ContextPackV2 from items + optional budget.
pub fn context_pack_build(args: &Value) -> Result<Value, String> {
let raw_items = args
.get("items")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let mut items = Vec::new();
for (i, raw) in raw_items.iter().enumerate() {
items.push(normalize_item(raw, i as i64)?);
}
// Stable priority order: lower priority number first (more important).
items.sort_by(|a, b| {
let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
pa.cmp(&pb)
});
let budget = args
.get("budget_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(8_000);
let reserve_pct = args
.get("output_reserve_pct")
.and_then(|v| v.as_u64())
.unwrap_or(20)
.min(50);
let available = budget.saturating_mul(100 - reserve_pct) / 100;
let used: u64 = items.iter().map(item_tokens).sum();
Ok(json!({
"schema": "ContextPackV2",
"schema_version": 2,
"items": items,
"budget_tokens": budget,
"available_tokens": available,
"used_tokens": used,
"output_reserve_pct": reserve_pct,
"compact_threshold_pct": args.get("compact_threshold_pct").and_then(|v| v.as_u64()).unwrap_or(70),
"goal": args.get("goal").cloned().unwrap_or(Value::Null),
"constraints": args.get("constraints").cloned().unwrap_or_else(|| json!([])),
}))
}
/// Compact pack when over threshold; must retain anchors listed in design §6.2.
pub fn context_pack_compact(args: &Value) -> Result<Value, String> {
let mut pack = if args.get("schema").and_then(|v| v.as_str()) == Some("ContextPackV2") {
args.clone()
} else {
context_pack_build(args)?
};
let available = pack
.get("available_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(6400);
let threshold_pct = pack
.get("compact_threshold_pct")
.and_then(|v| v.as_u64())
.unwrap_or(70);
let threshold = available.saturating_mul(threshold_pct) / 100;
let used = pack
.get("used_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
if used <= threshold {
if let Some(obj) = pack.as_object_mut() {
obj.insert("compacted".into(), json!(false));
obj.insert("reason".into(), json!("under_threshold"));
}
return Ok(pack);
}
let items = pack
.get("items")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
// Retain: goal/constraints (pack fields), retain=true, high priority (<=2),
// pending writes, failures — drop bulky tool dumps first (kind=tool_output, low priority).
let mut kept = Vec::new();
let mut dropped = Vec::new();
for item in items {
let retain = item.get("retain").and_then(|v| v.as_bool()).unwrap_or(false);
let priority = item.get("priority").and_then(|v| v.as_i64()).unwrap_or(99);
let kind = item.get("kind").and_then(|v| v.as_str()).unwrap_or("");
let trust = item.get("trust").and_then(|v| v.as_str()).unwrap_or("");
let must = retain
|| priority <= 2
|| matches!(kind, "goal" | "constraint" | "pending_write" | "plan" | "failure")
|| trust == "trusted";
if must {
kept.push(item);
} else if kind == "tool_output" || priority >= 8 {
dropped.push(item);
} else {
kept.push(item);
}
}
// If still over budget, drop lowest-priority non-retain from kept.
let mut kept_tokens: u64 = kept.iter().map(item_tokens).sum();
if kept_tokens > threshold {
kept.sort_by(|a, b| {
let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
pb.cmp(&pa) // high priority number first for dropping
});
let mut next = Vec::new();
for item in kept.into_iter().rev() {
// rebuild ascending later
let retain = item.get("retain").and_then(|v| v.as_bool()).unwrap_or(false);
let priority = item.get("priority").and_then(|v| v.as_i64()).unwrap_or(99);
let t = item_tokens(&item);
if (retain || priority <= 1) || kept_tokens <= threshold {
next.push(item);
} else if kept_tokens > threshold {
kept_tokens = kept_tokens.saturating_sub(t);
dropped.push(item);
} else {
next.push(item);
}
}
next.sort_by(|a, b| {
let pa = a.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
let pb = b.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);
pa.cmp(&pb)
});
kept = next;
kept_tokens = kept.iter().map(item_tokens).sum();
}
let digest_src = format!(
"kept={} dropped={} used={}",
kept.len(),
dropped.len(),
kept_tokens
);
let digest = format!("sha256-lite:{}", simple_hash(&digest_src));
if let Some(obj) = pack.as_object_mut() {
obj.insert("items".into(), json!(kept));
obj.insert("used_tokens".into(), json!(kept_tokens));
obj.insert("compacted".into(), json!(true));
obj.insert(
"compaction".into(),
json!({
"dropped_count": dropped.len(),
"source_event_range": args.get("source_event_range").cloned().unwrap_or(Value::Null),
"digest": digest,
"retained": ["goal", "constraints", "pending_write", "plan", "trusted_policy"],
}),
);
// Goal / constraints fields stay untouched.
if obj.get("goal").map(|v| v.is_null()).unwrap_or(true) {
if let Some(g) = opt_text(args, "goal") {
obj.insert("goal".into(), json!(g));
}
}
}
Ok(pack)
}
fn simple_hash(s: &str) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in s.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x100000001b3);
}
h
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_sorts_and_rejects_trusted_web() {
let pack = context_pack_build(&json!({
"budget_tokens": 1000,
"items": [
{"origin": "user", "text": "goal", "priority": 0, "kind": "goal", "retain": true},
{"origin": "tool", "text": "big dump", "priority": 9, "kind": "tool_output", "token_estimate": 500}
]
}))
.unwrap();
assert_eq!(pack["schema"], "ContextPackV2");
assert_eq!(pack["items"][0]["priority"], 0);
let bad = context_pack_build(&json!({
"items": [{"origin": "web", "trust": "trusted", "text": "x"}]
}));
assert!(bad.is_err());
}
#[test]
fn compact_keeps_goal_drops_tool_output() {
let pack = context_pack_build(&json!({
"budget_tokens": 200,
"output_reserve_pct": 20,
"compact_threshold_pct": 50,
"goal": "finish task",
"items": [
{"origin": "user", "text": "do it", "priority": 0, "kind": "goal", "retain": true, "token_estimate": 20},
{"origin": "tool", "text": "x".repeat(400), "priority": 9, "kind": "tool_output", "token_estimate": 200}
]
}))
.unwrap();
let compacted = context_pack_compact(&pack).unwrap();
assert_eq!(compacted["compacted"], true);
let items = compacted["items"].as_array().unwrap();
assert!(items.iter().any(|i| i["kind"] == "goal"));
assert!(!items.iter().any(|i| i["kind"] == "tool_output"));
assert_eq!(compacted["goal"], "finish task");
}
}
-207
View File
@@ -1,207 +0,0 @@
//! Markdown-heading-backed, bounded context projection for Marqdo SKILLs.
//! This is source selection, not execution: quoted text never becomes tool authority.
//! Markdown events ignore fenced-code headings; ambiguous functions fail closed.
use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
use serde_json::{json, Value};
#[derive(Clone, Debug)]
struct Section {
level: u8,
title: String,
start: usize,
}
fn level_num(h: HeadingLevel) -> u8 {
match h {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
fn headings(source: &str) -> Vec<Section> {
let mut out = Vec::new();
let mut pending: Option<Section> = None;
for (event, range) in Parser::new(source).into_offset_iter() {
match event {
Event::Start(Tag::Heading { level, .. }) => {
pending = Some(Section {
level: level_num(level),
title: String::new(),
start: range.start,
});
}
Event::Text(text) | Event::Code(text) => {
if let Some(section) = pending.as_mut() {
section.title.push_str(&text);
}
}
Event::End(TagEnd::Heading(_)) => {
if let Some(mut section) = pending.take() {
section.title = section.title.trim().to_string();
out.push(section);
}
}
_ => {}
}
}
out
}
fn class_for(headings: &[Section], index: usize) -> Option<&str> {
headings[..index]
.iter()
.rev()
.find(|h| h.level == 1)
.map(|h| h.title.as_str())
}
fn frontmatter_end(source: &str) -> usize {
if !source.starts_with("---\n") {
return 0;
}
let mut pos = 4;
for line in source[4..].split_inclusive('\n') {
pos += line.len();
if line.trim() == "---" {
return pos;
}
}
0
}
fn truncate_chars(text: &str, max_chars: usize) -> (&str, bool) {
let Some((end, _)) = text.char_indices().nth(max_chars) else {
return (text, false);
};
(&text[..end], true)
}
pub fn project(args: &Value) -> Result<Value, String> {
let source = match args.get("source").and_then(Value::as_str) {
Some(s) => s.to_string(),
None => crate::host_query_json("module_source")?
.as_str()
.ok_or_else(|| "module_source unavailable".to_string())?
.to_string(),
};
let scope = args.get("scope").and_then(Value::as_str).unwrap_or("function");
let class = args.get("class").and_then(Value::as_str);
let function = args.get("function").and_then(Value::as_str);
let maximum = args
.get("max_chars")
.and_then(Value::as_u64)
.unwrap_or(1600)
.clamp(32, 16000) as usize;
// YAML frontmatter may look like a setext Markdown heading; never treat it
// as a Marqdo class or function boundary.
let front_end = frontmatter_end(&source);
let marks: Vec<Section> = headings(&source)
.into_iter()
.filter(|heading| heading.start >= front_end)
.collect();
let results: Vec<(usize, usize)> = match scope {
"file" => {
let end = marks.first().map_or(source.len(), |h| h.start);
let start = frontmatter_end(&source).min(end);
vec![(start, end)]
}
"class" | "function" | "tool" => {
let level = match scope {
"class" => 1,
"function" => 2,
_ => 3,
};
let target = if level == 1 { class } else { function };
let wanted = target.ok_or_else(|| format!("{scope} selector required"))?;
marks
.iter()
.enumerate()
.filter(|(i, h)| {
h.level == level
&& h.title == wanted
&& (level == 1 || class.is_none() || class_for(&marks, *i) == class)
})
.map(|(i, h)| {
let end = marks[i + 1..]
.iter()
.find(|next| next.level <= level)
.map_or(source.len(), |next| next.start);
let end = if level == 1 {
marks[i + 1..]
.iter()
.find(|next| next.level <= 2)
.map_or(end, |next| next.start)
} else {
end
};
(h.start, end)
})
.collect()
}
_ => return Err("scope must be file, class, function or tool".to_string()),
};
if results.len() != 1 {
return Ok(json!({
"ok": false,
"status": if results.is_empty() { "not_found" } else { "ambiguous" },
"scope": scope,
"matches": results.len(),
"text": null
}));
}
let (start, end) = results[0];
let (slice, truncated) = truncate_chars(source[start..end].trim(), maximum);
let line_start = source[..start].bytes().filter(|c| *c == b'\n').count() + 1;
Ok(json!({
"ok": true, "status": "accepted", "scope": scope,
"text": slice, "truncated": truncated,
"start_byte": start, "end_byte": end,
"start_line": line_start,
"source_kind": "markdown_headings"
}))
}
#[cfg(test)]
mod tests {
use super::*;
const DOC: &str = "---\ntitle: example\n---\nEntry instructions.\n\n# main\nClass instructions.\n\n## route\nReal body.\n```md\n## route\nfake\n```\n\n## other\nOther body.\n\n# helper\nHelper prose.\n\n## route\nSecond body.\n";
#[test]
fn scope_is_bounded_and_fenced_headings_ignored() {
let v = project(&json!({"source": DOC, "scope": "function", "class": "main", "function": "route"})).unwrap();
assert_eq!(v["ok"], true);
assert!(v["text"].as_str().unwrap().contains("Real body."));
assert!(v["text"].as_str().unwrap().contains("fake"));
assert!(!v["text"].as_str().unwrap().contains("Other body."));
assert!(!v["text"].as_str().unwrap().contains("Second body."));
}
#[test]
fn ambiguous_function_fails_closed() {
let v = project(&json!({"source": DOC, "scope": "function", "function": "route"})).unwrap();
assert_eq!(v["status"], "ambiguous");
assert_eq!(v["text"], Value::Null);
}
#[test]
fn file_scope_removes_frontmatter_and_class_prose_excludes_functions() {
let a = project(&json!({"source": DOC, "scope": "file"})).unwrap();
assert_eq!(a["text"], "Entry instructions.");
let b = project(&json!({"source": DOC, "scope": "class", "class": "main"})).unwrap();
assert!(b["text"].as_str().unwrap().contains("Class instructions."));
assert!(!b["text"].as_str().unwrap().contains("Real body."));
}
#[test]
fn unicode_truncation_does_not_split_characters() {
let v = project(&json!({"source": "汉".repeat(100), "scope": "file", "max_chars": 32})).unwrap();
assert_eq!(v["text"].as_str().unwrap().chars().count(), 32);
assert_eq!(v["truncated"], true);
}
}
-316
View File
@@ -1,316 +0,0 @@
//! Local corpus search + MCP fixture adapter (evidence tools; workbook stays authority).
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| format!("missing {key}"))
}
fn arg_usize(args: &Value, key: &str, default: usize) -> usize {
match args.get(key) {
None | Some(Value::Null) => default,
Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as usize,
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn resolve_path(rel: &str) -> PathBuf {
let p = PathBuf::from(rel);
if p.is_absolute() {
return p;
}
// Prefer host cwd (entry file directory) via host_query — same as kb.rs.
let base = (|| {
let q = crate::host_query_json("cwd")?;
q.as_str()
.map(PathBuf::from)
.ok_or_else(|| "cwd not text".to_string())
})()
.or_else(|_| std::env::current_dir().map_err(|e| e.to_string()))
.unwrap_or_else(|_| PathBuf::from("."));
base.join(p)
}
fn is_corpus_file(path: &Path) -> bool {
match path.extension().and_then(|e| e.to_str()) {
Some("md" | "txt" | "mq.md") => true,
Some(ext) if ext.eq_ignore_ascii_case("markdown") => true,
_ => {
// `.mq.md` is two extensions on some platforms → check suffix
path.file_name()
.and_then(|n| n.to_str())
.map(|n| n.ends_with(".mq.md") || n.ends_with(".md") || n.ends_with(".txt"))
.unwrap_or(false)
}
}
}
fn query_terms(q: &str) -> Vec<String> {
let mut out = Vec::new();
let mut buf = String::new();
let flush = |buf: &mut String, out: &mut Vec<String>| {
if !buf.is_empty() {
out.push(buf.to_ascii_lowercase());
buf.clear();
}
};
for c in q.chars() {
if c.is_alphanumeric() {
buf.push(c);
} else if !c.is_whitespace() && !c.is_ascii() {
// CJK / other letters: treat each char as a term
flush(&mut buf, &mut out);
out.push(c.to_string());
} else {
flush(&mut buf, &mut out);
}
}
flush(&mut buf, &mut out);
out.retain(|t| !t.is_empty());
out
}
fn score_doc(text: &str, terms: &[String]) -> f64 {
if terms.is_empty() {
return 0.0;
}
let lower = text.to_ascii_lowercase();
let mut hits = 0usize;
for t in terms {
if lower.contains(t) {
hits += 1;
}
}
hits as f64 / terms.len() as f64
}
fn best_excerpt(text: &str, terms: &[String], max_chars: usize) -> String {
let lines: Vec<&str> = text.lines().collect();
let mut best_i = 0usize;
let mut best_score = -1.0f64;
for (i, line) in lines.iter().enumerate() {
let s = score_doc(line, terms);
if s > best_score {
best_score = s;
best_i = i;
}
}
let start = best_i.saturating_sub(1);
let end = (best_i + 2).min(lines.len());
let mut chunk = lines[start..end].join("\n");
if chunk.chars().count() > max_chars {
chunk = chunk.chars().take(max_chars).collect();
chunk.push('…');
}
chunk
}
fn walk_corpus(root: &Path, out: &mut Vec<PathBuf>, depth: usize) {
if depth > 6 || out.len() >= 400 {
return;
}
let Ok(rd) = fs::read_dir(root) else {
return;
};
let mut ents: Vec<_> = rd.flatten().collect();
ents.sort_by_key(|e| e.file_name());
for ent in ents {
let p = ent.path();
if p.is_dir() {
walk_corpus(&p, out, depth + 1);
} else if is_corpus_file(&p) {
out.push(p);
}
}
}
/// Keyword corpus search over local markdown/text. Evidence only — not authority.
pub fn corpus_search(args: &Value) -> Result<Value, String> {
let query = arg_text(args, "query")?;
let root_s = match args.get("root").and_then(|v| v.as_str()) {
Some(s) if !s.trim().is_empty() => s.trim(),
_ => ".marqdo/agent-corpus",
};
let limit = arg_usize(args, "limit", 6).clamp(1, 40);
let root = resolve_path(root_s);
if !root.is_dir() {
return Ok(json!({
"hits": [],
"count": 0,
"query": query,
"root": root_s,
"authority": "workbook",
"note": "Corpus miss or missing root. Evidence only — runnable .mq.md workbook remains authority.",
}));
}
let terms = query_terms(query);
let mut files = Vec::new();
walk_corpus(&root, &mut files, 0);
let mut ranked: Vec<(f64, PathBuf, String)> = Vec::new();
for path in files {
let Ok(src) = fs::read_to_string(&path) else {
continue;
};
let score = score_doc(&src, &terms);
if score <= 0.0 {
continue;
}
let excerpt = best_excerpt(&src, &terms, 320);
ranked.push((score, path, excerpt));
}
ranked.sort_by(|a, b| {
b.0.partial_cmp(&a.0)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.1.cmp(&b.1))
});
ranked.truncate(limit);
let hits: Vec<Value> = ranked
.into_iter()
.map(|(score, path, excerpt)| {
let rel = path
.strip_prefix(&root)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| path.to_string_lossy().into_owned());
json!({
"path": rel,
"score": (score * 1000.0).round() / 1000.0,
"excerpt": excerpt,
})
})
.collect();
let count = hits.len() as i64;
Ok(json!({
"hits": hits,
"count": count,
"query": query,
"root": root_s,
"authority": "workbook",
"note": "Corpus hits are external evidence only. Do not treat them as the runnable ground truth — the .mq.md workbook / OKF skill remains authority.",
}))
}
fn load_fixture(path: &str) -> Result<Value, String> {
let p = resolve_path(path);
let src = fs::read_to_string(&p).map_err(|e| format!("mcp fixture read: {e}"))?;
serde_json::from_str(&src).map_err(|e| format!("mcp fixture json: {e}"))
}
/// Offline / local MCP-shaped tool surface via a JSON fixture.
/// `action=list` → tools; `action=call` → results[name] (arguments ignored for fixture).
pub fn mcp_fixture(args: &Value) -> Result<Value, String> {
let action = args
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("list");
let fixture = arg_text(args, "fixture")?;
let doc = load_fixture(fixture)?;
let note = doc
.get("note")
.and_then(|v| v.as_str())
.unwrap_or(
"MCP/fixture evidence only. Workbook .mq.md remains authority; do not promote tool prose to ground truth.",
)
.to_string();
match action {
"list" => {
let tools = doc.get("tools").cloned().unwrap_or_else(|| json!([]));
Ok(json!({
"tools": tools,
"fixture": fixture,
"authority": "workbook",
"note": note,
}))
}
"call" => {
let name = arg_text(args, "name")?;
let results = doc.get("results").or_else(|| doc.get("calls"));
let Some(map) = results.and_then(|v| v.as_object()) else {
return Err("mcp fixture missing results/calls object".into());
};
let Some(val) = map.get(name) else {
return Ok(json!({
"ok": false,
"name": name,
"error": "tool not in fixture",
"authority": "workbook",
"note": note,
}));
};
Ok(json!({
"ok": true,
"name": name,
"result": val,
"arguments": args.get("arguments").cloned().unwrap_or(Value::Null),
"authority": "workbook",
"note": note,
}))
}
other => Err(format!("mcp fixture unknown action: {other}")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn corpus_search_ranks_matching_file() {
let dir = std::env::temp_dir().join("marqdo-corpus-a4-test");
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let mut f = fs::File::create(dir.join("refunds.md")).unwrap();
writeln!(f, "# Refunds\n\nCustomers may request a refund within 30 days.").unwrap();
let mut f2 = fs::File::create(dir.join("shipping.md")).unwrap();
writeln!(f2, "# Shipping\n\nShips in two business days.").unwrap();
let args = json!({
"query": "refund 30 days",
"root": dir.to_string_lossy(),
"limit": 4,
});
let out = corpus_search(&args).unwrap();
assert_eq!(out["authority"], "workbook");
assert!(out["count"].as_i64().unwrap() >= 1);
let hits = out["hits"].as_array().unwrap();
assert_eq!(hits[0]["path"], "refunds.md");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn mcp_fixture_list_and_call() {
let dir = std::env::temp_dir().join("marqdo-mcp-a4-test");
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("fixture.json");
fs::write(
&path,
r#"{"tools":[{"name":"wiki_get","description":"wiki"}],"results":{"wiki_get":{"text":"ok-page"}}}"#,
)
.unwrap();
let list = mcp_fixture(&json!({
"action": "list",
"fixture": path.to_string_lossy(),
}))
.unwrap();
assert_eq!(list["tools"][0]["name"], "wiki_get");
let call = mcp_fixture(&json!({
"action": "call",
"fixture": path.to_string_lossy(),
"name": "wiki_get",
}))
.unwrap();
assert_eq!(call["ok"], true);
assert_eq!(call["result"]["text"], "ok-page");
assert_eq!(call["authority"], "workbook");
let _ = fs::remove_dir_all(&dir);
}
}
-622
View File
@@ -1,622 +0,0 @@
//! EffectLedgerRecordV1 — operation receipts for write-safe resume (M-A5 subset).
//!
//! State machine (design §4.2):
//! prepared → started → committed
//! ↘ failed_no_effect
//! ↘ unknown → reconciled_committed | reconciled_no_effect | needs_input
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
const DEFAULT_LEDGER_DIR: &str = ".marqdo/agent-effects";
const STATES: &[&str] = &[
"prepared",
"started",
"committed",
"failed_no_effect",
"unknown",
"reconciled_committed",
"reconciled_no_effect",
"needs_input",
];
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
opt_text(args, key).ok_or_else(|| format!("missing text `{key}`"))
}
fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn resolve_path(rel: &str) -> PathBuf {
let p = PathBuf::from(rel);
if p.is_absolute() {
return p;
}
if p.exists() {
return p;
}
let base = (|| {
let q = crate::host_query_json("cwd")?;
q.as_str()
.map(PathBuf::from)
.ok_or_else(|| "cwd not text".to_string())
})()
.or_else(|_| std::env::current_dir().map_err(|e| e.to_string()))
.unwrap_or_else(|_| PathBuf::from("."));
base.join(p)
}
fn ledger_root(args: &Value) -> Result<PathBuf, String> {
let rel = opt_text(args, "ledger_dir").unwrap_or(DEFAULT_LEDGER_DIR);
let p = PathBuf::from(rel);
if p.is_absolute() {
return Err(
"ledger_dir must be host-relative; absolute client paths are rejected".into(),
);
}
if rel.contains("..") {
return Err("ledger_dir must not contain '..'".into());
}
Ok(resolve_path(rel))
}
fn safe_id(id: &str) -> String {
id.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect()
}
fn record_path(root: &Path, operation_id: &str) -> PathBuf {
root.join(format!("{}.json", safe_id(operation_id)))
}
fn ensure_dir(root: &Path) -> Result<(), String> {
fs::create_dir_all(root).map_err(|e| format!("effects mkdir: {e}"))
}
static EFFECT_TEMP_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn atomic_write_json(path: &Path, doc: &Value) -> Result<(), String> {
let parent = path
.parent()
.ok_or_else(|| "ledger path has no parent".to_string())?;
ensure_dir(parent)?;
let tmp_name = format!(
".{}.tmp-{}-{}",
path.file_name()
.and_then(|s| s.to_str())
.unwrap_or("op.json"),
std::process::id(),
format!("{}-{}", now_rfc3339().replace(':', ""),
EFFECT_TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
);
let tmp = parent.join(tmp_name);
let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?;
{
let mut f = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&tmp)
.map_err(|e| format!("effects temp open: {e}"))?;
f.write_all(text.as_bytes())
.map_err(|e| format!("effects temp write: {e}"))?;
f.flush().map_err(|e| format!("effects temp flush: {e}"))?;
f.sync_all()
.map_err(|e| format!("effects temp fsync: {e}"))?;
}
if let Ok(dir) = File::open(parent) {
let _ = dir.sync_all();
}
fs::rename(&tmp, path).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("effects atomic rename: {e}")
})?;
Ok(())
}
fn load_record(path: &Path) -> Result<Option<Value>, String> {
if !path.is_file() {
return Ok(None);
}
let text = fs::read_to_string(path).map_err(|e| format!("effects read: {e}"))?;
let doc: Value = serde_json::from_str(&text).map_err(|e| format!("effects corrupt: {e}"))?;
Ok(Some(doc))
}
fn valid_transition(from: &str, to: &str) -> bool {
matches!(
(from, to),
("prepared", "started")
| ("started", "committed")
| ("started", "failed_no_effect")
| ("started", "unknown")
| ("unknown", "reconciled_committed")
| ("unknown", "reconciled_no_effect")
| ("unknown", "needs_input")
// Idempotent no-ops / crash retries of the same terminal.
| ("committed", "committed")
| ("failed_no_effect", "failed_no_effect")
| ("reconciled_committed", "reconciled_committed")
| ("reconciled_no_effect", "reconciled_no_effect")
| ("needs_input", "needs_input")
// Re-prepare of same op is handled separately via idempotency.
| ("prepared", "prepared")
)
}
fn effect_class_ok(c: &str) -> bool {
matches!(c, "read" | "write" | "execute" | "external_write" | "none")
}
/// Prepare (or return existing) an EffectLedgerRecordV1.
pub fn effects_prepare(args: &Value) -> Result<Value, String> {
let operation_id = arg_text(args, "operation_id")?;
let idempotency_key = arg_text(args, "idempotency_key")?;
let args_digest = arg_text(args, "args_digest")?;
let effect_class = opt_text(args, "effect_class").unwrap_or("write");
if !effect_class_ok(effect_class) {
return Err(format!("invalid effect_class={effect_class}"));
}
let root = ledger_root(args)?;
ensure_dir(&root)?;
let path = record_path(&root, operation_id);
if let Some(existing) = load_record(&path)? {
let same_key = existing
.get("idempotency_key")
.and_then(|v| v.as_str())
== Some(idempotency_key);
let same_digest = existing.get("args_digest").and_then(|v| v.as_str()) == Some(args_digest);
if same_key && same_digest {
return Ok(json!({
"ok": true,
"deduped": true,
"record": existing,
}));
}
if same_key && !same_digest {
return Err(
"idempotency_key collision: same key with different args_digest".into(),
);
}
// Different operation_id path can't collide; same path different key is corrupt reuse.
return Err("operation_id already exists with different idempotency_key".into());
}
// Also scan for same idempotency_key under other operation_ids in this ledger dir.
if let Ok(rd) = fs::read_dir(&root) {
for ent in rd.flatten() {
let p = ent.path();
if p.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
if let Ok(Some(doc)) = load_record(&p) {
if doc.get("idempotency_key").and_then(|v| v.as_str()) == Some(idempotency_key) {
let dig = doc.get("args_digest").and_then(|v| v.as_str());
if dig == Some(args_digest) {
return Ok(json!({
"ok": true,
"deduped": true,
"record": doc,
}));
}
return Err(
"idempotency_key collision: same key with different args_digest".into(),
);
}
}
}
}
let doc = json!({
"schema": "EffectLedgerRecordV1",
"schema_version": 1,
"operation_id": operation_id,
"idempotency_key": idempotency_key,
"args_digest": args_digest,
"resource_scope": args.get("resource_scope").cloned().unwrap_or(Value::Null),
"expected_revision": args.get("expected_revision").cloned().unwrap_or(Value::Null),
"effect_class": effect_class,
"result_ref": args.get("result_ref").cloned().unwrap_or(Value::Null),
"state": "prepared",
"logical_run_id": args.get("logical_run_id").cloned().unwrap_or(Value::Null),
"step_id": args.get("step_id").cloned().unwrap_or(Value::Null),
"attempt_id": args.get("attempt_id").cloned().unwrap_or(Value::Null),
"prepared_at": now_rfc3339(),
"updated_at": now_rfc3339(),
});
atomic_write_json(&path, &doc)?;
Ok(json!({
"ok": true,
"deduped": false,
"record": doc,
"path": path.to_string_lossy(),
}))
}
/// Transition an existing record to a new state.
pub fn effects_transition(args: &Value) -> Result<Value, String> {
let operation_id = arg_text(args, "operation_id")?;
let to = arg_text(args, "state")?;
if !STATES.contains(&to) {
return Err(format!("invalid state={to}"));
}
let root = ledger_root(args)?;
let path = record_path(&root, operation_id);
let mut doc = load_record(&path)?
.ok_or_else(|| format!("operation_id not found: {operation_id}"))?;
let from = doc
.get("state")
.and_then(|v| v.as_str())
.unwrap_or("prepared")
.to_string();
if !valid_transition(&from, to) {
return Err(format!("illegal transition {from} → {to}"));
}
if let Some(obj) = doc.as_object_mut() {
obj.insert("state".into(), json!(to));
obj.insert("updated_at".into(), json!(now_rfc3339()));
if let Some(r) = args.get("result_ref") {
if !r.is_null() {
obj.insert("result_ref".into(), r.clone());
}
}
if let Some(n) = args.get("note") {
if !n.is_null() {
obj.insert("note".into(), n.clone());
}
}
if to == "unknown" || to.starts_with("reconciled") {
obj.insert(
"reconcile_hint".into(),
args.get("reconcile_hint")
.cloned()
.unwrap_or_else(|| json!("check receipt / resource revision")),
);
}
}
atomic_write_json(&path, &doc)?;
Ok(json!({
"ok": true,
"from": from,
"to": to,
"record": doc,
}))
}
pub fn effects_get(args: &Value) -> Result<Value, String> {
let operation_id = arg_text(args, "operation_id")?;
let root = ledger_root(args)?;
let path = record_path(&root, operation_id);
match load_record(&path)? {
Some(doc) => Ok(json!({
"ok": true,
"found": true,
"record": doc,
"path": path.to_string_lossy(),
})),
None => Ok(json!({
"ok": true,
"found": false,
"operation_id": operation_id,
"path": path.to_string_lossy(),
})),
}
}
pub fn effects_list(args: &Value) -> Result<Value, String> {
let root = ledger_root(args)?;
let mut records = Vec::new();
if root.is_dir() {
let mut paths: Vec<_> = fs::read_dir(&root)
.map_err(|e| e.to_string())?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("json"))
.collect();
paths.sort();
for p in paths {
if let Ok(Some(doc)) = load_record(&p) {
if let Some(run) = opt_text(args, "logical_run_id") {
if doc.get("logical_run_id").and_then(|v| v.as_str()) != Some(run) {
continue;
}
}
if let Some(st) = opt_text(args, "state") {
if doc.get("state").and_then(|v| v.as_str()) != Some(st) {
continue;
}
}
records.push(doc);
}
}
}
Ok(json!({
"ok": true,
"count": records.len(),
"records": records,
"ledger_dir": root.to_string_lossy(),
}))
}
/// Compute a watermark digest over committed / reconciled records for a run.
pub fn effects_watermark(args: &Value) -> Result<Value, String> {
let listed = effects_list(args)?;
let records = listed
.get("records")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let mut parts = Vec::new();
let mut open_unknown = 0u64;
let mut pending_writes = 0u64;
for r in &records {
let state = r.get("state").and_then(|v| v.as_str()).unwrap_or("");
let oid = r.get("operation_id").and_then(|v| v.as_str()).unwrap_or("");
let cls = r.get("effect_class").and_then(|v| v.as_str()).unwrap_or("");
parts.push(format!("{oid}:{state}"));
if state == "unknown" || state == "needs_input" {
open_unknown += 1;
}
if matches!(cls, "write" | "external_write" | "execute")
&& matches!(state, "prepared" | "started" | "unknown" | "needs_input")
{
pending_writes += 1;
}
}
parts.sort();
let joined = parts.join("|");
let digest = format!("sha256-lite:{:x}", fnv64(&joined));
let write_auto_resume_safe = open_unknown == 0 && pending_writes == 0;
Ok(json!({
"ok": true,
"schema": "EffectLedgerWatermarkV1",
"schema_version": 1,
"watermark": digest,
"record_count": records.len(),
"open_unknown": open_unknown,
"pending_writes": pending_writes,
"write_auto_resume_safe": write_auto_resume_safe,
"logical_run_id": args.get("logical_run_id").cloned().unwrap_or(Value::Null),
}))
}
/// Reconcile an `unknown` record after inspecting the external receipt / revision.
pub fn effects_reconcile(args: &Value) -> Result<Value, String> {
let outcome = arg_text(args, "outcome")?; // committed | no_effect | needs_input
let state = match outcome {
"committed" => "reconciled_committed",
"no_effect" => "reconciled_no_effect",
"needs_input" => "needs_input",
other => return Err(format!("invalid reconcile outcome={other}")),
};
let mut targs = args.clone();
if let Some(obj) = targs.as_object_mut() {
obj.insert("state".into(), json!(state));
}
effects_transition(&targs)
}
fn fnv64(s: &str) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in s.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x100000001b3);
}
h
}
#[cfg(test)]
mod tests {
use super::*;
// Avoid process-global set_current_dir: Rust executes tests concurrently.
// Keep each ledger in its own repository-relative, unique directory.
static SCRATCH_SEQ: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
fn scratch(tag: &str) -> PathBuf {
let seq = SCRATCH_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = PathBuf::from("target").join(format!(
"mq-effects-{}-{}-{}",
tag, std::process::id(), seq
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn prepare_dedupe_and_collision() {
let dir = scratch("prep");
let ledger_dir = dir.join("led").to_string_lossy().to_string();
let a = effects_prepare(&json!({
"operation_id": "op1",
"idempotency_key": "idem1",
"args_digest": "sha256:a",
"effect_class": "write",
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run1",
}))
.unwrap();
assert_eq!(a["deduped"], false);
assert_eq!(a["record"]["state"], "prepared");
let again = effects_prepare(&json!({
"operation_id": "op1",
"idempotency_key": "idem1",
"args_digest": "sha256:a",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
assert_eq!(again["deduped"], true);
let clash = effects_prepare(&json!({
"operation_id": "op2",
"idempotency_key": "idem1",
"args_digest": "sha256:b",
"ledger_dir": ledger_dir.clone(),
}));
assert!(clash.unwrap_err().contains("collision"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn transition_and_watermark_gates_write_resume() {
let dir = scratch("wm");
let ledger_dir = dir.join("led").to_string_lossy().to_string();
effects_prepare(&json!({
"operation_id": "op_w",
"idempotency_key": "idem_w",
"args_digest": "sha256:w",
"effect_class": "write",
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run1",
}))
.unwrap();
effects_transition(&json!({
"operation_id": "op_w",
"state": "started",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
// Crash window: unknown — write auto-resume must stay closed.
effects_transition(&json!({
"operation_id": "op_w",
"state": "unknown",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
let wm1 = effects_watermark(&json!({
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run1",
}))
.unwrap();
assert_eq!(wm1["write_auto_resume_safe"], false);
assert_eq!(wm1["open_unknown"], 1);
effects_reconcile(&json!({
"operation_id": "op_w",
"outcome": "committed",
"ledger_dir": ledger_dir.clone(),
"result_ref": "receipt:1",
}))
.unwrap();
let wm2 = effects_watermark(&json!({
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run1",
}))
.unwrap();
assert_eq!(wm2["write_auto_resume_safe"], true);
assert_eq!(wm2["open_unknown"], 0);
assert!(wm2["watermark"].as_str().unwrap().starts_with("sha256-lite:"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn ma_t03_unknown_then_reconcile_no_second_commit_path() {
// Write "succeeds" locally only after reconcile; retry while unknown must not
// look write_auto_resume_safe (MA-T03 watermark gate).
let dir = scratch("mat03");
let ledger_dir = dir.join("led").to_string_lossy().to_string();
effects_prepare(&json!({
"operation_id": "op_kill",
"idempotency_key": "run|s|write_probe|sha256-lite:1",
"args_digest": "sha256-lite:1",
"effect_class": "write",
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run_kill",
}))
.unwrap();
effects_transition(&json!({
"operation_id": "op_kill",
"state": "started",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
// Crash before commit:
effects_transition(&json!({
"operation_id": "op_kill",
"state": "unknown",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
let wm = effects_watermark(&json!({
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run_kill",
}))
.unwrap();
assert_eq!(wm["write_auto_resume_safe"], false);
// Idempotent re-prepare returns same unknown record (no new op).
let again = effects_prepare(&json!({
"operation_id": "op_kill",
"idempotency_key": "run|s|write_probe|sha256-lite:1",
"args_digest": "sha256-lite:1",
"effect_class": "write",
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run_kill",
}))
.unwrap();
assert_eq!(again["deduped"], true);
assert_eq!(again["record"]["state"], "unknown");
effects_reconcile(&json!({
"operation_id": "op_kill",
"outcome": "committed",
"ledger_dir": ledger_dir.clone(),
"result_ref": "effect:op_kill",
}))
.unwrap();
let wm2 = effects_watermark(&json!({
"ledger_dir": ledger_dir.clone(),
"logical_run_id": "run_kill",
}))
.unwrap();
assert_eq!(wm2["write_auto_resume_safe"], true);
assert_eq!(wm2["pending_writes"], 0);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn illegal_skip_started() {
let dir = scratch("bad");
let ledger_dir = dir.join("led").to_string_lossy().to_string();
effects_prepare(&json!({
"operation_id": "op_x",
"idempotency_key": "idem_x",
"args_digest": "sha256:x",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap();
let err = effects_transition(&json!({
"operation_id": "op_x",
"state": "committed",
"ledger_dir": ledger_dir.clone(),
}))
.unwrap_err();
assert!(err.contains("illegal transition"));
let _ = fs::remove_dir_all(&dir);
}
}
-731
View File
@@ -1,731 +0,0 @@
//! Engineering Knowledge preflight / reuse (reads `.marqdo` projections).
//! Does not call host_* — consumes compiled knowledge graph artifacts.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(|v| v.as_str())
.ok_or_else(|| format!("missing string arg `{key}`"))
}
fn arg_f64(args: &Value, key: &str, default: f64) -> f64 {
match args.get(key) {
Some(Value::Number(n)) => n.as_f64().unwrap_or(default),
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn arg_usize(args: &Value, key: &str, default: usize) -> usize {
match args.get(key) {
Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as usize,
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn char_bigram_tf(text: &str) -> HashMap<String, f64> {
let chars: Vec<char> = text.chars().filter(|c| !c.is_whitespace()).collect();
let mut m = HashMap::new();
if chars.is_empty() {
return m;
}
if chars.len() == 1 {
m.insert(chars[0].to_string(), 1.0);
return m;
}
for w in chars.windows(2) {
let key: String = w.iter().collect();
*m.entry(key).or_insert(0.0) += 1.0;
}
m
}
fn cosine_tf(a: &HashMap<String, f64>, b: &HashMap<String, f64>) -> f64 {
let mut na = 0.0;
let mut nb = 0.0;
for v in a.values() {
na += v * v;
}
for v in b.values() {
nb += v * v;
}
if na == 0.0 || nb == 0.0 {
return 0.0;
}
let mut dot = 0.0;
for (k, va) in a {
if let Some(vb) = b.get(k) {
dot += va * vb;
}
}
dot / (na.sqrt() * nb.sqrt())
}
fn resolve_marqdo_root(start: &str) -> PathBuf {
let mut cur = PathBuf::from(start);
if cur.is_file() {
if let Some(p) = cur.parent() {
cur = p.to_path_buf();
}
}
for _ in 0..8 {
let cand = cur.join(".marqdo");
if cand.join("engineering.yaml").exists()
|| cand.join("ekc/graph/graph.json").exists()
|| cand.join("graph/graph.json").exists()
{
return cand;
}
if !cur.pop() {
break;
}
}
PathBuf::from(start).join(".marqdo")
}
#[derive(Clone)]
struct CapHit {
id: String,
name: String,
score: f64,
implemented_by: Vec<String>,
}
fn load_capabilities(marqdo: &Path) -> Vec<(String, String, Vec<String>, String)> {
// returns (id, name, implemented_by, material)
let mut out = Vec::new();
let eng = marqdo.join("engineering.yaml");
if let Ok(raw) = fs::read_to_string(&eng) {
let mut cur_id = String::new();
let mut cur_name = String::new();
let mut impls = Vec::new();
let mut in_caps = false;
let mut in_impl = false;
for line in raw.lines() {
let t = line.trim_end();
if t.trim() == "capabilities:" {
in_caps = true;
continue;
}
if in_caps && !line.starts_with(' ') && !line.starts_with('\t') && !t.trim().is_empty()
{
if t.trim() == "knowledge:" {
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls.clone(),
format!("{cur_name} {cur_id}"),
));
}
break;
}
}
if !in_caps {
continue;
}
let trimmed = t.trim();
if let Some(rest) = trimmed.strip_prefix("- id:") {
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls.clone(),
format!("{cur_name} {cur_id}"),
));
}
cur_id = rest.trim().trim_matches('"').to_string();
cur_name.clear();
impls.clear();
in_impl = false;
} else if let Some(rest) = trimmed.strip_prefix("name:") {
cur_name = rest.trim().trim_matches('"').to_string();
} else if trimmed == "implemented_by:" {
in_impl = true;
} else if in_impl {
if let Some(rest) = trimmed.strip_prefix("- ") {
impls.push(rest.trim().trim_matches('"').to_string());
} else if !trimmed.is_empty() && !line.starts_with(' ') {
in_impl = false;
}
}
}
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls,
format!("{cur_name} {cur_id}"),
));
}
}
// Also scan catalog/capabilities/*.md
let cap_dir = marqdo.join("catalog/capabilities");
if let Ok(rd) = fs::read_dir(cap_dir) {
for ent in rd.flatten() {
let p = ent.path();
if !p
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.ends_with(".md"))
.unwrap_or(false)
{
continue;
}
let Ok(src) = fs::read_to_string(&p) else {
continue;
};
let id = fm_field(&src, "id").unwrap_or_else(|| {
p.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("cap")
.to_string()
});
let name = fm_field(&src, "name").unwrap_or_else(|| id.clone());
if out.iter().any(|(i, _, _, _)| i == &id) {
continue;
}
out.push((id.clone(), name.clone(), Vec::new(), format!("{name} {id} {src}")));
}
}
out
}
fn fm_field(source: &str, key: &str) -> Option<String> {
let prefix = format!("{key}:");
for line in source.lines() {
let t = line.trim();
if t == "---" {
continue;
}
if let Some(rest) = t.strip_prefix(&prefix) {
return Some(rest.trim().trim_matches('"').to_string());
}
}
None
}
fn load_knowledge_titles(marqdo: &Path, kind_subdir: &str) -> Vec<(String, String)> {
let dir = marqdo.join("knowledge").join(kind_subdir);
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(dir) else {
return out;
};
for ent in rd.flatten() {
let p = ent.path();
let Ok(src) = fs::read_to_string(&p) else {
continue;
};
let id = fm_field(&src, "id").unwrap_or_else(|| {
p.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("k")
.to_string()
});
let title = fm_field(&src, "title").unwrap_or_else(|| id.clone());
out.push((id, title));
}
out
}
fn rank_caps(task: &str, caps: &[(String, String, Vec<String>, String)]) -> Vec<CapHit> {
let qv = char_bigram_tf(task);
let mut hits = Vec::new();
for (id, name, impls, material) in caps {
let mut score = cosine_tf(&qv, &char_bigram_tf(material));
if name.to_ascii_lowercase().contains(&task.to_ascii_lowercase())
|| task
.to_ascii_lowercase()
.split_whitespace()
.any(|t| t.len() > 2 && name.to_ascii_lowercase().contains(t))
{
score = (score + 0.35).min(1.0);
}
if score > 0.12 {
hits.push(CapHit {
id: id.clone(),
name: name.clone(),
score,
implemented_by: impls.clone(),
});
}
}
hits.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
});
hits
}
fn relevant_knowledge(task: &str, items: &[(String, String)], cap_names: &[String]) -> Vec<String> {
let task_l = task.to_ascii_lowercase();
items
.iter()
.filter(|(id, title)| {
let m = format!("{id} {title}").to_ascii_lowercase();
task_l.split_whitespace().any(|t| t.len() > 3 && m.contains(t))
|| cap_names.iter().any(|c| m.contains(&c.to_ascii_lowercase()))
})
.map(|(id, title)| format!("{title} ({id})"))
.collect()
}
/// `agent_eng_preflight` — Engineering First Information gate.
pub fn eng_preflight(args: &Value) -> Result<Value, String> {
let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let root = args
.get("root")
.and_then(|v| v.as_str())
.unwrap_or(".");
let marqdo = args
.get("marqdo_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(|| resolve_marqdo_root(root));
if !marqdo.join("engineering.yaml").exists()
&& !marqdo.join("ekc/graph/graph.json").exists()
&& !marqdo.join("graph/graph.json").exists()
{
return Ok(json!({
"status": "missing_knowledge",
"create_allowed": false,
"decision": "CREATE",
"error": "run `marqdo knowledge` first",
"existing": [],
"recommended": [],
}));
}
let reuse_threshold = arg_f64(args, "reuse_threshold", 0.72);
let adapt_threshold = arg_f64(args, "adapt_threshold", 0.45);
let allow_create_after = arg_usize(args, "allow_create_after", 2);
let min_candidates = arg_usize(args, "min_candidates", 3);
let caps = load_capabilities(&marqdo);
let ranked = rank_caps(task, &caps);
let existing: Vec<String> = ranked.iter().take(8).map(|c| c.name.clone()).collect();
let cap_names = existing.clone();
let constraints = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "constraints"),
&cap_names,
);
let decisions = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "decisions"),
&cap_names,
);
let failures = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "failures"),
&cap_names,
);
let best = ranked.first();
let best_score = best.map(|c| c.score).unwrap_or(0.0);
let analyzed = ranked.len().max(1).min(min_candidates.max(allow_create_after));
let (decision, create_allowed, recommended, reason) = if best_score >= reuse_threshold {
let b = best.unwrap();
(
"REUSE",
false,
vec![format!("REUSE {}", b.name)],
vec![
"score meets REUSE threshold".into(),
"same capability semantics".into(),
],
)
} else if best_score >= adapt_threshold {
let b = best.unwrap();
(
"ADAPT",
false,
vec![format!("ADAPT {}", b.name)],
vec!["near match — wrap/compose/extend".into()],
)
} else if analyzed >= allow_create_after {
(
"CREATE",
true,
vec!["CREATE new capability".into()],
vec!["no existing capability satisfies constraints".into()],
)
} else {
(
"CREATE",
false,
vec![],
vec![format!(
"insufficient candidates ({analyzed} < {allow_create_after})"
)],
)
};
// Write context pack
let contexts = marqdo.join("agent/contexts");
let _ = fs::create_dir_all(&contexts);
let mut h: u64 = 5381;
for b in task.as_bytes() {
h = h.wrapping_mul(33).wrapping_add(u64::from(*b));
}
let tid = format!("{h:016x}")[..12].to_string();
let ctx_path = contexts.join(format!("task-{tid}.mq.md"));
let pack = format!(
"---\ntype: Marqdo Context Pack\ntitle: Engineering Context\ndecision: {decision}\ncreate_allowed: {create_allowed}\n---\n\n# Engineering Context\n\n## Task\n\n{task}\n\n## Existing Capabilities\n\n{existing}\n\n## Recommended Reuse\n\n{recommended}\n",
existing = existing
.iter()
.map(|e| format!("- {e}"))
.collect::<Vec<_>>()
.join("\n"),
recommended = recommended
.iter()
.enumerate()
.map(|(i, r)| format!("{}. {r}", i + 1))
.collect::<Vec<_>>()
.join("\n"),
);
let _ = fs::write(&ctx_path, pack);
let status = if create_allowed {
"ready_create"
} else if decision == "REUSE" || decision == "ADAPT" {
"ready"
} else if decision == "CREATE" && !create_allowed {
"blocked"
} else {
"ready"
};
Ok(json!({
"status": status,
"intent": { "capability": best.map(|c| c.name.clone()).unwrap_or_else(|| task.to_string()) },
"existing": existing,
"constraints": constraints,
"decisions": decisions,
"failures": failures,
"recommended": recommended,
"create_allowed": create_allowed,
"decision": decision,
"confidence": best_score,
"reason": reason,
"context_path": ctx_path.display().to_string(),
"candidates": ranked.iter().take(8).map(|c| json!({
"id": c.id,
"name": c.name,
"score": c.score,
"implemented_by": c.implemented_by,
})).collect::<Vec<_>>(),
}))
}
/// `agent_eng_reuse` — discovery + REUSE|ADAPT|CREATE decision.
///
/// Scores and capability names are **not** executable targets (G02/G07).
/// When decision is REUSE/ADAPT, callers must `artifact.bind` a
/// `bind_targets[]` entry before `artifact.execute`.
pub fn eng_reuse(args: &Value) -> Result<Value, String> {
let mut pf = eng_preflight(args)?;
if let Some(obj) = pf.as_object_mut() {
obj.insert("protocol".into(), json!("REUSE|ADAPT|CREATE"));
obj.insert("discovery_only".into(), json!(true));
let decision = obj
.get("decision")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_uppercase();
let bind_required = matches!(decision.as_str(), "REUSE" | "ADAPT");
obj.insert("bind_required".into(), json!(bind_required));
let mut targets = Vec::new();
if let Some(cands) = obj.get("candidates").and_then(|v| v.as_array()) {
for c in cands {
if let Some(impls) = c.get("implemented_by").and_then(|v| v.as_array()) {
for t in impls {
if let Some(s) = t.as_str() {
if !s.is_empty() {
targets.push(json!({
"query": s,
"via": "implemented_by",
"capability": c.get("name"),
"note": "pass query to artifact.bind then artifact.execute",
}));
}
}
}
}
if let Some(id) = c.get("id").and_then(|v| v.as_str()) {
if id.contains(':') || id.contains('.') {
targets.push(json!({
"query": id,
"via": "candidate_id",
"capability": c.get("name"),
"note": "pass query to artifact.bind then artifact.execute",
}));
}
}
}
}
// Dedup by query
let mut seen = std::collections::HashSet::new();
targets.retain(|t| {
t.get("query")
.and_then(|q| q.as_str())
.map(|q| seen.insert(q.to_string()))
.unwrap_or(false)
});
obj.insert("bind_targets".into(), json!(targets));
if bind_required {
let mut reasons = obj
.get("reason")
.cloned()
.unwrap_or_else(|| json!([]));
if let Some(arr) = reasons.as_array_mut() {
arr.push(json!(
"scores are discovery-only; bind SymbolId/handle before execute (G02/G07)"
));
}
obj.insert("reason".into(), reasons);
}
}
Ok(pf)
}
/// M04: discover → inspect → bind → execute → record (actual reuse, not n-gram REUSE).
///
/// Requires host_query `mlsp`. Returns trace with artifact_id, digests, inputs, result.
/// Does **not** promote skills — callers pass `candidate_only=true` to skip learn/promote.
pub fn eng_bind_execute(args: &Value) -> Result<Value, String> {
let project = args
.get("project")
.or_else(|| args.get("root"))
.and_then(|v| v.as_str())
.unwrap_or(".");
let policy = args
.get("policy")
.and_then(|v| v.as_str())
.unwrap_or("pure");
let inputs = args.get("inputs").cloned().unwrap_or(json!({}));
let query = if let Some(q) = args.get("artifact_id").or_else(|| args.get("query")).and_then(|v| v.as_str()) {
q.to_string()
} else {
// Fall back to first bind_target from eng_reuse.
let reuse = eng_reuse(args)?;
let targets = reuse
.get("bind_targets")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
targets
.first()
.and_then(|t| t.get("query").and_then(|q| q.as_str()))
.ok_or_else(|| {
"eng_bind_execute: no artifact_id/query and eng_reuse returned no bind_targets"
.to_string()
})?
.to_string()
};
let inspect = crate::host_query_json_args(
"mlsp",
&json!({"method":"artifact.inspect","params":{"project":project,"artifact_id":&query}}),
)?;
if inspect.get("ok") != Some(&json!(true)) {
return Ok(json!({
"ok": false,
"stage": "inspect",
"error": inspect.get("error").cloned().unwrap_or(json!("inspect failed")),
"query": query,
}));
}
let artifact_id = inspect["result"]["artifact_id"]
.as_str()
.unwrap_or(&query)
.to_string();
let bound = crate::host_query_json_args(
"mlsp",
&json!({"method":"artifact.bind","params":{"project":project,"artifact_id":&artifact_id,"policy":policy}}),
)?;
if bound.get("ok") != Some(&json!(true)) {
return Ok(json!({
"ok": false,
"stage": "bind",
"error": bound.get("error").cloned().unwrap_or(json!("bind failed")),
"artifact_id": artifact_id,
"discovery_only": false,
}));
}
let handle = bound["result"]["handle"].clone();
let executed = crate::host_query_json_args(
"mlsp",
&json!({"method":"artifact.execute","params":{"handle":&handle,"inputs":inputs}}),
)?;
if executed.get("ok") != Some(&json!(true)) {
return Ok(json!({
"ok": false,
"stage": "execute",
"error": executed.get("error").cloned().unwrap_or(json!("execute failed")),
"artifact_id": artifact_id,
"handle": handle,
}));
}
// Record only after successful bind+execute (actual reuse).
let _ = eng_record(&json!({
"decision": "REUSE",
"root": project,
"marqdo_dir": args.get("marqdo_dir"),
}));
Ok(json!({
"ok": true,
"stage": "executed",
"discovery_only": false,
"bind_required": false,
"actual_reuse": true,
"artifact_id": artifact_id,
"symbol_id": handle.get("symbol_id"),
"digest": handle.get("digest"),
"evidence_digest": handle.get("evidence_digest"),
"closure_digest": handle.get("closure_digest"),
"policy": policy,
"inputs": inputs,
"result": executed.get("result"),
"candidate_only": args.get("candidate_only").and_then(|v| v.as_bool()).unwrap_or(false),
"trace": {
"artifact_id": artifact_id,
"symbol_id": handle.get("symbol_id"),
"digest": handle.get("digest"),
"inputs": inputs,
"stdout": executed["result"]["stdout"],
"value": executed["result"]["result"],
},
}))
}
/// Gate promote/learn: when `candidate_only` or may_bind=false, refuse promotion.
pub fn eng_publish_gate(args: &Value) -> Result<Value, String> {
let candidate_only = matches!(args.get("candidate_only"), Some(Value::Bool(true)));
let product_ok = !matches!(args.get("product_gate_ok"), Some(Value::Bool(false)));
let project = args
.get("project")
.or_else(|| args.get("root"))
.and_then(|v| v.as_str())
.unwrap_or(".");
let policy = args
.get("policy")
.and_then(|v| v.as_str())
.unwrap_or("business");
let artifact = args
.get("artifact_id")
.or_else(|| args.get("query"))
.and_then(|v| v.as_str());
if candidate_only {
return Ok(json!({
"ok": true,
"may_promote": false,
"reason": "candidate_only — framework must not promote",
}));
}
if !product_ok {
return Ok(json!({
"ok": true,
"may_promote": false,
"reason": "product gate failed — framework must not promote",
}));
}
if let Some(id) = artifact {
let adj = crate::host_query_json_args(
"mlsp",
&json!({"method":"artifact.verify","params":{"project":project,"artifact_id":id,"policy":policy}}),
)?;
let may_bind = adj
.pointer("/result/may_bind")
.and_then(|v| v.as_bool())
.unwrap_or(false);
return Ok(json!({
"ok": true,
"may_promote": may_bind,
"verification": adj.get("result"),
"reason": if may_bind { "verification allows bind" } else { "verification denied bind" },
}));
}
Ok(json!({
"ok": true,
"may_promote": product_ok,
"reason": "no artifact_id; deferred to product_gate_ok",
}))
}
/// `agent_eng_record` — append reuse metrics under `.marqdo/agent/episodes`.
pub fn eng_record(args: &Value) -> Result<Value, String> {
let decision = arg_text(args, "decision")?;
let root = args
.get("root")
.and_then(|v| v.as_str())
.unwrap_or(".");
let marqdo = args
.get("marqdo_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(|| resolve_marqdo_root(root));
let duplicated = matches!(args.get("duplicated"), Some(Value::Bool(true)));
let path = marqdo.join("agent/episodes/reuse_metrics.json");
if let Some(p) = path.parent() {
let _ = fs::create_dir_all(p);
}
let mut m = if let Ok(raw) = fs::read_to_string(&path) {
serde_json::from_str::<Value>(&raw).unwrap_or(json!({}))
} else {
json!({})
};
let get_u = |v: &Value, k: &str| v.get(k).and_then(|x| x.as_u64()).unwrap_or(0);
let mut reused = get_u(&m, "reused");
let mut adapted = get_u(&m, "adapted");
let mut created = get_u(&m, "created");
let mut dups = get_u(&m, "duplicated");
match decision.to_ascii_uppercase().as_str() {
"REUSE" => reused += 1,
"ADAPT" => adapted += 1,
"CREATE" => {
created += 1;
if duplicated {
dups += 1;
}
}
_ => {}
}
m = json!({
"generated_functions": get_u(&m, "generated_functions") + 1,
"reused": reused,
"adapted": adapted,
"created": created,
"duplicated": dups,
});
let gen = m["generated_functions"].as_u64().unwrap_or(1) as f64;
m["reuse_ratio"] = json!(reused as f64 / gen);
m["adapt_ratio"] = json!(adapted as f64 / gen);
m["novel_ratio"] = json!(created as f64 / gen);
m["duplication_rate"] = json!(if created == 0 {
0.0
} else {
dups as f64 / created as f64
});
fs::write(&path, serde_json::to_string_pretty(&m).unwrap_or_default())
.map_err(|e| e.to_string())?;
Ok(m)
}
-311
View File
@@ -1,311 +0,0 @@
//! AgentErrorV1 — classified errors and bounded recovery decisions (M-A1).
use serde_json::{json, Value};
/// Build an AgentErrorV1 document from caller fields (compat: missing → defaults).
pub fn make_error(args: &Value) -> Result<Value, String> {
let code = args
.get("code")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| "missing text `code`".to_string())?;
let category = args
.get("category")
.and_then(|v| v.as_str())
.unwrap_or_else(|| infer_category(code));
let stage = args
.get("stage")
.and_then(|v| v.as_str())
.unwrap_or("agent");
let message = args
.get("message")
.and_then(|v| v.as_str())
.unwrap_or(code);
let retryable = args
.get("retryable")
.and_then(|v| v.as_bool())
.unwrap_or_else(|| default_retryable(category));
let effect_state = args
.get("effect_state")
.and_then(|v| v.as_str())
.unwrap_or("none");
let recovery_action = args
.get("recovery_action")
.and_then(|v| v.as_str())
.unwrap_or_else(|| default_recovery(category, effect_state));
let mut out = json!({
"schema": "AgentErrorV1",
"schema_version": 1,
"code": code,
"category": category,
"stage": stage,
"message": message,
"retryable": retryable,
"effect_state": effect_state,
"recovery_action": recovery_action,
});
if let Some(obj) = out.as_object_mut() {
if let Some(v) = args.get("retry_after_ms") {
obj.insert("retry_after_ms".into(), v.clone());
} else {
obj.insert("retry_after_ms".into(), Value::Null);
}
for key in ["call_id", "details_ref", "fingerprint"] {
if let Some(v) = args.get(key) {
if !v.is_null() {
obj.insert(key.into(), v.clone());
}
}
}
}
Ok(out)
}
/// Decide whether a step may auto-retry (read-only / no-effect only in M-A1).
///
/// Returns `{ok, action, reason, attempts_used, max_attempts}`.
pub fn decide_retry(args: &Value) -> Result<Value, String> {
let error = args
.get("error")
.cloned()
.ok_or_else(|| "missing map `error`".to_string())?;
let attempts = args
.get("attempts")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32;
let max_transport = args
.get("max_transport_attempts")
.and_then(|v| v.as_u64())
.unwrap_or(3) as u32; // 1 initial + 2 retries
let max_arg_repair = args
.get("max_arg_repairs")
.and_then(|v| v.as_u64())
.unwrap_or(1) as u32;
let max_output_repair = args
.get("max_output_repairs")
.and_then(|v| v.as_u64())
.unwrap_or(1) as u32;
let effect_class = args
.get("effect_class")
.and_then(|v| v.as_str())
.unwrap_or("read");
let cancelled = args
.get("cancelled")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let fingerprint_repeats = args
.get("fingerprint_repeats")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32;
if cancelled {
return Ok(decision("stop", "cancelled", attempts, max_transport));
}
let category = error
.get("category")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let retryable = error
.get("retryable")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let effect_state = error
.get("effect_state")
.and_then(|v| v.as_str())
.unwrap_or("none");
let recovery = error
.get("recovery_action")
.and_then(|v| v.as_str())
.unwrap_or("none");
// Write / unknown effect: never auto-retry in M-A1 (ledger required).
if effect_class != "read" || matches!(effect_state, "unknown" | "started" | "committed") {
return Ok(decision(
"manual_review",
"write_or_unknown_effect_requires_ledger",
attempts,
max_transport,
));
}
if fingerprint_repeats >= 2 {
return Ok(decision(
"stop",
"error_fingerprint_loop",
attempts,
max_transport,
));
}
match category {
"transient" if retryable && attempts + 1 < max_transport => Ok(decision(
"retry_step",
"transient_read_safe",
attempts,
max_transport,
)),
"invalid_arguments" if recovery == "repair_args" && attempts < max_arg_repair => Ok(
decision("repair_args", "one_arg_repair", attempts, max_arg_repair),
),
"invalid_output" if recovery == "repair_output" && attempts < max_output_repair => Ok(
decision("repair_output", "one_format_repair", attempts, max_output_repair),
),
"context_overflow" if recovery == "compact_context" && attempts == 0 => Ok(
decision("compact_context", "one_bounded_compaction", attempts, 1),
),
"auth" | "forbidden" | "policy_denied" => Ok(decision(
"needs_input",
category,
attempts,
max_transport,
)),
"budget_exhausted" => Ok(decision("partial", category, attempts, max_transport)),
"cancelled" => Ok(decision("stop", "cancelled", attempts, max_transport)),
"unknown_effect" | "worker_crash" => Ok(decision(
"manual_review",
category,
attempts,
max_transport,
)),
_ => Ok(decision("stop", "not_auto_retryable", attempts, max_transport)),
}
}
fn decision(action: &str, reason: &str, attempts: u32, max_attempts: u32) -> Value {
json!({
"ok": true,
"schema": "AgentRetryDecisionV1",
"schema_version": 1,
"action": action,
"reason": reason,
"attempts_used": attempts,
"max_attempts": max_attempts,
"auto": matches!(action, "retry_step" | "repair_args" | "repair_output" | "compact_context"),
})
}
fn infer_category(code: &str) -> &'static str {
let c = code.to_ascii_lowercase();
if c.contains("context_overflow") || c.contains("context_length") {
"context_overflow"
} else if c.contains("invalid_choice") || c.contains("invalid_output") {
"invalid_output"
} else if c.contains("timeout") || c.contains("429") || c.contains("5xx") || c.contains("connect") {
"transient"
} else if c.contains("schema") || c.contains("argument") {
"invalid_arguments"
} else if c.contains("auth") {
"auth"
} else if c.contains("forbid") {
"forbidden"
} else if c.contains("policy") {
"policy_denied"
} else if c.contains("budget") {
"budget_exhausted"
} else if c.contains("cancel") {
"cancelled"
} else if c.contains("conflict") || c.contains("stale") {
"conflict"
} else if c.contains("effect") || c.contains("crash") {
"unknown_effect"
} else {
"unknown"
}
}
fn default_retryable(category: &str) -> bool {
matches!(category, "transient")
}
fn default_recovery(category: &str, effect_state: &str) -> &'static str {
if effect_state == "unknown" {
return "reconcile";
}
match category {
"transient" => "retry_step",
"invalid_arguments" => "repair_args",
"invalid_output" => "repair_output",
"context_overflow" => "compact_context",
"auth" | "forbidden" | "policy_denied" | "needs_input" => "needs_input",
"budget_exhausted" => "return_partial",
"cancelled" => "stop",
"unknown_effect" | "worker_crash" => "manual_review",
_ => "stop",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_error_defaults() {
let err = make_error(&json!({"code": "tool.timeout", "message": "t"})).unwrap();
assert_eq!(err["schema"], "AgentErrorV1");
assert_eq!(err["category"], "transient");
assert_eq!(err["retryable"], true);
assert_eq!(err["recovery_action"], "retry_step");
}
#[test]
fn read_transient_retries_once() {
let err = make_error(&json!({"code": "tool.timeout"})).unwrap();
let d = decide_retry(&json!({
"error": err,
"attempts": 0,
"effect_class": "read"
}))
.unwrap();
assert_eq!(d["action"], "retry_step");
assert_eq!(d["auto"], true);
}
#[test]
fn write_never_auto_retries() {
let err = make_error(&json!({"code": "tool.timeout"})).unwrap();
let d = decide_retry(&json!({
"error": err,
"attempts": 0,
"effect_class": "write"
}))
.unwrap();
assert_eq!(d["action"], "manual_review");
assert_eq!(d["auto"], false);
}
#[test]
fn output_repair_is_bounded_and_read_only() {
let err = make_error(&json!({"code": "model.invalid_choice"})).unwrap();
assert_eq!(err["category"], "invalid_output");
let first = decide_retry(&json!({"error": err, "attempts": 0})).unwrap();
assert_eq!(first["action"], "repair_output");
let next = decide_retry(&json!({"error": err, "attempts": 1})).unwrap();
assert_eq!(next["action"], "stop");
let write = decide_retry(&json!({
"error": err, "attempts": 0, "effect_class": "write"
})).unwrap();
assert_eq!(write["action"], "manual_review");
}
#[test]
fn compaction_is_not_an_unbounded_model_loop() {
let err = make_error(&json!({"code": "model.context_overflow"})).unwrap();
assert_eq!(decide_retry(&json!({"error": err, "attempts": 0})).unwrap()["action"], "compact_context");
assert_eq!(decide_retry(&json!({"error": err, "attempts": 1})).unwrap()["action"], "stop");
}
#[test]
fn fingerprint_loop_stops() {
let err = make_error(&json!({"code": "tool.timeout"})).unwrap();
let d = decide_retry(&json!({
"error": err,
"attempts": 0,
"effect_class": "read",
"fingerprint_repeats": 2
}))
.unwrap();
assert_eq!(d["action"], "stop");
}
}
-251
View File
@@ -1,251 +0,0 @@
//! Durable input gates for document-native SKILLs.
//! Pausing is a committed *step boundary*, not serialization of a Rust stack.
//! The caller resumes the next documented step with the saved answer.
use std::fs::{self, OpenOptions};
use std::path::PathBuf;
use serde_json::{json, Value};
use crate::resume;
struct GateLock(PathBuf);
impl Drop for GateLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
fn text_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| format!("missing text `{key}`"))
}
fn valid_id(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 100
&& s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
}
fn root(args: &Value) -> Result<PathBuf, String> {
let name = args
.get("resume_dir")
.and_then(Value::as_str)
.unwrap_or(".marqdo/agent-resume");
let path = PathBuf::from(name);
if path.is_absolute()
|| path.components().any(|part| matches!(part, std::path::Component::ParentDir))
{
return Err("resume_dir must be a relative path without '..'".to_string());
}
fs::create_dir_all(&path).map_err(|e| format!("input gate mkdir: {e}"))?;
Ok(path)
}
fn lock(args: &Value, id: &str) -> Result<GateLock, String> {
if !valid_id(id) {
return Err("input gate id must be 1..=100 ASCII letters, numbers, '_' or '-'".into());
}
let path = root(args)?.join(format!("{id}.input-lock"));
OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.map_err(|e| format!("input gate is busy or needs reconciliation: {e}"))?;
Ok(GateLock(path))
}
fn options(args: &Value) -> Result<Value, String> {
let choices = args.get("options").and_then(Value::as_array)
.ok_or_else(|| "options must be a list of 1..=32 short labels".to_string())?;
if choices.is_empty() || choices.len() > 32 {
return Err("options must contain 1..=32 choices".into());
}
for v in choices {
let Some(s) = v.as_str() else {
return Err("every option must be text".into());
};
if s.is_empty() || s.len() > 256 {
return Err("each option must contain 1..=256 bytes".into());
}
}
let empty = crate::choice::parse_choice(&json!({
"options": choices, "reply": "__invalid_choice_probe__"
}))?;
// The parser checks duplicates and option size; the probe must not be accepted.
if empty["ok"] == true {
return Err("invalid reserved choice option".into());
}
Ok(Value::Array(choices.to_vec()))
}
/// Create a durable waiting-input checkpoint. Repeated open never resets a
/// previously answered gate. No external effect is performed.
pub fn input_open(args: &Value) -> Result<Value, String> {
let id = text_arg(args, "id")?;
let _lock = lock(args, id)?;
let labels = options(args)?;
let query = text_arg(args, "question")?;
let version = text_arg(args, "source_revision")?;
let read_args = json!({"id": id, "resume_dir": args.get("resume_dir")});
let existing = resume::resume_load(&read_args)?;
if existing["found"] == true {
let meta = &existing["meta"];
let same = meta["question"] == query
&& meta["options"] == labels
&& meta["source_revision"] == version
&& meta["session_id"] == *args.get("session_id").unwrap_or(&Value::Null)
&& meta["principal_ref"] == *args.get("principal_ref").unwrap_or(&Value::Null);
if same && existing["ok"] == true {
let status = existing["status"].as_str().unwrap_or("unknown");
return Ok(json!({
"ok": true, "id": id, "status": status,
"value": existing["result"], "reused": true,
"question": query, "options": labels
}));
}
return Ok(json!({"ok":false,"id":id,"status":"conflict",
"error":{"code":"input.stale_or_reused_gate"}}));
}
let saved = resume::resume_save(&json!({
"id": id, "resume_dir": args.get("resume_dir"),
"checkpoint_v2": true,
"status": "waiting_input",
"task": query,
"meta": {
"question": query,
"options": labels,
"source_revision": version,
"session_id": args.get("session_id").unwrap_or(&Value::Null),
"principal_ref": args.get("principal_ref").unwrap_or(&Value::Null),
"freeform": args.get("freeform").and_then(Value::as_bool).unwrap_or(true)
}
}))?;
if saved["ok"] != true {
return Err("unable to save input checkpoint".into());
}
Ok(json!({"ok": true, "id":id, "status":"waiting_input", "value":null,
"question":query,"options":labels,"reused":false}))
}
/// Resume a specific gate with a user response. Only a committed answer can be
/// replayed: different duplicate replies conflict instead of re-triggering work.
pub fn input_resume(args: &Value) -> Result<Value, String> {
let id = text_arg(args, "id")?;
let _lock = lock(args, id)?;
let reply = text_arg(args, "reply")?;
if reply.len() > 4096 {
return Err("input reply must not exceed 4096 bytes".into());
}
let version = text_arg(args, "source_revision")?;
let read_args = json!({"id": id, "resume_dir": args.get("resume_dir")});
let existing = resume::resume_load(&read_args)?;
if existing["ok"] != true || existing["schema"] != "CheckpointV2" {
return Ok(json!({"ok":false,"status":"not_found_or_corrupt","id":id}));
}
let meta = &existing["meta"];
if meta["source_revision"] != version
|| meta["session_id"] != *args.get("session_id").unwrap_or(&Value::Null)
|| meta["principal_ref"] != *args.get("principal_ref").unwrap_or(&Value::Null)
{
return Ok(json!({"ok":false,"status":"conflict","id":id,
"error":{"code":"input.scope_or_revision_changed"}}));
}
// Normalize the answer before duplicate detection: the index "2" and
// the selected label "office" must be the same committed response.
let allowed = crate::choice::parse_choice(&json!({
"options": meta["options"], "reply": reply
}))?;
let normalized = if allowed["ok"] == true {
allowed["value"].clone()
} else if meta["freeform"] == true && !reply.trim().is_empty() {
json!(reply.trim())
} else {
return Ok(json!({"ok":false,"status":"invalid","id":id,
"error":{"code":"input.invalid_choice"}}));
};
if existing["status"] == "resumed" {
if existing["result"] == normalized {
return Ok(json!({"ok":true,"status":"resumed","id":id,
"value":normalized,"reused":true}));
}
return Ok(json!({"ok":false,"status":"conflict","id":id,
"error":{"code":"input.already_answered"}}));
}
if existing["status"] != "waiting_input" {
return Ok(json!({"ok":false,"status":"conflict","id":id}));
}
let saved = resume::resume_save(&json!({
"id": id, "resume_dir": args.get("resume_dir"),
"checkpoint_v2": true,
"status": "resumed",
"task": existing["task"],
"meta": meta,
"result": normalized
}))?;
if saved["ok"] != true {
return Err("unable to commit resumed input".into());
}
Ok(json!({"ok":true,"status":"resumed","id":id,
"value":normalized,"reused":false}))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
fn fixture() -> (String, String) {
let id = format!("gate_{}_{}",std::process::id(),SEQ.fetch_add(1,Ordering::Relaxed));
let dir = format!("target/mq-gate-test-{id}");
(id, dir)
}
#[test]
fn persists_answer_without_duplicate_side_effect_or_changed_reply() {
let (id, dir) = fixture();
let initial = json!({"id":id,"resume_dir":dir,"question":"Choose?",
"options":["chat","office"],"source_revision":"v1",
"session_id":"s1","principal_ref":"u1","freeform":false});
assert_eq!(input_open(&initial).unwrap()["status"], "waiting_input");
assert_eq!(input_open(&initial).unwrap()["reused"], true);
let v = json!({"id":id,"resume_dir":dir,"reply":"2",
"source_revision":"v1","session_id":"s1","principal_ref":"u1"});
assert_eq!(input_resume(&v).unwrap()["value"], "office");
assert_eq!(input_resume(&v).unwrap()["reused"], true);
assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,
"reply":"office","source_revision":"v1","session_id":"s1",
"principal_ref":"u1"})).unwrap()["reused"], true);
assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,
"reply":"chat","source_revision":"v1","session_id":"s1",
"principal_ref":"u1"})).unwrap()["status"], "conflict");
assert_eq!(input_open(&initial).unwrap()["status"], "resumed");
}
#[test]
fn prevents_changed_source_or_unauthorized_session() {
let (id, dir) = fixture();
let initial = json!({"id":id,"resume_dir":dir,"question":"Proceed?",
"options":["yes","no"],"source_revision":"v1",
"session_id":"s1","principal_ref":"u1"});
input_open(&initial).unwrap();
for (rev,session) in [("v2","s1"),("v1","other")] {
assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,"reply":"yes",
"source_revision":rev,"session_id":session,
"principal_ref":"u1"})).unwrap()["status"], "conflict");
}
}
#[test]
fn invalid_choice_keeps_gate_open_and_no_freeform_is_enforced() {
let (id, dir) = fixture();
input_open(&json!({"id":id,"resume_dir":dir,"question":"Pick",
"options":["a","b"],"freeform":false,
"source_revision":"v1"})).unwrap();
assert_eq!(input_resume(&json!({"id":id,"resume_dir":dir,"reply":"??",
"source_revision":"v1"})).unwrap()["status"], "invalid");
assert_eq!(resume::resume_load(&json!({"id":id,"resume_dir":dir})).unwrap()["status"], "waiting_input");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-327
View File
@@ -1,327 +0,0 @@
//! MCP Client (stdio JSON-RPC) — spawn a server process, initialize, list/call tools.
use serde_json::{json, Value};
use std::ffi::CStr;
use std::io::{BufRead, BufReader, Write};
use std::os::raw::{c_char, c_int};
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::time::Duration;
use crate::{parse_args, set_err, set_out};
struct Session {
child: Child,
stdin: std::process::ChildStdin,
reader: BufReader<std::process::ChildStdout>,
next_id: i64,
server_name: String,
}
static SESSIONS: Mutex<Vec<(String, Session)>> = Mutex::new(Vec::new());
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty())
}
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
opt_text(args, key).ok_or_else(|| format!("missing text `{key}`"))
}
fn write_rpc(stdin: &mut impl Write, msg: &Value) -> Result<(), String> {
let s = serde_json::to_string(msg).map_err(|e| e.to_string())?;
writeln!(stdin, "{s}").map_err(|e| format!("mcp client write: {e}"))?;
stdin.flush().map_err(|e| format!("mcp client flush: {e}"))?;
Ok(())
}
fn read_rpc(reader: &mut impl BufRead) -> Result<Value, String> {
let mut line = String::new();
loop {
line.clear();
let n = reader
.read_line(&mut line)
.map_err(|e| format!("mcp client read: {e}"))?;
if n == 0 {
return Err("mcp client: server closed stdout".into());
}
let t = line.trim();
if t.is_empty() {
continue;
}
return serde_json::from_str(t).map_err(|e| format!("mcp client json: {e}"));
}
}
fn rpc_call(session: &mut Session, method: &str, params: Value) -> Result<Value, String> {
let id = session.next_id;
session.next_id += 1;
let req = json!({
"jsonrpc": "2.0",
"id": id,
"method": method,
"params": params,
});
write_rpc(&mut session.stdin, &req)?;
// Read until matching id (skip notifications).
for _ in 0..64 {
let resp = read_rpc(&mut session.reader)?;
if resp.get("id") == Some(&json!(id)) {
if let Some(err) = resp.get("error") {
let msg = err
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("rpc error");
return Err(msg.to_string());
}
return Ok(resp.get("result").cloned().unwrap_or(Value::Null));
}
}
Err("mcp client: no matching response".into())
}
fn spawn_session(command: &str, args: &[String], name: &str) -> Result<Session, String> {
let mut cmd = Command::new(command);
for a in args {
cmd.arg(a);
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit());
let mut child = cmd
.spawn()
.map_err(|e| format!("mcp client spawn `{command}`: {e}"))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| "mcp client: no stdin".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "mcp client: no stdout".to_string())?;
let mut session = Session {
child,
stdin,
reader: BufReader::new(stdout),
next_id: 1,
server_name: name.to_string(),
};
// initialize
let _ = rpc_call(
&mut session,
"initialize",
json!({
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": { "name": "marqdo-agent", "version": "0.1.0" }
}),
)?;
// optional initialized notification
let _ = write_rpc(
&mut session.stdin,
&json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
"params": {}
}),
);
let _ = session.server_name;
// Give slow servers a beat (ignore).
let _ = Duration::from_millis(1);
Ok(session)
}
fn command_args(args: &Value) -> Result<(String, Vec<String>), String> {
let command = arg_text(args, "command")?;
let mut argv = Vec::new();
if let Some(arr) = args.get("args").and_then(|v| v.as_array()) {
for a in arr {
if let Some(s) = a.as_str() {
argv.push(s.to_string());
} else {
argv.push(a.to_string());
}
}
} else if let Some(s) = opt_text(args, "args") {
// space-split simple args
for part in s.split_whitespace() {
argv.push(part.to_string());
}
}
Ok((command.to_string(), argv))
}
fn session_id_of(args: &Value) -> String {
opt_text(args, "session")
.or_else(|| opt_text(args, "id"))
.unwrap_or("default")
.to_string()
}
fn with_session<F>(args: &Value, f: F) -> Result<Value, String>
where
F: FnOnce(&mut Session) -> Result<Value, String>,
{
let sid = session_id_of(args);
let mut guard = SESSIONS
.lock()
.map_err(|_| "mcp client: session lock poisoned".to_string())?;
let idx = guard
.iter()
.position(|(id, _)| id == &sid)
.ok_or_else(|| format!("mcp client: no session `{sid}` (call connect first)"))?;
f(&mut guard[idx].1)
}
fn action_connect(args: &Value) -> Result<Value, String> {
let (command, argv) = command_args(args)?;
let name = opt_text(args, "name").unwrap_or("mcp");
let sid = session_id_of(args);
let session = spawn_session(&command, &argv, name)?;
let mut guard = SESSIONS
.lock()
.map_err(|_| "mcp client: session lock poisoned".to_string())?;
// Replace existing
guard.retain(|(id, _)| id != &sid);
guard.push((sid.clone(), session));
Ok(json!({
"ok": true,
"session": sid,
"transport": "stdio",
"command": command,
}))
}
fn action_list(args: &Value) -> Result<Value, String> {
with_session(args, |s| {
let result = rpc_call(s, "tools/list", json!({}))?;
let mut out = result;
if let Some(obj) = out.as_object_mut() {
obj.insert("authority".into(), json!("workbook"));
obj.insert("session".into(), json!(session_id_of(args)));
}
Ok(out)
})
}
fn action_call(args: &Value) -> Result<Value, String> {
let name = arg_text(args, "name")?;
let arguments = args.get("arguments").cloned().unwrap_or(json!({}));
with_session(args, |s| {
let result = rpc_call(
s,
"tools/call",
json!({ "name": name, "arguments": arguments }),
)?;
let mut out = if result.is_object() {
result
} else {
json!({ "result": result })
};
if let Some(obj) = out.as_object_mut() {
obj.insert("authority".into(), json!("workbook"));
obj.insert("session".into(), json!(session_id_of(args)));
}
Ok(out)
})
}
fn action_close(args: &Value) -> Result<Value, String> {
let sid = session_id_of(args);
let mut guard = SESSIONS
.lock()
.map_err(|_| "mcp client: session lock poisoned".to_string())?;
if let Some(idx) = guard.iter().position(|(id, _)| id == &sid) {
let (_, mut session) = guard.remove(idx);
let _ = session.child.kill();
let _ = session.child.wait();
Ok(json!({ "ok": true, "session": sid, "closed": true }))
} else {
Ok(json!({ "ok": true, "session": sid, "closed": false }))
}
}
/// One-shot: connect → list or call → close (no persistent session).
fn action_oneshot(args: &Value, kind: &str) -> Result<Value, String> {
let (command, argv) = command_args(args)?;
let name = opt_text(args, "name").unwrap_or("mcp");
let mut session = spawn_session(&command, &argv, name)?;
let result = match kind {
"list" => {
let r = rpc_call(&mut session, "tools/list", json!({}))?;
Ok(r)
}
"call" => {
let tname = arg_text(args, "tool").or_else(|_| arg_text(args, "name"))?;
// When oneshot call, `name` may be server name — prefer `tool=`.
let tname = opt_text(args, "tool").unwrap_or(tname);
let arguments = args.get("arguments").cloned().unwrap_or(json!({}));
rpc_call(
&mut session,
"tools/call",
json!({ "name": tname, "arguments": arguments }),
)
}
_ => Err(format!("unknown oneshot kind `{kind}`")),
};
let _ = session.child.kill();
let _ = session.child.wait();
let mut out = result?;
if let Some(obj) = out.as_object_mut() {
obj.insert("authority".into(), json!("workbook"));
obj.insert("transport".into(), json!("stdio"));
}
Ok(out)
}
pub fn mcp_client(args: &Value) -> Result<Value, String> {
let action = opt_text(args, "action").unwrap_or("list");
match action {
"connect" => action_connect(args),
"list" => {
if opt_text(args, "command").is_some() && opt_text(args, "session").is_none() {
action_oneshot(args, "list")
} else {
action_list(args)
}
}
"call" => {
if opt_text(args, "command").is_some() && opt_text(args, "session").is_none() {
action_oneshot(args, "call")
} else {
action_call(args)
}
}
"close" | "disconnect" => action_close(args),
other => Err(format!(
"mcp client: unknown action `{other}` (connect|list|call|close)"
)),
}
}
pub unsafe extern "C" fn agent_mcp_client(
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> c_int {
let args = match parse_args(args_json) {
Ok(v) => v,
Err(e) => {
set_err(err_msg, &e);
return 1;
}
};
match mcp_client(&args) {
Ok(v) => {
set_out(out_json, &v.to_string());
0
}
Err(e) => {
set_err(err_msg, &e);
1
}
}
}
#[allow(dead_code)]
fn _unused(_: &CStr) {}
-507
View File
@@ -1,507 +0,0 @@
//! Minimal MCP Server — stdio JSON-RPC + Streamable HTTP (spec 2025-03-26).
use serde_json::{json, Map, Value};
use std::ffi::CStr;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::os::raw::{c_char, c_int};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{host_query_json_args, parse_args, set_err, set_out};
fn read_line_message(reader: &mut impl BufRead) -> Result<Option<Value>, String> {
let mut line = String::new();
let n = reader
.read_line(&mut line)
.map_err(|e| format!("stdin: {e}"))?;
if n == 0 {
return Ok(None);
}
let line = line.trim();
if line.is_empty() {
return read_line_message(reader);
}
let v: Value = serde_json::from_str(line).map_err(|e| format!("json-rpc parse: {e}"))?;
Ok(Some(v))
}
fn write_message(msg: &Value) -> Result<(), String> {
let mut out = std::io::stdout().lock();
let s = serde_json::to_string(msg).map_err(|e| e.to_string())?;
writeln!(out, "{s}").map_err(|e| format!("stdout: {e}"))?;
out.flush().map_err(|e| format!("flush: {e}"))?;
Ok(())
}
fn rpc_result(id: &Value, result: Value) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"result": result,
})
}
fn rpc_error(id: &Value, code: i64, message: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"error": { "code": code, "message": message },
})
}
fn tools_list(tools: &[Value]) -> Value {
let mut arr = Vec::new();
for t in tools {
let name = t.get("name").and_then(|v| v.as_str()).unwrap_or("");
let desc = t
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("");
if name.is_empty() {
continue;
}
arr.push(json!({
"name": name,
"description": desc,
"inputSchema": {
"type": "object",
"properties": {},
"additionalProperties": true
}
}));
}
json!({ "tools": arr })
}
fn call_tool(tools: &[Value], name: &str, arguments: &Value) -> Result<Value, String> {
let tool = tools
.iter()
.find(|t| t.get("name").and_then(|v| v.as_str()) == Some(name))
.ok_or_else(|| format!("unknown tool `{name}`"))?;
let fn_path = tool
.get("fn")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tool `{name}` missing fn"))?
.to_string();
let result = host_query_json_args(
"call_lib_path",
&json!({
"path": fn_path,
"args": arguments,
}),
)?;
Ok(json!({
"content": [{
"type": "text",
"text": serde_json::to_string(&result).unwrap_or_else(|_| "{}".into())
}],
"isError": false,
"authority": "workbook"
}))
}
/// Handle one JSON-RPC message. Returns `None` for notifications (no response body).
fn dispatch_rpc(name: &str, tools: &[Value], msg: &Value) -> Option<Value> {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or("");
let params = msg.get("params").cloned().unwrap_or(json!({}));
if matches!(id, Value::Null) && method.starts_with("notifications/") {
return None;
}
Some(match method {
"initialize" => rpc_result(
&id,
json!({
"protocolVersion": "2025-03-26",
"capabilities": { "tools": {} },
"serverInfo": { "name": name, "version": "0.1.0" }
}),
),
"tools/list" | "list_tools" => rpc_result(&id, tools_list(tools)),
"tools/call" | "call_tool" => {
let tname = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match call_tool(tools, tname, &args) {
Ok(r) => rpc_result(&id, r),
Err(e) => rpc_error(&id, -32000, &e),
}
}
"ping" => rpc_result(&id, json!({})),
"" => rpc_error(&id, -32600, "missing method"),
other => rpc_error(&id, -32601, &format!("method not found: {other}")),
})
}
/// Blocking stdio MCP loop. `tools` is a JSON array of `{name, fn, description}`.
pub fn serve_stdio(name: &str, tools: Vec<Value>) -> Result<Value, String> {
let stdin = std::io::stdin();
let mut reader = BufReader::new(stdin.lock());
loop {
let Some(msg) = read_line_message(&mut reader)? else {
break;
};
if let Some(reply) = dispatch_rpc(name, &tools, &msg) {
write_message(&reply)?;
}
}
Ok(json!({ "ok": true, "transport": "stdio" }))
}
fn new_session_id() -> String {
static SEQ: AtomicU64 = AtomicU64::new(1);
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
format!("mcp-{ms}-{n}")
}
fn read_http_request(
reader: &mut BufReader<TcpStream>,
) -> Result<(String, String, Vec<(String, String)>, Vec<u8>), String> {
let mut request_line = String::new();
reader
.read_line(&mut request_line)
.map_err(|e| format!("read request: {e}"))?;
let parts: Vec<&str> = request_line.trim().split_whitespace().collect();
if parts.len() < 2 {
return Err("bad request line".into());
}
let method = parts[0].to_string();
let path = parts[1].to_string();
let mut headers = Vec::new();
let mut content_length = 0usize;
loop {
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|e| format!("read header: {e}"))?;
let line = line.trim_end_matches(['\r', '\n']);
if line.is_empty() {
break;
}
if let Some((k, v)) = line.split_once(':') {
let key = k.trim().to_string();
let val = v.trim().to_string();
if key.eq_ignore_ascii_case("content-length") {
content_length = val.parse().unwrap_or(0);
}
headers.push((key, val));
}
}
let mut body = vec![0u8; content_length];
if content_length > 0 {
reader
.read_exact(&mut body)
.map_err(|e| format!("read body: {e}"))?;
}
Ok((method, path, headers, body))
}
fn header_get<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
fn write_http(
stream: &mut TcpStream,
status: u16,
reason: &str,
content_type: &str,
body: &[u8],
extra: &[(&str, &str)],
) -> Result<(), String> {
let mut head = format!(
"HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n",
body.len()
);
for (k, v) in extra {
head.push_str(k);
head.push_str(": ");
head.push_str(v);
head.push_str("\r\n");
}
head.push_str("\r\n");
stream
.write_all(head.as_bytes())
.map_err(|e| e.to_string())?;
stream.write_all(body).map_err(|e| e.to_string())?;
stream.flush().map_err(|e| e.to_string())?;
Ok(())
}
fn path_matches(req_path: &str, endpoint: &str) -> bool {
let base = req_path.split('?').next().unwrap_or(req_path);
base == endpoint || base.trim_end_matches('/') == endpoint.trim_end_matches('/')
}
fn handle_http_conn(
stream: TcpStream,
name: &str,
tools: &[Value],
endpoint: &str,
) -> Result<(), String> {
let mut reader = BufReader::new(stream);
let (method, path, headers, body) = read_http_request(&mut reader)?;
let mut stream = reader.into_inner();
if !path_matches(&path, endpoint) {
write_http(
&mut stream,
404,
"Not Found",
"application/json",
br#"{"error":"not_found"}"#,
&[],
)?;
return Ok(());
}
if method.eq_ignore_ascii_case("GET") {
// Optional SSE stream — empty keepalive then close (clients may 405).
let accept = header_get(&headers, "Accept").unwrap_or("");
if accept.contains("text/event-stream") {
let body = b": mcp streamable-http ready\n\n";
write_http(
&mut stream,
200,
"OK",
"text/event-stream",
body,
&[("Cache-Control", "no-cache")],
)?;
} else {
write_http(
&mut stream,
405,
"Method Not Allowed",
"application/json",
br#"{"error":"use_post_for_jsonrpc"}"#,
&[("Allow", "POST, GET")],
)?;
}
return Ok(());
}
if method.eq_ignore_ascii_case("DELETE") {
write_http(&mut stream, 200, "OK", "application/json", b"{}", &[])?;
return Ok(());
}
if !method.eq_ignore_ascii_case("POST") {
write_http(
&mut stream,
405,
"Method Not Allowed",
"application/json",
br#"{"error":"method_not_allowed"}"#,
&[("Allow", "POST, GET, DELETE")],
)?;
return Ok(());
}
let text = String::from_utf8_lossy(&body);
let msg: Value = serde_json::from_str(text.trim()).map_err(|e| format!("json-rpc: {e}"))?;
let is_init = msg.get("method").and_then(|v| v.as_str()) == Some("initialize");
let existing_sid = header_get(&headers, "Mcp-Session-Id")
.or_else(|| header_get(&headers, "MCP-Session-Id"))
.map(|s| s.to_string());
// Notifications → 202 Accepted, empty body.
if msg.get("id").is_none() || msg.get("id") == Some(&Value::Null) {
if let Some(m) = msg.get("method").and_then(|v| v.as_str()) {
if m.starts_with("notifications/") {
write_http(
&mut stream,
202,
"Accepted",
"application/json",
b"",
&[],
)?;
return Ok(());
}
}
}
let reply = match dispatch_rpc(name, tools, &msg) {
Some(r) => r,
None => {
write_http(
&mut stream,
202,
"Accepted",
"application/json",
b"",
&[],
)?;
return Ok(());
}
};
let body = serde_json::to_vec(&reply).map_err(|e| e.to_string())?;
let mut extras: Vec<(&str, String)> = Vec::new();
if is_init {
let sid = existing_sid.unwrap_or_else(new_session_id);
extras.push(("Mcp-Session-Id", sid));
} else if let Some(sid) = existing_sid {
extras.push(("Mcp-Session-Id", sid));
}
let extra_refs: Vec<(&str, &str)> = extras.iter().map(|(k, v)| (*k, v.as_str())).collect();
write_http(
&mut stream,
200,
"OK",
"application/json",
&body,
&extra_refs,
)?;
Ok(())
}
/// Streamable HTTP MCP (POST JSON-RPC + optional GET SSE). Spec 2025-03-26.
pub fn serve_http(
name: &str,
tools: Vec<Value>,
host: &str,
port: u16,
path: &str,
) -> Result<Value, String> {
let addr = format!("{host}:{port}");
let listener = TcpListener::bind(&addr).map_err(|e| format!("bind {addr}: {e}"))?;
let name = Arc::new(name.to_string());
let tools = Arc::new(tools);
let endpoint = Arc::new(if path.is_empty() {
"/mcp".to_string()
} else if path.starts_with('/') {
path.to_string()
} else {
format!("/{path}")
});
eprintln!(
"mcp streamable-http listening on http://{addr}{} (POST JSON-RPC)",
&*endpoint
);
for conn in listener.incoming() {
match conn {
Ok(stream) => {
let name = Arc::clone(&name);
let tools = Arc::clone(&tools);
let endpoint = Arc::clone(&endpoint);
thread::spawn(move || {
if let Err(e) = handle_http_conn(stream, &name, &tools, &endpoint) {
eprintln!("mcp http conn: {e}");
}
});
}
Err(e) => eprintln!("mcp http accept: {e}"),
}
}
Ok(json!({
"ok": true,
"transport": "http",
"host": host,
"port": port,
"path": *endpoint
}))
}
pub fn tools_from_value(v: &Value) -> Vec<Value> {
if let Some(arr) = v.as_array() {
return arr.clone();
}
if let Value::Object(map) = v {
let mut out = Vec::new();
for (name, spec) in map {
let mut m = Map::new();
m.insert("name".into(), json!(name));
if let Some(obj) = spec.as_object() {
for (k, val) in obj {
m.insert(k.clone(), val.clone());
}
} else if let Some(s) = spec.as_str() {
m.insert("fn".into(), json!(s));
}
out.push(Value::Object(m));
}
return out;
}
Vec::new()
}
pub unsafe extern "C" fn agent_mcp_serve(
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> c_int {
let args = match parse_args(args_json) {
Ok(v) => v,
Err(e) => {
set_err(err_msg, &e);
return 1;
}
};
let transport = args
.get("transport")
.and_then(|v| v.as_str())
.unwrap_or("stdio");
let name = args
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("marqdo");
let tools = args
.get("tools")
.map(tools_from_value)
.unwrap_or_default();
let result = match transport {
"stdio" => serve_stdio(name, tools),
"http" | "streamable-http" | "sse" => {
let host = args
.get("host")
.and_then(|v| v.as_str())
.unwrap_or("127.0.0.1");
let port = args
.get("port")
.and_then(|v| {
v.as_u64()
.or_else(|| v.as_i64().map(|n| n as u64))
.or_else(|| v.as_str().and_then(|s| s.parse().ok()))
})
.unwrap_or(7434) as u16;
let path = args
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("/mcp");
serve_http(name, tools, host, port, path)
}
other => {
set_err(
err_msg,
&format!("mcp serve: transport `{other}` not supported (use stdio|http)"),
);
return 1;
}
};
match result {
Ok(v) => {
set_out(out_json, &v.to_string());
0
}
Err(e) => {
set_err(err_msg, &e);
1
}
}
}
#[allow(dead_code)]
fn _unused(_: &CStr) {}
File diff suppressed because it is too large. Load diff
-289
View File
@@ -1,289 +0,0 @@
//! AgentOutputV1 + ResponsePolicy (M-A4).
use serde_json::{json, Value};
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
/// Normalize / build an AgentOutputV1 document.
pub fn output_build(args: &Value) -> Result<Value, String> {
let status = opt_text(args, "status").unwrap_or("succeeded");
if !matches!(
status,
"succeeded" | "partial" | "failed" | "needs_input" | "cancelled"
) {
return Err(format!("invalid status={status}"));
}
let answer = args.get("answer").cloned().unwrap_or_else(|| {
json!({
"format": opt_text(args, "format").unwrap_or("markdown"),
"text": opt_text(args, "text").unwrap_or(""),
})
});
let validation = args.get("validation").cloned().unwrap_or_else(|| {
json!({
"status": "not_run",
"report_ref": Value::Null
})
});
let vstatus = validation
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("not_run");
if !matches!(
vstatus,
"passed" | "failed" | "not_applicable" | "not_run"
) {
return Err(format!("invalid validation.status={vstatus}"));
}
// Never claim passed without an explicit report when status says passed.
if vstatus == "passed" && validation.get("report_ref").map(|v| v.is_null()).unwrap_or(true) {
if args.get("allow_passed_without_report").and_then(|v| v.as_bool()) != Some(true) {
return Err("validation.status=passed requires report_ref".into());
}
}
let finish = opt_text(args, "finish_reason").unwrap_or(match status {
"succeeded" => "completed",
"partial" => "length_limited",
"cancelled" => "cancelled",
"needs_input" => "needs_input",
_ => "error",
});
Ok(json!({
"schema": "AgentOutputV1",
"schema_version": 1,
"status": status,
"answer": answer,
"artifacts": args.get("artifacts").cloned().unwrap_or_else(|| json!([])),
"citations": args.get("citations").cloned().unwrap_or_else(|| json!([])),
"validation": validation,
"finish_reason": finish,
"recovery_options": args.get("recovery_options").cloned().unwrap_or_else(|| json!([])),
"channels": args.get("channels").cloned().unwrap_or_else(|| json!({
"answer": true,
"artifact": true,
"progress": true,
"diagnostic": true
})),
}))
}
/// Apply ResponsePolicy budgets to an answer text → possibly partial output.
pub fn output_apply_policy(args: &Value) -> Result<Value, String> {
let mut out = if args.get("schema").and_then(|v| v.as_str()) == Some("AgentOutputV1") {
args.clone()
} else {
output_build(args)?
};
let policy = args.get("policy").cloned().unwrap_or(json!({}));
let detail = policy
.get("detail")
.and_then(|v| v.as_str())
.unwrap_or("standard");
let max_chars = match policy.get("max_chars").and_then(|v| v.as_u64()) {
Some(n) if n > 0 => n as usize,
_ => match detail {
"concise" => 250,
"detailed" => 8_000,
_ => 700,
},
};
let max_tokens = policy
.get("max_output_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0) as usize;
let artifact_allowed = policy
.get("artifact_allowed")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let text = out
.pointer("/answer/text")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
// Soft char budget (CJK-aware enough: count Unicode scalars).
let chars: Vec<char> = text.chars().collect();
let mut finish = out
.get("finish_reason")
.and_then(|v| v.as_str())
.unwrap_or("completed")
.to_string();
let mut status = out
.get("status")
.and_then(|v| v.as_str())
.unwrap_or("succeeded")
.to_string();
let mut answer_text = text.clone();
if chars.len() > max_chars {
answer_text = chars.into_iter().take(max_chars).collect();
// Prefer not to cut mid-code fence if possible — soft trim at last newline.
if let Some(pos) = answer_text.rfind('\n') {
if pos > max_chars / 2 {
answer_text.truncate(pos);
}
}
finish = "length_limited".into();
if status == "succeeded" {
status = "partial".into();
}
}
// Token budget is advisory here (chars/4 approx) when max_output_tokens set.
if max_tokens > 0 {
let approx = answer_text.chars().count().div_ceil(2); // rough CJK token estimate
if approx > max_tokens {
let keep = max_tokens.saturating_mul(2);
answer_text = answer_text.chars().take(keep).collect();
finish = "length_limited".into();
status = "partial".into();
}
}
if let Some(obj) = out.as_object_mut() {
obj.insert("status".into(), json!(status));
obj.insert("finish_reason".into(), json!(finish));
if let Some(ans) = obj.get_mut("answer").and_then(|v| v.as_object_mut()) {
ans.insert("text".into(), json!(answer_text));
}
if !artifact_allowed {
obj.insert("artifacts".into(), json!([]));
}
obj.insert(
"response_policy".into(),
json!({
"detail": detail,
"max_chars": max_chars,
"max_output_tokens": max_tokens,
"artifact_allowed": artifact_allowed,
}),
);
}
Ok(out)
}
/// Split a channel event. Only `answer` is meant for chat body append.
pub fn output_channel_event(args: &Value) -> Result<Value, String> {
let channel = opt_text(args, "channel").ok_or_else(|| "missing channel".to_string())?;
if !matches!(channel, "answer" | "artifact" | "progress" | "diagnostic") {
return Err(format!("invalid channel={channel}"));
}
let delta = opt_text(args, "delta").unwrap_or("");
Ok(json!({
"schema": "AgentChannelEventV1",
"schema_version": 1,
"channel": channel,
"delta": delta,
"append_to_chat": channel == "answer",
"resource_id": args.get("resource_id").cloned().unwrap_or(Value::Null),
"meta": args.get("meta").cloned().unwrap_or(json!({})),
}))
}
/// Project `# 结论` (or first non-empty paragraph) from a marqdo document for chat.
pub fn output_project_conclusion(args: &Value) -> Result<Value, String> {
let doc = opt_text(args, "document")
.or_else(|| opt_text(args, "text"))
.unwrap_or("");
let mut in_conclusion = false;
let mut buf = String::new();
for line in doc.lines() {
let t = line.trim();
if t == "# 结论" || t.eq_ignore_ascii_case("# conclusion") {
in_conclusion = true;
continue;
}
if in_conclusion {
if t.starts_with("# ") {
break;
}
if t.is_empty() {
if !buf.is_empty() {
buf.push('\n');
}
continue;
}
if !buf.is_empty() {
buf.push('\n');
}
buf.push_str(t);
}
}
if buf.trim().is_empty() {
// Fallback: first non-frontmatter paragraph.
let mut past_fm = !doc.starts_with("---");
let mut fm_done = past_fm;
for line in doc.lines() {
if !fm_done {
if line.trim() == "---" {
if past_fm {
fm_done = true;
} else {
past_fm = true;
}
}
continue;
}
let t = line.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with('|') {
continue;
}
buf = t.to_string();
break;
}
}
Ok(json!({
"ok": true,
"text": buf.trim(),
"channel": "answer",
"source": "conclusion_projection",
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_and_policy_limits() {
let out = output_build(&json!({
"status": "succeeded",
"text": "短答",
"validation": {"status": "not_applicable", "report_ref": null}
}))
.unwrap();
assert_eq!(out["schema"], "AgentOutputV1");
assert_eq!(out["answer"]["text"], "短答");
let long: String = "字".repeat(400);
let limited = output_apply_policy(&json!({
"status": "succeeded",
"text": long,
"validation": {"status": "not_applicable"},
"policy": {"detail": "concise", "max_chars": 100}
}))
.unwrap();
assert_eq!(limited["status"], "partial");
assert_eq!(limited["finish_reason"], "length_limited");
assert!(limited["answer"]["text"].as_str().unwrap().chars().count() <= 100);
}
#[test]
fn channel_answer_only_appends_chat() {
let e = output_channel_event(&json!({"channel": "progress", "delta": "检索中"})).unwrap();
assert_eq!(e["append_to_chat"], false);
let a = output_channel_event(&json!({"channel": "answer", "delta": "hi"})).unwrap();
assert_eq!(a["append_to_chat"], true);
}
#[test]
fn project_conclusion() {
let doc = "---\ntitle: t\n---\n\n# 任务\n问\n\n# 结论\n答案是 42。\n\n# main\nprint\n";
let p = output_project_conclusion(&json!({"document": doc})).unwrap();
assert!(p["text"].as_str().unwrap().contains("42"));
}
}
-81
View File
@@ -1,81 +0,0 @@
//! Deterministic fan-out results: never discard a successful sibling and never
//! infer success from a completed wait protocol alone.
use serde_json::{json, Value};
pub fn report(args: &Value) -> Result<Value, String> {
let results = args
.get("results")
.and_then(Value::as_array)
.ok_or_else(|| "results must be ordered subtask result list".to_string())?;
if results.len() > 10_000 {
return Err("parallel result count exceeds scheduler limit".into());
}
let mut passed = 0usize;
let mut failed = 0usize;
let mut unknown = 0usize;
let mut entries = Vec::with_capacity(results.len());
for (index, child) in results.iter().enumerate() {
let transport = child.get("ok").and_then(Value::as_bool);
let body = child.get("value").unwrap_or(&Value::Null);
let status = match (transport, body.get("code").and_then(Value::as_i64)) {
(Some(true), Some(0)) => { passed += 1; "succeeded" }
(Some(true), Some(_)) | (Some(false), _) => { failed += 1; "failed" }
_ => { unknown += 1; "uncertain" }
};
// Raw child result is kept as data; the model sees only an optional
// bounded summary. The host may store detailed output as an artifact.
let detail = child.get("error")
.and_then(Value::as_str)
.or_else(|| body.get("stderr").and_then(Value::as_str))
.unwrap_or("");
let brief: String = detail.chars().take(280).collect();
entries.push(json!({
"index": index,
"status": status,
"summary": brief,
"result": child
}));
}
let status = if unknown != 0 {
"uncertain"
} else if failed == 0 {
"succeeded"
} else if passed > 0 {
"partial"
} else {
"failed"
};
Ok(json!({
"ok": failed == 0 && unknown == 0,
"schema": "AgentParallelResultV1",
"status": status,
"succeeded": passed,
"failed": failed,
"uncertain": unknown,
"items": entries
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_success_and_exposes_failed_child() {
let result = report(&json!({"results":[
{"ok":true,"value":{"code":0,"value":"good"}},
{"ok":true,"value":{"code":2,"stderr":"failed"}},
{"ok":false,"error":"timeout"}
]})).unwrap();
assert_eq!(result["status"], "partial");
assert_eq!(result["succeeded"], 1);
assert_eq!(result["failed"], 2);
assert_eq!(result["items"][0]["status"], "succeeded");
}
#[test]
fn unknown_child_cannot_be_mislabeled_successful() {
let value = report(&json!({"results":[{"ok":true,"value":{"value":"no code"}}]})).unwrap();
assert_eq!(value["status"], "uncertain");
assert_eq!(value["ok"], false);
}
}
-511
View File
@@ -1,511 +0,0 @@
//! Agent plan/run resume checkpoints under `.marqdo/agent-resume/`.
//! M-A1: CheckpointV2 atomic write (temp→fsync→rename); legacy load → manual_review.
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
const DEFAULT_RESUME_DIR: &str = ".marqdo/agent-resume";
fn resolve_path(rel: &str) -> PathBuf {
let p = PathBuf::from(rel);
if p.is_absolute() {
return p;
}
if p.exists() {
return p;
}
let base = (|| {
let q = crate::host_query_json("cwd")?;
q.as_str()
.map(PathBuf::from)
.ok_or_else(|| "cwd not text".to_string())
})()
.or_else(|_| std::env::current_dir().map_err(|e| e.to_string()))
.unwrap_or_else(|_| PathBuf::from("."));
base.join(p)
}
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
opt_text(args, key).ok_or_else(|| format!("missing text `{key}`"))
}
fn opt_i64(args: &Value, key: &str, default: i64) -> i64 {
match args.get(key) {
None | Some(Value::Null) => default,
Some(Value::Number(n)) => n.as_i64().unwrap_or(default),
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
/// Host-relative resume roots only — reject absolute client paths (M-A1).
fn resume_root(args: &Value) -> Result<PathBuf, String> {
let rel = opt_text(args, "resume_dir").unwrap_or(DEFAULT_RESUME_DIR);
let p = PathBuf::from(rel);
if p.is_absolute() {
return Err(
"resume_dir must be host-relative; absolute client paths are rejected".into(),
);
}
if rel.contains("..") {
return Err("resume_dir must not contain '..'".into());
}
Ok(resolve_path(rel))
}
fn checkpoint_path(root: &Path, id: &str) -> PathBuf {
let safe: String = id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
root.join(format!("{safe}.json"))
}
fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn ensure_dir(root: &Path) -> Result<(), String> {
fs::create_dir_all(root).map_err(|e| format!("resume mkdir: {e}"))
}
/// Atomic durable write: unique temp → write → flush/fsync → rename.
static TEMP_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn atomic_write_json(path: &Path, doc: &Value) -> Result<(), String> {
let parent = path
.parent()
.ok_or_else(|| "checkpoint path has no parent".to_string())?;
ensure_dir(parent)?;
let tmp_name = format!(
".{}.tmp-{}-{}",
path.file_name()
.and_then(|s| s.to_str())
.unwrap_or("ckpt.json"),
std::process::id(),
format!("{}-{}", now_rfc3339().replace(':', ""),
TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
);
let tmp = parent.join(tmp_name);
let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?;
{
let mut f = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&tmp)
.map_err(|e| format!("resume temp open: {e}"))?;
f.write_all(text.as_bytes())
.map_err(|e| format!("resume temp write: {e}"))?;
f.flush().map_err(|e| format!("resume temp flush: {e}"))?;
f.sync_all()
.map_err(|e| format!("resume temp fsync: {e}"))?;
}
// Best-effort directory fsync (platform may ignore).
if let Ok(dir) = File::open(parent) {
let _ = dir.sync_all();
}
fs::rename(&tmp, path).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("resume atomic rename: {e}")
})?;
Ok(())
}
fn wants_checkpoint_v2(args: &Value) -> bool {
matches!(
args.get("schema").and_then(|v| v.as_str()),
Some("CheckpointV2")
) || args.get("schema_version").and_then(|v| v.as_u64()) == Some(2)
|| args.get("checkpoint_v2").and_then(|v| v.as_bool()) == Some(true)
}
fn build_checkpoint_v2(args: &Value, id: &str) -> Value {
let committed = now_rfc3339();
let mut doc = json!({
"schema": "CheckpointV2",
"schema_version": 2,
"checkpoint_id": args.get("checkpoint_id").cloned().unwrap_or_else(|| json!(id)),
"logical_run_id": args.get("logical_run_id").cloned().unwrap_or_else(|| json!(id)),
"task_id": args.get("task_id").cloned().unwrap_or_else(|| json!(id)),
"attempt_id": args.get("attempt_id").cloned().unwrap_or_else(|| json!("attempt_1")),
"step_id": args.get("step_id").cloned().unwrap_or(Value::Null),
"parent_checkpoint_id": args.get("parent_checkpoint_id").cloned().unwrap_or(Value::Null),
"principal_ref": args.get("principal_ref").cloned().unwrap_or(Value::Null),
"workspace_id": args.get("workspace_id").cloned().unwrap_or(Value::Null),
"session_id": args.get("session_id").cloned().unwrap_or(Value::Null),
"completed_steps": args.get("completed_steps").cloned().unwrap_or_else(|| json!([])),
"pending_operation": args.get("pending_operation").cloned().unwrap_or(Value::Null),
"deadline": args.get("deadline").cloned().unwrap_or(Value::Null),
"committed_at": args.get("committed_at").cloned().unwrap_or_else(|| json!(committed)),
// Effect watermark — absent/null means no ledger yet (write auto-resume closed).
"effect_ledger_watermark": args.get("effect_ledger_watermark").cloned().unwrap_or(Value::Null),
"event_seq": args.get("event_seq").cloned().unwrap_or(Value::Null),
"manifest_digest": args.get("manifest_digest").cloned().unwrap_or(Value::Null),
});
if let Some(obj) = doc.as_object_mut() {
// Preserve legacy author fields for dual-read.
for key in [
"goal", "task", "status", "workbook", "events", "route", "result", "round", "meta",
"id",
] {
if let Some(v) = args.get(key) {
if !v.is_null() {
obj.insert(key.to_string(), v.clone());
}
}
}
if !obj.contains_key("id") {
obj.insert("id".into(), json!(id));
}
if !obj.contains_key("updated_at") {
obj.insert("updated_at".into(), json!(committed.clone()));
}
if !obj.contains_key("round") {
obj.insert("round".into(), json!(opt_i64(args, "round", 0)));
}
if !obj.contains_key("status") {
obj.insert("status".into(), json!("running"));
}
}
doc
}
fn build_legacy_doc(args: &Value, id: &str) -> Value {
let mut doc = json!({
"id": id,
"updated_at": now_rfc3339(),
});
if let Some(obj) = doc.as_object_mut() {
for key in [
"goal", "task", "status", "workbook", "events", "route", "result", "round", "meta",
] {
if let Some(v) = args.get(key) {
if !v.is_null() {
obj.insert(key.to_string(), v.clone());
}
}
}
if !obj.contains_key("round") {
obj.insert("round".into(), json!(opt_i64(args, "round", 0)));
}
if !obj.contains_key("status") {
obj.insert("status".into(), json!("running"));
}
}
doc
}
pub fn resume_save(args: &Value) -> Result<Value, String> {
let id = arg_text(args, "id")?;
let root = resume_root(args)?;
ensure_dir(&root)?;
let path = checkpoint_path(&root, id);
let v2 = wants_checkpoint_v2(args);
let doc = if v2 {
build_checkpoint_v2(args, id)
} else {
build_legacy_doc(args, id)
};
atomic_write_json(&path, &doc)?;
Ok(json!({
"ok": true,
"id": id,
"path": path.to_string_lossy(),
"schema": doc.get("schema").cloned().unwrap_or(Value::Null),
"schema_version": doc.get("schema_version").cloned().unwrap_or(Value::Null),
"updated_at": doc.get("updated_at").or_else(|| doc.get("committed_at")).cloned().unwrap_or(Value::Null),
"atomic": true,
}))
}
fn watermark_allows_write_auto(wm: &Value) -> bool {
match wm {
Value::Null => false,
Value::String(s) => !s.is_empty(),
Value::Object(obj) => {
// Prefer explicit safety bit from effects_watermark; bare digest objects
// without the bit are treated as unsafe (open unknown / pending writes).
match obj.get("write_auto_resume_safe").and_then(|v| v.as_bool()) {
Some(b) => b,
None => obj
.get("watermark")
.and_then(|v| v.as_str())
.map(|s| !s.is_empty())
.unwrap_or(false)
&& obj.get("open_unknown").and_then(|v| v.as_u64()).unwrap_or(1) == 0
&& obj.get("pending_writes").and_then(|v| v.as_u64()).unwrap_or(1) == 0,
}
}
_ => false,
}
}
fn annotate_recovery(mut doc: Value) -> Value {
let is_v2 = doc.get("schema").and_then(|v| v.as_str()) == Some("CheckpointV2")
&& doc.get("schema_version").and_then(|v| v.as_u64()) == Some(2);
let wm = doc
.get("effect_ledger_watermark")
.cloned()
.unwrap_or(Value::Null);
let ledger_safe = watermark_allows_write_auto(&wm);
let (recovery_mode, write_auto_resume) = if is_v2 && ledger_safe {
("checkpoint_v2", true)
} else if is_v2 {
// V2 without a safe ledger watermark: read resume OK; write auto-resume closed.
("checkpoint_v2_read_only", false)
} else {
// Legacy: no effect info → manual_review; never auto redo writes.
("manual_review", false)
};
if let Some(obj) = doc.as_object_mut() {
obj.insert("recovery_mode".into(), json!(recovery_mode));
obj.insert("write_auto_resume".into(), json!(write_auto_resume));
if !is_v2 {
obj.insert("legacy_adaptation".into(), json!("manual_review"));
}
}
doc
}
pub fn resume_load(args: &Value) -> Result<Value, String> {
let id = arg_text(args, "id")?;
let root = resume_root(args)?;
let path = checkpoint_path(&root, id);
if !path.is_file() {
return Ok(json!({
"ok": false,
"found": false,
"id": id,
"path": path.to_string_lossy(),
}));
}
let text = fs::read_to_string(&path).map_err(|e| format!("resume load: {e}"))?;
let parsed: Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(e) => {
return Ok(json!({
"ok": false,
"found": true,
"id": id,
"path": path.to_string_lossy(),
"error": {
"schema": "AgentErrorV1",
"schema_version": 1,
"code": "checkpoint.corrupt",
"category": "unknown_effect",
"stage": "checkpoint",
"message": format!("corrupt checkpoint json: {e}"),
"retryable": false,
"effect_state": "unknown",
"recovery_action": "manual_review",
},
"recovery_mode": "manual_review",
"write_auto_resume": false,
}));
}
};
let mut doc = annotate_recovery(parsed);
if let Some(obj) = doc.as_object_mut() {
obj.insert("ok".into(), json!(true));
obj.insert("found".into(), json!(true));
obj.insert("path".into(), json!(path.to_string_lossy()));
}
Ok(doc)
}
pub fn resume_clear(args: &Value) -> Result<Value, String> {
let id = arg_text(args, "id")?;
let root = resume_root(args)?;
let path = checkpoint_path(&root, id);
let existed = path.is_file();
if existed {
fs::remove_file(&path).map_err(|e| format!("resume clear: {e}"))?;
}
Ok(json!({
"ok": true,
"id": id,
"cleared": existed,
"path": path.to_string_lossy(),
}))
}
pub fn resume_list(args: &Value) -> Result<Value, String> {
let root = resume_root(args)?;
if !root.is_dir() {
return Ok(json!({ "ok": true, "items": [], "resume_dir": root.to_string_lossy() }));
}
let mut items = Vec::new();
let rd = fs::read_dir(&root).map_err(|e| format!("resume list: {e}"))?;
for ent in rd.flatten() {
let p = ent.path();
if p.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
// Skip leftover temp files from crashed writers.
if p.file_name()
.and_then(|s| s.to_str())
.map(|s| s.starts_with('.'))
.unwrap_or(false)
{
continue;
}
let id = p
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let meta = fs::metadata(&p).ok();
items.push(json!({
"id": id,
"path": p.to_string_lossy(),
"len": meta.map(|m| m.len()).unwrap_or(0),
}));
}
items.sort_by(|a, b| {
let ai = a.get("id").and_then(|v| v.as_str()).unwrap_or("");
let bi = b.get("id").and_then(|v| v.as_str()).unwrap_or("");
ai.cmp(bi)
});
Ok(json!({
"ok": true,
"items": items,
"resume_dir": root.to_string_lossy(),
}))
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn scratch(label: &str) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
// Do not mutate process-wide cwd from concurrent Rust unit tests.
let dir = PathBuf::from("target").join(format!("marqdo-resume-{label}-{nanos}"));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn absolute_resume_dir_rejected() {
let err = resume_root(&json!({"resume_dir": "/tmp/evil"})).unwrap_err();
assert!(err.contains("host-relative"));
}
#[test]
fn atomic_v2_roundtrip_and_legacy_manual_review() {
let dir = scratch("v2");
let rel = dir.join("ckpts").to_string_lossy().to_string();
let saved = resume_save(&json!({
"id": "run1",
"schema": "CheckpointV2",
"schema_version": 2,
"goal": "ping",
"status": "running",
"round": 1,
"resume_dir": rel,
"attempt_id": "a1",
}))
.unwrap();
assert_eq!(saved["ok"], true);
assert_eq!(saved["atomic"], true);
assert_eq!(saved["schema"], "CheckpointV2");
let loaded = resume_load(&json!({"id": "run1", "resume_dir": rel})).unwrap();
assert_eq!(loaded["found"], true);
assert_eq!(loaded["schema"], "CheckpointV2");
assert_eq!(loaded["recovery_mode"], "checkpoint_v2_read_only");
assert_eq!(loaded["write_auto_resume"], false);
// Legacy document without schema.
let _ = resume_save(&json!({
"id": "legacy1",
"goal": "pong",
"status": "interrupted",
"round": 2,
"resume_dir": rel,
}))
.unwrap();
let legacy = resume_load(&json!({"id": "legacy1", "resume_dir": rel})).unwrap();
assert_eq!(legacy["recovery_mode"], "manual_review");
assert_eq!(legacy["write_auto_resume"], false);
assert_eq!(legacy["legacy_adaptation"], "manual_review");
// V2 + safe watermark → write_auto_resume opens.
let _ = resume_save(&json!({
"id": "run_safe",
"schema": "CheckpointV2",
"schema_version": 2,
"status": "running",
"round": 3,
"resume_dir": rel,
"attempt_id": "a2",
"effect_ledger_watermark": {
"schema": "EffectLedgerWatermarkV1",
"watermark": "sha256-lite:abc",
"write_auto_resume_safe": true,
"open_unknown": 0,
"pending_writes": 0
}
}))
.unwrap();
let safe = resume_load(&json!({"id": "run_safe", "resume_dir": rel})).unwrap();
assert_eq!(safe["recovery_mode"], "checkpoint_v2");
assert_eq!(safe["write_auto_resume"], true);
// Unsafe watermark (open unknown) keeps write auto-resume closed.
let _ = resume_save(&json!({
"id": "run_unsafe",
"schema": "CheckpointV2",
"schema_version": 2,
"status": "running",
"round": 4,
"resume_dir": rel,
"attempt_id": "a3",
"effect_ledger_watermark": {
"watermark": "sha256-lite:def",
"write_auto_resume_safe": false,
"open_unknown": 1
}
}))
.unwrap();
let unsafe_ck = resume_load(&json!({"id": "run_unsafe", "resume_dir": rel})).unwrap();
assert_eq!(unsafe_ck["recovery_mode"], "checkpoint_v2_read_only");
assert_eq!(unsafe_ck["write_auto_resume"], false);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn corrupt_checkpoint_reports_error() {
let dir = scratch("corrupt");
let ckpts = dir.join("ckpts");
fs::create_dir_all(&ckpts).unwrap();
fs::write(ckpts.join("bad.json"), "{not-json").unwrap();
let loaded = resume_load(&json!({"id": "bad", "resume_dir": ckpts.to_string_lossy()})).unwrap();
assert_eq!(loaded["found"], true);
assert_eq!(loaded["ok"], false);
assert_eq!(loaded["error"]["code"], "checkpoint.corrupt");
assert_eq!(loaded["recovery_mode"], "manual_review");
let _ = fs::remove_dir_all(&dir);
}
}
-719
View File
@@ -1,719 +0,0 @@
//! Adaptive Routing / Policy Compilation (Phase 4).
//! Router is abstract: marqdo | small-llm | llm | auto.
//! `jev` is accepted as an alias of `small-llm` (compat); not a first-class backend.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use crate::kb::{goal_sig_hex, goal_slug_str, normalize_goal};
use crate::memory::{self};
const DEFAULT_MEMORY_DIR: &str = ".marqdo/agent-memory";
const DEFAULT_KB_DIR: &str = ".marqdo/agent-kb";
const POLICY_NAME: &str = "router.mq.md";
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(|v| v.as_str())
.ok_or_else(|| format!("missing text `{key}`"))
}
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty())
}
fn opt_i64(args: &Value, key: &str, default: i64) -> i64 {
match args.get(key) {
None | Some(Value::Null) => default,
Some(Value::Number(n)) => n.as_i64().unwrap_or(default),
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn opt_f64(args: &Value, key: &str, default: f64) -> f64 {
match args.get(key) {
None | Some(Value::Null) => default,
Some(Value::Number(n)) => n.as_f64().unwrap_or(default),
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn opt_bool(args: &Value, key: &str, default: bool) -> bool {
match args.get(key) {
None | Some(Value::Null) => default,
Some(Value::Bool(b)) => *b,
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
_ => default,
}
}
fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn yaml_escape(s: &str) -> String {
if s.is_empty()
|| s.contains(':')
|| s.contains('#')
|| s.contains('|')
|| s.contains('"')
|| s.contains('\n')
{
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
} else {
s.to_string()
}
}
fn resolve_path(rel: &str) -> PathBuf {
let p = PathBuf::from(rel);
if p.is_absolute() {
return p;
}
if p.exists() {
return p;
}
let base = (|| {
let q = crate::host_query_json("cwd")?;
q.as_str()
.map(PathBuf::from)
.ok_or_else(|| "cwd not text".to_string())
})()
.or_else(|_| std::env::current_dir().map_err(|e| e.to_string()))
.unwrap_or_else(|_| PathBuf::from("."));
base.join(p)
}
fn memory_root(args: &Value) -> PathBuf {
let rel = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR);
resolve_path(rel)
}
fn policy_path(root: &Path) -> PathBuf {
root.join("policies").join(POLICY_NAME)
}
#[derive(Clone, Debug)]
struct PolicyRule {
task_hash: String,
slug: String,
skill: String,
task: String,
count: i64,
confidence: f64,
}
fn parse_policy(src: &str) -> Vec<PolicyRule> {
let mut rules = Vec::new();
let mut in_table = false;
let mut header_ok = false;
for line in src.lines() {
let t = line.trim();
if t.starts_with("|") && t.contains("task_hash") {
in_table = true;
header_ok = true;
continue;
}
if in_table && t.starts_with("|") && t.contains("---") {
continue;
}
if in_table && t.starts_with("|") {
let cols: Vec<&str> = t
.trim_matches('|')
.split('|')
.map(|c| c.trim().trim_matches('"'))
.collect();
if cols.len() >= 5 {
let count = cols[4].parse().unwrap_or(1);
let confidence = if cols.len() >= 6 {
cols[5].parse().unwrap_or(0.9)
} else {
0.9
};
let task = if cols.len() >= 7 {
cols[6].to_string()
} else {
String::new()
};
rules.push(PolicyRule {
task_hash: cols[0].to_string(),
slug: cols[1].to_string(),
skill: cols[2].to_string(),
count,
confidence,
task,
});
}
continue;
}
if in_table && header_ok && !t.starts_with('|') && !t.is_empty() {
break;
}
}
rules
}
fn write_policy(root: &Path, rules: &[PolicyRule]) -> Result<PathBuf, String> {
fs::create_dir_all(root.join("policies")).map_err(|e| format!("mkdir policies: {e}"))?;
let path = policy_path(root);
let ts = now_rfc3339();
let mut body = format!(
"---\ntype: policy\nstatus: compiled\nbackend: marqdo\ngenerated_at: {ts}\nrules: {}\n---\n\n# Adaptive router (compiled Marqdo policy)\n\nDeterministic task → skill routing. No LLM required.\n\n# Rules\n\n| task_hash | slug | skill | resource | count | confidence | task |\n|-----------|------|-------|----------|------:|-----------:|------|\n",
rules.len()
);
for r in rules {
body.push_str(&format!(
"| {} | {} | {} | {} | {} | {:.2} | {} |\n",
r.task_hash,
yaml_escape(&r.slug),
yaml_escape(&r.skill),
yaml_escape(&r.skill), // resource often == skill path for OKF
r.count,
r.confidence,
yaml_escape(&r.task),
));
}
body.push_str("\n# Fallback\n\nllm\n");
fs::write(&path, body).map_err(|e| format!("write policy: {e}"))?;
Ok(path)
}
fn load_rules(root: &Path) -> Vec<PolicyRule> {
let path = policy_path(root);
let Ok(src) = fs::read_to_string(&path) else {
return Vec::new();
};
parse_policy(&src)
}
fn match_policy(rules: &[PolicyRule], task: &str, threshold: f64) -> Option<PolicyRule> {
let th = goal_sig_hex(&normalize_goal(task));
if let Some(r) = rules.iter().find(|r| r.task_hash == th) {
return Some(r.clone());
}
// Near-match on stored task text / slug.
let mut best: Option<(f64, PolicyRule)> = None;
for r in rules {
let score = memory::task_near_score(task, &r.task);
if score >= threshold {
if best.as_ref().map(|(s, _)| score > *s).unwrap_or(true) {
best = Some((score, r.clone()));
}
}
let slug_score = memory::task_near_score(task, &r.slug);
if slug_score >= threshold {
if best.as_ref().map(|(s, _)| slug_score > *s).unwrap_or(true) {
let mut rr = r.clone();
rr.confidence = slug_score;
best = Some((slug_score, rr));
}
}
}
best.map(|(s, mut r)| {
r.confidence = s;
r
})
}
fn build_route_prompt(task: &str, candidates: &[Value]) -> String {
let mut s = String::from(
"You are a Marqdo Agent router. Pick the best skill slug for the task, or say EXPLORE.\n\nReply with exactly one line:\nSKILL:<slug>\nor\nEXPLORE\n\nTask:\n",
);
s.push_str(task);
s.push_str("\n\nCandidates:\n");
for (i, c) in candidates.iter().enumerate() {
let slug = c
.get("slug")
.or_else(|| c.get("title"))
.and_then(|v| v.as_str())
.unwrap_or("?");
let title = c
.get("title")
.or_else(|| c.get("goal"))
.and_then(|v| v.as_str())
.unwrap_or("");
s.push_str(&format!("{}. {slug} — {title}\n", i + 1));
}
s
}
fn candidate_list(args: &Value) -> Result<Vec<Value>, String> {
if let Some(Value::Array(items)) = args.get("candidates") {
return Ok(items.clone());
}
let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR);
let listed = crate::kb::kb_list_tasks(&json!({ "kb_dir": kb }))?;
let tasks = listed
.get("tasks")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if !tasks.is_empty() {
return Ok(tasks);
}
let goal = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let near = crate::kb::kb_near_match(&json!({
"kb_dir": kb,
"goal": goal,
}))?;
Ok(near
.get("candidates")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default())
}
fn enrich_with_kb(rule: &PolicyRule, kb: &str, task: &str) -> Result<Value, String> {
let hit = crate::kb::kb_lookup(&json!({
"kb_dir": kb,
"goal": task,
"slug": rule.slug,
"near_match": true,
"near_threshold": 0.5,
}))
.unwrap_or(Value::Null);
let resource = hit
.get("resource")
.cloned()
.unwrap_or_else(|| Value::String(rule.skill.clone()));
let skill = hit
.get("skill")
.cloned()
.unwrap_or_else(|| Value::String(rule.skill.clone()));
let llm_free = hit
.get("llm_free")
.and_then(|v| v.as_bool())
.unwrap_or(true);
Ok(json!({
"backend": "marqdo",
"mode": "policy",
"matched": true,
"needs_llm": false,
"slug": rule.slug,
"skill": skill,
"resource": resource,
"task_hash": rule.task_hash,
"confidence": rule.confidence,
"llm_free": llm_free,
"count": rule.count,
}))
}
fn route_marqdo(args: &Value) -> Result<Value, String> {
let root = memory_root(args);
let _ = memory::memory_ensure(&json!({
"memory_dir": opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR),
}));
let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let threshold = opt_f64(args, "threshold", 0.78);
let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR);
let rules = load_rules(&root);
if let Some(rule) = match_policy(&rules, task, threshold) {
if rule.confidence >= threshold {
return enrich_with_kb(&rule, kb, task);
}
}
Ok(json!({
"backend": "marqdo",
"mode": "miss",
"matched": false,
"needs_llm": false,
"confidence": 0.0,
}))
}
fn route_resolve_fallback(args: &Value) -> Result<Value, String> {
let resolved = memory::resolve_task(args)?;
let conf = resolved
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let llm_free = resolved
.get("llm_free")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if conf >= opt_f64(args, "threshold", 0.78) || llm_free {
return Ok(json!({
"backend": "kb",
"mode": resolved.get("mode").cloned().unwrap_or(Value::String("near".into())),
"matched": true,
"needs_llm": false,
"slug": resolved.get("slug").cloned().unwrap_or(Value::Null),
"skill": resolved.get("skill").cloned().unwrap_or(Value::Null),
"resource": resolved.get("resource").cloned().unwrap_or(Value::Null),
"confidence": conf,
"llm_free": llm_free,
}));
}
Ok(json!({
"backend": "kb",
"mode": "miss",
"matched": false,
"needs_llm": false,
"confidence": conf,
"resolve": resolved,
}))
}
fn route_model_request(args: &Value, level: &str) -> Result<Value, String> {
let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let cands = candidate_list(args)?;
let prompt = build_route_prompt(task, &cands);
Ok(json!({
"backend": level,
"mode": "needs_llm",
"matched": false,
"needs_llm": true,
"level": level,
"prompt": prompt,
"candidates": cands,
"confidence": 0.0,
}))
}
/// Cascade Adaptive Router (Phase 4).
///
/// `backend`: `auto` | `marqdo` | `small-llm` | `llm` (`jev` → alias of `small-llm`).
///
/// `auto` order: marqdo policy → kb resolve → small-llm request.
pub fn route(args: &Value) -> Result<Value, String> {
let backend = opt_text(args, "backend").unwrap_or("auto");
let threshold = opt_f64(args, "threshold", 0.78);
match backend {
"marqdo" => {
let hit = route_marqdo(args)?;
if hit.get("matched").and_then(|v| v.as_bool()) == Some(true) {
return Ok(hit);
}
route_resolve_fallback(args)
}
"small-llm" | "small_llm" | "small" | "jev" => route_model_request(args, "small-llm"),
"llm" | "large" | "large-llm" => route_model_request(args, "llm"),
"auto" | _ => {
let mut trace: Vec<Value> = Vec::new();
let m = route_marqdo(args)?;
trace.push(json!({"try": "marqdo", "matched": m.get("matched")}));
if m.get("matched").and_then(|v| v.as_bool()) == Some(true)
&& m.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0) >= threshold
{
let mut out = m;
if let Some(obj) = out.as_object_mut() {
obj.insert("trace".into(), Value::Array(trace));
obj.insert("backend".into(), Value::String("auto/marqdo".into()));
}
return Ok(out);
}
let kb = route_resolve_fallback(args)?;
trace.push(json!({"try": "kb", "matched": kb.get("matched")}));
if kb.get("matched").and_then(|v| v.as_bool()) == Some(true) {
let mut out = kb;
if let Some(obj) = out.as_object_mut() {
obj.insert("trace".into(), Value::Array(trace));
obj.insert("backend".into(), Value::String("auto/kb".into()));
}
return Ok(out);
}
// Prefer small-llm request in auto when nothing matched (caller may use large).
let mut req = route_model_request(args, "small-llm")?;
if let Some(obj) = req.as_object_mut() {
obj.insert("trace".into(), Value::Array(trace));
obj.insert("backend".into(), Value::String("auto/small-llm".into()));
}
Ok(req)
}
}
}
/// Apply a router model reply (`SKILL:<slug>` / `EXPLORE`) to a concrete skill hit.
pub fn route_apply(args: &Value) -> Result<Value, String> {
let reply = arg_text(args, "reply")?;
let kb = opt_text(args, "kb_dir").unwrap_or(DEFAULT_KB_DIR);
let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let line = reply
.lines()
.map(|l| l.trim())
.find(|l| !l.is_empty())
.unwrap_or("");
let upper = line.to_ascii_uppercase();
if upper.starts_with("EXPLORE") || upper == "LLM" || upper == "NEW" {
return Ok(json!({
"matched": false,
"mode": "explore",
"decision": "EXPLORE",
"needs_llm": false,
}));
}
let slug = if let Some(rest) = line.strip_prefix("SKILL:") {
rest.trim()
} else if let Some(rest) = line.strip_prefix("skill:") {
rest.trim()
} else if let Some(rest) = line.strip_prefix("调用:") {
rest.trim()
} else {
line.trim()
};
if slug.is_empty() {
return Ok(json!({
"matched": false,
"mode": "explore",
"decision": "EXPLORE",
"reason": "empty_slug",
}));
}
let hit = crate::kb::kb_lookup(&json!({
"kb_dir": kb,
"goal": task,
"slug": slug,
"near_match": true,
"near_threshold": 0.5,
}))?;
if hit.is_null() {
return Ok(json!({
"matched": false,
"mode": "miss",
"decision": "SKILL",
"slug": slug,
"reason": "slug_not_in_kb",
}));
}
Ok(json!({
"matched": true,
"mode": "routed",
"decision": "SKILL",
"backend": opt_text(args, "backend").unwrap_or("llm"),
"slug": slug,
"skill": hit.get("skill").cloned().unwrap_or(Value::Null),
"resource": hit.get("resource").cloned().unwrap_or(Value::Null),
"llm_free": hit.get("llm_free").cloned().unwrap_or(Value::Bool(false)),
"confidence": 0.85,
"needs_llm": false,
}))
}
/// Compile policy from successful episode skill selections (Policy Compilation).
pub fn compile_policy(args: &Value) -> Result<Value, String> {
let root = memory_root(args);
let mem_arg = opt_text(args, "memory_dir").unwrap_or(DEFAULT_MEMORY_DIR);
let _ = memory::memory_ensure(&json!({ "memory_dir": mem_arg }));
let min_evidence = opt_i64(args, "min_evidence", opt_i64(args, "improve_every", 3));
let listed = memory::list_episodes(&json!({
"memory_dir": mem_arg,
"status": "success",
"limit": 500,
}))?;
let eps = listed
.get("episodes")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
// task_hash → (slug → count, sample task, skill path)
let mut by_hash: HashMap<String, HashMap<String, (i64, String, String)>> = HashMap::new();
for e in &eps {
let id = e.get("id").and_then(|v| v.as_str()).unwrap_or("");
if id.is_empty() {
continue;
}
let full = memory::get_episode(&json!({
"memory_dir": mem_arg,
"id": id,
}))?;
if full.is_null() {
continue;
}
let src = full.get("source").and_then(|v| v.as_str()).unwrap_or("");
let skill = extract_fm(src, "skill").unwrap_or_default();
if skill.is_empty() || skill == "none" || skill == "null" {
continue;
}
let task_hash = extract_fm(src, "task_hash")
.or_else(|| e.get("task_hash").and_then(|v| v.as_str()).map(|s| s.to_string()))
.unwrap_or_default();
if task_hash.is_empty() {
continue;
}
let task = full
.get("task")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let slug = extract_fm(src, "slug")
.filter(|s| !s.is_empty())
.unwrap_or_else(|| goal_slug_str(&task));
// Prefer skill path as key when it looks like a path; else slug.
let key = if skill.contains('/') || skill.ends_with(".md") {
skill.clone()
} else {
slug.clone()
};
let entry = by_hash.entry(task_hash).or_default();
let cell = entry.entry(key).or_insert((0, task, skill));
cell.0 += 1;
}
let mut rules: Vec<PolicyRule> = Vec::new();
for (task_hash, skills) in by_hash {
let Some((skill_key, (count, task, skill_path))) =
skills.into_iter().max_by_key(|(_, (c, _, _))| *c)
else {
continue;
};
if count < min_evidence {
continue;
}
let slug = if skill_key.contains('/') {
Path::new(&skill_key)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(&skill_key)
.trim_end_matches(".mq")
.to_string()
} else {
skill_key
};
let confidence = (count as f64 / (count as f64 + 1.0)).min(0.99);
rules.push(PolicyRule {
task_hash,
slug,
skill: skill_path,
task,
count,
confidence,
});
}
rules.sort_by(|a, b| b.count.cmp(&a.count));
if rules.is_empty() && !opt_bool(args, "force", false) {
return Ok(json!({
"ok": false,
"compiled": false,
"reason": "insufficient_stable_mappings",
"min_evidence": min_evidence,
}));
}
let path = write_policy(&root, &rules)?;
Ok(json!({
"ok": true,
"compiled": true,
"path": path.to_string_lossy(),
"rules": rules.len() as i64,
"min_evidence": min_evidence,
}))
}
fn extract_fm(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(rest) = t.strip_prefix(&prefix) {
return Some(rest.trim().trim_matches('"').to_string());
}
}
None
}
/// Learn gate for policy: compile when enough skill-tagged episodes exist.
pub fn maybe_compile_policy(args: &Value) -> Result<Value, String> {
let compiled = compile_policy(args)?;
Ok(json!({
"policy_learned": compiled.get("ok").and_then(|v| v.as_bool()).unwrap_or(false),
"compile": compiled,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn compile_and_route_marqdo() {
let dir = std::env::temp_dir().join(format!("marqdo-route-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let mem = dir.join("agent-memory");
let kb = dir.join("agent-kb");
let mem_s = mem.to_string_lossy().into_owned();
let kb_s = kb.to_string_lossy().into_owned();
let task = "Reply with exactly the word pong and nothing else.";
// Seed a solidified skill via memory compile path.
for _ in 0..3 {
memory::record_episode(&json!({
"memory_dir": mem_s,
"task": task,
"status": "ok",
"mode": "explore",
"result": "pong",
"skill": "concepts/skills/reply-with-exactly-the-word-pong-and-nothing-els.md",
"llm_calls": 1,
}))
.unwrap();
}
let learned = memory::maybe_learn(&json!({
"memory_dir": mem_s,
"kb_dir": kb_s,
"task": task,
"improve_every": 3,
"promote": true,
}))
.unwrap();
assert_eq!(learned.get("learned").and_then(|v| v.as_bool()), Some(true));
// Tag episodes with skill path for policy mining (re-record with skill).
for _ in 0..3 {
memory::record_episode(&json!({
"memory_dir": mem_s,
"task": task,
"status": "ok",
"mode": "compiled",
"result": "pong",
"skill": "concepts/skills/reply-with-exactly-the-word-pong-and-nothing-els.md",
"llm_calls": 0,
}))
.unwrap();
}
let pol = compile_policy(&json!({
"memory_dir": mem_s,
"min_evidence": 3,
}))
.unwrap();
assert_eq!(pol.get("ok").and_then(|v| v.as_bool()), Some(true), "{pol}");
let routed = route(&json!({
"memory_dir": mem_s,
"kb_dir": kb_s,
"task": task,
"backend": "auto",
}))
.unwrap();
assert_eq!(
routed.get("matched").and_then(|v| v.as_bool()),
Some(true),
"{routed}"
);
assert_eq!(
routed.get("needs_llm").and_then(|v| v.as_bool()),
Some(false),
"{routed}"
);
let _ = fs::remove_dir_all(&dir);
}
}
-53
View File
@@ -1,53 +0,0 @@
//! Forward `sandbox_*` plugin calls to host_query (CoW lives in the host).
use super::{
host_query_json_args, parse_args, set_err, set_out,
};
use std::os::raw::c_char;
fn forward(
query_name: &str,
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
let v = match parse_args(args_json) {
Ok(v) => v,
Err(e) => {
set_err(err_msg, &format!("{query_name}: {e}"));
return 1;
}
};
match host_query_json_args(query_name, &v) {
Ok(j) => {
set_out(out_json, &j.to_string());
0
}
Err(e) => {
set_err(err_msg, &e);
1
}
}
}
macro_rules! sandbox_ffi {
($fn_name:ident, $query:expr) => {
pub unsafe extern "C" fn $fn_name(
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
forward($query, args_json, out_json, err_msg)
}
};
}
sandbox_ffi!(sandbox_open, "sandbox_open");
sandbox_ffi!(sandbox_write, "sandbox_write");
sandbox_ffi!(sandbox_read, "sandbox_read");
sandbox_ffi!(sandbox_remove, "sandbox_remove");
sandbox_ffi!(sandbox_diff, "sandbox_diff");
sandbox_ffi!(sandbox_commit, "sandbox_commit");
sandbox_ffi!(sandbox_discard, "sandbox_discard");
sandbox_ffi!(sandbox_inspect, "sandbox_inspect");
sandbox_ffi!(sandbox_run, "sandbox_run");
-794
View File
@@ -1,794 +0,0 @@
//! ToolSpecV1 registry + call validation (M-A2).
//! Discovery → schema validate → authorize. Execution of Marqdo `##` stays in subtask;
//! this module never evals model-supplied code.
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use serde_json::{json, Map, Value};
fn registry() -> &'static Mutex<HashMap<String, Value>> {
static REG: OnceLock<Mutex<HashMap<String, Value>>> = OnceLock::new();
REG.get_or_init(|| Mutex::new(HashMap::new()))
}
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
}
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
opt_text(args, key).ok_or_else(|| format!("missing text `{key}`"))
}
/// Supported JSON Schema subset for tool input (reject unsupported constructs).
fn validate_schema_subset(schema: &Value) -> Result<(), String> {
let obj = schema
.as_object()
.ok_or_else(|| "input_schema must be object".to_string())?;
let ty = obj
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("object");
if ty != "object" {
return Err(format!("unsupported root type={ty}; only object"));
}
if let Some(props) = obj.get("properties") {
let props = props
.as_object()
.ok_or_else(|| "properties must be object".to_string())?;
for (name, prop) in props {
let p = prop
.as_object()
.ok_or_else(|| format!("property {name} must be object"))?;
let pty = p.get("type").and_then(|v| v.as_str()).unwrap_or("string");
match pty {
"string" | "integer" | "number" | "boolean" | "array" | "object" => {}
other => {
return Err(format!(
"unsupported property type {other} for {name}; refuse register"
))
}
}
// Reject constructs we do not implement.
for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] {
if p.contains_key(banned) {
return Err(format!(
"unsupported schema keyword {banned} on {name}; refuse register"
));
}
}
}
}
for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] {
if obj.contains_key(banned) {
return Err(format!(
"unsupported schema keyword {banned}; refuse register"
));
}
}
Ok(())
}
fn normalize_spec(mut spec: Value) -> Result<Value, String> {
let obj = spec
.as_object_mut()
.ok_or_else(|| "spec must be object".to_string())?;
obj.insert("schema".into(), json!("ToolSpecV1"));
obj.entry("schema_version".to_string())
.or_insert(json!(1));
let id = obj
.get("id")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| "ToolSpecV1 requires id".to_string())?
.to_string();
obj.entry("version".to_string()).or_insert(json!("1"));
obj.entry("description".to_string())
.or_insert(json!(""));
let input = obj
.get("input_schema")
.cloned()
.unwrap_or_else(|| json!({"type": "object", "properties": {}, "additionalProperties": false}));
validate_schema_subset(&input)?;
obj.insert("input_schema".into(), input);
obj.entry("effect".to_string()).or_insert(json!("read"));
let effect = obj.get("effect").and_then(|v| v.as_str()).unwrap_or("read");
if !matches!(effect, "read" | "write" | "execute" | "external_write") {
return Err(format!("invalid effect={effect}"));
}
obj.entry("scopes".to_string()).or_insert(json!([]));
obj.entry("timeout_ms".to_string()).or_insert(json!(10_000));
obj.entry("max_result_bytes".to_string())
.or_insert(json!(65_536));
obj.entry("idempotency".to_string())
.or_insert(json!("safe"));
obj.entry("availability".to_string())
.or_insert(json!("ready"));
let _ = id;
Ok(spec)
}
fn validate_args_against_schema(schema: &Value, arguments: &Value) -> Result<(), String> {
let args = arguments
.as_object()
.ok_or_else(|| "arguments must be object".to_string())?;
let sch = schema.as_object().ok_or_else(|| "input_schema invalid".to_string())?;
let props = sch
.get("properties")
.and_then(|v| v.as_object())
.cloned()
.unwrap_or_default();
let additional = sch
.get("additionalProperties")
.and_then(|v| v.as_bool())
.unwrap_or(true);
if !additional {
for key in args.keys() {
if !props.contains_key(key) {
return Err(format!("unknown argument `{key}`"));
}
}
}
if let Some(req) = sch.get("required").and_then(|v| v.as_array()) {
for r in req {
let name = r.as_str().unwrap_or("");
if name.is_empty() {
continue;
}
if !args.contains_key(name) || args.get(name).map(|v| v.is_null()).unwrap_or(true) {
return Err(format!("missing required argument `{name}`"));
}
}
}
for (key, val) in args {
if let Some(prop) = props.get(key) {
if let Some(pty) = prop.get("type").and_then(|v| v.as_str()) {
let ok = match pty {
"string" => val.is_string(),
"integer" => val.as_i64().is_some() || val.as_u64().is_some(),
"number" => val.as_f64().is_some(),
"boolean" => val.is_boolean(),
"array" => val.is_array(),
"object" => val.is_object(),
_ => true,
};
if !ok {
return Err(format!("argument `{key}` type mismatch (want {pty})"));
}
}
if let Some(min) = prop.get("minimum").and_then(|v| v.as_f64()) {
if let Some(n) = val.as_f64() {
if n < min {
return Err(format!("argument `{key}` below minimum {min}"));
}
}
}
if let Some(max) = prop.get("maximum").and_then(|v| v.as_f64()) {
if let Some(n) = val.as_f64() {
if n > max {
return Err(format!("argument `{key}` above maximum {max}"));
}
}
}
}
}
Ok(())
}
fn authorized(allowlist: Option<&Value>, tool_id: &str) -> bool {
match allowlist {
None => true, // registry-only call sites may omit; still need registered spec
Some(tools) => crate::tool_names(tools).iter().any(|n| n == tool_id),
}
}
/// Register one ToolSpecV1 (or list). Host/trusted only — model cannot invent principal/root.
pub fn tools_register(args: &Value) -> Result<Value, String> {
let specs = if let Some(arr) = args.get("specs").and_then(|v| v.as_array()) {
arr.clone()
} else if args.get("spec").is_some() || args.get("id").is_some() {
let raw = args.get("spec").cloned().unwrap_or_else(|| args.clone());
vec![raw]
} else {
return Err("tools.register requires spec or specs[]".into());
};
let mut registered = Vec::new();
let mut guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
for raw in specs {
let spec = normalize_spec(raw)?;
let id = spec
.get("id")
.and_then(|v| v.as_str())
.unwrap()
.to_string();
guard.insert(id.clone(), spec);
registered.push(id);
}
Ok(json!({
"ok": true,
"registered": registered,
"count": registered.len(),
}))
}
pub fn tools_clear(args: &Value) -> Result<Value, String> {
let _ = args;
let mut guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
let n = guard.len();
guard.clear();
Ok(json!({"ok": true, "cleared": n}))
}
pub fn tools_search(args: &Value) -> Result<Value, String> {
let query = opt_text(args, "query").unwrap_or("").to_ascii_lowercase();
let allow = args.get("tools");
let guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
let mut items = Vec::new();
for (id, spec) in guard.iter() {
let avail = spec
.get("availability")
.and_then(|v| v.as_str())
.unwrap_or("ready");
let auth = authorized(allow, id);
if !auth {
// Do not leak unauthorized private connector names in search hits.
continue;
}
if !query.is_empty() {
let desc = spec
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("");
if !id.to_ascii_lowercase().contains(&query)
&& !desc.to_ascii_lowercase().contains(&query)
{
continue;
}
}
items.push(json!({
"id": id,
"version": spec.get("version").cloned().unwrap_or(json!("1")),
"description": spec.get("description").cloned().unwrap_or(json!("")),
"effect": spec.get("effect").cloned().unwrap_or(json!("read")),
"availability": avail,
"authorized": true,
}));
}
items.sort_by(|a, b| {
let ai = a.get("id").and_then(|v| v.as_str()).unwrap_or("");
let bi = b.get("id").and_then(|v| v.as_str()).unwrap_or("");
ai.cmp(bi)
});
Ok(json!({
"ok": true,
"schema": "ToolSearchResultV1",
"schema_version": 1,
"items": items,
"count": items.len(),
}))
}
pub fn tools_describe(args: &Value) -> Result<Value, String> {
let id = arg_text(args, "id")?;
let allow = args.get("tools");
if !authorized(allow, id) {
return Ok(json!({
"ok": false,
"found": false,
"authorized": false,
"error": {
"schema": "AgentErrorV1",
"schema_version": 1,
"code": "tool.forbidden",
"category": "forbidden",
"stage": "tool",
"message": format!("tool `{id}` not in allowlist"),
"retryable": false,
"effect_state": "none",
"recovery_action": "needs_input",
}
}));
}
let guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
match guard.get(id) {
Some(spec) => Ok(json!({
"ok": true,
"found": true,
"authorized": true,
"spec": spec,
})),
None => Ok(json!({
"ok": false,
"found": false,
"authorized": true,
"error": {
"schema": "AgentErrorV1",
"schema_version": 1,
"code": "tool.not_found",
"category": "capability_unavailable",
"stage": "tool",
"message": format!("tool `{id}` not registered"),
"retryable": false,
"effect_state": "none",
"recovery_action": "stop",
}
})),
}
}
/// Validate + authorize a ToolCallV1. Does not execute side effects.
pub fn tools_prepare_call(args: &Value) -> Result<Value, String> {
let tool_id = arg_text(args, "tool_id")
.or_else(|_| arg_text(args, "id"))
.or_else(|_| arg_text(args, "name"))?;
let allow = args.get("tools");
if !authorized(allow, tool_id) {
return Ok(tool_result_err(
"tool.forbidden",
"forbidden",
format!("unauthorized call to `{tool_id}`"),
false,
));
}
let guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
let spec = match guard.get(tool_id) {
Some(s) => s.clone(),
None => {
return Ok(tool_result_err(
"tool.not_found",
"capability_unavailable",
format!("tool `{tool_id}` not registered"),
false,
));
}
};
drop(guard);
let avail = spec
.get("availability")
.and_then(|v| v.as_str())
.unwrap_or("ready");
if avail != "ready" {
return Ok(tool_result_err(
"tool.unavailable",
"capability_unavailable",
format!("tool `{tool_id}` availability={avail}"),
false,
));
}
let arguments = match args.get("arguments") {
None | Some(Value::Null) => json!({}),
Some(v) => v.clone(),
};
let schema = spec
.get("input_schema")
.cloned()
.unwrap_or_else(|| json!({"type":"object"}));
if let Err(e) = validate_args_against_schema(&schema, &arguments) {
return Ok(tool_result_err(
"tool.invalid_arguments",
"invalid_arguments",
e,
true,
));
}
let call_id = opt_text(args, "call_id")
.map(|s| s.to_string())
.unwrap_or_else(|| format!("call_{}", std::process::id()));
let operation_id = opt_text(args, "operation_id")
.map(|s| s.to_string())
.unwrap_or_else(|| format!("op_{tool_id}_{call_id}"));
let version = spec
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("1");
let effect = spec
.get("effect")
.and_then(|v| v.as_str())
.unwrap_or("read");
let digest = args_digest(&arguments);
let logical_run = opt_text(args, "logical_run_id").unwrap_or("-");
let step = opt_text(args, "step_id").unwrap_or("-");
let idempotency_key = opt_text(args, "idempotency_key")
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{logical_run}|{step}|{tool_id}|{digest}"));
let needs_ledger = matches!(effect, "write" | "execute" | "external_write");
let call = json!({
"schema": "ToolCallV1",
"schema_version": 1,
"call_id": call_id,
"tool_id": tool_id,
"tool_version": version,
"arguments": arguments,
"operation_id": operation_id,
"parent_span_id": args.get("parent_span_id").cloned().unwrap_or(Value::Null),
});
Ok(json!({
"ok": true,
"status": "prepared",
"call": call,
"spec": {
"id": tool_id,
"effect": effect,
"timeout_ms": spec.get("timeout_ms").cloned().unwrap_or(json!(10000)),
"max_result_bytes": spec.get("max_result_bytes").cloned().unwrap_or(json!(65536)),
},
"args_digest": digest,
"idempotency_key": idempotency_key,
"needs_ledger": needs_ledger,
"summary": format!("prepared authorized call to `{tool_id}`"),
}))
}
/// Stable digest of tool arguments for effect ledger idempotency (M-A5a).
pub fn tools_args_digest(args: &Value) -> Result<Value, String> {
let arguments = args
.get("arguments")
.cloned()
.or_else(|| args.get("value").cloned())
.unwrap_or_else(|| json!({}));
Ok(json!({
"ok": true,
"args_digest": args_digest(&arguments),
}))
}
fn args_digest(arguments: &Value) -> String {
let text = serde_json::to_string(arguments).unwrap_or_else(|_| "{}".into());
format!("sha256-lite:{:x}", fnv1a64(&text))
}
fn fnv1a64(s: &str) -> u64 {
let mut h: u64 = 0xcbf29ce484222325;
for b in s.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x100000001b3);
}
h
}
/// True when effect_class requires EffectLedger before/after execution.
pub fn tools_needs_ledger(args: &Value) -> Result<Value, String> {
let effect = opt_text(args, "effect")
.or_else(|| opt_text(args, "effect_class"))
.unwrap_or("read");
Ok(json!({
"ok": true,
"needs_ledger": matches!(effect, "write" | "execute" | "external_write"),
"effect": effect,
}))
}
/// Wrap a successful / failed tool execution into ToolResultV1.
pub fn tools_wrap_result(args: &Value) -> Result<Value, String> {
let ok = args.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
let status = opt_text(args, "status").unwrap_or(if ok { "succeeded" } else { "failed" });
let summary = opt_text(args, "summary").unwrap_or("");
let mut out = json!({
"schema": "ToolResultV1",
"schema_version": 1,
"ok": ok,
"status": status,
"summary": summary,
"structured_content": args.get("structured_content").cloned().unwrap_or(Value::Null),
"resources": args.get("resources").cloned().unwrap_or_else(|| json!([])),
"citations": args.get("citations").cloned().unwrap_or_else(|| json!([])),
"error": args.get("error").cloned().unwrap_or(Value::Null),
"usage": args.get("usage").cloned().unwrap_or(Value::Null),
"truncated": args.get("truncated").and_then(|v| v.as_bool()).unwrap_or(false),
"next_cursor": args.get("next_cursor").cloned().unwrap_or(Value::Null),
"effect_receipt_ref": args.get("effect_receipt_ref").cloned().unwrap_or(Value::Null),
});
// Truncate oversized summary into artifact hint (do not dump MB into prompt).
let max_bytes = args
.get("max_result_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(65_536) as usize;
if summary.len() > max_bytes {
if let Some(obj) = out.as_object_mut() {
obj.insert("truncated".into(), json!(true));
obj.insert(
"summary".into(),
json!(format!(
"{}… [truncated; use resource handle]",
&summary[..max_bytes.min(summary.len())]
)),
);
}
}
Ok(out)
}
/// Seed the five engineering tools used by qdagent (aliases remain CALL:tool_*).
pub fn tools_register_eng_defaults(args: &Value) -> Result<Value, String> {
let _ = args;
let specs = eng_default_specs();
tools_register(&json!({"specs": specs}))
}
fn eng_default_specs() -> Vec<Value> {
vec![
json!({
"id": "tool_find",
"version": "1",
"description": "Engineering find via EKC (read-only)",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
"additionalProperties": false
},
"effect": "read",
"scopes": ["knowledge:read"],
"availability": "ready"
}),
json!({
"id": "tool_reuse",
"version": "1",
"description": "Engineering reuse / preflight discovery (read-only)",
"input_schema": {
"type": "object",
"properties": {"task": {"type": "string"}},
"required": ["task"],
"additionalProperties": false
},
"effect": "read",
"scopes": ["knowledge:read"],
"availability": "ready"
}),
json!({
"id": "tool_bind",
"version": "1",
"description": "Bind and execute a verified knowledge artifact",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"policy": {"type": "string"},
"project": {"type": "string"}
},
"required": ["query"],
"additionalProperties": false
},
"effect": "execute",
"scopes": ["knowledge:execute"],
"availability": "ready"
}),
json!({
"id": "tool_verify",
"version": "1",
"description": "Run L3 knowledge verification checks",
"input_schema": {
"type": "object",
"properties": {},
"additionalProperties": false
},
"effect": "read",
"scopes": ["knowledge:verify"],
"availability": "ready"
}),
json!({
"id": "tool_summarize",
"version": "1",
"description": "Summarize a Context Pack / preflight map",
"input_schema": {
"type": "object",
"properties": {"preflight": {"type": "object"}},
"required": ["preflight"],
"additionalProperties": false
},
"effect": "read",
"scopes": ["knowledge:read"],
"availability": "ready"
}),
]
}
fn tool_result_err(code: &str, category: &str, message: String, retryable: bool) -> Value {
let recovery = if category == "invalid_arguments" {
"repair_args"
} else if category == "forbidden" {
"needs_input"
} else {
"stop"
};
json!({
"ok": false,
"status": "failed",
"summary": message,
"schema": "ToolResultV1",
"schema_version": 1,
"structured_content": null,
"resources": [],
"citations": [],
"error": {
"schema": "AgentErrorV1",
"schema_version": 1,
"code": code,
"category": category,
"stage": "tool",
"message": message,
"retryable": retryable,
"retry_after_ms": null,
"effect_state": "none",
"recovery_action": recovery,
},
"usage": null,
"truncated": false,
"next_cursor": null,
"effect_receipt_ref": null,
})
}
/// Seed stub specs from a CALL allowlist (args.tools).
pub fn seed_from_allowlist_args(args: &Value) -> Result<Value, String> {
let tools = args
.get("tools")
.ok_or_else(|| "tools.seed_allowlist requires tools".to_string())?;
seed_from_allowlist(tools)
}
fn seed_from_allowlist(tools: &Value) -> Result<Value, String> {
let names = crate::tool_names(tools);
let mut specs = Vec::new();
for name in names {
// Minimal stub if not already registered — CALL whitelist compatibility.
let already = {
let guard = registry()
.lock()
.map_err(|_| "tools registry lock poisoned".to_string())?;
guard.contains_key(&name)
};
if already {
continue;
}
let mut m = Map::new();
m.insert("id".into(), json!(name));
m.insert("version".into(), json!("1"));
m.insert(
"description".into(),
json!(format!("Allowlist-derived tool `{name}`")),
);
m.insert(
"input_schema".into(),
json!({"type":"object","properties":{},"additionalProperties":true}),
);
m.insert("effect".into(), json!("execute"));
m.insert("scopes".into(), json!(["call:allowlist"]));
m.insert("availability".into(), json!("ready"));
specs.push(Value::Object(m));
}
if specs.is_empty() {
return Ok(json!({"ok": true, "registered": [], "count": 0}));
}
tools_register(&json!({"specs": specs}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn register_search_describe_and_forbid() {
let _ = tools_clear(&json!({}));
let reg = tools_register_eng_defaults(&json!({})).unwrap();
assert_eq!(reg["count"], 5);
let allow = json!(["tool_find", "tool_reuse"]);
let search = tools_search(&json!({"tools": allow, "query": "find"})).unwrap();
assert_eq!(search["count"], 1);
assert_eq!(search["items"][0]["id"], "tool_find");
// Unauthorized tool must not appear.
let search2 = tools_search(&json!({"tools": allow, "query": "bind"})).unwrap();
assert_eq!(search2["count"], 0);
let denied = tools_describe(&json!({"id": "tool_bind", "tools": allow})).unwrap();
assert_eq!(denied["authorized"], false);
assert_eq!(denied["ok"], false);
let ok = tools_describe(&json!({"id": "tool_find", "tools": allow})).unwrap();
assert_eq!(ok["found"], true);
assert_eq!(ok["spec"]["schema"], "ToolSpecV1");
}
#[test]
fn prepare_rejects_bad_args_and_unauthorized() {
let _ = tools_clear(&json!({}));
tools_register_eng_defaults(&json!({})).unwrap();
let allow = json!(["tool_find"]);
let bad = tools_prepare_call(&json!({
"tool_id": "tool_find",
"tools": allow,
"arguments": {}
}))
.unwrap();
assert_eq!(bad["ok"], false);
assert_eq!(bad["error"]["category"], "invalid_arguments");
let unauth = tools_prepare_call(&json!({
"tool_id": "tool_bind",
"tools": allow,
"arguments": {"query": "x"}
}))
.unwrap();
assert_eq!(unauth["ok"], false);
assert_eq!(unauth["error"]["category"], "forbidden");
let good = tools_prepare_call(&json!({
"tool_id": "tool_find",
"tools": allow,
"arguments": {"query": "foo"},
"call_id": "c1"
}))
.unwrap();
assert_eq!(good["ok"], true);
assert_eq!(good["call"]["schema"], "ToolCallV1");
assert_eq!(good["call"]["tool_id"], "tool_find");
assert_eq!(good["needs_ledger"], false);
assert!(good["args_digest"].as_str().unwrap().starts_with("sha256-lite:"));
let allow2 = json!(["tool_bind"]);
let bind = tools_prepare_call(&json!({
"tool_id": "tool_bind",
"tools": allow2,
"arguments": {"query": "x"},
"call_id": "c2",
"logical_run_id": "run1",
"step_id": "s1"
}))
.unwrap();
assert_eq!(bind["ok"], true);
assert_eq!(bind["needs_ledger"], true);
assert_eq!(bind["spec"]["effect"], "execute");
assert!(bind["idempotency_key"]
.as_str()
.unwrap()
.starts_with("run1|s1|tool_bind|"));
}
#[test]
fn needs_ledger_only_for_mutating_effects() {
assert_eq!(
tools_needs_ledger(&json!({"effect": "read"})).unwrap()["needs_ledger"],
false
);
assert_eq!(
tools_needs_ledger(&json!({"effect": "write"})).unwrap()["needs_ledger"],
true
);
assert_eq!(
tools_needs_ledger(&json!({"effect": "execute"})).unwrap()["needs_ledger"],
true
);
}
#[test]
fn refuse_unsupported_schema_keywords() {
let err = tools_register(&json!({
"id": "bad",
"input_schema": {
"type": "object",
"oneOf": [{"type": "object"}]
}
}));
assert!(err.is_err());
}
}
-679
View File
@@ -1,679 +0,0 @@
//! Plugin-only durable step workflow.
//! No interpreter-frame serialization: every model/tool decision is a checkpointed
//! transition. This state machine issues actions but never executes arbitrary code.
use std::fs::{self, OpenOptions};
use std::path::PathBuf;
use serde_json::{json, Value};
use crate::{choice, parallel, resume};
const MAX_STEPS: usize = 128;
struct Guard(PathBuf);
impl Drop for Guard {
fn drop(&mut self) { let _ = fs::remove_file(&self.0); }
}
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
v.get(key).and_then(Value::as_str).filter(|x| !x.is_empty())
.ok_or_else(|| format!("workflow requires text {key}"))
}
fn safe_key(s: &str) -> bool {
!s.is_empty() && s.len() <= 100
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
fn storage(args: &Value) -> Result<PathBuf, String> {
let rel = args.get("resume_dir").and_then(Value::as_str)
.unwrap_or(".marqdo/agent-resume");
let path = PathBuf::from(rel);
if path.is_absolute() || path.components().any(|part|
matches!(part, std::path::Component::ParentDir | std::path::Component::Prefix(_)))
{
return Err("resume_dir must be relative with no parent traversal".into());
}
let base = crate::host_query_json("cwd").ok()
.and_then(|v| v.as_str().map(PathBuf::from))
.unwrap_or(std::env::current_dir().map_err(|e| e.to_string())?);
let dir = base.join(path);
fs::create_dir_all(&dir).map_err(|e| format!("workflow mkdir: {e}"))?;
Ok(dir)
}
fn lock(args: &Value, id: &str) -> Result<Guard, String> {
if !safe_key(id) {
return Err("workflow id must be <=100 ASCII letters, numbers, - or _".into());
}
let path = storage(args)?.join(format!("{id}.flow-lock"));
OpenOptions::new().write(true).create_new(true).open(&path)
.map_err(|e| format!("workflow busy or stale lock; review before recovering: {e}"))?;
Ok(Guard(path))
}
fn checkpoint_args(args: &Value, id: &str) -> Value {
json!({"id": id, "resume_dir": args.get("resume_dir")})
}
fn read(args: &Value, id: &str) -> Result<Value, String> {
resume::resume_load(&checkpoint_args(args,id))
}
fn context(args: &Value) -> Value {
json!({
"source_revision": args.get("source_revision").cloned().unwrap_or(Value::Null),
"session_id": args.get("session_id").cloned().unwrap_or(Value::Null),
"principal_ref": args.get("principal_ref").cloned().unwrap_or(Value::Null)
})
}
fn check_context(args: &Value, ckpt: &Value) -> bool {
ckpt["meta"]["identity"] == context(args)
}
fn validate_steps(args: &Value) -> Result<Value, String> {
let steps = args.get("steps").and_then(Value::as_array)
.ok_or_else(|| "steps must be a list".to_string())?;
if steps.is_empty() || steps.len() > MAX_STEPS {
return Err("steps must contain 1..=128 items".into());
}
let mut seen = std::collections::HashSet::new();
for s in steps {
let id = field(s, "id")?;
if !safe_key(id) || !seen.insert(id) {
return Err("step ids must be unique safe identifiers".into());
}
let kind = field(s, "kind")?;
if !matches!(kind, "model" | "input" | "skill" | "parallel" | "return") {
return Err(format!("unsupported step kind: {kind}"));
}
if matches!(kind, "model" | "input") {
let options = s.get("options").and_then(Value::as_array)
.ok_or_else(|| "choice step requires options list".to_string())?;
let _ = choice::parse_choice(&json!({"reply":"","options":options}))?;
if kind == "input" { let _ = field(s, "question")?; }
if kind == "model" { let _ = field(s, "prompt")?; }
}
if kind == "skill" { let _ = field(s, "skill")?; }
if kind == "parallel" && !s.get("tasks").is_some_and(Value::is_array) {
return Err("parallel step requires tasks array".into());
}
}
// Resolve all branch targets against frozen, forward-only step IDs.
for (i, s) in steps.iter().enumerate() {
let targets = s.get("next").and_then(Value::as_str).into_iter()
.chain(s.get("routes").and_then(Value::as_object)
.into_iter().flat_map(|m| m.values().filter_map(Value::as_str)));
for target in targets {
let position = steps.iter().position(|x|x["id"]==target)
.ok_or_else(|| format!("unknown workflow target: {target}"))?;
if position <= i {
return Err("workflow routes must move forward to avoid loops".into());
}
}
if let Some(routes)=s.get("routes").and_then(Value::as_object) {
if !matches!(s["kind"].as_str(),Some("model"|"input")) {
return Err("only choice steps may declare routes".into());
}
for key in routes.keys() {
if !s["options"].as_array().is_some_and(|opts|
opts.iter().any(|x|x.as_str()==Some(key.as_str()))) {
return Err("route label is not a declared choice".into());
}
}
}
}
Ok(Value::Array(steps.clone()))
}
fn advance_cursor(step:&Value, value:&Value, steps:&[Value], current:usize)->Result<usize,String> {
let target=if let Some(routes)=step.get("routes").and_then(Value::as_object) {
let label=value.as_str().ok_or("routed choice must return a text label")?;
Some(routes.get(label).and_then(Value::as_str)
.ok_or("chosen option is missing a declared route")?)
} else {
step.get("next").and_then(Value::as_str)
};
match target {
None=>Ok(current+1),
Some(name)=> {
let n=steps.iter().position(|s|s["id"]==name)
.ok_or("unknown target after checkpoint recovery")?;
if n<=current {return Err("cyclic route refused".into())}
Ok(n)
}
}
}
fn state(ckpt: &Value) -> Result<(&Value,usize),String> {
let meta = ckpt.get("meta").ok_or("missing workflow metadata")?;
if meta.get("kind").and_then(Value::as_str) != Some("MarqdoAgentFlowV1") {
return Err("checkpoint is not a workflow".into());
}
let index = meta.get("cursor").and_then(Value::as_u64)
.ok_or("missing workflow cursor")? as usize;
Ok((meta,index))
}
fn save(args: &Value, id: &str, meta: &Value, status: &str) -> Result<(),String> {
let result = resume::resume_save(&json!({
"id": id,
"resume_dir": args.get("resume_dir"),
"checkpoint_v2": true,
"status": status,
"meta": meta,
"completed_steps": meta["completed"],
"step_id": meta["steps"].get(meta["cursor"].as_u64().unwrap_or(0) as usize)
.and_then(|x| x.get("id")).cloned().unwrap_or(Value::Null)
}))?;
if result["ok"] != true { return Err("workflow checkpoint write failed".into()); }
Ok(())
}
/// Register a bounded, frozen plan. Re-opening never resets a progressed plan.
pub fn open(args: &Value) -> Result<Value,String> {
let id = field(args,"id")?;
let _guard = lock(args,id)?;
let revision = field(args,"source_revision")?;
if revision.len()>256 { return Err("source_revision too long".into()); }
let steps = validate_steps(args)?;
let existing = read(args,id)?;
let identity = context(args);
if existing["found"] == true {
if existing["ok"] == true
&& existing["meta"]["identity"] == identity
&& existing["meta"]["steps"] == steps
{
return next_doc(&existing,id,true);
}
return Ok(json!({"ok":false,"status":"conflict","error":"workflow.id_or_revision_reused"}));
}
let meta = json!({
"kind":"MarqdoAgentFlowV1",
"identity":identity,
"steps":steps,
"cursor":0,
"completed":[],
});
save(args,id,&meta,"running")?;
Ok(json!({"ok":true,"id":id,"status":"created","cursor":0}))
}
fn next_doc(ckpt: &Value, id: &str, reused: bool) -> Result<Value,String> {
let (meta,index)=state(ckpt)?;
let steps = meta["steps"].as_array().ok_or("invalid steps")?;
if index>=steps.len() {
return Ok(json!({"ok":true,"id":id,"status":"succeeded",
"cursor":index,"completed":meta["completed"],"reused":reused}));
}
let step=&steps[index];
let status=ckpt["status"].as_str().unwrap_or("running");
if status=="blocked" || status=="uncertain" || status=="cancelled" {
return Ok(json!({"ok":false,"id":id,"status":status,
"cursor":index,"step":step,"completed":meta["completed"],
"partial": meta.get("partial").cloned().unwrap_or(Value::Null)}));
}
// Never auto-dispatch effectful or unclassified child documents.
// Those must be executed using the existing EffectLedger policy and an
// independently verified receipt, not an arbitrary model instruction.
if (step["kind"]=="skill" || step["kind"]=="parallel")
&& step["effect_class"]!="read"
{
return Ok(json!({"ok":false,"id":id,"status":"manual_review",
"cursor":index,"step":step,
"reason":"automatic child dispatch requires an explicit read-only effect class"}));
}
let waiting=match step["kind"].as_str().unwrap_or("") {
"model"=>"waiting_model",
"input"=>"waiting_input",
"skill" | "parallel"=>"ready_tool",
"return"=>"ready_return",
_=>"blocked"
};
Ok(json!({"ok":true,"id":id,"status":waiting,
"cursor":index,"step":step,"completed":meta["completed"],"reused":reused}))
}
/// Query the durable next action. This is non-blocking and does not invoke LLM.
pub fn next(args: &Value) -> Result<Value,String> {
let id=field(args,"id")?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"id":id,"status":"not_found_or_mismatched"}));
}
next_doc(&ckpt,id,false)
}
/// Read a workflow summary without advancing it or running any step.
/// The caller-supplied identity must match the checkpoint, exactly like next.
pub fn inspect(args:&Value)->Result<Value,String> {
let id=field(args,"id")?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"id":id,"status":"not_found_or_mismatched"}));
}
let (meta,index)=state(&ckpt)?;
let steps=meta["steps"].as_array().ok_or("invalid steps")?;
let completed=meta["completed"].as_array().ok_or("invalid completed")?;
// `status` is the durable checkpoint status; `action` is what tick would
// observe next (waiting_model, waiting_input, ready_tool, ...).
let action=next_doc(&ckpt,id,false)?.get("status").cloned().unwrap_or(Value::Null);
Ok(json!({
"ok":true,"id":id,
"status":ckpt["status"].as_str().unwrap_or("running"),
"action":action,
"cursor":index,
"total_steps":steps.len(),
"completed_steps":completed.len(),
"completed":meta["completed"],
"step":steps.get(index).cloned().unwrap_or(Value::Null),
"partial":meta.get("partial").cloned().unwrap_or(Value::Null),
"identity":meta["identity"],
"updated_at":ckpt.get("updated_at").cloned().unwrap_or(Value::Null)
}))
}
/// List workflow checkpoints in the (host-relative) resume directory.
/// Non-workflow checkpoints and corrupt entries are omitted. When the caller
/// supplies an attested session or principal, only matching runs are returned.
pub fn list(args:&Value)->Result<Value,String> {
let dir=storage(args)?;
let session=args.get("session_id").and_then(Value::as_str);
let principal=args.get("principal_ref").and_then(Value::as_str);
let mut items=Vec::new();
let rd=fs::read_dir(&dir).map_err(|e|format!("workflow list: {e}"))?;
for ent in rd.flatten() {
let path=ent.path();
if path.extension().and_then(|x|x.to_str())!=Some("json") { continue; }
if path.file_name().and_then(|x|x.to_str())
.map(|x|x.starts_with('.')).unwrap_or(false) { continue; }
let Ok(text)=fs::read_to_string(&path) else { continue };
let Ok(doc)=serde_json::from_str::<Value>(&text) else { continue };
let meta=&doc["meta"];
if meta["kind"].as_str()!=Some("MarqdoAgentFlowV1") { continue; }
if session.is_some() && meta["identity"]["session_id"].as_str()!=session { continue; }
if principal.is_some() && meta["identity"]["principal_ref"].as_str()!=principal { continue; }
let steps=meta["steps"].as_array().map(|x|x.len()).unwrap_or(0);
let completed=meta["completed"].as_array().map(|x|x.len()).unwrap_or(0);
items.push(json!({
"id":doc.get("id").cloned().unwrap_or(Value::Null),
"status":doc.get("status").cloned().unwrap_or(Value::Null),
"cursor":meta.get("cursor").cloned().unwrap_or(Value::Null),
"total_steps":steps,
"completed_steps":completed,
"source_revision":meta["identity"]["source_revision"],
"updated_at":doc.get("updated_at").cloned().unwrap_or(Value::Null)
}));
}
items.sort_by(|a,b| a["id"].as_str().cmp(&b["id"].as_str()));
Ok(json!({"ok":true,"items":items,"resume_dir":dir.to_string_lossy()}))
}
/// Commit a verified result for the exact current step. All mutations are
/// serialized with a lock; a completed step cannot be committed a second time.
pub fn commit(args: &Value) -> Result<Value,String> {
let id=field(args,"id")?;
let _guard=lock(args,id)?;
let step_id=field(args,"step_id")?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"status":"not_found_or_mismatched"}));
}
let (meta,index)=state(&ckpt)?;
let steps=meta["steps"].as_array().ok_or("invalid steps")?;
let response=args.get("response").ok_or("missing response")?;
if index>=steps.len() {
let previous = meta["completed"].as_array().ok_or("invalid completed")?;
if previous.iter().any(|x|x["step_id"]==step_id && x["value"]==*response) {
return Ok(json!({"ok":true,"status":"succeeded","reused":true}));
}
return Ok(json!({"ok":false,"status":"already_finished"}));
}
let step=&steps[index];
if step["id"]!=step_id {
if meta["completed"].as_array().is_some_and(|list|
list.iter().any(|x|x["step_id"]==step_id && x["value"]==*response))
{
return Ok(json!({"ok":true,"status":"already_committed","reused":true}));
}
return Ok(json!({"ok":false,"status":"step_conflict"}));
}
if ckpt["status"]!="running" {
return Ok(json!({"ok":false,"status":"blocked","reason":ckpt["status"]}));
}
let kind=field(step,"kind")?;
let value = match kind {
"model" | "input" => {
let reply = response.as_str().ok_or("model/input response must be text")?;
let valid=choice::parse_choice(&json!({"options":step["options"],"reply":reply}))?;
if valid["ok"]!=true {
return Ok(json!({"ok":false,"status":"invalid_choice",
"error":valid["error"]}));
}
valid["value"].clone()
}
"skill" => {
// A completed wait is not equivalent to a successful child process.
let exit = response.get("value").and_then(|v| v.get("code"))
.or_else(|| response.get("code")).and_then(Value::as_i64);
if response["ok"]==false || exit != Some(0) {
return Ok(json!({"ok":false,
"status":if exit.is_none() {"uncertain"} else {"failed"},
"reason":"child process exit code zero is required before commit"}));
}
response.clone()
}
"parallel" => {
let report=if response["schema"]=="AgentParallelResultV1" {
response.clone()
} else {
parallel::report(&json!({"results":response}))?
};
if report["ok"]!=true {
let status=if report["uncertain"].as_u64().unwrap_or(0)>0 {
"uncertain"
} else {"blocked"};
// Save the full manifest of successful and failed siblings before
// returning. Do not run failed/unknown children automatically.
let mut frozen=meta.clone();
frozen["partial"]=report.clone();
save(args,id,&frozen,status)?;
return Ok(json!({"ok":false,"status":status,
"report":report,"reason":"child results retained for reconciliation"}));
}
report
}
"return" => response.clone(),
_ => return Err("invalid step kind".into()),
};
let target=advance_cursor(step,&value,steps,index)?;
let mut new_meta=meta.clone();
new_meta["cursor"]=json!(target);
new_meta["completed"].as_array_mut().ok_or("completed not array")?
.push(json!({"step_id":step_id,"value":value}));
let terminal=target==steps.len();
save(args,id,&new_meta,if terminal {"succeeded"} else {"running"})?;
Ok(json!({"ok":true,"id":id,
"status":if terminal {"succeeded"} else {"advanced"},
"cursor":target,"value":value,"reused":false}))
}
/// Produce a plan containing only previously failed *read-only* child tasks.
/// "uncertain" children and effectful plans cannot be blindly retried.
pub fn retry_plan(args: &Value) -> Result<Value,String> {
let id=field(args,"id")?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"status":"not_found_or_mismatched"}));
}
let (meta,index)=state(&ckpt)?;
if ckpt["status"]!="blocked" {
return Ok(json!({"ok":false,"status":"not_retryable"}));
}
let step=&meta["steps"][index];
if step["kind"]!="parallel" || step["effect_class"]!="read"
|| meta["partial"]["uncertain"].as_u64().unwrap_or(1)!=0
{
return Ok(json!({"ok":false,"status":"manual_reconciliation_required"}));
}
let Some(items)=meta["partial"]["items"].as_array() else {
return Err("partial report has no items".into());
};
let Some(tasks)=step["tasks"].as_array() else {
return Err("parallel plan has no tasks".into());
};
if items.len()!=tasks.len() {
return Err("partial report task count mismatch".into());
}
let mut failed=Vec::new();
let mut indices=Vec::new();
for (i,item) in items.iter().enumerate() {
if item["index"]!=i {
return Err("out-of-order child result index".into());
}
if item["status"]=="failed" {
failed.push(tasks[i].clone());
indices.push(i);
} else if item["status"]!="succeeded" {
return Ok(json!({"ok":false,"status":"manual_reconciliation_required"}));
}
}
Ok(json!({"ok":true,"status":"retry_read_only",
"id":id,"step_id":step["id"],"tasks":failed,"indices":indices}))
}
/// Merge only the failed child slots with verified new outcomes.
/// Successful results and their order remain untouched.
pub fn retry_commit(args: &Value) -> Result<Value,String> {
let id=field(args,"id")?;
let _guard=lock(args,id)?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"status":"not_found_or_mismatched"}));
}
let (meta,index)=state(&ckpt)?;
if ckpt["status"]!="blocked" {
return Ok(json!({"ok":false,"status":"not_retryable"}));
}
let step=&meta["steps"][index];
if step["kind"]!="parallel" || step["effect_class"]!="read"
|| meta["partial"]["uncertain"].as_u64().unwrap_or(1)!=0
{
return Ok(json!({"ok":false,"status":"manual_reconciliation_required"}));
}
let items=meta["partial"]["items"].as_array()
.ok_or("invalid partial report")?;
let incoming=args.get("results").and_then(Value::as_array)
.ok_or("retry_commit requires results list")?;
let expected=items.iter().filter(|it|it["status"]=="failed").count();
if incoming.len()!=expected {
return Err("retry result count differs from failed child count".into());
}
let mut next=Vec::with_capacity(items.len());
let mut replacement=incoming.iter();
for item in items {
if item["status"]=="succeeded" {
next.push(item["result"].clone());
} else if item["status"]=="failed" {
next.push(replacement.next().ok_or("missing retry result")?.clone());
} else {
return Ok(json!({"ok":false,"status":"manual_reconciliation_required"}));
}
}
let report=parallel::report(&json!({"results":next}))?;
let mut updated=meta.clone();
if report["ok"]==true {
let target=advance_cursor(step,&report,
updated["steps"].as_array().ok_or("steps missing")?,index)?;
updated["cursor"]=json!(target);
updated["partial"]=Value::Null;
updated["completed"].as_array_mut().ok_or("completed not list")?
.push(json!({"step_id":step["id"],"value":report}));
let finished=target==updated["steps"].as_array().ok_or("steps missing")?.len();
save(args,id,&updated,if finished {"succeeded"} else {"running"})?;
Ok(json!({"ok":true,"status":if finished {"succeeded"} else {"advanced"},
"cursor":target,"result":report}))
} else {
updated["partial"]=report.clone();
save(args,id,&updated,if report["uncertain"].as_u64().unwrap_or(0)>0 {
"uncertain" } else {"blocked"})?;
Ok(json!({"ok":false,"status":"blocked","report":report}))
}
}
pub fn cancel(args: &Value) -> Result<Value,String> {
let id=field(args,"id")?;
let _guard=lock(args,id)?;
let ckpt=read(args,id)?;
if ckpt["ok"]!=true || !check_context(args,&ckpt) {
return Ok(json!({"ok":false,"status":"not_found_or_mismatched"}));
}
if ckpt["status"]=="succeeded" {
return Ok(json!({"ok":false,"status":"already_finished"}));
}
let (meta,_)=state(&ckpt)?;
save(args,id,meta,"cancelled")?;
Ok(json!({"ok":true,"id":id,"status":"cancelled"}))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64,Ordering};
static SEQ: AtomicU64=AtomicU64::new(0);
fn fixture()->Value {
let n=SEQ.fetch_add(1,Ordering::Relaxed);
json!({"id":format!("wf-{}-{n}",std::process::id()),
"resume_dir":format!("target/workflow-test-{}-{n}",std::process::id()),
"source_revision":"v1",
"steps":[
{"id":"choose","kind":"model","prompt":"Choose a skill","options":["chat","office"]},
{"id":"answer","kind":"input","question":"OK?","options":["yes","no"]},
{"id":"end","kind":"return"}
]})
}
#[test]
fn nonblocking_model_then_input_then_terminal() {
let a=fixture();
assert_eq!(open(&a).unwrap()["status"],"created");
assert_eq!(next(&a).unwrap()["status"],"waiting_model");
let mut c=a.clone();
c["step_id"]=json!("choose");
c["response"]=json!("office");
assert_eq!(commit(&c).unwrap()["status"],"advanced");
assert_eq!(next(&a).unwrap()["status"],"waiting_input");
assert_eq!(commit(&c).unwrap()["status"],"already_committed");
c["step_id"]=json!("answer");
c["response"]=json!("yes");
assert_eq!(commit(&c).unwrap()["status"],"advanced");
c["step_id"]=json!("end");
c["response"]=json!("ok");
assert_eq!(commit(&c).unwrap()["status"],"succeeded");
assert_eq!(next(&a).unwrap()["status"],"succeeded");
assert_eq!(open(&a).unwrap()["status"],"succeeded");
}
#[test]
fn unknown_and_write_effects_never_auto_dispatch() {
let mut a=fixture();
a["steps"]=json!([{"id":"publish","kind":"skill","skill":"office"}]);
open(&a).unwrap();
assert_eq!(next(&a).unwrap()["status"],"manual_review");
}
#[test]
fn routes_skip_unselected_skill_branches() {
let mut a=fixture();
a["steps"]=json!([
{"id":"decide","kind":"model","prompt":"Pick","options":["chat","office"],
"routes":{"chat":"chat_skill","office":"office_skill"}},
{"id":"chat_skill","kind":"skill","skill":"chat","effect_class":"read","next":"done"},
{"id":"office_skill","kind":"skill","skill":"office","effect_class":"read","next":"done"},
{"id":"done","kind":"return"}
]);
open(&a).unwrap();
let mut c=a.clone();
c["step_id"]=json!("decide");
c["response"]=json!("office");
assert_eq!(commit(&c).unwrap()["cursor"],2);
assert_eq!(next(&a).unwrap()["step"]["id"],"office_skill");
c["step_id"]=json!("office_skill");
c["response"]=json!({"ok":true,"value":{"code":0}});
assert_eq!(commit(&c).unwrap()["cursor"],3);
assert_eq!(next(&a).unwrap()["step"]["id"],"done");
}
#[test]
fn source_change_conflict_and_invalid_model_choice() {
let a=fixture();
open(&a).unwrap();
let mut bad=a.clone();
bad["source_revision"]=json!("v2");
assert_eq!(next(&bad).unwrap()["status"],"not_found_or_mismatched");
assert_eq!(open(&bad).unwrap()["status"],"conflict");
let mut c=a.clone();
c["step_id"]=json!("choose");
c["response"]=json!("chat or office");
assert_eq!(commit(&c).unwrap()["status"],"invalid_choice");
assert_eq!(next(&a).unwrap()["status"],"waiting_model");
}
#[test]
fn partial_children_remain_durable_and_unknown_requires_reconciliation() {
let mut a=fixture();
a["steps"]=json!([{"id":"batch","kind":"parallel","tasks":[{"skill":"a"},{"skill":"b"}]}]);
open(&a).unwrap();
let mut c=a.clone();
c["step_id"]=json!("batch");
c["response"]=json!([
{"ok":true,"value":{"code":0,"value":"useful"}},
{"ok":false,"error":"connection lost"}
]);
assert_eq!(commit(&c).unwrap()["status"],"blocked");
let after=next(&a).unwrap();
assert_eq!(after["status"],"blocked");
assert_eq!(after["partial"]["succeeded"],1);
assert_eq!(after["partial"]["failed"],1);
assert_eq!(commit(&c).unwrap()["status"],"blocked");
}
#[test]
fn retries_only_failed_read_only_children_without_redoing_successes() {
let mut a=fixture();
a["steps"]=json!([{"id":"batch","kind":"parallel","effect_class":"read",
"tasks":[{"path":"a.mq.md"},{"path":"b.mq.md"}]}]);
open(&a).unwrap();
let mut c=a.clone();
c["step_id"]=json!("batch");
c["response"]=json!([
{"ok":true,"value":{"code":0,"value":"keep"}},
{"ok":false,"error":"temporary timeout"}
]);
assert_eq!(commit(&c).unwrap()["status"],"blocked");
let plan=retry_plan(&a).unwrap();
assert_eq!(plan["indices"],json!([1]));
assert_eq!(plan["tasks"].as_array().unwrap().len(),1);
let mut retry=a.clone();
retry["results"]=json!([{"ok":true,"value":{"code":0,"value":"fixed"}}]);
assert_eq!(retry_commit(&retry).unwrap()["status"],"succeeded");
let out=next(&a).unwrap();
assert_eq!(out["completed"][0]["value"]["items"][0]["result"]["value"]["value"],"keep");
assert_eq!(out["completed"][0]["value"]["items"][1]["result"]["value"]["value"],"fixed");
}
#[test]
fn inspect_and_list_are_read_only_and_session_scoped() {
let mut a=fixture();
a["session_id"]=json!("s1");
a["principal_ref"]=json!("u1");
open(&a).unwrap();
let seen=inspect(&a).unwrap();
assert_eq!(seen["status"],"running");
assert_eq!(seen["action"],"waiting_model");
assert_eq!(seen["total_steps"],3);
assert_eq!(seen["completed_steps"],0);
assert_eq!(seen["step"]["id"],"choose");
// Inspection must not consume the current step.
assert_eq!(next(&a).unwrap()["status"],"waiting_model");
let listed=list(&a).unwrap();
assert!(listed["items"].as_array().unwrap()
.iter().any(|x|x["id"]==a["id"]));
let mut other=a.clone();
other["session_id"]=json!("s2");
assert_eq!(inspect(&other).unwrap()["status"],"not_found_or_mismatched");
assert!(list(&other).unwrap()["items"].as_array().unwrap().is_empty());
}
#[test]
fn explicit_cancel_stops_future_commits() {
let a=fixture();
open(&a).unwrap();
assert_eq!(cancel(&a).unwrap()["status"],"cancelled");
let mut c=a.clone();
c["step_id"]=json!("choose");
c["response"]=json!("chat");
assert_eq!(commit(&c).unwrap()["status"],"blocked");
}
}