Compare commits

...
31 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
cflmyandCursor 66926e9e0a release: Marqdo 1.4.0
Prose-unified control flow, formula meta bind, image writeback, view
inferred params; sync CLI/wasm/ext/VERSION and install docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:54:45 +08:00
cflmyandCursor dcf4c05663 fix(ext/net): wrap url.encode via lib/net, not host_*
Gold rule bans host_* from ext/**; encode must go through stdlib.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:47:07 +08:00
cflmyandCursor f47a1e143a feat(writeback): image form ![marqdo-out](…) with view parity
Auto-persist image paths/URLs as Markdown images (validated extension);
keep HTML comment for text. View and static export share styled source
markers and output-card <img> rendering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:45:52 +08:00
cflmyandCursor 9cf98a98b5 feat: block formula meta bind and control-flow prose
Support $$ % marqdo: var= binding, arm/loop narrative (fix comment-paragraph
swallow of branch arms), foreach ZH/EN sugar, and condition-line narrative.
Welcome pages and gold samples updated; view skips meta formula fence bodies.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:28:46 +08:00
cflmyandCursor f99d552d87 feat(view): show inferred param values; migrate welcome to v0.3 prose
Param chips carry call-frame values (and refresh with the call picker).
Welcome pages and the marqdo skill prefer body-inferred, conversational markup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:32:50 +08:00
cflmyandCursor 7d49c358c1 fix(view): nested-call welcome + clean formula/code cards
Welcome pages put greet calls in # main so CallFrames/pickers appear;
document surface skips fence body lines and Bind chips under formula/code cards.
Adds view-static-interactive design and entry-vs-method regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:13:42 +08:00
cflmyandCursor a32c0cd78f fix(ppa): skip cp when local orig already sits in build-area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:42:37 +08:00
cflmyandCursor 0a8f76d9b4 release: v1.3.3 — view document-surface Structure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:18:51 +08:00
cflmyandCursor 4e2419b598 feat(view): document-surface Structure with frame-aware annotations
Browse Structure keeps narration and surfaces post-stmt values, branch
arms, and call/loop pickers; static `view output` shares the same render
path so exported HTML matches live view.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:12:53 +08:00
cflmy f6374d1593 release: ext pack v1.3.2 trailing slash route fix 2026-10-13 15:37:42 +08:00
cflmy 9ede4bc63d fix(web): strip trailing slash so /post/foo/ matches /post/foo
Go ServeMux does exact-match routing; a trailing slash caused dynamic
routes like /post/{slug} to fall through to the 404 catch-all. Add
withStripTrailingSlash middleware as the outermost handler wrapper so
all downstream middleware (RBAC, tenant, mux) see the normalized path.

Tested: static routes, dynamic routes, root path, query-string preservation.
2026-10-13 15:24:26 +08:00
cflmyandCursor 3ae8f2c843 release: ext pack v1.3.1 OIDC path redirect_uri
Bump ext/VERSION only; CLI remains 1.3.0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:42:08 +08:00
cflmyandCursor e9c1a8a730 feat(web): resolve OIDC redirect_uri from request Host
Allow path-style redirect_uri (/oidc/callback) so apex/www and
proxied HTTPS share one config; persist the absolute URI for token exchange.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:35:12 +08:00
cflmyandCursor 5554b1642c feat(run): add --fs-root / MARQDO_FS_ROOT for subdirectory entries
marqdo run cli/… sandboxes to the entry directory by default; repo-root
sandbox+cwd lets qdagent keep thin CLI wrappers under cli/ without
escaping .marqdo or polluting cli/.marqdo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:17:24 +08:00
cflmyandCursor fe15603a91 fix(llm): hoist ask result fields out of the return table
Table cells shadowed self/column names (model, usage), so [model](self)
and [total_tokens](usage) raised "footnote index needs list or map" and
blocked live agent.step / qdagent BUILD.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:08:48 +08:00
cflmyandCursor 1418742655 Skip docker/data/.cursor when compiling engineering knowledge.
Packaging trees and runtime vaults were inflating EKC with duplicate noise; dogfood agents should index product sources only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 21:50:58 +08:00
cflmyandCursor ed31a2b31d release: v1.3.0 Engineering Knowledge Compiler (EKC)
Bump CLI/ext/wasm to 1.3.0; document L0–L4 catalog, reuse preflight, and
agent eng_* surfaces for AI-native engineering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 16:46:30 +08:00
cflmyandCursor 56ab52356f feat(knowledge): land Engineering Knowledge Compiler (EKC) from 008
Give agents Engineering First Information before codegen: L0–L4 catalog,
reuse/preflight (REUSE→ADAPT→CREATE), graph, and CLI surfaces so large
repos stop reinventing existing capabilities.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 16:44:39 +08:00
cflmyandCursor 2e425c3010 chore: sync Cargo.lock to 1.2.0 for PPA vendor
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:59:48 +08:00
cflmyandCursor 46a0263d7f release: v1.2.0 Web Artifact (ADR 0007) Document/Endpoint/Resource
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:39:25 +08:00
cflmyandCursor ff252fd469 feat(web): land Artifact serve/endpoint path and retire compose golds
Wire data_source into Document render, register Endpoint handlers via
run_artifact, restore marqdo-blog as an Artifact site, and replace old
compose_* web golds with ADR 0007 fixtures and docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:36:45 +08:00
cflmyandCursor 67bac1bf02 feat(web): Document/Endpoint/Resource artifact rewrite (ADR 0007)
Replace the monolithic compose_*/configure author surface with file-level
web|endpoint artifacts, split ext/{web,data,security,net}, and lock
no-degrade rules so the model cannot regress to God-object APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:06:38 +08:00
254 changed files with 23491 additions and 7390 deletions

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
---
description: Marqdo Web Artifact — no degradation; Document/Endpoint/Resource only
globs: ext/web/**,ext/net/**,ext/data/**,ext/security/**,examples/**/*,tests/ext/web*,doc/design/ext-web*,doc/adr/0007*
alwaysApply: true
---
# Web Artifact — 不允许降级
Canonical: `doc/adr/0007-web-document-endpoint.md` · `doc/design/ext-web-artifact.md` · `doc/next/007.md` (superseded).
## Hard bans
1. **Do not** restore or reintroduce author-facing `compose_main` / `compose_intro` / `compose_*` fragmented table DSLs, god `# page` mutation piles, or `app.configure(...)` junk-drawer APIs.
2. **Do not** use `json.set` / `json.append` bag glue for pages, routes, or middleware. Tables = data. View schema is only `|type|slot|value|attrs|style|` (ZH aliases allowed).
3. **Do not** call `ensure_plugin` or `host_*` from author programs or from `ext/**` (plugin load is facade/capability only).
4. **Do not** register implicit user routes. Declared routes come from Artifact metadata or `web.route`. System routes (`/_part`, `/_form`, …) must appear in `web.inspect`.
5. **Do not** invent DSL, nested frontmatter under `##`, or new table dialects when the design is silent — **stop and ask**.
6. **Do not** mix EN/ZH API names in one `.mq.md`.
7. **Do not** silently delete capabilities. Removals require design text + tests updated in the same change.
8. **Do not** put DB/auth/cache/storage/websocket author APIs back into `ext/web/web.mq.md` — they live in `ext/data`, `ext/security`, `ext/net`.
## Required direction
- Document (`type: web` / `类型: 网页`), Endpoint (`type: endpoint` / `类型: 端点`), Resource modules.
- Facade only: `web.page` · `web.route` · `web.serve` · `web.render` · `web.inspect` (ZH mirrors).
- Code is documentation: the `.mq.md` is the page/API docs and the implementation.
+4 -2
View File
@@ -92,7 +92,7 @@ Better still — call a named helper:
7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead.
8. **Index:** prefer `[键](集合)` / `` [`名`](集合) `` over footnote `` m[^k] ``.
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: `ext/web` + GFM page/style tables.
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: Artifact Metadata (`type: web|endpoint`) + `ext/web` facade + `ext/data` / `ext/security` / `ext/net` — see [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). **Never** restore `compose_*` / `app.configure`.
## Developing libraries (`lib/*`, `ext/*`)
@@ -121,7 +121,9 @@ Canonical thin-template + waves: [lib-code-as-docs.md](../../doc/design/lib-code
| Need | Place |
|------|--------|
| Browser effect maps (WASM client) | `lib/browser.mq.md` |
| Site HTML / HTTP / DB | `ext/web` classes + compose from tables |
| Site HTML / HTTP | `ext/web` Document/Endpoint + View tables |
| DB / cache / storage | `ext/data` |
| Auth / OIDC / RBAC | `ext/security` |
| List/map primitives | `lib/table.mq.md` |
| Parse JSON text | `lib/json.mq.md` only |
+42 -145
View File
@@ -4,95 +4,40 @@ description: >-
Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose,
importing lib/* or ext/web or ext/quantum or ext/linalg, running marqdo CLI,
building dynamic sites with ext/web, quantum circuits with ext/quantum,
formula-first linear algebra with ext/linalg, or when the user mentions
Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, quantum/量子,
or linalg/线性代数 extension.
importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic
sites with ext/web, quantum circuits with ext/quantum, or when the user
mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or
quantum/量子 extension.
---
# Marqdo development
Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python.
Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-mapping-v0.3.md) (**v0.3 · runtime**), `doc/design/keywords.md`. Legacy v0.2 notes: `doc/design/markdown-mapping.md` (historical). Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets, **ext → R2+GitHub**, **CLI → Ubuntu PPA**): use [marqdo-release](../marqdo-release/SKILL.md) — detect versions, **ask for SemVer + mode (`full` / `cli` / `ext`)**, then follow that playbook. Ext-only releases are allowed. If sudo/GPG/PPA steps need the user, print the exact commands.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text="…"**` / `> 打印 内容=…`.
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is **not** code-shaped (`**说明**`, mid-line `*only*`) is ignored — see [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md). Dead `` `名` `` (never read) is OK and does not become a param.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text="hi"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.
2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**.
3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
12. **Bracket-marked calls:** Function name may be marked with `[函数名]`; bare words before `[` are boolean modifiers (`礼貌 [问候] x` → `礼貌=True`). `]` immediately followed by `(` is **index** `[key](coll)`, not a call. Prefer `[k](c)` over footnote index in new code. See [bracket-call-modifiers.md](../../doc/design/bracket-call-modifiers.md).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## 记不住语法细节?查 MLSP(AI 必读)
**不必背 Marqdo 语法细节**——语法可查、程序可验、修复有界。写码前后走**查询式**工作流:
```bash
printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo mlsp
printf '%s\n' '{"id":2,"method":"locate","params":{"path":"a.mq.md","symbol":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":3,"method":"validate","params":{"path":"a.mq.md"}}' | marqdo mlsp
printf '%s\n' '{"id":4,"method":"schema","params":{"path":"a.mq.md","unit":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_mismatch","doc_anchor":"a.mq.md#L9-L15"}}' | marqdo mlsp
```
| method | 何时用 |
|--------|--------|
| `syntax` | 不确定某个语法怎么写(关键字/别名 → 构造卡片:「返回」「表」「调用」「循环」…) |
| `locate` | 找符号定义位置 + 契约;或反查构造卡片 |
| `validate` | 提交前校验(结构化诊断数组;`ok:false` 就修) |
| `schema` | 查单元契约(形参/返回/字段) |
| `repair_targets` | 拿错误的**有界**修复靶点:只改锚点范围内行,越界必弃权(abstain) |
行分隔 JSON:每行请求 `{"id","method","params"}` → 每行响应 `{"id","ok","result"|"error"}`。
语法唯一事实来源 = `doc/design/core-surface.md`(CI 守卫同步);卡片带 `manual` 指回文档行。
所有错误诊断都是结构化 JSON:`code` / `severity` / `span` / `suggestion` / `doc_anchor` / `doc_quote` / `contract_ref`。
### 渐进式契约(可选标注;schema 就长在文档表里)
契约是**未绑定文档表**(绑定表是数据,永远不是契约)。三种形状、严格位置:
| 形状(须含 `类型` 列) | 允许位置 | 附着 |
|--------------------------|----------|------|
| `参数`/`类型`/`说明` 表 + `返回`/`类型`/`说明` 表 | 函数体首个可执行行之前 | 函数 |
| `字段`/`类型`/`可空`/`说明` 表 | 紧邻 `` `名` = `` 绑定之前 | 集合(变量) |
| `字段`/`类型`/`可空`/`说明` 表 | 对象(`#`)体首成员之前 | 对象类型 |
````text
## 加一
对于输入变量`n`,期望是数字。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 加一结果 |
*n+1*
````
- 类型词汇:`text` / `number` / `bool` / `list` / `map` / `any` / `#` 对象名(拼错 ⇒ `contract.unknown_type` + 最近建议)。
- 契约表**永不执行**、不污染升参推断;无契约文件行为逐字节不变(动态默认,零摩擦)。
- 运行时只在四个边界校验:调用实参 / 字段访问 `[键](集合)` / 表绑定 / 返回。
- `marqdo check [FILE] [--json]` 静态互查:契约行 vs 升参推断形参**双向**漂移(错行=Error;新升参未覆盖=Warning)、未知类型、错位契约;有 Error 非零退出。
- 契约诊断带 `doc_anchor` + `doc_quote`(表原文)——修复只照锚点局部改。
## Markup → meaning (v0.3)
## Markup → meaning (v0.2)
| Marker | Meaning |
|--------|---------|
@@ -103,14 +48,13 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `修饰 [fn] args` | Bracket-marked call; leading words → `名=True` |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
| `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
| `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
| `****` or `**` + spaces + `**` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
@@ -159,17 +103,17 @@ Chinese builtins (same functions, no import):
## Statements, returns, branches
```markdown
**x = 1**
**y = x + 2**
*x = 1*
*y = x + 2*
## add_one
+ `n`
*n + 1*
**n + 1**
```
```markdown
**n = 0**
*n = 0*
1. `n` > 0
> print text=positive
@@ -192,16 +136,16 @@ import clock:lib/time.mq.md
# main
**xs = > text.str_split s="a,b,c" sep=","**
*xs = > text.split value="a,b,c" sep=","*
> print text=`xs`
**t = > clock.now_unix**
*t = > clock.now_unix*
```
- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum|linalg` (see `doc/design/ext-cli.md`). **`ext/llm`** — intelligence primitive (`ask` / `stream` / `collect`; `complete` is compat); **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below); **`ext/linalg`** — formula-first linear algebra (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
@@ -217,51 +161,23 @@ Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --releas
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
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).
## Official extension: `ext/web` (dynamic sites)
**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`.
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
Import **one language file** — never mix EN/ZH API names in the same `.mq.md`:
Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md).
**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`.
- EN: `import web:ext/web/web.mq.md`
- ZH: `导入 网页:ext/web/网页.mq.md`
**Hard rules (web):**
- Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON.
- Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes.
- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`.
- **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI (default **Go `libweb`**, build via `scripts/build-web-plugin.sh`).
- HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS).
**Typical layout:**
```text
index.mq.md # entry + home page table + listen
pages/ # sub-pages
components/ # reusable |属性|值|样式| tables
styles/ # CSS modules
public/ # static + favicon.ico|png|svg
db/ # schema + open/init
data/ # sqlite runtime (gitignore)
```
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
**Typical flow:** `db.init` → `page.compose_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)).
**Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **表驱动引言** `page.compose_intro` / `页面.引言装配`(属性/值/样式表 → `.main-intro`,避免手写 HTML 字符串);**D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/) · client: [examples/web-client-site/](../../examples/web-client-site/).
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
## Official extension: `ext/quantum` (circuits + Q7/Q8)
@@ -287,29 +203,13 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea
Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/).
## Official extension: `ext/linalg` (formula-first LA)
Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build --release -p marqdo_plugin_linalg`, then **`marqdo ext add linalg` again** so view loads the new native lib.
- EN: `import la:ext/linalg/linalg.mq.md`
- ZH: `导入 la:ext/linalg/线性代数.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards.
APIs (EN): `symbol` → `# matrix`;中缀 `+`/`-`/`*`;方法 `` `A`.T `` / ``.simplify`` / ``.ascii`` · `from_formula` / `explicit` / `factorize` / `draw` · `lstsq` / `norm` / `cond` / `rank`.
Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · formula-doc: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
## AI authoring workflow
1. **查再写**:不确定语法就 `marqdo mlsp`(`syntax` / `locate`)——不必背语法细节。
2. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
3. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
4. 可选:给函数/集合写**渐进式契约**(上节三种表格形状;写全或不写,别写一半)。
5. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
6. On errors:结构化诊断(含 `doc_anchor` / `suggestion`)→ `repair_targets` 取有界靶点,**只改锚点范围内**的行。
7. 提交前:`marqdo check path/to/file.mq.md`(或 `mlsp validate`)清到零 Error。
8. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
## Anti-patterns (common model mistakes)
@@ -325,13 +225,12 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` to build page parts | GFM tables + `page.compose_*` / `web.page` methods |
| `json.set` / `compose_*` page parts | `type: web` Document + View table / `web.render` / `web.serve` |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([marqdo-dev](../marqdo-dev/SKILL.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_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Call `host_*` from `ext/linalg` | Use `la.*` L1 wrappers; plugin ABI only |
| Bare `kind=eig` inside `*…*` | `kind="eig"` — quote text literals |
| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` |
| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) |
@@ -348,5 +247,3 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
- [ ] 语法拿不准的地方已查 MLSP(`syntax`/`locate`),而不是凭记忆发明
- [ ] 契约(如有)与升参一致:`marqdo check` 零 Error
+13 -7
View File
@@ -126,14 +126,20 @@ jobs:
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **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.1.0**:AI 原生闭环三件套——核心表面守卫 · 渐进式契约 + `marqdo check` · **MLSP for AI** · `run --json`
- **v1.1.0**: AI-native loop — core-surface guard, progressive contracts + `marqdo check`, **MLSP for AI**, `run --json`
- **v1.0.7**:WS/网络边界加固;`url_encode` `%20`
- **v1.0.3**:Ubuntu PPA + 扩展 CDN(ext.marqdo.com)
- **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**: 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**: Browse document-surface Structure — narration, markers, call/loop frames, `#mq-view-trace`, static site parity
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `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 removed
- **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
+6
View File
@@ -87,3 +87,9 @@ tests/ext/:memory:
# local secrets
.env
# sandbox gold leftovers
tests/ext/_sbx_cow/
tests/ext/_sbx_*/
examples/**/_example_sbx/
+238
View File
@@ -8,6 +8,244 @@
### 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
### Highlights
**叙述统一 + 公式 meta + 图片自写回**:块公式 `% marqdo: var=`;分支/循环体与函数体同权叙述;foreach 中英糖;自写回图片 `![marqdo-out](…)`(扩展名校验)与 view/静态站同源标记;view 展示推断形参实值;欢迎页迁到 v0.3 叙述面。
```bash
git checkout v1.4.0 && cargo build --release
marqdo run tests/markup-v03/formula-meta-var.mq.md
marqdo run tests/markup-v03/foreach-narrative.mq.md
marqdo view tests/view/document-annot-demo.mq.md --no-open
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.4.0
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。Language 层在既有 `formula` / `branch-list` / `loop-list` 上扩展语义(块公式 TeX 注释绑定、臂/循环体叙述、foreach 糖);Runtime:自写回图片形态 + view 推断形参展示。设计:[fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)。
### Added
- **块公式 meta 绑定**:`$$` 内 `% marqdo: var=<ident>`(剥离后解析;可无空 RHS);金样 `tests/markup-v03/formula-meta-var.mq.md`。
- **控制流叙述统一**:臂/循环体 `parse_indented_body` 与函数体同权;分支条件行支持叙述前缀与行内 `**…**`;foreach 糖 `- 对…的每一项…` / `- for each … in …`。
- **图片自写回**:路径/URL 且扩展名合法 → `![marqdo-out](…)`;文本仍 HTML 注释;view / `view output` 同源样式卡与 `<img>`。
- **view 推断形参实值**:Browse 展示 body-inferred 参数绑定值;欢迎页 EN/ZH 迁 v0.3 叙述。
### Fixed
- `ext/net/url.encode`:经 `lib/net` 包装,不再直接 `host_*`(金样 `ext_mq_md_never_calls_host`)。
- PPA 源包:`ppa-build-source.sh` 本地 `.orig` 已在 build-area 时跳过重复 `cp`。
- view:嵌套调用欢迎页与公式/代码卡渲染清理。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.0**;词法评论段遇有序分支臂 / 循环头 / 图片自写回标记时断开,避免吞掉控制流行。
## v1.3.3 — 2026-10-15
### Highlights
**view 文档面 Structure**:Browse 保真叙述与标记面(变量/语句/返回无源码定界符);表/循环/分支结构块;语句后绑定值、分支命中臂、函数多调用与循环迭代下拉(默认末帧);`#mq-view-trace` AI JSON。静态 `marqdo view output` 与 live view **同源渲染**(含用户站 `public/` → gh-pages)。
```bash
git checkout v1.3.3 && cargo build --release
marqdo view tests/view/document-annot-demo.mq.md --no-open
marqdo view output public -o public
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.3.3
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 文档面 + 帧选择),不触碰语言标记。
### Added
- **Browse Structure 文档面**(`src/view/document.rs` · `annot.rs`):叙述保真、标记面、GFM 表 / `doc-loop` / `doc-branch`、CSS L-leader 标注带。
- **StmtEvent / CallFrame / LoopFrame** 静默轨迹:post-stmt 绑定、分支 `call_id`、循环 `分 = 分数表[i] · value`;调用/迭代 picker(源码常显,只滤 chip)。
- **`ViewExecutionReport`** JSON(`#mq-view-trace` · `/api/view-trace` · SSE `trace_json`)。
- 设计:[view-document-annotations.md](doc/design/view-document-annotations.md) · [view-execution-trace.md](doc/design/view-execution-trace.md) · [view-frame-selection.md](doc/design/view-frame-selection.md);样例 `tests/view/document-annot-demo.mq.md`。
### Fixed
- 多调用分支 taken 混叠;调用切换误藏未执行臂源码;循环头重复 chip。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.3.3**;静态导出与 live view 共用 `build_file_view` → 文档面。
## Ext pack v1.3.2 — 2026-10-13
### Highlights
**Trailing slash 路由修复(CLI 仍为 v1.3.0)**:Go `ServeMux` 精确匹配导致 `/post/foo/`(带尾部斜杠)落入 404。新增 `withStripTrailingSlash` 中间件作为最外层 handler wrapper,所有下游中间件(RBAC、Tenant、路由)均看到规范化路径。覆盖静态路由、动态路由、根路径、查询参数保留。
```bash
marqdo ext add web # CDN latest → 1.3.2
# 或:MARQDO_EXT_VERSION=1.3.2 marqdo ext add web
```
### Fixed
- **web**: `/post/foo/` trailing slash now routes the same as `/post/foo` (dynamic and static routes). Root `/` unchanged. Query strings preserved after normalization.
## Ext pack v1.3.1 — 2026-10-08
### Highlights
**OIDC 路径型 `redirect_uri`(CLI 仍为 v1.3.0)**:`redirect_uri=/oidc/callback` 按请求 Host / `X-Forwarded-*` 拼绝对回调,写入会话供 token 交换;可选 `redirect_origins` allowlist。apex / www 多域名无需写死单一绝对 URI。
```bash
marqdo ext add web # CDN latest → 1.3.1
# 或:MARQDO_EXT_VERSION=1.3.1 marqdo ext add web
```
### Added
- **路径型 redirect_uri**:绝对 URL 行为不变;路径模式解析 public origin,session 键 `oidc_redirect_uri`。
- **`redirect_origins` / `回调来源`**:逗号分隔 origin allowlist(路径模式)。
- **ABI**:`web_app_oidc` 透传 `redirect_origins`;`ext/security/oidc.attach` 文档同步。
### Changed
- 扩展包 SemVer **1.3.1**(`ext/VERSION`);与 CLI **v1.3.0** 可独立安装。
## v1.3.0 — 2026-09-28
### Highlights
**Engineering Knowledge Compiler(EKC)**:把仓库投影为 AI 可查询的工程知识系统——L0–L4 Catalog、Capability / Decision / Constraint / Failure、知识图、Reuse Preflight(REUSE→ADAPT→CREATE)与 Context Pack。本版 CLI 与扩展包 **同步为 1.3.0**。
- **杀手命令**:`marqdo reuse "task"` / `find` / `duplicate` / `impact` / `conflicts` / `stale` / `verify` / `knowledge`
- **Agent**:`agent.preflight` · `agent_eng_*`;`plan … eng_preflight=True` 在造轮子前强制 EFI
- **投影**:`.marqdo/catalog|knowledge|graph|agent/` + `engineering.yaml`;`catalog` 默认挂钩 EKC
- **示例 / 金样**:`examples/engineering-knowledge/` · `tests/engineering/` · `tests/ext/eng-preflight.mq.md`
```bash
sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo
git checkout v1.3.0 && cargo build --release
marqdo knowledge . -o .marqdo
marqdo reuse "resolve configuration"
marqdo ext add agent
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(知识编译器 + CLI + agent 插件),不触碰语言标记。
### Added
- **`src/knowledge/` EKC**:L0–L4 IR、指纹、能力推导、图边、compile、find/reuse/preflight、impact/lifecycle/duplicate、metrics、policy、learn。
- **CLI**:`knowledge` · `find` · `reuse` · `impact` · `conflicts` · `stale` · `duplicate` · `verify`;`catalog`/`sync` 默认编译 EKC(`--no-knowledge` 可关)。
- **Agent**:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record`;`ext/ai` `## preflight` + `plan eng_preflight`。
- **规范**:`doc/design/engineering-knowledge.md`;提案叙事 `doc/next/008.md`(已实现标注)。
### Fixed
### Changed
- **OKF type 注册表**扩展 Capability/Decision/Constraint/Failure/Context Pack/Policy 等([okf.md](doc/design/okf.md))。
- **核心表面 Δ**:**无增删**。
## v1.2.0 — 2026-09-28
### Highlights
**Web Artifact 重写(ADR 0007)**:Document / Endpoint / Resource 一等公民;`type: web|endpoint`(ZH `类型: 网页|端点`);facade `web.page|route|serve|render|inspect|use`;DB/auth/ws 拆到 `ext/data` · `ext/security` · `ext/net`。本版 CLI 与扩展包 **同步为 1.2.0**。
- **Document**:文件级 Artifact + `data_source` / `data_order` / `data_where`;正文 Markdown → HTML;列表卡片 / 详情文章由 serve 时加载。
- **Endpoint**:`# main` 处理器;请求经 `run_artifact` Binding 注入;`response` 序列化 JSON/text/html。
- **破坏性**:删除作者面 `compose_*` / `app.configure` / 作者 `ensure_plugin`;旧 web gold 移除,新金样 `ext_web_*`。
- **示例**:`examples/marqdo-blog/` Artifact 站(pages/api/db + smoke);`web-client-site` serve 扫描。
```bash
sudo add-apt-repository ppa:cflmy/marqdo && sudo apt update && sudo apt install marqdo
git checkout v1.2.0 && cargo build --release
bash scripts/build-web-plugin.sh && marqdo ext add web
marqdo run examples/marqdo-blog/serve.mq.md
```
**核心表面 Δ(Core surface Δ)**:**无增删**——复用 Metadata `type`;装配语义在 ext + plugin。语言标记不变。
### Added
- **Web Artifact 模型(ADR 0007)**:`type: web|endpoint`(ZH `类型: 网页|端点`);核心 `src/artifact/`;`sys.artifact_kind`;无 `# main` 时 Result 摘要。
- **`ext/web` facade**:`page` · `route` · `serve` · `render` · `inspect` · `use`;子模块 page/route/dom/client/component。
- **`ext/data` · `ext/security` · `ext/net`**:从 monolithic web 拆出 Resource。
- **统一 View** `|type|slot|value|attrs|style|` + ABI `web_render_nodes` / `web_serve_root` / `web_inspect` / `web_app_use`。
- **规则**:`.cursor/rules/web-artifact-no-degrade.mdc`;设计 `doc/design/ext-web-artifact.md`。
### Fixed
- Document `data_source` / `data_where` now drive list cards and detail articles under `web.serve` (ADR 0007 flat metadata).
### Changed
- **破坏性**:删除作者面 `compose_*` / `app.configure` / 作者 `ensure_plugin`。旧 web gold 已移除;新金样 `web-artifact-*` / `ext_web_*`。
- **核心表面 Δ**:**无增删**(复用 Metadata `type`)。
- 修订 `ext-web.md` C1;`doc/next/007.md` superseded。
## v1.1.1 — 2026-09-24
### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "1.1.1"
version = "1.4.2"
dependencies = [
"anyhow",
"assert_cmd",
@@ -603,7 +603,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "1.1.1"
version = "1.4.2"
dependencies = [
"marqdo",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "1.1.1"
version = "1.4.2"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+26 -11
View File
@@ -6,7 +6,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 对象:[objects.md](doc/design/objects.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 **`vscode-extension`**;提交约定 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md)) · **AI Skill**:[skills/marqdo/](skills/marqdo/)(说明 [ai-skill.md](doc/design/ai-skill.md)) · 官方扩展:[ext-llm.md](doc/design/ext-llm.md)(`ext/llm`)· [ext-agent.md](doc/design/ext-agent.md)(智能体开发框架)· [ext-cli.md](doc/design/ext-cli.md)(`marqdo ext list/add/remove`) · 原生插件 ABI:[ext-abi.md](doc/design/ext-abi.md)(`lib/plugin`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) · 变更:[CHANGELOG.md](CHANGELOG.md)
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 对象:[objects.md](doc/design/objects.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · Engineering Knowledge:[engineering-knowledge.md](doc/design/engineering-knowledge.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 **`vscode-extension`**;提交约定 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md)) · **AI Skill**:[skills/marqdo/](skills/marqdo/)(说明 [ai-skill.md](doc/design/ai-skill.md)) · 官方扩展:[ext-llm.md](doc/design/ext-llm.md)(`ext/llm`)· [ext-agent.md](doc/design/ext-agent.md)(智能体开发框架)· [ext-cli.md](doc/design/ext-cli.md)(`marqdo ext list/add/remove`) · 原生插件 ABI:[ext-abi.md](doc/design/ext-abi.md)(`lib/plugin`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) · 变更:[CHANGELOG.md](CHANGELOG.md)
---
@@ -123,6 +123,13 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
```bash
marqdo catalog [PATH] -o OUT_DIR
marqdo sync [PATH] -o OUT_DIR # catalog 的别名
# Engineering Knowledge Compiler(L0–L4 能力目录 / 复用门闩)
marqdo knowledge [PATH] -o OUT_DIR
marqdo find "authentication"
marqdo reuse "implement oauth login"
marqdo duplicate [--fail]
marqdo verify
```
| 参数 | 默认 | 说明 |
@@ -130,7 +137,7 @@ marqdo sync [PATH] -o OUT_DIR # catalog 的别名
| `PATH` | `.` | 工程根或含 `.mq.md` 的目录 |
| `-o` / `--out` | `.marqdo` | 输出目录 |
产物示例:`catalog.yaml`、`index.md`、`modules/*.md`(`type: Marqdo Module` 等)。设计见 [generated-yaml-manifest.md](doc/design/generated-yaml-manifest.md) · 调研 [okf-and-marqdo.md](doc/research/okf-and-marqdo.md)。
`catalog` 成功后默认再跑 EKC(`--no-knowledge` 可关)。产物示例:`catalog.yaml`、`engineering.yaml`、`catalog/capabilities/`、`graph/graph.json`。设计见 [engineering-knowledge.md](doc/design/engineering-knowledge.md) · [catalog-cli.md](doc/design/catalog-cli.md) · 调研 [okf-and-marqdo.md](doc/research/okf-and-marqdo.md)。
智能体框架横向调研(LangGraph / CrewAI / 厂商 SDK 等 vs Marqdo 文档驱动优势):[agent-frameworks-and-marqdo.md](doc/research/agent-frameworks-and-marqdo.md) · 优化路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。
@@ -142,22 +149,30 @@ marqdo catalog public -o .marqdo
---
## 现状(v1.1.1)
## 现状(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)
- **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)
- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure`
- **AI 栈(v1.1.1)**:`ext/ai/llm` 语义 `ask`/`stream`/`collect` · Artifact Metadata Binding(`${env|arg|sys|secret}`)· Agent Skill Compilation + Adaptive Routing · MCP stdio 客户端 + resume 检查点 · 可选 `plugins/llm` Transport ABI
- **AI 原生闭环(v1.1.0)**:核心表面守卫(19 构造,单边改动 CI 必红)· **渐进式契约**(文档内嵌 `参数`/`返回`/`字段` 表 + 四边界校验 + `marqdo check` 防漂移)· **MLSP for AI**(`marqdo mlsp`:`locate`/`syntax`/`validate`/`repair_targets`/`repair_apply`/`schema`,AI 按需查语法而非背诵)· **结构化诊断**(`run --json`,错误即数据);验证见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md)
- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Variables 浮窗)
- **`marqdo view`**:文档浏览器(**文档面** Structure + 标注 / 调用·循环帧 + 函数大纲/搜索 + Execution + Variables 浮窗;`view output` 同构)
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页(默认挂钩 EKC)
- **`marqdo knowledge` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`**:Engineering Knowledge Compiler([engineering-knowledge.md](doc/design/engineering-knowledge.md))
- **`marqdo version --check`**:与 GitHub 最新 release 对比
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**;**中层 Mid M1–M6** + **Mid2 M7–M10**(datetime/url/toml/html/fs++/stats/log.fields 等,见 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md))
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
- **`web`**:W0–W7 + P3 + **W8**;**定制 C0–C4**;**宿主 H1–H2**(`proxy`/`invoke`,见 [ext-hosting.md](doc/roadmap/ext-hosting.md));**表驱动引言**(`compose_intro` / `引言装配`);原生层默认 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md),`scripts/build-web-plugin.sh`);示例 [web-site](examples/web-site/) · [web-site-zh](examples/web-site-zh/) · [marqdo-blog](examples/marqdo-blog/) · [anlian-mq](examples/anlian-mq/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)
- **`web`**:**Artifact 模型(ADR [0007](doc/adr/0007-web-document-endpoint.md))** — `type: web|endpoint` Document/Endpoint;facade `page`/`route`/`serve`/`render`/`inspect`/`use`;Resource 在 `ext/data` · `ext/security` · `ext/net`;设计 [ext-web-artifact.md](doc/design/ext-web-artifact.md);原生 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md));示例 [marqdo-blog](examples/marqdo-blog/) · [web-client-site](examples/web-client-site/) · [anlian-mq](examples/anlian-mq/)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
- **`linalg`**:L0–L6 + 公式文档面(中缀 / `declare` / 展示化简);示例 [linalg-transpose](examples/linalg-transpose/) · [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/)
- **`agent`**:A1–A4 + **MCP Server/Client stdio** + Skill Compilation + Adaptive Routing + resume;宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
- **`agent`**:A1–A4 + **MCP Server/Client stdio** + Skill Compilation + Adaptive Routing + resume + **Engineering preflight**(`agent.preflight` / `eng_preflight`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
- **`llm`**:语义 `ask`/`stream`/`collect`(OpenAI/Ollama;可选原生 `plugins/llm`)
- 安装:`marqdo ext list` / `add …` / `remove`([ext-cli.md](doc/design/ext-cli.md);默认 `~/.marqdo/ext`)。原生插件先 `cargo build -p marqdo_plugin_*` 再 `ext add`
- **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum,linalg,llm}`(`web` 为 Go;其余为 Rust)
@@ -166,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))
- 选型:[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.1.1)
### 如何使用最新 Marqdo(v1.4.2)
**安装解释器(任选其一)**
@@ -181,7 +196,7 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.1.1 # 或留在 main
git checkout v1.4.2 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -211,7 +226,7 @@ marqdo ext add llm # 或:大模型(.mq.md + 可选 native llm)
# 4) 动态站示例(扩展装好后)
marqdo run examples/web-site-zh/index.mq.md # 表驱动引言 Demo
marqdo run examples/marqdo-blog/index.mq.md
marqdo run examples/marqdo-blog/serve.mq.md
marqdo run examples/anlian-mq/index.mq.md # W-G14 验收站
# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8
@@ -220,7 +235,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v1.1.1
# https://github.com/cflmy/marqdo/releases/tag/v1.4.2
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "1.1.1"
version = "1.4.2"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+46
View File
@@ -1,3 +1,49 @@
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: Prose-unified control flow — block formula % marqdo: var=,
arm/loop narrative + foreach sugar, image writeback ![marqdo-out](...),
view inferred-param values; welcome pages on v0.3 prose surface.
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 15:53:00 +0800
marqdo (1.3.3-1ppa1) noble; urgency=medium
* Marqdo 1.3.3: Browse document-surface Structure — narration-preserving
markers, branch/loop frame pickers, ViewExecutionReport JSON; static
view output / gh-pages share the same render path as live view.
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 13:20:00 +0800
marqdo (1.3.0-1ppa1) noble; urgency=medium
* Marqdo 1.3.0: Engineering Knowledge Compiler (EKC) — L0–L4 catalog,
marqdo knowledge/find/reuse/duplicate/verify, Agent preflight
(REUSE→ADAPT→CREATE), graph + context packs.
-- cflmy <pingan@cflmy.cn> Mon, 28 Sep 2026 16:50:00 +0800
marqdo (1.2.0-1ppa1) noble; urgency=medium
* Marqdo 1.2.0: Web Artifact rewrite (ADR 0007) — Document/Endpoint/Resource,
type:web|endpoint, web.serve/render/inspect, ext/data|security|net split,
compose_* author surface removed; marqdo-blog Artifact example.
-- cflmy <pingan@cflmy.cn> Mon, 28 Sep 2026 11:39:04 +0800
marqdo (1.1.1-1ppa1) noble; urgency=medium
* Marqdo 1.1.1: AI stack closure — llm ask/stream/collect, Metadata Binding,
+8 -1
View File
@@ -25,6 +25,7 @@
| [design/return-hr-and-code-surface.md](design/return-hr-and-code-surface.md) | 语句/返回/输出决议 |
| [design/generated-yaml-manifest.md](design/generated-yaml-manifest.md) | 生成式 OKF 清单(早期方向) |
| [design/okf.md](design/okf.md) | **Marqdo OKF 实现规范**(catalog v0 + 任务知识包) |
| [design/engineering-knowledge.md](design/engineering-knowledge.md) | **Engineering Knowledge Compiler(EKC)**:L0–L4、reuse、EFI |
| [design/catalog-cli.md](design/catalog-cli.md) | **`marqdo catalog` / `sync` OKF 清单命令** |
| [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 |
| [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** |
@@ -89,10 +90,16 @@
| [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-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 |
| [design/ext-hosting-fill.md](design/ext-hosting-fill.md) | **宿主缺口补齐设计**(`ext/web` proxy/invoke · `ext/ai` mcp_server) |
| [roadmap/ext-hosting.md](roadmap/ext-hosting.md) | **宿主集成 H0–H4**(规划) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** · 后续优化见 [ext-ai-optimize](roadmap/ext-ai-optimize.md) O 波次 |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+54
View File
@@ -0,0 +1,54 @@
# ADR 0007:Web Document / Endpoint / Resource(破坏性 · 代码即文档)
| | |
|---|---|
| Status | **Accepted** |
| Date | 2026-09-28 |
| Related | [ext-web-artifact.md](../design/ext-web-artifact.md) · [ext-web.md](../design/ext-web.md) · [binding.md](../design/binding.md) · ADR [0006](0006-artifact-metadata-binding.md) · [layers.md](../design/layers.md) · [doc/next/007.md](../next/007.md) |
## Context
- [`ext/web/web.mq.md`](../../ext/web/web.mq.md) 已膨胀为小型 Web Framework(Page God Object、`configure` 垃圾抽屉、碎片 Table DSL、隐式路由),与 Marqdo「代码即文档」冲突。
- [doc/next/007.md](../next/007.md) 提出 Document / Endpoint / Resource 三原语与拆分 `ext/web` · `ext/net` · `ext/data` · `ext/security`。
- 现行 [ext-web.md](../design/ext-web.md) **C1** 禁止为 web 改核心;Document/Endpoint 装载识别需要 Language/Runtime 参与(复用 Artifact Metadata `type`,**不**新增 CORE_CONSTRUCTS 标记)。
- Binding(ADR 0006)已提供文件级 Metadata;`type: prompt` 先例在扩展侧消费 metadata。
## Decision
1. **采纳** Document / Endpoint / Resource 为 Web 模型一等公民;正式规范见 [ext-web-artifact.md](../design/ext-web-artifact.md)。
2. **修订 ext-web C1**:允许核心在装载期识别 `type: web|endpoint`(及中文 `类型: 网页|端点`)并暴露 artifact 分类;**装配 / HTTP / DB 语义仍在 ext + plugin**。单元格求值、import 句法、CORE_CONSTRUCTS 计数不变。
3. **文件级 Artifact only**:不在 `##` 函数体嵌套 `---` frontmatter(与 Binding Phase 1 / 解析器一致)。
4. **破坏性重写作者面**:删除 `compose_*` 碎片 DSL、god `# page` 变异堆、`app.configure` 多参数抽屉、作者 `ensure_plugin`;examples 与 `tests/ext/web*` 同步重写。
5. **目录定稿**(007 §三十五 + §四十):
- `ext/web/` — page · route · component · dom · client · facade
- `ext/net/` — http · websocket · url
- `ext/data/` — db · cache · storage
- `ext/security/` — auth · oidc · rbac
6. **统一 View 表**:`| type | slot | value | attrs | style |`;Table = Data,禁止每函数私有方言。
7. **declared vs system routes**:用户 route 须声明;`/_part` · `/_form` 等为 system,经 `web.inspect` 可见。
8. **import = capability**:`import web:…` 由 facade 自动加载 native plugin;作者程序不写 `ensure_plugin` / `host_*`。
9. **Metadata v1 锁定(原 007 未决项)**:
- 发现:`web.serve root=` 扫描 `root/**/*.mq.md`,仅注册 `type`/`类型` ∈ {web,网页,endpoint,端点} 的文件;无 type 的库文件忽略。
- Data:仅 flat 键 `data_source` · `data_order` · `data_where`(text;where 为 `col=val` 逗号分隔)。嵌套 YAML `data:` 推迟。
- Result:`{ok: bool, value: any, error: text|None}`。
- Realtime 模块名:`ext/net/websocket.mq.md`(ZH:`实时.mq.md`)。
- ZH metadata:`类型`←type,`路由`←route,`方法`←method,`路径`←path,`请求`←request,`响应`←response,`鉴权`←auth,`数据源`←data_source,`排序`←data_order,`条件`←data_where。
## Consequences
### Positive
- `.mq.md` 同时是文档、路由、实现与鉴权声明。
- 与 LLM/Agent Artifact Metadata 统一心智。
- 职责边界清晰,可独立演化 data/security/net。
### Negative / Risks
- 破坏性:全部现有 web 作者程序与 smokes 必须改写。
- Endpoint 热路径仍经 plugin → `CallLibPath` / 文件装载回调;须保持 ABI 稳定演进。
- flat data 键表达力弱于嵌套 YAML;后续另 ADR。
### Neutral
- 不新增 Markdown 核心标记;`${…}` 仍仅 Metadata。
- Go `plugins/web` 可分波删除死 compose ABI;作者面先断。
+5
View File
@@ -23,15 +23,20 @@ YAML / OKF 风格清单是**从 `.mq.md` 派生的生成物**,不是手写配
marqdo catalog [PATH] -o OUT_DIR
# 别名(与早期草案一致)
marqdo sync [PATH] -o OUT_DIR
# 跳过 Engineering Knowledge 投影(仅旧式 catalog)
marqdo catalog [PATH] -o OUT_DIR --no-knowledge
```
| 参数 | 默认 | 说明 |
|------|------|------|
| `PATH` | `.` | 工程根或含 `.mq.md` 的目录(递归扫描) |
| `-o` / `--out` | `.marqdo` | 生成目录(写入前创建;**覆盖**同名生成文件;扫描时跳过该目录) |
| `--no-knowledge` | off | 不跑 EKC;默认在 catalog 成功后编译 L0–L4 / graph |
退出码:成功 0;无可扫描文件或 IO/解析失败非 0(单文件解析失败时写入 `diagnostics` 并继续其余文件,最终若有失败则非 0)。
Engineering Knowledge 命令见 [engineering-knowledge.md](engineering-knowledge.md)(`find` / `reuse` / `duplicate` / …)。
---
## 3. 生成物
+97
View File
@@ -0,0 +1,97 @@
# Engineering Knowledge Compiler(EKC)
| | |
|---|---|
| 状态 | **Accepted(v1 已落地)** |
| 日期 | 2026-09-28 |
| 提案 | [next/008.md](../next/008.md) |
| 相关 | [okf.md](okf.md) · [catalog-cli.md](catalog-cli.md) · [ext-agent.md](ext-agent.md) |
## 1. 定位
Marqdo 把仓库投影为 **可查询、可验证、可复用** 的工程知识系统。Source of Truth 仍是 `*.mq.md`;`.marqdo/**` 是 GENERATED 投影。
```text
.mq.md ──► EKC ──► Executable + Catalog L0–L4 + Graph + Context Pack
│
▼
Agent preflight (REUSE → ADAPT → CREATE)
```
**Engineering First Information (EFI)**:生成代码前先获得已有能力、约束、决策、失败经验与推荐复用。
## 2. 五层 Catalog
| 层 | 内容 | 落盘 |
|----|------|------|
| L0 Repository | 语言/规模 | `.marqdo/catalog/repository.mq.md` |
| L1 Module | imports/exports/responsibility | `.marqdo/catalog/modules/` |
| L2 Symbol | signature/calls/fingerprint | `.marqdo/catalog/symbols/` |
| L3 Capability | 工程能做什么 | `.marqdo/catalog/capabilities/` |
| L4 Knowledge | Decision/Constraint/Failure/… | `.marqdo/knowledge/{decisions,constraints,…}/` |
既有 `marqdo catalog` 根级 `catalog.yaml` / `index.md` / `modules/` / `concepts/` **保留**;`catalog` 成功后默认再跑 EKC(`--no-knowledge` 可关)。
## 3. 知识类型(OKF `type`)
| type | 含义 |
|------|------|
| `Capability` / `Function` | 能力与符号投影 |
| `Decision` | 为什么这样做 |
| `Constraint` | 必须/禁止 |
| `Failure` / `AntiPattern` | 负面知识 |
| `Pattern` / `Migration` / `Fact` | 模式、迁移、事实 |
| `Marqdo Context Pack` | Agent 上下文制品 |
| `Marqdo Policy` | 复用决议编译结果 |
| `Marqdo Engineering Knowledge` | 总览 / `engineering.yaml` |
未知 type 优雅降级(可读,不专属逻辑)。
## 4. 图边
`implements` · `uses` · `depends_on` · `tested_by` · `documented_by` · `constrained_by` · `decided_by` · `supersedes` · `conflicts_with` · `deprecated_by` · `derived_from` · `failed_by` · `related_to`
落盘:`.marqdo/graph/graph.json` · `edges.json` · `index.json`。
## 5. CLI
```bash
marqdo knowledge [PATH] -o .marqdo # compile(默认)
marqdo knowledge preflight "task"
marqdo knowledge record REUSE
marqdo knowledge learn --task ... --failure ...
marqdo find "authentication"
marqdo reuse "implement oauth login"
marqdo impact path/to/file.mq.md
marqdo conflicts | stale | duplicate [--fail] | verify
```
统一 `--json`。`duplicate` 默认阈值 `0.75`;`--fail` 作 CI Gate。
## 6. Reuse 协议
三态:**REUSE → ADAPT → CREATE**(硬顺序)。Reuse budget:`min_candidates` / `allow_create_after`。仅 `create_allowed: true` 时允许盲生成。
## 7. Context Pack
`.marqdo/agent/contexts/task-<id>.mq.md`:Task / Existing Capabilities / APIs / Constraints / Decisions / Failures / Recommended / Forbidden。
## 8. Agent
- Plugin:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record`
- Facade:`agent.preflight` · `agent.eng_reuse` · `agent.eng_record`
- `agent.plan … eng_preflight=True` 在 agent-kb 之前跑 EFI;缺知识图时 `missing_knowledge` 放行(兼容纯 agent-kb 测试)
## 9. 指标
`.marqdo/agent/episodes/reuse_metrics.json`:`reuse_ratio` / `adapt_ratio` / `novel_ratio` / `duplication_rate`。
## 10. 原则(五条)
1. Discover before Create
2. Reuse before Adapt
3. Adapt before Duplicate
4. Verify before Promote
5. Code changes update knowledge
**不做**:以向量库为知识模型;embedding 仅可选检索实现,默认关闭。Hybrid = lexical + symbol + capability + graph。
+4 -3
View File
@@ -4,7 +4,7 @@
|---|---|
| Status | **Accepted · redesign**(取代「thin TOOL: loop」方案) |
| Date | 2026-08-07 |
| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [**调研:主流框架与 Marqdo 优势**](../research/agent-frameworks-and-marqdo.md) · [**缺口:A0–A4 之后**](../research/agent-framework-gaps-after-a4.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) |
| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [**engineering-knowledge.md**](engineering-knowledge.md)(**EKC / EFI preflight**) · [**调研:主流框架与 Marqdo 优势**](../research/agent-frameworks-and-marqdo.md) · [**缺口:A0–A4 之后**](../research/agent-framework-gaps-after-a4.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) |
## 0. 为什么要改掉旧方案
@@ -167,8 +167,9 @@ ext/
**分层纪律(硬规则,勿破)**:
1. `ext/**/*.mq.md` **禁止**出现任何 `host_*` / `host_` 调用。
2. Agent 专属能力(含 OKF agent-kb:`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / …)只进 **`plugins/agent` 注册名**,由 `ext/ai/agent` 在 `plugin.load` 后调用。
3. **禁止**向 `src/host/`(`HostFn` 表)添加 agent / OKF 领域原语,以免核心包体膨胀。通用 L0.5 仅保留 fs/json/subtask 等标准库底层。
2. Agent 专属能力(含 OKF agent-kb:`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / …;以及 EKC:`agent_eng_preflight` / `agent_eng_reuse` / `agent_eng_record`)只进 **`plugins/agent` 注册名**,由 `ext/ai/agent` 在 `plugin.load` 后调用。
3. **禁止**向 `src/host/`(`HostFn` 表)添加 agent / OKF / EKC 领域原语,以免核心包体膨胀。通用 L0.5 仅保留 fs/json/subtask 等标准库底层。
4. **Engineering preflight**:`agent.preflight` / `plan … eng_preflight=True` 在 agent-kb 之前解析 REUSE/ADAPT/CREATE(见 [engineering-knowledge.md](engineering-knowledge.md))。缺 `.marqdo` 知识图时返回 `missing_knowledge` 并放行,以兼容纯任务包测试。
4. 进程退出用 `sys.exit` / `系统.退出`,不用裸 `exit`。
官方 `ext/ai/` 用 `lib/*` 包装或插件注册名;见 [module-namespace.md](module-namespace.md) §8 · [ext-abi.md](ext-abi.md)。
+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`.
+197
View File
@@ -0,0 +1,197 @@
# 官方扩展:Web Artifact(Document / Endpoint / Resource)
| | |
|---|---|
| 状态 | **Accepted · 破坏性(取代 page/app God Object 作者面)** |
| 日期 | 2026-09-28 |
| ADR | [0007-web-document-endpoint.md](../adr/0007-web-document-endpoint.md) |
| 讨论稿 | [doc/next/007.md](../next/007.md)(superseded) |
| 安装 | `marqdo ext add web`(`web` / `网页`) |
| 相关 | [binding.md](binding.md) · [ext-web.md](ext-web.md) · [stdlib-i18n.md](stdlib-i18n.md) · [layers.md](layers.md) |
---
## 0. 一句话
> **Document describes the page. Table describes the data. Endpoint describes the interaction. Metadata describes the runtime. Marqdo executes all of them.**
---
## 1. 三原语
| Artifact | Metadata `type` / `类型` | 含义 |
|----------|--------------------------|------|
| **Document** | `web` / `网页` | Markdown 正文 + View → HTML;`route`/`路由` 注册 declared HTTP |
| **Endpoint** | `endpoint` / `端点` | 可执行正文为 handler;`path`+`method` 注册 API |
| **Resource** | (绑定/导入) | `ext/data` · `ext/security` · 未来 LLM 等,经 metadata / import 声明 |
核心装载识别 `type`/`类型`(见 `src/artifact/`);渲染与 listen 在 `ext/web` + `plugins/web`。
---
## 2. 目录
```text
ext/web/
web.mq.md · 网页.mq.md # facade: page route serve render inspect
page.mq.md · route.mq.md · component.mq.md · dom.mq.md · client.mq.md
ext/net/ http.mq.md · websocket.mq.md · url.mq.md
ext/data/ db.mq.md · cache.mq.md · storage.mq.md
ext/security/ auth.mq.md · oidc.mq.md · rbac.mq.md
```
作者入口通常:
```text
site/
index.mq.md # type: web · route: / · 或 # main → web.serve
pages/*.mq.md # type: web
api/*.mq.md # type: endpoint
data/ # sqlite runtime (gitignore)
```
---
## 3. Document(`type: web`)
```markdown
---
type: web
title: Marqdo Blog
route: /
method: GET
data_source: posts
data_order: -created_at
import web:ext/web/web.mq.md
import data:ext/data/db.mq.md
---
# Marqdo
Welcome to the executable web.
```
| 键 (EN) | 键 (ZH) | 说明 |
|---------|---------|------|
| `type` | `类型` | `web` / `网页` |
| `route` | `路由` | 路径,可含 `{param}` |
| `method` | `方法` | 默认 `GET` |
| `title` | `标题` | 文档标题 / `<title>` |
| `data_source` | `数据源` | 表名 |
| `data_order` | `排序` | 如 `-created_at` |
| `data_where` | `条件` | `col=val,col2=val2` |
正文 Markdown 经 `dom` 变为 DOM Artifact,再 `web.render`。可选 View 表:
```markdown
`nodes` =
| type | slot | value | attrs | style |
|------|------|-------|-------|-------|
| text | kicker | AI Native | | eyebrow |
| title | title | Marqdo | | title |
```
`page.render nodes=` 是**唯一**主装配路径。禁止 `compose_main` / `compose_intro` 等碎片 DSL。
---
## 4. Endpoint(`type: endpoint`)
```markdown
---
type: endpoint
method: POST
path: /api/posts
request: json
response: json
auth: member
import data:ext/data/db.mq.md
---
**post = > data.db.insert …**
*post*
```
| 键 (EN) | 键 (ZH) | 说明 |
|---------|---------|------|
| `type` | `类型` | `endpoint` / `端点` |
| `path` | `路径` | URL |
| `method` | `方法` | GET/POST/… |
| `request` | `请求` | `json` / `form` / `none` |
| `response` | `响应` | `json` / `text` / `html` |
| `auth` | `鉴权` | 角色名或 `none` |
正文在请求时执行;返回值按 `response` 序列化。Result 协议见 §8。
**Handler 约定(锁定)**:Endpoint 文件用 `# main` 作为请求处理器。请求体/query/path 参数经 `run_artifact` 以 Metadata Binding 覆盖注入(与 `--bind` 同源),正文用已提升的普通变量名。无 `# main` 时返回 Artifact Result 摘要(`ok`/`value`/`error`),适合作文档型 ping。
---
## 5. Facade API(EN / ZH)
| EN | ZH | 作用 |
|----|-----|------|
| `web.page` | `网页.页面` | 从 metadata/正文/nodes 构造 Document 句柄 |
| `web.route` | `网页.路由` | 注册 declared Document 或 Endpoint |
| `web.serve` | `网页.服务` | `root=` 扫描注册 + listen |
| `web.render` | `网页.渲染` | Document → HTML(离线/预览) |
| `web.inspect` | `网页.检视` | `{declared, system}` 路由表 |
Middleware 一等:`web.use` / `route.use`,表驱动;**禁止** `configure(cors, security, …)` 垃圾抽屉。
---
## 6. 发现算法(锁定)
`web.serve root=DIR host=… port=…`:
1. 递归枚举 `DIR` 下 `*.mq.md`(跳过 `data/`、隐藏目录、`node_modules`)。
2. 解析文件头 Metadata;无 `type`/`类型` 或非 web/endpoint → 跳过。
3. Document → declared route(缺 `route` 则相对 `root` 的路径映射,`index.mq.md` → `/`)。
4. Endpoint → declared path+method(`path`/`路径` 必需)。
5. System routes(`/_part/*`、`/_form/*`、静态等)由 runtime 挂载,仅出现在 `inspect.system`。
6. 调用 native listen。
---
## 7. Table 规则
- **View**:仅 `|type|slot|value|attrs|style|`(及列名 ZH 别名:`类型|槽|值|属性|样式`)。
- **Resource schema**:`|字段|类型|可空|` 等 — 专用且文档化,不是函数私有方言。
- **禁止** `|属性|值|样式|` / `|front|back|css|` / `|组件|样式|` 作为页面主装配(已删除)。
- Raw HTML/CSS = escape hatch(`dom.raw` / `page.css`),不是默认语言。
---
## 8. Result
所有易失败的 Resource / Endpoint 边界返回 map:
| 键 | 类型 | 说明 |
|----|------|------|
| `ok` | bool | 成功 |
| `value` | any | 成功载荷 |
| `error` | text \| None | 失败信息 |
---
## 9. 硬约束(取代旧 C1–C7 作者面)
| # | 约束 |
|---|------|
| A1 | Document/Endpoint 由核心识别 `type`;装配在 ext(ADR 0007) |
| A2 | 禁止 `json.set` 袋胶水;Table = Data |
| A3 | 中英分文件;同文件禁止混 API |
| A4 | 禁止作者 `ensure_plugin` / `host_*` |
| A5 | 禁止隐式用户 route;system 须 `inspect` 可见 |
| A6 | 禁止恢复 `compose_*` / `app.configure` / god page 变异堆 |
| A7 | 能力只许迁移/提升;删除须本设计明示 + tests 同步 |
| A8 | 设计未锁定处停工提问,禁止自行发明 DSL |
---
## 10. 与旧 ext-web.md
旧「页面表 + compose_* + app.route」作者面 **废止**。历史能力矩阵见 [web-net-capabilities.md](web-net-capabilities.md);迁移后以本文件与 ADR 0007 为准。
+17 -13
View File
@@ -2,18 +2,21 @@
| | |
|---|---|
| 状态 | **Accepted · W0–W7 + P3 + W8(站点图标/Head/图片装配)完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap / **favicon·头资源·图片装配**;Postgres 等见 §9) |
| 日期 | 2026-08-11(W8:2026-08-29;请求上下文:2026-09-18) |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) · **[ext-web-request-context.md](ext-web-request-context.md)** |
| 状态 | **Superseded(作者面)· 历史能力档案** — 现行作者面见 **[ext-web-artifact.md](ext-web-artifact.md)** · ADR [0007](../adr/0007-web-document-endpoint.md) |
| 日期 | 2026-08-11(W8:2026-08-29;请求上下文:2026-09-18;Artifact 重构:2026-09-28) |
| 相关 | [ext-web-artifact.md](ext-web-artifact.md) · [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) · **[ext-web-request-context.md](ext-web-request-context.md)** |
| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) |
| 本文目的 | 锁定**作者面**与**类 API**;指导实现 |
| 本文目的 | **历史**类 API 与能力矩阵;新站请勿按本文 `compose_*` / `app.configure` 写作 |
> **2026-09-28**:作者面迁移到 Document / Endpoint / Resource。C1 已由 ADR 0007 修订。下文保留作迁移对照,**不是**现行推荐 API。
---
## 0. 一句话
`ext/web` 用 **GFM 表格 + Marqdo 类方法** 描述动态网站:表仍是字典/列表嵌套;类方法把表装配成可渲染页面。
**不改 Marqdo 核心语法**;扩展库存在的理由,正是让「文档即代码」在网站场景下成立。
**现行**:`.mq.md` Artifact(`type: web|endpoint`)描述页面与交互;见 [ext-web-artifact.md](ext-web-artifact.md)。
**历史(废止)**:`ext/web` 曾用 GFM 表格 + `# page`/`# app` 类方法拼装站点。该模型因 God Object / 碎片 DSL / 隐式路由被破坏性替换。
---
@@ -41,13 +44,14 @@
| # | 约束 |
|---|------|
| C1 | **禁止**为 web 改动 Marqdo 核心:单元格求值、import、点号值读取等保持不变 |
| C2 | 作者面**禁止** `json.parse` / `json.set` 袋胶水、手写 part JSON、手写 assemble 袋 |
| C3 | 能力以 **`#` 类 + `##` 方法** 暴露;**英文库文件只用英文名,中文库文件只用中文名**(见 [stdlib-i18n.md](stdlib-i18n.md));同一 `.mq.md` 内禁止中英 API 混排 |
| C4 | 首页在 **`index.mq.md`**:页面表在此;可复用片段进 `components/`;主体可就地写 |
| C5 | **旧有网络扩展库全部废弃**:`plugins/web`、`ext/web/**`(含现网示例/gold 中依赖旧 API 者)评审通过后**删除或清空后重写**;禁止在旧代码上打补丁演进。**落实**:原生层 Go 全量重写见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md);作者面 ABI 名保持兼容 |
| C6 | `# db` / `# 数据库` 必须提供完整**增删改查**;列表查询英文方法名为 **`select`**(中文 **`查询`**);后台 `/admin` 与表单提交走同一套写库 API |
| C7 | 用户输入经 `# form` / `# 表单`:字段表 + 校验表;**服务端校验必须在写库前执行**(见 §5.5) |
| C1 | **修订(ADR 0007)**:核心可识别 Artifact `type: web\|endpoint`(及 ZH);**不**新增 CORE_CONSTRUCTS 标记;单元格求值 / import 句法不变;装配语义仍在 ext + plugin。旧文「禁止为 web 改核心」作废 |
| C2 | 作者面**禁止** `json.parse` / `json.set` 袋胶水(现行见 ext-web-artifact A2) |
| C3 | 中英分文件;同文件禁止混 API(现行 A3) |
| C4 | **废止**「页面表 + compose」心智 → Document Artifact + `pages/` · `api/` |
| C5 | 破坏性重写作者面(ADR 0007);原生 Go 演进见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md) |
| C6 | DB 迁至 **`ext/data`**;CRUD 仍须完整(`select` / `查询`) |
| C7 | 表单校验仍须在写库前执行;挂载经 declared Endpoint / system `/_form`(inspect 可见) |
| A1–A8 | **现行硬约束**见 [ext-web-artifact.md](ext-web-artifact.md) §9 |
---
@@ -0,0 +1,60 @@
# 块公式元数据绑定 · 控制流叙述统一
| | |
|---|---|
| 状态 | Active |
| 日期 | 2026-10-15 |
| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 块公式 `% marqdo: var=`
在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体):
```markdown
$$
% marqdo: var=f
x^2 - 2
$$
```
- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。
- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。
- **保留**旧空 RHS + 后随 `$$`。
- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。
- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。
无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。
---
## 2. 臂 / 循环体叙述(与函数体同权)
`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。
斜体返回结束**当前臂或当前循环体**,不结束外层函数。
---
## 3. 循环头
| 面 | 写法 | 说明 |
|----|------|------|
| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 |
| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 |
| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` |
糖与链接头语义相同,可混用嵌套。
---
## 4. 分支条件行叙述
结构行仍以 `1.` / `2.` 开头。条件提取顺序:
1. 整段可解析为表达式(现状);
2. 行内粗体代码条件 `**`n` > 0**`;
3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。
else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。
禁止无标记自然语言整句当条件。
+3 -1
View File
@@ -215,7 +215,9 @@ v0.3:
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
| ` ```lang ` | 外联(不变) |
| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) |
| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) |
| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` |
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
+28 -7
View File
@@ -143,13 +143,18 @@ Marqdo 对齐的判断是:
| `type` | 状态 | 含义 | 主要生产者 |
|--------|------|------|------------|
| `Marqdo Catalog` | **v0 已实现** | 包总览(`catalog.yaml` / `index.md`) | `marqdo catalog` |
| `Marqdo Module` | **v0 已实现** | 一个 `.mq.md` 模块的投影 | `marqdo catalog` |
| `Marqdo Task` | **规范已定;实现待做** | 一项可匹配的任务意图 | `plan` 晋升 |
| `Marqdo Agent Skill` | **规范已定;实现待做** | 指向可执行工作簿的技能 | `plan` 晋升 |
| `Marqdo Catalog` | **已实现** | 包总览(`catalog.yaml` / `index.md`) | `marqdo catalog` |
| `Marqdo Module` | **已实现** | 一个 `.mq.md` 模块的投影 | `marqdo catalog` |
| `Marqdo Task` | **已实现** | 一项可匹配的任务意图 | `plan` 晋升 |
| `Marqdo Agent Skill` | **已实现** | 指向可执行工作簿的技能 | `plan` 晋升 |
| `Capability` / `Function` | **EKC** | 工程能力 / 符号投影 | `marqdo knowledge` |
| `Decision` / `Constraint` / `Failure` / `AntiPattern` / `Pattern` / `Migration` / `Fact` | **EKC** | L4 工程知识 | 源 frontmatter + learn |
| `Marqdo Context Pack` | **EKC** | Agent EFI 上下文制品 | `reuse` / `preflight` |
| `Marqdo Policy` | **EKC** | 复用决议编译 | `marqdo reuse` |
| `Marqdo Engineering Knowledge` | **EKC** | 工程知识总览 | `engineering.yaml` / `index.mq.md` |
| 其他 | 开放 | 第三方/未来扩展 | — |
**不**引入 Google OKF 的 `Metric` / BigQuery 表类型作为 Marqdo 核心词汇;需要时可由用户包自行使用,运行时降级。
完整 EKC 规范见 [engineering-knowledge.md](engineering-knowledge.md)。
---
@@ -309,10 +314,15 @@ type: Marqdo Agent Skill
title: <短名>
sig: <12hex>
resource: ../../resources/<slug>.mq.md
status: stable | candidate
status: stable | candidate | quarantine
llm_free: true | false
quality: <int>
hits: <int>
# O2 optional metadata (from workbook frontmatter; see §7.5):
applies_when: <text condition or tag>
fixtures: <relative .mq.md proof path>
sandbox_profile: default | readonly | <name>
proof: <relative .mq.md> # alias of fixtures for sandbox gate
generated:
by: marqdo-agent/plan
at: <ISO8601>
@@ -326,7 +336,7 @@ verified:
Prefer spawning `resource` over re-planning.
```
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。**O2:** `agent_kb_promote` 默认要求 sandbox proof(`proof` / `fixtures` / workbook 本身经 `sandbox.run` 成功)才写入;失败返回 `promoted: false` / `reason: sandbox_proof_failed`。传 `require_proof=false` 仅用于明确豁免。
### 7.3 任务签名 → Concept 路径
@@ -396,6 +406,17 @@ Prefer spawning `resource` over re-planning.
| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` |
| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 |
| 分发 | 整包 `agent-kb/` 可复制(格式即契约) |
| **证明晋升(O2)** | `applies_when` / `fixtures` / `sandbox_profile` / `proof` 写在技能与 workbook frontmatter;promote 前 `sandbox.run` 绿才 `llm_free` |
| **隔离(O5)** | 失败技能 `status: quarantine`;回归 fixture 跟随 slug |
### 7.5a 技能 frontmatter 约定(O2 B1)
| 字段 | 含义 |
|------|------|
| `applies_when` | 适用条件(短文本 / 标签);路由与 harness 可读 |
| `fixtures` | 相对路径:sandbox 证明用 `.mq.md` |
| `sandbox_profile` | `default` / `readonly` / 其它 `sandbox.profile` 名 |
| `proof` | 与 `fixtures` 同义;promote 优先读 `proof` 再 `fixtures`,否则跑 workbook 自身 |
---
+14 -4
View File
@@ -34,7 +34,16 @@
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)):
````markdown
$$
% marqdo: var=f
sin(x) + x
$$
````
**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致):
````markdown
# main
@@ -52,13 +61,14 @@ $$
也支持:
- 单行围栏:下一行 `$$x^2 - 2$$`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面)
- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ ``
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。
### 2.3 从文本构造
+22 -5
View File
@@ -8,9 +8,11 @@
## 定位
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。
## 存储格式
## 存储格式(两种,可并存)
### 1. HTML 注释(文本 / 结构化输出)
```markdown
*`n` = > len value=`xs` *
@@ -30,11 +32,26 @@ pending
-->
```
- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
### 2. Markdown 图片(生成图 / 审计友好)
当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成:
```markdown
![marqdo-out](plots/out.svg)
![marqdo-out ok](plots/ok.png)
```
- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。
- 非图片路径仍走注释块;把非图片硬写成 `![marqdo-out](…)` 时扫描会忽略(校验失败)。
- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。
### 共用规则
- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
- 默认在**调用行下方**插入或替换紧邻**无键**块
- `at_end=true`:替换文件末尾的**无键**块
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文
- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁
### 替换跨度与空行
+1 -1
View File
@@ -4,7 +4,7 @@
|---|---|
| 状态 | 已定 |
| 日期 | 2026-08-04 |
| 相关 | [view.md](view.md) · 源目录 [`public/`](../../public/) |
| 相关 | [view.md](view.md) · [view-static-interactive.md](view-static-interactive.md)(静态交互 / 公式代码视觉 · Proposal) · 源目录 [`public/`](../../public/) |
---
+3 -3
View File
@@ -4,14 +4,14 @@
|---|---|
| 状态 | **v1(独立 debug 页)** |
| 日期 | 2026-08-05 |
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [pipeline-debug.md](pipeline-debug.md) |
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [view-document-annotations.md](view-document-annotations.md) · [pipeline-debug.md](pipeline-debug.md) |
## 分工
| 命令 | 角色 |
|------|------|
| `marqdo view` | 文档浏览器:Structure + Execution + Source;函数大纲与搜索;**无断点** |
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;**仅 live** |
| `marqdo view` | 文档浏览器:**叙述保真文档面** Structure + Execution + Source;函数大纲与搜索;跑后引出标注;**无断点**(见 [view-document-annotations.md](view-document-annotations.md)) |
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;AST Structure + BP;**仅 live** |
静态 `gh-pages` / `view output` **不能**真断点。
+113
View File
@@ -0,0 +1,113 @@
# View:文档面与结果引出标注
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 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) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 动机
`.mq.md` 是叙述与程序的同一载体。`marqdo view` 的 Structure 必须**保真叙述**,并在可执行标记旁展示运行结果。
旧 Browse Structure 用 AST 卡片重建语句,并用 `emit_comments` 只插入**语句行之前**的注释。当叙述与 `**…**` / `*…*` / `` `名` `` 在同一行时,该行被 Stmt 占用,叙述被丢弃——信息密度接近 debug,不适合文档浏览。
## 2. 模式分工
| 命令 | Structure | 叙述 | 结果 |
|------|-----------|------|------|
| `marqdo view`(Browse) | **文档面** | 保留并为主 | 跑后引出标注(callout + CSS L-leader) |
| `marqdo debug` | AST 卡片 + BP gutter | 弱化/可折叠 | Variables / 步进;不做文档 callout |
断点与逐步执行**仅**在 debug。静态 `view output` 与 live view **共用** Browse 文档面渲染。
## 3. 视觉语法
```
文本段…… `变量` …… **语句** …… *返回*
━━━━━
│
└──→ 结果标注
```
1. 叙述正文正常排版(Markdown)。
2. 可执行片段高亮,并带底部分割线(underline)。
3. 段落下方 **annotation band** 放结果 callout。
4. **CSS L-leader**(绝对定位小盒 + `border-left` + `border-bottom`)连接锚点与 callout。**不使用 SVG。**
5. 拥挤 / 极窄屏 / `prefers-reduced-motion`:取消长横折,改为编号 keyed 列表。
关联强度(递减):同色 underline + callout 色条 + label → CSS L-leader → keyed 编号。
对齐 [view.md](view.md) HIG:系统字体、无外链、浅色、克制装饰。
## 4. 文档面渲染
实现:`src/view/document.rs`;Browse 入口经 `render_module_structure` 调用。
| 源内容 | 呈现 |
|--------|------|
| 纯叙述段 | Markdown HTML;无 `comment` badge / 厚卡片 |
| 含 `ProseBit` 的行 | 原文保留;Decl / BoldCode / ItalicReturn 包 `mark.mq-anchor`(字节偏移来自 `scan_prose_line`) |
| 整行结构(`#` / `>` / `-` / `1.` / 表) | 表面语法保真(见 [view-markup-surface.md](view-markup-surface.md));整句可作锚点 |
| 函数标题 | 轻量 heading + `id="fn-{line}"`(大纲跳转不变) |
Debug 仍走 `render_module_structure_mode(..., Debug)` 的 AST 卡片路径。
## 5. ViewAnnot
跑后(或 `--no-exec` 时为空)组装标注集,嵌入文档面 `data-*` 与 band HTML。
| 字段 | 含义 |
|------|------|
| `id` | 稳定短 id(页内唯一) |
| `kind` | `bind` · `return` · `call` · `expr` · `branch` · `loop` · `writeback` |
| `anchor_line` | 1-based 源行 |
| `anchor_byte_start` / `anchor_byte_end` | 行内字节范围(可选;整行锚点可省略 end) |
| `label` | 短标题(名 / return / arm / loop) |
| `value` | 截断显示 |
| `detail` | 完整文本(inspect) |
| kind | 数据来源 | 锚点 |
|------|----------|------|
| `bind` | **StmtEvent post-stmt**(赋值执行后的值);禁止用入口终态回填初始化行 | 该赋值行 |
| `return` | 返回事件或入口返回 | ItalicReturn / Return |
| `call` / `expr` / `writeback` | writeback 槽、调用摘要 | 语句行或 BoldCode |
| `branch` | `ViewTrace`:命中 arm、次数 | 条件 / arm |
| `loop` | `ViewTrace`:迭代次数、末次 item | While / ForEach 头 |
标记面、结构块、多调用帧与 AI JSON 见 [view-execution-trace.md](view-execution-trace.md)。
`ViewTrace` 由 tree 解释器在 capture 时静默收集,**不**写入 stderr;与 `trace_eval` 调试轨迹分离。Bytecode 后端可暂无 trace(标注降级为 writeback)。
## 6. 布局与密度
- 每段默认最多 **4** 个常显 callout;其余 hover / 「show more」。
- Leader:按锚点 x 排序 callout,避免交叉;窄屏改为短竖线 + 堆叠。
- 客户端:`ResizeObserver` 重算 leader 盒的 `left/top/width/height`。
- 静态导出:页载 JS 跑一次布局。
右侧 **Variables** 仍为全集绑定;callout 为就地摘要,点击可打开同一 inspect。
## 7. 非目标
- 不在 view 内做断点 / 单步(见 [view-debug.md](view-debug.md))。
- 不新增作者侧标注 DSL / frontmatter 指令。
- 不引入外链字体、npm 组件或 SVG leader。
- 不把 DB/auth 等塞进 view 壳层。
## 8. 验收
1. `inc-prose.mq.md`:叙述「对于输入变量…」完整可见;`n` / `n=n+1` / 返回高亮。
2. 跑完后:值经 underline + CSS L-leader 连到下方标注(无 SVG)。
3. 分支/循环样例:可见命中 arm 与迭代次数(有 ViewTrace 时)。
4. `marqdo debug` 仍为 AST + 断点;叙述不抢主视觉。
5. 无外链字体/新依赖;`view output` 可离线打开。
## 9. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:文档面、ViewAnnot、CSS L-leader、与 debug 分工 |
| 2026-10-15 | bind = post-stmt;交叉链 view-execution-trace |
+103
View File
@@ -0,0 +1,103 @@
# View:执行轨迹与文档面保真
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [view.md](view.md) · [view-markup-surface.md](view-markup-surface.md) |
---
## 1. 目标
`marqdo view` Browse Structure 必须同时做到:
1. **标记面**:变量名 / 可执行语句 / 返回值按表面渲染(无源码定界符字面量)。
2. **结构块**:GFM 表、循环(`-`)、分支(`1.`)有正确 HTML 与缩进。
3. **语句后值**:赋值行标注该语句执行后的值,不用入口终态回填。
4. **执行臂**:高亮实际走的分支臂。
5. **多调用帧**:同函数多次调用可用下拉切换经历。
6. **AI 可读**:与 HTML 同源的 `ViewExecutionReport` JSON。
Debug 仍用 AST 卡片 + 断点;不做文档 callout。
## 2. 标记面
| 源标记 | 显示(无定界符) | class |
|--------|------------------|-------|
| `` `名` `` / `` `名`=默认 `` | `名`(默认次要后缀) | `mq-anchor mq-decl` |
| `**…**`(可执行) | 内层文本 | `mq-anchor mq-code` |
| `*…*`(返回) | 内层文本 | `mq-anchor mq-return` |
`data-byte-start/end` 仍为源码字节偏移(供 CSS L-leader)。软强调不进 anchor。
## 3. 结构块
| 块 | 呈现 |
|----|------|
| GFM 表 | `<table class="doc-table">` |
| `-` 循环 | `<ul class="doc-loop">`,体按源缩进 `--doc-indent` |
| `1.` 分支 | `<ol class="doc-branch">`;命中 `arm-taken`,未走 `arm-miss` |
| 公式 / 外联代码 | 现有 formula-card / code-card |
| `>` 调用 | 表面高亮,非整行灰 code |
## 4. StmtEvent / CallFrame
解释器 capture 时静默采集(非 `trace_eval` stderr):
```text
StmtEvent {
line, kind, // assign | return | call | branch | loop | bind_ref
name?, value_after?, // post-stmt 或求值结果
arm_index?, iter?,
call_id // 当前用户函数调用帧
}
CallFrame {
call_id, fn_name, fn_line, ordinal,
args_brief, // 短摘要供下拉
events[] // 或全局 events 用 call_id 过滤
}
```
- Assign → 写入后的值挂在**该行**。
- 循环内多次写入:UI 默认末次;可带次数。
- Branch → taken `arm_index` + 条件摘要。
- 进入用户函数分配 `call_id`;`# main` 单帧无下拉。
## 5. ViewExecutionReport(AI)
```json
{
"version": 1,
"path": "…",
"ok": true,
"calls": [{ "call_id": 1, "fn": "等级说明", "ordinal": 1, "args_brief": "等级=及格" }],
"events": [{ "line": 24, "kind": "assign", "name": "总分", "value_after": "0", "call_id": 0 }],
"bindings_final": { "均分": "73", "等级": "及格" }
}
```
产出:页内 `#mq-view-trace` JSON;live `GET /api/view-trace?path=`;SSE `done.trace_json`。
## 6. UI
- 函数标题旁 `<select class="call-picker">`(调用数 ≥ 2)。
- 循环头旁 `<select class="loop-picker">`(迭代数 ≥ 2);默认最后一轮;摘要 `分 = 分数表[i] · value`。
- **源码常显**:切换帧只改 chip / 臂高亮,不 `hidden` 结构节点。详见 [view-frame-selection.md](view-frame-selection.md)。
- CSS L-leader(非 SVG);拥挤 keyed 降级。
## 7. 验收
1. 无字面 `**` / 返回定界 `*` / 变量外层 `` ` ``(Source 除外)。
2. 表为真表格;循环/分支有缩进列表;未选中臂源码仍可见。
3. `总分 = 0` 标注 `0`,非终态累加。
4. 命中臂可视化;多调用下只显示当前帧的 taken。
5. 循环可按迭代切换;JSON 含 `loops`;单测覆盖。
## 8. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:标记面、结构块、StmtEvent、CallFrame、AI 报告 |
| 2026-10-15 | 帧选择保真:call_id 分支、LoopFrame、源码常显 |
+123
View File
@@ -0,0 +1,123 @@
# View:调用帧 / 循环帧选择与结构保真
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-execution-trace.md](view-execution-trace.md) · [view-document-annotations.md](view-document-annotations.md) |
---
## 1. 问题(对照实测)
1. **结构缺失**:切换函数调用下拉时,JS 按 `data-call-id` **隐藏** `.doc-exec`。未在本帧执行的分支臂体(赋值/返回)只有其它帧的 call_id,或仅有执行帧的 id → **未选中臂的源码被藏掉**,看起来像「臂消失 / 代码没渲染」。
2. **调用记录混叠**:`Branch` 标注未带 `call_id`;`taken_arms` 按行号只保留最后一次命中。多帧下同一分支同时出现 `arm 1 taken` 与 `arm 2 taken`。
3. **循环无帧**:循环只有总次数摘要;无法按迭代查看;`` - [分](分数表) `` 不能展示「当前是集合第几个元素」。
## 2. 定稿原则
| 原则 | 含义 |
|------|------|
| **源码常显** | 表 / 列表 / 分支臂 / 语句源码**永不**因帧选择 `hidden` |
| **轨迹随帧** | 标注 chip、臂高亮、变量值随「当前调用帧 / 当前迭代」变化 |
| **默认末帧** | 函数默认最后一次调用;循环默认最后一次迭代 |
| **一帧一真相** | 同时只展示一个 call_id(函数)或一个 (loop_id, iter)(循环)的轨迹 |
## 3. 函数调用帧
### 数据
`BranchHit` / 相关 `StmtEvent` 必须带 `call_id`。`ViewAnnot` 的 branch/bind/return 同样带 `call_id`。
### UI
- 函数标题旁 `<select class="call-picker" data-fn="…" data-scope="fn">`
- 选项:`1: 等级=及格` / `2: 等级=优秀`
- 默认选中最后一次
### 客户端(`applyCallFrame`)
1. 读 `#mq-view-trace` JSON。
2. 过滤 `events` where `call_id == selected`。
3. **不**设置结构节点 `hidden`。
4. 更新该函数作用域内:
- `.annot-chip[data-call-id]`:仅显示匹配帧;无 call_id 的结构说明类可保留
- `.doc-branch[data-line]`:按该帧的 branch 事件设置 `arm-taken` / `arm-miss`(全部臂仍可见)
- 绑定 chip 的 `.annot-value`:用该帧 assign/return 事件刷新(同名同行取末次)
## 4. 循环迭代帧
### 数据
```text
LoopFrame {
loop_id, line,
item_name?, // "分"
collection?, // "分数表"
iterations: [{ index, item_value, call_id }] // index 0-based
}
```
`StmtEvent` 增加可选 `loop_id`;循环体内事件带 `iter`(1-based 或 0-based,JSON 内统一 **0-based index**)。
### UI
- 循环头(`- [分](分数表)`)旁:`<select class="loop-picker" data-loop-id="…">`
- 选项:`迭代 1: 分=92` … `迭代 4: 分=88`
- 默认最后一次
- 头旁摘要 chip:`分 = 分数表[3] · 88`(下标 0-based 显示为 `[i]`)
### 客户端(`applyLoopFrame`)
1. **只显示当前迭代**:带 `data-iter` 的 chip 仅保留选中项;其余 `hidden` + `is-frame-hidden`(SSR 默认已按末轮预隐藏)。
2. 更新头摘要 chip(无 `data-iter`)为当前选项文案。
3. 不隐藏循环体源码。
## 5. 分支臂渲染
- 所有臂(含 else)**始终**渲染完整头 + 体(含 `*返回*` / 赋值)。
- `arm-miss` 仅降低不透明度,**不** `display:none` / `hidden`。
- 高亮仅反映**当前帧**的 taken `arm_index`。
## 6. AI JSON 增量
`ViewExecutionReport` 增加:
```json
"loops": [{
"loop_id": 1,
"line": 27,
"item": "分",
"collection": "分数表",
"iters": [{ "index": 0, "value": "92" }, { "index": 3, "value": "88" }]
}]
```
`events[].call_id` 必填;循环体内事件带 `loop_id` + `iter`(index)。
## 7. 验收
1. 未选中分支臂源码始终可见(含返回句)。
2. 切换「等级说明」调用:只显示该帧的 arm taken;变量/返回值对应该帧。
3. 循环下拉默认最后一轮;`分 = 分数表[3] · 88`;切换迭代后体内累加值变化。
4. `#mq-view-trace` 含 `loops` 与带 `call_id` 的 branch 事件。
5. `cargo test --lib view::` 全绿。
## 8. 开发计划(已执行)
| 阶段 | 内容 | 状态 |
|------|------|------|
| D0 | 本文档 + `view-execution-trace.md` 交叉引用 | ✅ |
| D1 | `BranchHit.call_id`;`LoopFrame` / `LoopIter`;`StmtEvent.loop_id` | ✅ |
| D2 | 解释器:foreach/while 推栈;BindRef `分=分数表[i]`;assign 带 iter | ✅ |
| D3 | `build_view_annots`:分支带 call_id;LoopFrame 选项;报告 JSON `loops` | ✅ |
| D4 | 文档面:源码不贴 `data-call-ids`;call picker `value=call_id`;loop picker;SSR taken=末帧 | ✅ |
| D5 | JS:`applyCallFrame` / `applyLoopFrame` — 只滤 chip + 重算 arm,不 hidden 结构 | ✅ |
| D6 | 单测:多调用不同臂、loop 末项、HTML 三臂返回 + picker | ✅ |
## 9. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:源码常显、帧过滤、循环迭代 picker |
| 2026-10-15 | 按计划落地 D1–D6 |
+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 间距加宽 |
+239
View File
@@ -0,0 +1,239 @@
# View:静态页交互与公式/代码卡视觉
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view.md](view.md) · [user-site.md](user-site.md) · [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [ADR 0002 browser WASM](../adr/0002-browser-marqdo-wasm.md) |
**已确认(2026-10-15)**
| 决策 | 选择 |
|------|------|
| 引擎 | **B**(快照 + S1 帧切换 + 可选懒加载 WASM S2) |
| 体验原则 | 静态页与 live view **尽量同构**;控件形态对齐;无服务端时用 WASM/JS 补齐 |
| 视觉原则 | **一层主视觉**;一眼能懂;公式/代码不与 Bind chip / 源残留叠床架屋 |
| 演示参数条 | **要**(历史实参 select + 可编辑;S1 切帧 / S2 重跑) |
| code-card Run | 有 WASM 时可用;否则隐藏(不对齐「假按钮」) |
| 公式 Bind chip | **卡内不显示**;Variables 可留终值 |
---
## 1. 动机(对照 `public/00-欢迎.mq.md` / gh-pages)
静态导出(`marqdo view output` → `gh-pages`)与 live `marqdo view` 已共用**文档面 Structure** 渲染路径,但用户站实测仍有三类落差:
1. **交互控件缺失 / 偏弱**
- 函数「问候」仅有参数 chip「谁」,没有可切换的调用帧下拉(即便源里 `> 问候` 写了两次)。
- 参数行 `+ 谁` 在文档面呈声明高亮,读者无法在静态页改「谁」并看到新输出。
- 外联 `code-card` 的 Run 在静态模式被禁用(`Run is available in live marqdo view`)。
- 静态 stdin 仅在有 preset 时显示只读提示,**不能**再跑。
2. **无服务端时仍可交互的预期**
用户站是纯静态托管:没有 `/api/run`。合理路径是 **页内 JS** 和/或 **嵌入 Marqdo WASM**,在浏览器里重算 Structure 标注、Execution 区,甚至模拟 `input` / 外联(沙箱约束另定)。
3. **公式 / 代码块视觉凌乱**
同一赋值同时出现多层表象,信息重复、线框错位:
| 层 | 公式 `f = $$…$$` | 外联 `hi = ```python…``` |
|----|------------------|---------------------------|
| A 卡片 | `formula` badge + KaTeX | `code` badge + 高亮源码 + cmd/Run |
| B 标注 chip | `f` → `x^2 - 2` | `hi` → 整段 fence 摘要 |
| C 源残留 | 卡片外/旁再露 `$$` 或 ASCII | 卡片下再露 `python print…` 明文 |
再叠加 CSS L-leader 与卡内边框,首屏显得碎、重复、「坏掉的线」。
**本文件只定问题与方案;确认前不改代码。**
---
## 2. 现状解剖
### 2.1 静态 vs live(同一 `page_file`)
| 能力 | Live | Static(`LinkMode::Static`) |
|------|------|------------------------------|
| 文档面 Structure + annot | ✅(跑后) | ✅(导出时跑后写入) |
| call / loop picker JS | ✅(读 `#mq-view-trace`) | ✅(同源 JS;若轨迹未写入则无控件) |
| `/api/run` · Stream | ✅ | ❌ |
| stdin 表单 | ✅ 可再跑 | 只读 hint(或无) |
| code-card Run | ✅ `POST` 外联 | ❌ 禁用按钮 |
| WASM 重算 | ❌(未接) | ❌(未接) |
结论:**不是「静态另做一套皮肤」**,而是「导出瞬间的快照 + 部分 JS 帧切换」;**没有**浏览器内重执行闭环。
### 2.2 欢迎页结构(问题复现源)
```text
> 问候 谁=marqdo
> 问候 谁=marqdo user
## 问候
+ `谁`
> 打印 内容=欢迎,`谁`!
`f` = $$ x^2 - 2 $$
`hi` = ```python … ```
```
- 期望:`## 问候` 旁 **调用** 下拉(`1: 谁=marqdo` / `2: 谁=marqdo user`),切换时打印行的绑定/输出随帧变。
- 现状风险:若导出时 CallFrame &lt; 2、或 picker 未挂上、或读者期望的是「编辑谁」而非「选历史调用」,都会表现为「没有下拉框」。
- 公式/代码:`SpecialAssign` → formula/code **card**,同时又对同名绑定建 **Bind annot**,文档面还可能保留块源视觉 → 三重展示。
### 2.3 已有红线(方案不得破坏)
- 代码即文档:`.mq.md` 源可读;不发明第二套嵌套 DSL(见 web-artifact / marqdo-dev)。
- Browse ≠ Debug:静态站不做断点。
- `public/**/*.html` 不入库;gh-pages 由 CI/`view output` 生成([user-site.md](user-site.md))。
- 外链字体禁令仍在 [view.md](view.md);WASM/重型资源须 **可选加载**,默认站可降级为纯快照。
---
## 3. 目标(验收口径)
### G1 — 帧与参数交互(静态可读、可拨)
1. 同函数 ≥2 次调用时,静态页 **必有**「调用」下拉;默认末次;切换只改 chip/臂/相关输出,**源码常显**(同 [view-frame-selection.md](view-frame-selection.md))。
2. 导出保证写入完整 `#mq-view-trace`(含 `calls` / `events` / 可选 `loops`)。
3. (增强)演示向参数可提供 **受控输入**:默认值来自末次调用或 FM;改参后可触发页内重算(见 §5 引擎选项)。
### G2 — 无服务端可重算(可选引擎)
| 档位 | 能力 | 依赖 |
|------|------|------|
| **S0 快照**(现状加强) | 导出时跑完;帧 picker;只读 Execution | 无 WASM |
| **S1 页内重放轨迹** | 不重跑程序,只切换已序列化帧/标注 | JSON only |
| **S2 WASM 重跑** | `marqdo_wasm` + bridge:改 stdin/实参后重跑,刷新 Structure/Execution | WASM 包(可 CDN/`public/wasm/`) |
| **S3 外联沙箱** | code-card Run:浏览器内 pyodide **或** 明确标「仅 live」 | 可选;默认可关 |
默认用户站:**S0 + S1 必达**;**S2 为推荐主路径**(与「用 wasm 模拟输出」对齐);S3 单独开关。
### G3 — 公式 / 代码视觉单层真相
对「特殊赋值」块约定 **一层主视觉 + 至多一层结果**:
| 块 | 主视觉 | 允许的结果层 | 禁止 |
|----|--------|--------------|------|
| 公式 | KaTeX(formula-card 精简) | 无 Bind chip,或仅在 Variables | 再渲一份 `$$` 明文;annot 与卡重复同一 TeX |
| 外联代码 | 高亮源码(code-card) | 运行输出区 `code-out`;静态可藏 Run 或接 S2/S3 | annot 再贴整段 fence;卡下重复裸源 |
| 普通赋值 | 标记面语句 | Bind chip + L-leader | — |
Leader:仅连接「主视觉锚点 → 唯一结果 chip」;卡内不用第二套 L 线。
---
## 4. 问题清单(成文)
| ID | 问题 | 严重度 | 根因假设 |
|----|------|--------|----------|
| P1 | 静态页看不到调用/循环下拉 | 高 | 轨迹未导出完整 / picker 条件(≥2)未满足 / 读者要的是编辑参而非选帧 |
| P2 | 不能改参/stdin 再看输出 | 高 | Static 禁用 `/api/run`;无 WASM 闭环 |
| P3 | code-card Run 静态无效 | 中 | `initForeignCards` 显式禁用 |
| P4 | 公式卡 + chip + `$$` 三重 | 高 | card 与 Bind annot 叠加;块源未完全被 SpecialAssign 吞掉 |
| P5 | 代码卡 + chip + 明文三重 | 高 | 同 P4 |
| P6 | 卡内/旁碎线、错位 | 中 | leader 锚到错误节点;卡 CSS 与 annot-band 叠层 |
| P7 | 静态 stdin 体验差 | 中 | 仅有只读 hint |
---
## 5. 解决方案(详案,待选)
### 5.1 引擎策略(三选一,推荐 **B**)
| 方案 | 做法 | 优点 | 代价 |
|------|------|------|------|
| **A. 纯快照 + S1** | 加强导出轨迹与 picker;不引入 WASM | 体积小、离线稳 | 不能改参真重算 |
| **B. 快照默认 + 可选 WASM(S0/S1/S2)** | `view output` 仍嵌入跑后 HTML;页脚/侧栏「在浏览器中重跑」懒加载 WASM;改参后 patch Structure/Execution | 对齐用户预期;无 WASM 时仍可读 | 打包/加载体积;宿主能力子集 |
| **C. 静态页全面 WASM 首屏** | 打开即 WASM 跑 | 交互最强 | 冷启动慢;gh-pages 带宽;与「文档先可读」冲突 |
**推荐 B**:文档先可读(S0),帧切换不依赖 WASM(S1),需要改参/演示时再拉 WASM(S2)。
### 5.2 交互控件(与文档面一致)
1. **调用 / 循环 picker**(已有组件)
- 导出验收:欢迎页「问候」必须出现调用下拉。
- 单测:对 `00-欢迎.mq.md` / `document-annot-demo` 断言 HTML 含 `call-picker` 且 options≥2。
2. **演示参数条(新,窄范围)**
- 仅当函数被标记为「可演示」**或**静态页检测到 ≥1 形参且存在 CallFrame 时,在函数标题旁增加:
`谁 [ text input | select(历史实参) ] [应用]`
- **不**改 `.mq.md` 语法;数据来自 trace 的 `args_brief` / 末次绑定。
- 「应用」:S1 仅切换已有帧;S2 调 WASM `run` 后替换 `#structure` / Execution。
3. **stdin**
- 静态:若源含 `input`,渲染与 live 同形的 textarea +「重跑」(S2)或说明「需 WASM」。
- 无 input 则不显示。
### 5.3 公式 / 代码去重(视觉)
**规则:SpecialAssign 行只走 card,不再为同名同值挂 Bind chip。**
```text
公式赋值行
└─ formula-card(badge + 名 + KaTeX)
└─ ✗ 不再 render_annot_band(Bind f)
└─ ✗ 不再在卡外输出 $$ 源
外联赋值行
└─ code-card(badge + 名 + 高亮体 + 可选 Run)
└─ ✗ 不再 Bind chip 贴 fence 全文
└─ 运行结果只进 .code-out
```
静态 Run 策略(与 §5.1 对齐):
- S0:隐藏 Run,或保留禁用并 tooltip「打开 live view / 启用 WASM」。
- S2:Run → WASM 宿主 `foreign`(若 WASM 支持)或提示不支持。
- S3:可选 Pyodide(默认关)。
CSS:formula-card / code-card 与 `.annot-band` 垂直节奏统一;禁止对 KaTeX 节点拉 L-leader。
### 5.4 导出管线
```text
marqdo view output
→ build_file_view(跑 + annot + trace_json) // 已有
→ page_file(Static)
+ 嵌入 #mq-view-trace
+ (可选)data-wasm-url / 懒加载脚本
+ 公式/代码去重后的 structure_html
→ public/ + gh-pages
```
`--no-exec`:文档面无标注;可提示「本页为结构-only」;S2 仍可尝试 WASM 首跑(可选,默认关以免惊喜执行)。
### 5.5 明确不做(本提案)
- 静态页断点调试(仍属 `marqdo debug`)。
- 在 `public/*.mq.md` 发明新的「交互表」DSL(除非另开设计并获批)。
- 默认全站加载 Pyodide。
- 提交生成 HTML 进 `main`。
---
## 6. 分阶段开发计划(确认后执行)
| 阶段 | 内容 | 交付 | 依赖确认 |
|------|------|------|----------|
| **D0** | 本文定稿;选定引擎 **A/B/C**;是否要「演示参数条」 | 状态 → Active | **本次决策** |
| **D1** | P4/P5/P6:SpecialAssign 与 Bind 互斥;卡 CSS;去掉重复源 | 欢迎页公式/代码干净;单测 | D0 |
| **D2** | P1:导出轨迹验收 + 欢迎页 call-picker 金样;修任何「≥2 调用无下拉」bug | HTML 断言 | D0 |
| **D3** | P2/P7 S1 夯实:静态 stdin UI 形态;无 WASM 时文案清晰 | UX | D0 |
| **D4** | (若选 B)S2:静态页懒加载 WASM;「应用参数 / 重跑」刷新 Structure+Execution | `public/wasm` 或 CDN 策略;体积预算 | D0=B |
| **D5** | P3:code-card 与 S2/S3 策略落地;默认隐藏无效 Run | — | D1+D4 |
| **D6** | `build-public` / pages CI 回归;更新 [user-site.md](user-site.md) · [view.md](view.md) 验收条 | gh-pages 抽检欢迎页 | D1–D5 |
建议默认路径:**D0 选 B → D1 → D2 → D3 → D4 → D5 → D6**。
---
## 7. 决策记录
见文首「已确认」。开发按 §6:D1 → D2 → D3 → D4 → D5 → D6。
---
## 8. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:静态交互缺口、公式/代码凌乱、S0–S3 与阶段 D0–D6 |
| 2026-10-15 | Active:引擎 B;对齐 live;干净视觉;演示参数条;Run 接 WASM 否则隐藏 |
+6 -4
View File
@@ -4,7 +4,7 @@
|---|---|
| 状态 | 已定(v0.0.2 方向) |
| 日期 | 2026-08-04 |
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
---
@@ -77,7 +77,7 @@ OUT_DIR/
- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。
- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。
- 渲染逻辑与实时 `view` **共用**同一套 HTML 构件(结构 / 执行 / 源码),禁止两套皮肤分叉。
- 渲染逻辑与实时 `view` **共用**同一路径:`build_file_view` → 文档面 Structure(`document.rs` + annots)→ `page_file`(同一 CSS/JS,含 call/loop picker、`#mq-view-trace`)。禁止第二套皮肤。`--no-exec` 时仍出文档面,但无运行标注。
示例:
@@ -90,14 +90,16 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc
## 4. 信息架构
侧栏文件索引 + 主区:结构(AST+注释)· 执行 · 源码。结构旁**右侧栏**(现有 outline 槽)为:
侧栏文件索引 + 主区:**文档面 Structure** · 执行 · 源码。Structure(Browse)为叙述保真文档面:标记面(变量/语句/返回无源码定界符)、表/列表/分支结构保真,跑后结果经 **CSS L-leader** 引出——见 [view-document-annotations.md](view-document-annotations.md) · [view-execution-trace.md](view-execution-trace.md)。**不是** AST 卡片栈(那是 debug)。
结构旁**右侧栏**(现有 outline 槽)为:
| 区块 | 内容 |
|------|------|
| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) |
| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) |
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板。
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板;终态亦可刷新 Structure 内标注。
表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。
+12 -5
View File
@@ -2,16 +2,23 @@
| | |
|---|---|
| 状态 | **Accepted · W0–W7 + P3 完结**(2026-08-28 复核) |
| 日期 | 2026-08-26(初稿)· 2026-08-28(完结复核) |
| 相关 | [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [ext-abi.md](ext-abi.md) · [stdlib-modules.md](stdlib-modules.md) |
| 目标 | 盘点 `ext/web` + `plugins/web` + `lib/net` 现状,对照主流语言网络栈,给出「开发一个完整 Web 项目」所需能力的差距清单与补强路线 |
| 状态 | **Historical capability matrix** — 作者面以 **[ext-web-artifact.md](ext-web-artifact.md)** / ADR [0007](../adr/0007-web-document-endpoint.md) 为准(2026-09-28) |
| 日期 | 2026-08-26(初稿)· 2026-08-28(完结复核)· 2026-09-28(Artifact 标注) |
| 相关 | [ext-web-artifact.md](ext-web-artifact.md) · [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [ext-abi.md](ext-abi.md) · [stdlib-modules.md](stdlib-modules.md) |
| 目标 | 盘点 `ext/web` + `plugins/web` + `lib/net` 现状;**下文 API 名多为 W0–W7 历史面**(`compose_*` / `configure` 已废止) |
> **2026-09-28**:作者面迁移到 Document / Endpoint / Resource。
> - Document/Endpoint:`type: web|endpoint` + `web.serve` / `web.render` / `web.inspect`
> - DB/cache/storage → `ext/data`;auth/oidc/rbac → `ext/security`;ws → `ext/net`
> - 统一 View:`|type|slot|value|attrs|style|`;中间件:`web.use`
> 本文件保留为**原生能力矩阵**对照,勿再按 `compose_*` / `app.configure` 写作。
---
## 0. 一句话结论
**`ext/web` + `plugins/web` 已完成 W0–W7 + P3 路线图**:中间件/JSON API、数据层(连接池/事务/分页/FTS/迁移/外键/审计时间戳)、安全硬化(argon2/CSRF/会话持久化/限速/RBAC)、内容站点标配(SEO/RSS/Markdown/分页 UI)、上传下载/相册/ETag、sitemap/robots/错误页/重定向、WebSocket 广播与访问日志。足以在 Marqdo 上实现博客/CMS/中小型 API 站点;**未内置**的仅剩标签页模板(D6,可用路由+`db.count` 自建)与应用层反垃圾。边界不变:**纯解析进 `lib/net`,HTTP 服务器与领域能力进 `plugins/web` + `ext/web` 作者面**。
**能力层(plugins/web)**:中间件/JSON API、数据层、安全、内容站点、上传下载、sitemap、WebSocket 等仍在原生实现中。
**作者面(2026-09-28)**:改为 Artifact Metadata + facade;`compose_*` / `configure` **已删除**。边界不变:**纯解析进 `lib/net`,HTTP 服务器进 `plugins/web`,作者 API 进 `ext/web` + `ext/data` + `ext/security` + `ext/net`**。
**宿主集成下一刀**(同域 LLM SSE 中继、HTTP→用户 `##`、与 MCP Server 协作)不在本 W 表内,见 [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) · [ext-hosting-fill.md](ext-hosting-fill.md) · [ext-hosting.md](../roadmap/ext-hosting.md)。
+2182
View File
File diff suppressed because it is too large. Load diff
+2818
View File
File diff suppressed because it is too large. Load diff
@@ -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` |
| **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`) |
| **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)** |
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) |
| 后续 | 优化波次 O1–O5 见 [ext-ai-optimize.md](ext-ai-optimize.md)(沙盒证明 · Skill Lift · 路由/成本 · lint · 隔离) |
---
+29
View File
@@ -0,0 +1,29 @@
# Roadmap: Agent/LLM 优化波次 O1–O5
| | |
|---|---|
| Status | **Active** |
| Date | 2026-10-16 |
| Design | [ext-ai-optimize.md](../design/ext-ai-optimize.md) |
| Research | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) |
| Prior | [ext-agent-optimize.md](ext-agent-optimize.md) (A0–A4 / Wave B) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
## Principles
1. Executable `.mq.md` remains authority; OKF reuses; sandbox proves; LLM explores.
2. No hidden TOOL: loop; no vector-store memory authority; no default shell Agent.
3. Do not edit `doc/next/*`.
## Waves
| Wave | Scope | Gold / deliverable | Status |
|------|-------|--------------------|--------|
| **O1** | A1 opt-in `sandbox=` · A3 profile table · D1 skill · D4 example | `agent-sandbox-optin` · `examples/agent-sandbox-okf` | **done** |
| **O2** | A2 promote proof · B1 OKF meta · B3/E1 harness Skill Lift | `agent-sandbox-promote` · harness subset | **done** |
| **O3** | C1 step route · C2 cost · B6 EFI default | `agent-step-route` · run usage/efi | **done** |
| **O4** | A4/D2 lint · A5 diff review report | `scripts/mq-style-lint.sh` · `sandbox.report` | **done** |
| **O5** | B4 quarantine · C3 offline policy rewrite | `agent-sandbox-quarantine` · `optimize-standing-policy.sh` | **done** |
## Non-goals
F1–F5 · wasmtime CLI embed · default `sandbox=True` without ADR · edit `doc/next/*`
+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/*`
+85 -78
View File
@@ -1,19 +1,22 @@
# 第 14 章:网络与 Web 扩展
Marqdo 的网络能力分两层:**标准库 `lib/net`**(HTTP 客户端、cookie / multipart 解析)与**官方扩展 `ext/web`**(网页应用、数据库、表单、登录鉴权、WebSocket)。分层的依据是「代码即文档」的可读性——基础、通用、低依赖的进标准库;领域性强、依赖重、只在 Web 场景才用的进扩展。
> **现行作者面(2026-09-28 · ADR 0007)**:Document / Endpoint / Resource —— 见 [ext-web-artifact.md](../design/ext-web-artifact.md)。
> 下文若仍出现 `compose_*` / `app.configure` / `web.db` 同文件混写,视为**历史示例**;DB → `ext/data`,鉴权 → `ext/security`,实时 → `ext/net`。
Marqdo 的网络能力分两层:**标准库 `lib/net`**(HTTP 客户端、cookie / multipart 解析)与**官方扩展 `ext/web`**(Document/Endpoint facade + 拆分后的 data/security/net)。分层的依据是「代码即文档」。
## 14.1 概览
| 能力 | 位置 | 典型函数 |
| 能力 | 位置 | 典型 API |
|------|------|----------|
| HTTP(S) 客户端 | `lib/net` | `http_get` / `http_post` / `http_request` |
| Cookie 解析 | `lib/net` | `cookie_parse` |
| multipart/form-data 解析 | `lib/net` | `multipart_parse` |
| 网页应用 / 路由 / 静态 | `ext/web` | `web.page` / `web.app` |
| SQLite 数据库 | `ext/web` | `web.db` |
| 表单 | `ext/web` | `web.form` |
| 登录鉴权(session) | `ext/web` | `web.auth` / `app.auth` |
| WebSocket 客户端 / 端点 | `ext/web` | `web.ws` / `app.route_ws` |
| Cookie / multipart | `lib/net` | `cookie_parse` / `multipart_parse` |
| Document / Endpoint | `ext/web` | `type: web\|endpoint` · `web.serve` · `web.render` · `web.inspect` |
| View 装配 | `ext/web` | `|type|slot|value|attrs|style|` → `web.render` |
| 数据库 | `ext/data` | `db` CRUD / txn |
| 表单 | `ext/data` | `form` |
| 鉴权 / RBAC / OIDC | `ext/security` | `auth` · `rbac` · `oidc` |
| WebSocket | `ext/net` | `websocket` |
```bash
# 运行使用 ext/web 的程序前,先安装扩展
@@ -67,107 +70,111 @@ import net:lib/net.mq.md
> print text=[name](`field`)
```
## 14.3 网页应用(`ext/web`)
## 14.3 网页应用(Artifact · ADR 0007)
`ext/web` 用类 + 方法装配页面。导入 `web:ext/web/web.mq.md`(中文 `网页:ext/web/网页.mq.md`)。
站点是一堆 `.mq.md`:**Document**(`type: web`)与 **Endpoint**(`type: endpoint`)。入口调用 `web.serve` 扫描目录并监听。完整设计见 [ext-web-artifact.md](../design/ext-web-artifact.md);示例 [marqdo-blog](../../examples/marqdo-blog/)。
### 页面、组件、主体
### Document 首页
```markdown
---
type: web
title: 我的站点
route: /
method: GET
data_source: posts
data_order: -created_at
import web:ext/web/web.mq.md
---
# 我的站点
欢迎。下方卡片列表由 `data_source` 在服务时从数据库加载。
```
### Endpoint
```markdown
---
type: endpoint
method: GET
path: /api/ping
request: none
response: json
---
# main
`首页` =
`out` =
| 组件 | 样式 |
|------|------|
| nav.`导航` | shell.`顶栏` |
| ok | service |
|----|---------|
| True | demo |
**page = > web.page title="我的站点" intro="<h1>你好</h1>"**
**page = > `page`.compose_components components=`首页`**
**html = > `page`.render**
*out*
```
### 服务入口
```markdown
---
import web:ext/web/web.mq.md
import posts:db/posts.mq.md
---
# main
**store = > posts.open url="sqlite:data/site.db"**
> web.serve root="." host="127.0.0.1" port=18081 db=`store` static_dir="public"
```
离线预览可用 View 表 + `web.render`:
```markdown
`nodes` =
| type | slot | value | attrs | style |
|------|------|-------|-------|-------|
| title | title | Marqdo | | title |
**html = > web.render nodes=`nodes` title="preview"**
> print text=`html`
```
### 应用 + 路由 + 监听
### 数据库(`ext/data`)
```markdown
**app = > web.app page=`page` host=127.0.0.1 port=18081**
**app = > `app`.route path="/about" page=`关于`**
> web_listen app=`app`
```
---
import data:ext/data/db.mq.md
---
`listen` 提供 `/`、路由页、表单端点 `/_form/{id}`、可选静态目录与 `/admin`。
# main
### 数据库(SQLite)
```markdown
**store = > web.db url="sqlite:site.db"**
**store = > data.db url="sqlite:site.db"**
> `store`.init name=articles fields=`字段表`
> `store`.insert table=articles rows=`数据`
**rows = > `store`.select table=articles limit=10**
- [行](rows)
> print text=[title](`行`)
```
## 14.4 登录鉴权(session / cookie)
## 14.4 鉴权(`ext/security`)
给 `/admin*` 加登录门禁:`app.auth` 挂用户表,未登录重定向到 `/admin/login`。
HTTP 门禁与登录走 `ext/security`(`auth` / `rbac` / `oidc`),再用 `web.use` 挂中间件表;勿再写 `app.configure`。独立脚本可用:
```markdown
`管理员` =
---
import rbac:ext/security/rbac.mq.md
---
| 行 | 用户名 | 密码 |
|----|--------|------|
| 1 | admin | secret |
| 2 | 站长 | pw123 |
# main
**app = > web.app page=`page` admin=True**
**app = > `app`.auth users=`管理员` session_ttl=3600**
> web_listen app=`app`
**gate = > rbac.rbac**
**r = > `gate`.can permissions="desk:access" needed="desk:access"**
> print text=[allowed](`r`)
```
`session_ttl` 是会话有效期(秒),过期后重新登录。
## 14.5 WebSocket(`ext/net`)
**独立鉴权工具** `web.auth`:登录、校验、登出(不依赖页面),返回 `{ok, session_id, username}`:
```markdown
**auth = > web.auth users=`管理员` session_ttl=3600**
**login = > `auth`.login username="admin" password="secret"**
1. [ok](`login`)
> print text=登录成功:[username](`login`)
2. *
> print text=登录失败
**sid = [session_id](login)**
**check = > `auth`.check session_id=`sid`**
> print text=[username](`check`)
> `auth`.logout session_id=`sid`
```
## 14.5 WebSocket
`app.route_ws` 注册端点,`web.ws.connect` 单次请求–响应:
```markdown
**app = > `app`.route_ws path="/live" echo=True**
> web_listen app=`app`
```
客户端(另开终端):
```markdown
**ws = > web.ws timeout_sec=30**
**echo = > `ws`.connect url="ws://127.0.0.1:18081/live" message="hi"**
1. [ok](`echo`)
> print text=[messages](`echo`)
2. *
> print text=连接失败:[error](`echo`)
```
实时能力在 `ext/net`(如 `websocket`),与 Document 站点并列导入,不再挂在 `web.app` 的 junk drawer 上。
## 14.6 字典操作:用表格与取元,不用 `json.get`/`json.set`
+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
@@ -0,0 +1,20 @@
---
title: resolve_config
capability: config.resolve
status: stable
---
Use when: final normalized configuration is required.
# config
## resolve_config
+ `path`
`defaults` =
| host | port |
|------|------|
| localhost | 8080 |
* defaults
@@ -0,0 +1,21 @@
---
title: Engineering Knowledge demo
description: Tiny project demonstrating Capability Catalog + reuse + decisions.
---
# Engineering Knowledge demo
This folder is a miniature “large engineering” slice: config resolution already exists.
Before generating a new loader, run:
```bash
marqdo knowledge examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo
marqdo reuse "load and resolve configuration" examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo
marqdo duplicate examples/engineering-knowledge -o examples/engineering-knowledge/.marqdo
```
Expected: **REUSE config.resolve**, not a new `load_configuration`.
# main
* "see README via catalog/reuse CLI"
@@ -0,0 +1,18 @@
---
type: Decision
id: ADR-022
title: Cache is not persistence
status: accepted
applies_to:
- config.resolve
---
# Cache is not persistence
## Decision
Redis is only used for ephemeral cache.
## Reason
The application must remain correct when Redis is unavailable.
@@ -0,0 +1,12 @@
---
type: Constraint
id: C-014
title: Centralized config resolution
status: stable
applies_to:
- config.resolve
---
# Centralized config resolution
All configuration resolution must go through `resolve_config`.
@@ -0,0 +1,20 @@
---
type: Failure
id: F-008
title: Do not invent a second config loader
status: resolved
---
# Do not invent a second config loader
## Failed approach
Added `load_configuration` beside `resolve_config`.
## Failure
Divergent defaults and error handling.
## Correct approach
Call `resolve_config`.
+27 -42
View File
@@ -1,54 +1,39 @@
# examples/marqdo-blog
一个用 Marqdo 的 `ext/web` 网络扩展库搭建的博客系统示例:美观大气的现代化主题、
SQLite 驱动的文章/标签、动态路由、WebSocket 实时终端、以及受会话门禁保护的后台 CRUD。
Marqdo **Web Artifact** blog (ADR 0007).
## 运行
## Layout
```bash
cargo build -p marqdo_plugin_web
cargo run -- examples/marqdo-blog/index.mq.md
```text
index.mq.md # type: web · / · data_source: posts
pages/about.mq.md # 类型: 网页 · /about
pages/post.mq.md # type: web · /post/{slug} · data_where
api/ping.mq.md # type: endpoint · GET /api/ping
api/echo.mq.md # type: endpoint · POST /api/echo
db/posts.mq.md # ext/data schema + seed + open
public/ # static (mounted at /static)
serve.mq.md # web.serve + db open
smoke.sh # curl checks against a running serve
```
打开 http://127.0.0.1:18085/:
- `/` — 首页:文章卡片网格 + 实时 WebSocket 终端
- `/post/{slug}` — 动态路由渲染单篇文章(标题/日期/标签/正文)
- `/tags` — 标签归档;`/tag/{slug}` 查看某标签下的文章
- `/about` — 关于页
- `/admin` — 会话门禁后台,登录 `admin` / `marqdo`,可增删改文章与标签
- `/live` — WebSocket 回显端点
- `/static/*` — 静态资源(`public/` 下的 `live.js`、favicon、logo)
- `/favicon.ico` — 站点图标(`应用.图标` 表装配)
## 设计亮点(文档即代码)
- **样式即数据表格,装配即函数**(`styles/theme.mq.md`):
主题不再是一大段手写 CSS 字符串,而是由一张张 GFM 样式表组成 ——
`|选择器|属性|值|` 规则行(同一选择器多行自动合并成一条规则),
响应式用 `|媒体|选择器|属性|值|` 分组进 `@media` 块。
每个 `## 段`(基础/顶栏/侧栏/主体/卡片/页脚/表单/响应式)导出一张样式表,
`## 全局` 用 `网页.样式装配` 函数把每张表装配成 CSS 文本,再 `text.str_join` 拼成完整样式表,
最后经 `页面.样式` 注入页面。样式保持可读的数据表格,不写胶水代码。
- **图标 / 头资源 / 图片装配**(W8):`应用.图标` 表挂 `/favicon.ico` 与 SVG;
`页面.头装配` 写 apple-touch-icon;`页面.图片装配` 把 logo 表注入主区(`mq-images`)。
含 `/` 的路径与 MIME 单元格需加引号(如 `"/static/logo.svg"`、`"image/png"`)。
- **页面 = 组件装配 + 主体绑定**(`index.mq.md`):
导航/侧栏/页脚用 `|组件|样式|` 表装配,文章列表用 `|属性|值|` 绑定 SQLite 字段。
- **动态路由**:`/post/{slug}` 的 `slug` 注入查询条件,`页面.详情` 把首行渲染成文章。
- **数据模型**(`db/`):`schema.mq.md` 定义 `posts`/`tags`/`post_tags` 三张表,
`seed.mq.md` 提供种子数据,`index.mq.md` 幂等建表 + 灌数据。
## 冒烟测试
服务器启动后(端口 18085),运行:
## Run
```bash
bash scripts/build-web-plugin.sh
export MARQDO_EXT=$PWD/ext # if ~/.marqdo/ext is stale
export MARQDO_WEB_PLUGIN=$PWD/plugins/web/build/libweb.so
cd examples/marqdo-blog && marqdo run serve.mq.md
# other terminal:
bash examples/marqdo-blog/smoke.sh
```
覆盖:首页/卡片/主题 CSS/媒体查询、静态资源、动态路由详情、标签归档、鉴权门禁、
登录会话、后台表单、WebSocket 回显。全部通过时输出 `通过 N / N`。
| Path | Artifact |
|------|----------|
| `/` | Document home + post cards |
| `/about` | ZH Document |
| `/post/{slug}` | Document detail |
| `/api/ping` | Endpoint JSON |
| `/api/echo` | Endpoint JSON echo |
| `/static/*` | public assets |
可从仓库根目录或本目录运行:相对 `static_dir`(`public`)与相对数据库路径
(`data/marqdo-blog.db`)都按**入口脚本所在目录**解析,不依赖终端工作目录。
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md).
+25
View File
@@ -0,0 +1,25 @@
---
type: endpoint
method: POST
path: /api/echo
request: json
response: json
auth: none
---
# main
Echo request fields bound via Artifact Metadata (`arg` overlays).
**msg = message**
1. not `msg`
**msg = ""**
2. *
`out` =
| ok | message |
|----|---------|
| True | `msg` |
*out*
+19
View File
@@ -0,0 +1,19 @@
---
type: endpoint
method: GET
path: /api/ping
request: none
response: json
auth: none
description: Health ping — documentation is the API (ADR 0007).
---
# main
`out` =
| ok | service |
|----|---------|
| True | marqdo-blog |
*out*
-28
View File
@@ -1,28 +0,0 @@
---
title: db/index
description: 打开 sqlite、建三张表、幂等种子。
导入 网页:ext/web/网页.mq.md
import schema:schema.mq.md
import seed:seed.mq.md
---
## 打开
**store = > 网页.数据库 地址="sqlite:data/marqdo-blog.db"**
**字段 = > schema.posts**
**标签字段 = > schema.tags**
**关联字段 = > schema.post_tags**
> `store`.初始化 名=posts 字段=`字段`
> `store`.初始化 名=tags 字段=`标签字段`
> `store`.初始化 名=post_tags 字段=`关联字段`
**行 = > store.查询 表="posts" 上限=1**
1. `行`
*store*
2. *
**文章 = > seed.posts**
**标签 = > seed.tags**
**关联 = > seed.post_tags**
> `store`.插入 表=posts 行=`文章`
> `store`.插入 表=tags 行=`标签`
> `store`.插入 表=post_tags 行=`关联`
*store*
+44
View File
@@ -0,0 +1,44 @@
---
title: blog posts schema
import data:ext/data/db.mq.md
---
## schema
`fields` =
| 字段 | 类型 | 可空 |
|------|------|------|
| title | text | False |
| slug | text | False |
| summary | text | True |
| content | text | True |
| tag | text | True |
| created_at | text | True |
*fields*
## seed
`rows` =
| title | slug | summary | content | tag | created_at |
|-------|------|---------|---------|-----|------------|
| Hello Marqdo | hello | Welcome | # Hello\n\nExecutable documents. | intro | 2026-09-01 |
| Artifact Web | artifact-web | Document first | Pages are mq.md files. | design | 2026-09-28 |
*rows*
## open
+ `url`="sqlite:data/blog.db"
**store = > data.db url=`url`**
**fields = > schema**
> `store`.init name=posts fields=`fields`
**existing = > `store`.select table="posts" limit=1**
1. `existing`
*store*
2. *
**seed = > seed**
> `store`.insert table=posts rows=`seed`
*store*
+9 -125
View File
@@ -1,131 +1,15 @@
---
type: web
title: Marqdo 博客
description: 用 web 扩展库搭建的博客系统示例:首页列表、动态文章详情、标签归档、登录门禁后台。
route: /
method: GET
data_source: posts
data_order: -created_at
description: >-
Document Artifact 首页(ADR 0007):正文即文档,列表来自 data_source。
导入 网页:ext/web/网页.mq.md
import theme:styles/theme.mq.md
import nav:components/nav.mq.md
import side:components/side.mq.md
import foot:components/foot.mq.md
import db:db/index.mq.md
---
# main
# Marqdo 博客
`首页` =
| 组件 | 样式 |
|------|------|
| nav.`导航` | |
| side.`侧栏` | |
| foot.`页脚` | |
`列表` =
| 属性 | 值 | 样式 |
|------|-----|------|
| title | posts.title | |
| body | posts.summary | |
| meta | posts.created_at | |
| tag | posts.tag | |
| href | posts.slug | |
`详情绑定` =
| 属性 | 值 | 样式 |
|------|-----|------|
| title | posts.title | |
| meta | posts.created_at | |
| tag | posts.tag | |
| body | posts.content | |
`标签列表` =
| 属性 | 值 | 样式 |
|------|-----|------|
| title | tags.name | |
| meta | 点击查看该标签下的文章 | |
| href | tags.slug | |
`文章条件` =
| 字段 | 操作 | 值 |
|------|------|-----|
| slug | = | {slug} |
`标签条件` =
| 字段 | 操作 | 值 |
|------|------|-----|
| tag | = | {slug} |
`管理员` =
| 行 | 用户名 | 密码 |
|----|--------|------|
| 1 | admin | marqdo |
`站点图标` =
| 路径 | 关系 | 类型 | 尺寸 | 地址 |
|------|------|------|------|------|
| "public/favicon.png" | icon | "image/png" | 32x32 | "/favicon.ico" |
| "public/favicon.svg" | icon | "image/svg+xml" | any | "/static/favicon.svg" |
`头资源` =
| 关系 | 地址 | 类型 |
|------|------|------|
| apple-touch-icon | "/static/favicon.png" | "image/png" |
`品牌图` =
| 源 | 替代 | 类 | 链接 | 宽度 | 加载 |
|----|------|----|------|------|------|
| "/static/logo.svg" | Marqdo | brand-logo | "/" | 40 | eager |
**store = > db.打开**
**首页CSS = > theme.全局**
**page = > 网页.页面 标题="Marqdo 博客" 引言="<h1>Marqdo 博客</h1><p>用 web 扩展库搭建的博客:表格装配页面、SQLite 数据、动态路由、实时终端。</p><h2 id=\"live\">实时终端</h2><p id=\"live-status\" class=\"live-pill\">connecting…</p><input id=\"live-msg\" placeholder=\"输入一条消息…\"><button id=\"live-send\" disabled>发送</button><div id=\"live-out\"></div><script src=\"/static/live.js\"></script>"**
**page = > page.组件装配 组件=`首页`**
**page = > page.主体装配 主体=`列表`**
**page = > page.排序 排序="-created_at"**
**page = > page.样式 样式=`首页CSS`**
**page = > page.头装配 表=`头资源`**
**page = > page.图片装配 表=`品牌图`**
**about = > 网页.页面 标题="关于" 引言="<h1>关于本站</h1><p>一个用 Marqdo 的 web 扩展库(ext/web)写成的博客系统。</p><p>它演示了:GFM 表格装配导航与侧栏、SQLite 驱动的主体绑定、动态路由 /post/{slug}、标签归档、以及受 session 保护的后台 CRUD。</p>"**
**about = > about.组件装配 组件=`首页`**
**about = > about.样式 样式=`首页CSS`**
**post = > 网页.页面 标题="文章"**
**post = > post.组件装配 组件=`首页`**
**post = > post.主体装配 主体=`详情绑定`**
**post = > post.查询条件 条件=`文章条件`**
**post = > post.详情 详情=True**
**post = > post.样式 样式=`首页CSS`**
**tags = > 网页.页面 标题="标签归档" 引言="<h1>标签归档</h1><p>点击标签查看该主题下的文章。</p>"**
**tags = > tags.组件装配 组件=`首页`**
**tags = > tags.主体装配 主体=`标签列表`**
**tags = > tags.链接前缀 前缀="/tag/"**
**tags = > tags.样式 样式=`首页CSS`**
**tagged = > 网页.页面 标题="标签"**
**tagged = > tagged.组件装配 组件=`首页`**
**tagged = > tagged.主体装配 主体=`列表`**
**tagged = > tagged.查询条件 条件=`标签条件`**
**tagged = > tagged.排序 排序="-created_at"**
**tagged = > tagged.样式 样式=`首页CSS`**
**app = > 网页.应用 页面=page 数据库=store 后台=True 主机="127.0.0.1" 端口=18085**
**app = > app.路由 路径="/about" 页面=about**
**app = > app.路由 路径="/post/{slug}" 页面=post**
**app = > app.路由 路径="/tags" 页面=tags**
**app = > app.路由 路径="/tag/{slug}" 页面=tagged**
**app = > app.静态 目录="public" 挂载="/static"**
**app = > app.图标 表=`站点图标`**
**app = > app.路由实时 路径="/live" 回显=True**
**app = > app.鉴权 用户表=`管理员` 会话时长=3600**
> `app`.监听
可执行文档即网页。本站用 Artifact Metadata 声明路由;文章列表由 `data_source: posts` 在服务时加载。
+10
View File
@@ -0,0 +1,10 @@
---
类型: 网页
路由: /about
方法: GET
标题: 关于
---
# 关于 Marqdo
Marqdo 是可执行文档语言:文档即程序,程序即知识。
+13
View File
@@ -0,0 +1,13 @@
---
type: web
title: Post
route: /post/{slug}
method: GET
data_source: posts
data_where: slug={slug}
description: Dynamic Document route — body is the article shell; data from Resource.
---
# Post
Article page for `{slug}`. List and detail data are provided by `ext/data` at serve time when `data_source` is set on the Artifact.
+11
View File
@@ -0,0 +1,11 @@
---
title: marqdo-blog serve
description: Scan Artifact documents/endpoints and listen (ADR 0007).
import web:ext/web/web.mq.md
import posts:db/posts.mq.md
---
# main
**store = > posts.open url="sqlite:data/blog.db"**
> web.serve root="." host="127.0.0.1" port=18081 db=`store` static_dir="public"
+23 -53
View File
@@ -1,71 +1,41 @@
#!/usr/bin/env bash
# 冒烟测试:marqdo-blog 全功能验证。
# 用法:bash examples/marqdo-blog/smoke.sh
# Artifact blog smoke (ADR 0007). Usage: bash examples/marqdo-blog/smoke.sh
# Expects serve.mq.md already listening on BASE (default 18081).
set -uo pipefail
BASE="http://127.0.0.1:18085"
BASE="${BASE:-http://127.0.0.1:18081}"
PASS=0; FAIL=0
ok() { echo " ok: $1"; PASS=$((PASS+1)); }
bad() { echo " FAIL: $1"; FAIL=$((FAIL+1)); }
echo "== 首页 =="
echo "== Document home =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/")
[ "$code" = "200" ] && ok "GET / -> $code" || bad "GET / -> $code"
curl -s "$BASE/" | grep -q '<title>Marqdo 博客</title>' && ok "title" || bad "title"
curl -s "$BASE/" | grep -q 'class="card"' && ok "卡片渲染" || bad "卡片缺失"
curl -s "$BASE/" | grep -q 'aside.side' && ok "主题 CSS 注入" || bad "主题 CSS 缺失"
curl -s "$BASE/" | grep -q '@media (max-width: 860px)' && ok "响应式媒体查询" || bad "媒体查询缺失"
curl -s "$BASE/" | grep -q 'class="card"' && ok "data_source cards" || bad "cards missing"
curl -s "$BASE/" | grep -q 'Hello Marqdo' && ok "seed title" || bad "seed title missing"
echo "== 静态 =="
echo "== Static =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/static/live.js")
[ "$code" = "200" ] && ok "GET /static/live.js -> $code" || bad "static -> $code"
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/favicon.ico")
[ "$code" = "200" ] && ok "GET /favicon.ico -> $code" || bad "favicon -> $code"
curl -s "$BASE/" | grep -q 'rel="icon"' && ok "head icon link" || bad "head icon 缺失"
curl -s "$BASE/" | grep -q 'mq-images' && ok "图片装配 logo" || bad "mq-images 缺失"
echo "== 动态路由 =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/hello-marqdo")
[ "$code" = "200" ] && ok "GET /post/hello-marqdo -> $code" || bad "post detail -> $code"
curl -s "$BASE/post/hello-marqdo" | grep -q 'article-title' && ok "文章详情渲染" || bad "文章详情缺失"
echo "== Dynamic Document =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/post/hello")
[ "$code" = "200" ] && ok "GET /post/hello -> $code" || bad "post detail -> $code"
curl -s "$BASE/post/hello" | grep -q 'article-title' && ok "article title" || bad "article title missing"
echo "== 标签 =="
curl -s "$BASE/tags" | grep -q 'href="/tag/marqdo"' && ok "标签归档链接" || bad "标签链接缺失"
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/tag/web")
[ "$code" = "200" ] && ok "GET /tag/web -> $code" || bad "tag page -> $code"
echo "== ZH Document =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/about")
[ "$code" = "200" ] && ok "GET /about -> $code" || bad "about -> $code"
curl -s "$BASE/about" | grep -q '关于 Marqdo' && ok "about body" || bad "about body missing"
echo "== 鉴权门禁 =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/admin")
[ "$code" = "303" ] && ok "未登录 /admin -> $code (重定向登录)" || bad "未登录 /admin -> $code"
echo "== 登录 =="
rm -f /tmp/mq_smoke_cookies.txt /tmp/mq_smoke_headers.txt
curl -s -D /tmp/mq_smoke_headers.txt -o /dev/null -d "username=admin&password=marqdo" "$BASE/admin/login"
sid=$(grep -i "set-cookie" /tmp/mq_smoke_headers.txt | sed 's/.*marqdo_sid=\([^;]*\).*/\1/')
[ -n "$sid" ] && ok "登录获取会话 cookie" || bad "登录未返回 cookie"
code=$(curl -s -b "marqdo_sid=$sid" -o /dev/null -w "%{http_code}" "$BASE/admin")
[ "$code" = "200" ] && ok "带会话访问 /admin -> $code" || bad "带会话 /admin -> $code"
echo "== 发布文章 (CRUD) =="
code=$(curl -s -b "marqdo_sid=$sid" -o /dev/null -w "%{http_code}" "$BASE/admin/posts/new")
[ "$code" = "200" ] && ok "GET /admin/posts/new -> $code" || bad "new form -> $code"
echo "== WebSocket =="
wsok=$(python3 -c "
import socket, base64, os
s = socket.create_connection(('127.0.0.1', 18085), timeout=3)
key = base64.b64encode(os.urandom(16)).decode()
s.sendall((f'GET /live HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
r = s.recv(1024).decode(errors='replace')
if '101' not in r.split('\r\n')[0]:
print('NO'); s.close(); raise SystemExit
mask = os.urandom(4); payload = b'ping'
m = bytes(b ^ mask[i%4] for i, b in enumerate(payload))
s.sendall(bytes([0x81, 0x80|len(payload)]) + mask + m)
d = s.recv(1024)
print('OK' if b'ping' in d else 'NO')
s.close()
" 2>/dev/null)
[ "$wsok" = "OK" ] && ok "WebSocket /live 回显" || bad "WebSocket 回显 $wsok"
echo "== Endpoint =="
code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE/api/ping")
[ "$code" = "200" ] && ok "GET /api/ping -> $code" || bad "ping -> $code"
curl -s "$BASE/api/ping" | grep -q 'marqdo-blog' && ok "ping json" || bad "ping json missing"
code=$(curl -s -o /tmp/mq_blog_echo.json -w "%{http_code}" \
-H 'Content-Type: application/json' -d '{"message":"hi"}' "$BASE/api/echo")
[ "$code" = "200" ] && ok "POST /api/echo -> $code" || bad "echo -> $code"
grep -q '"message":"hi"' /tmp/mq_blog_echo.json && ok "echo body" || bad "echo body missing"
echo
echo "通过 $PASS / $((PASS+FAIL))"
+9 -15
View File
@@ -1,20 +1,14 @@
# web-client-site(路线 D)
# examples/web-client-site
服务端 `ext/web` + 浏览器 WASM 会话;**作者零业务 JS**。
SSR **Document Artifact** + `web.client_embed` auto-mount(零作者 JS)。ADR 0007。
```bash
# 仓库根
cargo build -p marqdo --release
cargo build --release -p marqdo_plugin_web
./target/release/marqdo ext add web
# 构建 WASM + bridge 到本示例 static/
./target/release/marqdo wasm build -o examples/web-client-site/static
# 保留 client.mq.md(wasm build 只写入 wasm/bridge)
cd examples/web-client-site
marqdo run index.mq.md
# 打开 http://127.0.0.1:18090/
bash scripts/build-web-plugin.sh
export MARQDO_EXT=$PWD/ext # 若本机 ~/.marqdo/ext 未同步
marqdo wasm build -o examples/web-client-site/static
cargo run -- run examples/web-client-site/serve.mq.md
```
`index.mq.md` 用 `web.client_embed source="/static/client.mq.md"` 注入自启脚本;交互在 `static/client.mq.md`。
- `index.mq.md` — `type: web` 文档页
- `serve.mq.md` — `web.serve` + `static_dir`
- `static/client.mq.md` — `lib/browser` wire(不变)
+8 -13
View File
@@ -1,19 +1,14 @@
---
title: web-client-site
description: SSR shell + client_embed auto-mount; author zero JS (route D)
type: web
title: Marqdo client site
route: /
method: GET
description: SSR Document + client_embed auto-mount; author zero JS (ADR 0007).
import web:ext/web/web.mq.md
---
# main
# Marqdo client site
Server page with a counter UI. Client logic lives in `static/client.mq.md`
(loaded by official bridge via `client_embed`).
SSR shell with WASM session. Client logic lives in `static/client.mq.md`.
**`embed` = > web.client_embed bridge="/static/marqdo-bridge.js" wasm="/static/marqdo_wasm.wasm" source="/static/client.mq.md" boot=True**
**`intro` = "<h1>Marqdo client site</h1><p>SSR + WASM session. No author JS.</p><div id=\"count\">0</div><p><button id=\"bump\" type=\"button\" disabled>Bump</button> <button id=\"reset\" type=\"button\" disabled>Reset</button></p><pre id=\"log\">booting…</pre>" + embed**
**page = > web.page title="Marqdo client site" intro=intro**
**app = > web.app page=page host="127.0.0.1" port=18090**
**app = > app.static dir="static" mount="/static"**
> `app`.listen
To serve with static assets, run `serve.mq.md` in this directory.
+10
View File
@@ -0,0 +1,10 @@
---
title: web-client-site serve
import web:ext/web/web.mq.md
---
# main
**`embed` = > web.client_embed source="/static/client.mq.md"**
> print text=embed-ready
> web.serve root="." host="127.0.0.1" port=18090 static_dir="static"
+1 -1
View File
@@ -1 +1 @@
1.1.1
1.4.3
+320 -70
View File
@@ -9,6 +9,8 @@ import time:lib/time.mq.md
import wb:lib/writeback.mq.md
import subtask:lib/subtask.mq.md
import plugin:lib/plugin.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
---
## build_step_context
@@ -247,23 +249,129 @@ Structured observation for the parent developer-agent: source, named writeback s
---
## trial
+ `path`=None
+ `source`=None
+ `root`=None
+ `write_path`=None
+ `text`=None
+ `commit`=True
+ `profile`=default
Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard.
Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable).
**sb = sandbox.open root=`root` profile=`profile`**
**id = [id](sb)**
**prof = [profile](sb)**
**ok = True**
**stdout = ""**
**stderr = ""**
1. `write_path`
1. `text`
> sandbox.write id=`id` path=`write_path` text=`text`
2. *
**_ = 1**
2. *
**_ = 1**
1. `source`
**ret = sandbox.run id=`id` source=`source`**
**ok = [ok](ret)**
**stdout = [stdout](ret)**
**stderr = [stderr](ret)**
2. `path`
**ret = sandbox.run id=`id` path=`path`**
**ok = [ok](ret)**
**stdout = [stdout](ret)**
**stderr = [stderr](ret)**
3. *
**_ = 1**
**pending = sandbox.diff id=`id`**
**committed = False**
1. `ok`
1. `commit`
> sandbox.commit id=`id`
**committed = True**
2. *
> sandbox.discard id=`id`
2. *
> sandbox.discard id=`id`
**out = **
| ok | committed | diff | stdout | stderr | id | profile |
|----|-----------|------|--------|--------|-----|---------|
| `ok` | `committed` | `pending` | `stdout` | `stderr` | `id` | `prof` |
*out*
## step_route
+ `kind`=default
O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend.
Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads).
1. `kind` == "lookup"
**backend = "marqdo"**
2. `kind` == "patch"
**backend = "small-llm"**
3. `kind` == "sandbox_run"
**backend = "marqdo"**
4. `kind` == "net"
**backend = "llm"**
5. *
**backend = "auto"**
**out = table.put in=None at="kind" value=`kind`**
**out = table.put in=`out` at="backend" value=`backend`**
*out*
## await_workbook
+ `path`
+ `sandbox`=False
+ `sandbox_root`=None
+ `sandbox_profile`=default
Spawn a workbook file (quiet by default), wait for `{code,value,stdout?,stderr?}`, and inspect.
Spawn a workbook file (quiet by default), wait, and inspect.
With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit.
**id = > subtask.spawn path=`path`**
**waited = > subtask.wait id=`id`**
**code = > json.get value=`waited` key="code"**
**value = > json.get value=`waited` key="value"**
**stdout = > json.get value=`waited` key="stdout"**
**stderr = > json.get value=`waited` key="stderr"**
**obs = > inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = > json.parse text={"code":0}**
**out = > json.set map=`out` key="code" value=`code`**
**out = > json.set map=`out` key="value" value=`value`**
**out = > json.set map=`out` key="observation" value=`obs`**
*out*
1. `sandbox`
**tr = trial path=`path` root=`sandbox_root` profile=`sandbox_profile` commit=True**
**ok = [ok](tr)**
**stdout = [stdout](tr)**
**stderr = [stderr](tr)**
1. `ok`
**code = 0**
2. *
**code = 1**
**value = stdout**
**obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = **
| code | value | observation | sandbox |
|------|-------|-------------|---------|
| `code` | `value` | `obs` | `tr` |
*out*
2. *
**id = subtask.spawn path=`path`**
**waited = subtask.wait id=`id`**
**code = [code](waited)**
**value = [value](waited)**
**stdout = [stdout](waited)**
**stderr = [stderr](waited)**
**obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`**
**out = **
| code | value | observation |
|------|-------|-------------|
| `code` | `value` | `obs` |
*out*
---
@@ -1695,8 +1803,16 @@ Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `r
+ `kb_dir`=.marqdo/agent-kb
+ `memory_dir`=.marqdo/agent-memory
+ `threshold`=0.78
+ `step_kind`=None
Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`.
Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call.
1. `step_kind`
**sr = step_route kind=`step_kind`**
**backend = [backend](sr)**
2. *
**_ = 1**
**tools = > json.get value=`self` key="tools"**
*> agent_route task=`task` backend=`backend` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`threshold` tools=`tools`*
@@ -1747,6 +1863,15 @@ Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). M
*> agent_record_episode task=`task` status=`status` result=`result` mode=`mode` skill=`skill` observation=`observation` workbook=`workbook` cache=`cache` match=`match` llm_calls=`llm_calls` tool_calls=`tool_calls` error=`error` memory_dir=`memory_dir`*
## quarantine
+ `slug`
+ `kb_dir`=.marqdo/agent-kb
+ `reason`=sandbox_or_harness_failed
O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug.
*> agent_kb_quarantine kb_dir=`kb_dir` slug=`slug` reason=`reason`*
## maybe_learn
+ `task`
+ `kb_dir`=.marqdo/agent-kb
@@ -1755,6 +1880,7 @@ Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). M
+ `promote`=True
Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing.
O2: promote path requires sandbox proof unless `require_proof=false`.
**skill_learn = > agent_maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote`**
**policy_learn = > agent_maybe_compile_policy memory_dir=`memory_dir` min_evidence=`improve_every`**
@@ -1806,8 +1932,18 @@ Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_
+ `router_model`=None
+ `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume
+ `sandbox`=False
+ `sandbox_profile`=default
+ `efi`=True
Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome.
`sandbox=True` (O1 opt-in): workbook paths run via CoW trial before host commit. `efi=True` (O3): EKC preflight before explore; REUSE short-circuits. Pass `efi=False` to keep legacy golds that skip eng knowledge.
**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`**
**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"**
**llm_calls = 0**
**tokens = 0**
**token_cost = 0**
**out = None**
**route_backend = > json.get value=`routed` key="backend"**
1. `route_matched`
**path = > json.get value=`routed` key="resource"**
1. `path`
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**lf = > json.get value=`routed` key="llm_free"**
@@ -1832,19 +1969,14 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**exec_mode = "compiled"**
2. *
**exec_mode = "routed"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="hit"**
**rmode = > json.get value=`routed` key="mode"**
**out = > json.set map=`out` key="match" value=`rmode`**
**sk = > json.get value=`routed` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="adaptive route hit"**
**out = > json.set map=`out` key="route" value=`routed`**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary | route |
|--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` |
**llm_calls = 0**
2. *
**route_matched = False**
@@ -1858,7 +1990,7 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
2. `needs_llm`
1. `router_model`
**prompt = > json.get value=`routed` key="prompt"**
**turn = > model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`**
**turn = model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`**
**reply = > json.get value=`turn` key="text"**
**llm_calls = > json.get value=`turn` key="llm_calls"**
**tokens = > json.get value=`turn` key="tokens"**
@@ -1866,24 +1998,19 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
**am = > json.get value=`applied` key="matched"**
1. `am`
**path = > json.get value=`applied` key="resource"**
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
**exec_mode = "routed"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="soft-hit"**
**out = > json.set map=`out` key="match" value="routed"**
**sk = > json.get value=`applied` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="router model selected skill"**
**out = > json.set map=`out` key="route" value=`applied`**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary | route |
|--------|------|--------|----------|-------|-------|-------|-------------|---------|-------|
| ok | `task` | `child_val` | `path` | soft-hit | routed | `sk` | `last_obs` | router model selected skill | `applied` |
**route_matched = True**
2. *
**route_matched = False**
@@ -1897,29 +2024,53 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
1. `route_matched`
**_ = 1**
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`**
**mode = > json.get value=`resolved` key="mode"**
**llm_free = > json.get value=`resolved` key="llm_free"**
1. not `llm_free`
**llm_free = False**
1. `llm_free`
**path = > json.get value=`resolved` key="resource"**
**aw = > await_workbook path=`path`**
**code = > json.get value=`aw` key="code"**
**child_val = > json.get value=`aw` key="value"**
**last_obs = > json.get value=`aw` key="observation"**
**aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`**
**code = [code](aw)**
**child_val = [value](aw)**
**last_obs = [observation](aw)**
1. `code` == 0
> agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every`
**exec_mode = "compiled"**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="status" value="ok"**
**out = > json.set map=`out` key="goal" value=`task`**
**out = > json.set map=`out` key="result" value=`child_val`**
**out = > json.set map=`out` key="workbook" value=`path`**
**out = > json.set map=`out` key="cache" value="hit"**
**out = > json.set map=`out` key="match" value=`mode`**
**sk = > json.get value=`resolved` key="skill"**
**out = > json.set map=`out` key="skill" value=`sk`**
**out = > json.set map=`out` key="observation" value=`last_obs`**
**out = > json.set map=`out` key="summary" value="compiled skill (llm_free)"**
**out = **
| status | goal | result | workbook | cache | match | skill | observation | summary |
|--------|------|--------|----------|-------|-------|-------|-------------|--------|
| ok | `task` | `child_val` | `path` | hit | `mode` | `sk` | `last_obs` | compiled skill (llm_free) |
**llm_calls = 0**
2. *
**out = > `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force`**
@@ -1966,23 +2117,37 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
2. *
**_ = 1**
**execution = > json.parse text={"mode":"explore","llm_calls":0,"tokens":0}**
**execution = > json.set map=`execution` key="mode" value=`exec_mode`**
**execution = > json.set map=`execution` key="llm_calls" value=`llm_calls`**
**execution = > json.set map=`execution` key="tokens" value=`tokens`**
**execution = > json.set map=`execution` key="skill" value=`sk2`**
**execution = > json.set map=`execution` key="router" value=`route_backend`**
**out = > json.set map=`out` key="execution" value=`execution`**
**out = > json.set map=`out` key="episode" value=`ep`**
**out = > json.set map=`out` key="route" value=`routed`**
**token_cost = tokens**
**usage = **
| llm_calls | tokens | token_cost |
|-----------|--------|------------|
| `llm_calls` | `tokens` | `token_cost` |
**execution = **
| mode | llm_calls | tokens | token_cost | skill | router |
|------|-----------|--------|------------|-------|--------|
| `exec_mode` | `llm_calls` | `tokens` | `token_cost` | `sk2` | `route_backend` |
**out = table.put in=`out` at="execution" value=`execution`**
**out = table.put in=`out` at="episode" value=`ep`**
**out = table.put in=`out` at="route" value=`routed`**
**out = table.put in=`out` at="usage" value=`usage`**
**out = table.put in=`out` at="token_cost" value=`token_cost`**
1. `learning`
**out = > json.set map=`out` key="learning" value=`learning`**
**out = table.put in=`out` at="learning" value=`learning`**
2. *
**_ = 1**
1. `efi_pf`
**out = table.put in=`out` at="efi" value=`efi_pf`**
2. *
**_ = 1**
1. `resume_id`
**_ckpt = > resume_save id=`resume_id` goal=`task` task=`task` status=`st` round=1 workbook=`wb_path` result=`res` route=`routed` resume_dir=`resume_dir`**
**out = > json.set map=`out` key="resume" value=`_ckpt`**
**_ckpt = resume_save id=`resume_id` goal=`task` task=`task` status=`st` round=1 workbook=`wb_path` result=`res` route=`routed` resume_dir=`resume_dir`**
**out = table.put in=`out` at="resume" value=`_ckpt`**
2. *
**_ = 1**
@@ -1994,10 +2159,13 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
+ `stream`=False
+ `echo`=False
+ `max_reads`=2
+ `sandbox`=False
+ `sandbox_profile`=default
One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip.
With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer.
`sandbox=True` (O1 opt-in): attach the sandbox profile row on the result map (trial via `## trial` / `run sandbox=`).
**id = > json.get value=`self` key="id"**
**model = > json.get value=`self` key="model"**
@@ -2088,6 +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="tokens" value=`tokens`**
1. `sandbox`
**prof = sandbox.profile name=`sandbox_profile`**
**out = table.put in=`out` at="sandbox_profile" value=`prof`**
2. *
**_ = 1**
**as_turn = > json.parse text={"role":"assistant"}**
**as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn`
@@ -2104,6 +2278,51 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
*out*
## preflight
+ `task`
+ `root`="."
+ `marqdo_dir`=None
+ `min_candidates`=3
+ `allow_create_after`=2
+ `reuse_threshold`=0.72
+ `adapt_threshold`=0.45
Engineering First Information gate (008 / EKC). Reads compiled `.marqdo` knowledge.
Returns `{status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}`.
Hard rule: generate only when `create_allowed` is true (or decision is REUSE/ADAPT).
1. `marqdo_dir`
**pf = > agent_eng_preflight task=`task` root=`root` marqdo_dir=`marqdo_dir` min_candidates=`min_candidates` allow_create_after=`allow_create_after` reuse_threshold=`reuse_threshold` adapt_threshold=`adapt_threshold`**
2. *
**pf = > agent_eng_preflight task=`task` root=`root` min_candidates=`min_candidates` allow_create_after=`allow_create_after` reuse_threshold=`reuse_threshold` adapt_threshold=`adapt_threshold`**
*pf*
## eng_reuse
+ `task`
+ `root`="."
+ `marqdo_dir`=None
Alias of `preflight` focused on REUSE / ADAPT / CREATE payload.
1. `marqdo_dir`
*> agent_eng_reuse task=`task` root=`root` marqdo_dir=`marqdo_dir`*
2. *
*> agent_eng_reuse task=`task` root=`root`*
## eng_record
+ `decision`
+ `root`="."
+ `marqdo_dir`=None
+ `duplicated`=False
Record REUSE/ADAPT/CREATE into `.marqdo/agent/episodes/reuse_metrics.json`.
1. `marqdo_dir`
*> agent_eng_record decision=`decision` root=`root` marqdo_dir=`marqdo_dir` duplicated=`duplicated`*
2. *
*> agent_eng_record decision=`decision` root=`root` duplicated=`duplicated`*
## plan
+ `goal`
+ `workbook_dir`=None
@@ -2127,9 +2346,14 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
+ `trace`=False
+ `resume_id`=None
+ `resume_dir`=.marqdo/agent-resume
+ `eng_preflight`=False
+ `marqdo_dir`=.marqdo
+ `allow_create_after`=2
Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/<slug>.mq.md`. While task file count `< explore_n` and skill is not llm_free, force a new explore variant under `kb_dir/explore/<slug>/`. Code-first: llm_free hits skip parent LLM. File children return via `# main`; `plan` exposes that as `result`.
Engineering Knowledge preflight when `eng_preflight=True`: REUSE/ADAPT preferred; CREATE only if `create_allowed`. Production agents should enable this; tests that only exercise agent-kb may leave it false.
Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when `near_match=True` and score ≥ `near_threshold`. Non-hit path: optional `soft_match=True` parent REUSE/NEW over ranked `agent_kb_near_match` candidates; else decompose before first child spawn (`DECISION: RUN` / `CONTINUE`+patch / solidified `DONE`). Then `await` → revise loop. Process events (`decision` / `round` / `done` / tools) are always attached on the result map for audit and view process cards; `stream=True` additionally SSE-publishes them (and parent `delta`). `echo=True` prints `plan:decompose` / `plan:await` / deltas. `trace=True` writes events to writeback slot `trace`. Quiet child subtasks stay quiet.
**tools = > json.get value=`self` key="tools"**
@@ -2140,6 +2364,32 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
**explore_attempt = None**
**skel_kind = skeleton**
**events = > json.parse text=[]**
**eng = None**
1. `eng_preflight`
**eng = > agent_eng_preflight task=`goal` marqdo_dir=`marqdo_dir` allow_create_after=`allow_create_after`**
**eng_status = > json.get value=`eng` key="status"**
**eng_decision = > json.get value=`eng` key="decision"**
**eng_allowed = > json.get value=`eng` key="create_allowed"**
1. `eng_status` == missing_knowledge
**_ = 1**
2. `eng_decision` == REUSE
> agent_eng_record decision="REUSE" marqdo_dir=`marqdo_dir`
**_ = 1**
3. `eng_decision` == ADAPT
> agent_eng_record decision="ADAPT" marqdo_dir=`marqdo_dir`
**_ = 1**
4. `eng_allowed`
> agent_eng_record decision="CREATE" marqdo_dir=`marqdo_dir`
**_ = 1**
5. *
**out = > json.parse text={"status":"blocked","cache":"eng-block","eng":true}**
**out = > json.set map=`out` key="decision" value="BLOCKED"**
**out = > json.set map=`out` key="preflight" value=`eng`**
**out = > json.set map=`out` key="events" value=`events`**
*out*
2. *
**_ = 1**
**tf = > agent_kb_task_files kb_dir=`kb_dir` goal=`goal` tools=`tools`**
**nfiles = > json.get value=`tf` key="count"**
+10 -1
View File
@@ -289,11 +289,20 @@ Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `
2. *
**_ = 1**
Hoist receiver fields before the result table — table cells can shadow `self` /
column names (`model`, `usage`), so `[model](self)` / `[total_tokens](usage)`
inside the table is unsafe.
**mdl = [model](self)**
**b = [backend](self)**
**nm = [name](self)**
**tt = [total_tokens](usage)**
`result` =
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls |
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | [model](self) | `finish` | [backend](self) | `usage` | [name](self) | 1 | [total_tokens](usage) | `tc` |
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
*result*
+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*
+8 -1
View File
@@ -240,11 +240,18 @@ import openai:ext/ai/llm/openai.mq.md
2. *
**_ = 1**
表单元格会遮蔽 `自` / 列名,先取出字段再组结果表。
**mdl = [model](自)**
**b = [backend](自)**
**nm = [name](自)**
**tt = [total_tokens](usage)**
`result` =
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls |
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | [model](自) | `finish` | [backend](自) | `usage` | [name](自) | 1 | [total_tokens](usage) | `tc` |
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
*result*
+42 -5
View File
@@ -3,6 +3,8 @@ title: ext/ai/智能体
description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编译经 ABI v2 agent 插件(情景 → 学习 → llm_free)。
导入 大模型:ext/ai/大模型.mq.md
import agent:ext/ai/agent.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
import json:lib/json.mq.md
导入 系统:lib/系统.mq.md
导入 自写回:lib/自写回.mq.md
@@ -106,15 +108,30 @@ import json:lib/json.mq.md
> agent_history_clear id=`id`
****
## 试跑
+ `路径`=None
+ `源码`=None
+ `根目录`=None
+ `写入路径`=None
+ `文本`=None
+ `提交`=真
+ `配置`=default
O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。
*> agent.trial path=`路径` source=`源码` root=`根目录` write_path=`写入路径` text=`文本` commit=`提交` profile=`配置`*
## 单步
+ `任务`
+ `写回`=真
+ `流式`=假
+ `打印增量`=假
+ `沙盒`=假
+ `沙盒配置`=default
原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。
**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`**
**id = > json.get value=`自` key="id"**
@@ -171,6 +188,12 @@ import json:lib/json.mq.md
**as_turn = > json.set map=`as_turn` key="content" value=`reply`**
> agent_history_append id=`id` item=`as_turn`
1. `沙盒`
**配置行 = sandbox.profile name=`沙盒配置`**
**out = table.put in=`out` at="sandbox_profile" value=`配置行`**
2. *
**_ = 1**
1. `写回`
**body = > json.stringify value=`out`**
**st = > json.get value=`out` key="status"**
@@ -183,6 +206,15 @@ import json:lib/json.mq.md
*out*
## 工程预检
+ `任务`
+ `根目录`="."
+ `知识目录`=None
Engineering First Information 门闩。转发 `agent.preflight`。
*> agent.preflight task=`任务` root=`根目录` marqdo_dir=`知识目录`*
## 多步
+ `目标`
+ `工作簿目录`=None
@@ -204,14 +236,16 @@ import json:lib/json.mq.md
+ `流式`=False
+ `打印增量`=False
+ `轨迹`=False
+ `工程预检`=False
+ `工程知识目录`=.marqdo
多步工作簿默认写入 OKF `知识库目录/resources/<slug>.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。
多步工作簿默认写入 OKF `知识库目录/resources/<slug>.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。
**model = > json.get value=`self` key="model"**
**tools = > json.get value=`self` key="tools"**
**standing = > json.get value=`self` key="standing"**
**en = > agent.agent model=`model` tools=`tools` standing=`standing`**
*> en.plan goal=`目标` workbook_dir=`工作簿目录` workbook=`工作簿` max_rounds=`最大轮次` confirm=`确认分解` writeback=`写回` skeleton=`骨架` reuse=`复用` optimize=`优化` force=`强制` soft_match=`软命中` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` kb_dir=`知识库目录` improve_every=`改进周期` explore_n=`探索次数` stream=`流式` echo=`打印增量` trace=`轨迹`*
*> en.plan goal=`目标` workbook_dir=`工作簿目录` workbook=`工作簿` max_rounds=`最大轮次` confirm=`确认分解` writeback=`写回` skeleton=`骨架` reuse=`复用` optimize=`优化` force=`强制` soft_match=`软命中` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` kb_dir=`知识库目录` improve_every=`改进周期` explore_n=`探索次数` stream=`流式` echo=`打印增量` trace=`轨迹` eng_preflight=`工程预检` marqdo_dir=`工程知识目录`*
## 解析
+ `任务`
@@ -285,14 +319,17 @@ import json:lib/json.mq.md
+ `强制`=False
+ `路由`=auto
+ `路由模型`=None
+ `沙盒`=False
+ `沙盒配置`=default
+ `工程预检`=True
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。
**model = > json.get value=`self` key="model"**
**tools = > json.get value=`self` key="tools"**
**standing = > json.get value=`self` key="standing"**
**en = > agent.agent model=`model` tools=`tools` standing=`standing`**
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型`*
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型` sandbox=`沙盒` sandbox_profile=`沙盒配置` efi=`工程预检`*
## 路由
+ `任务`
+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`*
+60
View File
@@ -0,0 +1,60 @@
---
title: ext/data/cache
description: Cache Resource (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
# cache
+ `url`="memory:"
Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis.
> _load
*> web_cache_new url=`url`*
## get
+ `key`
**url = [url](self)**
*> web_cache_get url=`url` key=`key`*
## set
+ `key`
+ `value`
+ `ttl`=None
Optional `ttl` is seconds until expiry.
**url = [url](self)**
*> web_cache_set url=`url` key=`key` value=`value` ttl=`ttl`*
## del
+ `key`
**url = [url](self)**
*> web_cache_del url=`url` key=`key`*
## exists
+ `key`
**url = [url](self)**
*> web_cache_exists url=`url` key=`key`*
## ttl
+ `key`
**url = [url](self)**
*> web_cache_ttl url=`url` key=`key`*
+238
View File
@@ -0,0 +1,238 @@
---
title: ext/data/db
description: Database Resource — CRUD, txn, migrate, FTS (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
# db
+ `url`="sqlite:site.db"
Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods).
> _load
*> web_db_new url=`url`*
## init
+ `name`
+ `fields`
Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present.
**url = [url](self)**
*> web_db_init url=`url` name=`name` fields=`fields`*
## insert
+ `table`
+ `rows`
+ `txn`=None
**url = [url](self)**
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
## select
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
+ `txn`=None
Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`.
**url = [url](self)**
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
*[rows](r)*
## paginate
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
+ `跳过`=0
+ `txn`=None
Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10).
**url = [url](self)**
*> web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=`跳过` txn=`txn`*
## get
+ `table`
+ `id`
+ `txn`=None
**url = [url](self)**
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
## update
+ `table`
+ `id`
+ `row`
+ `txn`=None
**url = [url](self)**
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
## delete
+ `table`
+ `id`
+ `txn`=None
**url = [url](self)**
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
## exec
+ `sql`
+ `args`=None
+ `txn`=None
**url = [url](self)**
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
## query
+ `sql`
+ `args`=None
+ `txn`=None
Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`.
**url = [url](self)**
*> web_db_query url=`url` sql=`sql` args=`args` txn=`txn`*
## count
+ `table`
+ `where`=None
+ `txn`=None
Count rows matching a `where` filter (same syntax as `select`). Returns a number.
**url = [url](self)**
**r = > web_db_count url=`url` table=`table` where=`where` txn=`txn`**
*[count](r)*
## migrate
+ `steps`
Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only.
**url = [url](self)**
*> web_db_migrate url=`url` steps=`steps`*
## fts
+ `table`
+ `columns`
+ `name`=None
Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only.
**url = [url](self)**
*> web_db_fts_create url=`url` table=`table` columns=`columns` name=`name`*
## search
+ `table`
+ `q`
+ `limit`=20
+ `name`=None
Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only.
**url = [url](self)**
*> web_db_search url=`url` table=`table` q=`q` limit=`limit` name=`name`*
## 事务
Begin a transaction: borrows the pooled connection exclusively and returns a
`txn` handle. Write inside it, then `提交` (commit) or `回滚` (roll back).
Every statement runs on the same connection, so a batch is atomic.
**url = [url](self)**
*> web_db_begin url=`url`*
# txn
+ `txn`
+ `url`
A transaction handle from `db.事务`. All CRUD here runs on the transaction's
connection; finish with `提交` or `回滚`.
*self*
## insert
+ `table`
+ `rows`
**url = [url](self)**
**txn = [txn](self)**
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
## select
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
Same filters as `db.select`; runs inside the transaction.
**url = [url](self)**
**txn = [txn](self)**
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
*[rows](r)*
## get
+ `table`
+ `id`
**url = [url](self)**
**txn = [txn](self)**
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
## update
+ `table`
+ `id`
+ `row`
**url = [url](self)**
**txn = [txn](self)**
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
## delete
+ `table`
+ `id`
**url = [url](self)**
**txn = [txn](self)**
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
## exec
+ `sql`
+ `args`=None
**url = [url](self)**
**txn = [txn](self)**
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
## 提交
Commit the transaction and return its connection to the pool.
**txn = [txn](self)**
*> web_db_commit txn=`txn`*
## 回滚
Roll the transaction back (undo every write) and return its connection.
**txn = [txn](self)**
*> web_db_rollback txn=`txn`*
+67
View File
@@ -0,0 +1,67 @@
---
title: ext/data/form
description: Form Resource — fields, validate, submit (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
# form
+ `table`=None
+ `action`=insert
+ `id`=None
Field table + rules table; submit writes through `# db`.
> _load
*> web_form_new table=`table` action=`action` id=`id`*
## fields
+ `fields`
*> web_form_fields form=`self` fields=`fields`*
## rules
+ `rules`
*> web_form_rules form=`self` rules=`rules`*
## labels
+ `submit`="Submit"
+ `cancel`="cancel"
+ `cancel_href`=""
Localized submit / cancel copy for rendered forms.
*> web_form_labels form=`self` submit=`submit` cancel=`cancel` cancel_href=`cancel_href`*
## validate
+ `rules`=None
+ `data`
*> web_form_validate form=`self` rules=`rules` data=`data`*
## render
+ `id`=form
+ `data`=None
+ `errors`=None
*> web_form_render form=`self` id=`id` data=`data` errors=`errors`*
## submit
+ `data`
+ `db`
**url = [url](db)**
*> web_form_submit form=`self` data=`data` url=`url`*
+86
View File
@@ -0,0 +1,86 @@
---
title: ext/data/storage
description: Object storage Resource (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
# storage
+ `url`="file:data/blobs"
Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3.
> _load
*> web_storage_new url=`url`*
## put
+ `key`
+ `body`=None
+ `path`=None
+ `content_type`="application/octet-stream"
Provide either `body` (text) or `path` (local file to upload).
**url = [url](self)**
*> web_storage_put url=`url` key=`key` body=`body` path=`path` content_type=`content_type`*
## get
+ `key`
**url = [url](self)**
*> web_storage_get url=`url` key=`key`*
## delete
+ `key`
**url = [url](self)**
*> web_storage_delete url=`url` key=`key`*
## list
+ `prefix`=""
**url = [url](self)**
*> web_storage_list url=`url` prefix=`prefix`*
# media
+ `storage`=None
Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`).
> _load
*> web_media_new storage=`storage`*
## validate
+ `filename`
+ `content_type`="application/octet-stream"
+ `size`
+ `max_bytes`=5242880
+ `types`=None
*> web_upload_validate filename=`filename` content_type=`content_type` size=`size` max_bytes=`max_bytes` types=`types`*
## save
+ `path`
+ `key`=None
+ `content_type`="application/octet-stream"
+ `prefix`=uploads/
+ `storage`=None
**st = storage**
1. `st` == None
**st = [storage](self)**
2. *
*> web_upload_save storage=`st` path=`path` key=`key` content_type=`content_type` prefix=`prefix`*
+31
View File
@@ -0,0 +1,31 @@
---
title: ext/net/http
description: HTTP primitives surface for Web Runtime (ADR 0007). Prefer Document/Endpoint Artifacts over raw calls.
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/net: native web plugin not found
> sys.exit code=1
****
## result
+ `ok`
+ `value`=None
+ `error`=None
Unified Result map `{ok, value, error}`.
`out` =
| ok | value | error |
|----|-------|-------|
| `ok` | `value` | `error` |
*out*
+10
View File
@@ -0,0 +1,10 @@
---
title: ext/net/url
description: URL helpers (stdlib wrappers). ADR 0007.
import net:lib/net.mq.md
---
## encode
+ `text`
*> net.url_encode text=`text`*
+41
View File
@@ -0,0 +1,41 @@
---
title: ext/net/websocket
description: WebSocket client Resource (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/net: native web plugin not found
> sys.exit code=1
****
# ws
+ `timeout_sec`=30
WebSocket client helper.
> _load
`out` =
| timeout_sec | _type |
|-------------|-------|
| `timeout_sec` | ws |
*out*
## connect
+ `url`
+ `message`=""
+ `headers`=None
Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply.
**timeout = [timeout_sec](self)**
*> web_ws_connect url=`url` message=`message` headers=`headers` timeout_sec=`timeout`*
+58
View File
@@ -0,0 +1,58 @@
---
title: ext/security/auth
description: Auth Resource (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
# auth
+ `users`
+ `session_ttl`=3600
Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead.
> _load
*> web_auth_new users=`users` session_ttl=`session_ttl`*
## login
+ `username`
+ `password`
Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`.
**users = [users](self)**
**ttl = [session_ttl](self)**
*> web_auth_login username=`username` password=`password` users=`users` session_ttl=`ttl`*
## check
+ `session_id`
Returns `{ok, username, role}` when the session is valid.
*> web_auth_check session_id=`session_id`*
## logout
+ `session_id`
Destroy the session.
*> web_auth_logout session_id=`session_id`*
## hash_password
+ `password`
Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically.
*> web_password_hash password=`password`*
+41
View File
@@ -0,0 +1,41 @@
---
title: ext/security/oidc
description: OIDC attach helper for app handles (ADR 0007). Prefer declared auth metadata on Endpoints.
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
## attach
+ `app`
+ `issuer`=None
+ `client_id`
+ `client_secret`
+ `redirect_uri`
+ `redirect_origins`=None
+ `scopes`="openid profile email"
+ `callback_path`=None
+ `authorize_url`=None
+ `token_url`=None
+ `userinfo_url`=None
`redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path
(`/oidc/callback`). Path mode resolves the absolute callback from the login request
Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores
it in the session so token exchange uses the same string.
Optional `redirect_origins` is a comma-separated allowlist
(`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match.
The IdP must still register every absolute callback URL that will be used.
> _load
*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` redirect_origins=`redirect_origins` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`*
+61
View File
@@ -0,0 +1,61 @@
---
title: ext/security/rbac
description: RBAC Resource (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
---
## _load
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
# rbac
Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests.
## can
+ `permissions`
+ `needed`
Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all.
> _load
*> web_rbac_can permissions=`permissions` needed=`needed`*
## assign_role
+ `url`
+ `username`
+ `role`
Bind `username` (in `web_users`) to role name.
> _load
*> web_rbac_assign_role url=`url` username=`username` role=`role`*
## create_role
+ `url`
+ `name`
Create a non-system role; returns `{ok, id, name}`.
> _load
*> web_rbac_create_role url=`url` name=`name`*
## set_role_permissions
+ `url`
+ `role`
+ `permissions`
+ `grantable`=""
Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog.
> _load
*> web_rbac_set_role_permissions url=`url` role=`role` permissions=`permissions` grantable=`grantable`*
+17 -28
View File
@@ -1,31 +1,20 @@
# ext/web
# ext/web — Document / Endpoint / Resource
Official dynamic website extension: **GFM tables + class methods**.
Design: [`doc/design/ext-web.md`](../../doc/design/ext-web.md).
Official dynamic site extension (**ADR 0007**). Design: [`doc/design/ext-web-artifact.md`](../../doc/design/ext-web-artifact.md).
| Surface | Import | Classes |
|---------|--------|---------|
| English | `> ext/web/web.mq.md` | `page` · `db` · `app` · `form` · `style` |
| Chinese | `> ext/web/网页.mq.md` | `页面` · `数据库` · `应用` · `表单` · `样式` |
```bash
cargo build -p marqdo_plugin_web
# optional install into ~/.marqdo/ext
marqdo ext add web
```
Canonical sample (design §4): [`examples/web-site/`](../../examples/web-site/).
```bash
cargo run -- run examples/web-site/index.mq.md
# http://127.0.0.1:18081/
# /_form/article · /admin · /admin/articles/new
```
Offline smokes: `tests/ext/web-smoke.mq.md`, `web-form-smoke.mq.md`, `web-admin-smoke.mq.md`.
| Feature | Notes |
| Surface | Import |
|---------|--------|
| Form §5.5 | field/rules tables · `validate` · `submit` · `mount_form` → `GET\|POST /_form/{id}` |
| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
| Route | `` `app`.route path=/about page=`about` `` → `GET /about` |
| English | `import web:ext/web/web.mq.md` |
| Chinese | `导入 网页:ext/web/网页.mq.md` |
**Facade:** `page` · `route` · `serve` · `render` · `inspect` · `use`
**Related modules:** `ext/data` (db/cache/storage) · `ext/security` (auth/oidc/rbac) · `ext/net` (http/websocket/url)
```bash
bash scripts/build-web-plugin.sh
marqdo ext add web # optional install
marqdo run examples/marqdo-blog/serve.mq.md
```
Hard rules: no author `ensure_plugin` / `compose_*` / `configure` junk drawer; View schema `|type|slot|value|attrs|style|` only; declared vs system routes via `inspect`.
+18
View File
@@ -0,0 +1,18 @@
---
title: ext/web/_capability
description: Internal — load native web plugin once. Authors must not call this; import web = capability (ADR 0007).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
## load
Load ABI v2 `web` plugin if present. Fail loud when missing.
**p = > plugin.native_path name="web"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/web: native web plugin not found (build plugins/web or marqdo ext add web)
> sys.exit code=1
****
+50
View File
@@ -0,0 +1,50 @@
---
title: ext/web/client
description: Browser Runtime helpers (WASM bridge). Prefer lib/browser for effect tables (ADR 0007).
import cap:ext/web/_capability.mq.md
import table:lib/table.mq.md
---
## embed
+ `bridge`="/static/marqdo-bridge.js"
+ `wasm`="/static/marqdo_wasm.wasm"
+ `source`=""
+ `boot`=True
HTML snippet that loads the official browser Marqdo bridge (route C/D). With `boot` and non-empty `source`, auto-mounts. No author JS.
> cap.load
1. `boot`
1. `source` != ""
*"<script type=\"module\" src=\"" + bridge + "\" data-mq-wasm=\"" + wasm + "\" data-mq-source-url=\"" + source + "\"></script>"*
2. *
*"<script type=\"module\" src=\"" + bridge + "\"></script>"*
2. *
*"<script type=\"module\" src=\"" + bridge + "\" data-mq-no-boot=\"1\"></script>"*
## text_patch
+ `sel`
+ `text`
`set_text` effects map. Prefer `lib/browser` in client `.mq.md`.
**`m` = > table.put in=None at=sel value=text**
*> table.put in=None at="set_text" value=m*
## dom_patch
+ `sel`
+ `html`=""
+ `attrs`=None
+ `remove`=False
**`spec` = > table.put in=None at="html" value=html**
1. `attrs`
**`spec` = > table.put in=`spec` at="attrs" value=attrs**
2. *
**_ = 1**
1. `remove`
**`spec` = > table.put in=`spec` at="remove" value=True**
2. *
**_ = 1**
**`m` = > table.put in=None at=sel value=spec**
*> table.put in=None at="dom" value=m*
+20
View File
@@ -0,0 +1,20 @@
---
title: ext/web/component
description: Reusable Document fragments as View node tables (ADR 0007).
import table:lib/table.mq.md
---
## nodes
+ `table`
Identity helper — a component is a View table `|type|slot|value|attrs|style|`.
*table*
## merge
+ `a`
+ `b`
Concatenate two View node lists (list-of-maps or column tables). Prefer authoring one table.
*> table.concat a=`a` b=`b`*
+38
View File
@@ -0,0 +1,38 @@
---
title: ext/web/dom
description: DOM Artifact — Markdown/body to structure; raw HTML is escape hatch only (ADR 0007).
import cap:ext/web/_capability.mq.md
import table:lib/table.mq.md
---
## from_markdown
+ `text`
Turn Markdown text into a simple DOM map `{kind:"markdown", text}` for `page.render` / `web.render`.
> cap.load
**`out` = > table.put in=None at="kind" value="markdown"**
*> table.put in=`out` at="text" value=text*
## raw
+ `html`
Escape hatch — wrap a raw HTML string. Prefer Markdown / View nodes.
> cap.load
**`out` = > table.put in=None at="kind" value="raw"**
*> table.put in=`out` at="html" value=html*
## render
+ `dom`
Render a DOM Artifact (markdown or raw) to HTML via native plugin.
> cap.load
**kind = [kind](dom)**
1. `kind` == "raw"
**html = [html](dom)**
*html*
2. *
**text = [text](dom)**
*> web_dom_markdown text=`text`*
+54
View File
@@ -0,0 +1,54 @@
---
title: ext/web/page
description: Document → View. Sole compose path is render(nodes=) with unified View schema (ADR 0007).
import cap:ext/web/_capability.mq.md
import table:lib/table.mq.md
---
# page
+ `title`=""
+ `route`="/"
+ `method`="GET"
+ `body`=""
+ `nodes`=None
+ `data_source`=""
+ `data_order`=""
+ `data_where`=""
Web Document handle. Prefer constructing from Artifact Metadata via `web.page` facade.
View tables use only `|type|slot|value|attrs|style|` (ZH `|类型|槽|值|属性|样式|`).
> cap.load
`out` =
| _type | title | route | method | body | nodes | data_source | data_order | data_where |
|-------|-------|-------|--------|------|-------|-------------|------------|------------|
| page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` |
*out*
## render
+ `nodes`=None
+ `db`=None
Render Document to HTML. `nodes` is the unified View table; when omitted, uses `self.nodes` or Markdown `body`.
> cap.load
**n = nodes**
1. `n` == None
**n = [nodes](self)**
2. *
**_ = 1**
1. `n`
*> web_render_nodes page=`self` nodes=`n` db=`db`*
2. *
**body = [body](self)**
*> web_render_document page=`self` body=`body` db=`db`*
## css
+ `css`
Escape hatch — append raw CSS (not a second primary language).
> cap.load
*> web_page_css page=`self` css=`css`*
+60
View File
@@ -0,0 +1,60 @@
---
title: ext/web/route
description: Declared Endpoint / Document route registration (ADR 0007).
import cap:ext/web/_capability.mq.md
import table:lib/table.mq.md
---
# route
+ `app`
+ `path`
+ `method`="GET"
+ `page`=None
+ `fn`=""
+ `request`="json"
+ `response`="json"
+ `auth`=""
Declared route handle. Prefer `web.route` / Artifact `type: endpoint` discovery via `web.serve`.
> cap.load
`out` =
| _type | app | path | method | page | fn | request | response | auth |
|-------|-----|------|--------|------|----|---------|----------|------|
| route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` |
*out*
## use
+ `middleware`
Attach middleware table to this route (`|header|value|` or named capability rows).
> cap.load
*> web_route_use route=`self` middleware=`middleware`*
## register
+ `app`=None
Register this declared route on an app handle.
> cap.load
**a = app**
1. `a` == None
**a = [app](self)**
2. *
**_ = 1**
**page = [page](self)**
**fn = [fn](self)**
1. `page`
**path = [path](self)**
*> web_app_route app=`a` path=`path` page=`page`*
2. `fn`
**path = [path](self)**
**method = [method](self)**
**request = [request](self)**
**response = [response](self)**
*> web_app_invoke app=`a` path=`path` method=`method` fn=`fn` body=`request` return=`response`*
3. *
*> table.put in=None at="ok" value=False*
+94 -1091
View File
File diff suppressed because it is too large. Load diff
+47 -1113
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -52,6 +52,12 @@ Lookup one metadata key; missing → None.
*> host_meta_get key=`key`*
## artifact_kind
Classify entry Artifact Metadata: `web` / `endpoint` / `prompt` / `other`, or None if no `type`/`类型`. ADR 0007.
*> host_artifact_kind*
## module_source
Entry `.mq.md` source text (for document-as-prompt). Empty string if unset.
+2 -2
View File
@@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback)
+ `key`=None
+ `line`=None
Write `value` to `<!-- marqdo-out … -->` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `![marqdo-out](…)` (or `![marqdo-out key](…)`); other values use `<!-- marqdo-out … -->`. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
@@ -51,6 +51,6 @@ List all output blocks in the entry file (includes `key` when named).
## scan_path
+ `path`
List `<!-- marqdo-out … -->` slots in any file (workbook inspection).
List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection).
*> host_writeback_scan_path path=`path`*
+6
View File
@@ -52,6 +52,12 @@ description: 中文系统包装(加载环境 可选 路径=)
*> host_meta_get key=`键`*
## 工件种类
入口 Artifact 分类:`web` / `endpoint` / `prompt` / `other`;无 `type`/`类型` → None。ADR 0007。
*> host_artifact_kind*
## 模块源码
入口 `.mq.md` 全文(供 document-as-prompt)。未设置时为空文本。
+2 -2
View File
@@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
+ `键`=None
+ `行`=None
在入口文件中写入 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
@@ -51,6 +51,6 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
## 扫描路径
+ `路径`
扫描任意文件中的 `<!-- marqdo-out … -->` 槽(工作簿观察)。
扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察)。
*> host_writeback_scan_path path=`路径`*
+497
View File
@@ -0,0 +1,497 @@
//! Engineering Knowledge preflight / reuse (reads `.marqdo` projections).
//! Does not call host_* — consumes compiled knowledge graph artifacts.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
args.get(key)
.and_then(|v| v.as_str())
.ok_or_else(|| format!("missing string arg `{key}`"))
}
fn arg_f64(args: &Value, key: &str, default: f64) -> f64 {
match args.get(key) {
Some(Value::Number(n)) => n.as_f64().unwrap_or(default),
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn arg_usize(args: &Value, key: &str, default: usize) -> usize {
match args.get(key) {
Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as usize,
Some(Value::String(s)) => s.parse().unwrap_or(default),
_ => default,
}
}
fn char_bigram_tf(text: &str) -> HashMap<String, f64> {
let chars: Vec<char> = text.chars().filter(|c| !c.is_whitespace()).collect();
let mut m = HashMap::new();
if chars.is_empty() {
return m;
}
if chars.len() == 1 {
m.insert(chars[0].to_string(), 1.0);
return m;
}
for w in chars.windows(2) {
let key: String = w.iter().collect();
*m.entry(key).or_insert(0.0) += 1.0;
}
m
}
fn cosine_tf(a: &HashMap<String, f64>, b: &HashMap<String, f64>) -> f64 {
let mut na = 0.0;
let mut nb = 0.0;
for v in a.values() {
na += v * v;
}
for v in b.values() {
nb += v * v;
}
if na == 0.0 || nb == 0.0 {
return 0.0;
}
let mut dot = 0.0;
for (k, va) in a {
if let Some(vb) = b.get(k) {
dot += va * vb;
}
}
dot / (na.sqrt() * nb.sqrt())
}
fn resolve_marqdo_root(start: &str) -> PathBuf {
let mut cur = PathBuf::from(start);
if cur.is_file() {
if let Some(p) = cur.parent() {
cur = p.to_path_buf();
}
}
for _ in 0..8 {
let cand = cur.join(".marqdo");
if cand.join("engineering.yaml").exists() || cand.join("graph/graph.json").exists() {
return cand;
}
if !cur.pop() {
break;
}
}
PathBuf::from(start).join(".marqdo")
}
#[derive(Clone)]
struct CapHit {
id: String,
name: String,
score: f64,
implemented_by: Vec<String>,
}
fn load_capabilities(marqdo: &Path) -> Vec<(String, String, Vec<String>, String)> {
// returns (id, name, implemented_by, material)
let mut out = Vec::new();
let eng = marqdo.join("engineering.yaml");
if let Ok(raw) = fs::read_to_string(&eng) {
let mut cur_id = String::new();
let mut cur_name = String::new();
let mut impls = Vec::new();
let mut in_caps = false;
let mut in_impl = false;
for line in raw.lines() {
let t = line.trim_end();
if t.trim() == "capabilities:" {
in_caps = true;
continue;
}
if in_caps && !line.starts_with(' ') && !line.starts_with('\t') && !t.trim().is_empty()
{
if t.trim() == "knowledge:" {
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls.clone(),
format!("{cur_name} {cur_id}"),
));
}
break;
}
}
if !in_caps {
continue;
}
let trimmed = t.trim();
if let Some(rest) = trimmed.strip_prefix("- id:") {
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls.clone(),
format!("{cur_name} {cur_id}"),
));
}
cur_id = rest.trim().trim_matches('"').to_string();
cur_name.clear();
impls.clear();
in_impl = false;
} else if let Some(rest) = trimmed.strip_prefix("name:") {
cur_name = rest.trim().trim_matches('"').to_string();
} else if trimmed == "implemented_by:" {
in_impl = true;
} else if in_impl {
if let Some(rest) = trimmed.strip_prefix("- ") {
impls.push(rest.trim().trim_matches('"').to_string());
} else if !trimmed.is_empty() && !line.starts_with(' ') {
in_impl = false;
}
}
}
if !cur_id.is_empty() {
out.push((
cur_id.clone(),
cur_name.clone(),
impls,
format!("{cur_name} {cur_id}"),
));
}
}
// Also scan catalog/capabilities/*.md
let cap_dir = marqdo.join("catalog/capabilities");
if let Ok(rd) = fs::read_dir(cap_dir) {
for ent in rd.flatten() {
let p = ent.path();
if !p
.file_name()
.and_then(|s| s.to_str())
.map(|s| s.ends_with(".md"))
.unwrap_or(false)
{
continue;
}
let Ok(src) = fs::read_to_string(&p) else {
continue;
};
let id = fm_field(&src, "id").unwrap_or_else(|| {
p.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("cap")
.to_string()
});
let name = fm_field(&src, "name").unwrap_or_else(|| id.clone());
if out.iter().any(|(i, _, _, _)| i == &id) {
continue;
}
out.push((id.clone(), name.clone(), Vec::new(), format!("{name} {id} {src}")));
}
}
out
}
fn fm_field(source: &str, key: &str) -> Option<String> {
let prefix = format!("{key}:");
for line in source.lines() {
let t = line.trim();
if t == "---" {
continue;
}
if let Some(rest) = t.strip_prefix(&prefix) {
return Some(rest.trim().trim_matches('"').to_string());
}
}
None
}
fn load_knowledge_titles(marqdo: &Path, kind_subdir: &str) -> Vec<(String, String)> {
let dir = marqdo.join("knowledge").join(kind_subdir);
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(dir) else {
return out;
};
for ent in rd.flatten() {
let p = ent.path();
let Ok(src) = fs::read_to_string(&p) else {
continue;
};
let id = fm_field(&src, "id").unwrap_or_else(|| {
p.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("k")
.to_string()
});
let title = fm_field(&src, "title").unwrap_or_else(|| id.clone());
out.push((id, title));
}
out
}
fn rank_caps(task: &str, caps: &[(String, String, Vec<String>, String)]) -> Vec<CapHit> {
let qv = char_bigram_tf(task);
let mut hits = Vec::new();
for (id, name, impls, material) in caps {
let mut score = cosine_tf(&qv, &char_bigram_tf(material));
if name.to_ascii_lowercase().contains(&task.to_ascii_lowercase())
|| task
.to_ascii_lowercase()
.split_whitespace()
.any(|t| t.len() > 2 && name.to_ascii_lowercase().contains(t))
{
score = (score + 0.35).min(1.0);
}
if score > 0.12 {
hits.push(CapHit {
id: id.clone(),
name: name.clone(),
score,
implemented_by: impls.clone(),
});
}
}
hits.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
});
hits
}
fn relevant_knowledge(task: &str, items: &[(String, String)], cap_names: &[String]) -> Vec<String> {
let task_l = task.to_ascii_lowercase();
items
.iter()
.filter(|(id, title)| {
let m = format!("{id} {title}").to_ascii_lowercase();
task_l.split_whitespace().any(|t| t.len() > 3 && m.contains(t))
|| cap_names.iter().any(|c| m.contains(&c.to_ascii_lowercase()))
})
.map(|(id, title)| format!("{title} ({id})"))
.collect()
}
/// `agent_eng_preflight` — Engineering First Information gate.
pub fn eng_preflight(args: &Value) -> Result<Value, String> {
let task = arg_text(args, "task").or_else(|_| arg_text(args, "goal"))?;
let root = args
.get("root")
.and_then(|v| v.as_str())
.unwrap_or(".");
let marqdo = args
.get("marqdo_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(|| resolve_marqdo_root(root));
if !marqdo.join("engineering.yaml").exists() && !marqdo.join("graph/graph.json").exists() {
return Ok(json!({
"status": "missing_knowledge",
"create_allowed": false,
"decision": "CREATE",
"error": "run `marqdo knowledge` first",
"existing": [],
"recommended": [],
}));
}
let reuse_threshold = arg_f64(args, "reuse_threshold", 0.72);
let adapt_threshold = arg_f64(args, "adapt_threshold", 0.45);
let allow_create_after = arg_usize(args, "allow_create_after", 2);
let min_candidates = arg_usize(args, "min_candidates", 3);
let caps = load_capabilities(&marqdo);
let ranked = rank_caps(task, &caps);
let existing: Vec<String> = ranked.iter().take(8).map(|c| c.name.clone()).collect();
let cap_names = existing.clone();
let constraints = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "constraints"),
&cap_names,
);
let decisions = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "decisions"),
&cap_names,
);
let failures = relevant_knowledge(
task,
&load_knowledge_titles(&marqdo, "failures"),
&cap_names,
);
let best = ranked.first();
let best_score = best.map(|c| c.score).unwrap_or(0.0);
let analyzed = ranked.len().max(1).min(min_candidates.max(allow_create_after));
let (decision, create_allowed, recommended, reason) = if best_score >= reuse_threshold {
let b = best.unwrap();
(
"REUSE",
false,
vec![format!("REUSE {}", b.name)],
vec![
"score meets REUSE threshold".into(),
"same capability semantics".into(),
],
)
} else if best_score >= adapt_threshold {
let b = best.unwrap();
(
"ADAPT",
false,
vec![format!("ADAPT {}", b.name)],
vec!["near match — wrap/compose/extend".into()],
)
} else if analyzed >= allow_create_after {
(
"CREATE",
true,
vec!["CREATE new capability".into()],
vec!["no existing capability satisfies constraints".into()],
)
} else {
(
"CREATE",
false,
vec![],
vec![format!(
"insufficient candidates ({analyzed} < {allow_create_after})"
)],
)
};
// Write context pack
let contexts = marqdo.join("agent/contexts");
let _ = fs::create_dir_all(&contexts);
let mut h: u64 = 5381;
for b in task.as_bytes() {
h = h.wrapping_mul(33).wrapping_add(u64::from(*b));
}
let tid = format!("{h:016x}")[..12].to_string();
let ctx_path = contexts.join(format!("task-{tid}.mq.md"));
let pack = format!(
"---\ntype: Marqdo Context Pack\ntitle: Engineering Context\ndecision: {decision}\ncreate_allowed: {create_allowed}\n---\n\n# Engineering Context\n\n## Task\n\n{task}\n\n## Existing Capabilities\n\n{existing}\n\n## Recommended Reuse\n\n{recommended}\n",
existing = existing
.iter()
.map(|e| format!("- {e}"))
.collect::<Vec<_>>()
.join("\n"),
recommended = recommended
.iter()
.enumerate()
.map(|(i, r)| format!("{}. {r}", i + 1))
.collect::<Vec<_>>()
.join("\n"),
);
let _ = fs::write(&ctx_path, pack);
let status = if create_allowed {
"ready_create"
} else if decision == "REUSE" || decision == "ADAPT" {
"ready"
} else if decision == "CREATE" && !create_allowed {
"blocked"
} else {
"ready"
};
Ok(json!({
"status": status,
"intent": { "capability": best.map(|c| c.name.clone()).unwrap_or_else(|| task.to_string()) },
"existing": existing,
"constraints": constraints,
"decisions": decisions,
"failures": failures,
"recommended": recommended,
"create_allowed": create_allowed,
"decision": decision,
"confidence": best_score,
"reason": reason,
"context_path": ctx_path.display().to_string(),
"candidates": ranked.iter().take(8).map(|c| json!({
"id": c.id,
"name": c.name,
"score": c.score,
"implemented_by": c.implemented_by,
})).collect::<Vec<_>>(),
}))
}
/// `agent_eng_reuse` — alias of preflight focused on decision payload.
pub fn eng_reuse(args: &Value) -> Result<Value, String> {
let mut pf = eng_preflight(args)?;
if let Some(obj) = pf.as_object_mut() {
obj.insert(
"protocol".into(),
json!("REUSE|ADAPT|CREATE"),
);
}
Ok(pf)
}
/// `agent_eng_record` — append reuse metrics under `.marqdo/agent/episodes`.
pub fn eng_record(args: &Value) -> Result<Value, String> {
let decision = arg_text(args, "decision")?;
let root = args
.get("root")
.and_then(|v| v.as_str())
.unwrap_or(".");
let marqdo = args
.get("marqdo_dir")
.and_then(|v| v.as_str())
.map(PathBuf::from)
.unwrap_or_else(|| resolve_marqdo_root(root));
let duplicated = matches!(args.get("duplicated"), Some(Value::Bool(true)));
let path = marqdo.join("agent/episodes/reuse_metrics.json");
if let Some(p) = path.parent() {
let _ = fs::create_dir_all(p);
}
let mut m = if let Ok(raw) = fs::read_to_string(&path) {
serde_json::from_str::<Value>(&raw).unwrap_or(json!({}))
} else {
json!({})
};
let get_u = |v: &Value, k: &str| v.get(k).and_then(|x| x.as_u64()).unwrap_or(0);
let mut reused = get_u(&m, "reused");
let mut adapted = get_u(&m, "adapted");
let mut created = get_u(&m, "created");
let mut dups = get_u(&m, "duplicated");
match decision.to_ascii_uppercase().as_str() {
"REUSE" => reused += 1,
"ADAPT" => adapted += 1,
"CREATE" => {
created += 1;
if duplicated {
dups += 1;
}
}
_ => {}
}
m = json!({
"generated_functions": get_u(&m, "generated_functions") + 1,
"reused": reused,
"adapted": adapted,
"created": created,
"duplicated": dups,
});
let gen = m["generated_functions"].as_u64().unwrap_or(1) as f64;
m["reuse_ratio"] = json!(reused as f64 / gen);
m["adapt_ratio"] = json!(adapted as f64 / gen);
m["novel_ratio"] = json!(created as f64 / gen);
m["duplication_rate"] = json!(if created == 0 {
0.0
} else {
dups as f64 / created as f64
});
fs::write(&path, serde_json::to_string_pretty(&m).unwrap_or_default())
.map_err(|e| e.to_string())?;
Ok(m)
}
+170 -1
View File
@@ -511,11 +511,25 @@ fn write_skill_concept(
quality: i64,
hits: i64,
now: &str,
meta: &SkillMeta,
) -> Result<(), String> {
if let Some(p) = path.parent() {
fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?;
}
let title: String = goal.chars().take(48).collect();
let mut extra = String::new();
if let Some(ref s) = meta.applies_when {
extra.push_str(&format!("applies_when: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.fixtures {
extra.push_str(&format!("fixtures: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.sandbox_profile {
extra.push_str(&format!("sandbox_profile: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.proof {
extra.push_str(&format!("proof: {}\n", yaml_escape(s)));
}
let body = format!(
r#"---
type: Marqdo Agent Skill
@@ -526,7 +540,7 @@ status: {status}
llm_free: {llm_free}
quality: {quality}
hits: {hits}
generated:
{extra}generated:
by: marqdo-agent/plan
at: {now}
verified:
@@ -545,11 +559,29 @@ Prefer spawning `resource` over re-planning.
llm_free = if llm_free { "true" } else { "false" },
quality = quality,
hits = hits,
extra = extra,
now = now,
);
fs::write(path, body).map_err(|e| format!("write skill: {e}"))
}
#[derive(Default)]
struct SkillMeta {
applies_when: Option<String>,
fixtures: Option<String>,
sandbox_profile: Option<String>,
proof: Option<String>,
}
fn skill_meta_from_src(src: &str) -> SkillMeta {
SkillMeta {
applies_when: extract_fm_field(src, "applies_when"),
fixtures: extract_fm_field(src, "fixtures"),
sandbox_profile: extract_fm_field(src, "sandbox_profile"),
proof: extract_fm_field(src, "proof"),
}
}
fn refresh_index(root: &Path, slug: &str, goal: &str) -> Result<(), String> {
let index = root.join("index.md");
let line = format!(
@@ -585,6 +617,10 @@ fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
.ok_or_else(|| format!("missing text `{key}`"))
}
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty())
}
fn opt_tools(args: &Value) -> Option<&Value> {
args.get("tools").filter(|t| !t.is_null())
}
@@ -1107,6 +1143,54 @@ pub fn kb_record_hit(args: &Value) -> Result<Value, String> {
}))
}
/// Run workbook (or FM `proof:` / `fixtures:` path) inside CoW sandbox; discard after.
/// O2: llm_free promote requires this proof to succeed (unless `require_proof=false`).
fn sandbox_proof(workbook: &Path, proof_rel: Option<&str>) -> Result<(bool, String), String> {
let root = workbook
.parent()
.ok_or_else(|| "sandbox_proof: workbook has no parent".to_string())?;
// Always pass an absolute root so host `sandbox_open` does not re-join cwd.
let root_abs = if root.is_absolute() {
root.to_path_buf()
} else {
fs::canonicalize(root).unwrap_or_else(|_| {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(root)
})
};
let root_abs = fs::canonicalize(&root_abs).unwrap_or(root_abs);
let default_name = workbook
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| "sandbox_proof: bad workbook name".to_string())?;
let path = proof_rel.unwrap_or(default_name);
let open = crate::host_query_json_args(
"sandbox_open",
&json!({ "root": root_abs.to_string_lossy() }),
)?;
let id = open
.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_proof: open missing id".to_string())?
.to_string();
let run = crate::host_query_json_args("sandbox_run", &json!({ "id": id, "path": path }));
let _ = crate::host_query_json_args("sandbox_discard", &json!({ "id": id }));
match run {
Ok(r) => {
let ok = r.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
let detail = r
.get("stderr")
.and_then(|v| v.as_str())
.or_else(|| r.get("stdout").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
Ok((ok, detail))
}
Err(e) => Ok((false, e)),
}
}
pub fn kb_promote(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let goal = arg_text(args, "goal")?;
@@ -1119,6 +1203,26 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
let src_path = resolve_path(workbook);
let src = fs::read_to_string(&src_path)
.map_err(|e| format!("kb_promote read workbook: {e}"))?;
let require_proof = args
.get("require_proof")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let proof_rel = extract_fm_field(&src, "proof")
.or_else(|| extract_fm_field(&src, "fixtures"));
if require_proof {
let (ok, detail) = sandbox_proof(&src_path, proof_rel.as_deref())?;
if !ok {
return Ok(json!({
"promoted": false,
"reason": "sandbox_proof_failed",
"detail": detail,
"sig": sig,
"slug": slug,
"workbook": workbook,
"proof": proof_rel.unwrap_or_else(|| src_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_string()),
}));
}
}
let (llm_free, quality) = llm_free_score(&src);
let status = if llm_free { "stable" } else { "candidate" };
@@ -1168,6 +1272,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
&now,
&extra_aliases,
)?;
let meta = skill_meta_from_src(&src);
write_skill_concept(
&skill_path,
&sig,
@@ -1178,6 +1283,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
quality,
prev_hits,
&now,
&meta,
)?;
refresh_index(&root, &slug, &goal_n)?;
@@ -1190,6 +1296,69 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
"quality": quality,
"status": status,
"hits": prev_hits,
"proof_ok": true,
"applies_when": meta.applies_when,
"fixtures": meta.fixtures,
"sandbox_profile": meta.sandbox_profile,
}))
}
/// O5: mark a skill concept as `status: quarantine` and keep fixtures path in FM.
pub fn kb_quarantine(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let slug = arg_text(args, "slug")?;
let reason = opt_text(args, "reason").unwrap_or("sandbox_or_harness_failed");
let root = resolve_path(kb);
let skill_path = root.join("concepts/skills").join(format!("{slug}.md"));
if !skill_path.is_file() {
return Ok(json!({
"ok": false,
"reason": "skill_not_found",
"slug": slug,
"path": skill_path.to_string_lossy(),
}));
}
let src = fs::read_to_string(&skill_path)
.map_err(|e| format!("kb_quarantine read: {e}"))?;
let mut lines: Vec<String> = Vec::new();
let mut saw_status = false;
let mut in_fm = false;
for line in src.lines() {
let t = line.trim();
if t == "---" {
if !in_fm {
in_fm = true;
lines.push(line.to_string());
continue;
} else {
if !saw_status {
lines.push("status: quarantine".to_string());
}
lines.push(format!("quarantine_reason: {}", yaml_escape(reason)));
in_fm = false;
lines.push(line.to_string());
continue;
}
}
if in_fm && t.starts_with("status:") {
lines.push("status: quarantine".to_string());
saw_status = true;
continue;
}
if in_fm && t.starts_with("llm_free:") {
lines.push("llm_free: false".to_string());
continue;
}
lines.push(line.to_string());
}
let body = lines.join("\n") + "\n";
fs::write(&skill_path, body).map_err(|e| format!("kb_quarantine write: {e}"))?;
Ok(json!({
"ok": true,
"slug": slug,
"status": "quarantine",
"reason": reason,
"path": skill_path.to_string_lossy(),
}))
}
+64
View File
@@ -1,12 +1,14 @@
//! Agent plugin (C ABI v2): layout helpers + session bag + context via host_query + agent-kb + v2 memory + adaptive route.
mod corpus;
mod eng;
mod kb;
mod mcp_client;
mod mcp_server;
mod memory;
mod resume;
mod route;
mod sandbox;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
@@ -899,6 +901,7 @@ kb_ffi!(agent_corpus_search, corpus::corpus_search, "agent_corpus_search");
kb_ffi!(agent_mcp_fixture, corpus::mcp_fixture, "agent_mcp_fixture");
kb_ffi!(agent_kb_add_alias, kb::kb_add_alias, "agent_kb_add_alias");
kb_ffi!(agent_kb_promote, kb::kb_promote, "agent_kb_promote");
kb_ffi!(agent_kb_quarantine, kb::kb_quarantine, "agent_kb_quarantine");
kb_ffi!(agent_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit");
kb_ffi!(
agent_workbook_solidify,
@@ -930,6 +933,9 @@ kb_ffi!(agent_resume_save, resume::resume_save, "agent_resume_save");
kb_ffi!(agent_resume_load, resume::resume_load, "agent_resume_load");
kb_ffi!(agent_resume_clear, resume::resume_clear, "agent_resume_clear");
kb_ffi!(agent_resume_list, resume::resume_list, "agent_resume_list");
kb_ffi!(agent_eng_preflight, eng::eng_preflight, "agent_eng_preflight");
kb_ffi!(agent_eng_reuse, eng::eng_reuse, "agent_eng_reuse");
kb_ffi!(agent_eng_record, eng::eng_record, "agent_eng_record");
#[no_mangle]
pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 {
@@ -1062,6 +1068,15 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{
return 1;
}
if register(
host,
"agent_kb_quarantine",
"kb_dir,slug",
agent_kb_quarantine,
) != 0
{
return 1;
}
if register(host, "agent_kb_record_hit", "kb_dir,goal", agent_kb_record_hit) != 0 {
return 1;
}
@@ -1155,6 +1170,55 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{
return 1;
}
if register(
host,
"agent_eng_preflight",
"task",
agent_eng_preflight,
) != 0
{
return 1;
}
if register(host, "agent_eng_reuse", "task", agent_eng_reuse) != 0 {
return 1;
}
if register(
host,
"agent_eng_record",
"decision",
agent_eng_record,
) != 0
{
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
}
+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),
}))?;
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!({
"mode": "unknown",
"match": null,
"skill": null,
"resource": null,
"slug": null,
"status": null,
"llm_free": false,
"score": null,
"confidence": 0.0,
}));
}
@@ -1078,6 +1085,25 @@ pub fn resolve_task(args: &Value) -> Result<Value, String> {
mod tests {
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]
fn record_and_cluster_and_compile() {
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");
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more