Compare commits

..
4 Commits
Author SHA1 Message Date
cflmyandCursor 1730f26fc7 release: v2.2.0 call one function in any .mq.md
The same page is the document, the knowledge and the program. marqdo call runs that function with arguments, so reuse, tools and tests do not need a second skill system.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 09:07:23 +08:00
cflmyandCursor 4018e9928a fix(ai): stream usage events and accept free-form plan replies
Request stream_options.include_usage, emit usage SSE events for collect_usage,
propagate plan tokens through run, and treat unknown prose decisions as DONE.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 11:56:51 +08:00
cflmyandCursor 628e3b6e5d chore(ppa): bump 2.1.5 to 1ppa2 after Launchpad no-log failure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 17:38:04 +08:00
cflmyandCursor 5c6c612edd fix(test): coerce MARQDO_SITE_PORT for MR-01 isolated execute
Env port strings must be json.parsed to int; pin main site to 18220 so
inherited MARQDO_SITE_PORT cannot steal the fixture bind.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 16:05:24 +08:00
47 changed files with 2074 additions and 138 deletions

No files matched your search

+30 -12
View File
@@ -21,7 +21,7 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
These rules are the **current default**. Do **not** teach Classic `[key](map)` index or “bold is return of print”. Classic migration only: [migration-classic.md](migration-classic.md).
1. **File suffix** `.mq.md`. Print with `> print text=…` / `> 打印 内容=…` — never use `**…**` to print.
2. **`**…**` = code / return expression.** `*…*` = statement (bind / expr). Closing markers touch the last token (no trailing space).
2. **`**…**` = statement** (assign / call / expression). `*…*` = return. Closing markers touch the last token (no trailing space).
3. **`[描述](payload)` = occlusion:** `[]` is prose (never executed); `()` is the only executed part. Empty `()` → `None` stub.
4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion.
5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code.
@@ -34,8 +34,8 @@ These rules are the **current default**. Do **not** teach Classic `[key](map)` i
| Marker | Meaning (v2.1) |
|--------|----------------|
| `#` / `##`+ | Object/type · function/method |
| `*…*` | Statement |
| `**…**` | Return / code expression |
| `**…**` | Statement (assign / call / expression) |
| `*…*` | Return |
| `[描述](payload)` | Occlusion step (payload executes) |
| `access(c, k)` | Collection read |
| `> fn …` | Call |
@@ -57,6 +57,24 @@ Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executabl
8. Browser: Marqdo on WASM + `lib/browser` tables; do not hand-write business JS.
## Call one function
```markdown
# 计算器
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
```
```
marqdo call calculator.mq.md 计算器.加法 a=2 b=3
```
prints `5`. The same command works on any `.mq.md`; the file does not need a special skill name.
## Minimal program
```markdown
@@ -96,13 +114,13 @@ 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
@@ -130,9 +148,9 @@ import:
# main
*xs = > text.split value="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).
@@ -191,8 +209,8 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea
**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin.
```markdown
*_ = > `qc`.draw kind="circuit" theme="dark"*
*_ = > `qc`.draw kind="probs" theme="light"*
**_ = > `qc`.draw kind="circuit" theme="dark"**
**_ = > `qc`.draw kind="probs" theme="light"**
```
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/).
@@ -223,8 +241,8 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
| `# main` then prose then code with no blank line | Blank line before code |
| `if x > 0:` | `1. `x` > 0` |
| `* > print text=hi *` | `> print text=hi` |
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
| `` *`a` = 1 * `` (trailing space + backticks) | `**a = 1**` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (italic is return, and bare text args) | `**xs = > text.split value="a,b" sep=","**` — statement; quote text literals |
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
+3
View File
@@ -126,6 +126,9 @@ jobs:
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **v2.2.0**:函数级调用 `marqdo call`——同一份 .mq.md 就是文档、知识和工具;Tree/Bytecode 执行被点名的函数;外部调用默认只跑纯函数
- **v2.2.0**: `marqdo call` runs one function in any .mq.md — the file is the document, the knowledge and the tool; Tree and Bytecode execute that function; external calls stay pure
- **v2.2.0 ext**:扩展包同步 2.2.0 / Ext pack 2.2.0
- **v2.1.5**:Agent 可靠工作台——ResourceView / ToolSpec / CheckpointV2 / EffectLedger · EKC ir.json 暖机 · Web 短读槽隔离
- **v2.1.5**: Agent reliability workbench — ResourceView / ToolSpec / CheckpointV2 / EffectLedger, EKC ir.json warm-load, web short/read lane isolation
- **v2.1.5 ext**:扩展包同步 2.1.5 / Ext pack 2.1.5
+37
View File
@@ -8,6 +8,43 @@
### Changed
## v2.2.0 — 2026-10-30
### Highlights
**函数级调用 `marqdo call`**:同一份 `.mq.md` 已经是文档、知识和程序。这一版补上从外部调用其中某个函数的入口。人继续读这一页;开发者、测试和 Agent 用同一条命令传入参数并执行。知识复用、把函数当工具、逐个函数做测试、改完再跑,都是这一入口的用法,不是另一套 Skill 系统。CLI · wasm · ext **2.2.0**。
```bash
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
# 5
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 --json
```
**作用**:最小可执行单位从「整份文件」扩展到「文件里的一个函数」。不必为了试一个函数再写 `# main`、打印和包装程序。
**价值**:说明和实现仍在同一页。Agent 读函数旁边的叙述,定位函数,传入参数,得到可检查的结果。正式发布和权限仍走已有的项目验证;`call` 默认不开放写文件、进程、网络和插件。
说明页:[public/features/22-函数调用.mq.md](public/features/22-函数调用.mq.md) · [public/features/22-call.mq.md](public/features/22-call.mq.md)
**核心表面 Δ(Core surface Δ)**:**无增删**(仍 19 个构造)——新增的是 CLI 入口,不新增 Markdown 标记。`**…**` 仍是语句,`*…*` 仍是返回。
### Added
- **`marqdo call <文件.mq.md> <函数> [名字=值 ...]`**:加载该文件及其 import,按显示路径、SymbolId 或唯一短名定位函数,用现有签名和契约绑定参数,再用现有运行时执行。
- **`--json`**:成功 `{"ok":true,"result":...}`,失败 `{"ok":false,"error":...}`,错误带诊断 `code`。`--backend tree|bytecode` 与 `marqdo run` 相同;指定函数时两个后端都不会改去跑 `# main`。
- **默认纯函数**:效应含写入、网络、进程或插件时,执行前返回 `artifact.effect_denied`,副作用不会发生。
- **参照文档** `examples/calculator.mq.md`,以及用户说明页 `public/features/22-*`。
### Fixed
- 官方语法说明与 Agent 语法卡的标记极性与解析器对齐:粗体是语句,斜体是返回。同步测试会实际运行说明里的调用示例。
- Bytecode 的 `marqdo run --call-lib-path` 执行被点名的导入函数,不再忽略该参数去跑入口。
- 隔离运行时冒烟测试补上 `InvokeContext.fs_root`,`--tests` 可以编过。
### Changed
- CLI / wasm / `ext/VERSION` **同步 2.2.0**。扩展包版本号对齐;这一版的新能力在 CLI。
## v2.1.5 — 2026-10-27
### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "2.1.5"
version = "2.2.0"
dependencies = [
"anyhow",
"assert_cmd",
@@ -611,7 +611,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "2.1.5"
version = "2.2.0"
dependencies = [
"marqdo",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "2.1.5"
version = "2.2.0"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+11 -5
View File
@@ -4,6 +4,8 @@
Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,既是给人读的文稿,也是给机器跑的程序。写文档的过程就是在写可执行逻辑——大型项目里,说明、示例与实现不再分叉成三份真相。它不是「又一个 Markdown 编程语言」,而是**文档原生的编程运行时(Document-native runtime)**——一门关于**可执行知识(Executable Knowledge)**的语言。
v2.2.0 起,`marqdo call` 可以直接调用这份文件里的一个函数。读的是同一页说明,跑的是同一个实现。知识因此可以当工具用,测试也不必再包一层 `# main`。
欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。
**链接语法**:[doc/design/link-syntax.md](doc/design/link-syntax.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)
@@ -29,6 +31,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
| 真正的核心优势 | 说明 |
|------|------|
| **知识-代码一致性**<br>Knowledge-Code Coherence | 说明、数据、示例与实现**同一份源文件**:文档里的表格就是程序的数据,文档里的调用就是真实执行。「文档过期」不再是悄悄漂移,而是可被机器发现的**知识不一致**——知识陈述本身可以被测试。 |
| **函数即工具**<br>`marqdo call` | 最小可执行单位是文件中的函数,不只是整份文件。人阅读函数旁边的叙述;开发者、测试和 Agent 用 `marqdo call 文件 函数 名字=值` 执行它。知识复用、工具调用、函数级测试和局部改进是同一入口的四种用法。 |
| **默认安全,AI 友好** | 无标记文字默认是叙述(注释),只有显式标记才进入执行。AI 自由发挥**不会污染**文档与代码的边界——这比「自然语言编程」安全得多,是 AI 原生语言的重要前提。 |
| **multi-view artifact**<br>`.mq.md` 双后缀即开放接口 | `.mq` 告诉解释器「可执行」,`.md` 告诉整个 Markdown 生态「仍是文档」。GitHub 直接读、VS Code 直接改、搜索引擎直接索引、LLM 直接理解、Marqdo 直接运行。**Marqdo 不占有知识,只是给 Markdown 增加执行语义。** |
| **表格即数据结构** | 程序的数据结构直接就是文档的数据结构:单列竖表 → `List`;横表(1 数据行)→ `Map`;横表(多数据行)→ `Map` of `List`(列向聚合);首列写 `@` / `行` / `row` → 行向记录 `List` of `Map`。取元使用 `access(集合, "键")`,链接 `[描述](表达式)` 只承载叙述与执行体。这是 literate programming 的下一步。 |
@@ -281,8 +284,9 @@ marqdo catalog public -o .marqdo
---
## 现状(v2.1.5)
## 现状(v2.2.0)
- **函数级调用(v2.2.0)**:`marqdo call <文件.mq.md> <函数> 名字=值`。同一份文档给人读,也按函数执行;Tree 与 Bytecode 都跑被点名的函数,不回退到 `# main`。默认只执行纯函数。`--json` 给 Agent 读取结果或诊断。说明与价值见 [22-函数调用](public/features/22-函数调用.mq.md)。示例:`marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3` → `5`。扩展包同步 **2.2.0**
- **Agent 可靠工作台(v2.1.5)**:ResourceView(JSON/CSV/PDF/image)· ToolSpec 授权先于调用 · CheckpointV2 / EffectLedger / ContextPackV2 · EKC `ir.json` 暖机与 `--refresh` · Web 短读/控制与 execute 槽隔离;扩展包同步 **2.1.5**
- **默认隔离 HTTP execute(v2.1.4 · ADR 0009)**:`execute` / `sse-live` / `stream:true` → Supervisor worker 池(`--call-lib-path`);父进程不再占 `INVOKE_LOCK`;`/_runtime/*`;`runtime.isolated_execution=1`;MR-01 金样例
- **知识工作台运行时(v2.1.3)**:ModelSelection / RunContext / usage null≠0 · `view document` 只读嵌入 · LLM selection/messages/cancel · agent.step selection e2e · live smoke(设计 Partial:原生适配器 unavailable)
@@ -325,7 +329,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(v2.1.5)
### 如何使用最新 Marqdo(v2.2.0)
**安装解释器(任选其一)**
@@ -340,14 +344,16 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v2.1.5 # 或留在 main
git checkout v2.2.0 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
marqdo version --check
# 2) 跑解释器 / 文档站 / catalog
# 2) 跑整个文件,或只调用其中一个函数
marqdo run tests/structure/hello.mq.md
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3 --json
marqdo run tests/structure/hello.mq.md --backend bytecode
marqdo view public --no-open
marqdo debug public --no-open
@@ -379,7 +385,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/v2.1.5
# https://github.com/cflmy/marqdo/releases/tag/v2.2.0
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "2.1.5"
version = "2.2.0"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+15
View File
@@ -1,3 +1,18 @@
marqdo (2.2.0-1ppa1) noble; urgency=medium
* Marqdo 2.2.0: marqdo call runs one named function in any .mq.md.
The same file stays the document, the knowledge and the program.
Tree and bytecode both execute that function. External calls stay
pure: write, process, network and plugin stay off by default.
-- Marqdo Maintainers <noreply@marqdo.com> Fri, 30 Oct 2026 09:20:00 +0800
marqdo (2.1.5-1ppa2) noble; urgency=medium
* Rebuild 2.1.5 against Launchpad (previous 1ppa1 failed with no build log).
-- Marqdo Maintainers <noreply@marqdo.com> Tue, 27 Oct 2026 09:35:49 +0000
marqdo (2.1.5-1ppa1) noble; urgency=medium
* Marqdo 2.1.5: agent reliability workbench — ResourceView / ToolSpec /
+374
View File
@@ -0,0 +1,374 @@
请你重新阅读marqdo的官方库,掌握marqdo的最新进度。在我对marqdo项目的仔细审视之下我发现有一点没有闭环,我终于找到了,考虑现在智能体开发最常用的SKILL,这是一个markdown文件写明了智能体该干什么,我想要更推荐一步,因为marqdo使用markdown语法,支持叙述和代码相互混合,这就使得marqdo满足这样一个条件,当分章节的SKILL撰写下来,只要经过调整就能成为一份marqdo代码其中包含若干函数,我打算开发新的CLI命令marqdo > 函数名 函数参数或者marqdo call 函数名 函数参数 此时SKILL的不同章节就变成了不同的函数,智能体就真正的成为了将知识复现的作用,这让代码即文档、文档即知识,知识即可执行推进了一步变成了知识即工具,真正发挥了marqdo的优势,同样这样的执行还以为着智能体能够自行改进SKILL并接受确定的问题后修改而不会出错,这让自我进化的智能体成为了具备理论支撑和清晰边界的可能
# Marqdo 从“可执行知识”走向“知识即工具”:最新仓库审查与架构建议
我认为你这次找到了 Marqdo 一个非常重要、而且比单纯增加 `marqdo call` 命令更深层的突破口。
你实际上提出了一个新的统一关系:
> SKILL 是人和 AI 都能阅读的操作知识;Marqdo 可以让其中具有确定性执行语义的章节,直接成为可调用的工具。
这样,Agent 的职责就有机会从“阅读说明、理解步骤、临时生成实现”,转向“定位已有能力、填入参数、执行和验证结果”。
这与 Marqdo 原来的三句话是连续的,不需要推翻原来的定位:
代码即文档 → 文档即知识库 → 知识即可执行 → 知识即可作为工具使用。
不过我建议把“知识即工具”视为可执行知识的对外使用形态,而不是再创造一套与语言、知识库平行的 Skill 运行系统。
## 一、重新检查仓库后的最新情况
本次核对的是 [cflmy/marqdo](https://github.com/cflmy/marqdo?utm_source=chatgpt.com) 的 `main` 分支,HEAD 为 `4018e992`,`Cargo.toml` 版本为 2.1.5。最近的 v2.1.5 版本记录日期是 2026 年 10 月 27 日。
与我们之前讨论 v2.0.0 时相比,项目已经完成了不少与你的构想直接相关的基础建设。
| 相关能力 | 最新仓库证据 | 判断 |
| --------------------- | ---------------------------------------------------------------- | -------- |
| 跨文档确定性函数绑定 | `BoundCall`、`SymbolId`,Tree/Bytecode 双后端测试 | 已有核心基础 |
| 已编译知识的执行复用 | MLSP `artifact.bind`、`artifact.execute`、`artifact.reuse_execute` | 已有子集 |
| Agent 复用已有函数 | `agent_eng_bind_execute`、发布门禁 | 已有子集 |
| 指定函数执行 | `marqdo run --call-lib-path`、JSON 参数、隔离 worker | 已有底层入口 |
| 智能体工具规范 | `ToolSpecV1`、效应分类、权限检查与恢复设计 | 已有框架基础 |
| 章节式 SKILL 自动成为 CLI 工具 | 目前没有独立的 `marqdo call` 或 Skill 编译命令 | 待开发 |
| SKILL 自修改、自动测试和受控发布 | 已有局部修改、验证与沙盒组件 | 尚未形成完整闭环 |
因此,现在不是重新开发一个 Skill 执行器,而是将已存在的 Marqdo 函数、知识制品、工具协议和 Agent 机制统一起来。
还有一个与你的新构想直接相关的问题值得先修复:
最新官方 `skills/marqdo/SKILL.md` 的核心语法说明,与仓库中的现行解析器、v0.3 语法规范和可执行测试存在冲突。
目前解析器与测试使用的是:
- `**…**`:代码、赋值、调用等语句;
- `*…*`:返回值。
但官方 Skill 顶部却把两者反过来描述。这不是小的文档笔误:如果 Agent 按照错误规则自我修改 Skill,就可能产生与实际运行时不一致的程序。
这个真实存在的不一致,恰好证明了你所说的闭环为什么重要——SKILL 不能仅靠自然语言说明自己的正确性,它需要由语言编译器和实际测试提供独立验证。
## 二、你真正提出的是一种新的 Skill 体系
我建议把它暂时命名为 Executable Skill(可执行技能)。
它不应被理解为“给 Markdown Skill 增加一点代码”,而应当满足一个更严格的定义:
> Executable Skill 是一份以 Markdown 为人类可读接口、以 Marqdo 函数为确定性执行单元、以编译后的语义制品为工具身份、能够由 Agent 发现、调用、验证和改进的技能文档。
传统 Skill 与你的目标之间,存在一个非常重要的区别。
| 维度 | 普通 Markdown Skill | Marqdo Executable Skill |
| ---- | ----------------------- | ----------------------- |
| 技能说明 | 自然语言 | 自然语言 |
| 操作步骤 | Agent 阅读后自行实施 | 可以绑定已有 Marqdo 函数 |
| 函数接口 | 通常需要额外编写工具代码 | 从 `.mq.md` 的函数和契约生成 |
| 执行 | 依赖 Agent 选择工具、生成代码或操作软件 | 对已实现的步骤直接执行 |
| 输出验证 | 往往需要单独建立 | 可连接编译器、契约和测试 |
| 改进 | 编辑说明或脚本 | 编辑同源的知识与实现,验证后发布 |
| 可追踪性 | 主要依赖工具日志 | 可关联 SymbolId、源码、版本和执行结果 |
但不是每个 Skill 章节都应该自动变成可执行函数。
比如“适用场景”“注意事项”“禁止操作”是知识或约束;“检查订单”“生成报价”“汇总报告”才可能成为可调用能力。编译器应区分文档章节与可执行章节,不能把所有二级标题不加判断地暴露成工具。
### 这实际上使 Agent 的结构发生变化
SKILL.md
目标 · 流程 · 函数 · 契约 · 示例 · 约束
Marqdo Skill Compiler
章节解析 · 符号绑定 · 类型检查 · 效应分析
Knowledge View
Agent 阅读技能与限制
Tool Registry
Agent 调用已编译函数
Agent:选择、组合、执行、观察与改进
由语言运行时执行确定性部分,由模型处理非确定性判断
特别值得注意的是:这不仅是执行接口的统一,还是知识交付接口的统一。
同一份 Skill 能够投影成可读说明、CLI 函数、Agent Tool Schema、MCP 工具描述,以及知识库中的能力节点。实现这些投影的系统仍是同一个 Marqdo 编译器。
## 三、CLI 应采用 `marqdo call`,不要采用 `marqdo >`
你提出了两个命令形式:
```
marqdo > 函数名 函数参数
marqdo call 函数名 函数参数
```
我明确建议采用第二种。
原因是 `>` 在 Bash、PowerShell、CMD 等 Shell 中已经具有输出重定向语义。`marqdo > xxx` 会被 Shell 先行解释,无法可靠地作为传递给 Marqdo 的函数调用语法。
推荐设计为:
```
# 按函数名调用
marqdo call "订单计算.商品小计" \
--skill ./skills/order-calculator \
--arg 单价=30 \
--arg 数量=2
# 结构化调用,供 Agent 使用
marqdo call "订单计算.商品小计" \
--skill ./skills/order-calculator \
--args-json inputs.json \
--output json \
--policy pure
```
上述是建议新增的 CLI 接口,不是 v2.1.5 已支持的命令。
我还建议在 CLI 层保留一个便利别名:`marqdo skill call`。它与 `marqdo call` 进入同一个 dispatcher,不应分别实现两套调用逻辑。
### 最小必要的 CLI 能力
| 命令 | 作用 |
| ---------------------------- | ----------------------- |
| `marqdo skill inspect PATH` | 解析 Skill 文档、章节、可调用函数和依赖 |
| `marqdo skill list PATH` | 列出对 Agent 暴露的工具 |
| `marqdo skill check PATH` | 检查语法、绑定、签名、效应和工具导出规则 |
| `marqdo call TARGET` | 调用指定 Marqdo 函数并返回结果 |
| `marqdo skill test PATH` | 执行 Skill 的测试与契约检查 |
| `marqdo skill export PATH` | 生成通用工具描述或 MCP 暴露接口 |
| `marqdo skill trial PATH` | 对修改后的候选版本进行隔离验证 |
| `marqdo skill promote PATH` | 在门禁通过后发布新版本 |
| `marqdo skill rollback PATH` | 恢复到指定已接受版本 |
不过不建议一次性实现这九项命令。最小可用产品只需要 `inspect`、`call`、`check`、`test` 四项,版本发布与改进机制可以随后补齐。
最重要的技术决策是:
`marqdo call` 必须调用现有编译器绑定的函数,不得重新用字符串搜索源码、猜测章节位置再执行。
当前 [src/mlsp.rs](https://github.com/cflmy/marqdo/blob/main/src/mlsp.rs?utm_source=chatgpt.com) 已有 `artifact.bind` 与 `artifact.execute`,能够检查制品指纹、依赖闭包、来源摘要和效应策略。新的 CLI 应复用相同的应用服务和语义校验,而不是通过进程内调用 MLSP JSON 接口制造另一层重复协议。
还有一个现有实现细节:`marqdo run --call-lib-path` 已支持隔离 worker 通过 JSON 参数调用函数,但当前 `src/lib.rs` 的这个入口只在树遍历分支中处理,Bytecode 分支仍按普通程序入口执行。新的公开 `call` 命令需要补齐这一差异,或者明确在第一版只支持 Tree backend,不能静默忽略所选后端。
## 四、完整示例:让一份 Skill 同时成为文档、知识和工具
我建议第一版尽量保持作者体验简单:人只维护一份 Markdown 源文件,编译器自动生成工具描述、函数索引和知识制品。
例如,我们建立一个订单计算 Skill。
下面是目标设计示例。其中 `runtime` 和 `tools` 是我建议为 Skill 编译增加的元数据约定,目前不能将这份 `SKILL.md` 直接交给 v2.1.5 的 CLI,期待自动注册工具。
```
---
name: order-calculator
description: 订单价格计算,包括商品小计和含税金额
runtime: marqdo
tools:
- 订单计算.商品小计
- 订单计算.含税金额
---
# 订单计算
这份技能用于计算订单金额。
所有金额使用同一货币单位。税率使用小数表示,
例如 0.10 表示 10%。
## 商品小计
给定商品单价`单价`和购买数量`数量`,
计算未税商品小计。
*[商品小计](单价 * 数量)*
## 含税金额
给定商品单价`单价`、购买数量`数量`
和适用税率`税率`,计算含税金额。
**小计 = [计算商品小计](订单计算.商品小计(单价=单价, 数量=数量))**
*[最终含税金额](小计 * (1 + 税率))*
```
这里的计算是演示规则。正式业务技能还需要校验数量范围、金额精度、货币单位、税率适用条件与舍入规则;这些不能由函数名字自动推断为正确。
### 这份 Skill 会产生三种投影
给人阅读: 它是一份正常的 Markdown 文档。读者能理解每个步骤的目的,以及所需输入和返回值。
给 Marqdo 编译器: 两个 `##` 单元构成可解析的函数;第二个函数可以确定性地调用第一个函数;符号索引能够记录它们的依赖关系。
给 Agent 使用: 编译器输出两个工具的结构化描述。Agent 不需要重新生成乘法计算程序,只需选择工具并提供参数。
例如,编译后的工具描述可以是:
```
{
"id": "order-calculator::订单计算.商品小计",
"description": "计算未税商品小计",
"input_schema": {
"type": "object",
"properties": {
"单价": {"type": "number"},
"数量": {"type": "number"}
},
"required": ["单价", "数量"]
},
"output_schema": {
"type": "number"
},
"effect": "pure"
}
```
但这个 Schema 必须由明确的类型契约和编译器检查生成。若源文件没有足够的类型信息,应标记为未知或要求补全,不能因为变量参加了乘法就无条件断言它一定是 `number`。
需要强调:不是 `##` 标题自动等于一个公开工具。 `##` 让章节具备 Marqdo 函数的结构,`tools` 则声明哪些函数允许对外暴露。这样才能避免“安全说明”一类章节被意外注册成工具,也避免内部辅助函数被 Agent 随意调用。
### 为什么采用显式的 `runtime: marqdo`?
因为普通 Skill 的 Markdown 本来就可能包含 `**加粗内容**`、编号列表、代码块和二级标题。这些在现有 Marqdo 中可能具有执行语义。
如果直接把所有 `SKILL.md` 当成 `.mq.md` 执行,很可能发生严重的语义误读。
所以我建议:
- 未明确声明 Marqdo 运行时的 `SKILL.md`,仍然是普通 Markdown 文档。
- 明确声明 `runtime: marqdo` 的 Skill 才进入 Marqdo 编译流程。
- 内嵌示例代码块不应因展示而执行。
- 编辑器应对具有执行意义的 Markdown 标记提供可视化提示。
- 导出的工具必须经过独立检查和授权。
未来还可以支持从已有普通 Skill 中自动提取候选函数,但那应当是生成可审阅的转换补丁,而不是默认把自然语言步骤当成已经实现的代码。
## 五、这次最有价值的部分:自我改进的 Skill
你提出的第二层意义,我认为甚至比 `marqdo call` 更值得研究。
传统 Agent 修改一个 Skill 时,常见问题是:它修改了一段说明或脚本,却无法可靠判断其他步骤是否受到影响。
Marqdo 已经具备一些适合解决这个问题的基础,例如 `SymbolId`、依赖闭包、`artifact.patch`、`artifact.verify` 和知识影响分析。
但是,不能由此推出“智能体修改 Skill 就不会出错”。
更精确的目标是:智能体可以提出改进,系统能够判定一组明确、可测试的性质是否被保持,并且只有通过门禁的版本才有资格替换原有 Skill。
我建议采用以下演化协议:
已发布 Skill v1
现有稳定版本与完整依赖
1\. 发现确定的问题
失败测试、诊断、复现步骤或用户提出的明确修改要求
2\. AI 生成局部修改候选
只修改获准的章节或函数,记录版本与修改意图
3\. 编译与静态验证
语法、符号、参数、返回类型、效应、依赖关系
4\. 隔离测试与回归验证
目标问题修复、历史行为保持、异常输入、性能与权限边界
5\. 发布门禁
仅当策略允许且必要验证通过时晋升新版本;否则保留旧版本
Skill v2 · 已接受版本
可追溯、可回滚、后续调用绑定到明确版本
### 举一个真正的自我改进案例
原 Skill 中存在:
```
## 商品小计
商品单价`单价`,购买数量`数量`。
*[小计](单价 * 数量)*
```
现在发现一个确定的问题:输入 `数量=-1` 时,函数返回负数,但业务要求数量必须大于零。
Agent 不应该只是把说明修改成“数量必须大于零”。这不会改变执行行为。
它应当在候选版本中增加可执行的校验逻辑,并补充至少三个测试:
| 测试 | 输入 | 期望 |
| ---- | ----------- | ------------- |
| 正常订单 | 单价 30,数量 2 | 返回 60 |
| 非法数量 | 单价 30,数量 -1 | 返回结构化参数错误 |
| 边界数量 | 单价 30,数量 0 | 根据业务契约决定接受或拒绝 |
如果 Marqdo 尚不具备合适的语言级错误返回或异常处理方式,这个案例还会暴露一个语言能力缺口:需要一种由 Marqdo 程序自身构造、传递和处理错误的机制,而不是只能依赖 Rust 宿主报错。
这与此前我们讨论的通用语言能力重构是直接关联的。
### 自我进化的边界必须比普通代码修改更严格
我建议把以下约束固定下来:
1. 修改不能自动扩大权限。 原 Skill 只有纯计算权限,新版本不能因为 Agent 自己添加网络或文件操作就获得这些权限。
2. 候选版不能直接覆盖运行中的正式版本。 需要隔离工作区、原子发布和固定引用版本。
3. 必须证明目标问题被修复。 不允许通过删除测试、放宽断言或隐藏失败来宣称成功。
4. 测试通过不是绝对正确的证明。 未覆盖的业务情况、外部事实和依赖服务仍可能出错。
5. 高风险修改需要更严格的发布决策。 尤其是支付、外部写入、删除、凭证和安全策略变更,不能由被修改的 Skill 自己批准。
最新仓库的 `artifact.patch` 已经提供基于摘要的修改和有限回滚,但它还不是完整的候选版本事务与测试后晋升系统。现有 `HostCaps` 的默认值也允许文件写入、执行、网络和插件,因此新 `call` 的安全默认值应当收紧,不能简单继承普通本地运行的全部宿主权限。
这就是“有界自我进化”的含义:不保证 Agent 永不犯错,而是让它能够在可验证、可回滚、可限制权限的范围内持续改进。
## 六、我建议如何安排开发
| 阶段 | 目标 | 关键验收 |
| ---------------- | ---------------------------------------- | ------------------------ |
| S0 · Skill 语义一致性 | 修复官方 Skill 与解析器的标记冲突,建立 Skill 语法同步测试 | Skill 记载的每条核心语法都有可运行金样例 |
| S1 · 函数调用 CLI | `marqdo call` 调用已绑定的普通函数、类函数和跨文档函数 | JSON 参数正确绑定;错误路径和双后端行为明确 |
| S2 · Skill 编译 | 对显式启用的 `SKILL.md` 解析章节和可执行函数 | 自动产生 SymbolId、签名、依赖、导出清单 |
| S3 · 知识即工具 | 将公开函数编译为 ToolSpec,并接入现有 Agent dispatcher | Agent 不重新生成实现即可调用并取得结果 |
| S4 · Skill 测试 | 增加 `skill check/test`、负例、效应门禁和回归测试 | 未通过验证的 Skill 不得自动发布 |
| S5 · Skill 演化 | 实现候选修改、隔离验证、影响分析、版本晋升与回滚 | 修改失败不影响已发布版本,权限不能自行扩大 |
这里还需要一项对你的研究目标尤其重要的对照实验。
让相同模型分别使用普通 Markdown Skill、Markdown Skill 加外部脚本工具、以及 Marqdo Executable Skill 完成相同的一组任务。分别测量正确率、模型需要重新生成的代码量、工具调用参数错误、修改后的回归失败率、token 消耗和完成时间。
只有与“Markdown + 现有工具调用”进行公平对照,才能证明 Marqdo 的优势来自文档、程序与知识的统一,而不只是因为它额外提供了一个执行器。
## 七、我对这项构想的最终评价
我认为这次构想具有三个非常值得肯定的性质。
第一,它有明确的语言基础。`#`、`##`、自然语言叙述、函数参数、`[]()`、契约表和跨文档符号绑定并不是为了 Skill 重新创造的。Skill 可以成为现有语言的一种应用形态。
第二,它有真实的工程基础。当前 Marqdo 已经具备部分确定性绑定、制品验证、Agent 复用与隔离运行能力。你需要做的是将这些能力收敛到统一的公开接口,而不是重新实现一套 Agent 框架。
第三,它能够引出一个更有研究价值的问题:自然语言描述的操作知识,如何逐步转化为可调用、可检查、可维护,并可由 Agent 在受限条件下自行改进的程序制品?
但是,“SKILL 章节即函数”本身还不足以证明新的编程范式。Markdown 章节映射函数,与文学编程、文档驱动工作流及现有工具包装有明显的共同点。
更有价值的是把三个原本需要单独维护的对象——Skill 说明、函数实现、Agent Tool Schema——统一为一个可编译的源事实,并展示这种统一确实降低了错误、维护成本和重复生成成本。
我建议为 Marqdo 保留原来的核心理念,并将这一阶段的技术方向明确为:
> 知识即工具(Knowledge as Tool):将可执行知识直接编译为 Agent 能够发现、调用和验证的工具,并允许智能体在明确的语义、测试和权限边界内持续改进这些知识。
这可能是 Marqdo 从“AI 可以使用的编程语言”,进一步走向“AI 能够使用并维护的可执行知识体系”的关键一步。
备注,这里实际上有一点叙述错误,marqdo支持mq.md文件,所以最好针对SKILL也是SKILL.mq.md这样会比较统一。
+249
View File
@@ -0,0 +1,249 @@
SKILL的名称应该是.mq.md有一点必须提及,SKILL其实命名不一定必须得是SKILL,平常的一个marqdo文件也可以是一份skill这里的设计太复杂了没有抽离出来核心本质,你看对于一个平常的marqdo文件,完全也可以和SKILL一样,这都是没有区别的,所谓的知识即工具作为高度抽象本质就是带参数调用函数,所以你的inspect等等命令其实完全可以对传统的marqdo也生效而不是非要绑定SKILL对吧,而且这样处理还有好处是方面智能体做单元测试,单个函数是否可以带参数直接运行,换句话说,你仔细思考就会发现这些好处是marqdo的设计哲学在增加一点点call自然派生的优势,所以不需要繁复的设计
你说得对。这次我认为你抓住了真正的核心,而且我的上一版设计确实把一个本来很自然的语言能力复杂化了。
Marqdo 根本不需要引入一种叫作 Executable Skill 的新概念,也不需要专门建立 Skill 编译器。
因为在 Marqdo 的设计哲学下:
> 一个 `.mq.md` 文件本身就是文档、知识与程序。只要允许从外部直接调用其中的函数,它自然也就能够成为 Skill。
这不是为 Skill 开发一套新系统,而是为 Marqdo 补齐一个非常基础的语言使用入口。
## 一、真正缺少的只有一件事:函数级执行入口
Marqdo 当前已经支持函数定义、参数、返回值、模块引用,以及确定性符号绑定。
但是日常使用时,我们往往仍然站在“运行整个文件”的角度:
```
marqdo run example.mq.md
```
你现在提出的是:
```
marqdo call example.mq.md 函数名 参数
```
这实际上意味着:
Marqdo 的最小可执行单位,从文件进一步扩展为文件中的任意可调用函数。
而这一点会自然派生大量优势。
普通 `.mq.md` 文件
自然语言叙述 + 函数 + 参数 + 返回值
marqdo call
指定函数 + 绑定参数 + 直接执行
知识复用
调用已存在的实现
Agent Skill
直接暴露函数为工具
单元测试
逐个函数验证结果
自我改进
修改函数并重新测试
这里不存在四套实现,只有一个底层能力的四种使用方式。
## 二、一个普通的 Marqdo 文件就足够了
比如,文件 `calculator.mq.md`:
```
# 计算器
这是一个普通的 Marqdo 文档。
其中包含一些可以复用的数学计算知识。
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
## 乘法
计算两个数字`a`和`b`的积。
*[计算结果](a * b)*
```
它既是可阅读的文档,也包含两个函数。
现在只需要支持:
```
marqdo call calculator.mq.md 计算器.加法 a=2 b=3
```
返回:
```
5
```
再比如:
```
marqdo call calculator.mq.md 计算器.乘法 a=4 b=6
```
返回:
```
24
```
以上 `marqdo call` 是拟新增的命令形式;函数示例遵循当前 `*…*` 返回、`[]()` 遮蔽的语义。
这时候,一个 Agent 只要能够读取这个 `.mq.md` 文档,就可以理解函数的用途;只要能够调用 Marqdo CLI,就能执行其中的能力。
它根本不需要关心这个文件是不是 Skill,也不需要一份特殊的 `SKILL.md`。
如果 Agent 把它当成 Skill 阅读和使用,它就是 Skill;如果开发者把它当成程序库调用,它就是程序库;如果研究者把它作为知识库中的一部分,它就是可执行知识。
文件的身份没有变化,变化的是使用方式。
## 三、这项能力会自然解决三个问题
### 1. 让知识成为工具
传统 Skill:
Agent 阅读操作说明,决定如何完成任务。
Marqdo:
Agent 阅读函数说明,找到适合的函数,传入参数,直接执行。
这就将原来的:
知识 → Agent 理解 → 重新实现 → 执行
缩短为:
知识 → 函数定位 → 参数调用 → 执行
但模型仍然需要负责判断应该调用哪个函数、传入哪些参数。确定性的是被调用函数的语言语义,而不是整个 Agent 决策过程。
### 2. 让单元测试成为语言的天然能力
我非常赞同你提到的单元测试价值。
有了 `marqdo call`,可以直接测试:
```
marqdo call calculator.mq.md 计算器.加法 a=2 b=3
# 期望 5
marqdo call calculator.mq.md 计算器.加法 a=-2 b=3
# 期望 1
marqdo call calculator.mq.md 计算器.乘法 a=0 b=100
# 期望 0
```
不必为了测试一个函数,再创建一个 `# main`,再编写调用、打印和结果检查的包装程序。
未来即使增加 `marqdo test`,底层仍然可以复用同一个函数调用接口。
### 3. 让 Agent 可以针对知识进行局部改进
这是你提出的最有意义的延伸。
假设一个 Agent 发现 `计算器.乘法` 对某类输入存在错误。
它可以:
1. 阅读相应函数及其上下文。
2. 修改这个 `.mq.md` 文件中的函数实现。
3. 直接用 `marqdo call` 传入错误输入验证。
4. 再运行该函数的历史测试。
5. 如果检查通过,就提交候选修改;否则保留原有实现。
这使得 Agent 的改进对象不再仅仅是自然语言提示词,而是有明确输入、输出和可执行语义的知识单元。
当然,测试不能证明函数在所有输入上都正确;正式发布和权限控制仍需要遵循已有的项目验证机制。但不需要为此创造一套 Skill 专属的演化协议。
## 四、真正的 CLI 设计可以非常简单
我建议第一阶段只做一个命令:
```
marqdo call <文件> <函数> [具名参数...]
```
比如:
```
marqdo call book.mq.md 订单.计算总价 单价=30 数量=2
```
它只需要完成五件事:
| 步骤 | 职责 |
| -- | -------------------- |
| 1 | 加载指定 `.mq.md` 文件及其导入 |
| 2 | 解析并唯一定位目标函数 |
| 3 | 根据现有函数签名绑定、校验参数 |
| 4 | 使用现有运行时执行该函数 |
| 5 | 返回函数结果和结构化错误 |
额外提供一个 `--json` 输出选项就足够方便 Agent 调用。
如果未来需要 `marqdo inspect`,它也应该针对任何 `.mq.md` 文件,列出其中函数、参数和文档描述,而非限定 Skill。
此外,当前仓库已经有 `--call-lib-path` 和 `artifact.execute` 的相关基础,因此实现时应尽量复用现有函数定位与执行机制,而不是重复开发解释器。
唯一值得坚持的边界是:外部调用仍必须经过现有权限检查,不能因为新增了 `call` 就默认允许 Agent 对任意函数执行文件删除、网络写入等操作。
## 五、我认为你的设计哲学现在更加清晰了
你原来的理念:
> 代码即文档,文档即知识库,知识即可执行。
实际上已经足够完整。
“知识即工具”不是额外的设计理念,而是“知识即可执行”在函数级调用能力成熟后自然出现的结果。
进一步看,这件事还有一个很漂亮的对称性:
| 参与者 | 对同一个 `.mq.md` 的使用方式 |
| ---------- | ------------------- |
| 人类 | 阅读文档、理解知识 |
| 编译器 | 解析并验证函数 |
| 开发者 | 调用函数、组合程序 |
| Agent | 发现知识、调用工具 |
| 测试系统 | 输入参数、检查结果 |
| 维护者或 Agent | 修改实现、验证改进 |
这些角色并没有要求作者维护六份不同的东西。
同一份文件,同一套语义,同一个函数调用接口。
这也恰恰是我认为 Marqdo 相比传统“Markdown 文档 + 外部工具”组合最值得证明的优势:知识描述与执行实现共址,而且能够直接由语言工具链消费,避免维护重复的工具包装和操作说明。
所以,我现在的建议与上一轮不同:
不要开发 Executable Skill 系统。不要设计 Skill 专属语法。不要引入新的 Skill 注册、编译和执行机制。
先完成 `marqdo call`,使普通 `.mq.md` 中的可调用函数都能被精确定位、传参执行,并用现有语义系统验证。
这是一个相对很小的接口变化,却可能自然打通 Marqdo 的编程、知识复用、Agent 工具调用和函数级测试四个场景。
我认为这才是你所说的:让 Marqdo 自己的设计哲学发挥作用,而不是不断增加外部框架来证明它的价值。
+17
View File
@@ -0,0 +1,17 @@
# 计算器
这是一个普通的 Marqdo 文档。
其中包含一些可以复用的数学计算知识。
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
## 乘法
计算两个数字`a`和`b`的积。
*[计算结果](a * b)*
+1 -1
View File
@@ -1 +1 @@
2.1.5
2.2.0
+82 -18
View File
@@ -67,7 +67,11 @@ One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{te
1. `stream`
**evs = > model.stream prompt=`prompt` echo=`echo` stream_kind=`stream_kind`**
**text = > llm.collect events=`evs`**
**tokens = 0**
**tokens = > llm.collect_usage events=`evs`**
1. `tokens` == None
**tokens = 0**
2. *
**_ = 1**
**err = None**
**calls = 1**
1. not `text`
@@ -89,12 +93,16 @@ One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{te
**tokens = > json.get value=`r` key="tokens"**
**err = > json.get value=`r` key="error"**
**fin = > json.get value=`r` key="finish"**
1. `tokens` == None
**usage = > json.get value=`r` key="usage"**
1. `usage`
**tokens = > json.get value=`usage` key="total_tokens"**
2. *
**text = > str value=`r`**
**tokens = 0**
**err = None**
**fin = None**
1. not `tokens`
1. `tokens` == None
**tokens = 0**
2. *
**_ = 1**
@@ -1339,7 +1347,7 @@ Write a scratch tool workbook under `.marqdo/agent-runs/tools/<name>.mq.md`.
Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget.
**esc = > json.parse text={"card":"## CORE SYNTAX (v2.1 Occlusion)\n1. Print with > print / > 打印 — never use bold markers to print.\n2. Bold markers = return/code; italic markers = statement.\n3. [desc](payload) = occlusion; brackets never execute.\n4. Read with access(coll, key) — never Classic [key](map) index.\n5. Foreach: - [desc](for coll as item). import + one language per file.\n6. # type · ## function · + params · numbered branches · - loops.\n"}**
**esc = > json.parse text={"card":"## CORE SYNTAX (v2.1 Occlusion)\n1. Print with > print / > 打印 — never use bold markers to print.\n2. Bold markers = statement; italic markers = return.\n3. [desc](payload) = occlusion; brackets never execute.\n4. Read with access(coll, key) — never Classic [key](map) index.\n5. Foreach: - [desc](for coll as item). import + one language per file.\n6. # type · ## function · + params · numbered branches · - loops.\n"}**
*> json.get value=`esc` key="card"*
---
@@ -2813,19 +2821,31 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
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`**
**exec_mode = "explore"**
**llm_calls = 1**
**llm_calls = > json.get value=`out` key="llm_calls"**
**tokens = > json.get value=`out` key="tokens"**
1. `llm_calls` == None
**llm_calls = 1**
1. `tokens` == None
**tokens = 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`**
**cache = > json.get value=`out` key="cache"**
1. `cache` == "hit"
**exec_mode = "compiled"**
**llm_calls = 0**
**tokens = 0**
2. `cache` == "soft-hit"
**exec_mode = "near"**
**llm_calls = 0**
**tokens = 0**
3. *
**exec_mode = "explore"**
**llm_calls = 1**
**llm_calls = > json.get value=`out` key="llm_calls"**
**tokens = > json.get value=`out` key="tokens"**
1. `llm_calls` == None
**llm_calls = 1**
1. `tokens` == None
**tokens = 0**
**st = > json.get value=`out` key="status"**
**res = > json.get value=`out` key="result"**
@@ -3492,6 +3512,8 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
**status = "error"**
**err = "max_rounds exhausted"**
**skip_loop = None**
**plan_llm_calls = 0**
**plan_tokens = 0**
> plan_echo_decompose workbook=`path` stream=`stream` echo=`echo`
**last_obs = > inspect_workbook path=`path`**
@@ -3505,6 +3527,12 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
**last_reply = > json.get value=`turn` key="reply"**
**last_obs = > json.get value=`turn` key="observation"**
**events = > json.get value=`turn` key="events"**
**_c = > json.get value=`turn` key="llm_calls"**
**_t = > json.get value=`turn` key="tokens"**
1. `_c` != None
**plan_llm_calls = plan_llm_calls + _c**
1. `_t` != None
**plan_tokens = plan_tokens + _t**
2. *
**dec = "TRANSPORT_ERROR"**
**last_reply = "plan_llm_act_loop_not_map"**
@@ -3553,11 +3581,27 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
2. *
**_ = 1**
5. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**skip_loop = 1**
Free-form parent reply with no DECISION/CALL/READ (dec=unknown): accept as DONE
when there is prose — chat soft-recover depends on result/summary surviving.
1. `dec` == "unknown"
1. `last_reply`
**done = 1**
**status = "ok"**
**err = None**
**summary = `last_reply`**
**skip_loop = 1**
2. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**skip_loop = 1**
2. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**skip_loop = 1**
1. `skip_loop`
**left = 0**
@@ -3606,6 +3650,12 @@ Deterministic success stop (loop engineering): when the child already returned a
**last_reply = > json.get value=`turn` key="reply"**
**last_obs = > json.get value=`turn` key="observation"**
**events = > json.get value=`turn` key="events"**
**_c = > json.get value=`turn` key="llm_calls"**
**_t = > json.get value=`turn` key="tokens"**
1. `_c` != None
**plan_llm_calls = plan_llm_calls + _c**
1. `_t` != None
**plan_tokens = plan_tokens + _t**
1. `dec` == DONE
> agent_workbook_solidify path=`path` observation=`last_obs`
**done = 1**
@@ -3626,11 +3676,25 @@ Deterministic success stop (loop engineering): when the child already returned a
3. `dec` == RUN
**left = left - 1**
4. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**left = 0**
1. `dec` == "unknown"
1. `last_reply`
**done = 1**
**status = "ok"**
**err = None**
**summary = `last_reply`**
**left = 0**
2. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**left = 0**
2. *
**done = 1**
**status = "error"**
**err = "unrecognized plan decision"**
**summary = last_reply**
**left = 0**
1. `status` == "ok"
1. `promote`
@@ -3643,9 +3707,9 @@ Deterministic success stop (loop engineering): when the child already returned a
`out` =
| status | goal | workbook | rounds | cache |
|--------|------|----------|--------|-------|
| `status` | `goal` | `path` | `round` | `cache` |
| status | goal | workbook | rounds | cache | llm_calls | tokens |
|--------|------|----------|--------|-------|-----------|--------|
| `status` | `goal` | `path` | `round` | `cache` | `plan_llm_calls` | `plan_tokens` |
1. `summary`
**out = table.put in=`out` at="summary" value=`summary`**
+29
View File
@@ -92,6 +92,35 @@ Alias: `stream_result`.
**answer = ""**
*answer*
## collect_usage
+ `events`
Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`).
**tokens = None**
1. `events`
- [ev](遍历 events 为 ev)
**t = > json.get value=`ev` key="type"**
**raw = None**
1. `t` == "data"
**raw = > json.get value=`ev` key="data"**
2. *
**u0 = > json.get value=`ev` key="usage"**
1. `u0`
**tt0 = > json.get value=`u0` key="total_tokens"**
1. `tt0` != None
**tokens = `tt0`**
1. `raw`
1. not `raw` == "[DONE]"
**parsed = > json.parse text=`raw`**
1. `parsed`
**u = > json.get value=`parsed` key="usage"**
1. `u`
**tt = > json.get value=`u` key="total_tokens"**
1. `tt` != None
**tokens = `tt`**
*tokens*
## stream_result
+ `events`
+7
View File
@@ -115,6 +115,13 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes
1. `stream`
**req = > table.put in=`req` at="stream" value=True**
`stream_opts` =
| include_usage |
|---------------|
| True |
**req = > table.put in=`req` at="stream_options" value=`stream_opts`**
**body = > json.stringify value=`req`**
**resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo`**
**st = > json.get value=`resp` key="status"**
+9
View File
@@ -211,6 +211,10 @@ fn parse_sse_events(
{
accumulated.push_str(c);
}
// Preserve provider usage as a first-class event for llm.collect_usage.
if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
events.push(json!({"type": "usage", "usage": u}));
}
}
events.push(json!({"type": "data", "data": data}));
}
@@ -365,6 +369,11 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
}
if stream {
req_body.insert("stream".into(), Value::Bool(true));
// OpenAI / DeepSeek / compatible: final SSE chunk carries usage only when requested.
req_body.insert(
"stream_options".into(),
json!({ "include_usage": true }),
);
}
let body = Value::Object(req_body).to_string();
let auth = format!("{bearer}{api_key}");
+3 -1
View File
@@ -17,7 +17,9 @@ The language is still early: structural markers, English/Chinese builtin aliases
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
Want a quick hello? Calls only run when they sit in the entry `# main` — `##` children are methods until something calls them. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**.
Want a quick hello? `marqdo run` executes the entry `# main`. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**.
This version also runs one function on its own. `marqdo call` takes the file, the function and named arguments. The page you read is the program that runs. What that is for, and why it matters, is in [features/22-call.mq.md](features/22-call.mq.md).
Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention.
+3 -1
View File
@@ -17,7 +17,9 @@ AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再
English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English builtins).
想先打个招呼?调用写在入口 `# main` 里才会真的跑——子标题里的方法要等你叫到它。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。
想先打个招呼?`marqdo run` 会运行入口 `# main`。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。
从这一版起,不必为了试用一个函数再包一层入口。`marqdo call` 直接运行文件里的某个函数,参数写在命令上。同一页仍然是给人读的文档。作用和价值写在 [features/22-函数调用.mq.md](features/22-函数调用.mq.md)。
除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。
+1
View File
@@ -14,6 +14,7 @@
| [`features/19-foreign-view-cells.mq.md`](features/19-foreign-view-cells.mq.md) / [`19-外联视图单元.mq.md`](features/19-外联视图单元.mq.md) | 外联 v2 完整 Python 示例:probe / JSON call / 并行 / 持久内核 / 状态桥 / view 单元 |
| [`features/20-okf-ekc.mq.md`](features/20-okf-ekc.mq.md) / [`20-OKF与EKC.mq.md`](features/20-OKF与EKC.mq.md) | 代码即文档、文档即知识:OKF 形态与 EKC 工程知识编译器 |
| [`features/21-persistence.mq.md`](features/21-persistence.mq.md) / [`21-持久化.mq.md`](features/21-持久化.mq.md) | 外联结果持久化:静态快照与 writeback |
| [`features/22-call.mq.md`](features/22-call.mq.md) / [`22-函数调用.mq.md`](features/22-函数调用.mq.md) | `marqdo call`:同一份文档按函数执行,知识可以直接当工具 |
官方扩展(非 stdlib):`ext/llm`、`ext/agent`、`ext/web`、`ext/quantum`、`ext/linalg` — 见 `features/05-*.mq.md`、`06-*.mq.md`、`07-linalg.mq.md` / `07-线性代数.mq.md` 与 `doc/design/ext-*.md`。
+59
View File
@@ -0,0 +1,59 @@
---
markup: occlusion
title: Call one function: the same document is the tool
description: v2.2.0 marqdo call runs a function inside any .mq.md. The explanation, the implementation and the call are one page.
---
# main
v2.2.0 adds one command: `marqdo call`. It adds no Markdown marker and no skill system. An ordinary .mq.md file is already a document, a piece of knowledge and a program. What was missing is a way to call one of its functions from outside.
The usual command runs the whole file. Functions inside it run only when the entry calls them. Trying one calculation meant writing an entry, a print and a check. The smallest unit you can execute is now a function.
```text
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
```
Standard output is 5. `--json` is for programs and agents: success carries the result, failure carries a diagnostic code, and the process exits non-zero. `--backend tree` and `--backend bytecode` both run that function. Another entry in the file is not used as a fallback.
The second half of this page is itself a calculator. This command calls this page:
```text
marqdo call public/features/22-call.mq.md calculator.add a=2 b=3
```
---
The change is how the file is used.
A person reads the sentences next to the function and sees what add computes. The compiler reads the same markers and checks parameters and the return. A developer composes the function into another program. A test passes inputs to this function and looks at the output, without a wrapper whose only job is to print. An agent reads what the function is for and runs the implementation that is already there, instead of reading the page and rewriting it.
Those four uses are one call. Knowledge becomes a tool because knowledge can already run, now at function scope. The file does not need a special name, and it does not need to declare itself a skill.
---
The command keeps a boundary.
An external call runs a pure function. Writing files, starting a process, using the network or loading a plugin is refused before the function runs, so the side effect does not happen. Wider permission stays on the checks the project already has. An instance method needs its receiver; this command does not invent one.
The function must resolve to exactly one declaration. No match, or one short name that hits two functions, is a structured error. The command does not pick the first hit. Arguments bind through the signature and contract that the function already has. Missing, unknown and ill-typed arguments are diagnostics.
After editing a function, call it again with the inputs that failed. A passing check is a reason to keep the edit. A test does not prove every input. It gives the edit a check that can be repeated.
# calculator
This is an ordinary Marqdo document.
It holds a little reusable arithmetic.
## add
Add the numbers `a` and `b`.
*[result](a + b)*
## multiply
Multiply the numbers `a` and `b`.
*[result](a * b)*
+59
View File
@@ -0,0 +1,59 @@
---
markup: occlusion
title: 函数级调用:同一份文档成为工具
description: v2.2.0 的 marqdo call 让任意 .mq.md 里的函数可以带参数执行。说明、实现和调用是同一页。
---
# main
v2.2.0 增加一条命令:`marqdo call`。它不新增 Markdown 标记,也不另建一套技能系统。一个普通的 .mq.md 本来就是文档、知识和程序。缺的是从外部直接调用其中某个函数。
以前日常用法是运行整份文件。入口对象跑完,里面的函数要等文件自己去调用。要试验一个计算,往往得再写入口、打印和检查。现在最小可执行单位是函数。
```text
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
```
标准输出是 5。`--json` 给程序和 Agent 读:成功时是带结果的对象,失败时是带诊断码的对象,退出码非 0。`--backend tree` 与 `--backend bytecode` 执行同一个函数。文件里即使还有别的入口,也不会改去跑那个入口。
本页后半本身就是一份计算器。下面这条命令调用的就是这一页:
```text
marqdo call public/features/22-函数调用.mq.md 计算器.加法 a=2 b=3
```
---
它解决的是使用方式,不是再写一份说明书。
人打开这一页,读函数旁边的句子,知道加法在算什么。编译器解析同一批标记,检查参数和返回。开发者把函数嵌进别的程序。测试对这个函数传入输入,看输出是不是期望值,不必为它包一层只用来打印的程序。Agent 读到的是函数的用途,执行的是已经写好的实现,而不是读完说明再临时重写一遍。
这四件事共用一次调用。知识成为工具,是「知识即可执行」在函数这一层上的结果。文件不需要改名,也不需要声明自己是技能。运行时和工具清单都不会把一页普通文档挡在门外。
---
边界也写在命令里。
外部调用默认只执行纯函数。写文件、起进程、访问网络、加载插件,会在运行前被拒绝,副作用不会发生。要放宽权限,仍走项目里已有的验证,而不是在这条命令上新开一个开关。实例方法需要接收者,不能靠这条命令凭空调用。
函数名必须能唯一对上。没有这个函数,或同一个短名指向两个函数,都会返回结构化错误,不会擅自挑第一个。参数按函数已有的签名和契约绑定:缺了、多了、类型不对,都是诊断,不是静默猜一个值。
改一个函数之后,用原来的输入再调用一次。结果对了,这个实现就留下来;不对,就还是原来的实现。测试不能证明所有输入都正确。它让修改有一个可以重复的检查点。
# 计算器
这是一个普通的 Marqdo 文档。
其中包含一些可以复用的数学计算知识。
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
## 乘法
计算两个数字`a`和`b`的积。
*[计算结果](a * b)*
+30 -12
View File
@@ -21,7 +21,7 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
These rules are the **current default**. Do **not** teach Classic `[key](map)` index or “bold is return of print”. Classic migration only: [migration-classic.md](migration-classic.md).
1. **File suffix** `.mq.md`. Print with `> print text=…` / `> 打印 内容=…` — never use `**…**` to print.
2. **`**…**` = code / return expression.** `*…*` = statement (bind / expr). Closing markers touch the last token (no trailing space).
2. **`**…**` = statement** (assign / call / expression). `*…*` = return. Closing markers touch the last token (no trailing space).
3. **`[描述](payload)` = occlusion:** `[]` is prose (never executed); `()` is the only executed part. Empty `()` → `None` stub.
4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion.
5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code.
@@ -34,8 +34,8 @@ These rules are the **current default**. Do **not** teach Classic `[key](map)` i
| Marker | Meaning (v2.1) |
|--------|----------------|
| `#` / `##`+ | Object/type · function/method |
| `*…*` | Statement |
| `**…**` | Return / code expression |
| `**…**` | Statement (assign / call / expression) |
| `*…*` | Return |
| `[描述](payload)` | Occlusion step (payload executes) |
| `access(c, k)` | Collection read |
| `> fn …` | Call |
@@ -57,6 +57,24 @@ Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executabl
8. Browser: Marqdo on WASM + `lib/browser` tables; do not hand-write business JS.
## Call one function
```markdown
# 计算器
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
```
```
marqdo call calculator.mq.md 计算器.加法 a=2 b=3
```
prints `5`. The same command works on any `.mq.md`; the file does not need a special skill name.
## Minimal program
```markdown
@@ -96,13 +114,13 @@ 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
@@ -130,9 +148,9 @@ import:
# main
*xs = > text.split value="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).
@@ -191,8 +209,8 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea
**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin.
```markdown
*_ = > `qc`.draw kind="circuit" theme="dark"*
*_ = > `qc`.draw kind="probs" theme="light"*
**_ = > `qc`.draw kind="circuit" theme="dark"**
**_ = > `qc`.draw kind="probs" theme="light"**
```
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/).
@@ -223,8 +241,8 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
| `# main` then prose then code with no blank line | Blank line before code |
| `if x > 0:` | `1. `x` > 0` |
| `* > print text=hi *` | `> print text=hi` |
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
| `` *`a` = 1 * `` (trailing space + backticks) | `**a = 1**` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (italic is return, and bare text args) | `**xs = > text.split value="a,b" sep=","**` — statement; quote text literals |
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
+21 -3
View File
@@ -33,6 +33,16 @@ struct FlatFun {
}
pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
compile_with(path, module, true)
}
/// Compile every function even when the file has no single program entry.
/// `Program::entry` is then only a placeholder; callers must use [`Vm::call_function`].
pub fn compile_for_call(path: Option<&Path>, module: &Module) -> Result<Program> {
compile_with(path, module, false)
}
fn compile_with(path: Option<&Path>, module: &Module, require_entry: bool) -> Result<Program> {
let mut flat = Vec::new();
let mut next_scope = 1u32;
let _exports = collect_module_tree(module, &mut flat, 0, &mut next_scope);
@@ -40,7 +50,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
bail!("bytecode: no functions to compile");
}
let entry = flat
let chosen = flat
.iter()
.position(|f| f.name == "main" && f.parent.is_none())
.or_else(|| {
@@ -55,8 +65,14 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
} else {
None
}
})
.ok_or_else(|| anyhow::anyhow!("bytecode: no `# main` object"))?;
});
let entry = match chosen {
Some(index) => index,
None if !require_entry => 0,
None => bail!("bytecode: no `# main` object"),
};
// Imports are compiled first, so a missing entry must take paths from the file's own functions.
let path_owner = if chosen.is_some() { entry } else { flat.len() - 1 };
let mut objects = Vec::new();
let mut methods = Vec::new();
@@ -95,6 +111,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
let parents: Vec<Option<usize>> = flat.iter().map(|f| f.parent).collect();
let children: Vec<Vec<usize>> = flat.iter().map(|f| f.children.clone()).collect();
let path_index = flat[path_owner].path_index.clone();
Ok(Program {
functions,
@@ -104,6 +121,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
methods,
parents,
children,
path_index,
})
}
+5 -1
View File
@@ -3,9 +3,11 @@
mod compile;
mod vm;
pub use compile::compile_module;
pub use compile::{compile_for_call, compile_module};
pub use vm::Vm;
use std::collections::HashMap;
use crate::diagnostics::Span;
use crate::value::Value;
@@ -100,6 +102,8 @@ pub struct Program {
pub parents: Vec<Option<usize>>,
/// Parallel to `functions`: child fn indices.
pub children: Vec<Vec<usize>>,
/// Dotted path (`计算器.加法`, `inc.加一`) → function index. Entry module exports plus imports.
pub path_index: HashMap<Vec<String>, usize>,
}
impl Program {
+42 -4
View File
@@ -102,7 +102,6 @@ impl Vm {
}
pub fn run(&mut self, program: &Program) -> Result<Value> {
let mut stack: Vec<Value> = Vec::new();
let entry = program.entry;
let arity = program.functions[entry].params.len();
if arity != 0 {
@@ -113,14 +112,53 @@ impl Vm {
.unwrap_or(Span::new(1, 1));
return Err(self.err_at(span, "bytecode: entry function needs arguments"));
}
self.execute(program, entry, &[])
}
/// Run `fn_idx` with named arguments already bound to local slots.
/// Does not fall back to [`Program::entry`].
pub fn call_function(
&mut self,
program: &Program,
fn_idx: usize,
args: &[(String, Value)],
) -> Result<Value> {
if fn_idx >= program.functions.len() {
return Err(self.err_at(
Span::new(1, 1),
format!("bytecode: function index {fn_idx} is out of range"),
));
}
self.execute(program, fn_idx, args)
}
fn execute(
&mut self,
program: &Program,
fn_idx: usize,
args: &[(String, Value)],
) -> Result<Value> {
let mut stack: Vec<Value> = Vec::new();
let mut slots = vec![Value::None; program.functions[fn_idx].locals.len().max(1)];
for (name, value) in args {
if let Some(i) = program.functions[fn_idx]
.locals
.iter()
.position(|local| local == name)
{
if i < slots.len() {
slots[i] = value.clone();
}
}
}
let mut frames = vec![Frame {
fn_idx: entry,
fn_idx,
ip: 0,
slots: vec![Value::None; program.functions[entry].locals.len().max(1)],
slots,
retag_matrix: None,
}];
self.host
.push_call_frame(&program.functions[entry].name.clone());
.push_call_frame(&program.functions[fn_idx].name.clone());
loop {
let frame = frames.last_mut().unwrap();
+295
View File
@@ -0,0 +1,295 @@
//! `marqdo call`: run one already-bound function in a `.mq.md` file.
//!
//! Location, effects, and execution go through the existing compiler and runtime.
//! The command does not scan headings, and it does not run the program entry when
//! the named function cannot be compiled.
use std::path::Path;
use anyhow::Result;
use crate::ast::Function;
use crate::bytecode::{compile_for_call, Vm};
use crate::diagnostics::{Diagnostic, Span};
use crate::host::{HostCaps, HostContext};
use crate::interp::Interpreter;
use crate::load::load_module;
use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject};
use crate::value::Value;
use crate::Backend;
/// Call `function` in `path` with named arguments.
///
/// Non-pure effects are refused before the function runs. Host write, exec, net,
/// and plugin capabilities stay off for the call.
pub fn call_file(
path: &Path,
function: &str,
args: &[(String, Value)],
backend: Backend,
) -> Result<Value> {
let path = path
.canonicalize()
.map_err(|e| call_diag(None, 1, "call.compile", format!("failed to read {}: {e}", path.display())))?;
let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?;
let artifact = locate_artifact(&compilation.semantics, &path, function)?;
deny_unsafe(&path, artifact)?;
execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
args,
tight_caps(),
backend,
true,
)
.map(|(value, _stdout)| value)
}
/// Run the function declared at `line` in `path`.
///
/// `display_name` is the declaration path (`计算器.加法`). The query the caller
/// typed is not used as a heading search and is not used as the bytecode path,
/// so a unique short name or SymbolId still executes that function.
/// `caps` are the host capabilities for this run. `call` passes them all off.
pub(crate) fn execute_source_function(
path: &Path,
line: u32,
display_name: &str,
args: &[(String, Value)],
caps: HostCaps,
backend: Backend,
strict_args: bool,
) -> Result<(Value, String)> {
let module = load_module(path)?;
let fun = find_function_at_line(&module.functions, line).ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line),
)
})?;
let expected = display_name
.rsplit('.')
.next()
.unwrap_or(display_name);
if fun.name != expected {
return Err(call_diag(
Some(path),
line,
"artifact.unresolved",
format!("源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", fun.name),
));
}
let mut interp = Interpreter::with_capture(Some(path), false)
.with_host(HostContext::for_capture(Some(path), caps));
// `call` checks the signature. `artifact.execute` keeps its previous
// environment injection so an input the body reads is not rejected as unknown.
let bound;
let invoke_args: &[(String, Value)] = if strict_args {
bound = interp.bind_external_args(&module, fun, args)?;
&bound
} else {
args
};
match backend {
Backend::Tree => {
let value = interp.invoke_bound_function(&module, fun, invoke_args)?;
Ok((value, interp.captured_stdout))
}
Backend::Bytecode => {
let program = compile_for_call(Some(path), &module)?;
let key: Vec<String> = display_name
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let idx = program.path_index.get(&key).copied().ok_or_else(|| {
call_diag(
Some(path),
line,
"artifact.unresolved",
format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"),
)
})?;
let mut vm = Vm::with_capture(Some(path))
.with_host(HostContext::for_capture(Some(path), caps));
let value = vm.call_function(&program, idx, invoke_args)?;
Ok((value, vm.captured_stdout))
}
}
}
/// Parse `name=value` tokens. Values are integers, decimals, quoted text, or True/False/None.
pub fn parse_call_args(tokens: &[String]) -> Result<Vec<(String, Value)>> {
let mut out = Vec::new();
for token in tokens {
let Some((name, raw)) = token.split_once('=') else {
return Err(call_diag(
None,
0,
"call.bad_arg",
format!("参数 `{token}` 需要写成 名字=值"),
));
};
if name.is_empty() {
return Err(call_diag(
None,
0,
"call.bad_arg",
format!("参数 `{token}` 缺少名字"),
));
}
let value = parse_literal(raw).map_err(|message| {
call_diag(None, 0, "call.bad_value", format!("参数 `{name}`: {message}"))
})?;
out.push((name.to_string(), value));
}
Ok(out)
}
fn tight_caps() -> HostCaps {
HostCaps {
fs_write: false,
exec: false,
net: false,
plugin: false,
}
}
fn locate_artifact<'a>(
project: &'a SemanticProject,
entry: &Path,
query: &str,
) -> Result<&'a SemanticArtifact> {
let in_entry: Vec<&SemanticArtifact> = project
.artifacts
.iter()
.filter(|artifact| same_file(&project.root, &artifact.source.file, entry))
.collect();
let exact: Vec<&SemanticArtifact> = in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.display_name == query
|| artifact
.symbol_id
.as_ref()
.is_some_and(|id| id.as_str() == query)
|| artifact.artifact_id.0 == query
})
.collect();
let hits = if !exact.is_empty() {
exact
} else if !query.contains('.') {
in_entry
.iter()
.copied()
.filter(|artifact| {
artifact.kind == "function"
&& artifact.display_name.rsplit('.').next() == Some(query)
})
.collect()
} else {
Vec::new()
};
match hits.len() {
1 => Ok(hits[0]),
0 => Err(call_diag(
Some(entry),
1,
"artifact.unresolved",
format!("无法唯一绑定 `{query}`"),
)),
_ => Err(call_diag(
Some(entry),
1,
"artifact.ambiguous",
format!("无法唯一绑定 `{query}`"),
)),
}
}
fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> {
if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.not_executable",
"只有非实例函数可由 call 直接执行".to_string(),
));
}
if !artifact.effects.is_pure() {
return Err(call_diag(
Some(path),
artifact.source.line,
"artifact.effect_denied",
format!(
"call 默认只执行纯函数,拒绝效应 {}",
artifact.effects.values().join(", ")
),
));
}
Ok(())
}
fn same_file(root: &Path, rel: &str, entry: &Path) -> bool {
let abs = root.join(rel);
match (abs.canonicalize(), entry.canonicalize()) {
(Ok(left), Ok(right)) => left == right,
_ => false,
}
}
fn find_function_at_line(functions: &[Function], line: u32) -> Option<&Function> {
for fun in functions {
if fun.span.line == line {
return Some(fun);
}
if let Some(found) = find_function_at_line(&fun.children, line) {
return Some(found);
}
}
None
}
fn parse_literal(raw: &str) -> Result<Value, String> {
match raw {
"True" | "true" => return Ok(Value::Bool(true)),
"False" | "false" => return Ok(Value::Bool(false)),
"None" | "none" => return Ok(Value::None),
_ => {}
}
if raw.len() >= 2 {
let bytes = raw.as_bytes();
if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"')
|| (bytes[0] == b'\'' && bytes[raw.len() - 1] == b'\'')
{
return Ok(Value::Text(raw[1..raw.len() - 1].to_string()));
}
}
if let Ok(n) = raw.parse::<i64>() {
return Ok(Value::Int(n));
}
if raw.contains('.') {
if let Ok(n) = raw.parse::<f64>() {
return Ok(Value::Num(n));
}
}
Err(format!(
"无法解析 `{raw}`(整数、小数、引号文本、True/False/None)"
))
}
fn preserve_diag(path: &Path, err: anyhow::Error) -> anyhow::Error {
if Diagnostic::find(&err).is_some() {
err
} else {
call_diag(Some(path), 1, "call.compile", format!("{err:#}"))
}
}
fn call_diag(path: Option<&Path>, line: u32, code: &str, message: String) -> anyhow::Error {
anyhow::Error::new(Diagnostic::new(path, Span::new(line, 1), message).with_code(code))
}
+1 -1
View File
@@ -67,7 +67,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Host capability flags. Default: all enabled.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
pub struct HostCaps {
pub fs_write: bool,
pub exec: bool,
+108 -29
View File
@@ -151,6 +151,13 @@ impl Interpreter {
bail_at(self.path.as_deref(), self.current_span, message)
}
fn err_code(&self, code: &str, message: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(
crate::diagnostics::Diagnostic::new(self.path.as_deref(), self.current_span, message)
.with_code(code),
)
}
fn emit_line(&mut self, text: &str) {
if self.capture {
self.captured_stdout.push_str(text);
@@ -363,6 +370,68 @@ impl Interpreter {
self.run_function(module, fun, Env::new(), args, false)
}
/// Bind named arguments for an external call. Unknown names, missing
/// required parameters, and contract mismatches are errors. Defaults run.
pub fn bind_external_args(
&mut self,
module: &Module,
fun: &Function,
args: &[(String, Value)],
) -> Result<Vec<(String, Value)>> {
self.current_span = fun.span;
self.host.current_line = fun.span.line;
let mut named: HashMap<String, Value> = HashMap::new();
for (k, v) in args {
if named.insert(k.clone(), v.clone()).is_some() {
return Err(self.err_code(
"call.duplicate_arg",
format!("duplicate named argument `{k}`"),
));
}
}
for k in named.keys() {
if !fun.params.iter().any(|p| &p.name == k) {
return Err(self.err_code(
"call.unknown_arg",
format!("unknown argument `{k}`"),
));
}
}
let ev: Vec<EvArg> = named
.into_iter()
.map(|(k, v)| EvArg::Named(k, v))
.collect();
let mut env = Env::new();
let bound = bind_function_args(self, module, fun, &mut env, &fun.params, &ev, false)
.map_err(|m| {
if m.starts_with("missing argument") {
self.err_code("call.missing_arg", m)
} else if m.starts_with("duplicate named argument") {
self.err_code("call.duplicate_arg", m)
} else {
self.err(m)
}
})?;
if let Some(c) = &fun.contract {
if let Some(d) = crate::contract::call_arg_diag(
c,
&fun.name,
&bound,
self.path.as_deref(),
fun.span,
) {
return Err(d.into());
}
}
let mut out = Vec::new();
for p in &fun.params {
if let Some(v) = bound.get(&p.name) {
out.push((p.name.clone(), v.clone()));
}
}
Ok(out)
}
/// Call a function using (and updating) [`Self::entry_bindings`] from `# main`.
/// Used by browser WASM sessions so handlers share state with the entry object.
pub fn invoke_in_entry(
@@ -1450,36 +1519,8 @@ impl Interpreter {
path: &[String],
ev_args: &[EvArg],
) -> Result<Value> {
let (lib, node) = locate_import_function(module, path).map_err(|m| self.err(m))?;
let display = path.join(".");
if path.len() < 2 {
return Err(self.err(format!("library path `{display}`: need at least `lib.member`")));
}
let lib_name = &path[0];
let lib = module.import_modules.get(lib_name).ok_or_else(|| {
self.err(format!("unknown library `{lib_name}` (import it in frontmatter)"))
})?;
let mut parent_is_object = false;
let mut node = lib
.functions
.iter()
.find(|f| f.name == path[1])
.ok_or_else(|| self.err(format!("unknown `{display}`")))?;
for seg in &path[2..] {
parent_is_object = node.is_object();
node = node
.children
.iter()
.find(|c| c.name == *seg)
.ok_or_else(|| self.err(format!("unknown `{display}`")))?;
}
if parent_is_object && !node.is_object() && crate::ast::function_uses_receiver(node) {
return Err(self.err(format!(
"`{display}` is an instance method; call it as `var`.{}",
node.name
)));
}
let bound = {
let mut dummy_env = Env::new();
@@ -1613,6 +1654,44 @@ fn tag_instance(type_name: &str, value: Value) -> Value {
}
}
/// `lib.member` / `lib.Type.member` against frontmatter imports. Does not execute.
pub(crate) fn locate_import_function<'a>(
module: &'a Module,
path: &[String],
) -> Result<(&'a Module, &'a Function), String> {
let display = path.join(".");
if path.len() < 2 {
return Err(format!(
"library path `{display}`: need at least `lib.member`"
));
}
let lib = module
.import_modules
.get(&path[0])
.ok_or_else(|| format!("unknown library `{}` (import it in frontmatter)", path[0]))?;
let mut parent_is_object = false;
let mut node = lib
.functions
.iter()
.find(|f| f.name == path[1])
.ok_or_else(|| format!("unknown `{display}`"))?;
for seg in &path[2..] {
parent_is_object = node.is_object();
node = node
.children
.iter()
.find(|c| c.name == *seg)
.ok_or_else(|| format!("unknown `{display}`"))?;
}
if parent_is_object && !node.is_object() && crate::ast::function_uses_receiver(node) {
return Err(format!(
"`{display}` is an instance method; call it as `var`.{}",
node.name
));
}
Ok((lib, node))
}
/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path).
fn bind_function_args(
interp: &mut Interpreter,
+43 -1
View File
@@ -12,6 +12,7 @@ pub mod binding;
pub mod browser_session;
pub mod builtin;
pub mod bytecode;
pub mod call;
pub mod capture;
#[cfg(feature = "cli")]
pub mod catalog;
@@ -260,6 +261,23 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
let bound_call = if let Some(lib_path) = &opts.call_lib_path {
let named = named_call_args(opts)?;
let segments: Vec<String> = lib_path
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let (lib, fun) = crate::interp::locate_import_function(&module, &segments)
.map_err(|m| anyhow::anyhow!(m))?;
let mut binder = Interpreter::with_capture(Some(path), false).with_host(
HostContext::for_capture(Some(path), opts.host_caps()),
);
let bound = binder.bind_external_args(lib, fun, &named)?;
Some((lib_path.clone(), bound))
} else {
None
};
let mut vm = Vm::new(Some(path))
.with_stdin(stdin_lines)
.with_trace(opts.trace_eval)
@@ -267,7 +285,21 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
if opts.trace_eval {
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
}
let value = vm.run(&program)?;
let value = if let Some((lib_path, bound)) = bound_call {
let key: Vec<String> = lib_path
.split('.')
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
let idx = program.path_index.get(&key).copied().ok_or_else(|| {
anyhow::anyhow!(
"bytecode: `{lib_path}` did not compile to a function; refusing to run the program entry"
)
})?;
vm.call_function(&program, idx, &bound)?
} else {
vm.run(&program)?
};
if opts.trace_eval {
eprintln!("=== marqdo: end trace-eval ===");
}
@@ -301,6 +333,16 @@ fn run_call_lib_path(
Ok(value)
}
fn named_call_args(opts: &RunOptions) -> Result<Vec<(String, crate::value::Value)>> {
let Some(value) = load_args_json(opts)? else {
return Ok(Vec::new());
};
match value {
crate::value::Value::Map(pairs) => Ok(pairs),
_ => bail!("args-json must be a JSON object"),
}
}
fn load_args_json(opts: &RunOptions) -> Result<Option<crate::value::Value>> {
let Some(path) = &opts.args_json else {
return Ok(None);
+61
View File
@@ -137,6 +137,26 @@ enum Commands {
#[arg(long)]
legacy_markup: bool,
},
/// Call one function in a `.mq.md` file: `marqdo call <file> <function> name=value`.
Call {
/// Source file.
file: PathBuf,
/// Function display path, for example `计算器.加法`.
function: String,
/// Named arguments `name=value` (integer, decimal, quoted text, True/False/None).
/// A value may be negative (`a=-2`). `--json` and `--backend` remain flags.
args: Vec<String>,
/// Print one JSON object: `{"ok":true,"result":...}` or `{"ok":false,"error":...}`.
#[arg(long)]
json: bool,
/// Runtime. Both backends execute the named function.
#[arg(long, value_enum, default_value_t = BackendCli::Tree)]
backend: BackendCli,
},
/// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables
Check {
/// Program path (.mq.md)
@@ -784,6 +804,47 @@ fn try_main(cli: Cli) -> Result<i32> {
}
Ok(0)
}
Commands::Call {
file,
function,
args,
json,
backend,
} => {
let outcome = (|| -> Result<marqdo::value::Value> {
let parsed = marqdo::call::parse_call_args(&args)?;
marqdo::call::call_file(&file, &function, &parsed, backend.into())
})();
match outcome {
Ok(value) => {
if json {
let result = marqdo::value_as_json(&value)
.map_err(|e| anyhow::anyhow!(e))?;
println!(
"{}",
serde_json::json!({"ok": true, "result": result})
);
} else {
println!("{}", value.as_display());
}
Ok(0)
}
Err(err) => {
let diag = Diagnostic::find(&err).cloned().unwrap_or_else(|| {
Diagnostic::new(None, Span::new(0, 0), format!("{err:#}")).with_code("call.failed")
});
if json {
println!(
"{}",
serde_json::json!({"ok": false, "error": diag.to_json()})
);
} else {
eprintln!("error: {diag}");
}
Ok(1)
}
}
}
Commands::Check {
file,
json,
+11 -32
View File
@@ -833,28 +833,22 @@ fn artifact_execute(params: &Value) -> Result<Value, Value> {
let denied: Vec<String> = artifact.effects.values().into_iter().filter(|effect| effect != "pure" && !allowed.contains(&effect.as_str())).collect();
if !denied.is_empty() { return Err(json!({"code":"artifact.effect_denied","message":"效果策略拒绝执行","denied":denied,"effects":artifact.effects.values()})); }
let path = compilation.semantics.root.join(&artifact.source.file);
let module = load::load_module(&path).map_err(|e| diagnostic_err("artifact.load", &e))?;
let input = params.get("inputs").cloned().unwrap_or_else(|| json!({}));
let object = input.as_object().ok_or_else(|| err("mlsp.bad_request", "inputs 必须是 JSON 对象"))?;
let mut args = Vec::new();
for (name, value) in object { args.push((name.clone(), crate::host::json::json_to_value(value).map_err(|e| err("mlsp.bad_input", e))?)); }
let caps = crate::host::HostCaps { fs_write: allowed.contains(&"fs.write"), exec: allowed.iter().any(|e| matches!(*e, "process.exec" | "plugin.call" | "llm.call")), net: allowed.iter().any(|e| matches!(*e, "network.read" | "network.write" | "llm.call")), plugin: allowed.contains(&"plugin.call") };
let host = crate::host::HostContext::for_capture(Some(&path), caps);
let mut interpreter = crate::interp::Interpreter::with_capture(Some(&path), false).with_host(host);
// Bind by source line / declaration identity — never by bare display_name suffix (G07).
let fun = find_function_at_line(&module.functions, artifact.source.line).ok_or_else(|| {
err(
"artifact.unresolved",
format!(
"无法在 {}:{} 定位绑定函数 {}",
artifact.source.file, artifact.source.line, artifact.display_name
),
)
})?;
let value = interpreter
.invoke_bound_function(&module, fun, &args)
.map_err(|e| diagnostic_err("artifact.execution_failed", &e))?;
let stdout = std::mem::take(&mut interpreter.captured_stdout);
// Same line identity, argument binding, and runtime as `marqdo call`.
let (value, stdout) = crate::call::execute_source_function(
&path,
artifact.source.line,
&artifact.display_name,
&args,
caps,
crate::Backend::Tree,
false,
)
.map_err(|e| diagnostic_err("artifact.execution_failed", &e))?;
Ok(json!({
"schema_version": 1,
"artifact_id": artifact.artifact_id.0,
@@ -866,21 +860,6 @@ fn artifact_execute(params: &Value) -> Result<Value, Value> {
}))
}
fn find_function_at_line<'a>(
functions: &'a [crate::ast::Function],
line: u32,
) -> Option<&'a crate::ast::Function> {
for fun in functions {
if fun.span.line == line {
return Some(fun);
}
if let Some(found) = find_function_at_line(&fun.children, line) {
return Some(found);
}
}
None
}
fn err(code: &str, message: impl Into<String>) -> Value {
json!({"code": code, "message": message.into()})
}
+64 -6
View File
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use sha2::{Digest as _, Sha256};
@@ -240,10 +240,20 @@ pub struct Compilation {
/// side-effect free: it never loads plugins, evaluates expressions or fetches
/// sources.
pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
let t_index = std::time::Instant::now();
let root = ProjectRoot::new(&options.project_root)?;
let index = ProjectIndex::build(root.clone())?;
let index_ms = t_index.elapsed().as_millis();
compile_index(ProjectIndex::build(root)?)
}
/// Compile `entry` and the modules it imports. Sibling files in the directory are not included.
pub fn compile_file_closure(entry: &Path) -> Result<Compilation> {
let files = import_closure(entry)?;
let ancestor = common_ancestor(&files)?;
let root = ProjectRoot::new(&ancestor)?;
compile_index(ProjectIndex::from_files(root, files)?)
}
fn compile_index(index: ProjectIndex) -> Result<Compilation> {
let root = index.root().clone();
// Reuse parsed modules from ProjectIndex — same input snapshot, no second parse (M-R5b).
let mut files = BTreeMap::new();
let mut diagnostics = Vec::new();
@@ -257,8 +267,6 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
),
);
}
let _ = index_ms; // ProjectIndex build duration (M-R5b span)
// Wire import_modules from already-parsed project files so BoundCall path
// resolve shares `resolve_for_exec` (no plugin load / no re-parse).
attach_project_imports(&mut files);
@@ -349,6 +357,56 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
})
}
fn import_closure(entry: &Path) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
fn walk(path: &Path, out: &mut Vec<PathBuf>, seen: &mut std::collections::HashSet<PathBuf>) -> Result<()> {
if !path.is_file() {
return Ok(());
}
let canon = path.canonicalize().with_context(|| format!("resolve {}", path.display()))?;
if !seen.insert(canon.clone()) {
return Ok(());
}
out.push(canon.clone());
let source = fs::read_to_string(&canon).with_context(|| format!("read {}", canon.display()))?;
let module = crate::load::parse_source_auto(&source)
.with_context(|| format!("parse {}", canon.display()))?;
let base = canon.parent().unwrap_or_else(|| Path::new("."));
for imp in &module.imports {
let dep = crate::load::resolve_import(base, &imp.path)
.with_context(|| format!("import `{}` from {}", imp.path, canon.display()))?;
walk(&dep, out, seen)?;
}
Ok(())
}
if !entry.is_file() {
bail!("call target {} is not a file", entry.display());
}
walk(entry, &mut out, &mut seen)?;
out.sort();
Ok(out)
}
fn common_ancestor(files: &[PathBuf]) -> Result<PathBuf> {
let Some(first) = files.first() else {
bail!("call target has no source files");
};
let mut ancestor = first
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
for file in files.iter().skip(1) {
while !file.starts_with(&ancestor) {
ancestor = ancestor
.parent()
.map(|p| p.to_path_buf())
.ok_or_else(|| anyhow::anyhow!("source files have no common directory"))?;
}
}
Ok(ancestor)
}
fn module_artifact(index: &ProjectIndex, module: &ModuleId, path: &Path, text: &str) -> SemanticArtifact {
let implementation = digest(normalize_source(text));
let interface = digest(module.as_str());
+2 -1
View File
@@ -16,7 +16,8 @@ pub use bind::{
};
pub use extract::{plan_pure_extract, ExtractError, ExtractPlan};
pub use ir::{
artifact_json, compile_project, semantic_generation_dir, write_semantic_projections, ArtifactId,
artifact_json, compile_file_closure, compile_project, semantic_generation_dir,
write_semantic_projections, ArtifactId,
BoundCall, CompileOptions, Compilation, Digest, DynamicCall, EffectSet, LockMode,
SemanticArtifact, SemanticProject,
};
+6 -1
View File
@@ -119,8 +119,13 @@ pub struct ProjectIndex {
impl ProjectIndex {
pub fn build(root: ProjectRoot) -> Result<Self> {
let project_id = project_id(root.path());
let files = root.source_files()?;
Self::from_files(root, files)
}
/// Index exactly `files` (already chosen by the caller). Paths must sit under `root`.
pub fn from_files(root: ProjectRoot, files: Vec<PathBuf>) -> Result<Self> {
let project_id = project_id(root.path());
let mut modules = BTreeMap::new();
let mut path_to_module = BTreeMap::new();
let mut symbols = Vec::new();
+11
View File
@@ -0,0 +1,11 @@
# 甲
## 加法
*[计算结果](1)*
# 乙
## 加法
*[计算结果](2)*
+11
View File
@@ -0,0 +1,11 @@
# 校验
## 加一
对于输入变量`n`,期望是数字。
| 参数 | 类型 | 说明 |
| --- | --- | --- |
| n | 数值 | 输入值 |
*[结果](n + 1)*
+13
View File
@@ -0,0 +1,13 @@
# 危险
## 写入
> fs.write_text path=sent.txt text=no
*None*
## 联网
> net.http_post url="http://127.0.0.1:9/nope" body="{}"
*None*
+5
View File
@@ -0,0 +1,5 @@
## 加一
给定`n`。
*[结果](n + 1)*
+17
View File
@@ -0,0 +1,17 @@
---
import:
inc: inc.mq.md
---
# main
*0*
# 包装
## 再加一
给定`n`。
**结果 = [调用增量](inc.加一(n=n))**
*结果*
+11
View File
@@ -0,0 +1,11 @@
# main
*0*
# 计算器
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
+14
View File
@@ -0,0 +1,14 @@
---
runtime: markdown
tools: 计算器.加法
---
# 计算器
这份文件不是 SKILL。`runtime` 和 `tools` 不参与调用。
## 加法
计算两个数字`a`和`b`的和。
*[计算结果](a + b)*
+7
View File
@@ -0,0 +1,7 @@
# 点
## 横坐标
读取`self`。
*[结果](self)*
+219
View File
@@ -0,0 +1,219 @@
//! `marqdo call` runs one function. These tests start the real binary.
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
fn bin() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn run(args: &[&str]) -> std::process::Output {
Command::new(bin())
.args(args)
.current_dir(root())
.output()
.expect("spawn marqdo")
}
fn text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).trim().to_string()
}
fn assert_value(file: &Path, function: &str, args: &[&str], backend: &str, expect: &str) {
let file = file.to_str().unwrap();
let mut cmd = vec!["call", "--backend", backend, file, function];
cmd.extend_from_slice(args);
let out = run(&cmd);
assert_eq!(
out.status.code(),
Some(0),
"backend={backend} stdout={} stderr={}",
text(&out.stdout),
text(&out.stderr)
);
assert_eq!(text(&out.stdout), expect, "backend={backend}");
}
fn assert_code(file: &Path, function: &str, args: &[&str], code: &str) {
let file = file.to_str().unwrap();
let mut cmd = vec!["call", "--json", file, function];
cmd.extend_from_slice(args);
let out = run(&cmd);
assert_ne!(out.status.code(), Some(0), "stdout={}", text(&out.stdout));
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap_or_else(|e| {
panic!("json stdout: {e}\n{}", text(&out.stdout));
});
assert_eq!(body["ok"], false, "{body}");
assert_eq!(body["error"]["code"], code, "{body}");
}
#[test]
fn calculator_matches_the_documented_examples() {
let file = root().join("examples/calculator.mq.md");
for backend in ["tree", "bytecode"] {
assert_value(&file, "计算器.加法", &["a=2", "b=3"], backend, "5");
assert_value(&file, "计算器.加法", &["a=-2", "b=3"], backend, "1");
assert_value(&file, "计算器.乘法", &["a=4", "b=6"], backend, "24");
assert_value(&file, "计算器.乘法", &["a=0", "b=100"], backend, "0");
assert_value(&file, "加法", &["a=2", "b=3"], backend, "5");
}
}
#[test]
fn symbol_id_selects_the_same_function_on_both_backends() {
let file = root().join("examples/calculator.mq.md");
let compiled = marqdo::sema::compile_file_closure(&file).expect("compile calculator");
let artifact = compiled
.semantics
.artifacts
.iter()
.find(|artifact| artifact.display_name == "计算器.加法")
.expect("加法 artifact");
let id = artifact
.symbol_id
.as_ref()
.expect("symbol id")
.as_str()
.to_string();
let args = vec![
("a".to_string(), marqdo::value::Value::Int(2)),
("b".to_string(), marqdo::value::Value::Int(3)),
];
for backend in [marqdo::Backend::Tree, marqdo::Backend::Bytecode] {
let value = marqdo::call::call_file(&file, &id, &args, backend).unwrap_or_else(|err| {
panic!("symbol id call failed on {backend:?}: {err:#}")
});
assert_eq!(value, marqdo::value::Value::Int(5));
}
}
#[test]
fn json_envelope_and_metadata_are_not_a_skill_gate() {
let file = root().join("tests/call/metadata.mq.md");
let out = run(&[
"call",
"--json",
file.to_str().unwrap(),
"计算器.加法",
"a=2",
"b=3",
]);
assert_eq!(out.status.code(), Some(0), "{}", text(&out.stderr));
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
assert_eq!(body, serde_json::json!({"ok": true, "result": 5}));
let trailing = run(&[
"call",
file.to_str().unwrap(),
"计算器.加法",
"a=2",
"b=3",
"--backend",
"bytecode",
"--json",
]);
assert_eq!(trailing.status.code(), Some(0), "{}", text(&trailing.stderr));
let body: serde_json::Value = serde_json::from_str(&text(&trailing.stdout)).unwrap();
assert_eq!(body, serde_json::json!({"ok": true, "result": 5}));
}
#[test]
fn bytecode_does_not_run_main() {
let file = root().join("tests/call/main-split.mq.md");
for backend in ["tree", "bytecode"] {
assert_value(&file, "计算器.加法", &["a=2", "b=3"], backend, "5");
}
}
#[test]
fn missing_unknown_and_contract_args_are_structured() {
let calc = root().join("examples/calculator.mq.md");
assert_code(&calc, "没有这个函数", &[], "artifact.unresolved");
assert_code(&calc, "计算器.加法", &["a=2"], "call.missing_arg");
assert_code(
&calc,
"计算器.加法",
&["a=2", "b=3", "c=1"],
"call.unknown_arg",
);
let contract = root().join("tests/call/contract.mq.md");
assert_code(&contract, "校验.加一", &["n=True"], "contract.arg_mismatch");
assert_value(&contract, "校验.加一", &["n=3"], "tree", "4");
}
#[test]
fn same_short_name_is_ambiguous() {
let file = root().join("tests/call/ambiguous.mq.md");
assert_code(&file, "加法", &[], "artifact.ambiguous");
assert_value(&file, "甲.加法", &[], "tree", "1");
assert_value(&file, "乙.加法", &[], "bytecode", "2");
}
#[test]
fn instance_method_is_refused() {
let file = root().join("tests/call/method.mq.md");
assert_code(&file, "点.横坐标", &[], "artifact.not_executable");
}
#[test]
fn import_is_executed_and_call_lib_path_stays_on_bytecode() {
let site = root().join("tests/call/import/site.mq.md");
for backend in ["tree", "bytecode"] {
assert_value(&site, "包装.再加一", &["n=4"], backend, "5");
}
let tmp = std::env::temp_dir().join(format!("mq-call-lib-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let args = tmp.join("args.json");
let emit = tmp.join("out.json");
fs::write(&args, r#"{"n":4}"#).unwrap();
let out = Command::new(bin())
.args([
"run",
site.to_str().unwrap(),
"--backend",
"bytecode",
"--call-lib-path",
"inc.加一",
"--args-json",
args.to_str().unwrap(),
"--emit-result",
emit.to_str().unwrap(),
])
.current_dir(root())
.output()
.unwrap();
assert_eq!(
out.status.code(),
Some(0),
"stderr={} stdout={}",
text(&out.stderr),
text(&out.stdout)
);
assert_eq!(fs::read_to_string(&emit).unwrap().trim(), "5");
}
#[test]
fn impure_calls_do_not_run() {
let src = root().join("tests/call/effects.mq.md");
let dir = std::env::temp_dir().join(format!("mq-call-fx-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = dir.join("effects.mq.md");
fs::copy(&src, &file).unwrap();
for function in ["危险.写入", "危险.联网"] {
let out = run(&["call", "--json", file.to_str().unwrap(), function]);
assert_ne!(out.status.code(), Some(0), "{function} {}", text(&out.stdout));
let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap();
assert_eq!(body["error"]["code"], "artifact.effect_denied", "{body}");
}
assert!(
!dir.join("sent.txt").exists(),
"denied write must not create sent.txt"
);
}
+58
View File
@@ -1417,6 +1417,56 @@ fn m05_skill_front_has_occlusion_core_not_classic_index() {
root.join("skills/marqdo/migration-classic.md").is_file(),
"Classic rules must live in migration-classic.md"
);
for rel in ["skills/marqdo/SKILL.md", ".cursor/skills/marqdo/SKILL.md"] {
let text = std::fs::read_to_string(root.join(rel)).unwrap();
let core = text.split("## Minimal program").next().unwrap_or(&text);
assert!(
core.contains("| `**…**` | Statement") && core.contains("| `*…*` | Return |"),
"{rel} marker table must match the parser: bold statement, italic return"
);
assert!(
!core.contains("= code / return expression") && !core.contains("| `*…*` | Statement"),
"{rel} still teaches the inverted marker polarity"
);
}
let skill = std::fs::read_to_string(root.join("skills/marqdo/SKILL.md")).unwrap();
let golden = fence_after(&skill, "## Call one function");
let dir = std::env::temp_dir().join(format!("mq-skill-call-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("calculator.mq.md");
std::fs::write(&file, golden).unwrap();
let out = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"call",
file.to_str().unwrap(),
"计算器.加法",
"a=2",
"b=3",
])
.output()
.unwrap();
assert_eq!(
out.status.code(),
Some(0),
"skill golden failed\nstderr={}\nstdout={}\nsource=\n{golden}",
String::from_utf8_lossy(&out.stderr),
String::from_utf8_lossy(&out.stdout)
);
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "5");
}
fn fence_after<'a>(body: &'a str, heading: &str) -> &'a str {
let rest = body
.split_once(heading)
.unwrap_or_else(|| panic!("missing {heading}"))
.1;
let start = rest
.find("```markdown\n")
.unwrap_or_else(|| panic!("{heading} has no markdown fence"));
let rest = &rest[start + "```markdown\n".len()..];
let end = rest.find("\n```").expect("fence end");
rest[..end].trim()
}
#[test]
@@ -1643,6 +1693,14 @@ fn m05_skill_core_card_has_access_not_classic_index() {
agent.contains("## skill_core_card") && agent.contains("access(coll, key)"),
"skill_core_card must teach access()"
);
assert!(
agent.contains("Bold markers = statement; italic markers = return."),
"skill card must match parser polarity"
);
assert!(
!agent.contains("italic markers = statement"),
"skill card still teaches inverted markers"
);
assert!(
!agent.contains("never **bold** to print") || agent.contains("never use bold markers"),
"core card must not rely on conflicting bold-as-print Classic wording"
+2 -1
View File
@@ -6,6 +6,7 @@ import:
web: ext/web/web.mq.md
site: ./site.mq.md
sys: lib/sys.mq.md
json: lib/json.mq.md
---
# main
@@ -13,7 +14,7 @@ import:
**port_s = > sys.env_get name="MARQDO_SITE_PORT"**
**port = 18220**
1. `port_s`
**port = `port_s`**
**port = > json.parse text=`port_s`**
2. *
**_ = 1**
+23 -4
View File
@@ -238,6 +238,7 @@ fn mr01_dual_isolated_execute_and_short_reads() {
.env("MARQDO_WEB_PLUGIN", std::env::var_os("MARQDO_WEB_PLUGIN").unwrap())
.env("MARQDO_LLM_PLUGIN", std::env::var_os("MARQDO_LLM_PLUGIN").unwrap())
.env("MARQDO_RUNTIME_DIR", &runtime_dir)
.env("MARQDO_SITE_PORT", "18220")
.env("OPENAI_API_KEY", "mr01-key")
.stdout(Stdio::null())
.stderr(Stdio::piped())
@@ -459,9 +460,18 @@ fn disconnect_keeps_running_and_replay() {
.expect("spawn site");
let base = "http://127.0.0.1:18221";
if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(30)) {
if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(45)) {
let _ = child.kill();
panic!("site did not start for disconnect test");
let err = child
.stderr
.take()
.map(|mut s| {
let mut t = String::new();
let _ = s.read_to_string(&mut t);
t
})
.unwrap_or_default();
panic!("site did not start for disconnect test; stderr={err}");
}
let chat_url = format!("{base}/v1/chat/completions");
@@ -578,9 +588,18 @@ fn control_under_dual_execute() {
.expect("spawn site");
let base = "http://127.0.0.1:18222";
if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(30)) {
if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(45)) {
let _ = child.kill();
panic!("site did not start for control test");
let err = child
.stderr
.take()
.map(|mut s| {
let mut t = String::new();
let _ = s.read_to_string(&mut t);
t
})
.unwrap_or_default();
panic!("site did not start for control test; stderr={err}");
}
let chat_url = format!("{base}/v1/chat/completions");
+1
View File
@@ -124,6 +124,7 @@ fn mr07_supervisor_dry_run_slots_and_publish_recover() {
selection_ref: None,
capabilities_ref: None,
deadline_at: "2099-01-01T00:00:00Z".into(),
fs_root: Some(root.display().to_string()),
},
};
let a = sup.dispatch(req("a")).unwrap();