From 91d51f3f0a59695b68872ba950e144a2c44025c2 Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 12 Aug 2026 11:21:23 +0800 Subject: [PATCH] Treat bare ids as variables in italic/bold, and land table/quantum follow-ups. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prefer-var parsing in *…* / **…* (quoted strings for text), table cell expressions, digit map footnotes, and quantum steps/draw with updated golds and LLM sources. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 4 +- .cursor/skills/marqdo/examples.md | 8 +- .cursor/skills/marqdo/reference.md | 2 +- README.md | 2 +- doc/README.md | 3 +- doc/design/ext-abi.md | 1 + doc/design/ext-quantum.md | 2 +- doc/design/markdown-mapping.md | 52 ++++-- doc/design/table-cell-expressions.md | 138 ++++++++++++++ doc/roadmap/ext-quantum.md | 4 +- doc/roadmap/tables-maps-footnotes.md | 20 +- examples/quantum-bell/README.md | 10 + examples/quantum-bell/index.mq.md | 26 +++ ext/ai/agent.mq.md | 110 +++++------ ext/ai/llm.mq.md | 173 +++++++---------- ext/ai/大模型.mq.md | 177 +++++++----------- ext/ai/智能体.mq.md | 14 +- ext/quantum/quantum.mq.md | 12 +- ext/quantum/量子.mq.md | 12 +- plugins/quantum/src/draw.rs | 182 ++++++++++++++++++ plugins/quantum/src/lib.rs | 107 ++++++++++- plugins/quantum/src/sim.rs | 208 ++++++++++++++++++++- public/keywords/stdlib.mq.md | 2 +- public/structure/05-loop.mq.md | 2 +- public/structure/05-循环.mq.md | 2 +- public/structure/06-collection.mq.md | 2 +- public/structure/06-集合.mq.md | 2 +- skills/marqdo/SKILL.md | 4 +- skills/marqdo/examples.md | 8 +- skills/marqdo/reference.md | 2 +- src/ast.rs | 2 +- src/builtin.rs | 17 +- src/bytecode/vm.rs | 7 +- src/host/plugin.rs | 43 ++++- src/interp.rs | 2 +- src/parse/expr.rs | 166 ++++++++++++---- src/parse/mod.rs | 180 ++++++++++++++---- tests/ext/agent-kb-alias.mq.md | 18 +- tests/ext/agent-kb-near.mq.md | 12 +- tests/ext/agent-kb-reuse.mq.md | 2 +- tests/ext/agent-plan-decision.mq.md | 4 +- tests/ext/agent-plan-observe.mq.md | 2 +- tests/ext/llm-ctor-offline.mq.md | 11 ++ tests/ext/quantum-bell-smoke.mq.md | 7 +- tests/ext/quantum-gates-smoke.mq.md | 13 +- tests/ext/quantum-steps-smoke.mq.md | 37 ++++ tests/ext/quantum-zh-smoke.mq.md | 3 +- tests/ext/web-smoke.mq.md | 4 +- tests/ext/web-zh-smoke.mq.md | 4 +- tests/gold.rs | 82 ++++++++ tests/keywords/stdlib-more.mq.md | 2 +- tests/keywords/stdlib.mq.md | 2 +- tests/keywords/zh-builtins.mq.md | 2 +- tests/lib/subtask-child-print.mq.md | 2 +- tests/lib/subtask-child.mq.md | 2 +- tests/structure/bare-id-italic-bold.mq.md | 37 ++++ tests/structure/collection-cell-expr.mq.md | 35 ++++ tests/structure/collection-map.mq.md | 2 +- tests/structure/collection-records.mq.md | 2 +- tests/structure/collection.mq.md | 2 +- tests/structure/footnote-index.mq.md | 4 +- tests/structure/footnote-map-digits.mq.md | 18 ++ tests/structure/loop.mq.md | 2 +- 63 files changed, 1542 insertions(+), 477 deletions(-) create mode 100644 doc/design/table-cell-expressions.md create mode 100644 examples/quantum-bell/README.md create mode 100644 examples/quantum-bell/index.mq.md create mode 100644 plugins/quantum/src/draw.rs create mode 100644 tests/ext/llm-ctor-offline.mq.md create mode 100644 tests/ext/quantum-steps-smoke.mq.md create mode 100644 tests/structure/bare-id-italic-bold.mq.md create mode 100644 tests/structure/collection-cell-expr.mq.md create mode 100644 tests/structure/footnote-map-digits.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 04031bc..e367a3c 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -20,7 +20,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 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` ``, bindings `` `x` ``, foreach `` [`item`](`coll`) ``. **Complex text** uses `"..."` with escapes; bare tokens stay literal (no `\n` magic). +5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are variables (strings need `"…"` / `'…'`; ticks still ok). 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**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. 8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. @@ -34,7 +34,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | `##` … `######` | **Function / method** (nesting by heading depth). | | `` + `name` `` under heading | Parameter (optional `` `name`=default ``) | | `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). | -| `- …` inside body | Loop (`while` or `` [`item`](`coll`) ``) | +| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) | | Line `N. *` | Else arm | | `> fn args` | Call (named `k=v` or positional) | | `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) | diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index 92750a3..8889e90 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -74,7 +74,7 @@ Greeting via a nested function: |----| | 苹果 | -- [`果`](`篮子`) +- [果](篮子) > print text=`果` ``` @@ -89,13 +89,13 @@ Greeting via a nested function: |------|------| | 水果 | 蔬菜 | -*`种` = `分类`[^苹果] * +*`种` = 分类[^苹果] * > print text=`种` -*`第一` = `篮子`[^1] * +*`第一` = 篮子[^1] * ``` -One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Footnotes are 1-based on lists; map keys are header text. Foreach on a map walks **keys**. +One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Data cells are expressions (same as call-arg values): bare words, numbers, `` `var` ``, quoted strings; URLs and `gpt-4o-mini` stay text via path/hyphen folding. Footnotes: lists use 1-based digit indices; maps use key text (including digit keys like `[^00]`). Foreach on a map walks **keys**. Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index 2ea9a30..33d4ff5 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -18,7 +18,7 @@ marqdo ext remove llm|agent Diagnostics look like `path:line:col: message` (1-based line/col). -**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [`item`](`coll`) ``; identifiers in backticks. See `doc/design/markdown-mapping.md`. +**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) `` or `` - [`item`](`coll`) ``; identifiers in backticks (foreach header may omit ticks). See `doc/design/markdown-mapping.md`. Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. diff --git a/README.md b/README.md index b09b89e..93913a7 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件, | `##` … | 函数 / 方法(按标题深度嵌套) | | `` > `obj`.method … `` | 方法调用(`obj` 为带 `_type` 的 map) | | `+` / `1.` … | 函数头下 `` + `名` `` = 形参;体内 `1.` `2.` … = 分支(`N. *` = else) | -| `-` | 循环(`` - `条件` `` 或 `` - [`项`](`集合`) ``) | +| `-` | 循环(`` - `条件` `` 或 `` - [项](集合) `` / `` - [`项`](`集合`) ``) | | 表格 | 集合 | | 函数体内单独一行 `---` / `***` | **结束本函数体**(无返回值收束;见 mapping §11) | | 文件开头成对 `---` … `---` | Frontmatter(元信息 / 导入),与函数结束符消歧 | diff --git a/doc/README.md b/doc/README.md index 5962e73..d6fe598 100644 --- a/doc/README.md +++ b/doc/README.md @@ -55,7 +55,8 @@ | [roadmap/okf-near-match.md](roadmap/okf-near-match.md) | **规划:OKF 相近任务命中**(精确 sig 之外的可选软复用) | | [roadmap/agent-streaming.md](roadmap/agent-streaming.md) | **流式输出**(SSE + `complete`/`step` stream;S0–S1 已落地) | | [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **对象继承**(`# 子类 = > 父类`;I0–I2 已落地) | -| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录;T0–T4 已落地) | +| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录 / **单元格表达式 T5**) | +| [design/table-cell-expressions.md](design/table-cell-expressions.md) | **表数据单元格 = 表达式**(同调用实参值语法;Accepted) | | [roadmap/ext-web.md](roadmap/ext-web.md) | **实现路线:`ext/web`**(W0–W4;设计见 [ext-web.md](../design/ext-web.md)) | | [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) | | [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | diff --git a/doc/design/ext-abi.md b/doc/design/ext-abi.md index 8e804b6..2a80890 100644 --- a/doc/design/ext-abi.md +++ b/doc/design/ext-abi.md @@ -46,6 +46,7 @@ Plugin fn returns `0` + `*out_json` on success; non-zero + optional `*err_msg` o | `call_site` | `{path,function,line}` | Active call site | | `marqdo_skill` | string | Skill pack text | | `cwd` | string | Host `cwd` (entry file directory) for path resolution | +| `record_plot` | `{ok:true}` | Args `{svg}` + optional `path`; push SVG into host plots (view embed / CLI auto-write), same channel as math plots | Unknown names fail. Queries are only valid during a plugin function call (host sets thread-local context). diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index d0eb329..2a9a3b3 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · 实现中**(Q0–Q2:门集 + `run`;Q3+ 电路表/绘图见路线图) | +| 状态 | **Accepted · 实现中**(Q0–Q3:门集 + `run` + `steps=`/`draw`;Q4+ 见路线图) | | 日期 | 2026-08-12 | | 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [ext-web.md](ext-web.md) · [view.md](view.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | | 安装(目标) | `marqdo ext add quantum`(中英:`quantum` / `量子`) | diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md index 70a5dfc..95cf3cb 100644 --- a/doc/design/markdown-mapping.md +++ b/doc/design/markdown-mapping.md @@ -17,7 +17,11 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 2. **叙述注释**以空行分段:段首无标记 → 注释;段内续行一律注释(见 §2)。 3. **可执行**靠标记:结构标记(`#` `>` `+` `-` `1.` 表…)与 **斜体语句** / **粗体返回**。 4. **`#` = 对象/类型**,**`##`+ = 函数/方法**(嵌套按标题深度);入口优先 `# main`(见 [objects.md](objects.md))。函数体可用 `---` / `***` 或空返回收束(见 §11)。 -5. **标识符一律反引号**:凡表示变量槽位(形参、绑定、引用、遍历项、集合名)均写作 `` `名` ``,与 Markdown 无序列表/链接脱钩。 +5. **标识符默认反引号**:形参、绑定、引用写作 `` `名` ``,与 Markdown 无序列表/链接脱钩。 + **豁免:** + - foreach 头 `` - [项](集合) `` 允许裸名或反引号(可混用),推荐裸名;循环体内引用仍用 `` `名` ``。 + - 脚注取元 `` 名[^键] ``:基名在紧跟 `` [^…] `` 时可省略反引号(`` `名`[^键] `` 仍合法);链式同理。 + - **斜体语句 / 粗体返回内部**:裸标识符默认是**变量**;字符串须 `"…"` 或 `'…'`;`` `名` `` 仍合法。 --- @@ -43,7 +47,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 | `#` … `######` | **`#` = 对象/类型**(可 `# Child = > Parent`);**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) | | 函数头下 `+ `` `名` `` ` | 形参 / 构造参数(可选 `` `名`=默认值 ``) | | 体内 `1.` `2.` … | **分支**(有序列表臂;条件行或 else) | -| 体内 `-` | **循环**(`while` 条件,或 `` [`项`](`集合`) `` 遍历) | +| 体内 `-` | **循环**(`while` 条件,或 `[项](集合)` / `` [`项`](`集合`) `` 遍历) | | 分支臂头整行恰为 `*`(在 `N.` 后) | else,如 `2. *` | | `> 函数 形参=实参` 或 `> 函数 实参` | 调用(具名 / 位置,见 [call-arguments.md](call-arguments.md)) | | `` > `对象`.方法 … `` | 方法调用(实例 map 须含 `_type`) | @@ -75,7 +79,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 | `**Hello**` 表示打印 | `> print text=Hello` | | `+ `x` > 0` 作分支 | `1. `x` > 0` | | `- 谁` 作形参 | `` + `谁` `` | -| `[果](篮子)` 裸名遍历 | `` [`果`](`篮子`) `` | +| `[果](篮子)` 裸名遍历 | **仍合法**(foreach 豁免);亦可用 `` [`果`](`篮子`) `` | `print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。 @@ -86,12 +90,13 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 ### 程序语句(斜体) ```markdown -*`x` = 1* - -*`y` = `x` + 2* +*x = 1* +*y = x + 2* +*answer = ev[^message]* +*`亦可用` = 1* ``` -行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 +斜体内部:裸标识符 = 变量;字符串写 `"…"` / `'…'`。行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 ### 返回值(粗体) @@ -99,9 +104,13 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 ## 加一 + `n` +**n + 1** +**"ok"** **`n` + 1** ``` +粗体内部与斜体相同的值语法(裸词 = 变量;文本须引号)。 + ### 输出(内置函数 `print`) ```markdown @@ -227,10 +236,12 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 上例为两次独立判断(先 `a` 再 `b`),不是「四个臂的一个分支」。臂序号在同一分支内递增(`1.` → `2.` → `3.` …);**不要**在同一分支中途把序号重置为 `1.`。 ```markdown -- [`果`](`篮子`) +- [果](篮子) > print text=今天吃`果` ``` +反引号形式等价:`` - [`果`](`篮子`) ``。两侧可混用。 + `while`: ```markdown @@ -254,6 +265,18 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 | **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) | | 重复表头 | 诊断错误 | +**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。 + +```markdown +*`k` = secret * + +`cfg` = + +| api_key | model | +|---------|-------| +| `k` | gpt-4o-mini | +``` + 行向示例: ```markdown @@ -267,16 +290,19 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 *`名` = `订单`[^1][^品名] * ``` -**脚注取元**(表达式级,1-based 列表下标 / 字典键;可链式): +**脚注取元**(表达式级;可链式): ```markdown -*`第一` = `篮子`[^1] * -*`种` = `分类`[^苹果] * -*`第一种苹果` = `货架`[^苹果][^1] * +*`第一` = 篮子[^1] * # 基名可省略反引号(`[^` 已标明取元) +*`种` = 分类[^苹果] * +*`第一种苹果` = 货架[^苹果][^1] * +*`亦可用` = `分类`[^苹果] * # 反引号形式并存 ``` +- **List**:标签须为纯数字(1-based);`[^0]` / 越界 → 报错。 +- **Map**:标签为键文本(含 `"00"` 这类数字串键);缺键 → 报错。同一外形按接收值类型分派,不把 map 上的 `[^1]` 当成「第 1 个条目」。 +- 基名:`` `名`[^键] `` 与 `` 名[^键] `` 等价;无 `` [^ `` 时裸词仍是**文本字面量**(不是变量)。 - 文末 `[^1]: …` 定义块仍是注释,与取元无关。 -- `[^0]`、越界、缺键 → 报错。 - foreach:`List` 遍历元素;`Map` 遍历**键**(值用脚注取)。 --- diff --git a/doc/design/table-cell-expressions.md b/doc/design/table-cell-expressions.md new file mode 100644 index 0000000..4494f97 --- /dev/null +++ b/doc/design/table-cell-expressions.md @@ -0,0 +1,138 @@ +--- +title: table cell expressions +status: Accepted +date: 2026-08-12 +related: markdown-mapping.md · roadmap/tables-maps-footnotes.md · call-arguments.md +--- + +# 表单元格表达式(T5) + +| | | +|---|---| +| 状态 | **Accepted** | +| 日期 | 2026-08-12 | +| 相关 | [markdown-mapping.md](markdown-mapping.md) · [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [call-arguments.md](call-arguments.md) | + +--- + +## 1. 问题 + +v1 把 GFM 数据单元格一律收成 **字面量**(`Int` / `Text`)。结果虽是 `Map` / `List`,却不能写: + +```markdown +`h` = + +| api_key | model | +|---------|-------| +| `api_key` | `model` | +``` + +作者只好用 `json.set` 链或 JSON 字符串拼接——这是**实现缺口**,不是「字典只能装字面量」的语义必然。 + +--- + +## 2. 锁定规则 + +### 2.1 数据单元格 = 与调用实参相同的值语法 + +每个**数据**单元格(非表头、非分隔行)按 [`parse_call_arg_value`](../../src/parse/expr.rs) 解析,再在绑定求值时执行: + +| 单元格写法 | 含义 | +|------------|------| +| `苹果` / `Alpha` | 裸词 → 文本字面量(与今日竖表兼容) | +| `42` | 整数 | +| `` `api_key` `` | 变量引用 | +| `` `a` + `b` `` | 普通表达式 | +| `True` / `假` / `None` | 布尔 / 空 | +| `"https://…"` / `".marqdo/x"` | 引号字符串(可含 `/`、插值) | +| `https://api.openai.com/v1` | **路径折叠**:无空格的 `Text/Text/…` 除法链收成整段文本(同调用实参) | +| `gpt-4o-mini` | **连字符散文**:不拆成减法(同调用实参) | +| `` /about ``、`` /chat/completions `` | 以 `/` 开头的路径散文 → 整段文本 | +| 空单元格 | 空文本 `""` | + +### 2.2 表头仍是键名文本 + +表头单元格**不**求值:键 = trim 后的表头字符串(与今日一致)。不允许 `` | `k` | `` 当动态键(v1 非目标;需要时另文)。 + +### 2.3 几何语义不变 + +竖表 / 横表单行 Map / 多行列向 Map / `@`·`行`·`row` 行向记录——**形状规则不变**;只把「单元格 → `Expr::Literal`」换成「单元格 → 完整 `Expr`」。 + +求值已由解释器对 `Expr::List` / `Expr::Map` 递归完成,字节码后端已发射列表/字典,**无需新 AST 节点**。 + +### 2.4 求值时机 + +表出现在 `` `名` = `` 右侧时,在**该绑定语句**求值:单元格内变量读**当时**环境。构造函数体里的表与语句表规则相同。 + +### 2.5 错误 + +- 单元格表达式非法 → 与别处表达式相同的 `path:line:col` 诊断(行号取该表行)。 +- 变量未定义 → 求值期报错。 +- 不引入「单元格静默当字面量」的回退(除 §2.1 已列的路径/连字符折叠,与调用实参对齐)。 + +--- + +## 3. 作者示例(目标体验) + +```markdown +*`api_key` = > sys.env_get name=OPENAI_API_KEY * +*`model` = "gpt-4o-mini" * + +`handle` = + +| api_key | base_url | model | suffix | +|---------|----------|-------|--------| +| `api_key` | https://api.openai.com/v1 | `model` | /chat/completions | +``` + +`handle` 为含运行时 `api_key` / `model` 的字典;静态 URL 与 suffix 仍可裸写(路径折叠)。 + +嵌套: + +```markdown +*`prompt` = hello * + +`msg` = + +| role | content | +|------|---------| +| user | `prompt` | + +*`messages` = > json.append list=None item=`msg` * +``` + +(列表字面量表仍可用竖表;需要「单行记录」时用横表或 `@` 行向表。) + +--- + +## 4. 兼容性 + +| 旧写法 | 行为 | +|--------|------| +| 纯中文/英文词、整数 | **不变** | +| `gpt-4o-mini`、URL、`/path` | **不变**(折叠规则与调用实参一致) | +| 真正要做除法 / 减法 | 用空格或括号:`` `n` / 2 ``、`` `a` - 1 ``;或先在表外算再 `` `x` `` 填入 | + +破坏性:几乎无。唯一需注意的是「想在单元格里写算术且两侧是裸词」——与调用实参同一套消歧。 + +--- + +## 5. 非目标(本阶段) + +- 表头动态键 +- 单元格内 `>` 调用(可用表外算完再引用) +- 单元格内多语句 / 分支 +- 把叙述区(注释段)里的 GFM 表当成可执行(仍为注释) + +--- + +## 6. 验收 + +| 项 | 标准 | +|----|------| +| 金样 | 横表单元格 `` `var` `` 读环境;竖表旧金样全绿 | +| 路径 | `https://…`、`/chat/completions`、`gpt-4o-mini` 仍为文本 | +| 扩展 | `ext/ai/llm` 构造可用表写入运行时字段,去掉无必要的 `json.set` 链 | +| 文档 | 本页 + roadmap T5 + markdown-mapping §9 同步 | + +实现跟踪见 [roadmap/tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) **T5**。 diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md index 2ca8c7b..3f66d78 100644 --- a/doc/roadmap/ext-quantum.md +++ b/doc/roadmap/ext-quantum.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Q0–Q2 已落地**(设计 Accepted;Q3+ 待做) | +| 状态 | **Q0–Q3 已落地**(设计 Accepted;Q4+ 待做) | | 日期 | 2026-08-12 | | **锁定设计** | [design/ext-quantum.md](../design/ext-quantum.md) | | 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-math.md](../design/stdlib-math.md) · [view.md](../design/view.md) | @@ -25,7 +25,7 @@ | **Q0** | CATALOG + `plugins/quantum` ping + L1 `ensure_plugin` | **done** | | **Q1** | 态向量;I/X/H/CX;`simulate` / `probabilities`;贝尔态 gold | **done** | | **Q2** | Y/Z/S/T/R\* /CZ/SWAP;`run seed=`;中英 API | **done** | -| **Q3** | `steps=` 电路表;`draw` 轨线 SVG;view `record_plot` 或值识别 | pending | +| **Q3** | `steps=` 电路表;`draw` 轨线 SVG;view `record_plot` 或值识别 | **done** | | **Q4** | 概率条 / 布洛赫;`matches_matrix`;examples + 用户文档 | pending | | **Q5** | (可选)噪声 / 更大 n —— 另文 | pending | diff --git a/doc/roadmap/tables-maps-footnotes.md b/doc/roadmap/tables-maps-footnotes.md index aa0f624..fe9170c 100644 --- a/doc/roadmap/tables-maps-footnotes.md +++ b/doc/roadmap/tables-maps-footnotes.md @@ -2,9 +2,9 @@ | | | |---|---| -| 状态 | **T0–T4 已落地** | -| 日期 | 2026-08-10 | -| 相关 | [markdown-mapping.md](../design/markdown-mapping.md) §9 · [objects.md](../design/objects.md) · [stdlib.md](../design/stdlib.md)(`lib/table`) · [keywords.md](../design/keywords.md) | +| 状态 | **T0–T5 已落地**(单元格表达式见 [table-cell-expressions.md](../design/table-cell-expressions.md)) | +| 日期 | 2026-08-12 | +| 相关 | [markdown-mapping.md](../design/markdown-mapping.md) §9 · [table-cell-expressions.md](../design/table-cell-expressions.md) · [objects.md](../design/objects.md) · [stdlib.md](../design/stdlib.md)(`lib/table`) · [keywords.md](../design/keywords.md) | | 现状金样 | [tests/structure/collection.mq.md](../../tests/structure/collection.mq.md) | --- @@ -190,16 +190,18 @@ ### 4.3 字典:按键 -键为合法脚注标签(推荐与表头一致): +键为脚注标签文本(推荐与表头一致;**允许纯数字键**,如基矢标签 `00`)。基名可写 `` `概率`[^00] `` 或 `` 概率[^00] ``(紧跟 `[^` 时可省略反引号): ```markdown *`种` = `分类`[^苹果] * +*`p00` = `概率`[^00] * > print text=`种` ``` | 规则 | 说明 | |------|------| | `[^苹果]` | 键文本 `苹果` | +| `[^00]` / `[^1]` | 键文本 `00` / `1`(**不是**「第 n 个 map 条目」) | | 含空格的键 | 允许 `[^数码用品]`;极端键用引号策略开工前定 | | 缺失键 | 报错或 `None`——建议 v1 **报错**(少静默) | @@ -213,7 +215,7 @@ ``` 从左到右:先键、再下标。 -类型不对(对 List 用键名脚注、对 Map 用纯数字脚注)→ 诊断。 +类型不对(对 List 用非数字键名脚注)→ 诊断。Map 上的纯数字标签按**键名**解析。 ### 4.5 与 GFM「定义脚注」正文 @@ -236,7 +238,7 @@ ## 5. foreach 与字典 -今日:`` [`果`](`篮子`) `` 遍历列表。 +今日:`` [果](篮子) `` / `` [`果`](`篮子`) `` 遍历列表(裸名与反引号均可)。 扩展草案: @@ -255,8 +257,9 @@ T0 横表单行 → Map;金样;竖表回归 ✅ T1 横表多行 → Map of List(列向);嵌套金样 ✅ T2 脚注取元:List [^n]、Map [^键]、链式 ✅ -T3 文档:markdown-mapping §9;Skill / examples;table 库 ✅(本批) +T3 文档:markdown-mapping §9;Skill / examples;table 库 ✅ T4 行向记录表:首列 `@` / `行` / `row` ✅ +T5 数据单元格 = 表达式(同调用实参值语法) ✅ ``` 验收: @@ -264,7 +267,8 @@ T4 行向记录表:首列 `@` / `行` / `row` ✅ 1. `tests/structure/collection.mq.md` 行为不变。 2. 新金样:`collection-map.mq.md`、`collection-map-list.mq.md`、`footnote-index.mq.md`。 3. 错误下标 / 缺键带 `line:col`。 -4. 双后端(tree / bytecode)一致。 +4. 双后端(tree / bytecode)一致。 +5. **T5:** 单元格 `` `var` `` / 算术;URL 与 `gpt-4o-mini` 仍为文本;设计见 [table-cell-expressions.md](../design/table-cell-expressions.md)。 --- diff --git a/examples/quantum-bell/README.md b/examples/quantum-bell/README.md new file mode 100644 index 0000000..242f760 --- /dev/null +++ b/examples/quantum-bell/README.md @@ -0,0 +1,10 @@ +# quantum-bell + +Bell |Φ⁺⟩ via `ext/quantum` circuit table + draw. + +```bash +cargo build -p marqdo_plugin_quantum +marqdo run examples/quantum-bell/index.mq.md +``` + +Writes `bell.svg` next to the program (sandbox cwd). diff --git a/examples/quantum-bell/index.mq.md b/examples/quantum-bell/index.mq.md new file mode 100644 index 0000000..f77f206 --- /dev/null +++ b/examples/quantum-bell/index.mq.md @@ -0,0 +1,26 @@ +--- +title: Bell state +description: H then CX; probabilities ≈ 1/2; circuit SVG. +> ext/quantum/quantum.mq.md +> lib/math.mq.md +> lib/json.mq.md +--- + +# Bell |Φ+⟩ + +H on qubit 0, then CNOT(0→1). Ideal measurement: |00⟩ and |11⟩ each with probability 1/2. + +# main + +`steps` = + +| step | gate | qubits | +|------|------|--------| +| 1 | H | 0 | +| 2 | CX | 0,1 | + +*`qc` = > quantum.circuit qubits=2 steps=`steps` * +*`p` = > `qc`.probabilities * +*`_` = > `qc`.draw path=bell.svg * + +> print text=`p` diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index 8d211b4..a440287 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -40,7 +40,7 @@ Assemble a readable prompt: standing, task, tools, call site, source, skill, and *`f` = > json.get value=`esc` key=f * *`g` = > json.get value=`esc` key=g * -*`p` = You are a Marqdo agent. The runbook source is your ground truth — code is documentation. * +*`p` = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation." * *`p` = `p` + `a` + `up` + `b` + `task_s` + `c` + `tools_s` + `g` + `d` + `site_s` + `e` + `src` + `f` + `skill` * **`p`** @@ -90,7 +90,7 @@ Allowlist check, then invoke the runbook `##` via `lib/subtask` (`spawn fn=` → *`id` = > subtask.spawn fn=`name` * **> subtask.wait id=`id`** 2. * - *`msg` = Tool not allowed: * + *`msg` = "Tool not allowed:" * **`msg` + `name`** ## render_workbook_skeleton @@ -478,7 +478,7 @@ Write a scratch tool workbook under `.marqdo/agent-runs/tools/.mq.md`. *`esc` = > json.parse text={"a":".marqdo/agent-runs/tools/","b":".mq.md"} * *`a` = > json.get value=`esc` key=a * *`b` = > json.get value=`esc` key=b * -*`dir` = .marqdo/agent-runs/tools * +*`dir` = ".marqdo/agent-runs/tools" * > fs.make_dir path=`dir` *`path` = `a` + `name` + `b` * > fs.write_text path=`path` text=`text` @@ -654,7 +654,7 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`). 1. `head` == lib **> run_lib_call name=`name` reply=`reply`** 2. * - *`msg` = Parent tool not allowed: * + *`msg` = "Parent tool not allowed:" * **`msg` + `name`** --- @@ -860,25 +860,25 @@ Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继 *`_` = 1* 1. `found` == DONE - **DONE** + **"DONE"** 2. `found` == CONTINUE - **CONTINUE** + **"CONTINUE"** 3. `found` == RUN - **RUN** + **"RUN"** 4. `found` == REUSE - **REUSE** + **"REUSE"** 5. `found` == NEW - **NEW** + **"NEW"** 6. `found` == 完成 - **DONE** + **"DONE"** 7. `found` == 继续 - **CONTINUE** + **"CONTINUE"** 8. `found` == 运行 - **RUN** + **"RUN"** 9. `found` == 复用 - **REUSE** + **"REUSE"** 10. `found` == 新建 - **NEW** + **"NEW"** 11. * **`found`** @@ -956,7 +956,7 @@ Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical `sco *`row` = `slug` + `sep` + `title` * *`lines` = > json.append list=`lines` item=`row` * *`catalog` = > join value=`lines` sep=`nl` * -*`p` = Soft-match: same task intent? * +*`p` = "Soft-match: same task intent?" * **`p` + `a` + `goal` + `b` + `catalog` + `c`** --- @@ -1041,10 +1041,10 @@ Parent Plan-and-Move prompt. Short protocol only — no long monologues. *`f` = > json.get value=`esc` key=f * 1. `phase` == decompose *`e` = > json.get value=`esc` key=e_dec * - *`p` = Plan-and-Move: decompose before first run. * + *`p` = "Plan-and-Move: decompose before first run." * 2. * *`e` = > json.get value=`esc` key=e_rev * - *`p` = Plan-and-Move: revise after child run. * + *`p` = "Plan-and-Move: revise after child run." * *`p` = `p` + `a` + `up` + `b` + `goal_s` + `c` + `obs_s` + `tools` + `d` + `skill` + `e` * 1. `explore_attempt` *`p` = `p` + `f` * @@ -1052,7 +1052,7 @@ Parent Plan-and-Move prompt. Short protocol only — no long monologues. *`p` = `p` + `explore_attempt` * *`p` = `p` + of * *`p` = `p` + `explore_n` * - *`p` = `p` + . Different path; prefer code when fixed. * + *`p` = `p` + ". Different path; prefer code when fixed." * 2. * *`_` = 1* **`p`** @@ -1114,7 +1114,7 @@ LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,event *`evs_all` = > plan_append_decision events=`evs_all` decision=`decision` stream=`stream` * *`left` = 0* 4. * - *`decision` = unknown* + *`decision` = "unknown"* *`left` = 0* *`out` = > json.parse text={} * @@ -1367,13 +1367,13 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st *`reply` = `tool_s`* 2. * *`task_s` = > json.stringify value=`task` * - *`fp` = The user asked: * + *`fp` = "The user asked:" * *`fp` = `fp` + `task_s` * - *`fp` = `fp` + . Tool * + *`fp` = `fp` + ". Tool" * *`fp` = `fp` + `tool_name` * - *`fp` = `fp` + ran via subtask and returned: * + *`fp` = `fp` + "ran via subtask and returned:" * *`fp` = `fp` + `tool_s` * - *`fp` = `fp` + . Reply to the user briefly. * + *`fp` = `fp` + ". Reply to the user briefly." * 1. `stream` *`evs2` = > `model`.complete prompt=`fp` stream=True echo=`echo` * *`reply` = > llm.stream_result events=`evs2` * @@ -1428,7 +1428,7 @@ Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/.mq.md 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. With `stream=True`, emit parent `delta` / `decision` / `tool_start`/`tool_end` / `round` / `done` on `events`. `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 * -*`cache` = miss* +*`cache` = "miss"* *`path` = None* *`improve` = None* *`explore` = None* @@ -1448,19 +1448,19 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` 1. `hit` *`match_kind` = > json.get value=`hit` key=match * 1. `match_kind` == alias - *`cache_label` = soft-hit* + *`cache_label` = "soft-hit"* 2. `match_kind` == canonical - *`cache_label` = soft-hit* + *`cache_label` = "soft-hit"* *`hit_slug` = > json.get value=`hit` key=slug * > agent_kb_add_alias kb_dir=`kb_dir` slug=`hit_slug` alias=`goal` 3. `match_kind` == near - *`cache_label` = soft-hit* + *`cache_label` = "soft-hit"* *`hit_slug` = > json.get value=`hit` key=slug * > agent_kb_add_alias kb_dir=`kb_dir` slug=`hit_slug` alias=`goal` 4. `match_kind` == soft - *`cache_label` = soft-hit* + *`cache_label` = "soft-hit"* 5. * - *`cache_label` = hit* + *`cache_label` = "hit"* *`lf` = > json.get value=`hit` key=llm_free * 1. `lf` *`path` = > json.get value=`hit` key=resource * @@ -1481,7 +1481,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`out` = > json.set map=`out` key=skill value=`sk` * *`st` = > json.get value=`hit` key=status * *`out` = > json.set map=`out` key=skill_status value=`st` * - *`sum` = OKF llm_free skill hit; spawned resource * + *`sum` = "OKF llm_free skill hit; spawned resource" * *`out` = > json.set map=`out` key=summary value=`sum` * *`out` = > json.set map=`out` key=observation value=`last_obs` * *`out` = > json.set map=`out` key=result value=`child_val` * @@ -1497,11 +1497,11 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`path` = None* 2. `nfiles` < `explore_n` *`explore` = 1* - *`cache` = explore* + *`cache` = "explore"* *`path` = None* *`explore_attempt` = `nfiles` + 1* 1. `explore_attempt` == 2 - *`skel_kind` = dual* + *`skel_kind` = "dual"* 2. * *`skel_kind` = `skeleton`* 3. * @@ -1515,7 +1515,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`due` = > json.get value=`rec` key=improve_due * 1. `due` *`improve` = 1* - *`cache` = improve* + *`cache` = "improve"* 2. * *`cache` = `cache_label`* *`out` = > json.parse text={"status":"ok"} * @@ -1528,7 +1528,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`out` = > json.set map=`out` key=skill value=`sk` * *`st` = > json.get value=`hit` key=status * *`out` = > json.set map=`out` key=skill_status value=`st` * - *`sum` = OKF skill hit; spawned resource * + *`sum` = "OKF skill hit; spawned resource" * *`out` = > json.set map=`out` key=summary value=`sum` * *`out` = > json.set map=`out` key=observation value=`last_obs` * *`out` = > json.set map=`out` key=result value=`child_val` * @@ -1571,7 +1571,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`hit` = > agent_kb_lookup kb_dir=`kb_dir` slug=`reuse_slug` goal=`goal` tools=`tools` * 1. `hit` > agent_kb_add_alias kb_dir=`kb_dir` slug=`reuse_slug` alias=`goal` - *`cache_label` = soft-hit* + *`cache_label` = "soft-hit"* *`path` = > json.get value=`hit` key=resource * *`aw` = > await_workbook path=`path` * *`code` = > json.get value=`aw` key=code * @@ -1579,7 +1579,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`last_obs` = > json.get value=`aw` key=observation * 1. `code` == 0 > agent_kb_record_hit kb_dir=`kb_dir` goal=`goal` tools=`tools` improve_every=`improve_every` - *`cache` = soft-hit* + *`cache` = "soft-hit"* *`out` = > json.parse text={"status":"ok"} * *`out` = > json.set map=`out` key=status value=ok * *`out` = > json.set map=`out` key=goal value=`goal` * @@ -1590,7 +1590,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`out` = > json.set map=`out` key=skill value=`sk` * *`st` = > json.get value=`hit` key=status * *`out` = > json.set map=`out` key=skill_status value=`st` * - *`sum` = OKF soft_match REUSE; spawned resource * + *`sum` = "OKF soft_match REUSE; spawned resource" * *`out` = > json.set map=`out` key=summary value=`sum` * *`out` = > json.set map=`out` key=observation value=`last_obs` * *`out` = > json.set map=`out` key=result value=`child_val` * @@ -1616,10 +1616,10 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`_` = 1* 1. `nfiles` < `explore_n` *`explore` = 1* - *`cache` = explore* + *`cache` = "explore"* *`explore_attempt` = `nfiles` + 1* 1. `explore_attempt` == 2 - *`skel_kind` = dual* + *`skel_kind` = "dual"* 2. * *`skel_kind` = `skeleton`* 2. * @@ -1627,7 +1627,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` 4. * 1. `nfiles` < `explore_n` *`explore` = 1* - *`cache` = explore* + *`cache` = "explore"* *`explore_attempt` = `nfiles` + 1* 2. * *`_` = 1* @@ -1690,8 +1690,8 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`child_val` = None* *`done` = None* *`summary` = None* -*`status` = error* -*`err` = max_rounds exhausted * +*`status` = "error"* +*`err` = "max_rounds exhausted" * *`skip_loop` = None* > plan_echo_decompose workbook=`path` stream=`stream` echo=`echo` @@ -1721,7 +1721,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`events` = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo` * 1. `code` == 0 *`done` = 1* - *`status` = ok* + *`status` = "ok"* *`summary` = > extract_plan_summary reply=`last_reply` * *`err` = None* *`skip_loop` = 1* @@ -1729,8 +1729,8 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` *`_` = 1* 4. * *`done` = 1* - *`status` = error* - *`err` = unrecognized plan decision * + *`status` = "error"* + *`err` = "unrecognized plan decision" * *`summary` = `last_reply`* *`skip_loop` = 1* @@ -1769,10 +1769,10 @@ Deterministic success stop (loop engineering): when the child already returned a 1. `auto_done` > agent_workbook_solidify path=`path` observation=`last_obs` *`done` = 1* - *`status` = ok* - *`summary` = child returned value; solidified * + *`status` = "ok"* + *`summary` = "child returned value; solidified" * *`err` = None* - *`dec` = DONE* + *`dec` = "DONE"* *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` summary=`summary` * *`left` = 0* 2. * @@ -1784,7 +1784,7 @@ Deterministic success stop (loop engineering): when the child already returned a 1. `dec` == DONE > agent_workbook_solidify path=`path` observation=`last_obs` *`done` = 1* - *`status` = ok* + *`status` = "ok"* *`summary` = > extract_plan_summary reply=`last_reply` * *`err` = None* *`left` = 0* @@ -1794,25 +1794,25 @@ Deterministic success stop (loop engineering): when the child already returned a *`left` = `left` - 1* 2. * *`done` = 1* - *`status` = error* - *`err` = no patches applied * + *`status` = "error"* + *`err` = "no patches applied" * *`summary` = > extract_plan_summary reply=`last_reply` * *`left` = 0* 3. `dec` == RUN *`left` = `left` - 1* 4. * *`done` = 1* - *`status` = error* - *`err` = unrecognized plan decision * + *`status` = "error"* + *`err` = "unrecognized plan decision" * *`summary` = `last_reply`* *`left` = 0* 1. `status` == ok 1. `promote` *`prom` = > agent_kb_promote kb_dir=`kb_dir` goal=`goal` workbook=`path` tools=`tools` * - *`cache` = refreshed* + *`cache` = "refreshed"* 2. * - *`cache` = miss* + *`cache` = "miss"* 2. * *`_` = 1* diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md index c3334f5..922bcdb 100644 --- a/ext/ai/llm.mq.md +++ b/ext/ai/llm.mq.md @@ -16,144 +16,103 @@ Load `.env` from cwd (optional named arg `path=`). Does not override existing va ## stream_result + `events` -Reduce a `complete stream=True` event list to the final `done.result` text (or `error.message`). +Reduce a `complete stream=True` event list to the final `done.result` text (or `error.message`). Unknown event types abort. -*`answer` = "" * +*answer = "" * -- [`ev`](`events`) - *`t` = > json.get value=`ev` key=type * +- [ev](events) + *t = ev[^type] * 1. `t` == "done" - *`answer` = > json.get value=`ev` key=result * + *answer = ev[^result] * 2. `t` == "error" - *`answer` = > json.get value=`ev` key=message * - 3. * - *`_` = 1* + *answer = ev[^message] * + 3. `t` == "delta" + 4. * + > print text=ext/ai/llm: unexpected SSE event type + > print text=`t` + > sys.exit code=1 -**`answer`** +**answer** # llm -Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*` (default base OpenAI v1, model `gpt-4o-mini`). +Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*`. -*`d` = > json.parse text={"base":"https://api.openai.com/v1","model":"gpt-4o-mini","suffix":"/chat/completions","bearer":"Bearer ","p1":"{\"model\":","p2":",\"messages\":[{\"role\":\"user\",\"content\":","p3":"}]}","h1":"{\"Authorization\":","h2":"}","a1":"{\"api_key\":","a2":",\"base_url\":","a3":",\"model\":","a4":",\"suffix\":","a5":",\"bearer\":","a6":",\"p1\":","a7":",\"p2\":","a8":",\"p3\":","a9":",\"h1\":","a10":",\"h2\":","a11":"}"} * +*api_key = > sys.env_get name=OPENAI_API_KEY * +1. not `api_key` + *api_key = > sys.env_get name=MARQDO_LLM_API_KEY * -*`api_key` = > sys.env_get name=OPENAI_API_KEY * -1. `api_key` - *`_k` = 1* -2. * - *`api_key` = > sys.env_get name=MARQDO_LLM_API_KEY * -3. `api_key` - *`_k` = 1* -4. * +1. not `api_key` > print text=ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY > sys.exit code=1 -*`base_url` = > sys.env_get name=OPENAI_BASE_URL * -1. `base_url` - *`_k` = 1* -2. * - *`base_url` = > sys.env_get name=MARQDO_LLM_BASE_URL * -3. `base_url` - *`_k` = 1* -4. * - *`base_url` = > json.get value=`d` key=base * +*base_url = > sys.env_get name=OPENAI_BASE_URL * +1. not `base_url` + *base_url = > sys.env_get name=MARQDO_LLM_BASE_URL * +1. not `base_url` + *base_url = "https://api.openai.com/v1" * -*`model` = > sys.env_get name=OPENAI_MODEL * -1. `model` - *`_k` = 1* -2. * - *`model` = > sys.env_get name=MARQDO_LLM_MODEL * -3. `model` - *`_k` = 1* -4. * - *`model` = > json.get value=`d` key=model * +*model = > sys.env_get name=OPENAI_MODEL * +1. not `model` + *model = > sys.env_get name=MARQDO_LLM_MODEL * +1. not `model` + *model = "gpt-4o-mini" * -*`q_key` = > json.quote text=`api_key` * -*`q_base` = > json.quote text=`base_url` * -*`q_model` = > json.quote text=`model` * -*`suffix` = > json.get value=`d` key=suffix * -*`bearer` = > json.get value=`d` key=bearer * -*`p1` = > json.get value=`d` key=p1 * -*`p2` = > json.get value=`d` key=p2 * -*`p3` = > json.get value=`d` key=p3 * -*`h1` = > json.get value=`d` key=h1 * -*`h2` = > json.get value=`d` key=h2 * -*`q_suf` = > json.quote text=`suffix` * -*`q_br` = > json.quote text=`bearer` * -*`q_p1` = > json.quote text=`p1` * -*`q_p2` = > json.quote text=`p2` * -*`q_p3` = > json.quote text=`p3` * -*`q_h1` = > json.quote text=`h1` * -*`q_h2` = > json.quote text=`h2` * -*`a1` = > json.get value=`d` key=a1 * -*`a2` = > json.get value=`d` key=a2 * -*`a3` = > json.get value=`d` key=a3 * -*`a4` = > json.get value=`d` key=a4 * -*`a5` = > json.get value=`d` key=a5 * -*`a6` = > json.get value=`d` key=a6 * -*`a7` = > json.get value=`d` key=a7 * -*`a8` = > json.get value=`d` key=a8 * -*`a9` = > json.get value=`d` key=a9 * -*`a10` = > json.get value=`d` key=a10 * -*`a11` = > json.get value=`d` key=a11 * -*`raw` = `a1` + `q_key` + `a2` + `q_base` + `a3` + `q_model` + `a4` + `q_suf` + `a5` + `q_br` + `a6` + `q_p1` + `a7` + `q_p2` + `a8` + `q_p3` + `a9` + `q_h1` + `a10` + `q_h2` + `a11` * -**> json.parse text=`raw`** +`h` = + +| api_key | base_url | model | suffix | bearer | +|---------|----------|-------|--------|--------| +| `api_key` | `base_url` | `model` | /chat/completions | "Bearer " | + +**h** ## complete + `prompt` + `stream`=False + `echo`=False -Chat completion using `self` / `自` handle fields. +Chat completion using `self` handle fields. -With `stream=True`, returns a list of event maps (`delta` / `done` / `error`) for foreach; default remains a single answer string. Optional `echo=True` prints deltas to stdout while the SSE body is read. +Wire body is `{model, messages:[{role,content}], stream?}` — message row is a table; `stream` flag still needs a map set when true. Headers use one `json.set` because a 1-col table is a List, not a Map. -*`api_key` = > json.get value=`self` key=api_key * -*`base_url` = > json.get value=`self` key=base_url * -*`model` = > json.get value=`self` key=model * -*`suffix` = > json.get value=`self` key=suffix * -*`bearer` = > json.get value=`self` key=bearer * -*`p1` = > json.get value=`self` key=p1 * -*`p2` = > json.get value=`self` key=p2 * -*`p3` = > json.get value=`self` key=p3 * -*`h1` = > json.get value=`self` key=h1 * -*`h2` = > json.get value=`self` key=h2 * -*`url` = `base_url` + `suffix` * -*`auth` = `bearer` + `api_key` * -*`q_auth` = > json.quote text=`auth` * -*`hdr_raw` = `h1` + `q_auth` + `h2` * -*`headers` = > json.parse text=`hdr_raw` * -*`q_model` = > json.quote text=`model` * -*`q_prompt` = > json.quote text=`prompt` * +*url = self[^base_url] + self[^suffix] * +*auth = self[^bearer] + self[^api_key] * +*headers = > json.set map=None key=Authorization value=`auth` * + +`msg` = + +| role | content | +|------|---------| +| user | `prompt` | + +*messages = > json.append list=None item=`msg` * + +`req` = + +| model | messages | +|-------|----------| +| self[^model] | `messages` | 1. `stream` - *`p3s` = "}],\"stream\":true}" * - *`body` = `p1` + `q_model` + `p2` + `q_prompt` + `p3s` * - *`resp` = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo` * - *`status` = > json.get value=`resp` key=status * - *`events` = > json.get value=`resp` key=events * - 1. `status` == 200 - **`events`** + *req = > json.set map=`req` key=stream value=True * + *body = > json.stringify value=`req` * + *resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo` * + 1. resp[^status] == 200 + **resp[^events]** 2. * > print text=ext/ai/llm: HTTP error (stream) - > print text=`status` + > print text=resp[^status] > sys.exit code=1 2. * - *`body` = `p1` + `q_model` + `p2` + `q_prompt` + `p3` * - *`resp` = > net.http_post url=`url` body=`body` headers=`headers` * - *`status` = > json.get value=`resp` key=status * - *`raw` = > json.get value=`resp` key=body * - 1. `status` == 200 - *`data` = > json.parse text=`raw` * - *`choices` = > json.get value=`data` key=choices * - *`first` = > at value=`choices` index=0 * - *`message` = > json.get value=`first` key=message * - *`content` = > json.get value=`message` key=content * - **`content`** + *body = > json.stringify value=`req` * + *resp = > net.http_post url=`url` body=`body` headers=`headers` * + 1. resp[^status] == 200 + *data = > json.parse text=resp[^body] * + **data[^choices][^1][^message][^content]** 2. * > print text=ext/ai/llm: HTTP error - > print text=`status` - > print text=`raw` + > print text=resp[^status] + > print text=resp[^body] > sys.exit code=1 --- diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md index 2202ce0..00ab50e 100644 --- a/ext/ai/大模型.mq.md +++ b/ext/ai/大模型.mq.md @@ -9,151 +9,110 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. ## 加载环境 + `路径`=None -从工作目录加载 `.env`(可选具名实参 `路径=`)。不覆盖已有变量。 +从工作目录加载 `.env`(可选命名实参 `路径=`)。不覆盖已有变量。 **> 系统.加载环境 路径=`路径`** ## 流式结果 + `事件` -把 `运行 流式=真` 的事件列表收成最终 `done.result`(或 `error.message`)。 +把 `运行 流式=真` 的事件列表收成最终 `done.result`(或 `error.message`)。未知事件类型直接失败。 -*`answer` = "" * +*answer = "" * -- [`ev`](`事件`) - *`t` = > json.get value=`ev` key=type * +- [ev](事件) + *t = ev[^type] * 1. `t` == "done" - *`answer` = > json.get value=`ev` key=result * + *answer = ev[^result] * 2. `t` == "error" - *`answer` = > json.get value=`ev` key=message * - 3. * - *`_` = 1* + *answer = ev[^message] * + 3. `t` == "delta" + 4. * + > 打印 内容=ext/ai/大模型: 未预期的 SSE 事件类型 + > 打印 内容=`t` + > 系统.退出 码=1 -**`answer`** +**answer** # 大模型 -从 `OPENAI_*` / `MARQDO_LLM_*` 构造句柄(默认 OpenAI v1 + `gpt-4o-mini`)。 +从 `OPENAI_*` / `MARQDO_LLM_*` 构造句柄。 -*`d` = > json.parse text={"base":"https://api.openai.com/v1","model":"gpt-4o-mini","suffix":"/chat/completions","bearer":"Bearer ","p1":"{\"model\":","p2":",\"messages\":[{\"role\":\"user\",\"content\":","p3":"}]}","h1":"{\"Authorization\":","h2":"}","a1":"{\"api_key\":","a2":",\"base_url\":","a3":",\"model\":","a4":",\"suffix\":","a5":",\"bearer\":","a6":",\"p1\":","a7":",\"p2\":","a8":",\"p3\":","a9":",\"h1\":","a10":",\"h2\":","a11":"}"} * +*api_key = > 系统.取环境 名=OPENAI_API_KEY * +1. 非 `api_key` + *api_key = > 系统.取环境 名=MARQDO_LLM_API_KEY * -*`api_key` = > 系统.取环境 名=OPENAI_API_KEY * -1. `api_key` - *`_k` = 1* -2. * - *`api_key` = > 系统.取环境 名=MARQDO_LLM_API_KEY * -3. `api_key` - *`_k` = 1* -4. * +1. 非 `api_key` > 打印 内容=ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY > 系统.退出 码=1 -*`base_url` = > 系统.取环境 名=OPENAI_BASE_URL * -1. `base_url` - *`_k` = 1* -2. * - *`base_url` = > 系统.取环境 名=MARQDO_LLM_BASE_URL * -3. `base_url` - *`_k` = 1* -4. * - *`base_url` = > json.get value=`d` key=base * +*base_url = > 系统.取环境 名=OPENAI_BASE_URL * +1. 非 `base_url` + *base_url = > 系统.取环境 名=MARQDO_LLM_BASE_URL * +1. 非 `base_url` + *base_url = "https://api.openai.com/v1" * -*`model` = > 系统.取环境 名=OPENAI_MODEL * -1. `model` - *`_k` = 1* -2. * - *`model` = > 系统.取环境 名=MARQDO_LLM_MODEL * -3. `model` - *`_k` = 1* -4. * - *`model` = > json.get value=`d` key=model * +*model = > 系统.取环境 名=OPENAI_MODEL * +1. 非 `model` + *model = > 系统.取环境 名=MARQDO_LLM_MODEL * +1. 非 `model` + *model = "gpt-4o-mini" * -*`q_key` = > json.quote text=`api_key` * -*`q_base` = > json.quote text=`base_url` * -*`q_model` = > json.quote text=`model` * -*`suffix` = > json.get value=`d` key=suffix * -*`bearer` = > json.get value=`d` key=bearer * -*`p1` = > json.get value=`d` key=p1 * -*`p2` = > json.get value=`d` key=p2 * -*`p3` = > json.get value=`d` key=p3 * -*`h1` = > json.get value=`d` key=h1 * -*`h2` = > json.get value=`d` key=h2 * -*`q_suf` = > json.quote text=`suffix` * -*`q_br` = > json.quote text=`bearer` * -*`q_p1` = > json.quote text=`p1` * -*`q_p2` = > json.quote text=`p2` * -*`q_p3` = > json.quote text=`p3` * -*`q_h1` = > json.quote text=`h1` * -*`q_h2` = > json.quote text=`h2` * -*`a1` = > json.get value=`d` key=a1 * -*`a2` = > json.get value=`d` key=a2 * -*`a3` = > json.get value=`d` key=a3 * -*`a4` = > json.get value=`d` key=a4 * -*`a5` = > json.get value=`d` key=a5 * -*`a6` = > json.get value=`d` key=a6 * -*`a7` = > json.get value=`d` key=a7 * -*`a8` = > json.get value=`d` key=a8 * -*`a9` = > json.get value=`d` key=a9 * -*`a10` = > json.get value=`d` key=a10 * -*`a11` = > json.get value=`d` key=a11 * -*`raw` = `a1` + `q_key` + `a2` + `q_base` + `a3` + `q_model` + `a4` + `q_suf` + `a5` + `q_br` + `a6` + `q_p1` + `a7` + `q_p2` + `a8` + `q_p3` + `a9` + `q_h1` + `a10` + `q_h2` + `a11` * -**> json.parse text=`raw`** +`h` = + +| api_key | base_url | model | suffix | bearer | +|---------|----------|-------|--------|--------| +| `api_key` | `base_url` | `model` | /chat/completions | "Bearer " | + +**h** ## 运行 + `提示` + `流式`=False + `打印增量`=False -使用 `自` / `self` 句柄字段做聊天补全。 +使用 `自` 句柄字段做聊天补全。 -`流式=真` 时返回事件列表(`delta` / `done` / `error`),默认同今日返回整段文本。`打印增量=真` 边读边打印。 +线上 body 为 `{model, messages:[{role,content}], stream?}`——消息行用表;`流式` 为真时仍需一次 `json.set`。单键 headers 用一次 `json.set`(单列表是 List 不是 Map)。 -*`api_key` = > json.get value=`自` key=api_key * -*`base_url` = > json.get value=`自` key=base_url * -*`model` = > json.get value=`自` key=model * -*`suffix` = > json.get value=`自` key=suffix * -*`bearer` = > json.get value=`自` key=bearer * -*`p1` = > json.get value=`自` key=p1 * -*`p2` = > json.get value=`自` key=p2 * -*`p3` = > json.get value=`自` key=p3 * -*`h1` = > json.get value=`自` key=h1 * -*`h2` = > json.get value=`自` key=h2 * -*`url` = `base_url` + `suffix` * -*`auth` = `bearer` + `api_key` * -*`q_auth` = > json.quote text=`auth` * -*`hdr_raw` = `h1` + `q_auth` + `h2` * -*`headers` = > json.parse text=`hdr_raw` * -*`q_model` = > json.quote text=`model` * -*`q_prompt` = > json.quote text=`提示` * +*url = 自[^base_url] + 自[^suffix] * +*auth = 自[^bearer] + 自[^api_key] * +*headers = > json.set map=None key=Authorization value=`auth` * + +`msg` = + +| role | content | +|------|---------| +| user | `提示` | + +*messages = > json.append list=None item=`msg` * + +`req` = + +| model | messages | +|-------|----------| +| 自[^model] | `messages` | 1. `流式` - *`p3s` = "}],\"stream\":true}" * - *`body` = `p1` + `q_model` + `p2` + `q_prompt` + `p3s` * - *`resp` = > 网络.提交流式 地址=`url` 内容=`body` headers=`headers` 打印增量=`打印增量` * - *`status` = > json.get value=`resp` key=status * - *`events` = > json.get value=`resp` key=events * - 1. `status` == 200 - **`events`** + *req = > json.set map=`req` key=stream value=True * + *body = > json.stringify value=`req` * + *resp = > 网络.提交流式 地址=`url` 内容=`body` headers=`headers` 打印增量=`打印增量` * + 1. resp[^status] == 200 + **resp[^events]** 2. * > 打印 内容=ext/ai/大模型: HTTP 错误(流式) - > 打印 内容=`status` + > 打印 内容=resp[^status] > 系统.退出 码=1 2. * - *`body` = `p1` + `q_model` + `p2` + `q_prompt` + `p3` * - *`resp` = > 网络.提交 地址=`url` 内容=`body` headers=`headers` * - *`status` = > json.get value=`resp` key=status * - *`raw` = > json.get value=`resp` key=body * - 1. `status` == 200 - *`data` = > json.parse text=`raw` * - *`choices` = > json.get value=`data` key=choices * - *`first` = > at value=`choices` index=0 * - *`message` = > json.get value=`first` key=message * - *`content` = > json.get value=`message` key=content * - **`content`** + *body = > json.stringify value=`req` * + *resp = > 网络.提交 地址=`url` 内容=`body` headers=`headers` * + 1. resp[^status] == 200 + *data = > json.parse text=resp[^body] * + **data[^choices][^1][^message][^content]** 2. * > 打印 内容=ext/ai/大模型: HTTP 错误 - > 打印 内容=`status` - > 打印 内容=`raw` + > 打印 内容=resp[^status] + > 打印 内容=resp[^body] > 系统.退出 码=1 --- @@ -163,6 +122,6 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. + `流式`=False + `打印增量`=False -`运行` 的别名。 +运行 的别名。 **> `自`.运行 提示=`提示` 流式=`流式` 打印增量=`打印增量`** diff --git a/ext/ai/智能体.mq.md b/ext/ai/智能体.mq.md index 36f5517..5f831c3 100644 --- a/ext/ai/智能体.mq.md +++ b/ext/ai/智能体.mq.md @@ -39,7 +39,7 @@ description: 文档驱动智能体 — 单步 / 多步;工具经 lib/子任务 *`f` = > json.get value=`esc` key=f * *`g` = > json.get value=`esc` key=g * -*`p` = You are a Marqdo agent. The runbook source is your ground truth — code is documentation. * +*`p` = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation." * *`p` = `p` + `a` + `up` + `b` + `task_s` + `c` + `tools_s` + `g` + `d` + `site_s` + `e` + `src` + `f` + `skill` * **`p`** @@ -89,7 +89,7 @@ description: 文档驱动智能体 — 单步 / 多步;工具经 lib/子任务 *`id` = > 子任务.启动 函数=`名` * **> 子任务.等待 id=`id`** 2. * - *`msg` = Tool not allowed: * + *`msg` = "Tool not allowed:" * **`msg` + `名`** # 智能体 @@ -135,7 +135,7 @@ description: 文档驱动智能体 — 单步 / 多步;工具经 lib/子任务 原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 **map**(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 -`流式=真` 时走 SSE;`打印增量=真` 边读边打印。返回 map 仍是最终 `result` 文本。 +流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。 *`ctx` = > 构建单步上下文 智能体=`自` 任务=`任务` * *`id` = > json.get value=`自` key=id * @@ -170,13 +170,13 @@ description: 文档驱动智能体 — 单步 / 多步;工具经 lib/子任务 *`reply` = `tool_s`* 2. * *`task_s` = > json.stringify value=`任务` * - *`fp` = The user asked: * + *`fp` = "The user asked:" * *`fp` = `fp` + `task_s` * - *`fp` = `fp` + . Tool * + *`fp` = `fp` + ". Tool" * *`fp` = `fp` + `tool_name` * - *`fp` = `fp` + ran via subtask and returned: * + *`fp` = `fp` + "ran via subtask and returned:" * *`fp` = `fp` + `tool_s` * - *`fp` = `fp` + . Reply to the user briefly. * + *`fp` = `fp` + ". Reply to the user briefly." * 1. `流式` *`evs2` = > `model`.运行 提示=`fp` 流式=真 打印增量=`打印增量` * *`reply` = > 大模型.流式结果 事件=`evs2` * diff --git a/ext/quantum/quantum.mq.md b/ext/quantum/quantum.mq.md index 853e174..5c7de39 100644 --- a/ext/quantum/quantum.mq.md +++ b/ext/quantum/quantum.mq.md @@ -20,11 +20,12 @@ Load the ABI v2 `quantum` plugin once. # circuit + `qubits`=1 + + `steps`=None -State-vector circuit (default |0…0⟩). Methods append gates and return an updated handle. +State-vector circuit (default |0…0⟩). Optional `steps=` gate table (column or row records). Methods append gates and return an updated handle. > ensure_plugin -**> quantum_circuit_new qubits=`qubits`** +**> quantum_circuit_new qubits=`qubits` steps=`steps`** ## h + `qubit`=0 @@ -116,3 +117,10 @@ Return map of basis label → probability (qubit 0 = rightmost bit). Sample computational-basis shots (deterministic with `seed=`). **> quantum_run circuit=`self` shots=`shots` seed=`seed`** + +## draw + + `path`=None + +Circuit rail SVG (`quantum_svg`). Records into view/CLI plots via host `record_plot`. + +**> quantum_draw_circuit circuit=`self` path=`path`** diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md index 4794a1b..de4ffef 100644 --- a/ext/quantum/量子.mq.md +++ b/ext/quantum/量子.mq.md @@ -20,11 +20,12 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 # 电路 + `比特数`=1 + + `步骤`=None -状态向量电路(默认 |0…0⟩)。方法追加门并返回更新后的句柄。 +状态向量电路(默认 |0…0⟩)。可选 `步骤=` 门序列表。方法追加门并返回更新后的句柄。 > 确保插件 -**> quantum_circuit_new qubits=`比特数`** +**> quantum_circuit_new qubits=`比特数` steps=`步骤`** ## 哈达玛 + `比特`=0 @@ -114,3 +115,10 @@ description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 计算基采样(`种子=` 可复现)。 **> quantum_run circuit=`self` shots=`次数` seed=`种子`** + +## 绘图 + + `路径`=None + +电路轨线 SVG(`quantum_svg`)。经 host `record_plot` 进入 view/CLI plots。 + +**> quantum_draw_circuit circuit=`self` path=`路径`** diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs new file mode 100644 index 0000000..0a748c7 --- /dev/null +++ b/plugins/quantum/src/draw.rs @@ -0,0 +1,182 @@ +//! Circuit rail SVG (design §7.4). + +use serde_json::Value; + +use crate::sim::{parse_ops, Op}; + +const COL_W: f64 = 56.0; +const ROW_H: f64 = 40.0; +const PAD_X: f64 = 48.0; +const PAD_Y: f64 = 24.0; +const WIRE: &str = "#1a1a1a"; +const BOX: &str = "#f7f4ef"; +const STROKE: &str = "#1a1a1a"; + +fn esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +fn gate_label(op: &Op) -> String { + match op.gate.as_str() { + "RX" => op + .theta + .map(|t| format!("Rx({t:.2})")) + .unwrap_or_else(|| "Rx".into()), + "RY" => op + .theta + .map(|t| format!("Ry({t:.2})")) + .unwrap_or_else(|| "Ry".into()), + "RZ" => op + .theta + .map(|t| format!("Rz({t:.2})")) + .unwrap_or_else(|| "Rz".into()), + "HADAMARD" => "H".into(), + "CNOT" | "CN" => "CX".into(), + other => other.to_string(), + } +} + +fn y_of(q: usize) -> f64 { + PAD_Y + q as f64 * ROW_H +} + +fn x_of(col: usize) -> f64 { + PAD_X + col as f64 * COL_W +} + +/// Draw a circuit diagram as standalone SVG. +pub fn circuit_svg(circuit: &Value) -> Result { + let qubits = circuit + .get("qubits") + .or_else(|| circuit.get("比特数")) + .and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64))) + .ok_or_else(|| "circuit missing qubits".to_string())? as usize; + let ops = parse_ops(circuit)?; + let cols = ops.len().max(1); + let width = PAD_X + cols as f64 * COL_W + 32.0; + let height = PAD_Y * 2.0 + (qubits.saturating_sub(1).max(0) as f64) * ROW_H + 8.0; + let height = height.max(PAD_Y * 2.0 + 24.0); + + let mut body = String::new(); + // wires + for q in 0..qubits { + let y = y_of(q); + body.push_str(&format!( + r#""#, + x0 = 8.0, + x1 = width - 8.0, + y = y, + )); + body.push_str(&format!( + r#"q{q}"#, + ty = y + 4.0, + )); + } + + for (col, op) in ops.iter().enumerate() { + let x = x_of(col); + match op.gate.as_str() { + "CX" | "CNOT" | "CN" if op.qubits.len() >= 2 => { + draw_cx(&mut body, x, op.qubits[0], op.qubits[1]); + } + "CZ" if op.qubits.len() >= 2 => { + draw_cz(&mut body, x, op.qubits[0], op.qubits[1]); + } + "SWAP" if op.qubits.len() >= 2 => { + draw_swap(&mut body, x, op.qubits[0], op.qubits[1]); + } + _ => { + let q = *op.qubits.first().unwrap_or(&0); + draw_box(&mut body, x, q, &gate_label(op)); + } + } + } + + Ok(format!( + r#"{body}"#, + w = width, + h = height, + body = body, + )) +} + +fn draw_box(out: &mut String, x: f64, q: usize, label: &str) { + let y = y_of(q); + let w = 28.0; + let h = 28.0; + out.push_str(&format!( + r#""#, + rx = x - w / 2.0, + ry = y - h / 2.0, + )); + out.push_str(&format!( + r#"{label}"#, + ty = y + 4.0, + label = esc(label), + )); +} + +fn draw_cx(out: &mut String, x: f64, control: usize, target: usize) { + let yc = y_of(control); + let yt = y_of(target); + out.push_str(&format!( + r#""# + )); + out.push_str(&format!( + r#""# + )); + out.push_str(&format!( + r#""# + )); + out.push_str(&format!( + r#""#, + a = yt - 10.0, + b = yt + 10.0, + )); + out.push_str(&format!( + r#""#, + a = x - 10.0, + b = x + 10.0, + )); +} + +fn draw_cz(out: &mut String, x: f64, control: usize, target: usize) { + let yc = y_of(control); + let yt = y_of(target); + out.push_str(&format!( + r#""# + )); + out.push_str(&format!( + r#""# + )); + out.push_str(&format!( + r#""# + )); +} + +fn draw_swap(out: &mut String, x: f64, a: usize, b: usize) { + let ya = y_of(a); + let yb = y_of(b); + out.push_str(&format!( + r#""# + )); + for y in [ya, yb] { + out.push_str(&format!( + r#""#, + x0 = x - 8.0, + y0 = y - 8.0, + x1 = x + 8.0, + y1 = y + 8.0, + )); + out.push_str(&format!( + r#""#, + x0 = x - 8.0, + y0 = y + 8.0, + x1 = x + 8.0, + y1 = y - 8.0, + )); + } +} diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs index 573d8f8..2348505 100644 --- a/plugins/quantum/src/lib.rs +++ b/plugins/quantum/src/lib.rs @@ -1,5 +1,6 @@ //! Marqdo quantum plugin (C ABI v2): state-vector circuit simulation. +mod draw; mod sim; use std::ffi::{CStr, CString}; @@ -42,6 +43,8 @@ pub struct MarqdoHostApi { static mut HOST_FREE: Option = None; static mut HOST_ALLOC: Option *mut c_void> = None; +static mut HOST_QUERY: Option = None; +static mut HOST_USERDATA: *mut c_void = ptr::null_mut(); unsafe fn host_strdup(s: &str) -> *mut c_char { let alloc = HOST_ALLOC.expect("host alloc"); @@ -157,6 +160,60 @@ fn circuit_of(args: &Value) -> Result<&Value, String> { .ok_or_else(|| "missing `circuit`".to_string()) } +fn take_host_string(p: *mut c_char) -> Option { + if p.is_null() { + return None; + } + let s = unsafe { CStr::from_ptr(p) } + .to_str() + .ok() + .map(|s| s.to_string()); + unsafe { + if let Some(free) = HOST_FREE { + free(p as *mut c_void); + } + } + s +} + +fn host_query_json(name: &str, args: &Value) -> Result { + let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?; + let userdata = unsafe { HOST_USERDATA }; + let c_name = CString::new(name).map_err(|e| e.to_string())?; + let c_args = CString::new(args.to_string()).map_err(|e| e.to_string())?; + let mut out_ptr: *mut c_char = ptr::null_mut(); + let mut err_ptr: *mut c_char = ptr::null_mut(); + let rc = unsafe { + query( + userdata, + c_name.as_ptr(), + c_args.as_ptr(), + &mut out_ptr, + &mut err_ptr, + ) + }; + let err = take_host_string(err_ptr); + let out = take_host_string(out_ptr); + if rc != 0 { + return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed"))); + } + let out = out.unwrap_or_else(|| "null".into()); + serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}")) +} + +fn record_plot(svg: &str, path: Option<&str>) -> Result<(), String> { + let mut args = json!({ "svg": svg }); + if let Some(p) = path { + if !p.is_empty() { + args.as_object_mut() + .unwrap() + .insert("path".into(), json!(p)); + } + } + host_query_json("record_plot", &args)?; + Ok(()) +} + q_ffi!(quantum_ping, |_args: &Value| { Ok(json!({ "ok": true, @@ -168,11 +225,11 @@ q_ffi!(quantum_ping, |_args: &Value| { q_ffi!(quantum_circuit_new, |args: &Value| { let qubits = arg_u(args, "qubits").or_else(|_| arg_u(args, "比特数"))?; - sim::check_qubits(qubits)?; - Ok(json!({ - "qubits": qubits, - "ops": [], - })) + let steps = args + .get("steps") + .or_else(|| args.get("步骤")) + .filter(|v| !v.is_null()); + sim::circuit_new(qubits, steps) }); q_ffi!(quantum_h, |args: &Value| { @@ -286,6 +343,34 @@ q_ffi!(quantum_run, |args: &Value| { sim::run_circuit(c, shots, seed) }); +q_ffi!(quantum_draw_circuit, |args: &Value| { + let c = circuit_of(args)?; + let svg = draw::circuit_svg(c)?; + let path = args + .get("path") + .or_else(|| args.get("路径")) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()); + // Prefer view/CLI plots channel; still return structured value for authors. + record_plot(&svg, path)?; + let ops_n = c + .get("ops") + .and_then(|v| v.as_array()) + .map(|a| a.len()) + .unwrap_or(0); + let qubits = c + .get("qubits") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + Ok(json!({ + "_type": "quantum_svg", + "kind": "circuit", + "qubits": qubits, + "ops": ops_n, + "svg": svg, + })) +}); + fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int { let register = match host.register_fn { Some(f) => f, @@ -312,14 +397,13 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int let host = &*host; HOST_ALLOC = host.alloc; HOST_FREE = host.free; - if host.host_query.is_none() { - // v2 preferred; still allow init if only register is present - } + HOST_QUERY = host.host_query; + HOST_USERDATA = host.userdata; let regs = [ ("quantum_ping", "", quantum_ping as PluginFn), ( "quantum_circuit_new", - "qubits", + "qubits,steps", quantum_circuit_new as PluginFn, ), ("quantum_h", "circuit,qubit", quantum_h as PluginFn), @@ -354,6 +438,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int quantum_probabilities as PluginFn, ), ("quantum_run", "circuit,shots,seed", quantum_run as PluginFn), + ( + "quantum_draw_circuit", + "circuit,path", + quantum_draw_circuit as PluginFn, + ), ]; for (name, params, f) in regs { if register(host, name, params, f) != 0 { diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs index d9c25a4..73a052c 100644 --- a/plugins/quantum/src/sim.rs +++ b/plugins/quantum/src/sim.rs @@ -345,7 +345,8 @@ pub fn parse_ops(circuit: &Value) -> Result, String> { let theta = row .get("theta") .or_else(|| row.get("参数")) - .and_then(|v| v.as_f64()); + .or_else(|| row.get("params")) + .and_then(|v| parse_theta_value(v).ok().flatten()); out.push(Op { gate, qubits, theta }); } Ok(out) @@ -531,6 +532,211 @@ pub fn simulate_circuit(circuit: &Value) -> Result<(usize, Vec), String> { Ok((qubits, amps)) } +/// Build a circuit from `qubits` + optional `steps=` table (column map or row list). +pub fn circuit_new(qubits: usize, steps: Option<&Value>) -> Result { + check_qubits(qubits)?; + let ops = match steps { + None | Some(Value::Null) => Vec::new(), + Some(v) => ops_from_steps(v)?, + }; + for op in &ops { + for &q in &op.qubits { + if q >= qubits { + return Err(format!("qubit {q} out of range for n={qubits}")); + } + } + } + let ops_json: Vec = ops + .into_iter() + .map(|op| { + let mut m = json!({ + "gate": op.gate, + "qubits": op.qubits, + }); + if let Some(t) = op.theta { + m.as_object_mut() + .unwrap() + .insert("theta".into(), json!(t)); + } + m + }) + .collect(); + Ok(json!({ + "qubits": qubits, + "ops": ops_json, + })) +} + +/// Parse GFM `steps=` into ops. +/// +/// Accepts: +/// - list of row maps (`@` / `行` / `row` tables) +/// - column-oriented map (`gate`/`门` + `qubits`/`比特` lists or scalars) +pub fn ops_from_steps(steps: &Value) -> Result, String> { + match steps { + Value::Array(rows) => { + let mut out = Vec::with_capacity(rows.len()); + for row in rows { + out.push(op_from_step_row(row)?); + } + Ok(out) + } + Value::Object(map) => { + let gate_col = map + .get("gate") + .or_else(|| map.get("门")) + .ok_or_else(|| "steps table needs `gate` / `门` column".to_string())?; + let qubit_col = map + .get("qubits") + .or_else(|| map.get("qubit")) + .or_else(|| map.get("比特")) + .ok_or_else(|| "steps table needs `qubits` / `比特` column".to_string())?; + let theta_col = map + .get("theta") + .or_else(|| map.get("参数")) + .or_else(|| map.get("params")); + + let gates = as_col_list(gate_col)?; + let qubits = as_col_list(qubit_col)?; + let thetas = match theta_col { + Some(v) => as_col_list(v)?, + None => vec![Value::Null; gates.len()], + }; + if qubits.len() != gates.len() { + return Err(format!( + "steps column length mismatch: gate={} qubits={}", + gates.len(), + qubits.len() + )); + } + if thetas.len() != gates.len() && theta_col.is_some() { + return Err("steps `theta`/`参数` column length mismatch".into()); + } + let mut out = Vec::with_capacity(gates.len()); + for i in 0..gates.len() { + let gate = gates[i] + .as_str() + .ok_or_else(|| format!("steps gate row {i} must be text"))? + .to_ascii_uppercase(); + let qs = qubits_from_cell(&qubits[i])?; + let theta = thetas + .get(i) + .map(parse_theta_value) + .transpose()? + .flatten(); + out.push(Op { + gate, + qubits: qs, + theta, + }); + } + Ok(out) + } + _ => Err("steps must be a table (map or list of rows)".into()), + } +} + +fn as_col_list(v: &Value) -> Result, String> { + match v { + Value::Array(a) => Ok(a.clone()), + other => Ok(vec![other.clone()]), + } +} + +fn op_from_step_row(row: &Value) -> Result { + let gate = row + .get("gate") + .or_else(|| row.get("门")) + .and_then(|v| v.as_str()) + .ok_or_else(|| "step row missing `gate` / `门`".to_string())? + .to_ascii_uppercase(); + let qs = row + .get("qubits") + .or_else(|| row.get("qubit")) + .or_else(|| row.get("比特")) + .ok_or_else(|| "step row missing `qubits` / `比特`".to_string())?; + let qubits = qubits_from_cell(qs)?; + let theta = row + .get("theta") + .or_else(|| row.get("参数")) + .or_else(|| row.get("params")) + .map(parse_theta_value) + .transpose()? + .flatten(); + Ok(Op { + gate, + qubits, + theta, + }) +} + +fn qubits_from_cell(v: &Value) -> Result, String> { + match v { + Value::Array(a) => a + .iter() + .map(|x| { + x.as_u64() + .or_else(|| x.as_i64().map(|i| i as u64)) + .ok_or_else(|| "bad qubit index".to_string()) + .map(|u| u as usize) + }) + .collect(), + Value::Number(n) => { + let u = n + .as_u64() + .or_else(|| n.as_i64().map(|i| i as u64)) + .ok_or_else(|| "bad qubit index".to_string())? as usize; + Ok(vec![u]) + } + Value::String(s) => parse_qubit_list(s), + _ => Err("bad qubits cell".into()), + } +} + +fn parse_theta_value(v: &Value) -> Result, String> { + match v { + Value::Null => Ok(None), + Value::Number(n) => n + .as_f64() + .ok_or_else(|| "bad theta".to_string()) + .map(Some), + Value::String(s) => { + let t = s.trim(); + if t.is_empty() { + return Ok(None); + } + parse_theta_str(t).map(Some) + } + _ => Err("bad theta".into()), + } +} + +fn parse_theta_str(s: &str) -> Result { + let t = s.trim().to_ascii_lowercase().replace('π', "pi"); + if t == "pi" { + return Ok(std::f64::consts::PI); + } + if let Some(rest) = t.strip_prefix("pi/") { + let d: f64 = rest + .trim() + .parse() + .map_err(|_| format!("bad theta `{s}`"))?; + if d == 0.0 { + return Err(format!("bad theta `{s}`")); + } + return Ok(std::f64::consts::PI / d); + } + if let Some(rest) = t.strip_suffix("*pi") { + let n: f64 = rest + .trim() + .parse() + .map_err(|_| format!("bad theta `{s}`"))?; + return Ok(n * std::f64::consts::PI); + } + t.parse::() + .map_err(|_| format!("bad theta `{s}`")) +} + pub fn push_op(circuit: &Value, gate: &str, qubits: Vec, theta: Option) -> Result { let n = circuit .get("qubits") diff --git a/public/keywords/stdlib.mq.md b/public/keywords/stdlib.mq.md index 812388d..e7fa99e 100644 --- a/public/keywords/stdlib.mq.md +++ b/public/keywords/stdlib.mq.md @@ -7,7 +7,7 @@ description: Host builtins for strings and tables Length and type: -*`s` = hello* +*`s` = "hello"* *`n` = > len `s`* diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md index 498394e..5541d9a 100644 --- a/public/structure/05-loop.mq.md +++ b/public/structure/05-loop.mq.md @@ -24,5 +24,5 @@ Walk a table (tables are collections): | apple | | pear | -- [`fruit`](`basket`) +- [fruit](basket) > print text=today `fruit` diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md index af0b6fc..c8fac8a 100644 --- a/public/structure/05-循环.mq.md +++ b/public/structure/05-循环.mq.md @@ -24,5 +24,5 @@ description: 条件循环与表遍历 | 苹果 | | 梨 | -- [`水果`](`篮子`) +- [水果](篮子) > 打印 内容=今天 `水果` diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md index be749b1..1cc9df5 100644 --- a/public/structure/06-collection.mq.md +++ b/public/structure/06-collection.mq.md @@ -15,5 +15,5 @@ A single-column Markdown table is a list; loop to read each item. Use `basket`[^ | pear | | peach | -- [`fruit`](`basket`) +- [fruit](basket) > print text=`fruit` diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md index 71c3aa6..0f93c33 100644 --- a/public/structure/06-集合.mq.md +++ b/public/structure/06-集合.mq.md @@ -15,5 +15,5 @@ description: 单列竖表即列表 | 梨 | | 桃 | -- [`水果`](`篮子`) +- [水果](篮子) > 打印 内容=`水果` diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index e339bee..07d8e1f 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -20,7 +20,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 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` ``, bindings `` `x` ``, foreach `` [`item`](`coll`) ``. **Complex text** uses `"..."` with escapes; bare tokens stay literal (no `\n` magic). +5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are variables (strings need `"…"` / `'…'`; ticks still ok). 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. Prefer `` `path` `` vars, same-dir names, or call args — not raw `a/b` in expressions. 8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. @@ -33,7 +33,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | `##` … `######` | **Function / method** (nesting by heading depth). | | `` + `name` `` under heading | Parameter (optional `` `name`=default ``) | | `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). | -| `- …` inside body | Loop (`while` or `` [`item`](`coll`) ``) | +| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) | | Line `N. *` | Else arm | | `> fn args` | Call (named `k=v` or positional) | | `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) | diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md index 6b55321..1032340 100644 --- a/skills/marqdo/examples.md +++ b/skills/marqdo/examples.md @@ -74,7 +74,7 @@ Greeting via a nested function: |----| | 苹果 | -- [`果`](`篮子`) +- [果](篮子) > print text=`果` ``` @@ -89,13 +89,13 @@ Greeting via a nested function: |------|------| | 水果 | 蔬菜 | -*`种` = `分类`[^苹果] * +*`种` = 分类[^苹果] * > print text=`种` -*`第一` = `篮子`[^1] * +*`第一` = 篮子[^1] * ``` -One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Footnotes are 1-based on lists; map keys are header text. Foreach on a map walks **keys**. +One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Data cells are expressions (same as call-arg values): bare words, numbers, `` `var` ``, quoted strings; URLs and `gpt-4o-mini` stay text via path/hyphen folding. Footnotes: lists use 1-based digit indices; maps use key text (including digit keys like `[^00]`). Foreach on a map walks **keys**. Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md index 2ea9a30..33d4ff5 100644 --- a/skills/marqdo/reference.md +++ b/skills/marqdo/reference.md @@ -18,7 +18,7 @@ marqdo ext remove llm|agent Diagnostics look like `path:line:col: message` (1-based line/col). -**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [`item`](`coll`) ``; identifiers in backticks. See `doc/design/markdown-mapping.md`. +**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) `` or `` - [`item`](`coll`) ``; identifiers in backticks (foreach header may omit ticks). See `doc/design/markdown-mapping.md`. Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. diff --git a/src/ast.rs b/src/ast.rs index f92f7a9..7b959a4 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -146,7 +146,7 @@ pub enum Expr { /// Footnote index: `` `xs`[^1] `` / `` `m`[^key] `` (see tables-maps-footnotes). Index { base: Box, - /// Label inside `[^…]` (digits → 1-based list index; else map key). + /// Label inside `[^…]` (digits → 1-based list index, or map key text including digit keys). label: String, }, /// Parsed `$$…$$` formula tree (from assignment RHS). diff --git a/src/builtin.rs b/src/builtin.rs index 29a661d..c93b697 100644 --- a/src/builtin.rs +++ b/src/builtin.rs @@ -152,18 +152,11 @@ pub fn builtin_footnote_get(base: &Value, label: &str) -> Result } Ok(xs[(n as usize) - 1].clone()) } - Value::Map(pairs) => { - if is_digits { - return Err( - "map footnote must be a key name, not pure digits (keys are text)".into(), - ); - } - pairs - .iter() - .find(|(k, _)| k == label) - .map(|(_, v)| v.clone()) - .ok_or_else(|| format!("missing map key `{label}`")) - } + Value::Map(pairs) => pairs + .iter() + .find(|(k, _)| k == label) + .map(|(_, v)| v.clone()) + .ok_or_else(|| format!("missing map key `{label}`")), _ => Err("footnote index needs list or map".into()), } } diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs index 82f270d..9c969c7 100644 --- a/src/bytecode/vm.rs +++ b/src/bytecode/vm.rs @@ -492,8 +492,9 @@ impl Vm { }; bound.insert(ks, v); } - let result = crate::host::plugin::call_registered(&self.host, name, &bound) - .map_err(|m| self.err_at(span, m))?; + let result = + crate::host::plugin::call_registered(&mut self.host, name, &bound) + .map_err(|m| self.err_at(span, m))?; stack.push(result); } else { let mut vals = Vec::with_capacity(argc); @@ -523,7 +524,7 @@ impl Vm { bound.insert(p.clone(), v); } let result = - crate::host::plugin::call_registered(&self.host, &raw_name, &bound) + crate::host::plugin::call_registered(&mut self.host, &raw_name, &bound) .map_err(|m| self.err_at(span, m))?; stack.push(result); } diff --git a/src/host/plugin.rs b/src/host/plugin.rs index 28152df..49486f9 100644 --- a/src/host/plugin.rs +++ b/src/host/plugin.rs @@ -52,8 +52,8 @@ struct MarqdoHostApi { } thread_local! { - /// Set around plugin calls so `host_query` can read entry source / call site. - static CURRENT_HOST: Cell<*const HostContext> = const { Cell::new(std::ptr::null()) }; + /// Set around plugin calls so `host_query` can read/write host context (plots, etc.). + static CURRENT_HOST: Cell<*mut HostContext> = const { Cell::new(std::ptr::null_mut()) }; /// Optional `lib.member` resolver for `host_query("call_lib_path")` (site entry module). static LIB_PATH_CALL: RefCell> = const { RefCell::new(None) }; } @@ -255,7 +255,7 @@ unsafe extern "C" fn host_query( set_err("host_query: no active host context (call during plugin fn)"); return 1; } - let ctx = &*ctx_ptr; + let ctx = &mut *ctx_ptr; let args_owned: Option = if args_json.is_null() { None @@ -295,6 +295,37 @@ unsafe extern "C" fn host_query( value_to_json(&v) }) })(), + "record_plot" => (|| { + let raw = args_owned.as_deref().unwrap_or("{}"); + let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() { + "{}" + } else { + raw + }) + .map_err(|e| format!("record_plot args: {e}"))?; + let svg = args + .get("svg") + .and_then(|v| v.as_str()) + .ok_or_else(|| "record_plot requires `svg`".to_string())? + .to_string(); + let path_s = args + .get("path") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()); + if let Some(ref p) = path_s { + crate::host::fs::write_text( + ctx, + &Value::Text(p.clone()), + &Value::Text(svg.clone()), + )?; + } + ctx.plots.push(crate::host::PlotArtifact { + path: path_s, + svg, + }); + Ok(serde_json::json!({ "ok": true })) + })(), other => Err(format!("host_query: unknown `{other}`")), }; @@ -420,7 +451,7 @@ pub fn list(ctx: &HostContext) -> Result { /// Call a registered plugin function with already-bound args (param name → Value). pub fn call_registered( - ctx: &HostContext, + ctx: &mut HostContext, name: &str, bound: &HashMap, ) -> Result { @@ -449,9 +480,9 @@ pub fn call_registered( let mut out_ptr: *mut c_char = std::ptr::null_mut(); let mut err_ptr: *mut c_char = std::ptr::null_mut(); - CURRENT_HOST.with(|c| c.set(ctx as *const HostContext)); + CURRENT_HOST.with(|c| c.set(ctx as *mut HostContext)); let rc = unsafe { (reg.fn_ptr)(c_args.as_ptr(), &mut out_ptr, &mut err_ptr) }; - CURRENT_HOST.with(|c| c.set(std::ptr::null())); + CURRENT_HOST.with(|c| c.set(std::ptr::null_mut())); let err_s = take_c_string(err_ptr); let out_s = take_c_string(out_ptr); diff --git a/src/interp.rs b/src/interp.rs index 1e29c73..ae38293 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -206,7 +206,7 @@ impl Interpreter { data: &mut data as *mut HookData as *mut (), }; crate::host::plugin::with_lib_path_call(hook, || { - crate::host::plugin::call_registered(&self.host, name, bound) + crate::host::plugin::call_registered(&mut self.host, name, bound) }) } diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 4586fb7..87cb651 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -5,7 +5,16 @@ use anyhow::{bail, Result}; use crate::ast::{BinaryOp, CallExpr, Expr, InterpPart, Literal, UnaryOp}; pub fn parse_expr(input: &str) -> Result { - let mut p = Parser::new(input.trim()); + parse_expr_mode(input, false) +} + +/// Italic / bold value syntax: bare words are variables; text needs `"…"` / `'…'`. +pub fn parse_expr_prefer_var(input: &str) -> Result { + parse_expr_mode(input, true) +} + +fn parse_expr_mode(input: &str, prefer_var: bool) -> Result { + let mut p = Parser::new(input.trim(), prefer_var); let e = p.parse_or()?; p.skip_ws(); if !p.rest().is_empty() { @@ -22,7 +31,7 @@ pub fn parse_value_or_interp(input: &str) -> Result { if s.is_empty() { return Ok(Expr::Literal(Literal::Text(String::new()))); } - if s.starts_with('"') { + if s.starts_with('"') || s.starts_with('\'') { return match parse_expr(s) { Ok(e) => Ok(e), Err(_) => Ok(parse_interp(s)), @@ -45,7 +54,7 @@ pub fn parse_call_arg_value(input: &str) -> Result { if s.is_empty() { return Ok(Expr::Literal(Literal::Text(String::new()))); } - if s.starts_with('"') { + if s.starts_with('"') || s.starts_with('\'') { return match parse_expr(s) { Ok(e) => Ok(e), Err(_) => Ok(parse_interp(s)), @@ -56,7 +65,15 @@ pub fn parse_call_arg_value(input: &str) -> Result { } match parse_expr(s) { Ok(e) => Ok(collapse_text_div_path(e, s)), - Err(_) => Ok(parse_interp(s)), + Err(_) => { + // ext/web paths: `nav.`nav``, `articles.`articles`.title` — ticks are path + // punctuation, not interpolation. + if s.contains(".`") { + Ok(Expr::Literal(Literal::Text(s.to_string()))) + } else { + Ok(parse_interp(s)) + } + } } } @@ -145,11 +162,17 @@ pub fn parse_interp(s: &str) -> Expr { struct Parser<'a> { src: &'a str, i: usize, + /// When true (italic/bold), bare words are variables, not text literals. + prefer_var: bool, } impl<'a> Parser<'a> { - fn new(src: &'a str) -> Self { - Self { src, i: 0 } + fn new(src: &'a str, prefer_var: bool) -> Self { + Self { + src, + i: 0, + prefer_var, + } } fn rest(&self) -> &str { @@ -348,7 +371,10 @@ impl<'a> Parser<'a> { return Ok(e); } if self.eat("\"") { - return self.parse_quoted_string(); + return self.parse_quoted_string('"'); + } + if self.eat("'") { + return self.parse_quoted_string('\''); } if self.eat("`") { let start = self.i; @@ -362,20 +388,7 @@ impl<'a> Parser<'a> { if !self.eat("`") { bail!("unterminated `name`"); } - let mut expr = Expr::Var(name); - // Postfix footnotes: `xs`[^1] / `m`[^key] / chained `m`[^k][^1] - loop { - self.skip_ws(); - if !self.starts_with("[^") { - break; - } - let label = self.parse_footnote_label()?; - expr = Expr::Index { - base: Box::new(expr), - label, - }; - } - return Ok(expr); + return self.parse_index_chain(Expr::Var(name)); } if self.eat(">") { // Inline call: `> name k=v` @@ -417,39 +430,83 @@ impl<'a> Parser<'a> { let n: i64 = self.src[start..self.i].parse()?; return Ok(Expr::Literal(Literal::Int(n))); } - // Bare identifier / text word + // Bare identifier / text word. If immediately followed by `[^…]`, treat as + // variable + footnote index (exemption: ticks optional when `[^` marks the slot). if self.peek_char().map(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()).unwrap_or(false) { let start = self.i; while let Some(c) = self.peek_char() { - if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',' | '"') + if c.is_whitespace() + || matches!( + c, + '=' | '+' + | '-' + | '*' + | '/' + | '<' + | '>' + | '(' + | ')' + | '`' + | '|' + | ',' + | '"' + | '\'' + | '[' + | ']' + ) { break; } self.bump_char(); } - let word = &self.src[start..self.i]; - return Ok(Expr::Literal(Literal::Text(word.to_string()))); + let word = self.src[start..self.i].to_string(); + self.skip_ws(); + if self.starts_with("[^") { + return self.parse_index_chain(Expr::Var(word)); + } + if self.prefer_var { + return Ok(Expr::Var(word)); + } + return Ok(Expr::Literal(Literal::Text(word))); } bail!("unexpected expression input: {:?}", self.rest()); } - /// `"..."` string with `\n` `\t` `\r` `\\` `\"` and `` `var` `` interpolation. - fn parse_quoted_string(&mut self) -> Result { + /// `` `xs`[^1] `` / `m[^key]` / chained `m[^k][^1]` (base already parsed). + fn parse_index_chain(&mut self, mut expr: Expr) -> Result { + loop { + self.skip_ws(); + if !self.starts_with("[^") { + break; + } + let label = self.parse_footnote_label()?; + expr = Expr::Index { + base: Box::new(expr), + label, + }; + } + Ok(expr) + } + + /// `"..."` or `'...'` with escapes and `` `var` `` interpolation. + fn parse_quoted_string(&mut self, quote: char) -> Result { use crate::ast::InterpPart; let mut parts: Vec = Vec::new(); let mut lit = String::new(); loop { let Some(c) = self.peek_char() else { - bail!("unterminated \" string"); + bail!("unterminated {quote} string"); }; - if c == '"' { + if c == quote { self.bump_char(); break; } if c == '\\' { self.bump_char(); - let esc = self.peek_char().ok_or_else(|| anyhow::anyhow!("dangling \\ in string"))?; + let esc = self + .peek_char() + .ok_or_else(|| anyhow::anyhow!("dangling \\ in string"))?; self.bump_char(); lit.push(match esc { 'n' => '\n', @@ -457,6 +514,7 @@ impl<'a> Parser<'a> { 'r' => '\r', '\\' => '\\', '"' => '"', + '\'' => '\'', other => bail!("unknown escape \\{other} in string"), }); continue; @@ -756,11 +814,51 @@ mod tests { use super::*; #[test] - fn cmp_and_arith() { - let e = parse_expr("`x` > 0").unwrap(); - assert!(matches!(e, Expr::Binary { op: BinaryOp::Gt, .. })); - let e = parse_expr("`n` + 1").unwrap(); + fn bare_var_footnote_index() { + let e = parse_expr("ev[^result]").unwrap(); + match e { + Expr::Index { base, label } => { + assert!(matches!(base.as_ref(), Expr::Var(n) if n == "ev")); + assert_eq!(label, "result"); + } + other => panic!("expected Index, got {other:?}"), + } + let e = parse_expr("data[^choices][^1][^message]").unwrap(); + assert!(matches!(e, Expr::Index { .. })); + // Without `[^`, bare word stays text literal. + let e = parse_expr("ev").unwrap(); + assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "ev")); + // Ticked form still works. + let e = parse_expr("`ev`[^result]").unwrap(); + assert!(matches!(e, Expr::Index { .. })); + } + + #[test] + fn prefer_var_bare_id_and_quotes() { + let e = parse_expr_prefer_var("answer").unwrap(); + assert!(matches!(e, Expr::Var(ref n) if n == "answer")); + let e = parse_expr_prefer_var("n + 1").unwrap(); assert!(matches!(e, Expr::Binary { op: BinaryOp::Add, .. })); + let e = parse_expr_prefer_var("\"ok\"").unwrap(); + assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "ok")); + let e = parse_expr_prefer_var("'hi'").unwrap(); + assert!(matches!(e, Expr::Literal(Literal::Text(ref s)) if s == "hi")); + let e = parse_expr_prefer_var("`answer`").unwrap(); + assert!(matches!(e, Expr::Var(ref n) if n == "answer")); + } + + #[test] + fn call_arg_module_path_stays_text() { + let e = parse_call_arg_value("nav.`nav`").unwrap(); + assert!(matches!( + e, + Expr::Literal(Literal::Text(ref s)) if s == "nav.`nav`" + )); + let e = parse_call_arg_value("articles.`articles`.title").unwrap(); + assert!(matches!( + e, + Expr::Literal(Literal::Text(ref s)) if s == "articles.`articles`.title" + )); } #[test] diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 2bf028e..6e2db61 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -2,7 +2,10 @@ mod expr; -pub use expr::{parse_call_after_gt, parse_call_arg_value, parse_expr, parse_value_or_interp}; +pub use expr::{ + parse_call_after_gt, parse_call_arg_value, parse_expr, parse_expr_prefer_var, + parse_value_or_interp, +}; use anyhow::{bail, Result}; @@ -248,7 +251,7 @@ impl<'a> Cursor<'a> { let value = if inner.trim().is_empty() { Expr::Literal(Literal::None) } else { - parse_expr_str(inner)? + parse_expr_prefer_var(inner)? }; return Ok(Stmt::Return { value, span }); } @@ -277,12 +280,12 @@ impl<'a> Cursor<'a> { fn parse_italic_assign(&mut self, inner: &str, span: Span) -> Result { let Some((name, rhs)) = split_assign_inner(inner) else { - bail!("{span}: italic statement must be an assignment (`name` = …)"); + bail!("{span}: italic statement must be an assignment (name = …)"); }; if crate::aliases::is_reserved_keyword(&name) { bail!("{span}: `{name}` is a reserved keyword"); } - let (value, end_line) = self.resolve_assign_rhs(&rhs, span)?; + let (value, end_line) = self.resolve_assign_rhs(&rhs, span, true)?; Ok(Stmt::Assign { name, value, @@ -308,7 +311,7 @@ impl<'a> Cursor<'a> { return Ok(None); } let rhs = after[1..].trim().to_string(); - let (value, end_line) = self.resolve_assign_rhs(&rhs, span)?; + let (value, end_line) = self.resolve_assign_rhs(&rhs, span, false)?; Ok(Some(Stmt::Assign { name, value, @@ -319,7 +322,13 @@ impl<'a> Cursor<'a> { /// RHS on the same line, or empty RHS → following `$$` / ```lang fence or table. /// Returns `(expr, inclusive end_line)`. - fn resolve_assign_rhs(&mut self, rhs: &str, span: Span) -> Result<(Expr, u32)> { + /// `prefer_var`: italic RHS uses variable-preferring expression syntax. + fn resolve_assign_rhs( + &mut self, + rhs: &str, + span: Span, + prefer_var: bool, + ) -> Result<(Expr, u32)> { let rhs = rhs.trim(); if rhs.is_empty() { self.skip_blanks(); @@ -344,7 +353,12 @@ impl<'a> Cursor<'a> { if rhs.starts_with('>') { return Ok((Expr::Call(call_after_gt(rhs[1..].trim())?), span.line)); } - Ok((parse_value_or_interp(rhs)?, span.line)) + let value = if prefer_var { + parse_expr_prefer_var(rhs)? + } else { + parse_value_or_interp(rhs)? + }; + Ok((value, span.line)) } fn skip_blanks(&mut self) { @@ -463,11 +477,13 @@ impl<'a> Cursor<'a> { /// - 1-col → List /// - first header `@` / `行` / `row` → List of row Maps (marker col excluded) /// - else ≥2-col → Map (column-oriented) + /// + /// Data cells are expressions ([`parse_call_arg_value`]); headers stay key text. fn consume_table(&mut self) -> Result { self.skip_noise(); let mut header: Vec = Vec::new(); let mut header_line: u32 = 1; - let mut data_rows: Vec> = Vec::new(); + let mut data_rows: Vec<(u32, Vec)> = Vec::new(); let mut header_done = false; let mut sep_done = false; while let Some(l) = self.peek() { @@ -496,7 +512,7 @@ impl<'a> Cursor<'a> { continue; } sep_done = true; - data_rows.push(cells); + data_rows.push((line_no, cells)); } if !header_done { bail!("expected GFM table after empty assignment"); @@ -510,9 +526,9 @@ impl<'a> Cursor<'a> { } if header.len() <= 1 { let mut rows = Vec::new(); - for cells in data_rows { + for (line_no, cells) in data_rows { if let Some(cell) = cells.first() { - rows.push(Expr::Literal(cell_literal(cell))); + rows.push(parse_table_cell(cell, line_no)?); } } return Ok(Expr::List(rows)); @@ -536,14 +552,15 @@ impl<'a> Cursor<'a> { let mut pairs = Vec::with_capacity(header.len()); for (col, key) in header.iter().enumerate() { if n_rows == 1 { - let raw = data_rows[0].get(col).map(|s| s.as_str()).unwrap_or(""); - pairs.push((key.clone(), Expr::Literal(cell_literal(raw)))); + let (line_no, cells) = &data_rows[0]; + let raw = cells.get(col).map(|s| s.as_str()).unwrap_or(""); + pairs.push((key.clone(), parse_table_cell(raw, *line_no)?)); } else { // 0 rows → empty lists; ≥2 rows → column lists. let mut col_vals = Vec::with_capacity(n_rows); - for cells in &data_rows { + for (line_no, cells) in &data_rows { let raw = cells.get(col).map(|s| s.as_str()).unwrap_or(""); - col_vals.push(Expr::Literal(cell_literal(raw))); + col_vals.push(parse_table_cell(raw, *line_no)?); } pairs.push((key.clone(), Expr::List(col_vals))); } @@ -661,12 +678,38 @@ impl<'a> Cursor<'a> { fn split_assign_inner(inner: &str) -> Option<(String, String)> { let inner = inner.trim(); - let rest = inner.strip_prefix('`')?; - let end = rest.find('`')?; - let name = rest[..end].to_string(); - let after = rest[end + 1..].trim_start(); - let rhs = after.strip_prefix('=')?.trim().to_string(); - Some((name, rhs)) + if let Some(rest) = inner.strip_prefix('`') { + let end = rest.find('`')?; + let name = rest[..end].to_string(); + if name.is_empty() { + return None; + } + let after = rest[end + 1..].trim_start(); + let rhs = after.strip_prefix('=')?.trim().to_string(); + return Some((name, rhs)); + } + // Bare LHS: `answer = …` (italic exemption). + let eq = inner.find('=')?; + let name = inner[..eq].trim(); + if !is_bare_assign_ident(name) { + return None; + } + let rhs = inner[eq + 1..].trim().to_string(); + Some((name.to_string(), rhs)) +} + +fn is_bare_assign_ident(s: &str) -> bool { + if s.is_empty() || s.contains('`') || s.chars().any(char::is_whitespace) { + return false; + } + let mut chars = s.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !(first.is_alphanumeric() || first == '_' || !first.is_ascii()) { + return false; + } + true } /// Same-line `$$body$$` → Formula; otherwise None (caller parses normally). @@ -731,19 +774,39 @@ fn parse_param_line(trimmed: &str) -> Option { Some(Param { name, default }) } +fn parse_foreach_ident(s: &str) -> Option { + let s = s.trim(); + if s.starts_with('`') { + return parse_backtick_ident(s); + } + if s.is_empty() { + return None; + } + // Bare name exemption: `[item](list)` without ticks (foreach only). + if s.chars().any(|c| c.is_whitespace() || c == '`' || c == '[' || c == ']') { + return None; + } + let mut chars = s.chars(); + let first = chars.next()?; + if !(first.is_alphanumeric() || first == '_' || !first.is_ascii()) { + return None; + } + Some(s.to_string()) +} + fn parse_foreach_header(rest: &str) -> Option<(String, String)> { - // [`item`](`collection`) + // [`item`](`collection`) or bare [item](collection); sides may mix. let rest = rest.trim(); if !rest.starts_with('[') { return None; } let end_item = rest.find(']')?; - let item = parse_backtick_ident(&rest[1..end_item])?; + let item = parse_foreach_ident(&rest[1..end_item])?; let after = rest[end_item + 1..].trim_start(); if !after.starts_with('(') || !after.ends_with(')') { return None; } - let coll = parse_backtick_ident(&after[1..after.len() - 1])?; + let coll = parse_foreach_ident(&after[1..after.len() - 1])?; Some((item, coll)) } @@ -1003,15 +1066,15 @@ fn indent_of(text: &str) -> usize { .sum() } -fn cell_literal(raw: &str) -> Literal { - let t = raw.trim(); - let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); - if digits(t) || t.strip_prefix('-').is_some_and(digits) { - if let Ok(n) = t.parse::() { - return Literal::Int(n); - } - } - Literal::Text(t.to_string()) +fn parse_table_cell(raw: &str, line: u32) -> Result { + parse_call_arg_value(raw).map_err(|e| { + Diagnostic::new( + None, + Span { line, col: 1 }, + format!("table cell: {e}"), + ) + .into() + }) } /// First-column header that opts into row-oriented records (`List` of `Map`). @@ -1022,7 +1085,7 @@ fn is_row_table_marker(header: &str) -> bool { fn build_row_oriented_table( header: Vec, header_line: u32, - data_rows: Vec>, + data_rows: Vec<(u32, Vec)>, ) -> Result { if header.len() < 2 { return Err(Diagnostic::new( @@ -1051,12 +1114,12 @@ fn build_row_oriented_table( } } let mut rows = Vec::with_capacity(data_rows.len()); - for cells in data_rows { + for (line_no, cells) in data_rows { let mut pairs = Vec::with_capacity(fields.len()); for (i, key) in fields.iter().enumerate() { // Skip marker column (index 0); fields start at column 1. let raw = cells.get(i + 1).map(|s| s.as_str()).unwrap_or(""); - pairs.push((key.clone(), Expr::Literal(cell_literal(raw)))); + pairs.push((key.clone(), parse_table_cell(raw, line_no)?)); } rows.push(Expr::Map(pairs)); } @@ -1123,6 +1186,51 @@ mod tests { } } + #[test] + fn parse_foreach_bare_ids() { + let src = "# main\n\n- [x](xs)\n > print text=`x`\n"; + let m = parse_source(src).unwrap(); + match &m.functions[0].body[0] { + Stmt::ForEach { item, collection, .. } => { + assert_eq!(item, "x"); + assert_eq!(collection, "xs"); + } + other => panic!("expected foreach, got {other:?}"), + } + } + + #[test] + fn parse_foreach_mixed_ticks() { + let src = "# main\n\n- [果](`篮子`)\n > print text=`果`\n"; + let m = parse_source(src).unwrap(); + match &m.functions[0].body[0] { + Stmt::ForEach { item, collection, .. } => { + assert_eq!(item, "果"); + assert_eq!(collection, "篮子"); + } + other => panic!("expected foreach, got {other:?}"), + } + } + + #[test] + fn parse_italic_bare_lhs_prefer_var() { + let src = "# main\n\n*answer = 1*\n**answer**\n"; + let m = parse_source(src).unwrap(); + match &m.functions[0].body[0] { + Stmt::Assign { name, value, .. } => { + assert_eq!(name, "answer"); + assert!(matches!(value, Expr::Literal(Literal::Int(1)))); + } + other => panic!("expected assign, got {other:?}"), + } + match &m.functions[0].body[1] { + Stmt::Return { value, .. } => { + assert!(matches!(value, Expr::Var(n) if n == "answer")); + } + other => panic!("expected return, got {other:?}"), + } + } + #[test] fn parse_branch_rejects_plus_arm() { let src = "# main\n\n+ `x` > 0\n > print text=ok\n"; diff --git a/tests/ext/agent-kb-alias.mq.md b/tests/ext/agent-kb-alias.mq.md index e7486ce..6e36243 100644 --- a/tests/ext/agent-kb-alias.mq.md +++ b/tests/ext/agent-kb-alias.mq.md @@ -17,11 +17,11 @@ description: Promote resource; patch Task aliases; variant goal hits same resour > print text=no-agent-plugin > sys.exit code=1 -*`kb` = .marqdo/agent-kb-alias-test * -*`wb` = .marqdo/agent-runs/alias-pong.mq.md * -*`goal` = Reply with exactly the word pong and nothing else. * -*`alias` = say pong only * -*`body` = "---\ntitle: pong skill\n---\n\n# main\n\n**pong**\n" * +*`kb` = ".marqdo/agent-kb-alias-test" * +*`wb` = ".marqdo/agent-runs/alias-pong.mq.md" * +*`goal` = "Reply with exactly the word pong and nothing else." * +*`alias` = "say pong only" * +*`body` = "---\ntitle: pong skill\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n" * > fs.write_text path=`wb` text=`body` *`prom` = > agent_kb_promote kb_dir=`kb` goal=`goal` workbook=`wb` aliases=`alias` * @@ -63,9 +63,9 @@ description: Promote resource; patch Task aliases; variant goal hits same resour *`mk2` = > json.get value=`exact` key=match * > print text=`mk2` -*`g_trip` = 帮我规划明天的行程 * -*`wb2` = .marqdo/agent-runs/alias-trip.mq.md * -*`body2` = "---\ntitle: trip\n---\n\n# main\n\n**trip-ok**\n" * +*`g_trip` = "帮我规划明天的行程" * +*`wb2` = ".marqdo/agent-runs/alias-trip.mq.md" * +*`body2` = "---\ntitle: trip\n---\n\n# main\n\n*msg = \"trip-ok\"*\n\n**msg**\n" * > fs.write_text path=`wb2` text=`body2` *`prom2` = > agent_kb_promote kb_dir=`kb` goal=`g_trip` workbook=`wb2` * *`ok2` = > json.get value=`prom2` key=promoted * @@ -74,7 +74,7 @@ description: Promote resource; patch Task aliases; variant goal hits same resour 2. * > print text=trip-promote-fail -*`g_canon` = 你是一个智能体,帮我规划明天的行程 * +*`g_canon` = "你是一个智能体,帮我规划明天的行程" * *`c` = > agent_kb_canonicalize goal=`g_canon` * > print text=`c` *`hit_c` = > agent_kb_lookup kb_dir=`kb` goal=`g_canon` * diff --git a/tests/ext/agent-kb-near.mq.md b/tests/ext/agent-kb-near.mq.md index 2052f7f..11a76e4 100644 --- a/tests/ext/agent-kb-near.mq.md +++ b/tests/ext/agent-kb-near.mq.md @@ -17,10 +17,10 @@ description: Promote trip resource; near-dupe goals hit match=near; unrelated mi > print text=no-agent-plugin > sys.exit code=1 -*`kb` = .marqdo/agent-kb-near-test * -*`wb` = .marqdo/agent-runs/near-trip.mq.md * -*`goal` = 帮我规划明天的行程 * -*`body` = "---\ntitle: trip\n---\n\n# main\n\n**trip-ok**\n" * +*`kb` = ".marqdo/agent-kb-near-test" * +*`wb` = ".marqdo/agent-runs/near-trip.mq.md" * +*`goal` = "帮我规划明天的行程" * +*`body` = "---\ntitle: trip\n---\n\n# main\n\n*msg = \"trip-ok\"*\n\n**msg**\n" * > fs.write_text path=`wb` text=`body` *`prom` = > agent_kb_promote kb_dir=`kb` goal=`goal` workbook=`wb` * @@ -32,7 +32,7 @@ description: Promote trip resource; near-dupe goals hit match=near; unrelated mi *`slug` = > json.get value=`prom` key=slug * -*`g1` = 帮我规划明天行程 * +*`g1` = "帮我规划明天行程" * *`hit1` = > agent_kb_lookup kb_dir=`kb` goal=`g1` near_match=True near_threshold=0.78 * 1. `hit1` > print text=near-ok @@ -52,7 +52,7 @@ description: Promote trip resource; near-dupe goals hit match=near; unrelated mi 2. * > print text=off-miss -*`g2` = 明天做什么好 * +*`g2` = "明天做什么好" * *`hit2` = > agent_kb_lookup kb_dir=`kb` goal=`g2` near_match=True near_threshold=0.78 * 1. `hit2` > print text=neg-hit diff --git a/tests/ext/agent-kb-reuse.mq.md b/tests/ext/agent-kb-reuse.mq.md index 17563cd..18064fc 100644 --- a/tests/ext/agent-kb-reuse.mq.md +++ b/tests/ext/agent-kb-reuse.mq.md @@ -18,7 +18,7 @@ description: Promote a solidified workbook, lookup by goal, spawn without parent > print text=no-agent-plugin > sys.exit code=1 -*`paths` = > json.parse text={"kb":".marqdo/agent-kb","wb":".marqdo/agent-runs/pong-solid.mq.md","goal":"Reply with exactly the word pong and nothing else.","body":"---\ntitle: pong skill\n---\n\n# main\n\n**pong**\n"} * +*`paths` = > json.parse text={"kb":".marqdo/agent-kb","wb":".marqdo/agent-runs/pong-solid.mq.md","goal":"Reply with exactly the word pong and nothing else.","body":"---\ntitle: pong skill\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n"} * *`kb` = > json.get value=`paths` key=kb * *`wb` = > json.get value=`paths` key=wb * *`goal` = > json.get value=`paths` key=goal * diff --git a/tests/ext/agent-plan-decision.mq.md b/tests/ext/agent-plan-decision.mq.md index 43bee23..beef04b 100644 --- a/tests/ext/agent-plan-decision.mq.md +++ b/tests/ext/agent-plan-decision.mq.md @@ -31,14 +31,14 @@ description: extract_plan_decision/summary; dual skeleton contains research+writ *`r5` = > agent.extract_plan_decision reply=`d5` * > print text=`r5` -*`act_call` = CALL:lib_catalog * +*`act_call` = "CALL:lib_catalog" * *`a1` = > agent.extract_plan_act reply=`act_call` * *`a1k` = > json.get value=`a1` key=kind * *`a1n` = > json.get value=`a1` key=name * > print text=`a1k` > print text=`a1n` -*`act_read` = READ:stderr * +*`act_read` = "READ:stderr" * *`a2` = > agent.extract_plan_act reply=`act_read` * *`a2k` = > json.get value=`a2` key=kind * *`a2n` = > json.get value=`a2` key=name * diff --git a/tests/ext/agent-plan-observe.mq.md b/tests/ext/agent-plan-observe.mq.md index 91e48d0..7588dca 100644 --- a/tests/ext/agent-plan-observe.mq.md +++ b/tests/ext/agent-plan-observe.mq.md @@ -9,7 +9,7 @@ title: parent observation excerpt + deepen (offline) *`paths` = > json.parse text={"p":".marqdo/agent-runs/observe-fixture.mq.md"} * *`path` = > json.get value=`paths` key=p * -*`seed` = > json.parse text={"t":"---\ntitle: fixture\n---\n\n# main\n\n\n\n**ok**\n"} * +*`seed` = > json.parse text={"t":"---\ntitle: fixture\n---\n\n# main\n\n\n\n*msg = \"ok\"*\n\n**msg**\n"} * *`text` = > json.get value=`seed` key=t * > fs.write_text path=`path` text=`text` diff --git a/tests/ext/llm-ctor-offline.mq.md b/tests/ext/llm-ctor-offline.mq.md new file mode 100644 index 0000000..dd90eaa --- /dev/null +++ b/tests/ext/llm-ctor-offline.mq.md @@ -0,0 +1,11 @@ +--- +title: llm constructor offline +description: Build llm handle from env + defaults; no network. +> ext/ai/llm.mq.md +--- + +# main + +*`model` = > llm.llm * +> print text=`model`[^model] +> print text=`model`[^suffix] diff --git a/tests/ext/quantum-bell-smoke.mq.md b/tests/ext/quantum-bell-smoke.mq.md index 27173fc..c0ea248 100644 --- a/tests/ext/quantum-bell-smoke.mq.md +++ b/tests/ext/quantum-bell-smoke.mq.md @@ -3,7 +3,6 @@ title: quantum bell smoke description: H+CX Bell state probabilities ≈ 1/2 each. > ext/quantum/quantum.mq.md > lib/math.mq.md -> lib/json.mq.md --- # main @@ -13,8 +12,8 @@ description: H+CX Bell state probabilities ≈ 1/2 each. *`qc` = > `qc`.cx control=0 target=1 * *`p` = > `qc`.probabilities * -*`p00` = > json.get value=`p` key="00" * -*`p11` = > json.get value=`p` key="11" * +*`p00` = `p`[^00] * +*`p11` = `p`[^11] * *`lo` = > math.div a=2 b=5 * *`hi` = > math.div a=3 b=5 * @@ -35,7 +34,7 @@ description: H+CX Bell state probabilities ≈ 1/2 each. > print text=p11-fail *`ping` = > quantum_ping * -*`ok` = > json.get value=`ping` key=ok * +*`ok` = `ping`[^ok] * 1. `ok` > print text=ping-ok 2. * diff --git a/tests/ext/quantum-gates-smoke.mq.md b/tests/ext/quantum-gates-smoke.mq.md index af13e78..e5ee4e5 100644 --- a/tests/ext/quantum-gates-smoke.mq.md +++ b/tests/ext/quantum-gates-smoke.mq.md @@ -3,7 +3,6 @@ title: quantum gates + run smoke description: Z sandwich, Ry(pi), seeded Bell run counts. > ext/quantum/quantum.mq.md > lib/math.mq.md -> lib/json.mq.md --- # main @@ -15,7 +14,7 @@ H-Z-H on |0⟩ → |1⟩. *`qc` = > `qc`.z qubit=0 * *`qc` = > `qc`.h qubit=0 * *`p` = > `qc`.probabilities * -*`p1` = > json.get value=`p` key="1" * +*`p1` = `p`[^1] * *`lo` = > math.div a=9 b=10 * 1. `p1` > `lo` @@ -29,7 +28,7 @@ Ry(π) on |0⟩ → |1⟩. *`ry` = > quantum.circuit qubits=1 * *`ry` = > `ry`.ry qubit=0 theta=`pi` * *`rp` = > `ry`.probabilities * -*`rp1` = > json.get value=`rp` key="1" * +*`rp1` = `rp`[^1] * 1. `rp1` > `lo` > print text=ry-ok @@ -42,10 +41,10 @@ Bell run with fixed seed: both 00 and 11 appear; shots sum. *`bell` = > `bell`.h qubit=0 * *`bell` = > `bell`.cx control=0 target=1 * *`res` = > `bell`.run shots=200 seed=42 * -*`counts` = > json.get value=`res` key=counts * -*`c00` = > json.get value=`counts` key="00" * -*`c11` = > json.get value=`counts` key="11" * -*`shots` = > json.get value=`res` key=shots * +*`counts` = `res`[^counts] * +*`c00` = `counts`[^00] * +*`c11` = `counts`[^11] * +*`shots` = `res`[^shots] * 1. `c00` 1. `c11` diff --git a/tests/ext/quantum-steps-smoke.mq.md b/tests/ext/quantum-steps-smoke.mq.md new file mode 100644 index 0000000..60cd536 --- /dev/null +++ b/tests/ext/quantum-steps-smoke.mq.md @@ -0,0 +1,37 @@ +--- +title: quantum steps + draw smoke +description: steps= Bell table + draw SVG via record_plot. +> ext/quantum/quantum.mq.md +> lib/math.mq.md +--- + +# main + +`steps` = + +| step | gate | qubits | +|------|------|--------| +| 1 | H | 0 | +| 2 | CX | 0,1 | + +*`qc` = > quantum.circuit qubits=2 steps=`steps` * +*`p` = > `qc`.probabilities * +*`p00` = `p`[^00] * +*`lo` = > math.div a=2 b=5 * +*`hi` = > math.div a=3 b=5 * + +1. `p00` > `lo` + 1. `p00` < `hi` + > print text=steps-ok + 2. * + > print text=steps-fail +2. * + > print text=steps-fail + +*`img` = > `qc`.draw path=quantum-steps-draw.svg * +*`kind` = `img`[^kind] * + +1. `kind` == circuit + > print text=draw-ok +2. * + > print text=draw-fail diff --git a/tests/ext/quantum-zh-smoke.mq.md b/tests/ext/quantum-zh-smoke.mq.md index 2924ce8..2a99707 100644 --- a/tests/ext/quantum-zh-smoke.mq.md +++ b/tests/ext/quantum-zh-smoke.mq.md @@ -3,7 +3,6 @@ title: quantum zh API smoke description: Chinese 量子.电路 泡利Z sandwich. > ext/quantum/量子.mq.md > lib/math.mq.md -> lib/json.mq.md --- # main @@ -13,7 +12,7 @@ description: Chinese 量子.电路 泡利Z sandwich. *`电路` = > `电路`.泡利Z 比特=0 * *`电路` = > `电路`.哈达玛 比特=0 * *`概率` = > `电路`.概率 * -*`p1` = > json.get value=`概率` key="1" * +*`p1` = `概率`[^1] * *`lo` = > math.div a=9 b=10 * 1. `p1` > `lo` diff --git a/tests/ext/web-smoke.mq.md b/tests/ext/web-smoke.mq.md index 270514a..bdbe3dc 100644 --- a/tests/ext/web-smoke.mq.md +++ b/tests/ext/web-smoke.mq.md @@ -35,8 +35,8 @@ description: Offline assemble + render markers (no listen). | 属性 | 值 | 样式 | |------|-----|------| -| `title` | articles.`articles`.title | shell.`card_title` | -| `body` | articles.`articles`.body | shell.`card_body` | +| title | articles.`articles`.title | shell.`card_title` | +| body | articles.`articles`.body | shell.`card_body` | *`page` = > web.page title="smoke" intro="

