feat(agent): A4 corpus search and MCP fixture evidence tools
Add local keyword corpus_search and offline MCP fixture adapters as parent CALL tools; keep authority on workbook .mq.md. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ee3116513b
commit
9a8545b725
8 files changed
+519
-6
No files matched your search
@@ -3,6 +3,7 @@
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **`ext/agent` A4(RAG/MCP 证据工具)**: `corpus_search` 本地语料关键词检索;`mcp_list_tools` / `mcp_call` 读 JSON fixture;返回 `authority=workbook`。金样 `agent-tools-rag-a4`。
|
||||
- **`ext/agent` A3(上下文预算)**: `source_brief` / 加深版 `skill_brief`;`build_step_context` 默认截断并提示 `READ:source|skill`;`step` 支持最多 `max_reads` 次加深;父 `READ:skill`。金样 `agent-context-budget-a3`。
|
||||
- **`ext/agent` A2(过程可见)**: `plan` 过程事件默认写入返回 map 的 `events`(SSE 仍仅 `stream=True`);OKF 命中记 `REUSE` decision;view plan 卡渲染过程时间线。对齐 [agent-streaming.md](doc/roadmap/agent-streaming.md)。
|
||||
- **`ext/agent` A1(OKF 复用飞轮)**: `agent_kb_list_tasks` 返回 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`(summary 含 match kind);soft_match 策展提示带 status/llm_free/description;view plan 卡显示 match。金样 `agent-kb-plan-hit`。路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。
|
||||
|
||||
@@ -103,6 +103,10 @@
|
||||
| `workbook_excerpt` | 结构摘录(默认观察同源) |
|
||||
| `lib_catalog` | 枚举 `lib/*.mq.md` 能力摘要 |
|
||||
| `scratch_tool_write` | 写入 `.marqdo/agent-runs/tools/<name>.mq.md` |
|
||||
| `corpus_search` | 本地语料关键词检索(RAG-lite;`ARGS.query` / `root`) |
|
||||
| `mcp_list_tools` / `mcp_call` | MCP 形 JSON fixture 列工具 / 调用(离线证据) |
|
||||
|
||||
以上 **corpus / mcp** 返回一律带 `authority=workbook`:检索与外置工具只是证据,**可跑的 `.mq.md` 工作簿 / OKF 技能仍是权威真相**。
|
||||
|
||||
### 6.2 标准库与造工具
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **进行中 · A0–A3 完成**(A3:step/plan 源码·Skill 预算 + READ 渐进披露) |
|
||||
| 状态 | **A0–A4 完成**(调研驱动优化闭环;A4:corpus/MCP 证据工具,权威仍是 `.mq.md`) |
|
||||
| 日期 | 2026-08-28 |
|
||||
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) |
|
||||
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
|
||||
@@ -28,6 +28,6 @@
|
||||
| **A1** | OKF 复用飞轮(lookup / near / soft_match UX) | **done** — `list_tasks` 含 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`;soft_match 策展行含 meta;view plan 卡显示 match;金样 `agent-kb-plan-hit`(exact hit + near soft-hit) |
|
||||
| **A2** | 过程可见(stream + view 过程卡) | **done** — `plan_append_*` / `plan_finish_stream` 始终写入 `events`(SSE 仍仅 `stream=True`);OKF REUSE 记 `decision`;view `plan-card` 渲染过程时间线(跳过 delta);金样断言 `events-ok`;对齐 [agent-streaming.md](agent-streaming.md) |
|
||||
| **A3** | 上下文预算(源码/Skill 渐进披露) | **done** — `source_brief` / 加深 `skill_brief`;`build_step_context` 默认预算 + `READ:source|skill`;`step max_reads`;父 `READ:skill`;金样 `agent-context-budget-a3` |
|
||||
| **A4** | 可选:RAG/MCP 工具适配器 | 金样调用外置检索,权威仍是 `.mq.md` |
|
||||
| **A4** | 可选:RAG/MCP 工具适配器 | **done** — `corpus_search`(本地语料关键词);`mcp_list_tools` / `mcp_call`(JSON fixture);`authority=workbook`;金样 `agent-tools-rag-a4` |
|
||||
|
||||
细节与行业对照以调研正文为准;本文件只跟踪实现分期。
|
||||
+79
-4
@@ -347,13 +347,47 @@ Drop `<!-- … -->` blocks (including marqdo-out bodies) so parent excerpts stay
|
||||
|
||||
## lib_catalog
|
||||
|
||||
Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports.
|
||||
Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports. Parent also exposes evidence tools `corpus_search` / `mcp_list_tools` / `mcp_call` (not authority).
|
||||
|
||||
*out = > json.parse text={"note":"Direct CALL:lib.<mod>.<fn> + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/<file>.mq.md then PATCH / scratch_tool_write.","files":["fs.mq.md","json.mq.md","subtask.mq.md","sys.mq.md","writeback.mq.md","text.mq.md","time.mq.md","math.mq.md","net.mq.md","table.mq.md","plugin.mq.md","foreign.mq.md"],"callable":[{"name":"lib.fs.read_text","desc":"Read UTF-8 text file"},{"name":"lib.fs.exists","desc":"Path exists?"},{"name":"lib.fs.list_dir","desc":"List directory entries"},{"name":"lib.json.parse","desc":"Parse JSON text"},{"name":"lib.json.stringify","desc":"Serialize JSON"},{"name":"lib.sys.cwd","desc":"Process working directory"}]}*
|
||||
*out = > json.parse text={"note":"Direct CALL:lib.<mod>.<fn> + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/<file>.mq.md then PATCH / scratch_tool_write. Evidence tools: CALL:corpus_search | mcp_list_tools | mcp_call (fixture RAG/MCP) — workbook .mq.md remains authority.","files":["fs.mq.md","json.mq.md","subtask.mq.md","sys.mq.md","writeback.mq.md","text.mq.md","time.mq.md","math.mq.md","net.mq.md","table.mq.md","plugin.mq.md","foreign.mq.md"],"callable":[{"name":"lib.fs.read_text","desc":"Read UTF-8 text file"},{"name":"lib.fs.exists","desc":"Path exists?"},{"name":"lib.fs.list_dir","desc":"List directory entries"},{"name":"lib.json.parse","desc":"Parse JSON text"},{"name":"lib.json.stringify","desc":"Serialize JSON"},{"name":"lib.sys.cwd","desc":"Process working directory"},{"name":"corpus_search","desc":"Local markdown/text keyword search (evidence)"},{"name":"mcp_list_tools","desc":"List tools from MCP JSON fixture"},{"name":"mcp_call","desc":"Call a tool from MCP JSON fixture"}]}*
|
||||
**out**
|
||||
|
||||
---
|
||||
|
||||
## corpus_search
|
||||
+ `query`
|
||||
+ `root`=.marqdo/agent-corpus
|
||||
+ `limit`=6
|
||||
|
||||
Local keyword search over `.md` / `.mq.md` / `.txt` under `root`. Returns ranked excerpts. **Evidence only** — runnable workbook / OKF skill stays authority (`authority=workbook`).
|
||||
|
||||
**> agent_corpus_search query=`query` root=`root` limit=`limit`**
|
||||
|
||||
---
|
||||
|
||||
## mcp_list_tools
|
||||
+ `fixture`
|
||||
|
||||
List tools from an offline MCP-shaped JSON fixture (`tools` array). Evidence only.
|
||||
|
||||
**> agent_mcp_fixture action="list" fixture=`fixture`**
|
||||
|
||||
---
|
||||
|
||||
## mcp_call
|
||||
+ `name`
|
||||
+ `fixture`
|
||||
+ `arguments`=None
|
||||
|
||||
Call a named tool from a MCP-shaped fixture (`results` / `calls` map). Optional `arguments` echoed; fixture results are keyed by name. Evidence only.
|
||||
|
||||
1. `arguments`
|
||||
**> agent_mcp_fixture action="call" fixture=`fixture` name=`name` arguments=`arguments`**
|
||||
2. *
|
||||
**> agent_mcp_fixture action="call" fixture=`fixture` name=`name`**
|
||||
|
||||
---
|
||||
|
||||
## extract_call_args
|
||||
+ `reply`=None
|
||||
|
||||
@@ -693,7 +727,48 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
|
||||
**> json.get value=`errs` key="a"**
|
||||
2. *
|
||||
**> json.get value=`errs` key="b"**
|
||||
5. *
|
||||
5. `name` == corpus_search
|
||||
*args = > extract_call_args reply=`reply`*
|
||||
*q = > json.get value=`args` key="query"*
|
||||
*root = > json.get value=`args` key="root"*
|
||||
*limit = > json.get value=`args` key="limit"*
|
||||
*cerrs = > json.parse text={"q":"corpus_search needs ARGS.query"}*
|
||||
1. not `q`
|
||||
**> json.get value=`cerrs` key="q"**
|
||||
2. `root`
|
||||
1. `limit`
|
||||
**> corpus_search query=`q` root=`root` limit=`limit`**
|
||||
2. *
|
||||
**> corpus_search query=`q` root=`root`**
|
||||
3. `limit`
|
||||
**> corpus_search query=`q` limit=`limit`**
|
||||
4. *
|
||||
**> corpus_search query=`q`**
|
||||
6. `name` == mcp_list_tools
|
||||
*args = > extract_call_args reply=`reply`*
|
||||
*fx = > json.get value=`args` key="fixture"*
|
||||
*merrs = > json.parse text={"f":"mcp_list_tools needs ARGS.fixture"}*
|
||||
1. `fx`
|
||||
**> mcp_list_tools fixture=`fx`**
|
||||
2. *
|
||||
**> json.get value=`merrs` key="f"**
|
||||
7. `name` == mcp_call
|
||||
*args = > extract_call_args reply=`reply`*
|
||||
*fx = > json.get value=`args` key="fixture"*
|
||||
*tn = > json.get value=`args` key="name"*
|
||||
*targ = > json.get value=`args` key="arguments"*
|
||||
*xerrs = > json.parse text={"f":"mcp_call needs ARGS.fixture","n":"mcp_call needs ARGS.name"}*
|
||||
1. `fx`
|
||||
1. `tn`
|
||||
1. `targ`
|
||||
**> mcp_call name=`tn` fixture=`fx` arguments=`targ`**
|
||||
2. *
|
||||
**> mcp_call name=`tn` fixture=`fx`**
|
||||
2. *
|
||||
**> json.get value=`xerrs` key="n"**
|
||||
2. *
|
||||
**> json.get value=`xerrs` key="f"**
|
||||
8. *
|
||||
*dots = > split value=`name` sep=".*"*
|
||||
*head = > at value=`dots` index=0*
|
||||
1. `head` == lib
|
||||
@@ -1113,7 +1188,7 @@ Parent Plan-and-Move prompt. Short protocol only — no long monologues.
|
||||
*compact = > compact_plan_observation observation=`observation`*
|
||||
*obs_s = > json.stringify value=`compact`*
|
||||
*goal_s = > json.stringify value=`goal`*
|
||||
*esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots | skill\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\n4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses import llm:/agent:/json:….\nPATCH must use triple-angle blocks only:\n<<<\nFIND\n<exact old>\n===\nREPLACE\n<new>\n>>>\nDo not use \u0060\u0060\u0060find, \u0060\u0060\u0060replace, or *** Begin Patch ***.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already import llm:/agent:/….\n2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog.\n3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nPATCH must use <<< FIND === REPLACE >>> only (no \u0060\u0060\u0060find / Begin Patch).\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","f":"\n\n--- explore ---\n"}*
|
||||
*esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:corpus_search | mcp_list_tools | mcp_call (ARGS:{…}; evidence only — workbook authority)\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots | skill\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\n4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses import llm:/agent:/json:….\nPATCH must use triple-angle blocks only:\n<<<\nFIND\n<exact old>\n===\nREPLACE\n<new>\n>>>\nDo not use \u0060\u0060\u0060find, \u0060\u0060\u0060replace, or *** Begin Patch ***.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already import llm:/agent:/….\n2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog / corpus_search / mcp_call.\n3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nPATCH must use <<< FIND === REPLACE >>> only (no \u0060\u0060\u0060find / Begin Patch).\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","f":"\n\n--- explore ---\n"}*
|
||||
*a = > json.get value=`esc` key="a"*
|
||||
*b = > json.get value=`esc` key="b"*
|
||||
*c = > json.get value=`esc` key="c"*
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Agent plugin (C ABI v2): layout helpers + session bag + context via host_query + agent-kb.
|
||||
|
||||
mod corpus;
|
||||
mod kb;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -881,6 +882,8 @@ kb_ffi!(agent_kb_canonicalize, kb::kb_canonicalize, "agent_kb_canonicalize");
|
||||
kb_ffi!(agent_kb_lookup, kb::kb_lookup, "agent_kb_lookup");
|
||||
kb_ffi!(agent_kb_near_match, kb::kb_near_match, "agent_kb_near_match");
|
||||
kb_ffi!(agent_kb_list_tasks, kb::kb_list_tasks, "agent_kb_list_tasks");
|
||||
kb_ffi!(agent_corpus_search, corpus::corpus_search, "agent_corpus_search");
|
||||
kb_ffi!(agent_mcp_fixture, corpus::mcp_fixture, "agent_mcp_fixture");
|
||||
kb_ffi!(agent_kb_add_alias, kb::kb_add_alias, "agent_kb_add_alias");
|
||||
kb_ffi!(agent_kb_promote, kb::kb_promote, "agent_kb_promote");
|
||||
kb_ffi!(agent_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit");
|
||||
@@ -978,6 +981,12 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
if register(host, "agent_kb_list_tasks", "kb_dir", agent_kb_list_tasks) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "agent_corpus_search", "query", agent_corpus_search) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "agent_mcp_fixture", "action,fixture", agent_mcp_fixture) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "agent_kb_add_alias", "kb_dir,slug,alias", agent_kb_add_alias) != 0 {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: agent corpus_search + mcp fixture tools (A4 offline)
|
||||
description: Local RAG-lite corpus search and MCP fixture call; authority stays workbook.
|
||||
import agent:ext/ai/agent.mq.md
|
||||
import fs:lib/fs.mq.md
|
||||
import json:lib/json.mq.md
|
||||
import plugin:lib/plugin.mq.md
|
||||
import sys:lib/sys.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*p = > plugin.native_path name="agent"*
|
||||
1. `p`
|
||||
> plugin.load path=`p`
|
||||
2. *
|
||||
> print text=no-agent-plugin
|
||||
> sys.exit code=1
|
||||
|
||||
*paths = > json.parse text={"root":".marqdo/agent-corpus-a4","fx":".marqdo/agent-runs/a4-mcp-fixture.json","a":".marqdo/agent-corpus-a4/refunds.md","b":".marqdo/agent-corpus-a4/shipping.md"}*
|
||||
*root = > json.get value=`paths` key="root"*
|
||||
*fx = > json.get value=`paths` key="fx"*
|
||||
*pa = > json.get value=`paths` key="a"*
|
||||
*pb = > json.get value=`paths` key="b"*
|
||||
|
||||
1. > fs.exists path=`root`
|
||||
> fs.remove path=`root`
|
||||
2. *
|
||||
*_ = 1*
|
||||
> fs.make_dir path=`root`
|
||||
|
||||
*ba = > json.parse text={"t":"# Refund policy\n\nCustomers may request a refund within 30 days of purchase.\n"}*
|
||||
*body_a = > json.get value=`ba` key="t"*
|
||||
> fs.write_text path=`pa` text=`body_a`
|
||||
*bb = > json.parse text={"t":"# Shipping\n\nOrders ship in two business days.\n"}*
|
||||
*body_b = > json.get value=`bb` key="t"*
|
||||
> fs.write_text path=`pb` text=`body_b`
|
||||
|
||||
*fx_body = > json.parse text={"t":"{\"note\":\"Fixture evidence only; workbook remains authority.\",\"tools\":[{\"name\":\"wiki_get\",\"description\":\"Fetch policy wiki page\"}],\"results\":{\"wiki_get\":{\"page\":\"refunds\",\"text\":\"Refunds within 30 days.\"}}}"}*
|
||||
*fx_t = > json.get value=`fx_body` key="t"*
|
||||
> fs.write_text path=`fx` text=`fx_t`
|
||||
|
||||
*hit = > agent.corpus_search query="refund 30 days" root=`root` limit=4*
|
||||
*auth = > json.get value=`hit` key="authority"*
|
||||
1. `auth` == workbook
|
||||
> print text=auth-ok
|
||||
2. *
|
||||
> print text=auth-bad
|
||||
*cnt = > json.get value=`hit` key="count"*
|
||||
1. `cnt` > 0
|
||||
> print text=corpus-hit
|
||||
2. *
|
||||
> print text=corpus-miss
|
||||
*hits = > json.get value=`hit` key="hits"*
|
||||
*hn = > len value=`hits`*
|
||||
1. `hn` > 0
|
||||
*h0 = > at value=`hits` index=0*
|
||||
*p0 = > json.get value=`h0` key="path"*
|
||||
1. `p0` == refunds.md
|
||||
> print text=top-refunds
|
||||
2. *
|
||||
> print text=top-bad
|
||||
2. *
|
||||
> print text=top-empty
|
||||
|
||||
*listed = > agent.mcp_list_tools fixture=`fx`*
|
||||
*tools = > json.get value=`listed` key="tools"*
|
||||
*t0 = > at value=`tools` index=0*
|
||||
*tn = > json.get value=`t0` key="name"*
|
||||
1. `tn` == wiki_get
|
||||
> print text=mcp-list-ok
|
||||
2. *
|
||||
> print text=mcp-list-bad
|
||||
|
||||
*called = > agent.mcp_call name="wiki_get" fixture=`fx`*
|
||||
*ok = > json.get value=`called` key="ok"*
|
||||
1. `ok`
|
||||
> print text=mcp-call-ok
|
||||
2. *
|
||||
> print text=mcp-call-bad
|
||||
*auth2 = > json.get value=`called` key="authority"*
|
||||
1. `auth2` == workbook
|
||||
> print text=mcp-auth-ok
|
||||
2. *
|
||||
> print text=mcp-auth-bad
|
||||
|
||||
*reply = > json.parse text={"t":"CALL:corpus_search\nARGS:{\"query\":\"refund\",\"root\":\".marqdo/agent-corpus-a4\",\"limit\":3}\n"}*
|
||||
*raw = > json.get value=`reply` key="t"*
|
||||
*via = > agent.run_parent_tool name="corpus_search" path="." reply=`raw`*
|
||||
*vc = > json.get value=`via` key="count"*
|
||||
1. `vc` > 0
|
||||
> print text=parent-corpus-ok
|
||||
2. *
|
||||
> print text=parent-corpus-bad
|
||||
@@ -2758,6 +2758,20 @@ fn ext_agent_context_budget_a3() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_agent_tools_rag_a4() {
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "-p", "marqdo_plugin_agent"])
|
||||
.current_dir(env!("CARGO_MANIFEST_DIR"))
|
||||
.status()
|
||||
.expect("build agent plugin");
|
||||
assert!(status.success(), "failed to build marqdo_plugin_agent");
|
||||
assert_out(
|
||||
"tests/ext/agent-tools-rag-a4.mq.md",
|
||||
"auth-ok\ncorpus-hit\ntop-refunds\nmcp-list-ok\nmcp-call-ok\nmcp-auth-ok\nparent-corpus-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_agent_plan_observe() {
|
||||
assert_out(
|
||||
|
||||
Reference in new issue
Block a user