Compare commits

...
9 Commits
Author SHA1 Message Date
cflmyandCursor c44ea38ae2 release: Ext pack 1.4.3 — agent.run cold EFI / resolve llm_free
Bump ext/VERSION only (CLI stays 1.4.2). Ships agent facade + native miss-field fix for qdagent cold OKF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:56:40 +08:00
cflmyandCursor d489f7c088 fix(ext/ai): cold agent.run EFI — self.preflight and resolve llm_free
Miss resolve omitted llm_free and run called bare preflight, which crashed
qdagent on empty OKF. Align miss fields, use self.preflight + json.get, add
regression gold and research note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:54:00 +08:00
cflmyandCursor a993cfd76a chore: sync Cargo.lock package versions to 1.4.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:21:23 +08:00
cflmyandCursor d5f826a8c8 release: Marqdo 1.4.2
Bump CLI/wasm/ext to 1.4.2 for Agent/LLM optimize O1–O5 (sandbox trial,
promote proof, step_route/EFI, lint, quarantine).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:51:41 +08:00
cflmyandCursor 0f72173d08 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>
2026-10-16 11:47:28 +08:00
cflmyandCursor a707758d47 docs: research and plan Agent/LLM optimization with OKF and sandbox
Capture the 2026-10 landscape (skills, Skill Lift, routing, GEPA) against Marqdo’s code-as-docs assets and list feasible optimize directions without editing doc/next.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:13:48 +08:00
cflmyandCursor 63bcb882a6 feat(ext/ai): add CoW sandbox for Marqdo-only agent trials
Give agents a capability-capped run path that stages workspace edits until commit, so generated .mq.md can be verified without polluting the real tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:11:54 +08:00
cflmyandCursor 1bb16dd6db release: Marqdo 1.4.1
View annot leaders mid-to-mid SVG, frame chip id unify; bump CLI/wasm/ext.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:37:24 +08:00
cflmyandCursor 58ec2172d6 fix(view): mid-to-mid annot leaders and prose chip density
Unify frame chip ids with marks, reorder chips under anchors, and draw
SVG leaders from underline mid-bottom to chip mid-top so crowded bands
stay readable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:36:12 +08:00
65 changed files with 4006 additions and 356 deletions

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 Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose, 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, importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic
building dynamic sites with ext/web, quantum circuits with ext/quantum, sites with ext/web, quantum circuits with ext/quantum, or when the user
formula-first linear algebra with ext/linalg, or when the user mentions mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or
Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, quantum/量子, quantum/量子 extension.
or linalg/线性代数 extension.
--- ---
# Marqdo development # 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. 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/*`. **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) ## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources). 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="…"**` / `> 打印 内容=…`. 2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**.
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. 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: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted. 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:** `` `名` `` 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` ``. 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** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold. 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 / defaults / table cells, unspaced `a/b` and quoted paths are text. 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 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. 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. 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)). 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. **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). 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 语法细节**——语法可查、程序可验、修复有界。写码前后走**查询式**工作流: ## Markup → meaning (v0.2)
```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)
| Marker | Meaning | | 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`) ``) | | `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm | | Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) | | `> 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`) | | `` > `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:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) | | 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 ``) | | `> 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 | | `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables | | `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body | | `****` or `**` + spaces + `**` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) | | Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` | | 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 | | `- [item](coll)` | Foreach (unchanged) |
| `$$` + `% marqdo: var=name` | Block formula bind (TeX comment; prefer over empty RHS) | | `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `- [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 |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment | | Unmarked prose | Comment |
@@ -140,19 +82,20 @@ Chinese builtins (same functions, no import):
## Functions, calls, end-body ## Functions, calls, end-body
Prefer **body-inferred params** and **prose-unified** wording (v0.3). `` + `name` `` still works, but teach the inferred form first:
```markdown ```markdown
# main # main
**greet who="Marqdo"** > greet who=Marqdo
## greet ## 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 `#` (`##`, `###`, …). - 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). - 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 `>`). - 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 ## Statements, returns, branches
```markdown ```markdown
**x = 1** *x = 1*
**y = x + 2** *y = x + 2*
## add_one ## add_one
+ `n`
For input`n`, do **n = n + 1** and return*n*. **n + 1**
``` ```
```markdown ```markdown
**n = 0** *n = 0*
1. `n` > 0 1. `n` > 0
> print text=positive > print text=positive
@@ -192,16 +136,16 @@ import clock:lib/time.mq.md
# main # main
**xs = > text.str_split s="a,b,c" sep=","** *xs = > text.split value="a,b,c" sep=","*
> print text=`xs` > 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). - 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). - Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary. - `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md). - 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`. - 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`). - 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`/`非`. - 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. 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. 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)。 3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
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`.
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) ## 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. - EN: `import web:ext/web/web.mq.md`
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)
- ZH: `导入 网页:ext/web/网页.mq.md` - ZH: `导入 网页:ext/web/网页.mq.md`
```markdown Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
---
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).
## Official extension: `ext/quantum` (circuits + Q7/Q8) ## 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/). 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 ## AI authoring workflow
1. **查再写**:不确定语法就 `marqdo mlsp`(`syntax` / `locate`)——不必背语法细节。 1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. 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. 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. 可选:给函数/集合写**渐进式契约**(上节三种表格形状;写全或不写,别写一半)。 4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves). 5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
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.
## Anti-patterns (common model mistakes) ## 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` | | 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_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/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Call `host_*` from `ext/linalg` | Use `la.*` L1 wrappers; plugin ABI only | | Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals |
| Bare `kind=eig` inside `*…*` | `kind="eig"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` | | 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`) | | 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 - [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view - [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed) - [ ] `marqdo run` succeeds (or errors addressed)
- [ ] 语法拿不准的地方已查 MLSP(`syntax`/`locate`),而不是凭记忆发明
- [ ] 契约(如有)与升参一致:`marqdo check` 零 Error
+5 -5
View File
@@ -126,6 +126,10 @@ jobs:
## Marqdo ${{ github.ref_name }} ## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights ### 亮点 / Highlights
- **v1.4.2**:Agent/LLM 优化 O1–O5——sandbox trial · promote proof · step_route/EFI/cost · lint · quarantine
- **v1.4.2**: Agent/LLM optimize O1–O5 — sandbox trial, promote proof, step_route/EFI/cost, lint, quarantine
- **v1.4.1**:view 标注连线——SVG mid→mid(underline 底中 → chip 顶中)· 帧 chip id 对齐 · L→R 密度
- **v1.4.1**: View annot leaders — SVG mid→mid (mark bottom-center → chip top-center), frame chip id unify, L→R density
- **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参 - **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参
- **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view - **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view
- **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源 - **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源
@@ -134,12 +138,8 @@ jobs:
- **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE) - **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE)
- **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure` - **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure`
- **v1.2.0**: Web Artifact (ADR 0007) — Document/Endpoint, web.serve/render/inspect, ext/data|security|net, compose_*/configure removed - **v1.2.0**: Web Artifact (ADR 0007) — Document/Endpoint, web.serve/render/inspect, ext/data|security|net, compose_*/configure removed
- **v1.1.1**:AI 栈收口——llm `ask`/`stream`/`collect` · Metadata Binding · Skill Compilation + Adaptive Routing · MCP 客户端 + resume · 可选 `plugins/llm`
- **v1.1.1**: AI stack — llm ask/stream/collect, Metadata Binding, Skill Compilation + Adaptive Routing, MCP client + resume, optional plugins/llm
- **v1.0.7**:WS/网络边界加固;`url_encode` `%20`
- **v1.0.3**:Ubuntu PPA + 扩展 CDN(ext.marqdo.com)
- **Linux 包必出**:`*-native-x86_64-unknown-linux-gnu.zip` + Linux CLI bundle - **Linux 包必出**:`*-native-x86_64-unknown-linux-gnu.zip` + Linux CLI bundle
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [mapping v0.3](https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping-v0.3.md) - Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [ext-ai-optimize](https://github.com/cflmy/marqdo/blob/main/doc/roadmap/ext-ai-optimize.md)
### Downloads ### Downloads
+6
View File
@@ -87,3 +87,9 @@ tests/ext/:memory:
# local secrets # local secrets
.env .env
# sandbox gold leftovers
tests/ext/_sbx_cow/
tests/ext/_sbx_*/
examples/**/_example_sbx/
+77
View File
@@ -8,6 +8,83 @@
### Changed ### Changed
## Ext pack v1.4.3 — 2026-10-16
### Highlights
**Agent cold EFI / resolve 硬崩修复(CLI 仍为 v1.4.2)**:qdagent 接通 `agent.run` 时空 OKF 触发 `unknown function preflight` 与 `missing map key llm_free`。本包修复 `ext/ai/agent` facade 与 `agent` native;金样 `tests/ext/agent-run-cold-efi.mq.md`。说明:[`doc/research/agent-run-efi-resolve-bugs-2026-10.md`](doc/research/agent-run-efi-resolve-bugs-2026-10.md)。
```bash
marqdo ext add agent # CDN latest → 1.4.3
# 或:MARQDO_EXT_VERSION=1.4.3 marqdo ext add agent
```
**核心表面 Δ(Core surface Δ)**:**无增删**——仅 Extension / Agent Runtime 契约修补。
### Fixed
- **`agent.run`**:`efi=True` 改为 `` `self`.preflight ``(不再裸调全局 `preflight`)。
- **`agent_resolve` miss**:返回字段对齐命中路径,含 `llm_free: false`;facade 对 `llm_free` / route 字段改用 `json.get`。
### Changed
- 扩展包 SemVer **1.4.3**(`ext/VERSION`);与 CLI **v1.4.2** 可独立安装。
## v1.4.2 — 2026-10-16
### Highlights
**Agent/LLM 优化 O1–O5**:`ext/ai/sandbox` CoW 试跑接入 `agent.trial` / `run sandbox=`(默认关);promote 强制 sandbox proof;步骤路由 `step_route` + EFI preflight + `usage`/`token_cost`;风格 lint 与 `sandbox.report`;技能 `quarantine` 与离线 standing/policy 优化脚本。表优先、少 json 胶水。路线:[ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md)。
```bash
git checkout v1.4.2 && cargo build --release
cargo build --release -p marqdo_plugin_agent
marqdo run tests/ext/agent-sandbox-optin.mq.md
marqdo run examples/agent-sandbox-okf/index.mq.md
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add agent # CDN latest → 1.4.2
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Extension / Agent Runtime**(`ext/ai` 沙盒与晋升闸门),不触碰语言标记。
### Added
- **`ext/ai/sandbox`**:CoW 工作区(`open` / `run` / `diff` / `commit` / `discard` / `inspect` / `profile` / `report`);经 `plugins/agent` `sandbox_*` → `host_query`;默认拒 `plugin`/`exec`/`net`。
- **O1**:`agent.trial` · `run`/`step` `sandbox=` · 中文 `试跑`/`沙盒=` · 示例 `examples/agent-sandbox-okf/` · 金样 `agent-sandbox-optin`。
- **O2**:`agent_kb_promote` 默认 sandbox proof;OKF `applies_when`/`fixtures`/`sandbox_profile`/`proof`;harness Skill Lift。
- **O3**:`agent.step_route` · `ext/ai/policies/step-route.mq.md` · `run efi=`(缺工程知识时软放行)· 结果 `usage`/`token_cost`。
- **O4**:`scripts/mq-style-lint.sh` · `sandbox.report` markdown 审阅面。
- **O5**:`agent_kb_quarantine` / `agent.quarantine` · `scripts/optimize-standing-policy.sh`。
### Fixed
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.2**。
- Skill:强制表/链接取元、禁同文件混 EN/ZH、点名 sandbox 试跑习惯。
## v1.4.1 — 2026-10-15
### Highlights
**view 叙述标注连线**:Browse / `view output` 中 underline→chip 改为 SVG 正交连线(描述底边中点 → 轨道 → 短竖线 → 值顶边中点);同跨度多帧 chip 共用 annot id;可见 chip 按锚点 L→R;帧切换后重算密度。设计:[view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)。
```bash
git checkout v1.4.1 && cargo build --release
marqdo view public/00-welcome.mq.md --no-open
marqdo view output public -o /tmp/mq-public
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.4.1
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 标注几何与帧 chip 对齐),不触碰语言标记。
### Added
- 设计缺口文档 [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md):叙述 fence 卡、帧感知 chip 密度、L-leader 几何约定。
### Fixed
- view L-leader:id 与 mark 错配、chip 逆序交叉、border 无色变黑碎段、横线穿过 chip 文字;现为 mid→mid SVG path。
- 叙述 fence / 代码卡单层渲染;静态页隐藏 Run;主文函数引用 call chip + leader。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.1**。
## v1.4.0 — 2026-10-15 ## v1.4.0 — 2026-10-15
### Highlights ### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]] [[package]]
name = "marqdo" name = "marqdo"
version = "1.4.0" version = "1.4.2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"assert_cmd", "assert_cmd",
@@ -603,7 +603,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-wasm" name = "marqdo-wasm"
version = "1.4.0" version = "1.4.2"
dependencies = [ dependencies = [
"marqdo", "marqdo",
"serde_json", "serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "marqdo" name = "marqdo"
version = "1.4.0" version = "1.4.2"
edition = "2021" edition = "2021"
license = "Apache-2.0" license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language" description = "Marqdo — Markdown markers as an interpreted programming language"
+7 -4
View File
@@ -149,8 +149,11 @@ marqdo catalog public -o .marqdo
--- ---
## 现状(v1.4.0) ## 现状(v1.4.2 · Ext pack **1.4.3**)
- **Ext pack 1.4.3**:修复 `agent.run` cold EFI(`` `self`.preflight `` + miss resolve `llm_free`);`marqdo ext add agent` → CDN latest · [agent-run-efi-resolve-bugs-2026-10.md](doc/research/agent-run-efi-resolve-bugs-2026-10.md)
- **Agent/LLM 优化 O1–O5(v1.4.2)**:`ext/ai/sandbox` CoW · `agent.trial` / `sandbox=` · promote sandbox proof · `step_route` / EFI / cost · style lint · quarantine · [ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md)
- **view 标注连线(v1.4.1)**:underline→chip SVG mid→mid(底边中点→轨道→短竖线→顶边中点)· 帧 chip 共用 id · L→R 密度 · [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)
- **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `![marqdo-out](…)` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md) - **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `![marqdo-out](…)` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)
- **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md) - **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md)
- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md) - **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
@@ -178,7 +181,7 @@ marqdo catalog public -o .marqdo
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md)) - **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md) - 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
### 如何使用最新 Marqdo(v1.4.0) ### 如何使用最新 Marqdo(v1.4.2)
**安装解释器(任选其一)** **安装解释器(任选其一)**
@@ -193,7 +196,7 @@ marqdo catalog public -o .marqdo
```bash ```bash
# 1) 源码安装(跟 tag 或 main) # 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.4.0 # 或留在 main git checkout v1.4.2 # 或留在 main
cargo build --release cargo build --release
export PATH="$PWD/target/release:$PATH" export PATH="$PWD/target/release:$PATH"
marqdo version marqdo version
@@ -232,7 +235,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/ # → dist/wasm/ … 见 examples/browser-hello/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip # 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v1.4.0 # https://github.com/cflmy/marqdo/releases/tag/v1.4.2
``` ```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`: 开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "marqdo-wasm" name = "marqdo-wasm"
version = "1.4.0" version = "1.4.2"
edition = "2021" edition = "2021"
license = "Apache-2.0" license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)" description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+14
View File
@@ -1,3 +1,17 @@
marqdo (1.4.2-1ppa1) noble; urgency=medium
* Marqdo 1.4.2: Agent/LLM optimize O1–O5 — sandbox trial opt-in,
promote sandbox proof, step_route/EFI/cost, style lint, quarantine.
-- cflmy <pingan@cflmy.cn> Fri, 16 Oct 2026 11:51:05 +0800
marqdo (1.4.1-1ppa1) noble; urgency=medium
* Marqdo 1.4.1: View annot leaders — SVG mid-to-mid (mark bottom-center
to chip top-center), unify frame chip ids, L-to-R chip density.
-- cflmy <pingan@cflmy.cn> Thu, 15 Oct 2026 20:40:00 +0800
marqdo (1.4.0-1ppa1) noble; urgency=medium marqdo (1.4.0-1ppa1) noble; urgency=medium
* Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=, * Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=,
+7 -1
View File
@@ -90,10 +90,16 @@
| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 | | [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** | | [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** |
| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** | | [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** |
| [research/ai-agent-sandbox.md](research/ai-agent-sandbox.md) | **AI 扩展沙盒调研**:Wasm / OS / CoW / symlink 对比与 Marqdo 分层推荐 |
| [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) | **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 | | [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) | | [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-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/)。 金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+142
View File
@@ -0,0 +1,142 @@
# 方案:智能体 / 大模型优化方向(代码即文档 · OKF · 沙盒)
| | |
|---|---|
| 状态 | **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) |
---
## 0. 方案立场
1. **强化差异化**:可执行 `.mq.md` 为权威;OKF 为复用;沙盒为证明;LLM 为探索。
2. **不向隐藏 TOOL: 循环 / 向量权威回退。**
3. 下列方向均为**可行**;推荐波次见 §3,最终裁剪由你选型。
4. **不改** `doc/next/*`;落地时另开 roadmap 切片。
---
## 1. 架构愿景(闭环)
```text
目标 / 任务
│
▼
EFI / OKF lookup ──hit──► llm_free / marqdo 执行 ──► writeback
│ miss
▼
small-llm 路由 / 父分解
│
▼
生成或修补 .mq.md(代码即文档风格)
│
▼
sandbox.open → sandbox.run(caps)→ diff
│
├─ 失败 → writeback error / 隔离,不 promote
└─ 成功 → 人审或策略 → commit → solidify / OKF promote
│
▼
下次 REUSE(降本)
```
---
## 2. 可行方向全集
每个方向标注:解决的问题(Pn)、依赖、风险、粗粒度成本。
### A. 沙盒 × Agent 闭环
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **A1** | `step`/`plan` 默认经 sandbox 试跑再写实树 | P1 | 生成落 upper;绿才 `commit` | sandbox | 破坏现有金样默认 | 中 |
| **A2** | Promote / solidify 强制 sandbox proof | P1 | OKF 写入前要求 proof fixture 绿 | sandbox+OKF | 过严挡复用 | 中 |
| **A3** | Sandbox profile 表(caps 宣告) | P1/P3 | GFM 表声明 net/plugin/fs | sandbox | 表方言膨胀 | 低 |
| **A4** | Guest 风格门禁(表优先、禁 json 胶水) | P5 | commit 前 lint / preflight | sandbox+parser | 误杀合法 json.parse | 中 |
| **A5** | 会话 diff → view 审阅卡 | P1/P4 | HITL 看 CoW diff | view+sandbox | UI 工时 | 中高 |
| **A6** | 多会话并行 CoW(fan-out 实验) | — | 每假设一 session | sandbox | 隔离/合并复杂 | 高 |
### B. OKF / EKC / 技能层
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **B1** | OKF 技能元数据:适用条件 / fixtures / sandbox_profile | P2 | frontmatter + 目录约定 | okf | 与 catalog 字段冲突 | 中 |
| **B2** | Progressive disclosure(索引轻、正文按需 READ) | P2/P6 | 对齐 Anthropic Skills 层级 | agent A3 | 实现重复 | 中 |
| **B3** | Skill Lift 评测(有/无技能配对) | P4 | harness 指标 | B1 评测 | 样本少噪声大 | 中 |
| **B4** | 失败技能隔离(quarantine)+ 回归用例跟随血缘 | P1 | ForgeAgent 式 | OKF | 状态机复杂 | 中高 |
| **B5** | near-match / soft_match 产品化默认开 | P6 | 已有 roadmap | okf-near | 误复用 | 低中 |
| **B6** | EKC preflight 默认硬门槛(REUSE→ADAPT→CREATE) | P6 | step 前强制 EFI | EKC | 拖慢探索 | 中 |
| **B7** | Capability 包与 `llm_free` 资源双向链接 | P2 | catalog L3↔任务包 | EKC+OKF | 图维护 | 中 |
### C. 大模型 / 路由 / 成本
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **C1** | 步骤级路由(lookup / patch / sandbox_run / net) | P3 | 扩展 route policy 表 | routing | 策略过拟合 | 中 |
| **C2** | 总成本计量(含推理 token 膨胀)写回文档 | P7 | usage→writeback/metrics | llm result | 噪声 | 低中 |
| **C3** | 用强模型「反思」优化 standing / policy `.mq.md`(类 GEPA) | P3/P5 | 离线优化环,产物仍是文件 | llm | 需评测集 | 高 |
| **C4** | 高频 OKF 技能蒸馏/微调小模型(编译进权重) | — | 长期研究 | 数据+算力 | 运维重;偏离「源码权威」 | 很高 |
| **C5** | Named model 绑定任务类型(fast=路由,reasoning=分解) | P3 | 已有 named handles 加深 | llm | 配置漂移 | 低 |
| **C6** | Prompt document 强制:无参 ask 必须来自 type:prompt 文件 | P5 | 硬化 005 | llm | 破坏脚本式调用 | 低 |
### D. 代码即文档(产出质量)
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **D1** | 官方「可读 Marqdo」Skill 强化(表/链接取元/禁混名) | P5 | skills/marqdo 加厚 | skill | 模型仍违规 | 低 |
| **D2** | AST/结构 lint:json.set 链、混 EN/ZH API | P5 | `marqdo lint` 或 sandbox 钩子 | parser | 误报 | 中 |
| **D3** | 工作簿补丁只允许表驱动 / 命名槽写回 | P5 | 收紧 A0 补丁面 | agent | 表达力下降 | 中 |
| **D4** | 示例库:sandbox+OKF+表风格 canonical demos | P4/P5 | examples/ | 文档 | 维护 | 低 |
### E. 评测与产品化
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **E1** | 完成 Wave B1 harness(constitution / writeback / call_site) | P4 | 已规划 | agent | — | 中 |
| **E2** | 指标面板:ReuseRate / ProofRate / TokenCost | P4/P7 | metrics 写回或 catalog | agent | 虚荣指标 | 中 |
| **E3** | Live 金样矩阵(sandbox 开/关 × 路由后端) | P4 | CI optional | CI | flaky | 中 |
| **E4** | 教程:「只读一份 .mq.md 理解 Agent」 | — | doc/tutorial | 文档 | — | 低 |
### F. 明确不优先 / 需单独论证
| ID | 方向 | 理由 |
|----|------|------|
| **F1** | 第二套 Agent Framework(Python/TS 对象图权威) | 违宪 |
| **F2** | 向量库升为记忆权威 | 违宪;可作证据工具 |
| **F3** | 默认通用 shell Agent | 与 Marqdo-only 沙盒战略冲突 |
| **F4** | 整库 `ext/web` 进默认沙盒 | 已否决 |
| **F5** | 人人 microVM 本地默认 | DX 过重;留给 hosted |
---
## 3. 执行顺序(O1→O5 locked)
| 波次 | 方向组合 | 为何先做 |
|------|----------|----------|
| **O1** | A1 轻量(opt-in `sandbox=True`)+ A3 + D1 + D4 | 立刻接上刚落地的沙盒,风险可控 |
| **O2** | A2 + B1 + B3 + E1 | 验证→晋升→可度量 Skill Lift |
| **O3** | C1 + C2 + B6 | 降本与 EFI 硬门槛 |
| **O4** | A4 + D2 + A5 | 质量门禁与人审 |
| **O5** | B4 + C3 | 失败隔离与离线提示优化 |
| **O∞** | C4 / A6 | 研究项,单独立项 |
切片实现见 [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。
---
## 4. 验收原则(任一波次)
- 金样:有/无沙盒、有/无 OKF hit、路由后端切换。
- 指标:至少报告 ReuseRate 或 TokenCost 之一相对基线变化。
- 文档:`.mq.md` 示例仍可读为 Markdown(表/链接取元,少 json 胶水)。
- 红线:不改 `doc/next/*`;ext 不调 `host_*`。
---
## 5. 落地
O1–O5 已锁定;实现见 [roadmap/ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。**仍不改** `doc/next/*`。
+104
View File
@@ -0,0 +1,104 @@
# Official AI sandbox (`ext/ai/sandbox`)
| | |
|---|---|
| Status | **Accepted · implementing** |
| Date | 2026-10-16 |
| Related | [research/ai-agent-sandbox.md](../research/ai-agent-sandbox.md) · [roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [ext-abi.md](ext-abi.md) · [browser-marqdo-wasm.md](browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [stdlib-writeback.md](stdlib-writeback.md) |
---
## 0. One-liner
**Agent-only Marqdo trial runtime:** capability-isomorphic to browser Wasm defaults, CoW workspace until explicit `commit`, author surface under `ext/ai` (not stdlib).
---
## 1. Goals / non-goals
### Goals
| # | Goal |
|---|------|
| G1 | Open a CoW session over a workspace root; edits stay in upper until `commit` |
| G2 | `run` executes `.mq.md` (or in-memory source) under deny-by-default caps with core `lib/*` usable |
| G3 | `diff` / `discard` / `inspect` for review gates |
| G4 | Stable `unavailable in sandbox` for plugin.load, exec foreign/subtask path|code|lang, net (default), `ext/web` server APIs |
| G5 | Author API in `ext/ai/sandbox` via `plugins/agent` — **no** public `lib/sandbox` |
### Non-goals (this wave)
| # | Non-goal |
|---|----------|
| N1 | Embed wasmtime in CLI |
| N2 | True Wasm ABI plugins (linalg/quantum) |
| N3 | bwrap / microVM |
| N4 | Full `ext/web` listen/DB/WS inside sandbox |
| N5 | Symlink-forest workspace isolation |
| N6 | Default host-proxy of all native ABI plugins |
| N7 | Wire `agent.step`/`plan` through sandbox automatically (later) |
---
## 2. Layering
```text
ext/ai/sandbox.mq.md → plugin.load agent → sandbox_* ABI
↓ host_query
HostContext + CowSession
(fs / writeback see upper)
```
| Layer | May call `host_*` | Role |
|-------|-------------------|------|
| `ext/ai/sandbox` | **No** | Author facade |
| `plugins/agent` | via `host_query` only | Register `sandbox_*`; forward to host |
| `src/host` | — | CoW session store; fs/writeback intercept; nested `run` |
---
## 3. Author API
EN: `ext/ai/sandbox.mq.md` · ZH: `ext/ai/沙盒.mq.md` (separate files, no mixed names in one module).
| Method | Params | Result |
|--------|--------|--------|
| `open` | optional `root=` (default entry dir / cwd) | map `{ id, root }` |
| `write` | `id=`, `path=`, `text=` | none |
| `read` | `id=`, `path=` | text |
| `remove` | `id=`, `path=` | none (whiteout) |
| `diff` | `id=` | list of `{ path, kind: write\|remove }` |
| `commit` | `id=` | `{ ok, applied }` |
| `discard` | `id=` | `{ ok }` |
| `run` | `id=`, `path=` **or** `source=` | `{ ok, value, stdout?, error? }` |
| `inspect` | `id=` | caps, root, change count, notes |
Default `run` caps: `fs_write=true` (CoW only), `exec=false`, `net=false`, `plugin=false`.
---
## 4. CoW semantics
- **lower** = real workspace root (read-through).
- **upper** = session map path → bytes.
- **whiteout** = logical deletes; reads miss; commit unlinks lower.
- No symlink-as-isolation; resolve paths under root; reject `..` escape.
- Until `commit`, host tree unchanged (verifiable with `git status` / file mtime).
---
## 5. Hard bans
1. No public `lib/sandbox`.
2. No symlink forest as the isolation story.
3. No silent success when capability missing — diagnose `unavailable in sandbox`.
4. `ext/**` must not call `host_*`.
5. Do not treat empty `# main` as sandbox completeness.
---
## 6. ABI / host_query
Plugin exports (registered on agent plugin): `sandbox_open`, `sandbox_write`, `sandbox_read`, `sandbox_remove`, `sandbox_diff`, `sandbox_commit`, `sandbox_discard`, `sandbox_run`, `sandbox_inspect`.
Implementation: each forwards to allowlisted `host_query` names of the same stem (e.g. `sandbox_open`), which mutate the process-local CoW store and (for `run`) invoke nested capture with a sandboxed `HostContext`.
+18 -2
View File
@@ -314,10 +314,15 @@ type: Marqdo Agent Skill
title: <短名> title: <短名>
sig: <12hex> sig: <12hex>
resource: ../../resources/<slug>.mq.md resource: ../../resources/<slug>.mq.md
status: stable | candidate status: stable | candidate | quarantine
llm_free: true | false llm_free: true | false
quality: <int> quality: <int>
hits: <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: generated:
by: marqdo-agent/plan by: marqdo-agent/plan
at: <ISO8601> at: <ISO8601>
@@ -331,7 +336,7 @@ verified:
Prefer spawning `resource` over re-planning. 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 路径 ### 7.3 任务签名 → Concept 路径
@@ -401,6 +406,17 @@ Prefer spawning `resource` over re-planning.
| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` | | 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` |
| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 | | 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 |
| 分发 | 整包 `agent-kb/` 可复制(格式即契约) | | 分发 | 整包 `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 -1
View File
@@ -4,7 +4,7 @@
|---|---| |---|---|
| 状态 | **Active** | | 状态 | **Active** |
| 日期 | 2026-10-15 | | 日期 | 2026-10-15 |
| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | | 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
--- ---
+145
View File
@@ -0,0 +1,145 @@
# View:叙述面标注缺口(prose annot gaps)
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [view-frame-selection.md](view-frame-selection.md) · [view-execution-trace.md](view-execution-trace.md) |
> **定位**:对既有文档面设计的**缺口专章**——写清用户可见的四类问题、根因(文件:行)与验收口径。不改写 ADR;不发明作者侧标注 DSL。
---
## 1. 为何「改了却几乎没变化」
| 原因 | 说明 |
|------|------|
| 错二进制 | PATH 上的 `marqdo` 可能仍是旧版(如 1.3.0);改动在源码 / `./target/debug/marqdo`。验收必须用 `cargo build && ./target/debug/marqdo view …` |
| Chip 被溢出藏掉 | 同 band 堆多帧 return/print/who;`MAX_VISIBLE_ANNOTS=4` 把当前帧的 `who` 打成 `annot-chip-overflow`(`display:none`);帧切换不重算溢出 |
| L-leader 几何错位 | `initAnnotLeaders` 里 `y0=0` 只在 `.annot-band` 顶画短折,**连不到**上方 underline;窄屏或 chip>4 时整段关掉 leaders |
| 旧静态快照 | gh-pages / 旧 `view output` 不会自动刷新 |
---
## 2. 目标视觉语法(既有,不新造)
锚定 [view-document-annotations.md](view-document-annotations.md) §3:
```
文本段…… `变量` …… **语句** …… *返回*
━━━━━
│
└──→ 结果标注 chip
```
- underline:`mark.mq-anchor.mq-{decl|code|return}`
- band:段落下方 `.annot-band` → leaders + chips
- L-leader:CSS `border-left` + `border-bottom`(禁止 SVG)
- 公式/代码:[view-static-interactive.md](view-static-interactive.md) G3 **一层主视觉**;卡下不叠 Bind dump
- 帧:[view-frame-selection.md](view-frame-selection.md) **源码常显、只滤 chip**;默认末帧
---
## 3. 管线
```mermaid
flowchart LR
CLI["marqdo view / view output"] --> build["build_file_view"]
build --> cap["run_file_capture"]
cap --> annot["build_view_annots"]
annot --> doc["document::render_module_document"]
doc --> page["html.rs page_file"]
page --> js["initAnnotLeaders + initCallPickers"]
```
| 步骤 | 位置 |
|------|------|
| CLI / 导出 | `src/main.rs` · `src/view/mod.rs` · `src/view/output.rs` |
| Capture + Call 事件 | `src/interp.rs` |
| Annot 组装 | `src/view/annot.rs` `build_view_annots` |
| 文档面 HTML | `src/view/document.rs` |
| 卡片 chrome | `src/view/render.rs` `render_*_assign_card` |
| CSS / leader JS | `src/view/html.rs` |
---
## 4. 四条用户问题 → 根因 → 验收
复现源:`public/00-welcome.mq.md` · `public/00-欢迎.mq.md`
对照金样:`tests/view/document-annot-demo.mq.md` · `tests/markup-v03/inc-prose.mq.md`
### P1 — 叙述与代码同段时信息不显示
| | |
|---|---|
| 现象 | underline 在,chip / 连线弱或无 |
| 根因 | `html.rs` `initAnnotLeaders`:`y0=0` 相对 band;`document.rs` `MAX_VISIBLE_ANNOTS` 把当前帧 chip 溢出;PATH 旧 CLI |
| 目标 | 同 `inc-prose`:underline + L-leader(从锚点底到 chip)+ 可见 chip |
| 验收 | `./target/debug/marqdo view public/00-welcome.mq.md`:主文 `**greet…**` 与 `## greet` 体内均有可见 chip 与接到 underline 的 leader(宽屏) |
### P2 — 函数内变量不显示
| | |
|---|---|
| 现象 | `` `who` `` 有浅蓝 underline,无值 chip |
| 根因 | bind chip 存在但带 `annot-chip-overflow`;`applyCallFrame` 只 `hidden` 非选中帧,不解除当前帧 overflow |
| 目标 | 选中调用帧时常显 `who` · `print` · `return` 各一枚 |
| 验收 | 切换「调用」下拉,三枚 chip 随帧变且默认可见(无需点 +N) |
### P3 — ` ```text ` 渲染不一致
| | |
|---|---|
| 现象 | 变成内联 `text marqdo ext add…`,无卡片 |
| 根因 | Comment 围栏若进 `flush_para` → `join(" ")` → pulldown 当 inline code;应走 `render_narrative_fence` |
| 目标 | 与 bound python 同 `.code-card` chrome(badge + `pre.code-body`),**无** Run/foot |
| 验收 | welcome install 段:`data-lang="text"` + 两行 `marqdo ext add`;无 `<code>text marqdo` |
### P4 — 函数引用 / 代码卡未渲染
| | |
|---|---|
| 现象 | `**greet who=…**` 无结果;或 `hi` python 只见头/Run、不见源码 |
| 根因 | 同行多 Call 未与 BoldCode zip;或 Run 挤在 head;静态假 Run;错看 Debug 路径 |
| 目标 | 主文两 greet 各有 call chip(stdout 摘要);`hi` = `render_code_assign_card` head→body→foot;静态藏 Run |
| 验收 | 两枚 greet mark 均有非空 `data-annot-id`;`code-body` 含 `hello-from-python`;`MARQDO_VIEW_LIVE=false` 无 Run 按钮 |
### call_id 语义(写死)
| 位置 | call_id |
|------|---------|
| 主文 `**greet…**` 的 call chip | 入口帧(`# main` 的 call);结果为 stdout/返回摘要 |
| `## greet` 体内 print / who / return | callee 的 CallFrame id;跟函数标题旁 picker |
---
## 5. 修复约定(实现红线)
1. **帧感知密度**:band 内按选中 `call_id` 计可见 chip;默认末帧;同帧最多 4 枚常显;溢出只藏非当前帧或多余 kind。切换后客户端重算 overflow + `layoutAll()`。
2. **Leader 容器**:提升到 `.doc-block`(prose + band);`y0` = 锚点底相对 block;按锚点 x 排序再画线。
3. **卡片**:只复用 Browse `render_*_assign_card` / `render_narrative_fence` + `html.rs` `.code-*` / `.formula-card`;本波不改 Debug AST 路径(除非回归红)。
4. **静态 Run**:`MARQDO_VIEW_LIVE=false` 时隐藏 Run,不留禁用假按钮(对齐 view-static-interactive D5)。
5. **非目标**:不做 debug 断点;不发明作者标注 DSL;不用 SVG leader;不单独发版/推 gh-pages(除非另嘱)。
---
## 6. 验收命令
```bash
cargo build -q
./target/debug/marqdo version # 须为当前工作树版本
./target/debug/marqdo view public/00-welcome.mq.md --no-open
./target/debug/marqdo view tests/view/document-annot-demo.mq.md --no-open
cargo test -q --lib view::
```
---
## 7. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:四问题、错二进制/溢出/leader 根因、帧感知密度与 leader 几何约定 |
| 2026-10-15 | L-leader 拥挤/消失:同跨度多帧 chip **共用 annot id**;可见 chip 按锚点 x 重排;leader 挂 doc-block |
| 2026-10-15 | L-leader 黑线碎段:JS `border*: "1.5px solid"` 无色覆盖 class → 改为 kind 色写入 shorthand;chip SSR/DOM 按锚点 L→R |
| 2026-10-15 | L-leader 改为 SVG:描述底边中点 → 轨道 → 短竖线 → 值 chip 顶边中点;chip 间距加宽 |
@@ -0,0 +1,117 @@
# 缺陷记录:`agent.run` EFI / resolve 在消费方崩溃(qdagent 复现)
| | |
|---|---|
| 状态 | **Fixed(2026-10-16)** — 见 §3;金样 `tests/ext/agent-run-cold-efi.mq.md` |
| 日期 | 2026-10-16 |
| 发现方 | qdagent(`~/work/qdagent`)接通 Marqdo ≥1.4.2 Agent EFI 全路径时 |
| 影响面 | `ext/ai/agent` · `## run` · `plugins/agent` `agent_resolve` |
| 相关 | [ext-agent.md](../design/ext-agent.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) |
---
## 0. 一句话
`agent.run` 在 **空 OKF / 无 skill 命中** 或 **`efi=True`** 时,会以硬错误退出,而不是降级到 `plan` 探索。
这是 **Agent Runtime 契约不完整**,不是 qdagent 业务写错。
---
## 1. 复现(qdagent)
环境:工作区 Marqdo `1.4.2` + `MARQDO_EXT=~/work/marqdo/ext`;qdagent 调用:
```text
助手 = > agent.agent …
`助手`.run task=… efi=True # 或 efi=False 后仍进 resolve
```
本仓几乎没有 `.marqdo/agent-kb` 编译 skill。
### Bug A — `efi=True` → `unknown function preflight`
**位置**:[`ext/ai/agent.mq.md`](../../ext/ai/agent.mq.md) `## run`
```markdown
1. `efi`
**efi_pf = preflight task=`task`**
```
同文件其它同对象方法一律写 `` `self`.route `` / `` `self`.resolve ``。
裸标识 `preflight` 在导入消费方(如 `cli/求道-构建.mq.md`)里被解析成**全局函数**,找不到 → 硬错。
**期望**:`` **efi_pf = > `self`.preflight task=`task`** ``(或等价 method call)。
### Bug B — miss resolve → `missing map key llm_free`
**位置**:
1. Plugin:[`plugins/agent/src/memory.rs`](../../plugins/agent/src/memory.rs) `resolve_task`
当 `kb_lookup` 返回 null:
```rust
Ok(json!({
"mode": "unknown",
"skill": null,
"resource": null,
"confidence": 0.0,
// 缺 llm_free
}))
```
2. Facade:`## run` 在 resolve 之后:
```markdown
**llm_free = [llm_free](resolved)**
```
脚注式取键在缺键时 **硬失败**,无法落到后面的 `plan` 探索臂。
**期望**:
- miss 结果始终带 `"llm_free": false`(与命中路径字段集对齐)
- facade 侧对可选键用 `json.get`(缺省 `False`),防御其它调用方
---
## 2. 为何金样没拦住
| 金样 | 为何漏网 |
|------|----------|
| `tests/ext/agent-zero-llm.mq.md` | 先编译 skill / policy,再 `run`;resolve **命中** |
| `tests/ext/eng-preflight.mq.md` | 只测 `agent_eng_preflight`,**不**走 `agent.run efi=` |
| 多数 `agent-*-live` | 自带 kb 或 `efi=False` / 不经过 cold miss |
qdagent 是第一个「冷库 + 产品 EFI + `run`」消费方,因此打穿。
---
## 3. 修复清单(本轮)
| # | 改动 | 文件 |
|---|------|------|
| 1 | miss resolve 补 `llm_free: false` | `plugins/agent/src/memory.rs` |
| 2 | `` `self`.preflight ``;`llm_free`/`mode` 用 `json.get` | `ext/ai/agent.mq.md` |
| 3 | 回归金样:冷 kb + `run efi=True` 不崩溃,落到 explore/plan | `tests/ext/agent-run-cold-efi.mq.md` |
| 4 | 重建 `marqdo_plugin_agent` 并跑金样 | `cargo build -p marqdo_plugin_agent --release` |
---
## 4. 对 qdagent 的含义
修复后 qdagent 可恢复:
```text
product preflight → latch → agent.run (efi=True|False) / plan
```
而不必长期绕开 `agent.run`。
在插件未装入新 so 前,qdagent 侧 EFI latch + `step`/`plan` 仍是合法降级。
---
## 5. 非目标
- 不改 EKC / `agent_eng_preflight` 语义
- 不引入第二套 Agent loop
- 不把向量检索升为权威真相
@@ -0,0 +1,136 @@
# 调研:代码即文档 × OKF × 沙盒 下的智能体 / 大模型优化(2026-10)
| | |
|---|---|
| 状态 | **调研 + 问题分析 · 供方案 [ext-ai-optimize.md](../design/ext-ai-optimize.md) 参考** |
| 日期 | 2026-10-16 |
| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [agent-framework-2026-09.md](agent-framework-2026-09.md) · [ai-agent-sandbox.md](ai-agent-sandbox.md) · [okf-and-marqdo.md](okf-and-marqdo.md) |
| 本仓能力 | [ext-agent.md](../design/ext-agent.md) · [okf.md](../design/okf.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) |
| 外部抽样 | Anthropic Agent Skills · SoK Agentic Skills (arXiv 2602.20867) · ForgeAgent · ACES / Skill Lift · Switchcraft 路由 · DSPy/GEPA ·「工作流编译进权重」· MalSkillBench |
---
## 0. 一句话
业界正把 Agent 优化从「更好的 chat loop」转向 **可验证、可复用、可隔离执行的技能层**;Marqdo 已具备 **可执行 Markdown(代码即文档)+ OKF/EKC 复用 + CoW 沙盒** 三件套,优化目标应是把这三件套焊成闭环:**试跑 → 证据 → 晋升 → 零/少 LLM 复用**,而不是追平 LangChain 功能清单。
---
## 1. 调研方法
| 动作 | 说明 |
|------|------|
| 扫业界技能层 | Anthropic Skills(渐进披露 `SKILL.md`);SoK Agentic Skills 生命周期;ForgeAgent「能力铸造」;ACES Skill Lift |
| 扫成本/路由 | Switchcraft 工具调用路由;DSPy+GEPA 提示优化;工作流编译进小模型权重 |
| 扫安全 | MalSkillBench 运行时验证恶意技能;沙盒粒度讨论(per-skill / per-session) |
| 对照本仓 | A0–A4 / Wave B 已落地;沙盒 S0–S4 已落地;OKF + EKC + adaptive routing 现状 |
**不修改** `doc/next/*`(手写真相源);本文件只进 `doc/research/`。
---
## 2. 业界态势(与 Marqdo 相关的收敛点)
### 2.1 技能层取代「纯工具调用叙事」
| 来源 | 要点 | 对 Marqdo |
|------|------|-----------|
| Anthropic Agent Skills | 目录 + `SKILL.md`;元数据预载、正文按需;脚本可执行 | 形态近 OKF 任务包,但 Marqdo 技能 **本身可跑** |
| SoK Agentic Skills | 发现→练习→蒸馏→存储→组合→评测→更新;代码技能需沙盒 | 生命周期与 OKF promote / sandbox.run 对齐 |
| ForgeAgent | 生成能力 → 沙盒证明 → 信任复用;失败进回归隔离 | **验证后晋升** 正是 solidify / `llm_free` 缺的硬闸 |
| ACES | 有/无技能配对试验 → Skill Lift | 可作 Marqdo 评测 harness 指标 |
### 2.2 成本:路由 + 编译 + 小模型
| 来源 | 要点 | 对 Marqdo |
|------|------|-----------|
| Switchcraft | 工具调用场景路由到最便宜仍正确的模型;报道大幅降本 | 已有 `marqdo \| small-llm \| llm \| auto`;可加 **工具步/试跑步** 细分 |
| DSPy / GEPA | 用反馈改写指令,小模型追上大模型 | 优化对象应是 **`.mq.md` 提示文档 / standing / 路由策略文件**,不是黑盒字符串 |
| 工作流编译进权重 | 程序化流程进小模型权重,上下文常数级 | 长期对应「高频 OKF 技能 → 专用小模型」;短期优先 **llm_free 源码路径** |
### 2.3 安全:技能不可信 + 沙盒必验
恶意技能基准与 SoK 均强调:**技能说明与代码默认不可信**,须运行时隔离。Marqdo 新沙盒(默认拒 plugin/net/exec)正好是技能晋升前的证明场。
---
## 3. Marqdo 已有资产(优化起点)
| 资产 | 现状 | 优化杠杆 |
|------|------|----------|
| 代码即文档 | `.mq.md` = 程序 = 提示工作面;GFM 表 / 链接取元 | 减少 json 胶水;让模型「看见」结构 |
| 写回 | `marqdo-out` 槽;step 默认写回 | 晋升证据、失败避坑 |
| OKF / agent-kb | 命中 / near / promote / solidify / `llm_free` | 复用率、降本主轴 |
| EKC / EFI | L0–L4 catalog;preflight REUSE/ADAPT/CREATE | 生成前先查工程知识 |
| Adaptive routing | marqdo / small-llm / llm / auto + policy 文件 | 再细分 sandbox 试跑 vs 开放推理 |
| Sandbox | CoW + capped `run`;`ext/ai/sandbox` | **试跑闸门**;未 commit 不污染仓库 |
| MCP / corpus | 证据工具,`authority=workbook` | 保持不升权威 |
---
## 4. 问题分析(差距,不是功能羡慕)
### P1 — 试跑与晋升未焊死
沙盒已能 CoW 试跑,但 **`agent.step` / `plan` 默认仍可直接改真实树**;OKF `llm_free` 晋升不强制「沙盒金样绿」。
→ 风险:未验证技能进入复用池(业界 ForgeAgent / MalSkillBench 已证明此问题)。
### P2 — 技能形态双轨
Anthropic Skills = 文件夹 + 渐进披露;Marqdo = 可执行 `.mq.md` + OKF 类型。
→ 机会:用 **OKF frontmatter + 可执行体** 统一,不必引入第二套 SKILL.md 权威;缺的是 **披露层级与验证元数据**(适用条件、fixture、sandbox profile)。
### P3 — 路由粒度偏粗
现有路由偏「整任务后端」;未区分:查 OKF / 写补丁 / 沙盒 `run` / 对外 HTTP。
→ Switchcraft 启示:按 **步骤类型** 选模型,且「便宜模型推理 token 爆炸」要计入总成本。
### P4 — 评测未锁差异化
Wave B1 仍 Active:缺稳定 **Skill Lift / 沙盒证明率 / llm_free 命中率 / 文档可读性** 指标。
→ 没有指标,优化会滑回「多调几次模型」。
### P5 — 代码即文档在 Agent 产出侧仍易腐化
模型仍可能吐 `json.set` 链、混用 EN/ZH API、跳过表结构。
→ 沙盒可跑通语法,但 **风格门禁**(lint / preflight)未默认卡在 commit 前。
### P6 — 上下文与 EKC 未默认进每步
EFI / catalog 能力在,但 step 默认上下文仍可能偏源码切片,缺少「先 REUSE」硬门槛。
### P7 — LLM 表面与 Agent 成本账未统一
`llm.ask` / `stream` / usage 已有;Agent 侧缺 **按会话/技能的成本仪表盘** 写回文档(可 git 审)。
---
## 5. 优化目标函数(建议)
在固定任务集上最大化:
\[
\begin{align*}
& \text{ReuseRate}(\text{OKF hit} + \text{llm\_free}) \\
&+ \text{SandboxProofRate}(\text{试跑绿再 commit/promote}) \\
&- \lambda_1 \cdot \text{TokenCost} - \lambda_2 \cdot \text{HostMutationsWithoutCommit}
\end{align*}
\]
约束:权威真相仍是 `.mq.md`;不引入隐藏 TOOL 主循环;不改 `doc/next/*`。
---
## 6. 外部资料索引(抽样)
| 类型 | 链接 |
|------|------|
| Skills | [Anthropic engineering: Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) · [Claude Code skills](https://code.claude.com/docs/en/skills) · [agentskills / anthropics/skills](https://github.com/anthropics/skills) |
| 论文 | [SoK: Agentic Skills](https://arxiv.org/html/2602.20867) · [Skill Issue (repo SKILL 优化)](https://arxiv.org/html/2609.12742v1) · [ACES Skill Lift](https://arxiv.org/html/2608.20614) · [MalSkillBench](https://arxiv.org/html/2606.07131v3) · [Compiling workflows into weights](https://arxiv.org/html/2605.22502) |
| 开源/产品 | [ForgeAgent](https://github.com/Yashasm18/ForgeAgent) · [DSPy GEPA](https://dspy.ai/current/getting-started/gepa-optimization/) · [Switchcraft](https://www.microsoft.com/en-us/research/publication/switchcraft-ai-model-router-for-agentic-tool-calling/) |
---
## 7. 结语
Marqdo 不缺「再一个 Agent SDK」;缺的是把 **文档真相、知识晋升、沙盒证明、模型路由** 收成可度量闭环。下一篇方案文档按问题编号给出可选方向与推荐波次,**不预设唯一银弹**。
+392
View File
@@ -0,0 +1,392 @@
# 调研:AI 扩展库沙盒设计(执行隔离 × 工作区暂存 × 写回)
| | |
|---|---|
| 状态 | **调研笔记 · 供 `ext/ai/*` 沙盒设计锁定参考**(**2026-10-16 修订**:纳入「AI 只生成 Marqdo」产品约束) |
| 日期 | 2026-10-16 |
| 范围 | 浏览器 WASM / WASI、OS 进程沙盒、容器 / microVM、CoW 叠加工作区、符号链接暂存方案;对照 Marqdo AI 栈 |
| 相关设计 | **[ext-ai-sandbox.md](../design/ext-ai-sandbox.md)** · **[roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md)** · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [stdlib-writeback.md](../design/stdlib-writeback.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [adr/0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-modules.md](../design/stdlib-modules.md) |
| 姊妹调研 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) · [ext-ai-optimize.md](../design/ext-ai-optimize.md) |
---
## 0. 一句话结论
**在「Agent 只生成 / 只执行 Marqdo(`.mq.md`)」这一产品约束下,Marqdo AI 沙盒应以 Wasm 为主沙盒——且必须是「内核 + `lib/*` + `ext/*`」可运行的完整运行时沙盒,而不是只跑光秃解释器。**
锁定方向:
1. **执行隔离 = Marqdo Wasm 运行时(与 ADR 0002 同构)** — deny-by-default 能力导入;**默认不授予** shell / 外联 / `dlopen` 原生插件。AI 产出面收窄到 Markdown 程序后,不必为通用 coding Agent 的「任意二进制」付沙盒税。
2. **库完备性是验收线,不是加分项** — 沙盒内须能 `import lib/…` 与受支持的 `ext/…`;缺能力时 **显式失败**,禁止静默空成功(对齐 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5)。
3. **工作区突变 = CoW / whiteout / 显式 commit**(应用层 VFS,必要时 overlay)— 「修改短暂不生效 → 确认写回」保留;**禁止以符号链接森林作为隔离边界**。
4. **OS 沙盒 / microVM** — 降为 **逃逸舱 / 托管 Profile**:仅当显式启用 foreign、`subtask` 真子进程、或未来多租户托管时使用;**不是** Marqdo-only Agent 的默认主路径。
初稿曾按「通用 coding Agent 还需 shell」把 Wasm 与 bwrap 并列;在 Marqdo-only 约束下,主结论改为 **Wasm-first + 库完备 + CoW 写回**。
---
## 1. 调研方法与边界
### 1.1 做了什么
| 动作 | 说明 |
|------|------|
| 厂商/产品文档 | Anthropic Claude Code sandbox / `@anthropic-ai/sandbox-runtime`;VS Code Copilot agent sandboxing;Docker AI Sandboxes;Turso AgentFS CoW overlay;OpenSandbox isolation sessions;WASI / jco preview2-shim;VS Code for the Web WASM webshell |
| 工程对比文 | Northflank / Cosmonic 2026 agent sandbox 指南;gVisor vs Firecracker vs Docker 对比;ContainAI security comparison |
| 学术与标准 | USENIX SEC'22 *Provably-Safe Multilingual Software Sandboxing using WebAssembly*;KTH 论文 *Intra-process Fault Isolation Using WebAssembly*(SFI 通信开销);ACM TOSEM *Research on WebAssembly Runtimes: A Survey*(2025);WASI Design Principles(capability / 无 ambient authority) |
| 安全案例 | brig 项目挂载 symlink 逃逸(CVSS 8.2);Anthropic sandbox-runtime 对 bwrap bind 跟随 symlink 的修复;Docker Sandbox「direct mount vs clone」威胁说明 |
| 对照本仓 | `ext/ai/{llm,agent}`、`lib/writeback`、`lib/subtask`、ADR 0002 浏览器 WASM、`RunOptions.allow_fs_write` 默认关 |
### 1.2 不做的
- 不把「发版用的容器镜像」与「Agent 工具沙盒」混为一谈。
- 不宣称某一云厂商托管沙盒(E2B / Modal / Daytona)为 Marqdo 默认依赖。
- 不修改 `doc/next/*`(手写真相源);本文件只进 `doc/research/`。
### 1.3 产品约束(修订要点):AI 只生成 Marqdo
这是相对通用 coding Agent(Claude Code / Codex)的 **结构性好消息**:
| 通用 Agent | Marqdo AI Agent(本调研采纳) |
|------------|------------------------------|
| 模型可产出 shell / Python / 任意仓库补丁 | 模型产出面收束为 **`.mq.md`(文档即程序)** |
| 沙盒必须兼容「整台开发机能力」 | 沙盒只需跑 **同构 Marqdo 运行时** |
| Wasm 往往只能罩住工具子集 | Wasm **可以**成为主执行边界 |
| 标准库 = 语言运行时 + OS 工具链 | 标准库 / 扩展 = **`lib/*.mq.md` + `ext/**`(+ 受控宿主能力)** |
硬规则建议(后续 design 应写死):
1. Agent 工具表 **不提供** 通用 `bash` / 任意语言 `exec`(除非显式 opt-in 逃逸舱,且另套 OS 沙盒)。
2. Agent 改仓库的权威动作是 **写 / 修订 `.mq.md`(含写回块)**,经 CoW 会话再 `commit`。
3. 运行 Agent 生成的程序 = 在沙盒里 `run` 该 `.mq.md`,且其 `import` 的 **lib 与 ext 必须可用或显式报不可用**。
### 1.4 威胁模型(在 Marqdo-only 下收窄)
| 威胁 | 典型路径 | Marqdo-only 下的权重 |
|------|----------|----------------------|
| T1 提示注入 | 诱导读密钥、外泄、破坏 `.mq.md` | 仍高 — 靠能力拒绝 + CoW |
| T2 工具侧信道 | `subtask`/`foreign` 子进程 | **默认关闭**;opt-in 才升权 |
| T3 工作区即时破坏 | 直接写穿源树 | 靠 CoW;commit 闸门 |
| T4 挂载逃逸 | symlink / bind 打穿 | 仍相关 — **勿用 symlink 作 W 层** |
| T5 网络外泄 | `lib/net` / llm 出站 | 能力开关 + 域名策略 |
| T6 Wasm 宿主桥过宽 | `host_fs_*` / 插件桥过宽 | **主威胁** — 桥 = 权限表 |
| T7 库残缺假安全 | 沙盒能跑 `# main` 但 `import lib/fs` 怪崩或静默空 | **产品验收威胁** |
**成功标准:** 失败域止于会话 upper + 已授予能力;真实工作区默认只读直至 commit;**代表性 `lib/*` 与 `ext/*` 金样在沙盒内可跑或得到明确 `unavailable in sandbox` 诊断**。
---
## 2. 先拆三个「沙盒放哪里」(Marqdo-only 版)
业界「Harness / Workspace / Execution」三分法仍成立,但 **Execution 的内容变了**:
```text
┌──────────────────────────────────────────────────────────┐
│ Pattern H — Harness(编排环) │
│ ext/ai/agent · parent Plan-and-Move ·(可选)MCP client │
├──────────────────────────────────────────────────────────┤
│ Pattern W — Workspace mutation(.mq.md 真相如何变) │
│ CoW upper / whiteout / diff / commit → writeback │
├──────────────────────────────────────────────────────────┤
│ Pattern X — 执行 Agent 产出的 Marqdo 程序 │
│ Wasm Marqdo runtime + embedded/packaged lib + sandboxed │
│ ext 能力面(非「任意 shell」) │
└──────────────────────────────────────────────────────────┘
```
| Pattern | Marqdo 落点 | 沙盒要解决什么 |
|---------|-------------|----------------|
| H | `ext/ai/agent` | 编排是否持有过宽宿主权限;模型 I/O 与执行隔离 |
| W | `lib/writeback` · 工作簿 | 编辑是否立刻污染仓库;人审/父裁决后落盘 |
| X | **Wasm 内 `run` `.mq.md`** | 计算隔离;**lib/ext 能力是否完备且受控** |
用户提案在 Marqdo-only 下:**Wasm 作 X 主底层是正确方向**;仍须改掉 symlink,并补上 **库完备性** 这一环。
---
## 3. 方案谱系(横向对比)
> **读法(修订后):** 下表仍保留通用 Agent 对照。对 **Marqdo-only** 产品,请以 §0 / §5 / §6 的 Wasm-first 结论为准;本节 A/B 升权,F/G/H 降为逃逸舱或托管。
评分:● 强 / ◐ 中 / ○ 弱 / — 不适用。维度按「隔离强度」等客观属性;**产品适配**见 §5。
| 方案 | 隔离强度 | 启动成本 | 任意二进制 | 工作区暂存语义 | 与 Marqdo 契合 | 主要风险 |
|------|----------|----------|------------|----------------|----------------|----------|
| **A. 浏览器 WASM + 虚拟 FS** | ●(计算)◐(经桥的 FS) | ● | ○ | ◐(需自建 overlay) | ●(已有 ADR 0002) | 宿主桥过宽;无原生 toolchain |
| **B. WASI / Component Model(非浏览器亦可)** | ● | ● | ○(仅 WASI 目标) | ●(preopens + 自建 VFS) | ● | 工具链不全则需降级 |
| **C. 符号链接映射工作区 + 延迟写回** | ○ | ● | —(本身不是执行沙盒) | ◐(似是而非) | ○ | **symlink 逃逸是已知高危类** |
| **D. 应用层 CoW VFS(upper/lower/whiteout)** | ◐(逻辑) | ● | — | ● | ●● | 必须配合 X 层 OS 隔离 |
| **E. OS overlayfs / FUSE / AgentFS 式 CoW** | ●(配合命名空间) | ◐ | ●(在沙盒内) | ●● | ● | Linux/macOS 实现分叉;运维 |
| **F. bubblewrap / Seatbelt(Anthropic SRT 类)** | ● | ● | ● | ○(默认可写 cwd) | ● | 需另加 CoW 才有「暂不生效」 |
| **G. Docker / 硬化容器 / gVisor** | ◐→● | ◐ | ● | ◐(volume 策略) | ◐ | 共享内核或兼容性;重 |
| **H. microVM(Firecracker / Kata)** | ●● | ◐ | ● | ◐ | ○(本地 CLI 过重) | KVM/运维;适合多租户托管 |
| **I. 纯语言沙盒(RestrictedPython 等)** | ○ | ● | ○ | — | ○ | 对 Agent 工具链几乎无用 |
### 3.1 A — 浏览器 WASM + 虚拟 FS
**机制:** Wasm 线性内存 + 校验 + 仅经 import 碰宿主;FS 多为内存树 / OPFS / 经 JS bridge 的映射。Marqdo 已锁定「解释器进 WASM」(ADR 0002),默认 `allow_fs_write=false`。
**文献支撑:** Wasm 作为 SFI 窄腰(Bosamiya et al., USENIX SEC'22);进程内沙盒跨边界通信可比 IPC 快数量级(KTH Wasm-SFI 论文);WASI 明确 **capability / 无 ambient authority**。
**优点:** 与「代码即文档」浏览器运行同构;deny-by-default;适合跑 `.mq.md`、公式库、受控插件。
**缺点:** 不能原生跑 `cargo test` / `npm` / 任意 shell;安全上限取决于 **bridge 授予了什么**;浏览器场景下「符号链接用户工作区」通常要落到 File System Access API 或服务端中继,**不是** POSIX symlink 语义。
**判定:** 在 **Marqdo-only** 约束下,作为 **Pattern X 主沙盒** 与浏览器内 Marqdo 的正解;完备性取决于 **lib 嵌入 + ext 能力桥**(§4.1),不取决于 shell。通用「任意二进制 Agent」场景下仍不够——但那不是本产品默认。
### 3.2 B — WASI / Component Model(CLI 宿主)
**机制:** preopens 显式挂载;`WASIShim({ sandbox: { preopens, enableNetwork: false } })`(Bytecode Alliance jco);Component imports = 权限表。
**优点:** 与 Wasm 同族,可在 Node/Wasmtime 跑,不绑浏览器;能力模型清晰。
**缺点:** 同 A,任意 Linux 工具链需「宿主机再包一层」或改编译目标。
**判定:** Marqdo **官方扩展 / 插件中可 Wasm 化的部分**应走这条;与 ADR 0002 一条能力谱。
### 3.3 C — 符号链接映射工作区(用户设想的核心)
**设想:** 沙盒根下用 symlink 指向用户文件;写改暂存别处;确认后写回;删除 = 删 symlink。
**表面吸引力:** 零拷贝读、实现「像」有暂存。
**为何行业不把它当隔离原语:**
1. **Bind/mount 跟随 symlink 是经典逃逸。** Anthropic `sandbox-runtime` 明确修复:`allowWrite` 若为指向界外的 symlink,bwrap `--bind` 会把真实目标变成可写(PR #138 类修复)。
2. **项目挂载未解析 symlink 可致高危。** Endor Labs 披露 brig「project mount symlink traversal」(CVSS 8.2):Agent 在可写项目内把子目录换成指向 `/etc` 的 symlink,下一轮宿主机按字符串挂载即打穿。
3. **「删除 = 删 symlink」语义错误。** 删链接只去掉别名,**不等于**对 lower 层文件的 whiteout;若链接指向真实文件且曾被打开写穿,删除链接也救不回。
4. **写穿风险。** 若某路径被解析成真实 inode 且可写,暂存承诺立刻破产。
5. **跨平台。** Windows junction/reparse、浏览器虚拟 FS、容器 bind,行为不一致。
**判定:** **否决作为 Marqdo 默认工作区隔离方案。** 允许在 **只读、已解析、拒绝可写路径上的 symlink 组件** 的前提下作实现细节,但不得当作安全边界叙事。
### 3.4 D — 应用层 CoW VFS(推荐作 W 层默认)
**机制:**
```text
lower = 真实工作区(只读打开 / 只读能力)
upper = 会话 delta(内存 map / 目录树 / SQLite blob)
whiteout = 逻辑删除集合
view(path) = upper ?? (!whiteout && lower)
commit() = 把 upper/whiteout 应用到 lower(可经人审)
discard() = 丢弃会话
diff() = 可审变更集
```
与 Turso AgentFS、OpenSandbox `workspace.mode: overlay` 的 **语义同构**,但不强制 FUSE。
**与 Marqdo 对齐点:**
| VFS 操作 | Marqdo 真相 |
|----------|-------------|
| `diff()` | 父 Agent / 人审材料;可进 view |
| `commit()` 文本结果 | `writeback.record` / 工作簿补丁 |
| `discard()` | 失败回合不污染仓库 |
| 只读 lower | 防止 T3 即时破坏 |
**优点:** 纯用户态、可测、可嵌入 `plugins/agent`;不依赖 root/FUSE;金样可锁。
**缺点:** 对 **沙盒内原生工具**(它们走真实 POSIX)不可见,除非再挂 E 或把工具 I/O 也改走 VFS API。
**判定:** **Pattern W 的默认实现。**
### 3.5 E — OS CoW overlay(AgentFS / overlayfs / OpenSandbox)
**机制(AgentFS 公开设计):** lower=宿主只读;upper=SQLite delta;删除=whiteout;Linux 用 FUSE+user/mount ns;macOS 用 NFS+`sandbox-exec`。OpenSandbox 默认 `overlay`,会话结束可丢 upper。
**优点:** 对 **任意 shell 工具**透明;「改了但宿主机 `git status` 仍干净」体验业界已验证。
**缺点:** 平台依赖;FUSE 权限;与应用层 D 双实现成本。
**判定:** **当 Pattern X 需要真实 shell 且要求暂存对工具透明时**启用(Linux 优先);作为 D 的「native 加速后端」,不是替代 Wasm。
### 3.6 F — OS 进程沙盒(bwrap / Seatbelt / VS Code Copilot)
**机制:** Anthropic:文件系统隔离 + **网络隔离(缺一不可)**;Linux bubblewrap + 代理;macOS Seatbelt。VS Code Copilot:同类依赖;路径分 readwrite / readonly / denied;明确「不是 VM,削弱授权即削弱边界」。
**优点:** 本地编码 Agent 的事实标准;覆盖子进程;启动轻。
**缺点:** 默认可写 cwd → **没有**「暂不生效」;必须与 D/E 组合。Symlink 配置路径需解析与拒绝。
**判定:** **Pattern X(shell/外联/MCP)本地默认。**
### 3.7 G / H — 容器与 microVM
**共识:** 裸 Docker 共享内核,不适合作唯一边界应对不可信代码;gVisor 加强 syscall 拦截;Firecracker/Kata 适合多租户与高威胁(~125ms 级启动)。Docker AI Sandboxes 区分 **direct mount(即时写穿)** vs **clone(只读源 + 私有副本)**——后者才接近「确认后写回」。
**判定:** Marqdo **本地 CLI 默认不强制 microVM**;若未来 `ext` 提供托管执行 / 多租户,再把 H 定为服务端 Profile。G 可作为打包/CI Profile。
### 3.8 I — 语言级沙盒
对「Agent 会跑 shell」场景基本无效;仅作极窄解释器内嵌参考。
---
## 4. 专门评估:用户提案(修订)
> 浏览器 WASM 作沙盒底层 + 符号链接用户工作区 + 修改短暂不生效 + 确认后写回 + 删除变删 symlink。
> **补充约束:** AI 只生成 Marqdo;沙盒须能用标准库与扩展库。
| 子命题 | 评价 | 说明 |
|--------|------|------|
| Wasm 作主执行隔离 | **在 Marqdo-only 下正确** | 与 ADR 0002 同构;不必为 shell 全集付税 |
| 沙盒须含 lib + ext | **正确且关键** | 「能跑 `# main`」≠ 好沙盒;见 §4.1 |
| 「短暂不生效」 | **正确** | CoW / staging(方案 D,必要时 E) |
| 「确认后写回」 | **正确且极契合 Marqdo** | 与 writeback、父裁决、workbook 同一哲学 |
| 「symlink 映射工作区」 | **仍错误** | 与是否只用 Marqdo 无关;换 CoW/whiteout |
| 「删除 = 删 symlink」 | **仍错误** | 应为 whiteout;commit 时再对 lower 删除 |
| 「性能最好且安全性最高」 | **Wasm 主路径下接近成立** | 前提是桥最小权限 + CoW;symlink 仍拉低安全 |
**修订后的正确表述:**
> **以 Wasm Marqdo 运行时为主沙盒,打包/嵌入 `lib/*`,经能力桥提供受支持的 `ext/*`;工作区用 lower 只读 + upper/whiteout;人审/父裁决后 commit。符号链接不作隔离原语。shell/外联/原生 dlopen 默认关闭,仅作显式逃逸舱。**
### 4.1 库完备性:什么叫「标准库和扩展库也能用」
沙盒若只能跑内置算术、却不能 `import lib/json` 或跑 `ext/ai/llm` 的离线金样,对 Agent 开发几乎无用——模型生成的 `.mq.md` **本来就会依赖 lib/ext**。
三类库进沙盒的路径不同:
| 类别 | 今日形态 | 沙盒策略 |
|------|----------|----------|
| **纯 `.mq.md` 库**(多数 `lib/*`、部分 `ext` 门面) | 源码 import | **嵌入或会话导入图**(已有 `embedded_lib` / import map)— 必须默认可用 |
| **需宿主能力的 lib**(`fs` / `net` / `writeback` / `subtask` / `datetime.now`…) | `host_*` | **经能力表桥接**到会话 VFS / 受控 clock / 受控 fetch;默认最小集 |
| **原生 ABI 扩展**(`plugins/web`、`plugins/agent`、quantum 等 `.so`) | `plugin.load` + dlopen | 浏览器/Wasm **无 dlopen**(ADR 0002 N2)。沙盒内应:**纯 mq 门面 + Wasm 插件**、或 **宿主代执行且权限计入会话**、或 **显式 `unavailable`** — 禁止假装成功 |
与 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5 对齐并扩展为 **Agent 沙盒能力矩阵(草案)**:
| 能力 | 沙盒默认 | 备注 |
|------|----------|------|
| builtins / 表 / 控制流 / 对象 | ✓ | 内核 |
| `lib/math` `json` `table` `text` `collection`… | ✓ | embedded |
| `lib/fs` | ✓(仅会话 VFS) | 写进 upper;禁越出 root |
| `lib/writeback` | ✓(写会话内 `.mq.md`) | commit 后才进真实树 |
| `lib/net` / llm HTTP | 默认关 / 域名白名单 | 与 T5 |
| `lib/subtask` `fn=` | ✓(同 Wasm 会话) | |
| `lib/subtask` `path=`/`code=`/`lang=` | **默认拒** | 逃逸舱 + OS 沙盒 |
| `lib/plugin` + 原生 `.so` | **默认拒** | 改 Wasm 插件或宿主代执行 |
| `ext/ai/llm` · `ext/ai/agent`(mq 门面) | ✓(能力允许时) | 网络/密钥另授 |
| `ext/web` 服务端 listen/DB | **默认拒或只读 stub** | 完整 axum 不进沙盒;可测「装配/渲染」子集 |
| `ext/quantum` / `ext/linalg` | 目标 ✓ | 优先纯逻辑 / Wasm 插件,避免强依赖宿主机 .so |
**验收金样建议(S 阶段):**
一套「沙盒烟囱」:`import` 常用 lib → 写会话文件 → writeback → `diff` → `commit`;再各挑一个 **纯逻辑 ext** 与一个 **需网络的 ext**(后者验证拒绝/白名单)。缺能力必须诊断含 `unavailable in sandbox`(或同等措辞)。
---
## 5. 综合评分(面向 Marqdo-only 产品)
加权(修订):执行隔离契合 Marqdo-only 30%、**lib/ext 完备** 25%、与 writeback 真相 20%、实现成本 15%、跨端(CLI↔浏览器)10%。
(「任意 shell 工具完备」不再作为主权重。)
| 候选架构 | 分(相对) | 备注 |
|----------|------------|------|
| **A/B Wasm-first + D CoW + 库完备能力表** | **100(推荐)** | 主路径 |
| 同上 + 逃逸舱 F(opt-in shell) | 95 | 兼容少数 foreign 需求 |
| D + E + F(通用 coding 向) | 75 | 过重;非 Marqdo-only 默认 |
| 仅 F(可写 cwd) | 55 | 缺 CoW;且鼓励非 mq 工具 |
| 仅 A 但无 CoW、无 lib 嵌入 | 40 | 「半沙盒」 |
| 仅 C(symlink) | 20 | 否决 |
| 仅 H(人人 microVM) | 50 | 托管可选;本地默认过重 |
**绝对「最硬」单点**仍可以是 microVM(托管 Profile)。
**Marqdo「最合适」:** **Wasm 完整运行时沙盒(内核+lib+受控 ext)+ CoW 工作区 + commit 闸门**。
---
## 6. Marqdo 应采用的沙盒设计(推荐锁定草案 · 修订)
### 6.1 产品形态
| Profile | 场景 | 执行(X) | 工作区(W) |
|---------|------|-----------|------------|
| **`mq-sandbox`(默认)** | Agent 生成并试跑 `.mq.md` | **Wasm Marqdo** + embedded `lib/*` + 能力桥 `ext` | 应用层 CoW;commit→真实树 / writeback |
| **`browser`** | 页内同构运行 | 同左(ADR 0002) | 内存/OPFS;无 POSIX symlink |
| **`escape`(显式)** | foreign / 真子进程 | OS 沙盒包一层 | 仍建议 CoW 可见 |
| **`hosted`(可选)** | 多租户 | Wasm 或 microVM | 会话隔离;凭证外置 |
### 6.2 推荐架构图
```text
┌──────────────────────────────────────┐
│ ext/ai/agent (Harness) │
│ 只产出 / 编排 .mq.md · 人审闸门 │
└──────────────────┬───────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼
┌────────────────────┐ ┌────────────────────┐
│ Workspace CoW (W) │ │ Marqdo Wasm (X) │
│ lower = RO 工作区 │◄── fs/writeback ───│ 同构解释器/VM │
│ upper / whiteout │ 能力导入 │ + embedded lib/* │
│ diff·commit·discard│ │ + ext 能力面 │
└─────────┬──────────┘ │ 默认: 无 shell/so │
│ └────────────────────┘
▼
真实工作区 / <!-- marqdo-out -->
(代码即文档真相源)
(可选)escape: subtask path|code|lang → OS sandbox
```
### 6.3 API 面建议(设计级,非立即实现)
落点倾向:宿主能力进 `plugins/agent` / Wasm HostContext;作者面经 `ext/ai` 或 `lib`(**禁止** `ext/**` 直调 `host_*`)。
| 概念 | 语义 |
|------|------|
| `sandbox.open(root, mode=cow)` | 打开会话;lower 只读 |
| `sandbox.read/write/list/remove` | 经 view;remove → whiteout |
| `sandbox.diff` / `stat` | 供父 Agent / view |
| `sandbox.commit` / `discard` | 闸门;可要求 HITL |
| `sandbox.run(source\|path, caps=…)` | **Wasm 跑 Marqdo**;caps 声明 fs/net/llm/… |
| `sandbox.caps` / `inspect` | 列出已授能力与 lib/ext 可用性(对齐 `web.inspect` 哲学) |
| `sandbox.exec(...)` | **仅 escape Profile**;默认不存在于作者工具表 |
与现有衔接:
- `lib/*`:优先 embedded;FS/时间/网络走会话 caps。
- `ext/*`:mq 门面可加载;原生插件默认不可用并诊断;长期可 Wasm 化的(linalg/quantum 逻辑)优先进 Wasm。
- `lib/writeback`:写入会话内文件;`commit` 时进入真实树。
- `lib/subtask`:默认仅 `fn=`;`path`/`code`/`lang` 要 escape。
### 6.4 硬禁(写入后续 design 时应保留)
1. **不以 symlink 森林作为隔离或暂存原语。**
2. **不以「能跑空 `# main`」宣称沙盒完成** — 必须过 lib/ext 完备金样或显式 unavailable。
3. **默认工具表不提供通用 shell / 任意语言 exec。**
4. **不默认可写 bind 真实工作区。**
5. **宿主桥 = 权限表**:未授能力不得 ambient 成功。
6. **不静默降级**:缺 Wasm/能力时不得假装已隔离。
7. **`ext/**` 不调 `host_*`**(既有宪法)。
### 6.5 分阶段落地(建议,非 `doc/next`)
| 阶段 | 交付 | 验收线索 |
|------|------|----------|
| S0 | 威胁模型 + 本调研(含 Marqdo-only) | 本文 |
| S1 | Wasm `run` + embedded 核心 `lib/*` + 会话 VFS 读 | 常用 lib 金样在沙盒绿 |
| S2 | CoW upper/whiteout + diff/commit/discard | 未 commit 时宿主机 `git status` 干净 |
| S3 | writeback / 工作簿在会话内可写;commit 对齐 | agent step 金样 |
| S4 | caps:net/llm 白名单;`subtask` 非 fn 默认拒 | 诊断字符串稳定 |
| S5 | 代表性 ext(纯逻辑 + 需网)沙盒金样 | 完备性验收 |
| S6 | (可选)escape OS 沙盒;hosted microVM | 文档标明非默认 |
---
## 7. 外部资料索引(抽样)
| 类型 | 引用 |
|------|------|
| 产品 | [Anthropic: Claude Code sandboxing](https://www.anthropic.com/engineering/claude-code-sandboxing) · [sandbox-runtime](https://github.com/anthropic-experimental/sandbox-runtime) · [VS Code agent sandboxing](https://code.visualstudio.com/docs/agents/run/agent-sandboxing) · [Docker AI Sandboxes security](https://docs.docker.com/ai/sandboxes/security/) · [Turso AgentFS overlay](https://turso.tech/blog/agentfs-overlay) · [OpenSandbox isolation sessions](https://open-sandbox.ai/guides/isolation-sessions) |
| 标准 | [WASI Design Principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md) · [jco preview2-shim sandbox](https://github.com/bytecodealliance/jco/blob/main/packages/preview2-shim/README.md) |
| 论文 | Bosamiya et al., *Provably-Safe Multilingual Software Sandboxing using WebAssembly*, USENIX Security 2022 · *Intra-process Fault Isolation Using WebAssembly* (KTH) · *Research on WebAssembly Runtimes: A Survey*, ACM TOSEM 2025 |
| 综述 | [Cosmonic: Choosing an AI agent sandbox (2026)](https://cosmonic.com/ai-sandbox/choosing-an-agent-sandbox/) · [Northflank: MicroVMs, gVisor & isolation](https://northflank.com/blog/how-to-sandbox-ai-agents) |
| 安全案例 | [brig symlink traversal / Endor Labs](https://www.endorlabs.com/learn/project-mount-symlink-traversal-in-brig-how-a-sandbox-reaches-host-directories-it-was-never-given) · Anthropic sandbox-runtime symlink bind 修复 |
---
## 8. 结语
- **产品好消息:** Agent 只生成 Marqdo → **Wasm 主沙盒设计成立**,不必默认扛通用 shell Agent 的复杂度。
- **好沙盒的定义:** 不只跑内核,还要 **`lib/*` 可用、`ext/*` 在能力表内可用或显式不可用**;再加 **CoW + commit** 保护仓库真相。
- **仍要改掉的:** 符号链接当暂存/隔离;默认开放 foreign/dlopen;「空 main 能跑」就算完工。
- **降级为非默认的:** bwrap/microVM — 留给 escape / hosted,而不是 Marqdo-only 主路径。
不急着实现。下一步若继续收敛,再开 `doc/design/ext-ai-sandbox.md` 把 **能力矩阵 + 库完备金样清单** 锁死即可;**仍不要改 `doc/next/*`**。
+1
View File
@@ -18,6 +18,7 @@
|----|------|------| |----|------|------|
| **Intelligence primitive** | `ask` / `stream` / `collect`;结果对象 | `ext/ai/llm` | | **Intelligence primitive** | `ask` / `stream` / `collect`;结果对象 | `ext/ai/llm` |
| **Agent runtime** | `run` / `step` / `plan` / `route` | `ext/ai/agent` | | **Agent runtime** | `run` / `step` / `plan` / `route` | `ext/ai/agent` |
| **Sandbox (trial)** | CoW workspace + capped `run` | `ext/ai/sandbox` · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
| **Memory / compile** | episode → skill → policy | `plugins/agent`(ABI;**不进** `src/host`) | | **Memory / compile** | episode → skill → policy | `plugins/agent`(ABI;**不进** `src/host`) |
| **Transport** | HTTP / SSE / provider | `ext/ai/llm/openai` · `ollama`;用户不可见 | | **Transport** | HTTP / SSE / provider | `ext/ai/llm/openai` · `ollama`;用户不可见 |
+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)** | | 调研 | [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) | | 设计 | [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) | | 邻近 | [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/*`
+28
View File
@@ -0,0 +1,28 @@
# Roadmap: `ext/ai/sandbox` (AI CoW trial runtime)
| | |
|---|---|
| Status | **Active** |
| Date | 2026-10-16 |
| Design | [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
| Research | [ai-agent-sandbox.md](../research/ai-agent-sandbox.md) |
## Milestones
| ID | Deliverable | Done when |
|----|-------------|-----------|
| S0 | Design + this roadmap + research cross-links | **done** |
| S1 | CoW open/write/read/remove/diff/commit/discard | **done** (`sandbox-cow`) |
| S2 | `run` + default caps + core lib inside run | **done** (`sandbox-run-lib`) |
| S3 | `inspect` + deny plugin.load | **done** (`sandbox-deny`) |
| S4 | Polish: ai-stack + CHANGELOG | **done** |
## Gold samples (target)
- `tests/ext/sandbox-cow.mq.md`
- `tests/ext/sandbox-run-lib.mq.md`
- `tests/ext/sandbox-deny.mq.md`
## Out of scope this wave
wasmtime CLI embed · Wasm ABI plugins · bwrap/microVM · full web in sandbox · auto-wire agent.step · 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
+1 -1
View File
@@ -1 +1 @@
1.4.0 1.4.3
+244 -70
View File
@@ -9,6 +9,8 @@ import time:lib/time.mq.md
import wb:lib/writeback.mq.md import wb:lib/writeback.mq.md
import subtask:lib/subtask.mq.md import subtask:lib/subtask.mq.md
import plugin:lib/plugin.mq.md import plugin:lib/plugin.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
--- ---
## build_step_context ## 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 ## await_workbook
+ `path` + `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`** 1. `sandbox`
**waited = > subtask.wait id=`id`** **tr = trial path=`path` root=`sandbox_root` profile=`sandbox_profile` commit=True**
**code = > json.get value=`waited` key="code"** **ok = [ok](tr)**
**value = > json.get value=`waited` key="value"** **stdout = [stdout](tr)**
**stdout = > json.get value=`waited` key="stdout"** **stderr = [stderr](tr)**
**stderr = > json.get value=`waited` key="stderr"** 1. `ok`
**obs = > inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`** **code = 0**
**out = > json.parse text={"code":0}** 2. *
**out = > json.set map=`out` key="code" value=`code`** **code = 1**
**out = > json.set map=`out` key="value" value=`value`** **value = stdout**
**out = > json.set map=`out` key="observation" value=`obs`** **obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
*out* **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 + `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory + `memory_dir`=.marqdo/agent-memory
+ `threshold`=0.78 + `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`. 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"** **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`* *> 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`* *> 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 ## maybe_learn
+ `task` + `task`
+ `kb_dir`=.marqdo/agent-kb + `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 + `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. 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`** **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`** **policy_learn = > agent_maybe_compile_policy memory_dir=`memory_dir` min_evidence=`improve_every`**
@@ -1806,8 +1932,18 @@ Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_
+ `router_model`=None + `router_model`=None
+ `resume_id`=None + `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume + `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. 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.
**efi_pf = None**
1. `efi`
**efi_pf = > `self`.preflight task=`task`**
2. *
**_ = 1**
**routed = > `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold`** **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"** **route_matched = > json.get value=`routed` key="matched"**
@@ -1815,16 +1951,17 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**exec_mode = "explore"** **exec_mode = "explore"**
**llm_calls = 0** **llm_calls = 0**
**tokens = 0** **tokens = 0**
**token_cost = 0**
**out = None** **out = None**
**route_backend = > json.get value=`routed` key="backend"** **route_backend = > json.get value=`routed` key="backend"**
1. `route_matched` 1. `route_matched`
**path = > json.get value=`routed` key="resource"** **path = > json.get value=`routed` key="resource"**
1. `path` 1. `path`
**aw = > await_workbook path=`path`** **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = > json.get value=`aw` key="code"** **code = [code](aw)**
**child_val = > json.get value=`aw` key="value"** **child_val = [value](aw)**
**last_obs = > json.get value=`aw` key="observation"** **last_obs = [observation](aw)**
1. `code` == 0 1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every` > agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**lf = > json.get value=`routed` key="llm_free"** **lf = > json.get value=`routed` key="llm_free"**
@@ -1832,19 +1969,14 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**exec_mode = "compiled"** **exec_mode = "compiled"**
2. * 2. *
**exec_mode = "routed"** **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"** **rmode = > json.get value=`routed` key="mode"**
**out = > json.set map=`out` key="match" value=`rmode`**
**sk = > json.get value=`routed` key="skill"** **sk = > json.get value=`routed` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`** **out = **
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="adaptive route hit"** | status | goal | result | workbook | cache | match | skill | observation | summary | route |
**out = > json.set map=`out` key="route" value=`routed`** |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` |
**llm_calls = 0** **llm_calls = 0**
2. * 2. *
**route_matched = False** **route_matched = False**
@@ -1858,7 +1990,7 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
2. `needs_llm` 2. `needs_llm`
1. `router_model` 1. `router_model`
**prompt = > json.get value=`routed` key="prompt"** **prompt = > json.get value=`routed` key="prompt"**
**turn = > model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`** **turn = model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`**
**reply = > json.get value=`turn` key="text"** **reply = > json.get value=`turn` key="text"**
**llm_calls = > json.get value=`turn` key="llm_calls"** **llm_calls = > json.get value=`turn` key="llm_calls"**
**tokens = > json.get value=`turn` key="tokens"** **tokens = > json.get value=`turn` key="tokens"**
@@ -1866,24 +1998,19 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**am = > json.get value=`applied` key="matched"** **am = > json.get value=`applied` key="matched"**
1. `am` 1. `am`
**path = > json.get value=`applied` key="resource"** **path = > json.get value=`applied` key="resource"**
**aw = > await_workbook path=`path`** **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = > json.get value=`aw` key="code"** **code = [code](aw)**
**child_val = > json.get value=`aw` key="value"** **child_val = [value](aw)**
**last_obs = > json.get value=`aw` key="observation"** **last_obs = [observation](aw)**
1. `code` == 0 1. `code` == 0
**exec_mode = "routed"** **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"** **sk = > json.get value=`applied` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`** **out = **
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="router model selected skill"** | status | goal | result | workbook | cache | match | skill | observation | summary | route |
**out = > json.set map=`out` key="route" value=`applied`** |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | soft-hit | routed | `sk` | `last_obs` | router model selected skill | `applied` |
**route_matched = True** **route_matched = True**
2. * 2. *
**route_matched = False** **route_matched = False**
@@ -1897,29 +2024,53 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
1. `route_matched` 1. `route_matched`
**_ = 1** **_ = 1**
2. * 2. *
1. `efi_pf`
**efi_st = > json.get value=`efi_pf` key="status"**
**efi_dec = > json.get value=`efi_pf` key="decision"**
**efi_allow = > json.get value=`efi_pf` key="create_allowed"**
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`** **resolved = > `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold`**
**mode = > json.get value=`resolved` key="mode"** **mode = > json.get value=`resolved` key="mode"**
**llm_free = > json.get value=`resolved` key="llm_free"** **llm_free = > json.get value=`resolved` key="llm_free"**
1. not `llm_free`
**llm_free = False**
1. `llm_free` 1. `llm_free`
**path = > json.get value=`resolved` key="resource"** **path = > json.get value=`resolved` key="resource"**
**aw = > await_workbook path=`path`** **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = > json.get value=`aw` key="code"** **code = [code](aw)**
**child_val = > json.get value=`aw` key="value"** **child_val = [value](aw)**
**last_obs = > json.get value=`aw` key="observation"** **last_obs = [observation](aw)**
1. `code` == 0 1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every` > agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**exec_mode = "compiled"** **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"** **sk = > json.get value=`resolved` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`** **out = **
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="compiled skill (llm_free)"** | 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** **llm_calls = 0**
2. * 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`** **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 +2117,37 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
2. * 2. *
**_ = 1** **_ = 1**
**execution = > json.parse text={"mode":"explore","llm_calls":0,"tokens":0}** **token_cost = tokens**
**execution = > json.set map=`execution` key="mode" value=`exec_mode`** **usage = **
**execution = > json.set map=`execution` key="llm_calls" value=`llm_calls`**
**execution = > json.set map=`execution` key="tokens" value=`tokens`** | llm_calls | tokens | token_cost |
**execution = > json.set map=`execution` key="skill" value=`sk2`** |-----------|--------|------------|
**execution = > json.set map=`execution` key="router" value=`route_backend`** | `llm_calls` | `tokens` | `token_cost` |
**out = > json.set map=`out` key="execution" value=`execution`**
**out = > json.set map=`out` key="episode" value=`ep`** **execution = **
**out = > json.set map=`out` key="route" value=`routed`**
| 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` 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. * 2. *
**_ = 1** **_ = 1**
1. `resume_id` 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`** **_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`** **out = table.put in=`out` at="resume" value=`_ckpt`**
2. * 2. *
**_ = 1** **_ = 1**
@@ -1994,10 +2159,13 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
+ `stream`=False + `stream`=False
+ `echo`=False + `echo`=False
+ `max_reads`=2 + `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. 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. 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"** **id = > json.get value=`self` key="id"**
**model = > json.get value=`self` key="model"** **model = > json.get value=`self` key="model"**
@@ -2088,6 +2256,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="llm_calls" value=`llm_calls`**
**out = > json.set map=`out` key="tokens" value=`tokens`** **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.parse text={"role":"assistant"}**
**as_turn = > json.set map=`as_turn` key="content" value=`reply`** **as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn` > 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*
+191
View File
@@ -0,0 +1,191 @@
---
title: ext/ai/sandbox
description: >-
CoW trial workspace for AI-generated Marqdo: open / run / diff / commit.
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"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)
> sys.exit code=1
## 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
Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade.
> ensure_plugin
1. `root`
*> sandbox_open root=`root`*
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`
+ `text`
Write text into the session upper layer (host tree unchanged until `commit`).
> ensure_plugin
*> sandbox_write id=`id` path=`path` text=`text`*
## read
+ `id`
+ `path`
Read through CoW (upper, else lower; whiteout misses).
> ensure_plugin
*> sandbox_read id=`id` path=`path`*
## remove
+ `id`
+ `path`
Logical delete (whiteout).
> ensure_plugin
*> sandbox_remove id=`id` path=`path`*
## diff
+ `id`
List of `{ path, kind }` pending changes (`write` | `remove`).
> ensure_plugin
*> sandbox_diff id=`id`*
## commit
+ `id`
Apply upper / whiteout to the real workspace root.
> ensure_plugin
*> sandbox_commit id=`id`*
## discard
+ `id`
Drop the session without writing the host tree.
> ensure_plugin
*> sandbox_discard id=`id`*
## run
+ `id`
+ `source`=None
+ `path`=None
Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW).
Pass `source=` or `path=` (relative to session root).
> ensure_plugin
1. `source`
*> sandbox_run id=`id` source=`source`*
2. `path`
*> sandbox_run id=`id` path=`path`*
3. *
> print text=ext/ai/sandbox.run: need source= or path=
> sys.exit code=1
## inspect_native
+ `id`
> 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)。 description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编译经 ABI v2 agent 插件(情景 → 学习 → llm_free)。
导入 大模型:ext/ai/大模型.mq.md 导入 大模型:ext/ai/大模型.mq.md
import agent:ext/ai/agent.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 import json:lib/json.mq.md
导入 系统:lib/系统.mq.md 导入 系统:lib/系统.mq.md
导入 自写回:lib/自写回.mq.md 导入 自写回:lib/自写回.mq.md
@@ -106,15 +108,30 @@ import json:lib/json.mq.md
> agent_history_clear id=`id` > 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`;传 `写回=假` 可关闭。 原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。 流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。
**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`** **ctx = > 构建单步上下文 智能体=`自` 任务=`任务`**
**id = > json.get value=`自` key="id"** **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`** **as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn` > agent_history_append id=`id` item=`as_turn`
1. `沙盒`
**配置行 = sandbox.profile name=`沙盒配置`**
**out = table.put in=`out` at="sandbox_profile" value=`配置行`**
2. *
**_ = 1**
1. `写回` 1. `写回`
**body = > json.stringify value=`out`** **body = > json.stringify value=`out`**
**st = > json.get value=`out` key="status"** **st = > json.get value=`out` key="status"**
@@ -296,14 +319,17 @@ Engineering First Information 门闩。转发 `agent.preflight`。
+ `强制`=False + `强制`=False
+ `路由`=auto + `路由`=auto
+ `路由模型`=None + `路由模型`=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"** **model = > json.get value=`self` key="model"**
**tools = > json.get value=`self` key="tools"** **tools = > json.get value=`self` key="tools"**
**standing = > json.get value=`self` key="standing"** **standing = > json.get value=`self` key="standing"**
**en = > agent.agent model=`model` tools=`tools` standing=`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=`工程预检`*
## 路由 ## 路由
+ `任务` + `任务`
+63
View File
@@ -0,0 +1,63 @@
---
title: ext/ai/沙盒
description: >-
AI 试跑 CoW 工作区:打开 / 运行 / 差异 / 提交(中文面,委托英文 sandbox 模块)。
import sandbox:ext/ai/sandbox.mq.md
---
## 打开
+ `根`=None
*> sandbox.open root=`根`*
## 写入
+ `id`
+ `路径`
+ `文本`
*> sandbox.write id=`id` path=`路径` text=`文本`*
## 读取
+ `id`
+ `路径`
*> sandbox.read id=`id` path=`路径`*
## 删除
+ `id`
+ `路径`
*> sandbox.remove id=`id` path=`路径`*
## 差异
+ `id`
*> sandbox.diff id=`id`*
## 提交
+ `id`
*> sandbox.commit id=`id`*
## 丢弃
+ `id`
*> sandbox.discard id=`id`*
## 运行
+ `id`
+ `源码`=None
+ `路径`=None
1. `源码`
*> sandbox.run id=`id` source=`源码`*
2. `路径`
*> sandbox.run id=`id` path=`路径`*
3. *
> print text=沙盒.运行: 需要 源码= 或 路径=
> sys.exit code=1
## 检查
+ `id`
*> sandbox.inspect id=`id`*
+170 -1
View File
@@ -511,11 +511,25 @@ fn write_skill_concept(
quality: i64, quality: i64,
hits: i64, hits: i64,
now: &str, now: &str,
meta: &SkillMeta,
) -> Result<(), String> { ) -> Result<(), String> {
if let Some(p) = path.parent() { if let Some(p) = path.parent() {
fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?; fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?;
} }
let title: String = goal.chars().take(48).collect(); 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!( let body = format!(
r#"--- r#"---
type: Marqdo Agent Skill type: Marqdo Agent Skill
@@ -526,7 +540,7 @@ status: {status}
llm_free: {llm_free} llm_free: {llm_free}
quality: {quality} quality: {quality}
hits: {hits} hits: {hits}
generated: {extra}generated:
by: marqdo-agent/plan by: marqdo-agent/plan
at: {now} at: {now}
verified: verified:
@@ -545,11 +559,29 @@ Prefer spawning `resource` over re-planning.
llm_free = if llm_free { "true" } else { "false" }, llm_free = if llm_free { "true" } else { "false" },
quality = quality, quality = quality,
hits = hits, hits = hits,
extra = extra,
now = now, now = now,
); );
fs::write(path, body).map_err(|e| format!("write skill: {e}")) 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> { fn refresh_index(root: &Path, slug: &str, goal: &str) -> Result<(), String> {
let index = root.join("index.md"); let index = root.join("index.md");
let line = format!( 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}`")) .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> { fn opt_tools(args: &Value) -> Option<&Value> {
args.get("tools").filter(|t| !t.is_null()) 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> { pub fn kb_promote(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?; let kb = arg_text(args, "kb_dir")?;
let goal = arg_text(args, "goal")?; 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_path = resolve_path(workbook);
let src = fs::read_to_string(&src_path) let src = fs::read_to_string(&src_path)
.map_err(|e| format!("kb_promote read workbook: {e}"))?; .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 (llm_free, quality) = llm_free_score(&src);
let status = if llm_free { "stable" } else { "candidate" }; let status = if llm_free { "stable" } else { "candidate" };
@@ -1168,6 +1272,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
&now, &now,
&extra_aliases, &extra_aliases,
)?; )?;
let meta = skill_meta_from_src(&src);
write_skill_concept( write_skill_concept(
&skill_path, &skill_path,
&sig, &sig,
@@ -1178,6 +1283,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
quality, quality,
prev_hits, prev_hits,
&now, &now,
&meta,
)?; )?;
refresh_index(&root, &slug, &goal_n)?; refresh_index(&root, &slug, &goal_n)?;
@@ -1190,6 +1296,69 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
"quality": quality, "quality": quality,
"status": status, "status": status,
"hits": prev_hits, "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(),
})) }))
} }
+39
View File
@@ -8,6 +8,7 @@ mod mcp_server;
mod memory; mod memory;
mod resume; mod resume;
mod route; mod route;
mod sandbox;
use std::collections::HashMap; use std::collections::HashMap;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
@@ -900,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_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_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_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_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit");
kb_ffi!( kb_ffi!(
agent_workbook_solidify, agent_workbook_solidify,
@@ -1066,6 +1068,15 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{ {
return 1; 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 { if register(host, "agent_kb_record_hit", "kb_dir,goal", agent_kb_record_hit) != 0 {
return 1; return 1;
} }
@@ -1180,6 +1191,34 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{ {
return 1; return 1;
} }
// Optional JSON keys only — empty params CSV so omitted args are not required.
if register(host, "sandbox_open", "", sandbox::sandbox_open) != 0 {
return 1;
}
if register(host, "sandbox_write", "", sandbox::sandbox_write) != 0 {
return 1;
}
if register(host, "sandbox_read", "", sandbox::sandbox_read) != 0 {
return 1;
}
if register(host, "sandbox_remove", "", sandbox::sandbox_remove) != 0 {
return 1;
}
if register(host, "sandbox_diff", "", sandbox::sandbox_diff) != 0 {
return 1;
}
if register(host, "sandbox_commit", "", sandbox::sandbox_commit) != 0 {
return 1;
}
if register(host, "sandbox_discard", "", sandbox::sandbox_discard) != 0 {
return 1;
}
if register(host, "sandbox_inspect", "", sandbox::sandbox_inspect) != 0 {
return 1;
}
if register(host, "sandbox_run", "", sandbox::sandbox_run) != 0 {
return 1;
}
0 0
} }
+26
View File
@@ -1038,10 +1038,17 @@ pub fn resolve_task(args: &Value) -> Result<Value, String> {
"tools": args.get("tools").cloned().unwrap_or(Value::Null), "tools": args.get("tools").cloned().unwrap_or(Value::Null),
}))?; }))?;
if hit.is_null() { if hit.is_null() {
// Keep field set aligned with hit path so facades can safely read llm_free
// (qdagent / agent.run crashed on missing key when OKF is cold).
return Ok(json!({ return Ok(json!({
"mode": "unknown", "mode": "unknown",
"match": null,
"skill": null, "skill": null,
"resource": null, "resource": null,
"slug": null,
"status": null,
"llm_free": false,
"score": null,
"confidence": 0.0, "confidence": 0.0,
})); }));
} }
@@ -1078,6 +1085,25 @@ pub fn resolve_task(args: &Value) -> Result<Value, String> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn resolve_miss_includes_llm_free() {
let dir = std::env::temp_dir().join(format!(
"marqdo-resolve-miss-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let out = resolve_task(&json!({
"task": "no-such-skill-cold-miss",
"kb_dir": dir.to_string_lossy(),
"near_match": false,
}))
.unwrap();
assert_eq!(out.get("mode").and_then(|v| v.as_str()), Some("unknown"));
assert_eq!(out.get("llm_free").and_then(|v| v.as_bool()), Some(false));
let _ = fs::remove_dir_all(&dir);
}
#[test] #[test]
fn record_and_cluster_and_compile() { fn record_and_cluster_and_compile() {
let dir = std::env::temp_dir().join(format!( let dir = std::env::temp_dir().join(format!(
+53
View File
@@ -0,0 +1,53 @@
//! Forward `sandbox_*` plugin calls to host_query (CoW lives in the host).
use super::{
host_query_json_args, parse_args, set_err, set_out,
};
use std::os::raw::c_char;
fn forward(
query_name: &str,
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
let v = match parse_args(args_json) {
Ok(v) => v,
Err(e) => {
set_err(err_msg, &format!("{query_name}: {e}"));
return 1;
}
};
match host_query_json_args(query_name, &v) {
Ok(j) => {
set_out(out_json, &j.to_string());
0
}
Err(e) => {
set_err(err_msg, &e);
1
}
}
}
macro_rules! sandbox_ffi {
($fn_name:ident, $query:expr) => {
pub unsafe extern "C" fn $fn_name(
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
forward($query, args_json, out_json, err_msg)
}
};
}
sandbox_ffi!(sandbox_open, "sandbox_open");
sandbox_ffi!(sandbox_write, "sandbox_write");
sandbox_ffi!(sandbox_read, "sandbox_read");
sandbox_ffi!(sandbox_remove, "sandbox_remove");
sandbox_ffi!(sandbox_diff, "sandbox_diff");
sandbox_ffi!(sandbox_commit, "sandbox_commit");
sandbox_ffi!(sandbox_discard, "sandbox_discard");
sandbox_ffi!(sandbox_inspect, "sandbox_inspect");
sandbox_ffi!(sandbox_run, "sandbox_run");
+1 -1
View File
@@ -5,7 +5,7 @@ description: Local browse and static export from the interpreter
# main # main
Milestone: `marqdo view` and `view output` (v1.4.0 document surface + inferred params). Milestone: `marqdo view` and `view output` (v1.4.1 mid→mid annot leaders + document surface).
Local: `marqdo view public` Local: `marqdo view public`
+1 -1
View File
@@ -5,7 +5,7 @@ description: 本地浏览与静态导出由解释器生成
# main # main
里程碑:`marqdo view` 与 `view output`(v1.4.0 文档面 + 推断形参)。 里程碑:`marqdo view` 与 `view output`(v1.4.1 mid→mid 标注连线 + 文档面)。
本地浏览:`marqdo view public` 本地浏览:`marqdo view public`
+26
View File
@@ -39,6 +39,32 @@ run tests/ext/agent-zero-llm.mq.md
run tests/ext/agent-plan-preserve.mq.md run tests/ext/agent-plan-preserve.mq.md
run examples/agent-okf-flywheel/index.mq.md run examples/agent-okf-flywheel/index.mq.md
run examples/agent-pong/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 if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
export AGENT_LIVE=1 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. 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. 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)). 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) ## 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:`). 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) ## Official extension: `ext/web` (Document / Endpoint / Resource)
+14 -1
View File
@@ -34,6 +34,9 @@ fn text_body(v: &Value) -> Result<&str, String> {
pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> { pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?; let p = ctx.resolve_path(text_path(path)?)?;
if let Some(hit) = crate::host::sandbox_fs::cow_read_text(ctx, &p)? {
return Ok(Value::Text(hit));
}
let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?; let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?;
Ok(Value::Text(s)) Ok(Value::Text(s))
} }
@@ -43,10 +46,14 @@ pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value
return Err("write_text denied by host policy".into()); return Err("write_text denied by host policy".into());
} }
let p = ctx.resolve_path(text_path(path)?)?; let p = ctx.resolve_path(text_path(path)?)?;
let body = text_body(text)?;
if crate::host::sandbox_fs::cow_write_text(ctx, &p, body)? {
return Ok(Value::None);
}
if let Some(parent) = p.parent() { if let Some(parent) = p.parent() {
fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?; fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?;
} }
fs::write(&p, text_body(text)?).map_err(|e| format!("write_text {}: {e}", p.display()))?; fs::write(&p, body).map_err(|e| format!("write_text {}: {e}", p.display()))?;
Ok(Value::None) Ok(Value::None)
} }
@@ -68,6 +75,9 @@ pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Valu
pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> { pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?; let p = ctx.resolve_path(text_path(path)?)?;
if let Some(hit) = crate::host::sandbox_fs::cow_exists(ctx, &p)? {
return Ok(Value::Bool(hit));
}
Ok(Value::Bool(p.exists())) Ok(Value::Bool(p.exists()))
} }
@@ -109,6 +119,9 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
return Err("remove denied by host policy".into()); return Err("remove denied by host policy".into());
} }
let p = ctx.resolve_path(text_path(path)?)?; let p = ctx.resolve_path(text_path(path)?)?;
if crate::host::sandbox_fs::cow_remove(ctx, &p)? {
return Ok(Value::None);
}
if p.is_dir() { if p.is_dir() {
fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?; fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
} else { } else {
+4
View File
@@ -40,6 +40,7 @@ pub mod subtask;
#[cfg(not(feature = "exec-host"))] #[cfg(not(feature = "exec-host"))]
#[path = "subtask_stub.rs"] #[path = "subtask_stub.rs"]
pub mod subtask; pub mod subtask;
pub mod sandbox_fs;
mod sys; mod sys;
pub mod writeback; pub mod writeback;
@@ -111,6 +112,8 @@ pub struct HostContext {
pub subtask_seq: u64, pub subtask_seq: u64,
/// Minimum log level (`lib/log`); default Info (20). See `host::log::Level`. /// Minimum log level (`lib/log`); default Info (20). See `host::log::Level`.
pub log_min_level: u8, pub log_min_level: u8,
/// Active `ext/ai/sandbox` CoW session id (nested `sandbox_run`).
pub sandbox_session: Option<String>,
} }
impl Default for HostContext { impl Default for HostContext {
@@ -135,6 +138,7 @@ impl Default for HostContext {
subtasks: HashMap::new(), subtasks: HashMap::new(),
subtask_seq: 0, subtask_seq: 0,
log_min_level: 20, // Info log_min_level: 20, // Info
sandbox_session: None,
} }
} }
} }
+9
View File
@@ -120,6 +120,9 @@ pub fn http_get(
headers: Option<&Value>, headers: Option<&Value>,
) -> Result<Value, String> { ) -> Result<Value, String> {
if !ctx.allow_net() { if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_get denied by host policy".into()); return Err("http_get denied by host policy".into());
} }
let url = as_text(url, "url")?; let url = as_text(url, "url")?;
@@ -137,6 +140,9 @@ pub fn http_post(
headers: Option<&Value>, headers: Option<&Value>,
) -> Result<Value, String> { ) -> Result<Value, String> {
if !ctx.allow_net() { if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_post denied by host policy".into()); return Err("http_post denied by host policy".into());
} }
let url = as_text(url, "url")?; let url = as_text(url, "url")?;
@@ -161,6 +167,9 @@ pub fn http_request(
headers: Option<&Value>, headers: Option<&Value>,
) -> Result<Value, String> { ) -> Result<Value, String> {
if !ctx.allow_net() { if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_request denied by host policy".into()); return Err("http_request denied by host policy".into());
} }
let method = as_text(method, "method")?.to_uppercase(); let method = as_text(method, "method")?.to_uppercase();
+13
View File
@@ -417,6 +417,16 @@ unsafe extern "C" fn host_query(
}); });
Ok(serde_json::json!({ "ok": true })) Ok(serde_json::json!({ "ok": true }))
})(), })(),
name if name.starts_with("sandbox_") => (|| {
let raw = args_owned.as_deref().unwrap_or("{}");
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
"{}"
} else {
raw
})
.map_err(|e| format!("{name} args: {e}"))?;
crate::host::sandbox_fs::query(name, &args, ctx)
})(),
// ADR 0007: run a Document/Endpoint `.mq.md` for HTTP handlers. // ADR 0007: run a Document/Endpoint `.mq.md` for HTTP handlers.
"run_artifact" => (|| { "run_artifact" => (|| {
let raw = args_owned.as_deref().unwrap_or("{}"); let raw = args_owned.as_deref().unwrap_or("{}");
@@ -472,6 +482,9 @@ unsafe extern "C" fn host_query(
pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> { pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_plugin() { if !ctx.allow_plugin() {
if ctx.sandbox_session.is_some() {
return Err("plugin.load unavailable in sandbox".into());
}
return Err("plugin_load denied by host policy".into()); return Err("plugin_load denied by host policy".into());
} }
let rel = as_text(path, "path")?; let rel = as_text(path, "path")?;
+475
View File
@@ -0,0 +1,475 @@
//! Application-level CoW workspace for `ext/ai/sandbox` (via host_query).
//!
//! lower = real root (read-through); upper = session bytes; whiteout = logical delete.
//! Not a symlink forest. Symlink targets are not followed as isolation primitives.
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use serde_json::json;
use crate::host::HostContext;
use crate::value::Value;
#[derive(Debug, Default)]
pub struct CowSession {
pub root: PathBuf,
/// Relative path (forward slashes) → file bytes.
pub upper: HashMap<String, Vec<u8>>,
pub whiteout: HashSet<String>,
}
static SESSIONS: OnceLock<Mutex<HashMap<String, CowSession>>> = OnceLock::new();
static SEQ: OnceLock<Mutex<u64>> = OnceLock::new();
fn sessions() -> &'static Mutex<HashMap<String, CowSession>> {
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn next_id() -> String {
let mut g = SEQ
.get_or_init(|| Mutex::new(0))
.lock()
.unwrap_or_else(|e| e.into_inner());
*g = g.wrapping_add(1);
format!("sbx-{g}")
}
fn normalize_rel(rel: &str) -> Result<String, String> {
let rel = rel.trim().trim_start_matches('/');
if rel.is_empty() {
return Err("sandbox path must not be empty".into());
}
let p = Path::new(rel);
if p.is_absolute() {
return Err("sandbox path must be relative to session root".into());
}
let mut out = Vec::new();
for c in p.components() {
match c {
Component::Normal(s) => out.push(s.to_string_lossy().into_owned()),
Component::CurDir => {}
Component::ParentDir => {
return Err("sandbox path must not contain '..'".into());
}
_ => return Err(format!("sandbox path invalid component in `{rel}`")),
}
}
if out.is_empty() {
return Err("sandbox path must not be empty".into());
}
Ok(out.join("/"))
}
fn abs_under_root(root: &Path, rel: &str) -> Result<PathBuf, String> {
let rel_n = normalize_rel(rel)?;
let abs = root.join(Path::new(&rel_n));
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
// Parent may not exist yet for writes — check by prefix components.
let mut check = abs.clone();
loop {
if check == *root || check == root_canon {
return Ok(root.join(Path::new(&rel_n)));
}
if !check.pop() {
break;
}
if let Ok(c) = check.canonicalize() {
if crate::host::path_under_root(&c, &root_canon) || c == root_canon {
return Ok(root.join(Path::new(&rel_n)));
}
}
}
if crate::host::path_under_root(&abs, root) {
return Ok(abs);
}
Err(format!("path escapes sandbox root: {rel_n}"))
}
pub fn open(root: Option<&str>, ctx: &HostContext) -> Result<serde_json::Value, String> {
let root_pb = if let Some(r) = root.filter(|s| !s.is_empty()) {
let p = PathBuf::from(r);
if p.is_absolute() {
p
} else {
ctx.cwd.join(p)
}
} else if let Some(ep) = &ctx.entry_path {
ep.parent()
.unwrap_or(ep.as_path())
.to_path_buf()
} else {
ctx.cwd.clone()
};
let root_pb = if root_pb.is_absolute() {
root_pb
} else {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(root_pb)
};
if !root_pb.is_dir() {
return Err(format!(
"sandbox_open: root is not a directory: {}",
root_pb.display()
));
}
let id = next_id();
let sess = CowSession {
root: root_pb.clone(),
upper: HashMap::new(),
whiteout: HashSet::new(),
};
sessions()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id.clone(), sess);
Ok(json!({
"id": id,
"root": root_pb.to_string_lossy(),
}))
}
fn with_session_mut<F, T>(id: &str, f: F) -> Result<T, String>
where
F: FnOnce(&mut CowSession) -> Result<T, String>,
{
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
let sess = map
.get_mut(id)
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
f(sess)
}
fn with_session<F, T>(id: &str, f: F) -> Result<T, String>
where
F: FnOnce(&CowSession) -> Result<T, String>,
{
let map = sessions().lock().unwrap_or_else(|e| e.into_inner());
let sess = map
.get(id)
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
f(sess)
}
pub fn write(id: &str, path: &str, text: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let rel = normalize_rel(path)?;
let _ = abs_under_root(&sess.root, &rel)?;
sess.whiteout.remove(&rel);
sess.upper.insert(rel, text.as_bytes().to_vec());
Ok(json!({ "ok": true }))
})
}
pub fn read(id: &str, path: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
let rel = normalize_rel(path)?;
if sess.whiteout.contains(&rel) {
return Err(format!("sandbox_read: not found (whiteout): {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
let s = String::from_utf8(bytes.clone())
.map_err(|e| format!("sandbox_read: not utf-8: {e}"))?;
return Ok(json!(s));
}
let abs = abs_under_root(&sess.root, &rel)?;
let s = std::fs::read_to_string(&abs)
.map_err(|e| format!("sandbox_read {}: {e}", abs.display()))?;
Ok(json!(s))
})
}
pub fn remove(id: &str, path: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let rel = normalize_rel(path)?;
let _ = abs_under_root(&sess.root, &rel)?;
sess.upper.remove(&rel);
sess.whiteout.insert(rel);
Ok(json!({ "ok": true }))
})
}
pub fn diff(id: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
let mut items: Vec<serde_json::Value> = Vec::new();
for p in sess.upper.keys() {
items.push(json!({ "path": p, "kind": "write" }));
}
for p in &sess.whiteout {
items.push(json!({ "path": p, "kind": "remove" }));
}
items.sort_by(|a, b| {
let pa = a.get("path").and_then(|v| v.as_str()).unwrap_or("");
let pb = b.get("path").and_then(|v| v.as_str()).unwrap_or("");
pa.cmp(pb)
});
Ok(json!(items))
})
}
pub fn commit(id: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let mut applied = 0i64;
let writes: Vec<(String, Vec<u8>)> = sess
.upper
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let removes: Vec<String> = sess.whiteout.iter().cloned().collect();
for (rel, bytes) in writes {
let abs = abs_under_root(&sess.root, &rel)?;
if let Some(parent) = abs.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("sandbox_commit mkdir: {e}"))?;
}
std::fs::write(&abs, &bytes)
.map_err(|e| format!("sandbox_commit write {}: {e}", abs.display()))?;
applied += 1;
}
for rel in removes {
let abs = abs_under_root(&sess.root, &rel)?;
if abs.exists() {
if abs.is_dir() {
std::fs::remove_dir_all(&abs)
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
} else {
std::fs::remove_file(&abs)
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
}
applied += 1;
}
}
sess.upper.clear();
sess.whiteout.clear();
Ok(json!({ "ok": true, "applied": applied }))
})
}
pub fn discard(id: &str) -> Result<serde_json::Value, String> {
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
if map.remove(id).is_none() {
return Err(format!("sandbox: unknown session `{id}`"));
}
Ok(json!({ "ok": true }))
}
pub fn inspect(id: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
Ok(json!({
"id": id,
"root": sess.root.to_string_lossy(),
"upper_count": sess.upper.len(),
"whiteout_count": sess.whiteout.len(),
"caps_default": {
"fs_write": true,
"exec": false,
"net": false,
"plugin": false
},
"notes": [
"ext/web listen/DB/WS unavailable in sandbox",
"plugin.load denied during sandbox.run",
"subtask path/code/lang unavailable in sandbox"
]
}))
})
}
/// Read file bytes through CoW for an active host sandbox session (lib/fs).
pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result<Option<String>, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(None);
};
with_session(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
if sess.whiteout.contains(&rel) {
return Err(format!("read_text: not found (sandbox whiteout): {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
let s = String::from_utf8(bytes.clone())
.map_err(|e| format!("read_text: not utf-8: {e}"))?;
return Ok(Some(s));
}
Ok(None)
})
}
pub fn cow_write_text(ctx: &HostContext, abs: &Path, text: &str) -> Result<bool, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(false);
};
with_session_mut(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
sess.whiteout.remove(&rel);
sess.upper.insert(rel, text.as_bytes().to_vec());
Ok(true)
})
}
pub fn cow_remove(ctx: &HostContext, abs: &Path) -> Result<bool, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(false);
};
with_session_mut(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
sess.upper.remove(&rel);
sess.whiteout.insert(rel);
Ok(true)
})
}
pub fn cow_exists(ctx: &HostContext, abs: &Path) -> Result<Option<bool>, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(None);
};
with_session(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
if sess.whiteout.contains(&rel) {
return Ok(Some(false));
}
if sess.upper.contains_key(&rel) {
return Ok(Some(true));
}
Ok(None)
})
}
fn rel_from_root(root: &Path, abs: &Path) -> Result<String, String> {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let abs_canon = abs.canonicalize().unwrap_or_else(|_| abs.to_path_buf());
let rel = abs_canon
.strip_prefix(&root_canon)
.or_else(|_| abs.strip_prefix(root))
.map_err(|_| format!("path not under sandbox root: {}", abs.display()))?;
normalize_rel(&rel.to_string_lossy().replace('\\', "/"))
}
pub fn run(
id: &str,
source: Option<&str>,
path: Option<&str>,
) -> Result<serde_json::Value, String> {
let (root, body) = with_session(id, |sess| {
let body = if let Some(src) = source.filter(|s| !s.trim().is_empty()) {
src.to_string()
} else if let Some(p) = path.filter(|s| !s.is_empty()) {
let rel = normalize_rel(p)?;
if sess.whiteout.contains(&rel) {
return Err(format!("sandbox_run: path whiteout: {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
String::from_utf8(bytes.clone())
.map_err(|e| format!("sandbox_run: path not utf-8: {e}"))?
} else {
let abs = abs_under_root(&sess.root, &rel)?;
std::fs::read_to_string(&abs)
.map_err(|e| format!("sandbox_run read {}: {e}", abs.display()))?
}
} else {
return Err("sandbox_run requires `source` or `path`".into());
};
Ok((sess.root.clone(), body))
})?;
let opts = crate::RunOptions {
allow_fs_write: true,
allow_exec: false,
allow_net: false,
allow_plugin: false,
fs_root: Some(root),
sandbox_session: Some(id.to_string()),
sleep_limit_ms: Some(0),
..crate::RunOptions::default()
};
match crate::run_source(&body, &opts) {
Ok(cap) => {
let value = crate::host::json::value_to_json(&cap.value)
.unwrap_or(serde_json::Value::Null);
Ok(json!({
"ok": true,
"value": value,
"stdout": cap.stdout,
}))
}
Err(e) => {
let msg = e.to_string();
Ok(json!({
"ok": false,
"error": msg,
"value": null,
"stdout": "",
}))
}
}
}
/// Parse host_query JSON args helper used from plugin.rs.
pub fn query(name: &str, args: &serde_json::Value, ctx: &HostContext) -> Result<serde_json::Value, String> {
let id = || {
args.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("{name}: missing `id`"))
};
match name {
"sandbox_open" => {
let root = args.get("root").and_then(|v| v.as_str());
open(root, ctx)
}
"sandbox_write" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_write: missing `path`".to_string())?;
let text = args
.get("text")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_write: missing `text`".to_string())?;
write(id()?, path, text)
}
"sandbox_read" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_read: missing `path`".to_string())?;
read(id()?, path)
}
"sandbox_remove" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_remove: missing `path`".to_string())?;
remove(id()?, path)
}
"sandbox_diff" => diff(id()?),
"sandbox_commit" => commit(id()?),
"sandbox_discard" => discard(id()?),
"sandbox_inspect" => inspect(id()?),
"sandbox_run" => {
let source = args.get("source").and_then(|v| v.as_str());
let path = args.get("path").and_then(|v| v.as_str());
run(id()?, source, path)
}
other => Err(format!("sandbox query unknown `{other}`")),
}
}
#[allow(dead_code)]
pub fn unavailable(feature: &str) -> String {
format!("{feature} unavailable in sandbox")
}
/// Used by fs layer when session is active — map Value path through resolve then CoW.
pub fn try_read_value(ctx: &HostContext, path: &Value) -> Result<Option<Value>, String> {
let rel = match path {
Value::Text(s) => s.as_str(),
_ => return Ok(None),
};
let abs = ctx.resolve_path(rel)?;
match cow_read_text(ctx, &abs)? {
Some(s) => Ok(Some(Value::Text(s))),
None => Ok(None),
}
}
+3
View File
@@ -150,6 +150,9 @@ pub fn exec(
{ {
use std::process::Stdio; use std::process::Stdio;
if !ctx.allow_exec() { if !ctx.allow_exec() {
if ctx.sandbox_session.is_some() {
return Err("exec unavailable in sandbox".into());
}
return Err("exec denied by host policy".into()); return Err("exec denied by host policy".into());
} }
let cmd = as_text(cmd, "cmd")?; let cmd = as_text(cmd, "cmd")?;
+67 -2
View File
@@ -652,7 +652,26 @@ impl Interpreter {
&[("kind", "call"), ("callee", call.callee.as_str())], &[("kind", "call"), ("callee", call.callee.as_str())],
); );
} }
let _ = self.eval_call(module, fun, env, call)?; let stdout_before = self.captured_stdout.len();
let v = self.eval_call(module, fun, env, call)?;
if self.capture {
let (loop_id, iter) = self.loop_ctx();
self.record_stmt_event(StmtEvent {
line: span.line,
kind: StmtEventKind::Call,
name: Some(call.callee.clone()),
value_after: Some(call_event_brief(
&v,
&self.captured_stdout,
stdout_before,
&call.callee,
)),
arm_index: None,
iter,
call_id: self.current_call_id(),
loop_id,
});
}
Ok(None) Ok(None)
} }
Stmt::Expr { value, span } => { Stmt::Expr { value, span } => {
@@ -665,7 +684,30 @@ impl Interpreter {
&[("kind", "expr")], &[("kind", "expr")],
); );
} }
let _ = self.eval_expr(module, fun, env, value)?; let stdout_before = self.captured_stdout.len();
let v = self.eval_expr(module, fun, env, value)?;
if self.capture {
let (loop_id, iter) = self.loop_ctx();
let name = match value {
Expr::Call(c) => Some(c.callee.clone()),
_ => None,
};
self.record_stmt_event(StmtEvent {
line: span.line,
kind: StmtEventKind::Call,
name: name.clone(),
value_after: Some(call_event_brief(
&v,
&self.captured_stdout,
stdout_before,
name.as_deref().unwrap_or("expr"),
)),
arm_index: None,
iter,
call_id: self.current_call_id(),
loop_id,
});
}
Ok(None) Ok(None)
} }
Stmt::Branch { arms, span } => { Stmt::Branch { arms, span } => {
@@ -1688,6 +1730,29 @@ fn brief_trace_val(v: &Value) -> String {
} }
} }
/// Prefer real result; else last stdout line emitted by the call; else callee name.
fn call_event_brief(v: &Value, stdout: &str, stdout_before: usize, callee: &str) -> String {
if !matches!(v, Value::None) {
return brief_trace_val(v);
}
if stdout.len() > stdout_before {
let delta = &stdout[stdout_before..];
let line = delta
.trim_end()
.lines()
.last()
.unwrap_or(delta.trim_end());
if !line.is_empty() {
return if line.chars().count() > 48 {
format!("{}…", line.chars().take(48).collect::<String>())
} else {
line.to_string()
};
}
}
callee.to_string()
}
fn stmt_span(stmt: &Stmt) -> Span { fn stmt_span(stmt: &Stmt) -> Span {
match stmt { match stmt {
Stmt::Assign { span, .. } Stmt::Assign { span, .. }
+11 -1
View File
@@ -92,6 +92,8 @@ pub struct RunOptions {
pub allow_fs_write: bool, pub allow_fs_write: bool,
pub allow_exec: bool, pub allow_exec: bool,
pub allow_net: bool, pub allow_net: bool,
/// Native `plugin.load` (default true for CLI; false inside `sandbox.run`).
pub allow_plugin: bool,
/// Exposed via `host_args` / `args`. /// Exposed via `host_args` / `args`.
pub argv: Vec<String>, pub argv: Vec<String>,
/// Override filesystem sandbox root (default: source file's directory). /// Override filesystem sandbox root (default: source file's directory).
@@ -102,6 +104,8 @@ pub struct RunOptions {
pub emit_result: Option<std::path::PathBuf>, pub emit_result: Option<std::path::PathBuf>,
/// CLI `--bind KEY=VALUE` pairs for Artifact Metadata Binding (`arg` + overlay). /// CLI `--bind KEY=VALUE` pairs for Artifact Metadata Binding (`arg` + overlay).
pub binds: Vec<(String, String)>, pub binds: Vec<(String, String)>,
/// Attach CoW session for `ext/ai/sandbox` nested runs.
pub sandbox_session: Option<String>,
} }
impl Default for RunOptions { impl Default for RunOptions {
@@ -118,11 +122,13 @@ impl Default for RunOptions {
allow_fs_write: true, allow_fs_write: true,
allow_exec: true, allow_exec: true,
allow_net: true, allow_net: true,
allow_plugin: true,
argv: Vec::new(), argv: Vec::new(),
fs_root: None, fs_root: None,
sleep_limit_ms: None, sleep_limit_ms: None,
emit_result: None, emit_result: None,
binds: Vec::new(), binds: Vec::new(),
sandbox_session: None,
} }
} }
} }
@@ -154,7 +160,7 @@ impl RunOptions {
fs_write: self.allow_fs_write, fs_write: self.allow_fs_write,
exec: self.allow_exec, exec: self.allow_exec,
net: self.allow_net, net: self.allow_net,
plugin: true, plugin: self.allow_plugin,
} }
} }
} }
@@ -289,6 +295,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
host.set_entry_source(Some(path), &source); host.set_entry_source(Some(path), &source);
host.argv = opts.argv.clone(); host.argv = opts.argv.clone();
host.entry_metadata = module.metadata.clone(); host.entry_metadata = module.metadata.clone();
host.sandbox_session = opts.sandbox_session.clone();
if let Some(root) = &opts.fs_root { if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone()); host.fs_root = Some(root.clone());
host.cwd = root.clone(); host.cwd = root.clone();
@@ -315,6 +322,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
host.set_entry_source(Some(path), &source); host.set_entry_source(Some(path), &source);
host.argv = opts.argv.clone(); host.argv = opts.argv.clone();
host.entry_metadata = module.metadata.clone(); host.entry_metadata = module.metadata.clone();
host.sandbox_session = opts.sandbox_session.clone();
if let Some(root) = &opts.fs_root { if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone()); host.fs_root = Some(root.clone());
host.cwd = root.clone(); host.cwd = root.clone();
@@ -351,6 +359,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
host.set_entry_source(None, source); host.set_entry_source(None, source);
host.argv = opts.argv.clone(); host.argv = opts.argv.clone();
host.entry_metadata = module.metadata.clone(); host.entry_metadata = module.metadata.clone();
host.sandbox_session = opts.sandbox_session.clone();
if let Some(root) = &opts.fs_root { if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone()); host.fs_root = Some(root.clone());
host.cwd = root.clone(); host.cwd = root.clone();
@@ -377,6 +386,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
host.set_entry_source(None, source); host.set_entry_source(None, source);
host.argv = opts.argv.clone(); host.argv = opts.argv.clone();
host.entry_metadata = module.metadata.clone(); host.entry_metadata = module.metadata.clone();
host.sandbox_session = opts.sandbox_session.clone();
if let Some(root) = &opts.fs_root { if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone()); host.fs_root = Some(root.clone());
host.cwd = root.clone(); host.cwd = root.clone();
+243 -7
View File
@@ -33,7 +33,7 @@ pub enum AnnotKind {
Return, Return,
#[allow(dead_code)] #[allow(dead_code)]
Call, Call,
#[allow(dead_code)] #[allow(dead_code)] // reserved for non-call BoldCode expr chips
Expr, Expr,
Branch, Branch,
Loop, Loop,
@@ -119,7 +119,9 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec
) )
}); });
let key = (*line, name.clone(), ev.call_id, ev.loop_id, ev.iter); let key = (*line, name.clone(), ev.call_id, ev.loop_id, ev.iter);
let mut value = ev.value_after.clone().unwrap_or_else(|| "?".into()); let raw = ev.value_after.clone().unwrap_or_else(|| "?".into());
let (value, detail) = abbreviate_bind_value(&raw);
let mut value = value;
let count = assign_counts.get(&key).copied().unwrap_or(1); let count = assign_counts.get(&key).copied().unwrap_or(1);
if count > 1 { if count > 1 {
value = format!("{value} · ×{count}"); value = format!("{value} · ×{count}");
@@ -132,7 +134,7 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec
anchor_byte_end: end, anchor_byte_end: end,
label: name.clone(), label: name.clone(),
value: brief_str(&value), value: brief_str(&value),
detail: ev.value_after.clone().unwrap_or_default(), detail,
arm_index: None, arm_index: None,
call_id: Some(ev.call_id), call_id: Some(ev.call_id),
loop_id: ev.loop_id, loop_id: ev.loop_id,
@@ -352,6 +354,62 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec
} }
} }
// Call / expr events → chips; zip with BoldCode spans when several share a line.
let mut calls_by_line: HashMap<u32, Vec<&crate::capture::StmtEvent>> = HashMap::new();
for ev in &cap.view_trace.events {
if ev.kind == StmtEventKind::Call {
calls_by_line.entry(ev.line).or_default().push(ev);
}
}
for (line, evs) in calls_by_line {
let text = lines
.get(line.saturating_sub(1) as usize)
.copied()
.unwrap_or("");
let bold_spans: Vec<(usize, usize)> = scan_prose_line(text)
.into_iter()
.filter_map(|bit| match bit {
ProseBit::BoldCode { .. } => {
let start = bit_at(&bit);
Some((start, prose_bit_end(text, &bit)))
}
_ => None,
})
.collect();
for (i, ev) in evs.iter().enumerate() {
// One BoldCode on the line (e.g. print across call frames): share it.
// Several BoldCodes (e.g. two greets in main): zip by index.
let (start, end) = if bold_spans.is_empty() {
(None, None)
} else if bold_spans.len() == 1 {
let (s, e) = bold_spans[0];
(Some(s), Some(e))
} else {
bold_spans
.get(i)
.copied()
.map(|(s, e)| (Some(s), Some(e)))
.unwrap_or((None, None))
};
let value = ev.value_after.clone().unwrap_or_default();
let label = ev.name.clone().unwrap_or_else(|| "call".into());
out.push(ViewAnnot {
id: next_id("c"),
kind: AnnotKind::Call,
anchor_line: line,
anchor_byte_start: start,
anchor_byte_end: end,
label,
value: brief_str(&value),
detail: value,
arm_index: None,
call_id: Some(ev.call_id),
loop_id: ev.loop_id,
iter: ev.iter,
});
}
}
// Call frames for picker (label = fn name). // Call frames for picker (label = fn name).
for fr in &cap.view_trace.calls { for fr in &cap.view_trace.calls {
out.push(ViewAnnot { out.push(ViewAnnot {
@@ -370,9 +428,167 @@ pub fn build_view_annots(module: &Module, source: &str, cap: &RunCapture) -> Vec
}); });
} }
// Param Decl sites in function body: bind chips from CallFrame args.
for fr in &cap.view_trace.calls {
let Some(fun) = find_fun_by_line(module, fr.fn_line) else {
continue;
};
let body_lines = fun_stmt_lines(fun);
for (pname, pval) in parse_args_brief_pairs(&fr.args_brief) {
for (i, text) in lines.iter().enumerate() {
let line_no = (i + 1) as u32;
if !body_lines.contains(&line_no) {
continue;
}
for bit in scan_prose_line(text) {
if let ProseBit::Decl { name, at, .. } = &bit {
if name != &pname {
continue;
}
let end = prose_bit_end(text, &bit);
out.push(ViewAnnot {
id: next_id("p"),
kind: AnnotKind::Bind,
anchor_line: line_no,
anchor_byte_start: Some(*at),
anchor_byte_end: Some(end),
label: pname.clone(),
value: brief_str(&pval),
detail: format!("{pname}={pval}"),
arm_index: None,
call_id: Some(fr.call_id),
loop_id: None,
iter: None,
});
}
}
}
}
}
// Same prose span across call frames shares one id so <mark data-annot-id>
// matches the visible chip after frame filter (else L-leaders find no anchor).
unify_annot_ids_by_span(&mut out);
out out
} }
fn unify_annot_ids_by_span(annots: &mut [ViewAnnot]) {
let mut first: HashMap<(u32, Option<usize>, Option<usize>, u8), String> = HashMap::new();
for a in annots.iter_mut() {
if matches!(a.kind, AnnotKind::CallFrame | AnnotKind::LoopFrame) {
continue;
}
if a.anchor_byte_start.is_none() {
continue;
}
let tag = match a.kind {
AnnotKind::Bind => 1u8,
AnnotKind::Return => 2,
AnnotKind::Call | AnnotKind::Expr => 3,
AnnotKind::Branch => 4,
AnnotKind::Loop => 5,
AnnotKind::Writeback => 6,
AnnotKind::CallFrame | AnnotKind::LoopFrame => 0,
};
let key = (
a.anchor_line,
a.anchor_byte_start,
a.anchor_byte_end,
tag,
);
if let Some(id) = first.get(&key) {
a.id = id.clone();
} else {
first.insert(key, a.id.clone());
}
}
}
fn abbreviate_bind_value(raw: &str) -> (String, String) {
if raw.contains("<svg") {
return ("svg".into(), "svg".into());
}
if raw.contains("```") {
return ("code".into(), "code".into());
}
if raw.chars().count() > 96 {
let short: String = raw.chars().take(48).collect();
return (format!("{short}…"), format!("{short}…"));
}
(raw.to_string(), raw.to_string())
}
fn parse_args_brief_pairs(brief: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
for part in brief.split(", ") {
if let Some((k, v)) = part.split_once('=') {
if !k.is_empty() {
out.push((k.to_string(), v.to_string()));
}
}
}
out
}
fn find_fun_by_line(module: &Module, line: u32) -> Option<&Function> {
fn walk<'a>(fun: &'a Function, line: u32) -> Option<&'a Function> {
if fun.span.line == line {
return Some(fun);
}
for c in &fun.children {
if let Some(f) = walk(c, line) {
return Some(f);
}
}
None
}
for f in &module.functions {
if let Some(found) = walk(f, line) {
return Some(found);
}
}
None
}
fn fun_stmt_lines(fun: &Function) -> std::collections::HashSet<u32> {
let mut s = std::collections::HashSet::new();
fn walk_stmt(st: &Stmt, s: &mut std::collections::HashSet<u32>) {
let line = match st {
Stmt::Assign { span, .. }
| Stmt::Return { span, .. }
| Stmt::Call { span, .. }
| Stmt::Expr { span, .. }
| Stmt::Branch { span, .. }
| Stmt::While { span, .. }
| Stmt::ForEach { span, .. } => span.line,
};
s.insert(line);
match st {
Stmt::Branch { arms, .. } => {
for arm in arms {
for b in &arm.body {
walk_stmt(b, s);
}
}
}
Stmt::While { body, .. } | Stmt::ForEach { body, .. } => {
for b in body {
walk_stmt(b, s);
}
}
_ => {}
}
}
for st in &fun.body {
walk_stmt(st, &mut s);
}
for c in &fun.children {
s.extend(fun_stmt_lines(c));
}
s
}
/// Serialize ViewExecutionReport JSON for AI / page embed. /// Serialize ViewExecutionReport JSON for AI / page embed.
pub fn view_execution_report_json(path: &str, ok: bool, cap: &RunCapture) -> String { pub fn view_execution_report_json(path: &str, ok: bool, cap: &RunCapture) -> String {
use serde_json::{json, Map}; use serde_json::{json, Map};
@@ -583,8 +799,10 @@ pub fn bit_kind_class(bit: &ProseBit) -> &'static str {
/// Render annotation band HTML for a set of annots (already filtered to one block). /// Render annotation band HTML for a set of annots (already filtered to one block).
/// ///
/// Chips with `iter` default to the **last** iteration per `loop_id` (SSR); the loop /// SSR defaults to the **last** call_id and **last** iteration per loop_id (matches
/// picker toggles `hidden` / `is-frame-hidden` so only the selected iter is shown. /// pickers). Overflow (`max_visible`) is counted only among chips visible in that
/// default frame — so `who` on the last greet call is not buried behind +N.
/// Client `applyCallFrame` recomputes overflow after switching.
pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String { pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String {
let annots: Vec<&ViewAnnot> = annots let annots: Vec<&ViewAnnot> = annots
.iter() .iter()
@@ -603,17 +821,35 @@ pub fn render_annot_band(annots: &[ViewAnnot], max_visible: usize) -> String {
} }
} }
} }
// Default call frame = max call_id among chips that carry one (last invocation).
let default_call_id: Option<u32> = annots.iter().filter_map(|a| a.call_id).max();
// Left-to-right by anchor so chips sit under their underlines (avoids
// crossed L-leaders that look like “missing” lines when crowded).
let mut ordered: Vec<&ViewAnnot> = annots;
ordered.sort_by(|a, b| {
let sa = a.anchor_byte_start.unwrap_or(usize::MAX);
let sb = b.anchor_byte_start.unwrap_or(usize::MAX);
sa.cmp(&sb).then_with(|| a.id.cmp(&b.id))
});
let mut s = String::from(r#"<div class="annot-band" data-annot-band>"#); let mut s = String::from(r#"<div class="annot-band" data-annot-band>"#);
// Leaders live on the parent .doc-block (see initAnnotLeaders); keep a hook
// for keyed mode / a11y but geometry is computed against the block.
s.push_str(r#"<div class="annot-leaders" aria-hidden="true"></div>"#); s.push_str(r#"<div class="annot-leaders" aria-hidden="true"></div>"#);
s.push_str(r#"<div class="annot-chips">"#); s.push_str(r#"<div class="annot-chips">"#);
let mut shown = 0usize; let mut shown = 0usize;
let mut overflow_count = 0usize; let mut overflow_count = 0usize;
for a in &annots { for a in &ordered {
let frame_miss = a let iter_miss = a
.iter .iter
.zip(default_iter.get(&a.loop_id)) .zip(default_iter.get(&a.loop_id))
.map(|(i, d)| i != *d) .map(|(i, d)| i != *d)
.unwrap_or(false); .unwrap_or(false);
let call_miss = match (a.call_id, default_call_id) {
(Some(cid), Some(def)) if cid != def => true,
_ => false,
};
let frame_miss = iter_miss || call_miss;
let overflow = if frame_miss { let overflow = if frame_miss {
false false
} else if shown >= max_visible { } else if shown >= max_visible {
+167 -5
View File
@@ -110,9 +110,33 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot
LineKind::Comment => { LineKind::Comment => {
let text = l.text.trim_end_matches(['\r', '\n']); let text = l.text.trim_end_matches(['\r', '\n']);
let trimmed = text.trim(); let trimmed = text.trim();
// Unbound ```lang fences stay Comment in lex — render as code cards
// (same chrome as bound foreign), never join into a prose <code> blob.
if crate::foreign::is_fence_opener(trimmed)
|| (trimmed.starts_with("```") && !crate::foreign::is_fence_closer(trimmed))
{
flush_para(&mut para, &mut out);
let (html, next) = render_narrative_fence(&lines, i);
out.push_str(&html);
i = next;
continue;
}
if crate::foreign::is_fence_closer(trimmed) {
// Orphan closer — skip.
flush_para(&mut para, &mut out);
i += 1;
continue;
}
let bits = scan_prose_line(text); let bits = scan_prose_line(text);
let is_stmt = stmt_lines.contains(&l.line_no); let is_stmt = stmt_lines.contains(&l.line_no);
let has_annots = by_line
.get(&l.line_no)
.map(|v| !v.is_empty())
.unwrap_or(false);
// Decl alone stays in Markdown prose (keep links). Open a marked
// line block when there is executable prose, a stmt, or chips.
let needs_annot = is_stmt let needs_annot = is_stmt
|| has_annots
|| bits.iter().any(|b| { || bits.iter().any(|b| {
matches!(b, ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. }) matches!(b, ProseBit::BoldCode { .. } | ProseBit::ItalicReturn { .. })
}); });
@@ -722,14 +746,24 @@ fn render_line_block(
let trimmed = text.trim_start(); let trimmed = text.trim_start();
if bits.is_empty() { if bits.is_empty() {
if let Some(rest) = trimmed.strip_prefix("> ") { if let Some(rest) = trimmed.strip_prefix("> ") {
let aid = match_annot_for_line(annots)
.map(|a| a.id.as_str())
.unwrap_or("");
s.push_str(&format!( s.push_str(&format!(
r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> {}</div>"#, r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> <mark class="mq-anchor mq-code" data-line="{line}" data-annot-id="{aid}">{rest}</mark></div>"#,
escape(rest) line = line_no,
aid = escape(aid),
rest = escape(rest),
)); ));
} else if let Some(rest) = trimmed.strip_prefix('>') { } else if let Some(rest) = trimmed.strip_prefix('>') {
let aid = match_annot_for_line(annots)
.map(|a| a.id.as_str())
.unwrap_or("");
s.push_str(&format!( s.push_str(&format!(
r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> {}</div>"#, r#"<div class="doc-line doc-call"><span class="mq-call-gt">&gt;</span> <mark class="mq-anchor mq-code" data-line="{line}" data-annot-id="{aid}">{rest}</mark></div>"#,
escape(rest.trim_start()) line = line_no,
aid = escape(aid),
rest = escape(rest.trim_start()),
)); ));
} else { } else {
s.push_str(&format!( s.push_str(&format!(
@@ -768,7 +802,8 @@ fn render_line_block(
s s
} }
/// Huge SVG / fenced code dumps make annot bands unreadable — keep those out of chips. /// Huge SVG / fenced code dumps — prefer abbreviated chips from annot builder;
/// only drop if detail is still an unreadable dump.
fn is_noisy_result_chip(a: &ViewAnnot) -> bool { fn is_noisy_result_chip(a: &ViewAnnot) -> bool {
if a.kind != crate::view::annot::AnnotKind::Bind { if a.kind != crate::view::annot::AnnotKind::Bind {
return false; return false;
@@ -777,6 +812,49 @@ fn is_noisy_result_chip(a: &ViewAnnot) -> bool {
v.contains("<svg") || v.contains("```") || v.chars().count() > 96 v.contains("<svg") || v.contains("```") || v.chars().count() > 96
} }
fn match_annot_for_line<'a>(annots: &[&'a ViewAnnot]) -> Option<&'a ViewAnnot> {
annots.iter().copied().find(|a| {
matches!(
a.kind,
crate::view::annot::AnnotKind::Call
| crate::view::annot::AnnotKind::Bind
| crate::view::annot::AnnotKind::Return
)
})
}
/// Unbound Markdown fence → same visual card as bound foreign (no Run chrome).
fn render_narrative_fence(lines: &[ClassifiedLine], start: usize) -> (String, usize) {
let opener = lines[start].text.trim_end_matches(['\r', '\n']).trim();
let lang = crate::foreign::fence_lang(opener).unwrap_or_else(|| "text".into());
let line_no = lines[start].line_no;
let mut body: Vec<String> = Vec::new();
let mut j = start + 1;
while j < lines.len() {
let t = lines[j].text.trim_end_matches(['\r', '\n']);
if crate::foreign::is_fence_closer(t.trim()) {
j += 1;
break;
}
body.push(t.to_string());
j += 1;
}
let source = body.join("\n");
let html = format!(
r#"<div class="doc-block doc-exec" data-line="{line}"><div class="card code-card" data-lang="{lang}">
<div class="code-head">
<span class="badge">code</span>
<span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
</div></div>"#,
line = line_no,
lang = escape(&lang),
src = escape(&source),
);
(html, j)
}
/// Render prose with markers stripped; show surface inner text only. /// Render prose with markers stripped; show surface inner text only.
fn render_prose_with_marks( fn render_prose_with_marks(
line_no: u32, line_no: u32,
@@ -1244,4 +1322,88 @@ mod tests {
"{html}" "{html}"
); );
} }
#[test]
fn narrative_text_fence_renders_as_code_card() {
let src = r#"# main
```text
marqdo ext add web
marqdo ext add quantum
```
> print text=ok
"#;
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_document(&module, src, &[]);
assert!(
html.contains(r#"data-lang="text""#) && html.contains("code-body"),
"text fence should be a code card: {html}"
);
assert!(
html.contains("marqdo ext add web\nmarqdo ext add quantum"),
"fence body newlines preserved: {html}"
);
assert!(
!html.contains("<code>text marqdo"),
"must not collapse fence into inline code: {html}"
);
}
#[test]
fn prose_calls_and_param_decl_get_chips() {
let src = r#"# main
Try **greet who="a"** and **greet who="b"**.
## greet
When we meet `who`, we **print text="Hi, `who`!"** and close with*None*.
"#;
let module = crate::parse::parse_source(src).unwrap();
let cap = crate::run_source(src, &crate::RunOptions::default()).unwrap();
let annots = build_view_annots(&module, src, &cap);
assert!(
annots
.iter()
.filter(|a| a.kind == crate::view::annot::AnnotKind::Call)
.count()
>= 3,
"expected greet×2 + print call events: {:?}",
cap.view_trace.events
);
assert!(
annots.iter().any(|a| {
a.kind == crate::view::annot::AnnotKind::Bind && a.label == "who"
}),
"param Decl bind missing: {annots:?}"
);
let html = render_module_document(&module, src, &annots);
assert!(html.contains("annot-call"), "{html}");
assert!(html.contains("annot-bind"), "{html}");
assert!(html.contains("Hi, a!") || html.contains("Hi, b!"), "{html}");
// Dual greet call sites each get a non-empty annot id.
let greet_ids: Vec<_> = html
.match_indices("mq-code")
.filter(|_| true)
.collect();
assert!(
html.matches(r#"data-annot-id="c"#).count() >= 2
|| html.contains(r#"data-annot-id="c"#),
"expected call annot ids on greet marks: {html}"
);
let _ = greet_ids;
// Last-frame who bind must not be buried in overflow (frame-aware density).
assert!(
!html.contains(r#"annot-bind annot-chip-overflow"#)
|| html.contains(r#"annot-label">who</span>"#),
"who bind should be visible for default (last) call frame: {html}"
);
// Prefer: no overflow on bind chips when last frame has ≤4 chips.
let bind_overflow = html.matches("annot-bind annot-chip-overflow").count();
assert_eq!(
bind_overflow, 0,
"default frame who/print/return must not overflow: {html}"
);
}
} }
+209 -79
View File
@@ -382,6 +382,20 @@ li.doc-list-meta {
margin-left: -1.25rem; margin-left: -1.25rem;
} }
.doc-block { position: relative; margin: 0.55rem 0 0.85rem; } .doc-block { position: relative; margin: 0.55rem 0 0.85rem; }
.doc-block > .annot-leaders {
position: absolute;
inset: 0;
pointer-events: none;
overflow: visible;
z-index: 1; /* below .annot-chips */
}
.doc-block > .annot-leaders svg {
position: absolute;
left: 0;
top: 0;
overflow: visible;
}
.doc-block.is-keyed > .annot-leaders { display: none; }
.doc-block.doc-exec[style*="--doc-indent"] { .doc-block.doc-exec[style*="--doc-indent"] {
margin-left: calc(var(--doc-indent, 1) * 1.5rem); margin-left: calc(var(--doc-indent, 1) * 1.5rem);
} }
@@ -466,38 +480,26 @@ ul.doc-loop, ol.doc-branch {
.mq-anchor.is-focus { background: rgba(0,0,0,0.04); } .mq-anchor.is-focus { background: rgba(0,0,0,0.04); }
.annot-band { .annot-band {
position: relative; position: relative;
margin: 0.35rem 0 0.15rem; margin: 0.55rem 0 0.15rem;
min-height: 1.6rem; min-height: 1.6rem;
padding-top: 0.55rem; padding-top: 1.15rem; /* room for mid→mid leaders (rail + stub) */
} z-index: 1;
.annot-leaders {
position: absolute;
inset: 0;
pointer-events: none;
overflow: visible;
} }
/* Band-local leaders kept for keyed fallback; geometry uses .doc-block > .annot-leaders */
.annot-band > .annot-leaders { display: none; }
.annot-leader { .annot-leader {
position: absolute; fill: none;
box-sizing: border-box; stroke-width: 1.5;
border-left: 1.5px solid var(--line-strong); stroke-linecap: round;
border-bottom: 1.5px solid var(--line-strong); stroke-linejoin: round;
border-color: #8e8e93;
pointer-events: none; pointer-events: none;
} }
.annot-leader.annot-bind { border-color: #5ac8fa; }
.annot-leader.annot-return { border-color: #30d158; }
.annot-leader.annot-code,
.annot-leader.annot-call,
.annot-leader.annot-expr { border-color: #ff9f0a; }
.annot-leader.annot-branch { border-color: #bf5af2; }
.annot-leader.annot-loop { border-color: #64d2ff; }
.annot-leader.annot-writeback { border-color: #8e8e93; }
.annot-chips { .annot-chips {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 0.4rem 0.55rem; gap: 0.45rem 0.7rem;
position: relative; position: relative;
z-index: 1; z-index: 3; /* chips above leaders */
} }
.annot-chip { .annot-chip {
display: inline-flex; display: inline-flex;
@@ -531,9 +533,9 @@ ul.doc-loop, ol.doc-branch {
.annot-chip.annot-branch { border-left-color: #bf5af2; } .annot-chip.annot-branch { border-left-color: #bf5af2; }
.annot-chip.annot-loop { border-left-color: #64d2ff; } .annot-chip.annot-loop { border-left-color: #64d2ff; }
.annot-chip.annot-writeback { border-left-color: #8e8e93; } .annot-chip.annot-writeback { border-left-color: #8e8e93; }
.annot-chip-overflow { display: none; } .annot-chip.annot-chip-overflow { display: none !important; }
.annot-band.is-expanded .annot-chip-overflow:not([hidden]):not(.is-frame-hidden) { .annot-band.is-expanded .annot-chip.annot-chip-overflow:not([hidden]):not(.is-frame-hidden) {
display: inline-flex; display: inline-flex !important;
} }
.annot-label { color: var(--muted); font-weight: 600; } .annot-label { color: var(--muted); font-weight: 600; }
.annot-value { color: var(--ink); word-break: break-word; } .annot-value { color: var(--ink); word-break: break-word; }
@@ -546,17 +548,17 @@ ul.doc-loop, ol.doc-branch {
padding: 0.22rem 0.45rem; padding: 0.22rem 0.45rem;
cursor: pointer; cursor: pointer;
} }
.annot-band.is-keyed .annot-leaders { display: none; } .annot-band.is-keyed .annot-chip::before,
.annot-band.is-keyed .annot-chip::before { .doc-block.is-keyed .annot-chip::before {
content: attr(data-annot-key) " "; content: attr(data-annot-key) " ";
color: var(--muted); color: var(--muted);
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.annot-band { padding-top: 0.25rem; } .annot-band { padding-top: 0.25rem; }
.annot-leaders { display: none; } .doc-block > .annot-leaders { display: none; }
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.annot-leaders { display: none; } .doc-block > .annot-leaders { display: none; }
} }
.badge { .badge {
display: inline-block; display: inline-block;
@@ -1340,6 +1342,16 @@ ul.doc-loop, ol.doc-branch {
align-items: center; align-items: center;
gap: 0.4rem; gap: 0.4rem;
} }
.code-foot {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem 0.65rem;
padding: 0.5rem 0.85rem;
border-top: 1px solid var(--line);
background: #fafafa;
}
.code-foot .code-actions { margin-left: auto; }
.code-cmd { .code-cmd {
min-width: 9rem; min-width: 9rem;
max-width: 16rem; max-width: 16rem;
@@ -1376,6 +1388,7 @@ ul.doc-loop, ol.doc-branch {
background: #1e1e1e; background: #1e1e1e;
color: #d4d4d4; color: #d4d4d4;
font: 0.82rem/1.45 var(--mono); font: 0.82rem/1.45 var(--mono);
min-height: 2.4rem;
} }
.code-body code { .code-body code {
font: inherit; font: inherit;
@@ -1579,17 +1592,23 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
function initForeignCards() {{ function initForeignCards() {{
var live = !!window.MARQDO_VIEW_LIVE; var live = !!window.MARQDO_VIEW_LIVE;
document.querySelectorAll(".code-card").forEach(function (card) {{ document.querySelectorAll(".code-card").forEach(function (card) {{
var foot = card.querySelector(".code-foot");
var btn = card.querySelector(".code-run"); var btn = card.querySelector(".code-run");
var cmd = card.querySelector(".code-cmd"); var cmd = card.querySelector(".code-cmd");
var out = card.querySelector(".code-out"); var out = card.querySelector(".code-out");
var body = card.querySelector(".code-body code"); var body = card.querySelector(".code-body code");
if (!btn || !out || !body) return; // Narrative ```text``` cards have no Run chrome — leave as-is.
if (!btn) return;
if (!live) {{ if (!live) {{
btn.disabled = true; // Static: hide fake Run (view-static-interactive D5 / view-prose-annot-gaps P4).
btn.title = "Run is available in live marqdo view"; if (foot) foot.hidden = true;
if (cmd) cmd.disabled = true; else {{
btn.hidden = true;
if (cmd) cmd.hidden = true;
}}
return; return;
}} }}
if (!out || !body) return;
btn.addEventListener("click", function () {{ btn.addEventListener("click", function () {{
btn.disabled = true; btn.disabled = true;
out.hidden = false; out.hidden = false;
@@ -2280,6 +2299,45 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}); }});
}} }}
var MAX_VISIBLE_ANNOTS = 4;
function setFrameHidden(el, hide) {{
el.hidden = !!hide;
if (hide) el.classList.add("is-frame-hidden");
else el.classList.remove("is-frame-hidden");
}}
/** After frame filter: overflow only among chips visible in the selected frame. */
function recomputeAnnotOverflow(scope) {{
var root = scope || document.getElementById("structure") || document;
root.querySelectorAll("[data-annot-band]").forEach(function (band) {{
band.classList.remove("is-expanded");
var chips = band.querySelectorAll(".annot-chip");
var visible = [];
chips.forEach(function (chip) {{
chip.classList.remove("annot-chip-overflow");
if (chip.hidden || chip.classList.contains("is-frame-hidden")) return;
visible.push(chip);
}});
var overflow = 0;
visible.forEach(function (chip, i) {{
if (i >= MAX_VISIBLE_ANNOTS) {{
chip.classList.add("annot-chip-overflow");
overflow++;
}}
}});
var more = band.querySelector("[data-annot-more]");
if (more) {{
if (overflow > 0) {{
more.hidden = false;
more.textContent = "+" + overflow;
}} else {{
more.hidden = true;
}}
}}
}});
}}
/** Source structure always stays visible; only chips + arm classes follow the frame. */ /** Source structure always stays visible; only chips + arm classes follow the frame. */
function initCallPickers() {{ function initCallPickers() {{
document.querySelectorAll(".call-picker").forEach(function (sel) {{ document.querySelectorAll(".call-picker").forEach(function (sel) {{
@@ -2295,7 +2353,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
root.querySelectorAll(".annot-chip[data-call-id]").forEach(function (chip) {{ root.querySelectorAll(".annot-chip[data-call-id]").forEach(function (chip) {{
var cid = String(chip.getAttribute("data-call-id") || ""); var cid = String(chip.getAttribute("data-call-id") || "");
if (!allowed[cid]) return; if (!allowed[cid]) return;
chip.hidden = cid !== callId; setFrameHidden(chip, cid !== callId);
}}); }});
var trace = readViewTrace(); var trace = readViewTrace();
applyParamChipValues(fnName, callId, trace); applyParamChipValues(fnName, callId, trace);
@@ -2318,6 +2376,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}); }});
}}); }});
}} }}
recomputeAnnotOverflow(root);
initAnnotLeaders(); initAnnotLeaders();
}} }}
if (sel.dataset.bound !== "1") {{ if (sel.dataset.bound !== "1") {{
@@ -2328,12 +2387,6 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}); }});
}} }}
function setFrameHidden(el, hide) {{
el.hidden = !!hide;
if (hide) el.classList.add("is-frame-hidden");
else el.classList.remove("is-frame-hidden");
}}
function initLoopPickers() {{ function initLoopPickers() {{
document.querySelectorAll(".loop-picker").forEach(function (sel) {{ document.querySelectorAll(".loop-picker").forEach(function (sel) {{
function apply() {{ function apply() {{
@@ -2355,6 +2408,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
if (lid && loopId && String(lid) !== loopId) return; if (lid && loopId && String(lid) !== loopId) return;
setFrameHidden(chip, String(chipIter) !== iter); setFrameHidden(chip, String(chipIter) !== iter);
}}); }});
recomputeAnnotOverflow(scope);
initAnnotLeaders(); initAnnotLeaders();
}} }}
if (sel.dataset.bound !== "1") {{ if (sel.dataset.bound !== "1") {{
@@ -2365,6 +2419,26 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}); }});
}} }}
function ensureBlockLeaders(block) {{
var leaders = block.querySelector(":scope > .annot-leaders");
if (!leaders) {{
leaders = document.createElement("div");
leaders.className = "annot-leaders";
leaders.setAttribute("aria-hidden", "true");
block.insertBefore(leaders, block.firstChild);
}}
return leaders;
}}
function leaderColor(kind) {{
if (kind === "bind") return "#5ac8fa";
if (kind === "return") return "#30d158";
if (kind === "call" || kind === "expr" || kind === "code") return "#ff9f0a";
if (kind === "branch") return "#bf5af2";
if (kind === "loop") return "#64d2ff";
return "#8e8e93";
}}
function initAnnotLeaders() {{ function initAnnotLeaders() {{
var bands = document.querySelectorAll("[data-annot-band]"); var bands = document.querySelectorAll("[data-annot-band]");
if (!bands.length) return; if (!bands.length) return;
@@ -2372,68 +2446,122 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
var narrow = window.matchMedia && window.matchMedia("(max-width: 640px)").matches; var narrow = window.matchMedia && window.matchMedia("(max-width: 640px)").matches;
function layoutBand(band) {{ function layoutBand(band) {{
var leaders = band.querySelector(".annot-leaders"); var block = band.closest(".doc-block");
var chips = band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)"); if (!block) return;
if (!leaders) return; var leaders = ensureBlockLeaders(block);
leaders.innerHTML = ""; leaders.innerHTML = "";
if (reduce || narrow || chips.length > 4) {{ var chipsEl = band.querySelector(".annot-chips");
band.classList.add("is-keyed"); var chips = Array.prototype.slice.call(
chips.forEach(function (chip, i) {{ band.querySelectorAll(".annot-chip:not(.annot-chip-overflow):not([hidden]):not(.is-frame-hidden)")
chip.setAttribute("data-annot-key", String(i + 1)); );
}}); // Pair chips with anchors; reorder DOM left→right under underlines so
return; // L-leaders do not cross (crowded reverse order looked like missing lines).
}} var items = [];
band.classList.remove("is-keyed");
var bandRect = band.getBoundingClientRect();
chips.forEach(function (chip) {{ chips.forEach(function (chip) {{
if (chip.hidden || chip.classList.contains("is-frame-hidden")) return;
var id = chip.getAttribute("data-annot-id") || ""; var id = chip.getAttribute("data-annot-id") || "";
var kind = chip.getAttribute("data-annot-kind") || ""; var kind = chip.getAttribute("data-annot-kind") || "";
var anchor = id var anchor = id
? document.querySelector('.mq-anchor[data-annot-id="' + id + '"]') ? (block.querySelector('.mq-anchor[data-annot-id="' + id + '"]')
|| document.querySelector('.mq-anchor[data-annot-id="' + id + '"]'))
: null; : null;
// Fallback: match mark kind on this block (frame chips may share a span).
if (!anchor) {{ if (!anchor) {{
var block = band.closest(".doc-block"); var cls = kind === "bind" ? "mq-decl"
anchor = block ? block.querySelector(".mq-anchor") : null; : kind === "return" ? "mq-return"
: (kind === "call" || kind === "expr" || kind === "code") ? "mq-code"
: "";
if (cls) anchor = block.querySelector(".mq-anchor." + cls);
}} }}
if (!anchor) return; if (!anchor) return;
var a = anchor.getBoundingClientRect(); if (id) anchor.setAttribute("data-annot-id", id);
var c = chip.getBoundingClientRect(); items.push({{
var x0 = a.left + a.width / 2 - bandRect.left; chip: chip,
var y0 = 0; anchor: anchor,
var x1 = c.left + Math.min(12, c.width / 2) - bandRect.left; kind: kind,
var y1 = c.top - bandRect.top + c.height / 2; x: anchor.getBoundingClientRect().left
var left = Math.min(x0, x1); }});
var width = Math.max(2, Math.abs(x1 - x0));
var height = Math.max(2, y1 - y0);
var el = document.createElement("div");
el.className = "annot-leader annot-" + kind;
el.style.left = left + "px";
el.style.top = y0 + "px";
el.style.width = width + "px";
el.style.height = height + "px";
if (x1 < x0) {{
el.style.borderLeft = "none";
el.style.borderRight = "1.5px solid";
el.style.borderBottom = "1.5px solid";
}}
leaders.appendChild(el);
}}); }});
items.sort(function (a, b) {{ return a.x - b.x; }});
if (chipsEl && items.length) {{
items.forEach(function (it) {{ chipsEl.appendChild(it.chip); }});
var more = band.querySelector("[data-annot-more]");
if (more) chipsEl.appendChild(more);
}}
if (reduce || narrow || items.length > MAX_VISIBLE_ANNOTS) {{
block.classList.add("is-keyed");
band.classList.add("is-keyed");
items.forEach(function (it, i) {{
it.chip.setAttribute("data-annot-key", String(i + 1));
}});
return;
}}
block.classList.remove("is-keyed");
band.classList.remove("is-keyed");
// Mid-bottom of mark → mid-top of chip: vertical, horizontal rail, short stub.
var blockRect = block.getBoundingClientRect();
var bw = Math.max(1, block.offsetWidth);
var bh = Math.max(1, block.offsetHeight);
var svgNS = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", String(bw));
svg.setAttribute("height", String(bh));
svg.setAttribute("viewBox", "0 0 " + bw + " " + bh);
svg.setAttribute("aria-hidden", "true");
items.forEach(function (it) {{
var a = it.anchor.getBoundingClientRect();
var c = it.chip.getBoundingClientRect();
var x0 = a.left + a.width / 2 - blockRect.left;
var y0 = a.bottom - blockRect.top + 1;
var x1 = c.left + c.width / 2 - blockRect.left;
var y1 = c.top - blockRect.top;
if (y1 < y0 + 8) {{
y1 = y0 + 12;
}}
// Short stub into chip top-center; rail sits above that.
var stub = Math.min(10, Math.max(6, (y1 - y0) * 0.28));
var yRail = y1 - stub;
if (yRail < y0 + 4) {{
yRail = (y0 + y1) / 2;
}}
var path = document.createElementNS(svgNS, "path");
path.setAttribute("class", "annot-leader annot-" + it.kind);
path.setAttribute("stroke", leaderColor(it.kind));
// Orthogonal: down from mark mid → across → short down to chip mid.
path.setAttribute(
"d",
"M " + x0.toFixed(1) + " " + y0.toFixed(1) +
" L " + x0.toFixed(1) + " " + yRail.toFixed(1) +
" L " + x1.toFixed(1) + " " + yRail.toFixed(1) +
" L " + x1.toFixed(1) + " " + y1.toFixed(1)
);
svg.appendChild(path);
}});
leaders.appendChild(svg);
}} }}
function layoutAll() {{ function layoutAll() {{
bands.forEach(layoutBand); bands.forEach(layoutBand);
}} }}
layoutAll(); layoutAll();
// Second pass after fonts/layout settle (first paint often has zero chip width).
requestAnimationFrame(function () {{ layoutAll(); }});
if (document.documentElement.dataset.annotLeadersRo === "1") return;
document.documentElement.dataset.annotLeadersRo = "1";
if (typeof ResizeObserver !== "undefined") {{ if (typeof ResizeObserver !== "undefined") {{
var ro = new ResizeObserver(function () {{ layoutAll(); }}); var ro = new ResizeObserver(function () {{ layoutAll(); }});
bands.forEach(function (b) {{ ro.observe(b); }}); bands.forEach(function (b) {{
ro.observe(b);
var blk = b.closest(".doc-block");
if (blk) ro.observe(blk);
}});
var surface = document.querySelector(".document-surface"); var surface = document.querySelector(".document-surface");
if (surface) ro.observe(surface); if (surface) ro.observe(surface);
}} }}
window.addEventListener("resize", layoutAll); window.addEventListener("resize", layoutAll);
document.querySelectorAll("[data-annot-more]").forEach(function (btn) {{ document.querySelectorAll("[data-annot-more]").forEach(function (btn) {{
if (btn.dataset.bound === "1") return;
btn.dataset.bound = "1";
btn.addEventListener("click", function () {{ btn.addEventListener("click", function () {{
var band = btn.closest("[data-annot-band]"); var band = btn.closest("[data-annot-band]");
if (!band) return; if (!band) return;
@@ -2443,6 +2571,8 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}}); }});
}}); }});
document.querySelectorAll(".annot-chip").forEach(function (chip) {{ document.querySelectorAll(".annot-chip").forEach(function (chip) {{
if (chip.dataset.focusBound === "1") return;
chip.dataset.focusBound = "1";
chip.addEventListener("mouseenter", function () {{ chip.addEventListener("mouseenter", function () {{
var id = chip.getAttribute("data-annot-id"); var id = chip.getAttribute("data-annot-id");
if (!id) return; if (!id) return;
+7 -2
View File
@@ -1259,12 +1259,14 @@ fn render_stmt(
<span class="badge">code</span> <span class="badge">code</span>
<code class="expr">`{name}` =</code> <code class="expr">`{name}` =</code>
<span class="code-lang">{lang}</span> <span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<div class="code-foot">
<div class="code-actions"> <div class="code-actions">
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/> <input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
<button type="button" class="code-run">Run</button> <button type="button" class="code-run">Run</button>
</div> </div>
</div> </div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<pre class="code-out" hidden></pre> <pre class="code-out" hidden></pre>
</div>"#, </div>"#,
lang = lang, lang = lang,
@@ -1526,6 +1528,7 @@ pub(crate) fn render_formula_assign_card(name: &str, tex: &str) -> String {
} }
/// Foreign code assign card for document surface embedding (single visual layer). /// Foreign code assign card for document surface embedding (single visual layer).
/// Head → body → foot(actions) so the source is never collapsed under the Run row.
pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String { pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> String {
let placeholder = escape(&crate::foreign::default_cmd_display(lang)); let placeholder = escape(&crate::foreign::default_cmd_display(lang));
format!( format!(
@@ -1534,12 +1537,14 @@ pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> S
<span class="badge">code</span> <span class="badge">code</span>
<span class="code-name">{name}</span> <span class="code-name">{name}</span>
<span class="code-lang">{lang}</span> <span class="code-lang">{lang}</span>
</div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<div class="code-foot">
<div class="code-actions"> <div class="code-actions">
<input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/> <input type="text" class="code-cmd" placeholder="{placeholder}" spellcheck="false" autocomplete="off"/>
<button type="button" class="code-run">Run</button> <button type="button" class="code-run">Run</button>
</div> </div>
</div> </div>
<pre class="code-body"><code class="language-{lang}">{src}</code></pre>
<pre class="code-out" hidden></pre> <pre class="code-out" hidden></pre>
</div>"#, </div>"#,
lang = escape(lang), lang = escape(lang),
+76
View File
@@ -0,0 +1,76 @@
---
title: agent.run cold OKF — resolve llm_free + self.preflight
description: >-
Regression for qdagent-facing bugs (2026-10):
(A) miss resolve must expose llm_free=false;
(B) `self`.preflight must resolve when agent is imported by a consumer.
Offline — dummy API key; no live network required for assertions A/B.
import agent:ext/ai/agent.mq.md
import fs:lib/fs.mq.md
import json:lib/json.mq.md
import llm:ext/ai/llm.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
# main
> sys.env_set name="OPENAI_API_KEY" value="offline-cold-efi-dummy"
**p = > plugin.native_path name="agent"**
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
**kb = ".marqdo/agent-kb-cold-efi"**
**ex = > fs.exists path=`kb`**
1. `ex`
> fs.remove_tree path=`kb`
2. *
**_ = 1**
> fs.make_dir path=`kb`
**resolved = > agent_resolve task="qdagent-cold-unknown-task-xyz-20261016" kb_dir=`kb`**
**lf = > json.get value=`resolved` key="llm_free"**
**mode = > json.get value=`resolved` key="mode"**
1. `lf` == False
> print text=resolve-miss-llm_free-ok
2. *
> print text=resolve-miss-llm_free-MISSING
> print text=`resolved`
> sys.exit code=1
1. `mode` == "unknown"
> print text=resolve-miss-mode-ok
2. *
> print text=resolve-miss-mode-unexpected
> sys.exit code=1
**model = > llm.llm**
`tools` =
| 工具 |
|------|
**ag = > agent.agent model=`model` tools=`tools` standing="cold efi preflight probe"**
**pf = > `ag`.preflight task="qdagent-cold-unknown-task-xyz-20261016" marqdo_dir=".marqdo"**
**st = > json.get value=`pf` key="status"**
1. `st`
> print text=self-preflight-ok
> print text=`st`
2. *
> print text=self-preflight-failed
> print text=`pf`
> sys.exit code=1
**via = > `ag`.resolve task="qdagent-cold-unknown-task-xyz-20261016" kb_dir=`kb`**
**via_lf = > json.get value=`via` key="llm_free"**
1. `via_lf` == False
> print text=method-resolve-llm_free-ok
2. *
> print text=method-resolve-llm_free-MISSING
> sys.exit code=1
*"agent-run-cold-efi-ok"*
+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`
+60
View File
@@ -0,0 +1,60 @@
---
title: sandbox CoW — write stays upper until commit
description: >
Readable trial: seed on disk, mutate in session, host tree unchanged,
then commit / discard. Prefer link index over json.get.
import sandbox:ext/ai/sandbox.mq.md
import fs:lib/fs.mq.md
---
# main
Prepare a tiny workspace under this test directory (reset leftovers from prior runs).
**had = fs.exists path="_sbx_cow"**
1. `had`
> fs.remove path="_sbx_cow"
2. *
**_ = 0**
> fs.make_dir path="_sbx_cow"
> fs.write_text path="_sbx_cow/seed.txt" text=seed-lower
**sb = sandbox.open root="_sbx_cow"**
**id = [id](sb)**
Session edits (upper / whiteout only).
> sandbox.write id=`id` path="seed.txt" text=seed-upper
> sandbox.write id=`id` path="new.txt" text=brand-new
> sandbox.remove id=`id` path="seed.txt"
**pending = sandbox.diff id=`id`**
**n = len value=`pending`**
> print text=`n`
Host tree must still show the lower seed; `new.txt` must not exist yet.
**lower = fs.read_text path="_sbx_cow/seed.txt"**
> print text=`lower`
**ex_new = fs.exists path="_sbx_cow/new.txt"**
> print text=`ex_new`
Commit applies upper + whiteout.
> sandbox.commit id=`id`
**after = fs.read_text path="_sbx_cow/new.txt"**
> print text=`after`
**seed_gone = fs.exists path="_sbx_cow/seed.txt"**
> print text=`seed_gone`
Discard must not touch the host.
**sb2 = sandbox.open root="_sbx_cow"**
**id2 = [id](sb2)**
> sandbox.write id=`id2` path="new.txt" text=should-discard
> sandbox.discard id=`id2`
**kept = fs.read_text path="_sbx_cow/new.txt"**
> print text=`kept`
+34
View File
@@ -0,0 +1,34 @@
---
title: sandbox.run — plugin.load denied; inspect lists notes
description: >
Guest that loads a native plugin must fail with unavailable in sandbox.
No json.get chains — link index + a small expect table.
import sandbox:ext/ai/sandbox.mq.md
---
# main
**sb = sandbox.open root="sandbox-fixtures"**
**id = [id](sb)**
**ret = sandbox.run id=`id` path="guest-plugin.mq.md"**
**ok = [ok](ret)**
**err = [error](ret)**
> print text=`ok`
**parts = split value=`err` sep="unavailable in sandbox"**
**hits = len value=`parts`**
1. `hits` > 1
> print text=deny-ok
2. *
> print text=`err`
**info = sandbox.inspect id=`id`**
**notes = [notes](info)**
**nn = len value=`notes`**
1. `nn` > 0
> print text=inspect-ok
2. *
> print text=inspect-missing
> sandbox.discard id=`id`
@@ -0,0 +1,9 @@
---
import json:lib/json.mq.md
---
# main
**m = > json.parse text={"a":1}**
**x = > json.get value=`m` key="a"**
> print text=`x`
@@ -0,0 +1,8 @@
---
import plugin:lib/plugin.mq.md
---
# main
**p = > plugin.native_path name="agent"**
> plugin.load path=`p`
@@ -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
+22
View File
@@ -0,0 +1,22 @@
---
title: sandbox.run — core lib/json inside the trial
description: Guest fixture imports lib/json; print ok and guest stdout via link index.
import sandbox:ext/ai/sandbox.mq.md
---
# main
Open a session on the fixture directory (guest programs live here).
**sb = sandbox.open root="sandbox-fixtures"**
**id = [id](sb)**
Run the guest that imports `lib/json` and prints `1`.
**ret = sandbox.run id=`id` path="guest-json.mq.md"**
**ok = [ok](ret)**
**out = [stdout](ret)**
> print text=`ok`
> print text=`out`
> sandbox.discard id=`id`
+83
View File
@@ -2951,6 +2951,89 @@ fn ext_agent_zero_llm() {
); );
} }
#[test]
fn ext_ai_sandbox_cow() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/sandbox-cow.mq.md",
"2
seed-lower
False
brand-new
False
brand-new",
);
}
#[test]
fn ext_ai_sandbox_run_lib() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/sandbox-run-lib.mq.md",
"True
1",
);
}
#[test]
fn ext_ai_sandbox_deny() {
ensure_agent_plugin_built();
assert_out(
"tests/ext/sandbox-deny.mq.md",
"False
deny-ok
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] #[test]
fn ext_llm_named_offline() { fn ext_llm_named_offline() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));