smoke

" * *`page` = > `page`.compose_components components=`home` * diff --git a/tests/ext/web-zh-smoke.mq.md b/tests/ext/web-zh-smoke.mq.md index 574623c..e28661c 100644 --- a/tests/ext/web-zh-smoke.mq.md +++ b/tests/ext/web-zh-smoke.mq.md @@ -29,8 +29,8 @@ description: Offline Chinese 网页.mq.md assemble (no listen). | 属性 | 值 | 样式 | |------|-----|------| -| `title` | articles.`articles`.title | | -| `body` | articles.`articles`.body | | +| title | articles.`articles`.title | | +| body | articles.`articles`.body | | `seed` = diff --git a/tests/gold.rs b/tests/gold.rs index e76b26f..5ddd44e 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -163,6 +163,31 @@ fn structure_collection_map_list() { ); } +#[test] +fn structure_collection_cell_expr() { + assert_out( + "tests/structure/collection-cell-expr.mq.md", + "sk-live +gpt-4o-mini +https://api.openai.com/v1 +/chat/completions +sk-live", + ); +} + +#[test] +fn structure_bare_id_italic_bold() { + assert_out( + "tests/structure/bare-id-italic-bold.mq.md", + "2 +2 +quoted +7 +ok +hi", + ); +} + #[test] fn structure_footnote_index() { assert_out( @@ -173,6 +198,15 @@ fn structure_footnote_index() { ); } +#[test] +fn structure_footnote_map_digits() { + assert_out( + "tests/structure/footnote-map-digits.mq.md", + "half +other", + ); +} + #[test] fn structure_collection_records() { assert_out( @@ -1418,6 +1452,34 @@ fn ext_quantum_zh_smoke() { assert_out("tests/ext/quantum-zh-smoke.mq.md", "zh-ok"); } +#[test] +fn ext_quantum_steps_smoke() { + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_quantum"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build quantum plugin"); + assert!(status.success(), "failed to build marqdo_plugin_quantum"); + let path = "tests/ext/quantum-steps-smoke.mq.md"; + let (code, stdout, stderr) = run(&["run", path]); + assert_eq!(code, 0, "{path} stderr={stderr}"); + assert!( + stdout.contains("steps-ok"), + "{path} missing steps-ok in {stdout}" + ); + assert!( + stdout.contains("draw-ok"), + "{path} missing draw-ok in {stdout}" + ); + let svg_path = "tests/ext/quantum-steps-draw.svg"; + let svg = std::fs::read_to_string(svg_path).unwrap_or_default(); + assert!( + svg.contains(" trim `raw`* diff --git a/tests/keywords/stdlib.mq.md b/tests/keywords/stdlib.mq.md index 7612d31..df53582 100644 --- a/tests/keywords/stdlib.mq.md +++ b/tests/keywords/stdlib.mq.md @@ -5,7 +5,7 @@ description: Built-in conversions and length # main -*`s` = hello* +*`s` = "hello"* *`n` = > len `s`* diff --git a/tests/keywords/zh-builtins.mq.md b/tests/keywords/zh-builtins.mq.md index 6f6e39a..8d62c2b 100644 --- a/tests/keywords/zh-builtins.mq.md +++ b/tests/keywords/zh-builtins.mq.md @@ -5,7 +5,7 @@ description: 打印 / 长度 / 文本 / 整数(与英文别名等价) # main -*`s` = hello* +*`s` = "hello"* *`n` = > 长度 值=`s`* diff --git a/tests/lib/subtask-child-print.mq.md b/tests/lib/subtask-child-print.mq.md index 73d6331..0279822 100644 --- a/tests/lib/subtask-child-print.mq.md +++ b/tests/lib/subtask-child-print.mq.md @@ -6,4 +6,4 @@ title: subtask child that prints > print text=hello-from-child -**child_ok** +**"child_ok"** diff --git a/tests/lib/subtask-child.mq.md b/tests/lib/subtask-child.mq.md index dc63ead..2f13baa 100644 --- a/tests/lib/subtask-child.mq.md +++ b/tests/lib/subtask-child.mq.md @@ -4,4 +4,4 @@ title: subtask child # main -**child_ok** +**"child_ok"** diff --git a/tests/structure/bare-id-italic-bold.mq.md b/tests/structure/bare-id-italic-bold.mq.md new file mode 100644 index 0000000..c3c0165 --- /dev/null +++ b/tests/structure/bare-id-italic-bold.mq.md @@ -0,0 +1,37 @@ +--- +title: bare id in italic and bold +description: Inside *…* / **…**, bare ids are variables; strings need quotes. +--- + +# main + +*answer = 1* +*n = answer + 1* +*`ticked` = 2* +*`s` = 'quoted'* + +> print text=`n` +> print text=`ticked` +> print text=`s` + +*`a` = > ret_var x=7* +> print text=`a` + +*`b` = > ret_str* +> print text=`b` + +*`c` = > ret_single* +> print text=`c` + +## ret_var + + `x` + +**x** + +## ret_str + +**"ok"** + +## ret_single + +**'hi'** diff --git a/tests/structure/collection-cell-expr.mq.md b/tests/structure/collection-cell-expr.mq.md new file mode 100644 index 0000000..4f46d47 --- /dev/null +++ b/tests/structure/collection-cell-expr.mq.md @@ -0,0 +1,35 @@ +--- +title: table cell expressions +description: Data cells evaluate like call-arg values (`var`, paths, hyphen prose). +--- + +# main + +*`secret` = "sk-live" * +*`name` = "gpt-4o-mini" * + +`cfg` = + +| api_key | model | base | +|---------|-------|------| +| `secret` | `name` | https://api.openai.com/v1 | + +> print text=`cfg`[^api_key] +> print text=`cfg`[^model] +> print text=`cfg`[^base] + +`paths` = + +| p | +|---| +| /chat/completions | + +> print text=`paths`[^1] + +`rec` = + +| @ | role | content | +|---|------|---------| +| 1 | user | `secret` | + +> print text=`rec`[^1][^content] diff --git a/tests/structure/collection-map.mq.md b/tests/structure/collection-map.mq.md index 81222ab..5b13dd0 100644 --- a/tests/structure/collection-map.mq.md +++ b/tests/structure/collection-map.mq.md @@ -22,5 +22,5 @@ title: 横表单行 → 字典 > print text=`种` -- [`键`](`分类`) +- [键](分类) > print text=`键` diff --git a/tests/structure/collection-records.mq.md b/tests/structure/collection-records.mq.md index c691f1a..ca6e33c 100644 --- a/tests/structure/collection-records.mq.md +++ b/tests/structure/collection-records.mq.md @@ -23,5 +23,5 @@ title: 行向记录表(首列 行 / @) > print text=`量` -- [`记录`](`订单`) +- [记录](订单) > print text=`记录` diff --git a/tests/structure/collection.mq.md b/tests/structure/collection.mq.md index 7604560..4f7f200 100644 --- a/tests/structure/collection.mq.md +++ b/tests/structure/collection.mq.md @@ -12,5 +12,5 @@ title: 集合(表格)示例 | 梨 | | 桃 | -- [`果`](`篮子`) +- [果](篮子) > print text=`果` diff --git a/tests/structure/footnote-index.mq.md b/tests/structure/footnote-index.mq.md index 94b65b8..b91d3cc 100644 --- a/tests/structure/footnote-index.mq.md +++ b/tests/structure/footnote-index.mq.md @@ -12,7 +12,7 @@ title: 脚注取元(列表下标) | 梨 | | 桃 | -*`第一` = `篮子`[^1] * +*`第一` = 篮子[^1] * > print text=`第一` @@ -20,6 +20,6 @@ title: 脚注取元(列表下标) > print text=`第二` -*`第三` = `篮子`[^3] * +*`第三` = 篮子[^3] * > print text=`第三` diff --git a/tests/structure/footnote-map-digits.mq.md b/tests/structure/footnote-map-digits.mq.md new file mode 100644 index 0000000..60a954a --- /dev/null +++ b/tests/structure/footnote-map-digits.mq.md @@ -0,0 +1,18 @@ +--- +title: map footnote digit keys +description: Pure-digit labels are map keys (text), not list indices. Bare base ok. +--- + +# main + +`p` = + +| 00 | 11 | +|----|----| +| half | other | + +*`a` = p[^00] * +*`b` = `p`[^11] * + +> print text=`a` +> print text=`b` diff --git a/tests/structure/loop.mq.md b/tests/structure/loop.mq.md index d130d1d..019a59b 100644 --- a/tests/structure/loop.mq.md +++ b/tests/structure/loop.mq.md @@ -21,5 +21,5 @@ title: 循环示例 | 苹果 | | 梨 | -- [`果`](`篮子`) +- [果](篮子) > print text=今天吃`果`