feat(ext/ai): land Agent/LLM optimize waves O1–O5

Wire opt-in sandbox trial into agent, require sandbox proof before OKF
promote, add step_route/EFI/cost surfaces, style lint + quarantine, and
offline policy optimize script—keeping GFM tables over json glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-16 11:47:28 +08:00
1 parent a707758d47
commit 0f72173d08
26 files changed
+1107 -272

No files matched your search

+51 -163
View File
@@ -4,95 +4,40 @@ description: >-
Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose,
importing lib/* or ext/web or ext/quantum or ext/linalg, running marqdo CLI,
building dynamic sites with ext/web, quantum circuits with ext/quantum,
formula-first linear algebra with ext/linalg, or when the user mentions
Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, quantum/量子,
or linalg/线性代数 extension.
importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic
sites with ext/web, quantum circuits with ext/quantum, or when the user
mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or
quantum/量子 extension.
---
# Marqdo development
Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python.
Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-mapping-v0.3.md) (**v0.3 · runtime**), `doc/design/keywords.md`. Legacy v0.2 notes: `doc/design/markdown-mapping.md` (historical). Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets, **ext → R2+GitHub**, **CLI → Ubuntu PPA**): use [marqdo-release](../marqdo-release/SKILL.md) — detect versions, **ask for SemVer + mode (`full` / `cli` / `ext`)**, then follow that playbook. Ext-only releases are allowed. If sudo/GPG/PPA steps need the user, print the exact commands.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text="…"**` / `> 打印 内容=…`.
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is **not** code-shaped (`**说明**`, mid-line `*only*`) is ignored — see [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md). Dead `` `名` `` (never read) is OK and does not become a param.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text="hi"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.
2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**.
3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
12. **Bracket-marked calls:** Function name may be marked with `[函数名]`; bare words before `[` are boolean modifiers (`礼貌 [问候] x` → `礼貌=True`). `]` immediately followed by `(` is **index** `[key](coll)`, not a call. Prefer `[k](c)` over footnote index in new code. See [bracket-call-modifiers.md](../../doc/design/bracket-call-modifiers.md).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## 记不住语法细节?查 MLSP(AI 必读)
**不必背 Marqdo 语法细节**——语法可查、程序可验、修复有界。写码前后走**查询式**工作流:
```bash
printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo mlsp
printf '%s\n' '{"id":2,"method":"locate","params":{"path":"a.mq.md","symbol":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":3,"method":"validate","params":{"path":"a.mq.md"}}' | marqdo mlsp
printf '%s\n' '{"id":4,"method":"schema","params":{"path":"a.mq.md","unit":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_mismatch","doc_anchor":"a.mq.md#L9-L15"}}' | marqdo mlsp
```
| method | 何时用 |
|--------|--------|
| `syntax` | 不确定某个语法怎么写(关键字/别名 → 构造卡片:「返回」「表」「调用」「循环」…) |
| `locate` | 找符号定义位置 + 契约;或反查构造卡片 |
| `validate` | 提交前校验(结构化诊断数组;`ok:false` 就修) |
| `schema` | 查单元契约(形参/返回/字段) |
| `repair_targets` | 拿错误的**有界**修复靶点:只改锚点范围内行,越界必弃权(abstain) |
行分隔 JSON:每行请求 `{"id","method","params"}` → 每行响应 `{"id","ok","result"|"error"}`。
语法唯一事实来源 = `doc/design/core-surface.md`(CI 守卫同步);卡片带 `manual` 指回文档行。
所有错误诊断都是结构化 JSON:`code` / `severity` / `span` / `suggestion` / `doc_anchor` / `doc_quote` / `contract_ref`。
### 渐进式契约(可选标注;schema 就长在文档表里)
契约是**未绑定文档表**(绑定表是数据,永远不是契约)。三种形状、严格位置:
| 形状(须含 `类型` 列) | 允许位置 | 附着 |
|--------------------------|----------|------|
| `参数`/`类型`/`说明` 表 + `返回`/`类型`/`说明` 表 | 函数体首个可执行行之前 | 函数 |
| `字段`/`类型`/`可空`/`说明` 表 | 紧邻 `` `名` = `` 绑定之前 | 集合(变量) |
| `字段`/`类型`/`可空`/`说明` 表 | 对象(`#`)体首成员之前 | 对象类型 |
````text
## 加一
对于输入变量`n`,期望是数字。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 加一结果 |
*n+1*
````
- 类型词汇:`text` / `number` / `bool` / `list` / `map` / `any` / `#` 对象名(拼错 ⇒ `contract.unknown_type` + 最近建议)。
- 契约表**永不执行**、不污染升参推断;无契约文件行为逐字节不变(动态默认,零摩擦)。
- 运行时只在四个边界校验:调用实参 / 字段访问 `[键](集合)` / 表绑定 / 返回。
- `marqdo check [FILE] [--json]` 静态互查:契约行 vs 升参推断形参**双向**漂移(错行=Error;新升参未覆盖=Warning)、未知类型、错位契约;有 Error 非零退出。
- 契约诊断带 `doc_anchor` + `doc_quote`(表原文)——修复只照锚点局部改。
## Markup → meaning (v0.3)
## Markup → meaning (v0.2)
| Marker | Meaning |
|--------|---------|
@@ -103,20 +48,17 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `修饰 [fn] args` | Bracket-marked call; leading words → `名=True` |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
| `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
| `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
| `****` or `**` + spaces + `**` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `` ```lang `` | Foreign code block (via `lib/foreign`); bind with `` `name` = `` then fence |
| `$$` + `% marqdo: var=name` | Block formula bind (TeX comment; prefer over empty RHS) |
| `- [item](coll)` | Foreach (**preferred**, nestable). Sugar: `- 对`coll`的每一项`item`` / `- for each `item` in `coll`` |
| `![marqdo-out](path)` | Image writeback form (validated stem.ext / URL); text writeback stays HTML comment |
| `- [item](coll)` | Foreach (unchanged) |
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment |
@@ -140,19 +82,20 @@ Chinese builtins (same functions, no import):
## Functions, calls, end-body
Prefer **body-inferred params** and **prose-unified** wording (v0.3). `` + `name` `` still works, but teach the inferred form first:
```markdown
# main
**greet who="Marqdo"**
> greet who=Marqdo
## greet
+ `who`
When we meet`who`, we **print text="Hello, `who`!"** and close with*None*.
> print text=Hello, `who`!
*None*
```
- Call: `**fn key="text"**` (bold; quote text literals) or `> fn key=text` (standalone `>`; bare words are text).
- Call: `> name key=value` or `> name value`.
- Nested helpers use deeper `#` (`##`, `###`, …).
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
@@ -160,16 +103,17 @@ When we meet`who`, we **print text="Hello, `who`!"** and close with*None*.
## Statements, returns, branches
```markdown
**x = 1**
**y = x + 2**
*x = 1*
*y = x + 2*
## add_one
+ `n`
For input`n`, do **n = n + 1** and return*n*.
**n + 1**
```
```markdown
**n = 0**
*n = 0*
1. `n` > 0
> print text=positive
@@ -192,16 +136,16 @@ import clock:lib/time.mq.md
# main
**xs = > text.str_split s="a,b,c" sep=","**
*xs = > text.split value="a,b,c" sep=","*
> print text=`xs`
**t = > clock.now_unix**
*t = > clock.now_unix*
```
- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum|linalg` (see `doc/design/ext-cli.md`). **`ext/llm`** — intelligence primitive (`ask` / `stream` / `collect`; `complete` is compat); **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below); **`ext/linalg`** — formula-first linear algebra (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
@@ -216,61 +160,24 @@ Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --releas
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only. **Engineering Knowledge(EKC)**:`marqdo knowledge|find|reuse|…` + `agent.preflight`(REUSE→ADAPT→CREATE)——见 [engineering-knowledge.md](../../doc/design/engineering-knowledge.md)。
4. **Skill Compilation (v2)** — successful runs become `.mq.md` episodes; after enough evidence, `maybe_learn` compiles an executable skill (`llm_free`). Prefer `## run` over bare `## plan` when you want learning.
5. **Adaptive Routing (P4)** — router is abstract (`marqdo` / `small-llm` / `llm` / `auto`); `jev` is a compat alias of `small-llm`. Decision via `router_model` (any llm handle). Policy Compilation writes `policies/router.mq.md`.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## run` / `## route` / `## step` / `## plan` (+ `resolve` / `record_episode` / `maybe_learn` / `compile` / `compile_policy` / `metrics`). Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`). Inspect without LLM: `dump_step_context`. Inside `writeback=` / `写回=` branches use `host_writeback_record` (param name shadows the writeback import).
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) · v2: [doc/next/003.md](../../doc/next/003.md) · P4: [doc/next/004.md](../../doc/next/004.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin: `scripts/build-web-plugin.sh` / `marqdo ext add web`.
Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md).
**Constitution (ADR 0007 — do not degrade):**
**Do not degrade:** Document/Endpoint metadata; facade `web.page|route|serve|render|inspect`; View `|type|slot|value|attrs|style|` only; no `compose_*` / `configure` / author `ensure_plugin`. DB → `ext/data`; auth → `ext/security`; net → `ext/net`.
1. **Document / Endpoint / Resource** — `.mq.md` with `type: web|endpoint` (ZH `类型: 网页|端点`) is the site surface; not a Flask-style class pile.
2. **Code is documentation** — the file is docs + route + handler.
3. **Table = data** — View schema only `|type|slot|value|attrs|style|`. No `compose_*` dialects, no `json.set` glue.
4. **Facade only** — `web.page` · `web.route` · `web.serve` · `web.render` · `web.inspect`. DB → `ext/data`; auth → `ext/security`; ws/http → `ext/net`.
5. **No author `ensure_plugin` / `host_*`**; import web = capability (plugin auto-load).
6. **Declared vs system routes**; `web.inspect` lists both. No silent user routes.
Import **one language** per file:
- EN: `import web:ext/web/web.mq.md` (+ `import data:ext/data/db.mq.md` as needed)
- EN: `import web:ext/web/web.mq.md`
- ZH: `导入 网页:ext/web/网页.mq.md`
```markdown
---
type: web
route: /
title: Hello
import web:ext/web/web.mq.md
---
# Hello
Executable document as a page.
```
```markdown
---
type: endpoint
method: POST
path: /api/ping
response: json
---
*{"ok": true}*
```
Site entry may `# main` → `web.serve root="."`. Client WASM: `ext/web/client.mq.md` / `lib/browser` — no author JS.
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · ADR [0007](../../doc/adr/0007-web-document-endpoint.md) · rule: `.cursor/rules/web-artifact-no-degrade.mdc` · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
Web patterns: [examples.md](examples.md) · API index: [reference.md](reference.md).
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
## Official extension: `ext/quantum` (circuits + Q7/Q8)
@@ -296,29 +203,13 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea
Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/).
## Official extension: `ext/linalg` (formula-first LA)
Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build --release -p marqdo_plugin_linalg`, then **`marqdo ext add linalg` again** so view loads the new native lib.
- EN: `import la:ext/linalg/linalg.mq.md`
- ZH: `导入 la:ext/linalg/线性代数.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards.
APIs (EN): `symbol` → `# matrix`;中缀 `+`/`-`/`*`;方法 `` `A`.T `` / ``.simplify`` / ``.ascii`` · `from_formula` / `explicit` / `factorize` / `draw` · `lstsq` / `norm` / `cond` / `rank`.
Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · formula-doc: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
## AI authoring workflow
1. **查再写**:不确定语法就 `marqdo mlsp`(`syntax` / `locate`)——不必背语法细节。
2. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
3. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
4. 可选:给函数/集合写**渐进式契约**(上节三种表格形状;写全或不写,别写一半)。
5. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
6. On errors:结构化诊断(含 `doc_anchor` / `suggestion`)→ `repair_targets` 取有界靶点,**只改锚点范围内**的行。
7. 提交前:`marqdo check path/to/file.mq.md`(或 `mlsp validate`)清到零 Error。
8. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
## Anti-patterns (common model mistakes)
@@ -339,8 +230,7 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Call `host_*` from `ext/linalg` | Use `la.*` L1 wrappers; plugin ABI only |
| Bare `kind=eig` inside `*…*` | `kind="eig"` — quote text literals |
| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` |
| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) |
@@ -357,5 +247,3 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
- [ ] 语法拿不准的地方已查 MLSP(`syntax`/`locate`),而不是凭记忆发明
- [ ] 契约(如有)与升参一致:`marqdo check` 零 Error
+3
View File
@@ -90,3 +90,6 @@ tests/ext/:memory:
# sandbox gold leftovers
tests/ext/_sbx_cow/
tests/ext/_sbx_*/
examples/**/_example_sbx/
+3 -2
View File
@@ -94,11 +94,12 @@
| [design/ext-ai-sandbox.md](design/ext-ai-sandbox.md) | **`ext/ai/sandbox` 设计锁定**:CoW · 能力表 · agent ABI(非 stdlib) |
| [roadmap/ext-ai-sandbox.md](roadmap/ext-ai-sandbox.md) | **`ext/ai/sandbox` 实现里程碑** S0–S4 |
| [research/ai-agent-llm-optimize-2026-10.md](research/ai-agent-llm-optimize-2026-10.md) | **2026-10 调研**:代码即文档×OKF×沙盒下的 Agent/LLM 优化与问题分析 |
| [design/ext-ai-optimize.md](design/ext-ai-optimize.md) | **方案**:Agent/LLM 优化可行方向全集与推荐波次 O1–O5 |
| [design/ext-ai-optimize.md](design/ext-ai-optimize.md) | **Accepted**:Agent/LLM 优化 O1–O5 locked |
| [roadmap/ext-ai-optimize.md](roadmap/ext-ai-optimize.md) | **O1–O5 实现路线**(沙盒接入→证明晋升→路由/成本→lint→隔离) |
| [research/ext-hosting-gaps.md](research/ext-hosting-gaps.md) | **宿主集成缺口**:同域 SSE 中继 · HTTP→`##` · MCP Server · 副端口 · 跨模块 db/corpus |
| [design/ext-hosting-fill.md](design/ext-hosting-fill.md) | **宿主缺口补齐设计**(`ext/web` proxy/invoke · `ext/ai` mcp_server) |
| [roadmap/ext-hosting.md](roadmap/ext-hosting.md) | **宿主集成 H0–H4**(规划) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** · 后续优化见 [ext-ai-optimize](roadmap/ext-ai-optimize.md) O 波次 |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+7 -4
View File
@@ -2,9 +2,10 @@
| | |
|---|---|
| 状态 | **Proposed · 方向全集(待选型排期)** |
| 状态 | **Accepted · O1–O5 locked** |
| 日期 | 2026-10-16 |
| 调研 | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) |
| 路线 | [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md) |
| 相关 | [ext-ai-sandbox.md](ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [okf.md](okf.md) · [engineering-knowledge.md](engineering-knowledge.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) · [ai-stack.md](../roadmap/ai-stack.md) |
---
@@ -112,7 +113,7 @@ sandbox.open → sandbox.run(caps)→ diff
---
## 3. 推荐落地波次(默认建议,可改)
## 3. 执行顺序(O1→O5 locked)
| 波次 | 方向组合 | 为何先做 |
|------|----------|----------|
@@ -123,6 +124,8 @@ sandbox.open → sandbox.run(caps)→ diff
| **O5** | B4 + C3 | 失败隔离与离线提示优化 |
| **O∞** | C4 / A6 | 研究项,单独立项 |
切片实现见 [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。
---
## 4. 验收原则(任一波次)
@@ -134,6 +137,6 @@ sandbox.open → sandbox.run(caps)→ diff
---
## 5. 下一步
## 5. 落地
请从 §2 方向方向中圈选优先级(或确认 §3 默认 O1→O2)。确认后另开 `doc/roadmap/ext-ai-optimize.md` 做切片实现,**仍不改** `doc/next/*`。
O1–O5 已锁定;实现见 [roadmap/ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。**仍不改** `doc/next/*`。
+18 -2
View File
@@ -314,10 +314,15 @@ type: Marqdo Agent Skill
title: <短名>
sig: <12hex>
resource: ../../resources/<slug>.mq.md
status: stable | candidate
status: stable | candidate | quarantine
llm_free: true | false
quality: <int>
hits: <int>
# O2 optional metadata (from workbook frontmatter; see §7.5):
applies_when: <text condition or tag>
fixtures: <relative .mq.md proof path>
sandbox_profile: default | readonly | <name>
proof: <relative .mq.md> # alias of fixtures for sandbox gate
generated:
by: marqdo-agent/plan
at: <ISO8601>
@@ -331,7 +336,7 @@ verified:
Prefer spawning `resource` over re-planning.
```
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。**O2:** `agent_kb_promote` 默认要求 sandbox proof(`proof` / `fixtures` / workbook 本身经 `sandbox.run` 成功)才写入;失败返回 `promoted: false` / `reason: sandbox_proof_failed`。传 `require_proof=false` 仅用于明确豁免。
### 7.3 任务签名 → Concept 路径
@@ -401,6 +406,17 @@ Prefer spawning `resource` over re-planning.
| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` |
| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 |
| 分发 | 整包 `agent-kb/` 可复制(格式即契约) |
| **证明晋升(O2)** | `applies_when` / `fixtures` / `sandbox_profile` / `proof` 写在技能与 workbook frontmatter;promote 前 `sandbox.run` 绿才 `llm_free` |
| **隔离(O5)** | 失败技能 `status: quarantine`;回归 fixture 跟随 slug |
### 7.5a 技能 frontmatter 约定(O2 B1)
| 字段 | 含义 |
|------|------|
| `applies_when` | 适用条件(短文本 / 标签);路由与 harness 可读 |
| `fixtures` | 相对路径:sandbox 证明用 `.mq.md` |
| `sandbox_profile` | `default` / `readonly` / 其它 `sandbox.profile` 名 |
| `proof` | 与 `fixtures` 同义;promote 优先读 `proof` 再 `fixtures`,否则跑 workbook 自身 |
---
+1
View File
@@ -7,6 +7,7 @@
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) · **[agent-framework-2026-09.md](../research/agent-framework-2026-09.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) |
| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) |
| 后续 | 优化波次 O1–O5 见 [ext-ai-optimize.md](ext-ai-optimize.md)(沙盒证明 · Skill Lift · 路由/成本 · lint · 隔离) |
---
+29
View File
@@ -0,0 +1,29 @@
# Roadmap: Agent/LLM 优化波次 O1–O5
| | |
|---|---|
| Status | **Active** |
| Date | 2026-10-16 |
| Design | [ext-ai-optimize.md](../design/ext-ai-optimize.md) |
| Research | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) |
| Prior | [ext-agent-optimize.md](ext-agent-optimize.md) (A0–A4 / Wave B) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
## Principles
1. Executable `.mq.md` remains authority; OKF reuses; sandbox proves; LLM explores.
2. No hidden TOOL: loop; no vector-store memory authority; no default shell Agent.
3. Do not edit `doc/next/*`.
## Waves
| Wave | Scope | Gold / deliverable | Status |
|------|-------|--------------------|--------|
| **O1** | A1 opt-in `sandbox=` · A3 profile table · D1 skill · D4 example | `agent-sandbox-optin` · `examples/agent-sandbox-okf` | **done** |
| **O2** | A2 promote proof · B1 OKF meta · B3/E1 harness Skill Lift | `agent-sandbox-promote` · harness subset | **done** |
| **O3** | C1 step route · C2 cost · B6 EFI default | `agent-step-route` · run usage/efi | **done** |
| **O4** | A4/D2 lint · A5 diff review report | `scripts/mq-style-lint.sh` · `sandbox.report` | **done** |
| **O5** | B4 quarantine · C3 offline policy rewrite | `agent-sandbox-quarantine` · `optimize-standing-policy.sh` | **done** |
## Non-goals
F1–F5 · wasmtime CLI embed · default `sandbox=True` without ADR · edit `doc/next/*`
+13
View File
@@ -0,0 +1,13 @@
# agent-sandbox-okf(O1)
演示 **opt-in 沙盒试跑 + 表风格**(少 json 胶水):`agent.trial` 写入先落 upper,`commit=False` 时宿主不变,成功后再 `commit=True`。
```bash
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/ext"
./target/release/marqdo run examples/agent-sandbox-okf/index.mq.md
```
期望:`dry-ok` · `host-clean` · `wet-ok` · `proof-visible` · `profile-default`。
见 [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md) · 金样 [agent-sandbox-optin.mq.md](../../tests/ext/agent-sandbox-optin.mq.md)。
+59
View File
@@ -0,0 +1,59 @@
---
title: agent-sandbox-okf — trial then commit
description: >
O1 example: opt-in sandbox trial with GFM-table returns and link-index reads.
import agent:ext/ai/agent.mq.md
import fs:lib/fs.mq.md
---
# main
Short demo: write via `agent.trial`, prove the host is clean until commit.
**had = fs.exists path="_example_sbx"**
1. `had`
> fs.remove path="_example_sbx"
2. *
**_ = 0**
> fs.make_dir path="_example_sbx"
**dry = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=False**
**dry_ok = [ok](dry)**
**dry_committed = [committed](dry)**
1. `dry_ok`
1. not `dry_committed`
> print text=dry-ok
2. *
> print text=dry-bad-commit
2. *
> print text=dry-fail
**leaked = fs.exists path="_example_sbx/note.txt"**
1. `leaked`
> print text=host-leaked
2. *
> print text=host-clean
**wet = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=True**
**wet_ok = [ok](wet)**
**wet_committed = [committed](wet)**
1. `wet_ok`
1. `wet_committed`
> print text=wet-ok
2. *
> print text=wet-no-commit
2. *
> print text=wet-fail
**body = fs.read_text path="_example_sbx/note.txt"**
1. `body` == "sandbox-okf"
> print text=proof-visible
2. *
> print text=proof-missing
**pname = [name]([profile](wet))**
1. `pname` == "default"
> print text=profile-default
2. *
> print text=profile-other
+262 -90
View File
@@ -9,6 +9,8 @@ import time:lib/time.mq.md
import wb:lib/writeback.mq.md
import subtask:lib/subtask.mq.md
import plugin:lib/plugin.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
---
## build_step_context
@@ -247,23 +249,129 @@ Structured observation for the parent developer-agent: source, named writeback s
---
## trial
+ `path`=None
+ `source`=None
+ `root`=None
+ `write_path`=None
+ `text`=None
+ `commit`=True
+ `profile`=default
Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard.
Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable).
**sb = sandbox.open root=`root` profile=`profile`**
**id = [id](sb)**
**prof = [profile](sb)**
**ok = True**
**stdout = ""**
**stderr = ""**
1. `write_path`
1. `text`
> sandbox.write id=`id` path=`write_path` text=`text`
2. *
**_ = 1**
2. *
**_ = 1**
1. `source`
**ret = sandbox.run id=`id` source=`source`**
**ok = [ok](ret)**
**stdout = [stdout](ret)**
**stderr = [stderr](ret)**
2. `path`
**ret = sandbox.run id=`id` path=`path`**
**ok = [ok](ret)**
**stdout = [stdout](ret)**
**stderr = [stderr](ret)**
3. *
**_ = 1**
**pending = sandbox.diff id=`id`**
**committed = False**
1. `ok`
1. `commit`
> sandbox.commit id=`id`
**committed = True**
2. *
> sandbox.discard id=`id`
2. *
> sandbox.discard id=`id`
**out = **
| ok | committed | diff | stdout | stderr | id | profile |
|----|-----------|------|--------|--------|-----|---------|
| `ok` | `committed` | `pending` | `stdout` | `stderr` | `id` | `prof` |
*out*
## step_route
+ `kind`=default
O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend.
Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads).
1. `kind` == "lookup"
**backend = "marqdo"**
2. `kind` == "patch"
**backend = "small-llm"**
3. `kind` == "sandbox_run"
**backend = "marqdo"**
4. `kind` == "net"
**backend = "llm"**
5. *
**backend = "auto"**
**out = table.put in=None at="kind" value=`kind`**
**out = table.put in=`out` at="backend" value=`backend`**
*out*
## await_workbook
+ `path`
+ `sandbox`=False
+ `sandbox_root`=None
+ `sandbox_profile`=default
Spawn a workbook file (quiet by default), wait for `{code,value,stdout?,stderr?}`, and inspect.
Spawn a workbook file (quiet by default), wait, and inspect.
With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit.
**id = > subtask.spawn path=`path`**
**waited = > subtask.wait id=`id`**
**code = > json.get value=`waited` key="code"**
**value = > json.get value=`waited` key="value"**
**stdout = > json.get value=`waited` key="stdout"**
**stderr = > json.get value=`waited` key="stderr"**
**obs = > inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = > json.parse text={"code":0}**
**out = > json.set map=`out` key="code" value=`code`**
**out = > json.set map=`out` key="value" value=`value`**
**out = > json.set map=`out` key="observation" value=`obs`**
*out*
1. `sandbox`
**tr = trial path=`path` root=`sandbox_root` profile=`sandbox_profile` commit=True**
**ok = [ok](tr)**
**stdout = [stdout](tr)**
**stderr = [stderr](tr)**
1. `ok`
**code = 0**
2. *
**code = 1**
**value = stdout**
**obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = **
| code | value | observation | sandbox |
|------|-------|-------------|---------|
| `code` | `value` | `obs` | `tr` |
*out*
2. *
**id = subtask.spawn path=`path`**
**waited = subtask.wait id=`id`**
**code = [code](waited)**
**value = [value](waited)**
**stdout = [stdout](waited)**
**stderr = [stderr](waited)**
**obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = **
| code | value | observation |
|------|-------|-------------|
| `code` | `value` | `obs` |
*out*
---
@@ -1695,8 +1803,16 @@ Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `r
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `threshold`=0.78
+ `step_kind`=None
Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`.
Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call.
1. `step_kind`
**sr = step_route kind=`step_kind`**
**backend = [backend](sr)**
2. *
**_ = 1**
**tools = > json.get value=`self` key="tools"**
*> agent_route task=`task` backend=`backend` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`threshold` tools=`tools`*
@@ -1747,6 +1863,15 @@ Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). M
*> agent_record_episode task=`task` status=`status` result=`result` mode=`mode` skill=`skill` observation=`observation` workbook=`workbook` cache=`cache` match=`match` llm_calls=`llm_calls` tool_calls=`tool_calls` error=`error` memory_dir=`memory_dir`*
## quarantine
+ `slug`
+ `kb_dir`=.marqdo/agent-kb
+ `reason`=sandbox_or_harness_failed
O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug.
*> agent_kb_quarantine kb_dir=`kb_dir` slug=`slug` reason=`reason`*
## maybe_learn
+ `task`
+ `kb_dir`=.marqdo/agent-kb
@@ -1755,6 +1880,7 @@ Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). M
+ `promote`=True
Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing.
O2: promote path requires sandbox proof unless `require_proof=false`.
**skill_learn = > agent_maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote`**
**policy_learn = > agent_maybe_compile_policy memory_dir=`memory_dir` min_evidence=`improve_every`**
@@ -1806,45 +1932,51 @@ Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_
+ `router_model`=None
+ `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume
+ `sandbox`=False
+ `sandbox_profile`=default
+ `efi`=True
Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome.
`sandbox=True` (O1 opt-in): workbook paths run via CoW trial before host commit. `efi=True` (O3): EKC preflight before explore; REUSE short-circuits. Pass `efi=False` to keep legacy golds that skip eng knowledge.
**routed = > `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold`**
**route_matched = > json.get value=`routed` key="matched"**
**needs_llm = > json.get value=`routed` key="needs_llm"**
**efi_pf = None**
1. `efi`
**efi_pf = preflight task=`task`**
2. *
**_ = 1**
**routed = `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold`**
**route_matched = [matched](routed)**
**needs_llm = [needs_llm](routed)**
**exec_mode = "explore"**
**llm_calls = 0**
**tokens = 0**
**token_cost = 0**
**out = None**
**route_backend = > json.get value=`routed` key="backend"**
**route_backend = [backend](routed)**
1. `route_matched`
**path = > json.get value=`routed` key="resource"**
1. `path`
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**lf = > json.get value=`routed` key="llm_free"**
**lf = [llm_free](routed)**
1. `lf`
**exec_mode = "compiled"**
2. *
**exec_mode = "routed"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="hit"**
**rmode = > json.get value=`routed` key="mode"**
**out = > json.set map=`out` key="match" value=`rmode`**
**sk = > json.get value=`routed` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="adaptive route hit"**
**out = > json.set map=`out` key="route" value=`routed`**
**rmode = [mode](routed)**
**sk = [skill](routed)**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary | route |
|--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` |
**llm_calls = 0**
2. *
**route_matched = False**
@@ -1857,33 +1989,28 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**_ = 1**
2. `needs_llm`
1. `router_model`
**prompt = > json.get value=`routed` key="prompt"**
**turn = > model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`**
**reply = > json.get value=`turn` key="text"**
**llm_calls = > json.get value=`turn` key="llm_calls"**
**tokens = > json.get value=`turn` key="tokens"**
**applied = > `self`.route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`router`**
**am = > json.get value=`applied` key="matched"**
**prompt = [prompt](routed)**
**turn = model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`**
**reply = [text](turn)**
**llm_calls = [llm_calls](turn)**
**tokens = [tokens](turn)**
**applied = `self`.route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`router`**
**am = [matched](applied)**
1. `am`
**path = > json.get value=`applied` key="resource"**
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**path = [resource](applied)**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
**exec_mode = "routed"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="soft-hit"**
**out = > json.set map=`out` key="match" value="routed"**
**sk = > json.get value=`applied` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="router model selected skill"**
**out = > json.set map=`out` key="route" value=`applied`**
**sk = [skill](applied)**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary | route |
|--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | soft-hit | routed | `sk` | `last_obs` | router model selected skill | `applied` |
**route_matched = True**
2. *
**route_matched = False**
@@ -1897,29 +2024,51 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
1. `route_matched`
**_ = 1**
2. *
**resolved = > `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold`**
**mode = > json.get value=`resolved` key="mode"**
**llm_free = > json.get value=`resolved` key="llm_free"**
1. `efi_pf`
**efi_st = [status](efi_pf)**
**efi_dec = [decision](efi_pf)**
**efi_allow = [create_allowed](efi_pf)**
1. `efi_st` == "missing_knowledge"
**_ = 1**
2. `efi_dec` == "REUSE"
**_ = 1**
3. `efi_dec` == "ADAPT"
**_ = 1**
4. `efi_allow`
**_ = 1**
5. *
**out = **
| status | goal | error | summary | efi |
|--------|------|-------|---------|-----|
| error | `task` | efi_create_denied | EKC preflight denied CREATE | `efi_pf` |
**exec_mode = "efi"**
2. *
**_ = 1**
1. `out`
**_ = 1**
2. *
**resolved = `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold`**
**mode = [mode](resolved)**
**llm_free = [llm_free](resolved)**
1. `llm_free`
**path = > json.get value=`resolved` key="resource"**
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**path = [resource](resolved)**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**exec_mode = "compiled"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="hit"**
**out = > json.set map=`out` key="match" value=`mode`**
**sk = > json.get value=`resolved` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="compiled skill (llm_free)"**
**sk = [skill](resolved)**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary |
|--------|------|--------|----------|-------|-------|-------|-------------|--------|
| ok | `task` | `child_val` | `path` | hit | `mode` | `sk` | `last_obs` | compiled skill (llm_free) |
**llm_calls = 0**
2. *
**out = > `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force`**
@@ -1966,23 +2115,37 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
2. *
**_ = 1**
**execution = > json.parse text={"mode":"explore","llm_calls":0,"tokens":0}**
**execution = > json.set map=`execution` key="mode" value=`exec_mode`**
**execution = > json.set map=`execution` key="llm_calls" value=`llm_calls`**
**execution = > json.set map=`execution` key="tokens" value=`tokens`**
**execution = > json.set map=`execution` key="skill" value=`sk2`**
**execution = > json.set map=`execution` key="router" value=`route_backend`**
**out = > json.set map=`out` key="execution" value=`execution`**
**out = > json.set map=`out` key="episode" value=`ep`**
**out = > json.set map=`out` key="route" value=`routed`**
**token_cost = tokens**
**usage = **
| llm_calls | tokens | token_cost |
|-----------|--------|------------|
| `llm_calls` | `tokens` | `token_cost` |
**execution = **
| mode | llm_calls | tokens | token_cost | skill | router |
|------|-----------|--------|------------|-------|--------|
| `exec_mode` | `llm_calls` | `tokens` | `token_cost` | `sk2` | `route_backend` |
**out = table.put in=`out` at="execution" value=`execution`**
**out = table.put in=`out` at="episode" value=`ep`**
**out = table.put in=`out` at="route" value=`routed`**
**out = table.put in=`out` at="usage" value=`usage`**
**out = table.put in=`out` at="token_cost" value=`token_cost`**
1. `learning`
**out = > json.set map=`out` key="learning" value=`learning`**
**out = table.put in=`out` at="learning" value=`learning`**
2. *
**_ = 1**
1. `efi_pf`
**out = table.put in=`out` at="efi" value=`efi_pf`**
2. *
**_ = 1**
1. `resume_id`
**_ckpt = > resume_save id=`resume_id` goal=`task` task=`task` status=`st` round=1 workbook=`wb_path` result=`res` route=`routed` resume_dir=`resume_dir`**
**out = > json.set map=`out` key="resume" value=`_ckpt`**
**_ckpt = resume_save id=`resume_id` goal=`task` task=`task` status=`st` round=1 workbook=`wb_path` result=`res` route=`routed` resume_dir=`resume_dir`**
**out = table.put in=`out` at="resume" value=`_ckpt`**
2. *
**_ = 1**
@@ -1994,10 +2157,13 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
+ `stream`=False
+ `echo`=False
+ `max_reads`=2
+ `sandbox`=False
+ `sandbox_profile`=default
One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip.
With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer.
`sandbox=True` (O1 opt-in): attach the sandbox profile row on the result map (trial via `## trial` / `run sandbox=`).
**id = > json.get value=`self` key="id"**
**model = > json.get value=`self` key="model"**
@@ -2088,6 +2254,12 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
**out = > json.set map=`out` key="llm_calls" value=`llm_calls`**
**out = > json.set map=`out` key="tokens" value=`tokens`**
1. `sandbox`
**prof = sandbox.profile name=`sandbox_profile`**
**out = table.put in=`out` at="sandbox_profile" value=`prof`**
2. *
**_ = 1**
**as_turn = > json.parse text={"role":"assistant"}**
**as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn`
+25
View File
@@ -0,0 +1,25 @@
---
title: step-route policy (O3)
description: >
Table-driven map from step class → Adaptive Routing backend.
Readable authority for agent.step_route; do not invent a second dialect.
---
# Step class → backend
Authors and `agent.step_route` read this table. Backends match Adaptive Routing:
`marqdo` | `small-llm` | `llm` | `auto`.
**routes = **
| kind | backend | note |
|------|---------|------|
| lookup | marqdo | OKF / kb skill hit — no parent LLM |
| patch | small-llm | Local patch / soft match |
| sandbox_run | marqdo | CoW trial of `.mq.md` |
| net | llm | Needs network / toolful turn |
| default | auto | Cascade policy → kb → small-llm |
# main
*routes*
+87 -5
View File
@@ -5,10 +5,14 @@ description: >-
Native work lives in plugins/agent (`sandbox_*` → host_query).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
import fs:lib/fs.mq.md
---
Load the agent plugin once per call (same pattern as other `ext/ai` helpers).
Capability profiles are GFM tables under `## profile` (readable authority; `open` / `inspect` echo them). Do not invent a second table dialect.
## ensure_plugin
**p = plugin.native_path name="agent"**
@@ -18,10 +22,38 @@ Load the agent plugin once per call (same pattern as other `ext/ai` helpers).
> print text=ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)
> sys.exit code=1
## open
## profile
+ `name`=default
Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`.
Catalog (documentation + authority):
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| default | true | false | false | false |
| readonly | false | false | false | false |
1. `name` == "readonly"
**row = **
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| readonly | false | false | false | false |
2. *
**row = **
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| default | true | false | false | false |
*row*
## open_native
+ `root`=None
Open a CoW session. Optional `root=` (directory). Default: entry file directory.
Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade.
> ensure_plugin
@@ -30,6 +62,18 @@ Open a CoW session. Optional `root=` (directory). Default: entry file directory.
2. *
*> sandbox_open*
## open
+ `root`=None
+ `profile`=default
Open a CoW session. Optional `root=` (directory). Default: entry file directory.
`profile=` selects the caps row from `## profile` (echoed by `inspect`).
**sess = open_native root=`root`**
**prof = profile name=`profile`**
**sess = table.put in=`sess` at="profile" value=`prof`**
*sess*
## write
+ `id`
+ `path`
@@ -100,10 +144,48 @@ Pass `source=` or `path=` (relative to session root).
> print text=ext/ai/sandbox.run: need source= or path=
> sys.exit code=1
## inspect
## inspect_native
+ `id`
Caps defaults, change counts, and availability notes.
> ensure_plugin
*> sandbox_inspect id=`id`*
## inspect
+ `id`
+ `profile`=default
Native caps / change counts, plus the GFM `## profile` row under key `profile`.
**raw = inspect_native id=`id`**
**prof = profile name=`profile`**
**out = table.put in=`raw` at="profile" value=`prof`**
*out*
## report
+ `id`
+ `path`=sandbox-diff.md
O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite).
**pending = diff id=`id`**
**n = len value=`pending`**
**body = "# Sandbox diff report\n\nPending changes: "**
**body = body + n**
**body = body + "\n\n| path | kind |\n|------|------|\n"**
- [row](pending)
**p = [path](row)**
**k = [kind](row)**
**body = body + "| "**
**body = body + p**
**body = body + " | "**
**body = body + k**
**body = body + " |\n"**
> fs.write_text path=`path` text=`body`
**out = **
| path | count |
|------|-------|
| `path` | `n` |
*out*
+29 -3
View File
@@ -3,6 +3,8 @@ title: ext/ai/智能体
description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编译经 ABI v2 agent 插件(情景 → 学习 → llm_free)。
导入 大模型:ext/ai/大模型.mq.md
import agent:ext/ai/agent.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
import json:lib/json.mq.md
导入 系统:lib/系统.mq.md
导入 自写回:lib/自写回.mq.md
@@ -106,15 +108,30 @@ import json:lib/json.mq.md
> agent_history_clear id=`id`
****
## 试跑
+ `路径`=None
+ `源码`=None
+ `根目录`=None
+ `写入路径`=None
+ `文本`=None
+ `提交`=真
+ `配置`=default
O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。
*> agent.trial path=`路径` source=`源码` root=`根目录` write_path=`写入路径` text=`文本` commit=`提交` profile=`配置`*
## 单步
+ `任务`
+ `写回`=真
+ `流式`=假
+ `打印增量`=假
+ `沙盒`=假
+ `沙盒配置`=default
原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。
**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`**
**id = > json.get value=`自` key="id"**
@@ -171,6 +188,12 @@ import json:lib/json.mq.md
**as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn`
1. `沙盒`
**配置行 = sandbox.profile name=`沙盒配置`**
**out = table.put in=`out` at="sandbox_profile" value=`配置行`**
2. *
**_ = 1**
1. `写回`
**body = > json.stringify value=`out`**
**st = > json.get value=`out` key="status"**
@@ -296,14 +319,17 @@ Engineering First Information 门闩。转发 `agent.preflight`。
+ `强制`=False
+ `路由`=auto
+ `路由模型`=None
+ `沙盒`=False
+ `沙盒配置`=default
+ `工程预检`=True
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。
**model = > json.get value=`self` key="model"**
**tools = > json.get value=`self` key="tools"**
**standing = > json.get value=`self` key="standing"**
**en = > agent.agent model=`model` tools=`tools` standing=`standing`**
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型`*
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型` sandbox=`沙盒` sandbox_profile=`沙盒配置` efi=`工程预检`*
## 路由
+ `任务`
+170 -1
View File
@@ -511,11 +511,25 @@ fn write_skill_concept(
quality: i64,
hits: i64,
now: &str,
meta: &SkillMeta,
) -> Result<(), String> {
if let Some(p) = path.parent() {
fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?;
}
let title: String = goal.chars().take(48).collect();
let mut extra = String::new();
if let Some(ref s) = meta.applies_when {
extra.push_str(&format!("applies_when: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.fixtures {
extra.push_str(&format!("fixtures: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.sandbox_profile {
extra.push_str(&format!("sandbox_profile: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.proof {
extra.push_str(&format!("proof: {}\n", yaml_escape(s)));
}
let body = format!(
r#"---
type: Marqdo Agent Skill
@@ -526,7 +540,7 @@ status: {status}
llm_free: {llm_free}
quality: {quality}
hits: {hits}
generated:
{extra}generated:
by: marqdo-agent/plan
at: {now}
verified:
@@ -545,11 +559,29 @@ Prefer spawning `resource` over re-planning.
llm_free = if llm_free { "true" } else { "false" },
quality = quality,
hits = hits,
extra = extra,
now = now,
);
fs::write(path, body).map_err(|e| format!("write skill: {e}"))
}
#[derive(Default)]
struct SkillMeta {
applies_when: Option<String>,
fixtures: Option<String>,
sandbox_profile: Option<String>,
proof: Option<String>,
}
fn skill_meta_from_src(src: &str) -> SkillMeta {
SkillMeta {
applies_when: extract_fm_field(src, "applies_when"),
fixtures: extract_fm_field(src, "fixtures"),
sandbox_profile: extract_fm_field(src, "sandbox_profile"),
proof: extract_fm_field(src, "proof"),
}
}
fn refresh_index(root: &Path, slug: &str, goal: &str) -> Result<(), String> {
let index = root.join("index.md");
let line = format!(
@@ -585,6 +617,10 @@ fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
.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_tools(args: &Value) -> Option<&Value> {
args.get("tools").filter(|t| !t.is_null())
}
@@ -1107,6 +1143,54 @@ pub fn kb_record_hit(args: &Value) -> Result<Value, String> {
}))
}
/// Run workbook (or FM `proof:` / `fixtures:` path) inside CoW sandbox; discard after.
/// O2: llm_free promote requires this proof to succeed (unless `require_proof=false`).
fn sandbox_proof(workbook: &Path, proof_rel: Option<&str>) -> Result<(bool, String), String> {
let root = workbook
.parent()
.ok_or_else(|| "sandbox_proof: workbook has no parent".to_string())?;
// Always pass an absolute root so host `sandbox_open` does not re-join cwd.
let root_abs = if root.is_absolute() {
root.to_path_buf()
} else {
fs::canonicalize(root).unwrap_or_else(|_| {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(root)
})
};
let root_abs = fs::canonicalize(&root_abs).unwrap_or(root_abs);
let default_name = workbook
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| "sandbox_proof: bad workbook name".to_string())?;
let path = proof_rel.unwrap_or(default_name);
let open = crate::host_query_json_args(
"sandbox_open",
&json!({ "root": root_abs.to_string_lossy() }),
)?;
let id = open
.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_proof: open missing id".to_string())?
.to_string();
let run = crate::host_query_json_args("sandbox_run", &json!({ "id": id, "path": path }));
let _ = crate::host_query_json_args("sandbox_discard", &json!({ "id": id }));
match run {
Ok(r) => {
let ok = r.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
let detail = r
.get("stderr")
.and_then(|v| v.as_str())
.or_else(|| r.get("stdout").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
Ok((ok, detail))
}
Err(e) => Ok((false, e)),
}
}
pub fn kb_promote(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let goal = arg_text(args, "goal")?;
@@ -1119,6 +1203,26 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
let src_path = resolve_path(workbook);
let src = fs::read_to_string(&src_path)
.map_err(|e| format!("kb_promote read workbook: {e}"))?;
let require_proof = args
.get("require_proof")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let proof_rel = extract_fm_field(&src, "proof")
.or_else(|| extract_fm_field(&src, "fixtures"));
if require_proof {
let (ok, detail) = sandbox_proof(&src_path, proof_rel.as_deref())?;
if !ok {
return Ok(json!({
"promoted": false,
"reason": "sandbox_proof_failed",
"detail": detail,
"sig": sig,
"slug": slug,
"workbook": workbook,
"proof": proof_rel.unwrap_or_else(|| src_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_string()),
}));
}
}
let (llm_free, quality) = llm_free_score(&src);
let status = if llm_free { "stable" } else { "candidate" };
@@ -1168,6 +1272,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
&now,
&extra_aliases,
)?;
let meta = skill_meta_from_src(&src);
write_skill_concept(
&skill_path,
&sig,
@@ -1178,6 +1283,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
quality,
prev_hits,
&now,
&meta,
)?;
refresh_index(&root, &slug, &goal_n)?;
@@ -1190,6 +1296,69 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
"quality": quality,
"status": status,
"hits": prev_hits,
"proof_ok": true,
"applies_when": meta.applies_when,
"fixtures": meta.fixtures,
"sandbox_profile": meta.sandbox_profile,
}))
}
/// O5: mark a skill concept as `status: quarantine` and keep fixtures path in FM.
pub fn kb_quarantine(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let slug = arg_text(args, "slug")?;
let reason = opt_text(args, "reason").unwrap_or("sandbox_or_harness_failed");
let root = resolve_path(kb);
let skill_path = root.join("concepts/skills").join(format!("{slug}.md"));
if !skill_path.is_file() {
return Ok(json!({
"ok": false,
"reason": "skill_not_found",
"slug": slug,
"path": skill_path.to_string_lossy(),
}));
}
let src = fs::read_to_string(&skill_path)
.map_err(|e| format!("kb_quarantine read: {e}"))?;
let mut lines: Vec<String> = Vec::new();
let mut saw_status = false;
let mut in_fm = false;
for line in src.lines() {
let t = line.trim();
if t == "---" {
if !in_fm {
in_fm = true;
lines.push(line.to_string());
continue;
} else {
if !saw_status {
lines.push("status: quarantine".to_string());
}
lines.push(format!("quarantine_reason: {}", yaml_escape(reason)));
in_fm = false;
lines.push(line.to_string());
continue;
}
}
if in_fm && t.starts_with("status:") {
lines.push("status: quarantine".to_string());
saw_status = true;
continue;
}
if in_fm && t.starts_with("llm_free:") {
lines.push("llm_free: false".to_string());
continue;
}
lines.push(line.to_string());
}
let body = lines.join("\n") + "\n";
fs::write(&skill_path, body).map_err(|e| format!("kb_quarantine write: {e}"))?;
Ok(json!({
"ok": true,
"slug": slug,
"status": "quarantine",
"reason": reason,
"path": skill_path.to_string_lossy(),
}))
}
+10
View File
@@ -901,6 +901,7 @@ 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_quarantine, kb::kb_quarantine, "agent_kb_quarantine");
kb_ffi!(agent_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit");
kb_ffi!(
agent_workbook_solidify,
@@ -1067,6 +1068,15 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{
return 1;
}
if register(
host,
"agent_kb_quarantine",
"kb_dir,slug",
agent_kb_quarantine,
) != 0
{
return 1;
}
if register(host, "agent_kb_record_hit", "kb_dir,goal", agent_kb_record_hit) != 0 {
return 1;
}
+26
View File
@@ -39,6 +39,32 @@ run tests/ext/agent-zero-llm.mq.md
run tests/ext/agent-plan-preserve.mq.md
run examples/agent-okf-flywheel/index.mq.md
run examples/agent-pong/index.mq.md
run examples/agent-sandbox-okf/index.mq.md
run tests/ext/agent-sandbox-optin.mq.md
run tests/ext/agent-sandbox-promote.mq.md
# Skill Lift subset (O2 B3/E1): with-skill vs without — constitution / writeback / call_site markers.
skill_lift_pass=0
skill_lift_fail=0
assert_out_has() {
local f="$1"
local needle="$2"
local label="$3"
local out
out="$("$MQ" run "$f" 2>/dev/null || true)"
if printf '%s' "$out" | grep -q -- "$needle"; then
echo "SkillLift OK $label ($needle)"
skill_lift_pass=$((skill_lift_pass + 1))
else
echo "SkillLift MISS $label (need $needle)" >&2
skill_lift_fail=$((skill_lift_fail + 1))
fail=1
fi
}
assert_out_has tests/ext/agent-constitution-b0.mq.md "constitution-ok" "constitution"
assert_out_has tests/ext/agent-writeback-shadow.mq.md "writeback-shadow-ok" "writeback"
assert_out_has tests/ext/agent-dump-context.mq.md "dump-context-ok" "call_site"
echo "SkillLift summary: pass=$skill_lift_pass fail=$skill_lift_fail"
if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
export AGENT_LIVE=1
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# O4 — style gate: flag json.set dict chains and mixed EN/ZH API hints in .mq.md.
# Exit 0 when clean; 1 when findings (unless MQ_STYLE_LINT_SOFT=1).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
TARGETS=("$@")
if [[ ${#TARGETS[@]} -eq 0 ]]; then
TARGETS=(ext/ai/sandbox.mq.md ext/ai/policies examples/agent-sandbox-okf)
fi
fail=0
findings=0
scan_file() {
local f="$1"
[[ -f "$f" ]] || return 0
# Long json.set pipelines (3+ consecutive) — style bug per marqdo-dev.
if awk '
/json\.set/ { c++; if (c >= 3) { found=1 } next }
{ c=0 }
END { exit found ? 0 : 1 }
' "$f"; then
echo "STYLE json.set-chain: $f" >&2
findings=$((findings + 1))
fail=1
fi
# Same file imports both EN agent and ZH 智能体 (or web/网页) — mixed surface.
if grep -qE 'import[[:space:]]+agent:|import[[:space:]]+web:' "$f" \
&& grep -qE '导入[[:space:]]+(智能体|网页):' "$f"; then
echo "STYLE mixed-EN/ZH-import: $f" >&2
findings=$((findings + 1))
fail=1
fi
}
while IFS= read -r -d '' f; do
scan_file "$f"
done < <(find "${TARGETS[@]}" -type f -name '*.mq.md' -print0 2>/dev/null)
echo "mq-style-lint: findings=$findings"
if [[ "${MQ_STYLE_LINT_SOFT:-}" == "1" ]]; then
exit 0
fi
exit "$fail"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# O5 — offline standing / policy rewrite hint (GEPA-like, products stay repo files).
# Does NOT change the runtime agent path. Reads harness failure log + current files,
# writes a suggested patch under .marqdo/optimize/ for human review.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
LOG="${1:-}"
STANDING="${2:-ext/ai/agent.mq.md}"
POLICY="${3:-ext/ai/policies/step-route.mq.md}"
OUT_DIR="${OUT_DIR:-.marqdo/optimize}"
mkdir -p "$OUT_DIR"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
REPORT="$OUT_DIR/standing-policy-$STAMP.md"
{
echo "# Offline standing / policy optimize suggestion"
echo
echo "Generated: $STAMP"
echo
echo "This is a **review artifact**, not an automatic runtime rewrite."
echo "Strong models may rewrite \`standing\` / \`policies/*.mq.md\` offline;"
echo "commit only after harness green."
echo
echo "## Inputs"
echo
echo "- standing source: \`$STANDING\`"
echo "- policy source: \`$POLICY\`"
if [[ -n "$LOG" && -f "$LOG" ]]; then
echo "- harness log: \`$LOG\`"
echo
echo "## Harness failure excerpt"
echo
echo '```'
tail -n 80 "$LOG" || true
echo '```'
else
echo "- harness log: _(none — pass path as \$1)_"
fi
echo
echo "## Current policy table (copy)"
echo
if [[ -f "$POLICY" ]]; then
echo '```markdown'
cat "$POLICY"
echo '```'
else
echo "_missing $POLICY_"
fi
echo
echo "## Suggested next edits"
echo
echo "1. Keep step-class → backend as a **GFM table** (no json glue)."
echo "2. Quarantine failing skills (\`status: quarantine\`) before promoting again."
echo "3. Re-run \`scripts/agent-harness.sh\` and confirm Skill Lift summary."
} > "$REPORT"
echo "wrote $REPORT"
+6 -2
View File
@@ -32,7 +32,9 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## Markup → meaning (v0.2)
@@ -162,7 +164,9 @@ Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --releas
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
+49
View File
@@ -0,0 +1,49 @@
---
title: agent trial sandbox opt-in — host unchanged until commit
description: >
O1: agent.trial write stays upper until commit=True.
Prefer link index over json.get.
import agent:ext/ai/agent.mq.md
import sandbox:ext/ai/sandbox.mq.md
import fs:lib/fs.mq.md
---
# main
Reset leftover workspace from prior runs.
**had = fs.exists path="_sbx_optin"**
1. `had`
> fs.remove path="_sbx_optin"
2. *
**_ = 0**
> fs.make_dir path="_sbx_optin"
Trial with `commit=False`: upper write must not touch the host tree.
**dry = agent.trial root="_sbx_optin" write_path="proof.txt" text=optin-ok commit=False**
**dry_ok = [ok](dry)**
**dry_committed = [committed](dry)**
> print text=`dry_ok`
> print text=`dry_committed`
**before = fs.exists path="_sbx_optin/proof.txt"**
> print text=`before`
Trial with `commit=True`: host sees the file after success.
**wet = agent.trial root="_sbx_optin" write_path="proof.txt" text=optin-ok commit=True**
**wet_ok = [ok](wet)**
**wet_committed = [committed](wet)**
> print text=`wet_ok`
> print text=`wet_committed`
**after = fs.read_text path="_sbx_optin/proof.txt"**
> print text=`after`
Profile row is attached (link-index readable).
**prof = [profile](wet)**
**pname = [name](prof)**
> print text=`pname`
+35
View File
@@ -0,0 +1,35 @@
---
title: promote requires sandbox proof (O2)
description: >
Good workbook promotes; broken workbook is rejected (sandbox_proof_failed).
Link-index reads; no json glue.
import plugin:lib/plugin.mq.md
import fs:lib/fs.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-plugin
> sys.exit code=1
**kb = "_sbx_promote_kb"**
**had = fs.exists path=`kb`**
1. `had`
> fs.remove path=`kb`
2. *
**_ = 0**
**prom = agent_kb_promote kb_dir=`kb` goal="sandbox promote good" workbook="sandbox-fixtures/promote-good.mq.md"**
**ok = [promoted](prom)**
> print text=`ok`
**rej = agent_kb_promote kb_dir=`kb` goal="sandbox promote bad" workbook="sandbox-fixtures/promote-bad.mq.md"**
**rej_ok = [promoted](rej)**
**reason = [reason](rej)**
> print text=`rej_ok`
> print text=`reason`
+34
View File
@@ -0,0 +1,34 @@
---
title: O5 quarantine skill status
description: Promote good skill then quarantine — status becomes quarantine.
import plugin:lib/plugin.mq.md
import fs:lib/fs.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-plugin
> sys.exit code=1
**kb = "_sbx_quar_kb"**
**had = fs.exists path=`kb`**
1. `had`
> fs.remove path=`kb`
2. *
**_ = 0**
**prom = agent_kb_promote kb_dir=`kb` goal="quarantine demo" workbook="sandbox-fixtures/promote-good.mq.md"**
**ok = [promoted](prom)**
**slug = [slug](prom)**
> print text=`ok`
**q = agent_kb_quarantine kb_dir=`kb` slug=`slug` reason="fixture_regression"**
**qok = [ok](q)**
**st = [status](q)**
> print text=`qok`
> print text=`st`
+19
View File
@@ -0,0 +1,19 @@
---
title: O3 step_route table backends
description: lookup → marqdo; net → llm; default → auto.
import agent:ext/ai/agent.mq.md
---
# main
**a = agent.step_route kind="lookup"**
**ba = [backend](a)**
> print text=`ba`
**b = agent.step_route kind="net"**
**bb = [backend](b)**
> print text=`bb`
**c = agent.step_route kind="default"**
**bc = [backend](c)**
> print text=`bc`
@@ -0,0 +1,8 @@
---
title: promote-bad
proof: promote-bad.mq.md
---
# main
> this_is_not_a_real_builtin_xyz
@@ -0,0 +1,12 @@
---
title: promote-ok
type: skill
applies_when: demo
fixtures: promote-good.mq.md
sandbox_profile: default
proof: promote-good.mq.md
---
# main
> print text=proof-ok
+48
View File
@@ -2986,6 +2986,54 @@ inspect-ok",
);
}
#[test]
fn ext_ai_agent_sandbox_optin() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/agent-sandbox-optin.mq.md",
"True
False
False
True
True
optin-ok
default",
);
}
#[test]
fn ext_ai_agent_sandbox_promote() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/agent-sandbox-promote.mq.md",
"True
False
sandbox_proof_failed",
);
}
#[test]
fn ext_ai_agent_step_route() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/agent-step-route.mq.md",
"marqdo
llm
auto",
);
}
#[test]
fn ext_ai_agent_sandbox_quarantine() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/agent-sandbox-quarantine.mq.md",
"True
True
quarantine",
);
}
#[test]
fn ext_llm_named_offline() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));