diff --git a/.cursor/skills/marqdo-dev/SKILL.md b/.cursor/skills/marqdo-dev/SKILL.md index 542cd43..3d9ed31 100644 --- a/.cursor/skills/marqdo-dev/SKILL.md +++ b/.cursor/skills/marqdo-dev/SKILL.md @@ -140,15 +140,17 @@ Matching surrounding **legacy** `json.set` in `ext/ai/*.mq.md` is **not** compli 3. `##` handlers: short prose OK; data as tables; return via `browser.*` / `web.*` / one `table.put`. 4. Blank line between comment paragraphs and code. 5. Run `marqdo run path.mq.md` from repo root. -6. **Calls in narrative:** prefer `**结果 = 某函数 名=`x`**` (no `>` on the RHS). Bracket form `礼貌 [问候] "x"` / `**出 = [put] …**` is fine when modifiers help. Use `> …` for standalone step lists. See `examples/code-as-docs/`. +6. **Calls in narrative:** explain the action in its sentence, for example `` 读取之后得到**结果 = [读取文件](文件.读文本(路径=`路径`))**。 `` Return in the sentence with `` 完成后返回*结果*。 `` Keep real control structures and data tables separate when that improves reading. The label describes intent; the payload contains the actual call. See the executable library development guide. 7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead. -8. **Index:** prefer `[键](集合)` / `` [`名`](集合) `` over footnote `` m[^k] ``. +8. **Index:** use `access(collection, key)` (or `取`); `[描述](payload)` is executable occlusion, never an index by label. Browser client programs: prefer nested `import:` with `browser: lib/browser.mq.md` (no native plugin). Server sites: Artifact Metadata (`type: web|endpoint`) + `ext/web` facade + `ext/data` / `ext/security` / `ext/net` — see [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). **Never** restore `compose_*` / `app.configure`. ## Developing libraries (`lib/*`, `ext/*`) -Canonical thin-template + waves: [lib-code-as-docs.md](../../doc/design/lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../../doc/roadmap/lib-ext-code-as-docs.md). +Start with the [executable library development guide](../../../doc/library-development.mq.md): parameter/return tables below headings, prose >50%, inline assignments/returns and occlusion labels. Single-file stdlib needs no index; multi-file extensions organize through index.mq.md. + +Design background + waves: [lib-code-as-docs.md](../../doc/design/lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../../doc/roadmap/lib-ext-code-as-docs.md). ### Goals @@ -156,14 +158,20 @@ Canonical thin-template + waves: [lib-code-as-docs.md](../../doc/design/lib-code - One concern per helper; name the effect (`set_text`, `canvas`, …), do not expose bag surgery. - EN + ZH pair when shipping user-facing libs (`lib/browser.mq.md` ↔ `lib/浏览器.mq.md`, `ext/web` ↔ `ext/web/网页.mq.md`). - `ext/**` never calls `host_*` — use plugins / public lib only (`doc/design/ext-agent.md`). -- Collection get: **`[key](coll)`** (no new footnote indexes). Calls in examples may use `修饰 [fn] …` or classic `>` / bold. +- Collection get: **`access(coll, key)`**; bracket labels are inert descriptions. Calls in examples may use `修饰 [fn] …` or classic `>` / bold. ### Library checklist -- [ ] Purpose sentence + prose params + one example + short body +- [ ] Single-file stdlib is its own handbook; no forced index/module guide directory +- [ ] Parameter/type/default table directly below the function heading, then return contract +- [ ] Prose parameters; remove legacy `+` declarations in standard library sources +- [ ] Explain purpose, real input shape, output, failure and limits; narrative >50% per function +- [ ] Put assignments, occlusion calls and returns in explanatory sentences where natural; reserve separate blocks for real structure +- [ ] Use `[action](actual code)` inside return/statement markers for opaque host calls +- [ ] One actual example + short implementation; never pad prose to satisfy the ratio - [ ] Public examples use **tables + helpers**, not json glue -- [ ] Index with `[k](c)`; foreach `- [item](coll)` -- [ ] Helpers documented with a one-line purpose above `##` +- [ ] Read with `access(c, k)`; foreach `- [description](遍历 coll 为 item)` +- [ ] Function heading names the tool; tables and task explanation follow it - [ ] Defaults on params; omit `None` fields in merged maps - [ ] No `json.set` chains in new code — use `table.put` / `table.merge` / GFM - [ ] `marqdo run` on a tiny demo under `examples/` or inline smoke diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 8b0f024..37afebb 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -26,7 +26,7 @@ These rules are the **current default**. Do **not** teach Classic `[key](map)` i 4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion. 5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code. 6. **Import / call:** frontmatter `import:` / `导入:`; call `lib.member`. One language (EN or ZH) per file. -7. **Control flow:** `#` object/type, `##`+ function, `+` params, `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. +7. **Control flow:** `#` object/type, `##`+ function, prose params (legacy `+` remains parseable), `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. 8. **Prose vs code:** blank line separates comment paragraphs from executable lines. 9. **GFM tables** for data; prefer `table.put` over `json.set` chains. `ext/**` never calls `host_*`. 10. Body narrative `[描述](target)` is lazy (NarrativeRef) — reading does not execute side effects. @@ -48,7 +48,7 @@ Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executabl ## Hard rules (do not violate) 1. Obey **CORE SYNTAX** above — Occlusion is default; do not emit Classic index links. -2. **Identifiers:** params `` + `name` ``; inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. +2. **Identifiers:** declare library parameters in prose as `` input `name` `` (defaults follow `=`); inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. 3. **Structure lines** (`#` `>` `+` `-` `|`) are not wrapped in italics. 4. **Paths:** bare `/` in expressions is division; in call args / table cells unspaced `a/b` is path text. Ratios as text need quotes (`"1/5"`). 5. End side-effect-only helpers with `*None*` / `*空*` / `**` / `****` when the outer function continues. Lone `---` is a thematic break, not function end. @@ -136,6 +136,9 @@ Chinese builtins (same functions, no import): ## Frontmatter imports + stdlib +A standard library is normally one `lib/*.mq.md` file: read/import/call that file directly. It is its own manual and skill; no `index.mq.md` or module handbook directory is required. Each function puts parameter/default and return tables directly below its heading, explains purpose, failures and limits, and keeps narrative above 50%. Use prose parameters, not legacy `+` declarations. Describe opaque instructions with `[what it does](actual code)` inside statement/return markers; labels do not execute. Multi-file extensions use an index to organize their files. File tools require explicit `--effects fs.read` or `--effects fs.write` with `--fs-root`; real workflows live in `examples/stdlib-handbook`. Read the [executable authoring guide](../../../doc/library-development.mq.md) for inline prose and complete runnable examples. + + Imports use nested YAML `import:` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: ```markdown diff --git a/Cargo.lock b/Cargo.lock index 755aeed..8f2de45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -186,6 +186,27 @@ dependencies = [ "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6dd8046d00723a59a2f8c5f295c515b9bb9a331ee4f8f3d4dd49e428acd3b6" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f10f8c9340e31fc120ff885fcdb54a0b48e474bbd77cab557f0c30a3e569402" +dependencies = [ + "parse-zoneinfo", + "phf_codegen", +] + [[package]] name = "chunked_transfer" version = "1.5.0" @@ -307,6 +328,12 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "find-msvc-tools" version = "0.1.10" @@ -414,6 +441,12 @@ dependencies = [ "wasi", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + [[package]] name = "heck" version = "0.4.1" @@ -525,6 +558,16 @@ dependencies = [ "quote", ] +[[package]] +name = "indexmap" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -577,6 +620,7 @@ dependencies = [ "anyhow", "assert_cmd", "chrono", + "chrono-tz", "clap", "futures-util", "getrandom", @@ -597,6 +641,7 @@ dependencies = [ "tiny_http", "tokio", "tokio-tungstenite", + "toml", "ureq", "zeroize", "zip", @@ -727,12 +772,59 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -971,6 +1063,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "sha1" version = "0.10.6" @@ -1005,6 +1106,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" @@ -1152,6 +1259,47 @@ dependencies = [ "tungstenite", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + [[package]] name = "tungstenite" version = "0.24.0" @@ -1493,6 +1641,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + [[package]] name = "zerocopy" version = "0.8.56" diff --git a/Cargo.toml b/Cargo.toml index 46d30b5..28d9716 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,8 @@ zip = { version = "=0.6.6", default-features = false, features = ["deflate"], op libloading = { version = "=0.8.6", optional = true } include_dir = "0.7" libc = { version = "0.2", optional = true } +chrono-tz = "=0.10.0" +toml = "=0.8.23" [target.'cfg(target_arch = "wasm32")'.dependencies] # Custom entropy — no `js`/wasm-bindgen imports (raw mq_* ABI + marqdo-bridge.js). diff --git a/README.md b/README.md index 7c50926..a5a5172 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ v2.2.0 起,`marqdo call` 可以直接调用这份文件里的一个函数。 --- +标准库单文件本身就是手册:直接阅读[文件库](lib/文件.mq.md)、[集合库](lib/表.mq.md)等源码,按函数标题下的参数表、返回契约和动作说明调用;[工程实践](examples/stdlib-handbook/索引.mq.md)演示文件整理、CSV 汇总与文档维护。 +开发标准库和拓展库请直接阅读[可执行库开发指南](doc/library-development.mq.md):契约表、叙述式实现、遮蔽调用与多文件工程组织均有可运行示范。 + + ## 核心优势:可执行知识(Executable Knowledge) > **Knowledge That Can Run —— 知识即可执行。** diff --git a/doc/README.md b/doc/README.md index e0718ce..e7a473d 100644 --- a/doc/README.md +++ b/doc/README.md @@ -27,6 +27,7 @@ | [跨库缺陷复核(2026-10-26)](../../qdagent/doc/gaps/04-workbench-runtime-and-product-audit-2026-10-26.md) | **最新源码与测试证据**:实际 HTTP 路由、知识发布/阅读断点、旧缺陷处置及 1000 单元编译性能失败;需同级 qdagent checkout | | [design/qdagent-workbench-runtime-and-view-2026-10-25.md](design/qdagent-workbench-runtime-and-view-2026-10-25.md) | **qdagent 知识工作台框架支持**:M00–M05 合同落地中(`src/workbench/`、MLSP `capabilities` / `view.document` / `view.reference_resolve`、`tests/workbench_contracts.rs`);完整 verified 以切片验收证据为准 | | [design/view-knowledge-reading-experience-2026-10-24.md](design/view-knowledge-reading-experience-2026-10-24.md) | **View 知识阅读体验重设计(建议)**:正文优先、结构导航、就地知识说明、来源与运行状态、响应式线框、实现契约与验收;含当前呈现和 no-exec 反例 | +| [design/view-readable-actions.md](design/view-readable-actions.md) | **View 阅读优化实现**:动作留在正文、实际逻辑引到侧注、空逻辑明确标识;语法阅读指南、输入输出与依据卡片、单文件依赖分析及浏览器验收 | | [roadmap/qdagent-knowledge-support-gaps-2026-10-24.md](roadmap/qdagent-knowledge-support-gaps-2026-10-24.md) | **求道知识沉淀与文档编译支撑缺口**:2.1.1 源码复核、来源/依赖失效反例、验证与 Agent 协议、语法提示词、导入底座及跨库分工 | | [design/document-native-development-guide.md](design/document-native-development-guide.md) | **下一阶段开发指导**:语法审查裁决、正文→命名→复用工作流、AI 上下文与局部编辑、渐进严格、作者成本及 S0–S6 验收 | | [design/core-surface.md](design/core-surface.md) | **核心构造清单**:v2.1 默认链接/循环说明与构造守卫;不是全部实现状态清单 | @@ -48,6 +49,7 @@ | [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置函数** | | [design/keywords-i18n.md](design/keywords-i18n.md) | **内核中英双名(无需导入;少而精)** | | [design/module-namespace.md](design/module-namespace.md) | **模块命名空间:导入绑定库名、`库.成员` / `use`(M1+M2 已落地)** | +| [library-development.mq.md](library-development.mq.md) | **可执行库开发指南**:单文件标准库、多文件拓展库、叙述超过 50%、标题下参数与返回表、句中赋值/返回和遮蔽调用;含真实调用及失败场景 | | [design/stdlib.md](design/stdlib.md) | **标准库:内置 + `lib/` + 错误约定** | | [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** | | [design/stdlib-modules.md](design/stdlib-modules.md) | **L1:文件/系统/时间/JSON/网络/数学/外联/插件** | diff --git a/doc/design/lib-code-as-docs.md b/doc/design/lib-code-as-docs.md index f24568d..ab3fd17 100644 --- a/doc/design/lib-code-as-docs.md +++ b/doc/design/lib-code-as-docs.md @@ -1,5 +1,7 @@ # 标准库 / 扩展库:代码即文档 +当前可执行开发规范见[库开发指南](../library-development.mq.md),其中的真实函数示范叙述内赋值、遮蔽调用、表格数据与返回。本页保留设计背景与历史波次。 + | | | |---|---| | 状态 | **Active** | @@ -10,39 +12,51 @@ ## 1. 目标 -`lib/*` 与 `ext/*` 的 `.mq.md` 应**可当说明书读、可当程序跑**。薄库不写长文;厚领域库(web / quantum / …)仍用叙述承载意图,但数据与调用面与用户程序同一套标记。 +`lib/*` 与 `ext/*` 的 `.mq.md` 应**可当说明书读、可当程序跑**。薄库用充分且具体的叙述解释短实现;厚领域库(web / quantum / …)仍用叙述承载意图,但数据与调用面与用户程序同一套标记。 -## 2. 薄库模板(默认) +## 2. 单文件标准库模板 -每个导出函数 / 方法尽量按此骨架(中英分文件锁步): +标准库通常是一个 `lib/*.mq.md` 文件,源码自身承担使用手册、开发说明与 SKILL。 +直接阅读、导入或调用此文件,不增加强制 `index.mq.md` 或平行模块手册。 +多文件拓展库才用 `index.mq.md` 组织模块与开发路线。 -1. **目的句**(一句人话,无标记即可)。 -2. **叙述形参**:正文里出现 `` `名` `` / `` `名`=默认 ``(推断签名);过渡期可保留 `` + `名` ``。 -3. **一例**:粗体或 `>` 调用;优先可读表面。 -4. **实现**:短;取元用 `[键](集合)`,**禁止新增**脚注取元 `` `m`[^k] ``(旧解析仍可用)。 +每个函数依次提供:标题、参数表(名称、类型、默认值、含义)、返回契约、效应说明、 +叙述形参、用途与真实调用例子、简短实现。无参数函数直接放返回表。 +参数和返回契约位于第一条执行语句之前;标准库不再保留旧 `+` 形参清单。 -调用示例(三种等价,试点期任选;新叙述优先括号标记或粗体): +叙述形参使用正文中的反引号名称,默认值紧跟等号;表格说明与实际默认值必须一致。 +例如正文写「输入路径 `path`」,调用时即可提供 path。含标点的文本默认值使用完整引号。 +不透明类型保留渐进式 any,并说明其产生途径和限制。 + +## 3. 可读性与调用规范 + +每个函数单元的叙述比例必须超过 50%,同时说明真实用途和边界;不能靠重复套话凑比例。 +参数和返回契约表属于文档面,绑定的数据表仍须表达真实数据。 + +宿主等不透明调用用遮蔽语法表达动作:`[]` 写做什么,`()` 写实际执行代码。 +返回和赋值仍遵循原有标记;标签不执行,也不替代失败处理。 ```markdown -**出 = [put] 入=`表` 键="a" 值=1** +## read_text -**出 = put 入=`表` 键="a" 值=1** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | 必填 | 授权根目录内的文件路径 | -> put 入=`表` 键="a" 值=1 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | UTF-8 文本;无效编码或读取失败产生诊断 | + +输入路径 `path`。此操作读取整个文件;大文件应改用分块读取。 +文件根目录由调用方授权,不能通过传入路径绕过权限。 + +读取完成后,我们返回*[读取授权范围内的 UTF-8 文本](> host_read_text path=`path`)*,供调用方继续处理。 ``` -带布尔开关时可用前置修饰:`严格 [parse] text=`源`` → `严格=True`(形参名与修饰语字面一致;核心不剥「的」等词缀)。 - -## 3. 硬约束 - -| 要 | 不要 | -|----|------| -| GFM 表作数据;`table.put` / 具名助手 | `json.set` 链当字典构造器 | -| 作者程序用 `[k](c)` 取元;`- [项](集合)` foreach | 新代码写 `` m[^k] `` | -| 中英 API 对称(见 [stdlib-i18n.md](stdlib-i18n.md)) | 只改一侧 | -| 一例跑通即文档(public/stdlib 或 examples) | 另开第二套「文档站」手写说明 | - -**库函数体内的叙述坑:** 函数体里的链接形 `[k](c)`、以及单独的 `**强调**` 会被当成可执行代码。库内说明用「链接取元 / link-index」等字面描述;可执行示例放在 `public/stdlib` 或 `examples/`,不要写在 `##` 体内当叙述。 +集合读取使用 access(collection, key),不使用旧链接取元;循环使用显式遍历。 +用 GFM 表和具名助手表达结构化数据,避免 json.set/json.append 链。 +说明中的调用示例放在未绑定代码围栏内,不能让示例意外成为函数执行步骤。 +中英文源码保持语义、默认值与行为一致;检查叙述比例、契约并执行真实示例。 ## 4. 波次 diff --git a/doc/design/stdlib-handbook.md b/doc/design/stdlib-handbook.md new file mode 100644 index 0000000..729c180 --- /dev/null +++ b/doc/design/stdlib-handbook.md @@ -0,0 +1,130 @@ +# 标准库:代码、文档、SKILL 与 tools 同源 + +标准库通常是单文件:直接阅读并调用 [fs.mq.md](../../lib/fs.mq.md)、[文件.mq.md](../../lib/文件.mq.md)、[table.mq.md](../../lib/table.mq.md) 或其他任务所需源码。 +31 个模块族对应 61 份公开标准库单文件;源码本身承担手册与 SKILL,不设强制总入口或模块 index。 +多文件拓展库的 index 用于组织多文件,标准库沿用其可读性和调用规范。 + +## 源码就是手册 + +每个函数标题下立即放参数表(名称、类型、默认、含义),随后是返回契约、效应、叙述形参、 +用途和边界、实际调用例子及短实现。无参数函数直接放返回表。旧 `+` 形参已移除。 +契约表位于首条执行语句之前;默认值和参数顺序保持兼容。 + +叙述比例逐函数超过 50%;既检查比例,也检查真实契约、调用和错误语义。 +不透明宿主指令使用遮蔽调用,例如 `` *[读取 UTF-8 文本](> host_read_text path=`path`)* ``: +方括号说明目的,圆括号执行真实代码;赋值语句同样采用描述标签。 +标签不替代参数与权限,也不能用空标签或重复模板代替说明。调用与返回自然写入正文; +行内表达式仍计作代码,绑定数据表不冒充叙述。125 份库源码的统一验收见 +[本轮记录](../roadmap/library-authoring-refactor.md),公共标准库当前为 650 个函数。 +键值行记录可用 table.from_pairs / 表.键值转记录生成具名记录,保留空值和重复键更新语义。 + +## 接口事实来自编译器 + +现有 call、catalog、MLSP 与编译器读取同一份标准库源码,不额外包装一层目录函数或示例函数。 +`examples/stdlib_catalog.rs` 使用实际装载、签名和效应结果检查源码中的效应说明; +--json 输出接口事实,--write 仅刷新效应说明,不生成第二套手册。 +人工维护用途、参数含义、失败处理和工程实践。不透明值保留渐进式 any,并说明来源和限制。 + +```sh +cargo run --example stdlib_catalog -- --json +cargo run --example stdlib_catalog -- --check +marqdo check lib/文件.mq.md --narrative-ratio +cargo test --test stdlib_tasks +``` + +测试直接读取 61 份公开源码中的实际命令,在 Tree 与 Bytecode 执行 126 次。 +验证每个函数的参数/返回契约、标题下表格、无旧形参声明以及逐函数叙述比例。 + +## 能力与兼容性 + +| 任务 | 新的公共入口 | 关键契约 | +|---|---|---| +| 文件整理 | fs.find/read_lines/write_lines/read_json/write_json/read_csv/write_csv | 明确根目录、格式和资源上限 | +| 文件修改 | atomic_write/write_changed/write_checked | 单文件原子替换;摘要检查不是内核 CAS,竞争写入仍需协调 | +| 批量文件 | copy_tree/sync_tree/rename_many | 先预检冲突,覆盖需选择;不承诺多文件事务;目录复制面向普通文件,不复制权限、链接与空目录 | +| 临时文件 | make_temp/temp_dir | 在授权根目录创建,由调用方明确清理;真实工程演示清理 | +| 二进制 | bytes 与 fs.read_bytes/write_bytes/read_chunk/append_bytes/file_hash | 普通 bytes 记录,Base64 跨 CLI/JSON/插件传递,字节偏移从零起 | +| 集合 | range/enumerate/pluck/project/where/find/any/all | 不增加回调字符串求值或新的查询方言 | +| 表数据 | group_by/aggregate/summarize/join/rename/unique_by/sort_keys | 行记录、分组键和字段含义明确;批量汇总避免作者循环反复复制列表 | +| 数据形态 | from_columns/to_columns/cast/try_cast/validate | 不猜测列式表与普通对象;列长、字段及类型错误有明确结果 | +| 集合运算 | union/intersection/difference | 返回保序列表,沿用运行时值相等规则 | +| 网络 | net.get/request/download/header_values | 超时、响应上限、重复响应头、字节响应;失败下载保留原文件 | +| 配置与日期 | toml.parse/stringify、datetime.parse_local/add_calendar | 标准 TOML;内嵌 IANA 规则;夏令时缺口和重叠明确失败或选择 | +| 子任务 | wait_timeout/cancel_all/run_many | 文件任务并发上限、超时终止回收、父权限与根目录继承 | +| 文档维护 | document.sections/section/tables/links/code_blocks/replace_section/replace_table | 与渲染共用 Markdown 解析器,不执行文档,保留周围源码 | +| 归档 | archive.pack/unpack | 可选 ZIP,预检路径、链接、重复项和展开上限,目标必须不存在 | + +旧 remove 保持递归删除行为,公开文档已纠正;新代码用 remove_file/remove_empty_dir。 +access 与 put 的整数路径从一开始;旧 at/slice/insert/remove_at 等接口从零开始,不能混用。 +更新返回新集合,原值保留;单次追加仍有复制成本。规模任务使用批量变换,去重使用分桶并保留原相等语义。 +混合排序采用明确类型顺序,修复数字与文本混排造成非传递比较的问题。 +大下标在 32/64 位目标上保持一致:取元越界为空,更新越界为诊断,巨大分块大小不会截断成零或导致死循环。 + +## 权限与错误 + +宿主身份声明效应,编译器沿解析后的依赖传播,不依据 fs、net 等导入别名猜测。 +函数、BoundCall 和步骤共享最终效应,外部标准库和中英文别名也使用同一逻辑。 + +```sh +marqdo call lib/fs.mq.md read_text 'path="notes.md"' --effects fs.read --fs-root /absolute/project --json +marqdo call lib/fs.mq.md atomic_write 'path="notes.md"' 'text="updated"' --effects fs.write --fs-root /absolute/project --json +``` + +默认 none 只准纯函数;fs.write 包含读取授权,其余能力仍需明确选择。 +plugin 保留加载提示所需的既有能力,不增加文件写入、网络或进程执行授权。 +根目录检查覆盖新文件的最近已存在父路径与符号链接越界。 +会话保存规范化根目录与可持久化结果;重建会话不重复文件、网络或进程写操作。 +不可重放写操作缺少快照时明确拒绝,不能为了重建句柄偷偷重做。 + +可恢复操作统一返回 `{ok,value,error}`,错误含 code/message/operation,校验错误可附 details。 +代码来自明确错误标签与 IO 错误种类,不扫描任意路径文本猜类别。Result 不授权操作,也不捕获任意语言错误。 +CLI 外层 ok 表示调用成功;函数值的 Result.ok 表示操作协议成功;HTTP status、子进程 code 仍需按领域判断。 +语法、契约与不可恢复运行错误继续使用原有结构化 Diagnostic,保留库来源和调用点。 + +## 平台与资源边界 + +| 能力 | 原生 | WebAssembly 浏览器目标 | CoW 试运行 | +|---|---|---|---| +| 集合、文本、JSON/CSV/TOML、字节数据、文档结构、静态时区计算 | 支持 | 纯计算可构建;具体浏览器熵/时钟依赖桥接 | 支持 | +| 原生文件与分块 IO | 支持 | 未接入浏览器文件系统时明确不可用 | 文件内容经覆盖层;已有目录枚举/元数据为宿主快照,试运行变更用 sandbox.diff/inspect | +| 文件复制、移动、追加与文本补丁 | 支持 | 无原生 FS | 经覆盖层;复制最多 64 MiB,不绕过试运行写入真实文件 | +| 目录状态、目录树批处理、归档、流式下载 | 支持 | 原生专属能力不可用 | 未建模的目录/原生任务明确拒绝 | +| HTTP、进程、动态插件 | 按构建特性支持 | 原生接口不可用;浏览器使用 browser 效果与桥接 | 依 profile/caps,不以库包装绕过 | +| 子任务取消 | 进程可终止并回收 | 不提供原生子进程 | 函数线程仅逻辑取消;有界批处理只接收文件任务 | + +新增有界读取默认 8 MiB、上限 64 MiB;旧 read_text 及其格式组合接口保留整文件读取语义,大文件使用 read_chunk/file_hash;原生文件摘要和下载使用 64 KiB 缓冲区。 +查找最多十万条目;序列和连接最多一百万结果;文件批处理最多一万任务、六十四并发。 +HTTP 时限与字节上限由调用方明确设置;不自动重试可能修改远端状态的请求。 +TOML 日期转换为 ISO 文本;写出不保留注释,None 和非有限数没有支持的表示。 +IANA 数据随锁定依赖交付,不声称总是最新政策数据。ZIP 不提供完整备份语义。 + +## 真实工程与验收 + +[标准库工程](../../examples/stdlib-handbook/index.mq.md)和[中文入口](../../examples/stdlib-handbook/索引.mq.md)同时完成: + +1. 扫描 Markdown,保留逐文件读取结果;坏 UTF-8 不阻止其他记录。 +2. 读取 CSV,转换字段,筛选并批量分组汇总,输出 CSV。 +3. 精确替换章节,以读取文本的摘要检查来源,保留其他叙述并原子写入。 + +`tests/stdlib_tasks.rs` 验证公开文档和双后端,而非只测私有宿主调用。 +附加测试覆盖 CoW 不落盘、写入快照不重放、超时后继续等待、网络参数预检、重复响应头、 +失败下载保留目标、ZIP 越界与链接、夏令时、TOML、混合排序和十万项去重。 +旧诊断测试从编译器 AST 定位库指令,继续严格检查独立调用点;不再因添加文档而依赖固定行号。 + +## 构建验证 + +原生默认特性、精简 wasm-core 特性、真实 wasm32 交叉编译均已验证。 +浏览器 ABI 与 `tests/wasm/stdlib.mjs` 在当前 wasm 产物上由 Node 执行,覆盖集合、字节、 +文档、TOML、IANA/DST、32 位大下标与嵌套路径诊断。Node 验收不是浏览器 DOM 布局验收。 + +发行版 rustc 与官方 wasm 标准库的构建元数据不能混用;本次使用同版本匹配的官方组件, +校验后在临时目录构建并执行,不依赖修改系统工具链。复现时使用已安装对应 wasm32 标准库的工具链: + +```sh +cargo check --no-default-features --features wasm-core +cargo build -p marqdo-wasm --target wasm32-unknown-unknown +node tests/wasm/smoke.mjs target/wasm32-unknown-unknown/debug/marqdo_wasm.wasm +node tests/wasm/stdlib.mjs target/wasm32-unknown-unknown/debug/marqdo_wasm.wasm +``` +单文件结构修正后,全量 970 项测试通过,0 失败,2 个原有忽略项;其中包括 17 项标准库工程测试。 +完整命令、分轮计数和交叉目标结果见[实施验收记录](../roadmap/stdlib-executable-handbook.md)。 diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md index 4efbf4d..0f2b6cf 100644 --- a/doc/design/stdlib-modules.md +++ b/doc/design/stdlib-modules.md @@ -1,5 +1,7 @@ # 标准库 L1 模块 +直接阅读并导入标准库单文件,例如 [文件](../../lib/文件.mq.md)和[表](../../lib/表.mq.md)。每个文件自身就是手册,函数标题下给出参数表、返回契约和动作说明;不要求额外 index。模块分层与历史波次见下表,当前规范见[标准库说明](stdlib-handbook.md)。 + | | | |---|---| | 状态 | **核心已落地**;**Mid M1–M6 已落地**;**Mid2 规划中** · [stdlib-mid2.md](stdlib-mid2.md) / [roadmap/stdlib-mid2.md](../roadmap/stdlib-mid2.md) | diff --git a/doc/design/view-markup-surface.md b/doc/design/view-markup-surface.md index c97a404..66eac91 100644 --- a/doc/design/view-markup-surface.md +++ b/doc/design/view-markup-surface.md @@ -16,17 +16,22 @@ | AST / 概念 | View 优先显示 | 备注 | |------------|---------------|------| -| `Expr::Index` | `[键](基)` | 嵌套 `[k2]([k1](base))` | -| `InterpPart::Index` | 同上嵌套链接形 | 不再默认 `` `base`[^k] `` | +| `Expr::Occluded` | 正文只读动作说明,实际实现进入侧注 | 每个片段独立关联,不把整句改成一次赋值 | +| 空遮蔽 `()` | 待补充实际逻辑 | 当前空遮蔽返回 None,不伪装成已接通工具 | +| `Expr::Index` / `InterpPart::Index` | 保留经典或脚注取元的兼容说明 | 当前作者程序优先用 access 读取集合;默认链接形是遮蔽 | | `CallExpr` + `bracket_marked` / `pre_modifiers` | `修饰 [callee] 实参…` 或 `[callee] 实参…` | 仅经典 `>` 解析时仍显示 `> callee …` | -| 赋值 / 返回 | 粗体 / 斜体语义即可 | 不强制还原整句叙述 | -| foreach | `- [项](集合)` | 不变 | +| 赋值 / 返回 | 保留原叙述句子,在真实执行片段上标明语句或返回 | 普通链接与字面量不冒充执行遮蔽 | +| foreach | `- [动作](遍历 集合 为 项)` | 正文显示动作,控制逻辑见侧注;迭代选择器只切换已有运行记录 | ## 3. 非目标 - 不把 view 做成第二语法;解析真相仍在 mapping / call-arguments。 - 不删除对脚注取元、旧 `>` 调用的兼容显示需求时,可用次要提示,但默认推荐面优先。 +当前阅读器的实现与验收见 [view-readable-actions.md](view-readable-actions.md)。 +可执行知识先展示输入、返回、调用边界、依赖和各项依据;摘要和机器身份按需展开。 +源码说明与运行标注分开,展开侧注或知识卡片不会执行代码。 + ## 4. 修订历史 | 日期 | 说明 | diff --git a/doc/design/view-readable-actions.md b/doc/design/view-readable-actions.md new file mode 100644 index 0000000..751e414 --- /dev/null +++ b/doc/design/view-readable-actions.md @@ -0,0 +1,47 @@ +# View:动作留在正文,逻辑留在侧注 + +本轮针对阅读界面,不改变语言求值和工具权限。阅读示例为 +[view-reading.mq.md](../../examples/view-reading.mq.md)。 + +遮蔽按真实 AST 识别,随后按源片段保留句子:方括号的动作说明留在正文,圆括号中的 +实现进入独立侧注。同一句话可以包含多个调用和返回,不再把整行当成一次赋值。 +文字字面量中的链接、普通 Markdown 导航与 classic 取元不冒充执行遮蔽。 +空圆括号明确显示“待补充实际逻辑”,并说明当前空遮蔽返回 None。 + +宽屏实现侧注与运行标注共用现有的左右避碰及引出线布局,彼此有明确名称区分。 +实现侧注标记“源码说明 · 不是运行结果”,不带调用帧或迭代帧身份。 +密集区域、窄屏和无脚本页面使用可原生展开的 details;动作按钮可按需查看完整逻辑。 +悬停与键盘聚焦关联实际源片段,不触发运行。 + +“怎样读这份可执行文档”沿用核心构造注册表,说明参数、赋值、返回、调用、条件、 +循环、数据表、代码块、公式、写回与兼容标记。公式和外语代码仍使用既有卡片, +不新增语法或作者必填的展示配置。 + +可执行知识按真实源单元分组。默认先读输入、返回、调用边界、依赖和验证依据, +身份、摘要与原始状态收进技术详情。契约说明来自已解析的参数和返回表;缺失时如实说明。 +语法检查、契约检查、测试、来源和领域审阅分别展示,静态分析不代表实际执行或内容正确。 +源码结构步骤与实际运行时序分开;内存面板先展示最终绑定与调用记录,再按需展开原始报告。 + +函数的说明链接和知识卡片使用当前文档源行定位,避免同名方法共用一个 DOM 身份。 +单文件阅读只分析它和实际导入的依赖,避免无关同目录模块重名导致知识区整体失败。 +目录阅读保留项目分析。来源身份及版本匹配沿用现有编译器和页面 token,不另建求值器。 + +验收入口: + +```sh +cargo test --offline --lib view:: +cargo test --offline --test view_readability +cargo test --offline --test gold view_ +cargo test --offline --test executable_knowledge +marqdo view output examples/view-reading.mq.md --no-exec --out /tmp/marqdo-reading +``` + +浏览器验收脚本是 [readability.browser.cjs](../../tests/view/readability.browser.cjs), +接收真实页面 URL,支持 MARQDO_PLAYWRIGHT_MODULE、MARQDO_CHROMIUM 和 MARQDO_SCREENSHOT_DIR。 +覆盖七种宽度、侧注边界与碰撞、多动作句子、空逻辑、知识卡片、正文定位和无脚本回退。 +原有 [reader.browser.cjs](../../tests/view/reader.browser.cjs)继续覆盖曲线、帧选择及实时/静态交互。 + +本轮实际验收(2026-11-08):67 项 view 相关单元测试、2 项新增只读导出测试通过; +全量回归 984 通过、0 失败、2 个原有忽略项。真实 Chromium 验证静态快照、 +只读导出和实时页面,覆盖七种宽度、无脚本阅读、曲线与帧切换、源码定位及实时重新运行。 +GOFLAGS 仅对完整回归命令关闭工作区所有权引起的 Go VCS 盖章失败,不改全局配置。 diff --git a/doc/library-development.mq.md b/doc/library-development.mq.md new file mode 100644 index 0000000..69b3889 --- /dev/null +++ b/doc/library-development.mq.md @@ -0,0 +1,256 @@ +--- +markup: occlusion +title: 库开发指南:源码即手册,手册即 SKILL,函数即工具 +description: 标准库与拓展库的叙述式开发规范,包含可以直接调用的真实示例。 +import: + 文件: lib/文件.mq.md +--- + +库开发指南:让说明、调用和实现长在同一份源码里。 + +本文件供人和 AI 开发标准库、拓展库时直接阅读。目标是把库文件交给一个没有读过 +完整语法手册的模型,它仍能判断何时使用、提供哪些输入、如何调用、如何消费结果, +以及遇到失败时怎么办。完成这些任务所需的信息必须在库文件中,不依赖聊天历史、 +隐藏提示词、另一份签名清单或模型猜测。修改实现所需的最少标记也在本文就地示范。 + +这份指南本身可以执行。下方三个函数分别演示句中计算、结构化数据和可恢复文件读取; +它们返回真实结果,不返回“已遵守规范”之类的固定通过标志。直接使用的命令为: + +```sh +marqdo call doc/library-development.mq.md 计算金额 单价=12 数量=3 --json +marqdo call doc/library-development.mq.md 形成订单摘要 '商品="笔记本"' 单价=12 数量=3 --json +marqdo call doc/library-development.mq.md 尝试读取正文 '路径="doc/library-development.mq.md"' --effects fs.read --fs-root . --json +``` + +第一条返回 36,第二条返回商品为笔记本、数量为 3、金额为 36 的记录。 +第三条返回包含本文源码的成功结果记录。需要读写权限的工具必须给出授权命令及路径基准; +纯计算不要求插件、网络或文件授权。读到一个工具时,读者应该能直接复制其真实命令。 + +--- + +一、先确定文件承担的任务。 + +标准库通常是一份 lib/名称.mq.md:这个单文件本身就是手册和 SKILL,直接导入或调用。 +不要为了文档另造一个 index、目录包装函数或同名模块手册。文件开头写清用途、适用范围、 +输入来源、权限、运行环境、共享数据形态和一个真实工作流;每个函数再就地说明自己的契约。 + +拓展库需要多个文件时,以 index.mq.md 为入口组织工程。入口要说明先读什么、任务在哪个 +模块、依赖怎样安装或准备、有哪些可运行流程,以及新能力应该加在哪里。 +子目录有独立职责和多个文件时,也用自己的 index.mq.md 收拢接口与开发路线; +叶子只有一个文件时直接使用该文件,不为空目录层级继续增加入口。 +中文镜像遵守已有命名约定,并说明其与英文模块的对应关系。 + +下面只是目录组织示意,不是已经存在、可以直接调用的拓展包: + +```text +ext/sample/ + index.mq.md 任务导航、安装和权限、主流程、公开门面、开发路线 + core.mq.md 单一职责的纯计算;本文件自身就是手册 + parse/ + index.mq.md 解析任务入口,组合本目录的格式能力 + markdown.mq.md Markdown 叶子能力,保留可独立调用的契约 + csv.mq.md CSV 叶子能力 + examples/ + workflow.mq.md 使用公开 API 的完整业务流程 + tests/ + acceptance.mq.md 工程自有的可执行验收场景 +``` + +入口沿用公开能力进行组合,避免复制一份底层实现。索引中的路径和命令必须可用, +还要说明输入与产物怎样跨步骤传递,而不只是列文件名。工具 schema、签名和效应由现有 +编译器、call、catalog、MLSP 从源码投影,不另建一套由作者同步维护的工具协议。 +本指南也无需安装为另一套 SKILL 包;开发者或 AI 读这份源码即可使用其中的规范与示例。 + +--- + +二、标题下面立即交代参数与返回。 + +每个真正可调用的函数使用函数标题。紧接标题先写参数表,再写返回表;没有参数时直接 +放返回表。表格必须位于第一条执行语句之前。正文中的普通小节使用说明段和分隔线, +不要把“安装说明”“注意事项”等叙述标题误做成空函数。 + +参数表逐项写名称、类型、默认值和含义。含义应包含输入来源、数据形态、单位、索引基数、 +是否允许为空及必要限制,而非“运行时参数”或把参数名复述一次。返回表写实际值的类型、 +字段和含义,指出是新集合、文件路径、句柄、普通值还是可恢复结果,并说明失败出口。 +正文进一步解释这些约束的原因与处理方式,不能把关键边界埋到另一个文件才找得到。 + +新库用正文中的叙述形参,不保留旧的加号形参清单。参数表提供类型契约和说明, +不是另一套参数声明器:名称、顺序和默认值要与正文和实际实现一致。 +有默认值的形参在正文首次声明时紧跟等号,文本默认值加完整引号;无默认值的输入 +必须由调用方提供。下面的真实函数展示完整排版,不需要先学另一份模板语法。 + +--- + +三、先把函数写成能读懂的文章,再让必要部分执行。 + +每个函数单元的叙述比例超过 50%,整份文件也保持说明充分。目的、适用条件、步骤之间 +的因果、数据含义、返回去向和失败处理都属于有用叙述。不要用重复套话、巨型契约表、 +无关背景或在文件头堆文章来掩盖某个函数仍然难读。短实现也需要说明为什么这样做。 + +检查按每个真实函数单元分别计算,契约表与说明文字属于叙述;绑定的数据表与代码围栏 +属于实现。句中粗体、返回表达式和遮蔽圆括号中的代码仍计入代码,方括号中的动作说明 +计入叙述。因此把整段代码搬进一句话,并不会把它全部变成说明文字。比例只是最低门槛, +还应逐段检查输入来源、分支理由、失败出口与可执行示例。 + +尽量让语句成为句子的组成部分。粗体标记执行赋值、调用或表达式;单斜体标记返回。 +例如,下方计算金额函数在解释金额来源的句子中完成赋值,在交代用途的句子中返回结果。 +先读句子能够理解意图,展开其中的精确表达式又能看清实际执行的代码。 + +使用当前已支持的句中返回写法:`完成上述操作后,我们返回*结果*,供调用方继续使用。` +其中“返回”直接引出单斜体。不要把粗体当作返回,也不要假定任意句中出现的单斜体强调 +都会结束函数。返回立即结束当前函数;同一句后面的文字只能解释,不能安排后续执行动作。 +讲解标记本身或展示尚不执行的示例时,使用行内代码或未绑定的代码围栏,避免意外执行。 + +确实需要单独成块的表格、分支和循环可以保留结构化排版。减少孤立代码的目的在于 +保留可读因果,而不是把长循环硬塞到一句话里。每个结构块前说明判断或遍历的目的, +块内使用清楚的变量名与动作标签,块后说明产物;不要让读者靠追踪临时变量猜流程。 + +--- + +四、用遮蔽语法把意图和精确实现放在同一处。 + +方括号写“要做什么”,圆括号写实际代码。标签应解释领域动作、输入与结果之间的关系, +例如“按单价和购买数量计算金额”“在授权根目录读取 UTF-8 正文”,而不是“执行操作” +或原样复述宿主函数名。简单算术、取元、库调用和宿主调用都可以按需要使用这种写法。 + +下方函数会在叙述中执行赋值,赋值右侧用遮蔽表达式写出动作和实现。返回也可以直接 +包住一个有说明的表达式;以下围栏只是排版示例,不会在阅读本指南时执行文件操作: + +```markdown +读取阶段先**正文 = [读取授权范围内的 UTF-8 文本](文件.读文本(路径=`路径`))**,得到后续使用的内容。 +读取完成后,我们返回*正文*,供调用方继续处理。 +``` + +如果不需要中间命名,也可以用下面的直接返回替代上面整个过程。二者是两种写法, +不是连续执行的两个读取步骤;不要为了叙述或展示再调用一次有副作用的能力。 + +```markdown +读取阶段直接返回*[读取授权范围内的 UTF-8 文本](文件.读文本(路径=`路径`))*,把内容交给调用方。 +``` + +执行位置很重要:普通正文中的链接样式是叙述引用或导航,单靠写出一个动作标签不会 +自动执行它。需要执行的表达式应放在赋值、语句、返回等明确的执行位置; +不要用一个没有实现的空圆括号假装功能已完成。标签不参与参数求值,也不能证明实现 +符合描述;修改标签或实现后仍要检查二者是否一致,并执行相关场景。 + +--- + +五、用表格表达结构,用模块表达职责。 + +静态记录、行列表、配置、命令和视图结构优先写成 GFM 表格。一列表达列表, +一行多列表达记录;多行多列默认是列式数据,要表达行记录列表时把首列写成 @。 +调用产生的值先计算并命名,再在单元格中引用,不能假定表格里任意一段函数文本会执行。 +普通值用列表和记录传递;读取集合使用 access,不能把描述标签误当作集合键。 + +不可变更新要保存返回的新值。少量动态键用表库的具名助手;解析与序列化才使用 JSON。 +不要用长串 json.set/json.append 来拼原本一张表就能读懂的数据,也不要为每个数字或 +单个字段创建层层转发的空壳函数。只有当一段逻辑需要解释、复用或独立验证时才提取职责。 + +网页工程从最小布局拆分开始:首页拆为导航、主体、底部,底部再拆为品牌和链接双栏, +链接栏还可拆成文档与社区。一直拆到叶子内部能够用简单 Markdown 表达内容; +父模块负责导入、组合与布局,叶子负责内容。使用现有 web 的文档、组件与 View 表能力, +让结构与内容保持统一语言,避免大段原生 HTML/CSS、转义字符串和手写业务 JavaScript。 + +通用组合优先写在 mq 源码里。仅在 OS、算法或原生 ABI 边界加入小型宿主原语, +声明实际效应与资源限制;拓展库通过公开标准库或插件接口使用能力,不直接调用 host_*。 +中英文镜像保持契约、默认值与行为一致。不要把未来规划写成当前已经可用的接口。 + +--- + +六、把运行边界和工程验收写在开发者找得到的位置。 + +有副作用的能力写明授权、根目录、平台、超时、资源上限以及重试与清理责任。 +返回可恢复结果时先检查其中的 ok,再读取 value 或 error;CLI 外层的 ok 只说明调用 +是否完成,不替代函数结果、HTTP 状态或子进程退出码的判断。未知副作用不能声称为纯函数。 +文件原子替换不等于多文件事务;条件写入也不等于无竞争的内核 CAS。 + +文件类示例使用明确的临时根目录,说明产物是否保留、失败是否留下临时文件、由谁清理。 +需要插件、外部服务或凭据时写明前提,验收优先使用本地可控替身,不把线上写入作为 +阅读文档的隐含步骤。维护原有库时保留既有调用语义,必要变更要说明迁移路径。 + +交付时至少检查四件事:首次读源码能否完成一次真实调用;契约和正文是否一致; +叙述是否超过半数且解释了真实行为;正常、边界、错误场景是否返回预期结果。 +修改源码中的示例时同步执行它们;公共调用面需要兼顾 Tree 和 Bytecode。 +检查叙述比例是可读性门槛,不是功能正确性的证明,更不能代替业务与失败场景。 + +本文件可用以下命令检查。第二条是仓库内的可执行指南验收,覆盖叙述内赋值、 +默认参数、结构化返回以及可恢复读取;修改库时还应运行该库本身相关的回归。 + +```sh +marqdo check doc/library-development.mq.md --narrative-ratio +cargo test --test stdlib_tasks library_development_guide_examples_match_their_contracts +``` + +现有能力可直接参考 [文件库](../lib/文件.mq.md)、[表库](../lib/表.mq.md)、 +[量子工程入口](../ext/quantum/index.mq.md)和[网页工程入口](../ext/web/index.mq.md)。 +需要了解解析与语义的边界时再阅读[文档原生开发指导](design/document-native-development-guide.md)。 +以下是真实可调用的单文件示例,也是前面三个命令的实现。 + +## 计算金额 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 单价 | number | 必填 | 单件商品的金额;币种由调用方保持一致 | +| 数量 | number | 1 | 参与乘法的购买数量;调用方按业务规则校验其范围 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | number | 单价乘以数量的金额,不含税费、折扣或币种转换 | + +输入单价为`单价`,购买数量`数量`=1,没有指定数量时按一件计算。 +本示例只演示透明的乘法组合,不暗示商品有效、允许负数交易或具有货币精度保证; +需要货币精度时由领域库采用整数最小货币单位,并补充其单位和范围约束。 + +为得到这笔购买的基础金额,我们先**结果 = [按单价和购买数量计算金额](单价 * 数量)**, +后续说明仍留在同一段落,使读者无需从一条孤立赋值反推它的业务目的。 + +完成上述计算后,我们返回*结果*,调用方可以继续计算税费、折扣或生成订单摘要。 + +## 形成订单摘要 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 商品 | text | 必填 | 调用方提供的商品显示名称;此函数不查商品库 | +| 单价 | number | 必填 | 与数量相乘的单件金额,币种与调用方约定 | +| 数量 | number | 1 | 购买数量,默认一件;业务校验由调用方完成 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 摘要 | map | 商品、数量、金额三个字段组成的新记录 | + +本函数接收商品名`商品`、单件金额`单价`以及购买数量`数量`=1, +只生成供下一步展示或保存的数据,不会下单、扣款、写文件或访问外部服务。 +因此调用者可以在纯计算权限下验证完整的数据组合过程。 + +我们复用同一文件的计算能力,先**金额 = [计算本次购买的基础金额](计算金额(单价=`单价`, 数量=`数量`))**, +避免在订单摘要中再维护一份乘法规则。接着将需要交给调用方的字段直接列成记录, +让阅读者能逐项看到商品名称、数量和金额从哪里来,而无需解码字典构造链。 + +`摘要` = + +| 商品 | 数量 | 金额 | +|---|---|---| +| `商品` | `数量` | `金额` | + +表格中的反引号引用已经得到的值,未增加一层隐式求值。字段准备好后,我们返回*摘要*, +调用方可以把它交给其他库继续展示或序列化;本函数不会修改传入的值。 + +## 尝试读取正文 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的 UTF-8 文件路径;不是相对本指南的导航链接 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 读取结果 | map | ok/value/error 记录;成功的 value 是正文,失败的 error 含 code/message/operation | + +输入文件`路径`由调用者提供,执行时需要 fs.read,路径以 --fs-root 为基准; +省略根目录时采用被调用文件的目录。本函数复用文件库的有界读取,不能绕过根目录、 +编码检查或资源上限。此例不执行读到的代码,也不从正文推断额外的文件访问权限。 + +为了让一次读取失败仍能作为数据交给下一步,我们先**读取结果 = [在授权范围读取 UTF-8 正文并保留失败信息](文件.尝试读文本(路径=`路径`))**, +由公开文件库统一处理已定义的可恢复失败,而不是在此复制宿主 IO 或假造成功文本。 + +读取结束后,我们返回*读取结果*,调用者先检查记录中的 ok,再使用 value 或 error。 +失败记录只说明这次操作没有成功;它不会捕获任意语言错误,也不会替调用者授予权限。 diff --git a/doc/research/stdlib-gaps-after-mid.md b/doc/research/stdlib-gaps-after-mid.md index 7e9b222..8e92675 100644 --- a/doc/research/stdlib-gaps-after-mid.md +++ b/doc/research/stdlib-gaps-after-mid.md @@ -1,5 +1,7 @@ # 调研:Mid M1–M6 之后标准库还缺什么 +历史调研快照:以下缺口已由 Mid2 和后续标准库闭环分批解决,不能作为当前缺失清单。当前能力请从[标准库源码](../../lib/文件.mq.md)与[验收说明](../design/stdlib-handbook.md)核对。 + | | | |---|---| | 状态 | **调研笔记 · 缺口盘点(M1–M6 闭环之后)** | diff --git a/doc/roadmap/library-authoring-refactor.md b/doc/roadmap/library-authoring-refactor.md new file mode 100644 index 0000000..ba59303 --- /dev/null +++ b/doc/roadmap/library-authoring-refactor.md @@ -0,0 +1,66 @@ +# 库源码叙述式重构验收 + +本轮以[可执行开发指南](../library-development.mq.md)为准,覆盖 lib 与 ext 的全部 mq 源码。 +重构前为 117 个文件、1,258 个函数或对象单元;349 个缺少契约,956 条旧显式形参声明。 +完成后为 125 个文件、1,273 个单元。其中 61 份公开标准库保持单文件结构,提供 650 个函数; +另有 lint 库单元。数据、安全、网络、线性代数和 AI 补齐工程入口,独立多文件职责由 index 组织。 +原工作区阅读器改动及本轮之前的功能实现保留。 + +- [x] 标准库保持单文件,赋值、调用与返回融入叙述,宿主调用有动作说明。 +- [x] 量子、网页的契约紧接标题,入口与叶子采用同一叙述规范。 +- [x] 数据、安全、网络、线性代数补齐契约、输入来源、真实工作流与多文件索引。 +- [x] AI 补齐公开与内部单元的职责说明,解释上下文、路由、工具、工作簿和失败处理。 +- [x] 所有单元移除旧形参,参数与返回表对应真实接口;不以占位工具或固定通过标志验收。 +- [x] 逐函数严格检查叙述超过 50%,行内表达式与绑定数据表仍计作代码。 +- [x] 既有接口与实际行为回归;真实工作流和源码示例在 Tree、Bytecode 执行。 +- [x] 扩展安装清单包含新入口及其源文件依赖,精简构建、WASM 与全量回归通过。 + +源码与工程组织 + +标准库不增加强制 index 或平行手册层。每个函数先给参数与返回契约,再说明输入、 +调用效应、用途、边界与实现。新 table.from_pairs / 表.键值转记录将较宽的具名记录改为 +可读的 key/value 行表;空列表、空值、重复键更新、键顺序与输入不可变性均有双后端验证。 + +拓展库入口解释任务选择、依赖、权限、结果跨步骤传递与开发归属。网页继续采用递归布局: +首页拆导航、主体、页脚;页脚与链接的双栏继续拆,直到内部只是单一 Markdown 内容职责。 +父 index 只负责一层关系,叶子保留普通正文。已有双语参考站点验证真实嵌套、预览、服务与 API。 + +AI 中的静态提示、目录与工作簿片段改为普通表格数据,保留原字符、字段顺序和换行; +真正的传输 JSON 仍交给 JSON 库解析。复杂函数解释决策顺序、工具授权、上下文预算、 +事件收集、去重账本和写回责任。中文单步的 sandbox 参数只附加配置行,实际隔离需调用 +CoW 试跑;工具名解析的半角冒号边界也已如实说明。 + +兼容性审核 + +[审核器](../../examples/library_audit.rs)使用真实解析器,对比参数顺序、默认值、对象层级、 +接收者、控制流与计算。遮蔽标签不参与执行;审核只对明确支持的纯常量构造做等价折叠, +重复 JSON 键、不安全数值、非常量与未知调用均不会被当作等价常量。折叠规则有独立测试。 +原始源码快照保留在本次执行环境的临时目录;它不是另一套工具签名或运行时协议。 + +对比只有三项旧缺陷修复产生的八条 AST 差异,其余既有单元的参数、默认值与规范化执行结构一致。 +[精确修复记录](library-authoring-reviewed-fixes.json)保存差异名称、修复前后摘要与原因; +审核器只接受摘要完全匹配的记录,新增差异或失效记录都会失败。 + +| 旧问题 | 实际修复与验证 | +|---|---| +| 中文单步说明中的斜体 map 被当作提前返回,实现错误落入构造器 | 说明恢复为文字,单步真正执行;离线模型替身验证上下文调用与最终结果 | +| 事务构造器返回未绑定的 self | 用实际 txn 与 url 构造句柄;验证提交、回滚及事务外读取,不额外开启事务 | +| 策略说明标题被误认成对象,main 返回未绑定的 routes | 恢复说明与真实 routes 工具,main 调用它;验证 lookup 和默认后端,文件后缀保持文字 | + +执行证据(2026-11-08) + +| 检查 | 结果 | +|---|---| +| `cargo test --offline --test library_authoring` | 5 项通过;覆盖全部 125 份源码与 1,273 单元、包工作流、旧缺陷、双语记录与安装依赖 | +| `cargo test --offline --test stdlib_tasks --test quantum_handbook --test web_handbook` | 18 + 4 + 3 项通过;源码中的真实命令与作者程序在双后端运行 | +| `cargo run --offline --quiet --example stdlib_catalog -- --check` | 650 个公开函数,0 条效应说明需要更新 | +| AST 原始快照对比及精确修复记录检查 | 8 条已审查修复差异,0 条未解释差异,0 条失效记录 | +| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets` | 982 通过、0 失败、2 个原有忽略项,包含千文档编译与 312 项金样例 | +| `cargo check --offline --no-default-features --features wasm-core` | 通过;保留已有未使用代码告警 | +| 版本匹配工具链的实际 wasm32 构建与 Node 验收 | ABI、桥接、标准库、32 位边界、双语记录、转义表格及句中遮蔽计算通过 | +| `git diff --check` | 通过 | + +GOFLAGS 仅用于当前命令绕过工作区所有权引起的 Go VCS 盖章问题,不修改全局配置。 +WASM 使用临时目录中版本匹配的官方工具链;不以本机编译代替真实 wasm 运行。 +网络和身份提供方示例使用离线数据或本机可控服务;没有把构造配置、清单或演示结果 +宣称成生产服务已验证。Node 验收不代表重新完成浏览器 DOM 几何验收。 diff --git a/doc/roadmap/library-authoring-reviewed-fixes.json b/doc/roadmap/library-authoring-reviewed-fixes.json new file mode 100644 index 0000000..1f8c2ab --- /dev/null +++ b/doc/roadmap/library-authoring-reviewed-fixes.json @@ -0,0 +1,50 @@ +[ + { + "after": "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b", + "before": "754acb518e0d5f0c5c6f6ae6d48c94a1df69ddbdfff13395114786cbe63edf5e", + "difference": "removed ext/ai/policies/step-route.mq.md \"Step class → backend\"", + "reason": "修复说明标题被误认成对象、路由表未绑定且 main 返回未定义 routes;真实 routes 工具返回原策略数据,沙盒行文件后缀显式写为文字。双后端验证 lookup 和默认后端。" + }, + { + "after": "62bd87e62802aeaefbc635715481451d5eee3b918aefe8db9c816039ef91b04f", + "before": "f6c5aecc836c461f7593ffabe9cc2c236a3738a90c49c9c2b5c12a767d97c94c", + "difference": "ext/ai/policies/step-route.mq.md \"main\" changed body", + "reason": "修复说明标题被误认成对象、路由表未绑定且 main 返回未定义 routes;真实 routes 工具返回原策略数据,沙盒行文件后缀显式写为文字。双后端验证 lookup 和默认后端。" + }, + { + "after": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", + "before": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", + "difference": "ext/ai/智能体.mq.md \"智能体\" changed receiver", + "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" + }, + { + "after": "888398739b40074de2e2f93943516541eec872cecc284835968650b3ef72a24d", + "before": "a7553f00f8f05c97c2c44299fd2fcd4641c8f5e9acbb6a246874b096a2acdc0a", + "difference": "ext/ai/智能体.mq.md \"智能体\" changed body", + "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" + }, + { + "after": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", + "before": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", + "difference": "ext/ai/智能体.mq.md \"智能体.单步\" changed receiver", + "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" + }, + { + "after": "e3853fac627ca88f1557132aabb6b818ecc805ab53e6feacb3b08c77e503ece4", + "before": "aae371909b83bdaec63671897c5581a8ba7f14a5e113bd825fca0576df403e2b", + "difference": "ext/ai/智能体.mq.md \"智能体.单步\" changed body", + "reason": "修复单步说明中的 返回 *map* 被当作提前返回,使实现落入构造器且无法执行的问题;正文保留自然语言说明,单步实际完成上下文、模型调用和结果处理。离线模型替身在双后端验证。" + }, + { + "after": "fcbcf165908dd18a9e49f7ff27810176db8e9f63b4352213741664245224f8aa", + "before": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b", + "difference": "ext/data/db.mq.md \"txn\" changed receiver", + "reason": "事务构造器原来返回未绑定的 self;改为保留调用者传入的真实 txn 和 url 句柄,不额外开始事务。双后端验证构造、提交、回滚与事务外读取。" + }, + { + "after": "0a51bc7e7fe4577f32aae9a76ea461213c3547ea9e937f280e17b6e8075194c5", + "before": "92096850522e76cff3350d582b57ae3124fd400635ad25fd63f208a1994514f0", + "difference": "ext/data/db.mq.md \"txn\" changed body", + "reason": "事务构造器原来返回未绑定的 self;改为保留调用者传入的真实 txn 和 url 句柄,不额外开始事务。双后端验证构造、提交、回滚与事务外读取。" + } +] diff --git a/doc/roadmap/stdlib-executable-handbook.md b/doc/roadmap/stdlib-executable-handbook.md new file mode 100644 index 0000000..2b7eb07 --- /dev/null +++ b/doc/roadmap/stdlib-executable-handbook.md @@ -0,0 +1,60 @@ +# 标准库:可执行手册与通用能力闭环 + +目标:代码即文档,文档即 SKILL,SKILL 即 tools。AI 直接阅读任务对应的 `lib/*.mq.md` 单文件,理解输入来源、输出形态、效应、失败处理和可执行示例;保持既有导入兼容。 +本清单记录真实交付状态,未完成项不能因文档或接口占位而标为完成。 + +## 阶段与验收 + +- [x] A. 宿主效应作为唯一事实来源;直调、导入别名、中英文和双后端一致。 +- [x] A. `call` 明确授权文件读写及根目录;会话重放保留权限范围。 +- [x] A. 明确递归删除、索引基数、不可变更新、结构化可恢复错误契约。 +- [x] B. 文件筛选、行/JSON/CSV 读写、目录树复制、批量改名/同步及冲突策略。 +- [x] B. 原子/条件写入、临时目录与清理、路径相对化与扩展名替换。 +- [x] C. 序列、投影、筛选、分组/聚合、连接、按键去重/多键排序和表形态转换。 +- [x] C. 字段类型转换与记录校验;避免回调字符串求值及新集合方言。 +- [x] D. 字节与分块 IO、文件哈希、网络下载、压缩归档及明确资源上限。 +- [x] D. HTTP 响应头、可配置超时、一致的错误结果;保留既有入口兼容。 +- [x] E. 子任务超时、并发上限、批量取消与资源回收。 +- [x] E. 日期完整时区/DST、配置读写边界、规模性能。 +- [x] F. 文档章节/表格/代码块/链接提取和保留叙述的受控局部修改,复用解析器。 +- [x] G. 全标准库单文件手册、标题下参数表、叙述形参和遮蔽调用;叙述超过 50%;提供契约与真实示例;不以伪函数或叙述比例代替正确性。 +- [x] G. 三个端到端工程:文件整理、CSV 数据处理、文档维护;示例直接提取执行。 +- [x] G. 相关回归、双后端、默认/最小特性构建及平台能力矩阵。 + +## 实施约束 + +保留工作区已有的 reader 改动。通用组合优先 `.mq.md`,OS/算法边界使用小型宿主原语; +不增加第二套 Skill 编译器、字符串 eval 或应用模板语法。递归删除保留旧入口行为, +新增清晰的窄接口;每次修改都同时写清兼容性和失败语义。 + +## 验证记录 + +按用户澄清修正为 31 个模块族、61 份公开标准库单文件;撤除先前误增的 64 份目录与模块手册。648 个公开函数的名称、参数顺序和默认值 AST 与迁移前逐项一致;不再保留旧 + 形参。源码中的实际调用在 Tree 与 Bytecode 共执行 126 次,并检查操作结果。17 项标准库工程测试通过;所有函数的叙述比例均超过 50%。 + +先前能力实现的验证记录如下;单文件结构与遮蔽调用修正后的全量复验记录在表后追加。 + +| 验证 | 真实结果 | +|---|---| +| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets` | 首次全量 967 通过、0 失败、2 个原有忽略项,包含千文档编译测试 | +| `GOFLAGS=-buildvcs=false cargo test --offline --all-targets -- --skip v3_corpus_1000_compile_smoke` | 结构修正前回归 968 通过、0 失败、2 个原有忽略项;跳过的千文档测试已在首次全量通过,合计覆盖 969 个不同通过项 | +| `cargo check --offline --no-default-features --features wasm-core` | 通过;保留已有未使用代码告警 | +| `cargo run --offline --quiet --example stdlib_catalog -- --check` | 0 条源码效应说明需要更新 | +| `cargo check/build --offline -p marqdo-wasm --target wasm32-unknown-unknown` | 使用临时目录内版本匹配的官方工具链通过 | +| `node tests/wasm/smoke.mjs ` | ABI 与桥接通过 | +| `node tests/wasm/stdlib.mjs ` | 集合、字节、文档、TOML、IANA/DST 与 32 位边界通过 | +| `git diff --check` | 通过 | + +最终全量回归包含 17 项标准库工程测试。`GOFLAGS` 仅对本次命令关闭工作区所有权导致的 Go VCS 盖章失败,不修改全局 Git 配置。wasm 检查和运行使用同一构建产物,Node 验收不代表浏览器 DOM 布局验收。 + +单文件结构与遮蔽调用修正后的复验: + +- `GOFLAGS=-buildvcs=false cargo test --offline --all-targets`:970 通过、0 失败、2 个原有忽略项,包含千文档编译、312 项金样例及 17 项标准库工程测试。 +- 61 份公开源码包含 63 条真实命令,Tree 与 Bytecode 共执行 126 次;操作返回 Result 时同时检查其 ok。 +- 648 个函数的名称、参数顺序与默认值 AST 逐项保持一致;每个函数叙述均超过 50%,标题下有完整契约,且不再保留旧形参。 +- 编译器效应检查:0 条源码效应说明需要更新;--json 直接输出 648 条真实接口记录。 +- 精简 wasm-core 构建通过;当前源码重新构建的 wasm32 产物通过 ABI、桥接和标准库 Node 运行验证。 +- `git diff --check` 通过。保留原有 reader 工作区修改。 + +删除旧形参后,沿用现有叙述形参推断;修复引号内星号、分号、空格被误作默认值边界的问题,并增加扫描回归测试。宿主调用的遮蔽标签不参与执行,诊断测试继续穿过标签定位真实指令和独立调用点。 + +[设计与能力边界](../design/stdlib-handbook.md)记录平台能力矩阵、兼容索引基数、资源上限、CoW 限制、目录复制范围、条件写入并发边界及线程取消语义。这些边界均为明确契约,不以占位实现宣称支持。保留工作区既有 reader 改动。 diff --git a/examples/library_audit.rs b/examples/library_audit.rs new file mode 100644 index 0000000..68c8f48 --- /dev/null +++ b/examples/library_audit.rs @@ -0,0 +1,803 @@ +//! Audit library source with the real parser, and compare executable ASTs across prose refactors. +use anyhow::{Context, Result}; +use marqdo::{ast::*, diagnostics::Span}; +use serde_json::{json, Value}; +use std::{ + fs, + path::{Path, PathBuf}, +}; +fn files(dir: &Path, out: &mut Vec) -> Result<()> { + for entry in fs::read_dir(dir)? { + let p = entry?.path(); + if p.is_dir() { + files(&p, out)? + } else if p.to_string_lossy().ends_with(".mq.md") { + out.push(p) + } + } + Ok(()) +} +fn expr(e: Expr) -> Expr { + match e { + Expr::Occluded { payload, .. } => payload + .map(|p| expr(*p)) + .unwrap_or(Expr::Literal(Literal::None)), + Expr::Unary { op, expr: e } => Expr::Unary { + op, + expr: Box::new(expr(*e)), + }, + Expr::Binary { op, left, right } => Expr::Binary { + op, + left: Box::new(expr(*left)), + right: Box::new(expr(*right)), + }, + Expr::Call(c) => { + let c = call(c); + pure_literal_call(&c).unwrap_or(Expr::Call(c)) + } + Expr::List(xs) => Expr::List(xs.into_iter().map(expr).collect()), + Expr::Map(xs) => Expr::Map(xs.into_iter().map(|(k, v)| (k, expr(v))).collect()), + Expr::Index { base, label } => Expr::Index { + base: Box::new(expr(*base)), + label, + }, + other => other, + } +} +fn call(mut c: CallExpr) -> CallExpr { + for a in &mut c.args { + match a { + Arg::Positional(e) | Arg::Named { value: e, .. } => *e = expr(e.clone()), + } + } + c +} +// Only the explicitly supported pure literal-building cases are folded. This is +// a refactor audit, not an evaluator: unknown calls and nonconstant data remain. +fn literal_json_value(v: serde_json::Value) -> Option { + use serde_json::Value as J; + Some(Expr::Literal(match v { + J::Null => Literal::None, + J::Bool(b) => Literal::Bool(b), + J::String(s) => Literal::Text(s), + J::Number(n) => { + if let Some(i) = n.as_i64() { + if i.unsigned_abs() > 9_007_199_254_740_991 { + return None; + } + Literal::Int(i) + } else { + let n = n.as_f64()?; + if !n.is_finite() || (n.fract() == 0.0 && n.abs() > 9_007_199_254_740_991.0) { + return None; + } + Literal::Num(n) + } + } + _ => return None, + })) +} +// Read JSON literals without accepting duplicate keys or unsafe numeric coercions. +fn flat_json_record(text: &str) -> Option { + struct Constant; + impl<'de> serde::Deserialize<'de> for ConstantExpr { + fn deserialize>(de: D) -> Result { + de.deserialize_any(Constant).map(ConstantExpr) + } + } + struct ConstantExpr(Expr); + impl<'de> serde::de::Visitor<'de> for Constant { + type Value = Expr; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("constant JSON in the exact audit numeric domain") + } + fn visit_unit(self) -> Result { + Ok(Expr::Literal(Literal::None)) + } + fn visit_bool(self, b: bool) -> Result { + Ok(Expr::Literal(Literal::Bool(b))) + } + fn visit_str(self, s: &str) -> Result { + Ok(Expr::Literal(Literal::Text(s.into()))) + } + fn visit_i64(self, n: i64) -> Result { + literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer")) + } + fn visit_u64(self, n: u64) -> Result { + literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer")) + } + fn visit_f64(self, n: f64) -> Result { + let n = serde_json::Number::from_f64(n).ok_or_else(|| E::custom("nonfinite number"))?; + literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe number")) + } + fn visit_seq>(self, mut seq: A) -> Result { + let mut values = Vec::new(); + while let Some(ConstantExpr(v)) = seq.next_element()? { + values.push(v); + } + Ok(Expr::List(values)) + } + fn visit_map>(self, mut map: A) -> Result { + use serde::de::Error; + let mut fields = std::collections::BTreeMap::new(); + while let Some((key, ConstantExpr(value))) = map.next_entry::()? { + if fields.insert(key, value).is_some() { + return Err(A::Error::custom("duplicate key")); + } + } + Ok(Expr::Map(fields.into_iter().collect())) + } + } + let ConstantExpr(value) = serde_json::from_str::(text).ok()?; + Some(value) +} +fn pure_literal_call(c: &CallExpr) -> Option { + let name = c + .path + .as_ref() + .map(|p| p.join(".")) + .unwrap_or_else(|| c.callee.clone()); + let get = |key: &str| { + c.args.iter().find_map(|a| match a { + Arg::Named { name, value } if name == key => Some(value), + _ => None, + }) + }; + match name.as_str() { + "json.parse" => { + if let Expr::Literal(Literal::Text(text)) = get("text")? { + flat_json_record(text) + } else { + None + } + } + "table.put" if matches!(get("in")?, Expr::Literal(Literal::None)) => { + if let Expr::Literal(Literal::Text(key)) = get("at")? { + let value = get("value")?; + if matches!(value, Expr::Literal(_)) { + Some(Expr::Map(vec![(key.clone(), value.clone())])) + } else { + None + } + } else { + None + } + } + "table.empty_list" => Some(Expr::List(Vec::new())), + "table.from_pairs" => { + let Expr::List(rows) = get("pairs")? else { + return None; + }; + let mut fields = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + for row in rows { + let Expr::Map(pairs) = row else { + return None; + }; + let Some((_, Expr::Literal(Literal::Text(key)))) = + pairs.iter().find(|(k, _)| k == "key") + else { + return None; + }; + let Some((_, value)) = pairs.iter().find(|(k, _)| k == "value") else { + return None; + }; + if !constant(value) || !seen.insert(key.clone()) { + return None; + } + fields.push((key.clone(), value.clone())); + } + Some(Expr::Map(fields)) + } + "text.str_join" => { + let Expr::List(rows) = get("xs")? else { + return None; + }; + let Expr::Literal(Literal::Text(separator)) = get("sep")? else { + return None; + }; + let rows = rows + .iter() + .map(|e| { + if let Expr::Literal(Literal::Text(s)) = e { + Some(s.as_str()) + } else { + None + } + }) + .collect::>>()?; + Some(Expr::Literal(Literal::Text(rows.join(separator)))) + } + _ => None, + } +} +fn constant(e: &Expr) -> bool { + match e { + Expr::Literal(_) => true, + Expr::List(xs) => xs.iter().all(constant), + Expr::Map(xs) => xs.iter().all(|(_, v)| constant(v)), + _ => false, + } +} +fn substitute(e: Expr, temps: &std::collections::BTreeMap) -> Expr { + let e = match e { + Expr::Var(name) if temps.contains_key(&name) => temps[&name].clone(), + Expr::Call(mut c) => { + for a in &mut c.args { + match a { + Arg::Named { value, .. } | Arg::Positional(value) => { + *value = substitute(value.clone(), temps) + } + } + } + Expr::Call(c) + } + Expr::Map(xs) => Expr::Map( + xs.into_iter() + .map(|(k, v)| (k, substitute(v, temps))) + .collect(), + ), + Expr::List(xs) => Expr::List(xs.into_iter().map(|v| substitute(v, temps)).collect()), + Expr::Occluded { + payload: Some(v), .. + } => substitute(*v, temps), + Expr::Unary { op, expr: v } => Expr::Unary { + op, + expr: Box::new(substitute(*v, temps)), + }, + Expr::Binary { op, left, right } => Expr::Binary { + op, + left: Box::new(substitute(*left, temps)), + right: Box::new(substitute(*right, temps)), + }, + other => other, + }; + expr(e) +} +fn canonical_statements(statements: Vec) -> Vec { + fn block( + statements: Vec, + mut temps: std::collections::BTreeMap, + ) -> Vec { + let mut out = Vec::new(); + for s in statements { + let s = statement(s); + let s = match s { + Stmt::Assign { + name, + value, + span, + end_line, + } => { + let value = substitute(value, &temps); + if name.starts_with("_literal_") && constant(&value) { + temps.insert(name, value); + continue; + } + Stmt::Assign { + name, + value, + span, + end_line, + } + } + Stmt::Return { value, span } => Stmt::Return { + value: substitute(value, &temps), + span, + }, + Stmt::Expr { value, span } => Stmt::Expr { + value: substitute(value, &temps), + span, + }, + Stmt::Branch { arms, span } => Stmt::Branch { + arms: arms + .into_iter() + .map(|a| BranchArm { + condition: a.condition.map(|e| substitute(e, &temps)), + body: block(a.body, temps.clone()), + }) + .collect(), + span, + }, + Stmt::ForEach { + item, + collection, + label, + body, + span, + } => Stmt::ForEach { + item, + collection, + label, + body: block(body, temps.clone()), + span, + }, + Stmt::While { + condition, + body, + span, + } => Stmt::While { + condition: substitute(condition, &temps), + body: block(body, temps.clone()), + span, + }, + other => other, + }; + out.push(s); + } + out + } + block(statements, std::collections::BTreeMap::new()) +} + +fn statement(s: Stmt) -> Stmt { + let span = Span::new(0, 0); + match s { + Stmt::Assign { name, value, .. } => Stmt::Assign { + name, + value: expr(value), + span, + end_line: 0, + }, + Stmt::Return { value, .. } => Stmt::Return { + value: expr(value), + span, + }, + Stmt::Call { call: c, .. } => Stmt::Expr { + value: Expr::Call(call(c)), + span, + }, + Stmt::Expr { value, .. } => Stmt::Expr { + value: expr(value), + span, + }, + Stmt::Branch { arms, .. } => Stmt::Branch { + arms: arms + .into_iter() + .map(|a| BranchArm { + condition: a.condition.map(expr), + body: a.body.into_iter().map(statement).collect(), + }) + .collect(), + span, + }, + Stmt::While { + condition, body, .. + } => Stmt::While { + condition: expr(condition), + body: body.into_iter().map(statement).collect(), + span, + }, + Stmt::ForEach { + item, + collection, + body, + .. + } => Stmt::ForEach { + item, + collection, + body: body.into_iter().map(statement).collect(), + span, + label: None, + }, + } +} +fn quote(s: &str) -> String { + serde_json::to_string(s).unwrap().replace('`', "\\`") +} +fn render(e: &Expr) -> Result { + Ok(match e { + Expr::Literal(l) => match l { + Literal::None => "None".into(), + Literal::Bool(b) => if *b { "True" } else { "False" }.into(), + Literal::Int(n) => n.to_string(), + Literal::Num(n) => { + let text = n.to_string(); + if text.contains('.') || text.contains(['e', 'E']) { + text + } else { + format!("{text}.0") + } + } + Literal::Text(s) => quote(s), + }, + Expr::Var(n) => format!("`{n}`"), + Expr::Interp(parts) => { + let mut s = String::new(); + for p in parts { + match p { + InterpPart::Lit(t) => s.push_str(&t.replace('`', "\\`")), + InterpPart::Var(v) => s.push_str(&format!("`{v}`")), + InterpPart::Index { .. } => { + anyhow::bail!("legacy interpolated index needs review") + } + } + } + serde_json::to_string(&s)?.replace("\\\\`", "\\`") + } + Expr::Call(c) => render_call(c)?, + Expr::Unary { op, expr: e } => format!( + "({}{})", + match op { + UnaryOp::Not => "not ", + UnaryOp::Neg => "-", + }, + render(e)? + ), + Expr::Binary { op, left, right } => format!( + "({} {} {})", + render(left)?, + match op { + BinaryOp::Add => "+", + BinaryOp::Sub => "-", + BinaryOp::Mul => "*", + BinaryOp::Div => "/", + BinaryOp::Eq => "==", + BinaryOp::Ne => "!=", + BinaryOp::Lt => "<", + BinaryOp::Le => "<=", + BinaryOp::Gt => ">", + BinaryOp::Ge => ">=", + BinaryOp::And => "and", + BinaryOp::Or => "or", + }, + render(right)? + ), + Expr::List(xs) => format!( + "[{}]", + xs.iter() + .map(render) + .collect::>>()? + .join(", ") + ), + Expr::Map(xs) => format!( + "{{{}}}", + xs.iter() + .map(|(k, v)| Ok(format!("{}: {}", quote(k), render(v)?))) + .collect::>>()? + .join(", ") + ), + Expr::Occluded { + label, + payload: Some(p), + } => format!("[{}]({})", label.replace(']', "\\]"), render(p)?), + Expr::Occluded { payload: None, .. } => "None".into(), + _ => anyhow::bail!("expression needs manual rendering: {e:?}"), + }) +} +fn render_call(c: &CallExpr) -> Result { + let target = if let Some(r) = &c.receiver { + format!("`{r}`.{}", c.callee) + } else if let Some(p) = &c.path { + p.join(".") + } else { + c.callee.clone() + }; + let c = c.with_modifiers_expanded().map_err(anyhow::Error::msg)?; + let args = c + .args + .iter() + .map(|a| { + Ok(match a { + Arg::Positional(e) => render(e)?, + Arg::Named { name, value } => format!("{name}={}", render(value)?), + }) + }) + .collect::>>()?; + if c.receiver.is_some() { + Ok(format!("> {target} {} ", args.join(" "))) + } else { + Ok(format!("{target}({})", args.join(", "))) + } +} +fn receiver_call(c: &CallExpr, f: &Function, imports: &[String]) -> CallExpr { + let mut c = c.clone(); + if let Some(path) = &c.path { + if path.len() == 2 + && f.params.iter().any(|p| p.name == path[0]) + && !imports.contains(&path[0]) + { + c.receiver = Some(path[0].clone()); + c.path = None; + } + } + c +} +fn render_value(v: &Expr, f: &Function, imports: &[String]) -> Result { + match v { + Expr::Call(c) => render_call(&receiver_call(c, f, imports)), + Expr::Occluded { + label, + payload: Some(v), + } => Ok(format!( + "[{}]({})", + label.replace(']', "\\]"), + render_value(v, f, imports)? + )), + other => render(other), + } +} +// A qualified call through a parameter and its explicit receiver form resolve +// the same object when that name is not an imported module binding. +fn normalize_receiver_text(mut body: String, params: &Value, imports: &[String]) -> String { + for p in params.as_array().unwrap() { + let name = p["name"].as_str().unwrap(); + if imports.iter().any(|i| i == name) { + continue; + } + let quoted = serde_json::to_string(name).unwrap(); + let pattern = format!( + r#"path: Some\(\[{}, "[^"\n]+"\]\), receiver: None"#, + regex::escape("ed) + ); + let re = regex::Regex::new(&pattern).unwrap(); + body = re + .replace_all(&body, format!("path: None, receiver: Some({quoted})")) + .into_owned(); + } + body +} +fn collect(fs: &[Function], prefix: &str, source: &str, imports: &[String], out: &mut Vec) { + for f in fs { + let name = if prefix.is_empty() { + f.name.clone() + } else { + format!("{prefix}.{}", f.name) + }; + let mut calls = Vec::new(); + marqdo::ast::walk_stmts(f, &mut |s| { + if let Stmt::Call { call, span } = s { + calls.push(json!({"line":span.line,"rendered":render_call(&receiver_call(call, f, imports)).ok(),"call":format!("{call:?}")})) + } + }); + let mut statements = Vec::new(); + marqdo::ast::walk_stmts(f, &mut |s| { + let (kind, name, value, line, end) = match s { + Stmt::Assign { + name, + value, + span, + end_line, + } => ( + "assign", + Some(name.as_str()), + Some(value), + span.line, + *end_line, + ), + Stmt::Return { value, span } => ("return", None, Some(value), span.line, span.line), + Stmt::Expr { value, span } => ("expr", None, Some(value), span.line, span.line), + Stmt::Call { call, span } => { + statements.push(json!({"kind":"call", "line":span.line, "rendered":render_call(&receiver_call(call, f, imports)).ok(), "callee":call.callee, "path":call.path, "receiver":call.receiver})); + return; + } + _ => return, + }; + let mut inner = value; + while let Some(Expr::Occluded { + payload: Some(p), .. + }) = inner + { + inner = Some(p); + } + let target = match inner { + Some(Expr::Call(c)) => { + Some(json!({"callee":c.callee,"path":c.path,"receiver":c.receiver})) + } + _ => None, + }; + statements.push(json!({"kind":kind,"name":name,"line":line,"end":end,"rendered":value.and_then(|v|render_value(v, f, imports).ok()),"target":target,"value":value.map(|v|format!("{v:?}"))})); + }); + out.push(json!({"name":name,"short_name":f.name,"line":f.span.line,"level":f.level,"base":f.base,"receiver":function_uses_receiver(f),"params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"default":p.default.as_ref().map(|e|format!("{:?}",expr(e.clone()))),"default_source":p.default.as_ref().and_then(|e|render(e).ok()),"type":f.contract.as_ref().and_then(|c|c.params.iter().find(|x|x.name==p.name)).map(|p|p.ty.name()).unwrap_or("any".into())})).collect::>(),"returns":f.contract.as_ref().and_then(|c|c.returns.as_ref()).map(|r|r.ty.name()).unwrap_or("any".into()),"contract":f.contract.as_ref().map(|c|format!("{c:?}")),"body":format!("{:?}",canonical_statements(f.body.clone())),"calls":calls,"statements":statements,"narrative":marqdo::narrative_ratio::measure_source_units(source,std::slice::from_ref(f)).first().map(|r|r.ratio)})); + collect(&f.children, &name, source, imports, out); + } +} +fn difference(description: String, before: Value, after: Value) -> Value { + use sha2::Digest; + let digest = |value: Value| { + format!( + "{:x}", + sha2::Sha256::digest(serde_json::to_vec(&value).unwrap()) + ) + }; + json!({"difference":description,"before":digest(before),"after":digest(after)}) +} +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().collect(); + let baseline = args + .iter() + .position(|x| x == "--compare") + .map(|i| fs::read_to_string(&args[i + 1])) + .transpose()? + .map(|s| serde_json::from_str::(&s)) + .transpose()?; + let original = args + .iter() + .position(|x| x == "--from") + .map(|i| fs::read_to_string(&args[i + 1])) + .transpose()? + .map(|s| serde_json::from_str::(&s)) + .transpose()?; + let mut paths = Vec::new(); + files(Path::new("lib"), &mut paths)?; + files(Path::new("ext"), &mut paths)?; + paths.sort(); + if let Some(input) = &original { + paths.retain(|p| input.get(p.to_str().unwrap()).is_some()); + } + let mut result = serde_json::Map::new(); + let mut differences = Vec::new(); + for path in paths { + let key = path.to_str().context("UTF-8 library path")?; + let source = if let Some(s) = original + .as_ref() + .and_then(|m| m.get(key)) + .and_then(|m| m["source"].as_str()) + { + s.to_owned() + } else { + fs::read_to_string(&path)? + }; + let module = marqdo::parse::parse_source(&source).with_context(|| key.to_owned())?; + let mut functions = Vec::new(); + let imports: Vec<_> = module + .imports + .iter() + .map(|i| i.bind.clone()) + .chain(module.uses.iter().map(|i| i.bind.clone())) + .collect(); + collect(&module.functions, "", &source, &imports, &mut functions); + let reports = marqdo::narrative_ratio::measure_source_units(&source, &module.functions); + for f in &mut functions { + let report = reports.iter().find(|r| json!(r.line) == f["line"]).unwrap(); + f["narrative_chars"] = json!(report.narrative); + f["code_chars"] = json!(report.total - report.narrative); + f["narrative"] = json!( + reports + .iter() + .find(|r| json!(r.line) == f["line"]) + .unwrap() + .ratio + ); + } + if let Some(old) = baseline.as_ref().and_then(|b| b.get(key)) { + for o in old["functions"].as_array().unwrap() { + match functions.iter().find(|f| f["name"] == o["name"]) { + None => differences.push(difference( + format!("removed {key} {}", o["name"]), + json!({"level":o["level"],"base":o["base"],"receiver":o["receiver"],"params":o["params"].as_array().unwrap().iter().map(|p|json!([p["name"],p["default"]])).collect::>(),"body":o["body"]}), + Value::Null, + )), + Some(n) => { + for field in ["level", "base", "receiver", "body"] { + let same = if field == "body" { + normalize_receiver_text( + n[field].as_str().unwrap().to_owned(), + &o["params"], + &imports, + ) == normalize_receiver_text( + o[field].as_str().unwrap().to_owned(), + &o["params"], + &imports, + ) + } else { + n[field] == o[field] + }; + if !same { + differences.push(difference(format!("{key} {} changed {field}", o["name"]), o[field].clone(), n[field].clone())); + } + } + let sig = |f: &Value| { + f["params"] + .as_array() + .unwrap() + .iter() + .map(|p| json!([p["name"], p["default"]])) + .collect::>() + }; + if sig(n) != sig(o) { + differences.push(difference(format!("{key} {} changed parameters", o["name"]),json!(sig(o)),json!(sig(n)))); + } + } + } + } + } + result.insert( + key.to_owned(), + json!({"source": source, "functions": functions}), + ); + } + if let Some(i) = args.iter().position(|x| x == "--snapshot") { + fs::write(&args[i + 1], serde_json::to_vec_pretty(&result)?)?; + } + println!( + "{} library files, {} functions", + result.len(), + result + .values() + .map(|f| f["functions"].as_array().unwrap().len()) + .sum::() + ); + if let Some(i) = args.iter().position(|x| x == "--differences") { + fs::write(&args[i + 1], serde_json::to_vec_pretty(&differences)?)?; + } + if baseline.is_some() { + let reviewed = args + .iter() + .position(|x| x == "--reviewed-fixes") + .map(|i| fs::read_to_string(&args[i + 1])) + .transpose()? + .map(|text| serde_json::from_str::>(&text)) + .transpose()? + .unwrap_or_default(); + let matches = |d: &Value, r: &Value| { + ["difference", "before", "after"] + .iter() + .all(|k| d[*k] == r[*k]) + && r["reason"].as_str().is_some_and(|s| !s.trim().is_empty()) + }; + let unreviewed: Vec<_> = differences + .iter() + .filter(|d| !reviewed.iter().any(|r| matches(d, r))) + .collect(); + let stale: Vec<_> = reviewed + .iter() + .filter(|r| !differences.iter().any(|d| matches(d, r))) + .collect(); + println!("{} executable differences, {} exact reviewed fixes, {} unreviewed, {} stale review records", + differences.len(),differences.len()-unreviewed.len(),unreviewed.len(),stale.len()); + for d in &unreviewed { + println!("{}", d["difference"]); + } + if !unreviewed.is_empty() || !stale.is_empty() { + anyhow::bail!( + "review executable differences; only exact before/after digests are accepted" + ); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn json_literal_audit_rejects_duplicates_unsafe_numbers_and_trailing_data() { + for text in [ + r#"{"x":1,"x":2}"#, + r#"{"nested":{"x":1,"x":2}}"#, + r#"{"x":9007199254740992}"#, + r#"{} false"#, + r#"{"x":NaN}"#, + ] { + assert!(flat_json_record(text).is_none(), "{text}"); + } + let value = flat_json_record(r#"{"z":[null,true,"a\nb"],"a":1}"#).unwrap(); + assert!(constant(&value)); + let Expr::Map(fields) = value else { + panic!("map expected"); + }; + assert_eq!(fields[0].0, "a"); + assert_eq!(fields[1].0, "z"); + } + #[test] + fn only_supported_constant_builders_are_folded() { + for code in [ + "unknown(text=\"{}\")", + "json.parse(text=`input`)", + "table.put(in=`input`, at=\"key\", value=1)", + "text.str_join(xs=`rows`, sep=\"\\n\")", + ] { + let Expr::Call(call) = marqdo::parse::expr::parse_expr(code).unwrap() else { + panic!("call expected"); + }; + assert!(pure_literal_call(&call).is_none(), "{code}"); + } + let Expr::Call(call) = + marqdo::parse::expr::parse_expr("json.parse(text=\"{\\\"key\\\":null}\")").unwrap() + else { + panic!("call expected"); + }; + assert!(pure_literal_call(&call).is_some()); + } +} diff --git a/examples/stdlib-handbook/index.mq.md b/examples/stdlib-handbook/index.mq.md new file mode 100644 index 0000000..da648ce --- /dev/null +++ b/examples/stdlib-handbook/index.mq.md @@ -0,0 +1,169 @@ +--- +markup: occlusion +title: Standard library engineering practice +import: + fs: lib/fs.mq.md + path: lib/path.mq.md + table: lib/table.mq.md + csv: lib/csv.mq.md + document: lib/document.mq.md + hash: lib/hash.mq.md + bytes: lib/bytes.mq.md +--- + +This project demonstrates file inventory, typed CSV aggregation and controlled +Markdown maintenance using the public standard library. No foreign program, +plugin or alternate data syntax is involved. Each operation below is callable. +The demo creates its own directory under the filesystem root and removes it +when successful; it returns the real inventory, report and update outcome. + +Create a disposable directory and set MQ_WORK to its absolute path before the +following command. All relative IO is confined to that directory. The Rust +acceptance test prepares this directory and runs the same source on both runtimes. + +```sh +marqdo call examples/stdlib-handbook/index.mq.md demo --fs-root "$MQ_WORK" --effects fs.write --json +``` + +For production, call inventory on your source directory, summarize_csv on text +from fs.read_text, or update_section with an explicit title and replacement body. +Inspect each operation Result before using its value. File inventory keeps one +unreadable file from aborting other records. Directory cleanup and the update are +separate operations, not a transaction. For high-volume inputs use the batched +collection transforms; this report uses batch transforms, including grouping and aggregation. + +## inventory + + `root` + +| 参数 | 类型 | 说明 | +|---|---|---| +| root | text | Directory relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One path/ok/characters/error record per Markdown file | + +Discover Markdown files, then retain each read outcome. A bad UTF-8 document +is represented as an error record; valid documents still contribute counts. + +**names = fs.find path=`root` pattern="**/*.md"** +**out = table.empty_list** +- [inspect each discovered file](遍历 names 为 name) + **file = path.join a=`root` b=`name`** + **read = fs.try_read_text path=`file`** + **characters = None** + 1. [read succeeded](access(`read`, "ok")) + **body = access(read, "value")** + **characters = len `body`** + 2. * + **characters = None** + **success = access(read, "ok")** + **error = access(read, "error")** + `record` = + + | path | ok | characters | error | + |---|---|---|---| + | `name` | `success` | `characters` | `error` | + + **out = table.append list=`out` item=`record`** +*out* + +## summarize_csv + + `text` + +| 参数 | 类型 | 说明 | +|---|---|---| +| text | text | Header-based CSV: team, amount and active fields | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | CSV with team/total/count for active rows | + +CSV cells start as text. Convert them deliberately, select active rows, group +by team, and sum integer amounts with overflow checks. Nothing passes through SQL. + +**rows = csv.parse text=`text`** +`schema` = + +| amount | active | +|---|---| +| int | bool | + +**typed = table.cast rows=`rows` schema=`schema`** +**selected = table.where list=`typed` key="active" value=True** +**summary = table.summarize list=`selected` key="team" field="amount"** +`names` = + +| key | value | +|---|---| +| team | total | + +**renamed = table.rename list=`summary` fields=`names`** +`fields` = + +| field | +|---| +| team | +| total | +| count | + +**report = table.project list=`renamed` keys=`fields`** +*> csv.stringify rows=`report`* + +## update_section + + `path` + + `title` + + `body` + +| 参数 | 类型 | 说明 | +|---|---|---| +| path | text | Existing Markdown file under the granted root | +| title | text | Exact, unique heading title | +| body | text | Replacement section body, without its heading | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Recoverable replacement/write outcome | + +Compute the expected digest from the exact source that was read. Transform +only the selected body; fs.write_checked detects stale content before replacing. +Concurrent writers still need coordination: this is not a kernel CAS primitive. + +**source = fs.read_text path=`path`** +**expected = hash.sha256 text=`source`** +**changed = document.replace_section text=`source` title=`title` body=`body`** +1. [section replacement succeeded](access(`changed`, "ok")) + **next = access(changed, "value")** + *> fs.write_checked path=`path` text=`next` expected_sha256=`expected`* +2. * + *changed* + +## demo + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Actual file inventory, CSV report and document update | + +Prepare a small valid corpus and an invalid UTF-8 file, then run all three +operations. Validate the returned data; this function never fabricates a pass flag. + +**work = fs.temp_dir prefix="stdlib-demo"** +**note = path.join a=`work` b="notes.md"** +**bad = path.join a=`work` b="invalid.md"** +**corpus = "# Notes\n\n## Status\n\nOld status.\n\n# Appendix\n\nKeep this paragraph.\n"** +> fs.atomic_write path=`note` text=`corpus` +**binary = bytes.from_base64 text="/w=="** +> fs.write_bytes path=`bad` data=`binary` +**files = inventory root=`work`** +**data = "team,amount,active\na,10,true\nb,4,false\na,20,true\n"** +**report = summarize_csv text=`data`** +**update = update_section path=`note` title="Status" body="Updated through public standard libraries."** +**after = fs.read_text path=`note`** +> fs.remove_tree path=`work` +`out` = + +| inventory | csv | update | document | +|---|---|---|---| +| `files` | `report` | `update` | `after` | + +*out* diff --git a/examples/stdlib-handbook/worker.mq.md b/examples/stdlib-handbook/worker.mq.md new file mode 100644 index 0000000..e6cc49b --- /dev/null +++ b/examples/stdlib-handbook/worker.mq.md @@ -0,0 +1,9 @@ +--- +markup: occlusion +--- + +# main + +A file task returns its answer; stdout is not the answer channel. + +*17* diff --git a/examples/stdlib-handbook/索引.mq.md b/examples/stdlib-handbook/索引.mq.md new file mode 100644 index 0000000..2a70af7 --- /dev/null +++ b/examples/stdlib-handbook/索引.mq.md @@ -0,0 +1,29 @@ +--- +markup: occlusion +title: 标准库工程实践 +import: + practice: index.mq.md +--- + +本工程把文件整理、CSV 数据处理和文档维护连为真实工作流。 +中文入口复用同一份实现,避免双语版本逐渐分叉。准备一个可丢弃目录, +把其绝对路径设为 MQ_WORK,再执行下面的工具;成功后会清理自己的临时子目录。 +返回值包含真实的文件结果、CSV 报表及修改后文档,不以一个通过标志代替验收。 + +```sh +marqdo call examples/stdlib-handbook/索引.mq.md 演示 --fs-root "$MQ_WORK" --effects fs.write --json +``` + +生产使用时先阅读[同源实现](index.mq.md),选择文件清单、汇总报表或更新章节。 +读取失败以每文件错误记录保留;CSV 字段先显式转换类型;章节替换保留周围叙述, +写入前检查来源摘要。根目录、失败结果和并发写入限制都在真实函数旁说明。 + +## 演示 + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 三项真实工作流的结果 | + +执行同源工程,保留所有实际返回数据和失败行为。 + +*> practice.demo* diff --git a/examples/stdlib_catalog.rs b/examples/stdlib_catalog.rs new file mode 100644 index 0000000..8a8c275 --- /dev/null +++ b/examples/stdlib_catalog.rs @@ -0,0 +1,123 @@ +//! Inspect real single-file standard library signatures; no index module is required. +//! --json emits compiler metadata; --check validates source effect notes; +//! --write refreshes only effect notes, preserving authored prose and examples. +use anyhow::{bail, Context, Result}; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().collect(); + let write = args.iter().any(|arg| arg == "--write"); + let json = args.iter().any(|arg| arg == "--json"); + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut sources: Vec<_> = fs::read_dir(root.join("lib"))? + .map(|entry| entry.map(|e| e.path())) + .collect::>()?; + sources.retain(|p| p.is_file() && p.to_string_lossy().ends_with(".mq.md")); + sources.sort(); + let mut changed = 0; + let mut tools = Vec::new(); + for source in sources { + let module = marqdo::load::load_module(&source)?; + let compilation = marqdo::sema::compile_file_closure(&source)?; + let content = fs::read_to_string(&source)?; + let mut lines: Vec<_> = content.lines().map(str::to_owned).collect(); + let mut edits = Vec::new(); + let zh = source + .file_name() + .unwrap() + .to_string_lossy() + .chars() + .any(|c| !c.is_ascii()); + for (index, function) in module.functions.iter().enumerate() { + let artifact = compilation + .semantics + .artifacts + .iter() + .find(|a| { + a.kind == "function" + && a.source.line == function.span.line + && same_source(&compilation.semantics.root, &a.source.file, &source) + }) + .context("missing compiler function artifact")?; + let signature = artifact + .signature + .as_ref() + .context("missing compiler signature")?; + let effects: Vec<_> = artifact + .effects + .values() + .into_iter() + .filter(|e| *e != "pure") + .collect(); + let effects = if effects.is_empty() { + "pure".to_owned() + } else { + effects.join(",") + }; + let expected = if zh { + format!("调用效应:{effects}。") + } else { + format!("Effects: {effects}.") + }; + let start = function.span.line as usize; + let end = module + .functions + .get(index + 1) + .map(|f| (f.span.line as usize).saturating_sub(1)) + .unwrap_or(lines.len()); + let notes: Vec<_> = (start..end) + .filter(|i| { + lines[*i].starts_with("Effects: ") || lines[*i].starts_with("调用效应:") + }) + .collect(); + if notes.len() != 1 { + bail!( + "{} {} needs one effect note in its source", + source.display(), + function.name + ); + } + if lines[notes[0]] != expected { + changed += 1; + if write { + edits.push((notes[0], expected)); + } else if !json { + eprintln!("stale effect note: {} {}", source.display(), function.name); + } + } + tools.push(serde_json::json!({ + "name": function.name, + "parameters": signature.params.iter().map(|p| serde_json::json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d| &d.0),"unit":p.unit})).collect::>(), + "returns": signature.returns, + "effects": artifact.effects.values(), + "source": source.strip_prefix(&root)?, + "line": function.span.line + })); + } + if !edits.is_empty() { + for (line, text) in edits { + lines[line] = text; + } + fs::write(&source, lines.join("\n") + "\n")?; + } + } + if json { + println!("{}", serde_json::to_string_pretty(&tools)?); + } else if changed > 0 && !write { + bail!("{changed} effect notes differ from compiler metadata; run with --write"); + } else { + println!( + "{} source effect notes {}; {} public functions", + changed, + if write { "updated" } else { "need updating" }, + tools.len() + ); + } + Ok(()) +} +fn same_source(root: &Path, relative: &str, source: &Path) -> bool { + root.join(relative).canonicalize().ok() == source.canonicalize().ok() +} diff --git a/examples/view-reading.mq.md b/examples/view-reading.mq.md new file mode 100644 index 0000000..cd15861 --- /dev/null +++ b/examples/view-reading.mq.md @@ -0,0 +1,80 @@ +--- +markup: occlusion +title: 在正文里读懂一段程序 +description: 用同一份源码演示动作遮蔽、输入输出、数据表、条件、循环和待补逻辑。 +--- + +这份示例把计算留在文章里。动作说明可以直接阅读,展开侧注才看到实际表达式。 +侧注说明“准备怎样计算”,运行标注说明“这一次得到什么”;两种信息有不同的来源。 + +用 marqdo view examples/view-reading.mq.md 打开实时阅读,或执行下面的离线导出命令。 +导出时的 --no-exec 只分析和排版,不运行示例,也不触发任何动作。 + +```sh +marqdo view output examples/view-reading.mq.md --no-exec --out /tmp/marqdo-reading +``` + +## 计算小计 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 单价 | number | 必填 | 每件商品的价格,使用调用方选定的同一种货币单位 | +| 数量 | number | 1 | 购买的件数;本例由调用方保证非负 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 小计 | number | 单价乘以数量得到的金额,不包含额外税费或优惠 | + +已知商品的`单价`,未指定时购买`数量`=1。这里没有网络请求或文件写入; +价格与数量由调用者提供,不会从屏幕上的说明自动推测。 +完成乘法后,我们返回*[按件数计算金额](单价 * 数量)*,让后面的步骤继续使用。 + +## 预留逻辑 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 当前返回 None;尚未接入实际业务实现 | + +此函数演示空遮蔽的显示。它没有实现业务行为,不能作为“功能已完成”的证据。 +目前返回*[由作者补充具体业务]()*;阅读器会明确标出待补逻辑,而不会假装已有结果。 + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 两笔金额与遍历计算的总数,均来自这一次实际执行 | + +先**第一笔 = [购买两件商品](计算小计(单价=12, 数量=2))**,再**第二笔 = [使用默认件数](计算小计(单价=8))**。 +两个动作可以在同一句话里出现,各自关联自己的逻辑侧注。金额的实际数值只在运行后产生。 + +下面的单列表是三个数量组成的列表;绑定名让它成为数据,和上面的参数契约表不同。 + +`数量列表` = + +| 数量 | +|---| +| 1 | +| 2 | +| 3 | + +从**总数 = 0**开始累计,每次迭代读取一个值。切换迭代记录只是在查看既有结果,不会重跑循环。 + +- [依次累计数量](遍历 数量列表 为 项) + 把当前项加入已有累计,得到**总数 = 总数 + 项**。 + +下面按计算结果选择分支;未进入的分支仍然属于源码,不会因为查看运行记录而消失。 + +1. `总数` > 0 + 确认这次遍历已有数据后,执行**[输出累计值](print(text=`总数`))**。 +2. * + 没有数量时,执行**[说明输入为空](print(text="没有数量"))**。 + +把已经计算的值整理成一行记录,字段名称说明每一项的来源。 + +`摘要` = + +| 第一笔 | 第二笔 | 总数 | +|---|---|---| +| `第一笔` | `第二笔` | `总数` | + +最后返回*摘要*,调用者得到的是结构化记录;上面的预留函数并未在本流程中调用。 diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index 883c7d5..a2c01a9 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -16,104 +16,165 @@ import: table: lib/table.mq.md --- +This file owns agent orchestration: call-site context, explicit tools, routing, workbooks, observations and continuation. Start with [the AI workflows](index.mq.md) for package choices and native dependencies. Use step for one turn, run for reuse and learning, and plan for a bounded workbook lifecycle. Internal helpers are documented for development but are not automatically model-callable tools. Changes must preserve source authority, effect deduplication and the location of writeback. + ## build_step_context - + `agent` - + `task` - + `source_depth`=default - + `skill_depth`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| agent | any | required | Agent configuration or receiver created by this package | +| task | any | required | Structured task or text supplied to the agent | +| source_depth | any | "default" | Source-context depth; default follows the documented context budget | +| skill_depth | any | "default" | Skill-context depth; default follows the documented context budget | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Assemble a readable prompt: standing, task, call site, tools, budgeted source + skill, and the act protocol. The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`. | + +Use `agent`, `task`, `source_depth`="default", `skill_depth`="default" as the inputs for this operation. Assemble a readable prompt: standing, task, call site, tools, budgeted source + skill, and the act protocol. The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`. -**standing = > json.get value=`agent` key="standing"** +The sections have different authority. Standing text sets the agent's role, task text states the current request, and the call site identifies the exact source location that requested it. Source and skill excerpts are bounded evidence for that location. They are not a replacement for the author's runbook. The returned prompt is plain text; constructing it does not call a model or execute any listed tool. + +Tool descriptions come from the supplied whitelist. The act instructions restrict CALL names to that section, so an internal helper mentioned elsewhere is not automatically callable. A truncated excerpt can request a deeper source or skill read through the explicit READ protocol. The caller must enforce its read budget and tool permissions; these instructions alone are not an authorization mechanism. + +We retain **`standing` = [Read the standing field](json.get(value=`agent`, key="standing"))**. 1. `standing` - **up = standing** + We retain **up = standing**. 2. * - **up = None** + We retain **up = None**. -**tools = > json.get value=`agent` key="tools"** -**tools_s = > agent_format_tools tools=`tools`** -**src = > source_brief depth=`source_depth`** -**site = > agent_call_site** -**site_s = > json.stringify value=`site`** -**skill = > skill_brief depth=`skill_depth`** -**task_s = > json.stringify value=`task`** +We retain **`tools` = [Read the tools field](json.get(value=`agent`, key="tools"))**. +We retain **`tools_s` = [Format tools](agent_format_tools(tools=`tools`))**. +We retain **`src` = [Source brief](source_brief(depth=`source_depth`))**. +We retain **`site` = [Call site](agent_call_site())**. +We retain **`site_s` = [Encode the structured value as JSON text](json.stringify(value=`site`))**. +We retain **`skill` = [Skill brief](skill_brief(depth=`skill_depth`))**. +We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. -**esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nCall ONLY names listed under --- tools --- (whitelist). If that section is empty or says none, do NOT emit CALL / 调用 — reply with the final answer only.\nNever CALL internal framework helpers (build_step_context, plan, inspect_workbook, etc.).\nContext is budgeted: if you see a [truncated …] marker, you may first emit exactly one line READ:source or READ:skill (Chinese: 读取:source|skill) to deepen, then you will be re-prompted.\nWhen calling an allowed tool, reply with exactly one line: CALL:\n(Chinese ok: 调用:)\nOtherwise reply with the final answer only.\nIf a capability cannot truly be wired, do NOT fake it silently and never claim it works: write an occlusion with an explicit status, e.g. [按关键词检索,接口未接,待开发](None). Stubs must run without error and must state their return value (None is acceptable). Before finishing, check your own declarations with labels.search.\nTools run via Marqdo subtask (spawn fn / wait).\n"}** -**a = > json.get value=`esc` key="a"** -**b = > json.get value=`esc` key="b"** -**c = > json.get value=`esc` key="c"** -**d = > json.get value=`esc` key="d"** -**e = > json.get value=`esc` key="e"** -**f = > json.get value=`esc` key="f"** -**g = > json.get value=`esc` key="g"** +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. -**p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt. When you cannot wire a capability, declare it in the description (待开发 / 模拟) instead of faking success."** -**p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g** -*p* +`_literal_esc_g_lines` = + +| line | +|---| +| "" | +| "" | +| "--- how to act ---" | +| "Call ONLY names listed under --- tools --- (whitelist). If that section is empty or says none, do NOT emit CALL / 调用 — reply with the final answer only." | +| "Never CALL internal framework helpers (build_step_context, plan, inspect_workbook, etc.)." | +| "Context is budgeted: if you see a [truncated …] marker, you may first emit exactly one line READ:source or READ:skill (Chinese: 读取:source\|skill) to deepen, then you will be re-prompted." | +| "When calling an allowed tool, reply with exactly one line: CALL:" | +| "(Chinese ok: 调用:)" | +| "Otherwise reply with the final answer only." | +| "If a capability cannot truly be wired, do NOT fake it silently and never claim it works: write an occlusion with an explicit status, e.g. [按关键词检索,接口未接,待开发](None). Stubs must run without error and must state their return value (None is acceptable). Before finishing, check your own declarations with labels.search." | +| "Tools run via Marqdo subtask (spawn fn / wait)." | +| "" | + +Join exactly those lines into **_literal_esc_g_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_g_lines`, sep="\n"))**. + +The following record names each literal field without a JSON construction chain. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "a" | "\n\n--- standing ---\n" | +| 2 | "b" | "\n\n--- task ---\n" | +| 3 | "c" | "\n\n--- tools ---\n" | +| 4 | "d" | "\n\n--- call site ---\n" | +| 5 | "e" | "\n\n--- source (.mq.md) ---\n" | +| 6 | "f" | "\n\n--- marqdo skill ---\n" | +| 7 | "g" | `_literal_esc_g_text` | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. +We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. +We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. +We retain **`d` = [Read the d field](json.get(value=`esc`, key="d"))**. +We retain **`e` = [Read the e field](json.get(value=`esc`, key="e"))**. +We retain **`f` = [Read the f field](json.get(value=`esc`, key="f"))**. +We retain **`g` = [Read the g field](json.get(value=`esc`, key="g"))**. + +We retain **p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt. When you cannot wire a capability, declare it in the description (待开发 / 模拟) instead of faking success."**. +We retain **p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g**. +Return *p*. --- ## model_turn - + `model` - + `prompt` - + `stream`=False - + `echo`=False - + `stream_kind`="delta" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | required | Model resource or provider model identifier, as required by this operation | +| prompt | any | required | Prompt text or structured prompt expected by this adapter | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{text,llm_calls,tokens}` for episode metrics; transport failures set `error` + `llm_calls=0` (never abort). | + +Use `model`, `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{text,llm_calls,tokens}` for episode metrics; transport failures set `error` + `llm_calls=0` (never abort). `stream_kind=plan` publishes protocol tokens onto the process trail (not the answer bubble). 1. `stream` - **evs = > model.stream prompt=`prompt` echo=`echo` stream_kind=`stream_kind`** - **text = > llm.collect events=`evs`** - **tokens = > llm.collect_usage events=`evs`** + We retain **`evs` = [Stream](> `model`.stream prompt=`prompt` echo=`echo` stream_kind=`stream_kind` )**. + We retain **`text` = [Collect](llm.collect(events=`evs`))**. + We retain **`tokens` = [Collect usage](llm.collect_usage(events=`evs`))**. 1. `tokens` == None - **tokens = 0** + We retain **tokens = 0**. 2. * **_ = 1** - **err = None** - **calls = 1** + We retain **err = None**. + We retain **calls = 1**. 1. not `text` - **e0 = > at value=`evs` index=0** - **e0_s = > json.stringify value=`e0`** - **e0_map = > text.starts_with text=`e0_s` prefix="{"** + We retain **`e0` = [At](at(value=`evs`, index=0))**. + We retain **`e0_s` = [Encode the structured value as JSON text](json.stringify(value=`e0`))**. + We retain **`e0_map` = [Starts with](text.starts_with(text=`e0_s`, prefix="{"))**. 1. `e0_map` - **err = > json.get value=`e0` key="message"** + We retain **`err` = [Read the message field](json.get(value=`e0`, key="message"))**. 1. `err` - **calls = 0** + We retain **calls = 0**. 2. * **_ = 1** 2. * - **r = > model.ask prompt=`prompt`** - **r_s = > json.stringify value=`r`** - **r_map = > text.starts_with text=`r_s` prefix="{"** + We retain **`r` = [Ask](> `model`.ask prompt=`prompt` )**. + We retain **`r_s` = [Encode the structured value as JSON text](json.stringify(value=`r`))**. + We retain **`r_map` = [Starts with](text.starts_with(text=`r_s`, prefix="{"))**. 1. `r_map` - **text = > json.get value=`r` key="text"** - **tokens = > json.get value=`r` key="tokens"** - **err = > json.get value=`r` key="error"** - **fin = > json.get value=`r` key="finish"** + We retain **`text` = [Read the text field](json.get(value=`r`, key="text"))**. + We retain **`tokens` = [Read the tokens field](json.get(value=`r`, key="tokens"))**. + We retain **`err` = [Read the error field](json.get(value=`r`, key="error"))**. + We retain **`fin` = [Read the finish field](json.get(value=`r`, key="finish"))**. 1. `tokens` == None - **usage = > json.get value=`r` key="usage"** + We retain **`usage` = [Read the usage field](json.get(value=`r`, key="usage"))**. 1. `usage` - **tokens = > json.get value=`usage` key="total_tokens"** + We retain **`tokens` = [Read the total_tokens field](json.get(value=`usage`, key="total_tokens"))**. 2. * - **text = > str value=`r`** - **tokens = 0** - **err = None** - **fin = None** + We retain **`text` = [Str](str(value=`r`))**. + We retain **tokens = 0**. + We retain **err = None**. + We retain **fin = None**. 1. `tokens` == None - **tokens = 0** + We retain **tokens = 0**. 2. * **_ = 1** 1. `err` - **calls = 0** + We retain **calls = 0**. 2. `fin` == "error" - **calls = 0** + We retain **calls = 0**. 1. not `err` - **err = "llm transport error"** + We retain **err = "llm transport error"**. 3. * - **calls = 1** + We retain **calls = 1**. `out` = @@ -121,80 +182,108 @@ One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{te |------|-----------|--------|-------| | `text` | `calls` | `tokens` | `err` | -*out* +Return *out*. --- ## dump_step_context - + `agent` - + `task`="" - + `source_depth`=default - + `skill_depth`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| agent | any | required | Agent configuration or receiver created by this package | +| task | any | "" | Structured task or text supplied to the agent | +| source_depth | any | "default" | Source-context depth; default follows the documented context budget | +| skill_depth | any | "default" | Skill-context depth; default follows the documented context budget | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline. | + +Use `agent`, `task`="", `source_depth`="default", `skill_depth`="default" as the inputs for this operation. Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline. -**prompt = > build_step_context agent=`agent` task=`task` source_depth=`source_depth` skill_depth=`skill_depth`** -**site = > agent_call_site** -**chars = > len value=`prompt`** -**parts = > split value=`prompt` sep="[truncated"** -**n = > len value=`parts`** -**truncated = False** +We retain **`prompt` = [Build step context](build_step_context(agent=`agent`, task=`task`, source_depth=`source_depth`, skill_depth=`skill_depth`))**. +We retain **`site` = [Call site](agent_call_site())**. +We retain **`chars` = [Len](len(value=`prompt`))**. +We retain **`parts` = [Split](split(value=`prompt`, sep="[truncated"))**. +We retain **`n` = [Len](len(value=`parts`))**. +We retain **truncated = False**. 1. `n` > 1 - **truncated = True** + We retain **truncated = True**. 2. * **_ = 1** + `out` = | prompt | call_site | prompt_chars | truncated | |--------|-----------|--------------|-----------| | `prompt` | `site` | `chars` | `truncated` | -*out* +Return *out*. --- ## extract_tool_name - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Find a human-readable call line: `CALL:` or `调用:` / `调用:`. | + +Use `reply` as the inputs for this operation. Find a human-readable call line: `CALL:` or `调用:` / `调用:`. -**esc = > json.parse text={"nl":"\n"}** -**nl = > json.get value=`esc` key="nl"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**found = None** +Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **found = None**. - [line](遍历 `lines` 为 `line`) - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == CALL - **found = rest** + We retain **found = rest**. 2. `head` == 调用 - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * **_ = 1** -*found* +Return *found*. --- ## run_tool - + `tools` - + `name` - + `arguments`=None - + `ledger_dir`=.marqdo/agent-effects - + `logical_run_id`=None - + `step_id`=None - + `call_id`=None - + `operation_id`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| tools | any | required | Explicit tool whitelist or tool-specification records | +| name | any | required | Name registered or looked up by this operation | +| arguments | any | None | Named argument record for the selected registered tool | +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | +| logical_run_id | any | None | Stable logical execution identifier shared by retries | +| step_id | any | None | Identifier of the current workbook step | +| call_id | any | None | Identifier of this tool invocation | +| operation_id | any | None | Stable idempotent operation identifier | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask. Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions). Mutating effects (write / execute / external_write) go through EffectLedger (M-A5a). State flow is prepared then started then spawn then committed, failed_no_effect, or unknown. Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec. | + +Use `tools`, `name`, `arguments`=None, `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None, `step_id`=None, `call_id`=None, `operation_id`=None as the inputs for this operation. Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask. Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions). @@ -202,372 +291,597 @@ Mutating effects (write / execute / external_write) go through EffectLedger (M-A State flow is prepared then started then spawn then committed, failed_no_effect, or unknown. Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec. -**p = > plugin.native_path name="agent"** +Preparation and execution are separate stages. A registered ToolSpec is validated before a child task is created. If preparation fails, its structured failure is returned immediately. The operation identifiers connect retries to the same logical effect; changing arguments under an old identity must not be treated as a successful replay. Supplying these identifiers is the orchestration caller's responsibility. + +For effects that need a ledger, an existing committed record yields a receipt instead of another child execution. A previously started record without a completion record is uncertain: the code marks it unknown and requires reconciliation. It cannot infer that the external write failed merely because the process stopped. Read-only tools follow the shorter path and return the awaited child result. + +The compatibility path when no native agent plugin is found is narrower: it checks the name whitelist and spawns the runbook section. It does not provide ToolSpec validation or durable effect deduplication. Applications that require those guarantees must prepare the native plugin and inspect the returned status and receipt, rather than treating every nonempty value as proof of completion. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * **_ = 1** 1. not `arguments` - **arguments = > table.empty_map** + We retain **`arguments` = [Empty map](table.empty_map())**. 2. * **_ = 1** -**prepared = None** -**needs = False** -**opid = None** -**digest = None** -**idem = None** -**effect = "read"** -**receipt = None** -**raw = None** +We retain **prepared = None**. +We retain **needs = False**. +We retain **opid = None**. +We retain **digest = None**. +We retain **idem = None**. +We retain **effect = "read"**. +We retain **receipt = None**. +We retain **raw = None**. 1. not `p` - **allowed = > agent_tool_allowed tools=`tools` name=`name`** + We retain **`allowed` = [Tool allowed](agent_tool_allowed(tools=`tools`, name=`name`))**. 1. not `allowed` - **msg = "Tool not allowed:"** - *msg + name* + We retain **msg = "Tool not allowed:"**. + Return *msg + name*. 2. * - **id = > subtask.spawn fn=`name`** - *> subtask.wait id=`id`* + We retain **`id` = [Spawn](subtask.spawn(fn=`name`))**. + Return *[Wait](subtask.wait(id=`id`))*. -**prepared = > agent_tools_prepare_call tool_id=`name` tools=`tools` arguments=`arguments` call_id=`call_id` operation_id=`operation_id` logical_run_id=`logical_run_id` step_id=`step_id`** -**pok = > json.get value=`prepared` key="ok"** +We retain **`prepared` = [Tools prepare call](agent_tools_prepare_call(tool_id=`name`, tools=`tools`, arguments=`arguments`, call_id=`call_id`, operation_id=`operation_id`, logical_run_id=`logical_run_id`, step_id=`step_id`))**. +We retain **`pok` = [Read the ok field](json.get(value=`prepared`, key="ok"))**. 1. not `pok` - *prepared* + Return *prepared*. 2. * **_ = 1** -**needs = > json.get value=`prepared` key="needs_ledger"** -**call = > json.get value=`prepared` key="call"** -**opid = > json.get value=`call` key="operation_id"** -**digest = > json.get value=`prepared` key="args_digest"** -**idem = > json.get value=`prepared` key="idempotency_key"** -**tspec = > json.get value=`prepared` key="spec"** -**effect = > json.get value=`tspec` key="effect"** +We retain **`needs` = [Read the needs_ledger field](json.get(value=`prepared`, key="needs_ledger"))**. +We retain **`call` = [Read the call field](json.get(value=`prepared`, key="call"))**. +We retain **`opid` = [Read the operation_id field](json.get(value=`call`, key="operation_id"))**. +We retain **`digest` = [Read the args_digest field](json.get(value=`prepared`, key="args_digest"))**. +We retain **`idem` = [Read the idempotency_key field](json.get(value=`prepared`, key="idempotency_key"))**. +We retain **`tspec` = [Read the spec field](json.get(value=`prepared`, key="spec"))**. +We retain **`effect` = [Read the effect field](json.get(value=`tspec`, key="effect"))**. 1. `needs` - **led = > agent_effects_prepare operation_id=`opid` idempotency_key=`idem` args_digest=`digest` effect_class=`effect` logical_run_id=`logical_run_id` step_id=`step_id` ledger_dir=`ledger_dir`** - **rec = > json.get value=`led` key="record"** - **st0 = > json.get value=`rec` key="state"** + We retain **`led` = [Effects prepare](agent_effects_prepare(operation_id=`opid`, idempotency_key=`idem`, args_digest=`digest`, effect_class=`effect`, logical_run_id=`logical_run_id`, step_id=`step_id`, ledger_dir=`ledger_dir`))**. + We retain **`rec` = [Read the record field](json.get(value=`led`, key="record"))**. + We retain **`st0` = [Read the state field](json.get(value=`rec`, key="state"))**. 1. `st0` == "committed" - **receipt = > json.get value=`rec` key="result_ref"** + We retain **`receipt` = [Read the result_ref field](json.get(value=`rec`, key="result_ref"))**. 1. not `receipt` - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=True status="succeeded" summary="deduped committed effect; skipped re-exec" structured_content=`rec` effect_receipt_ref=`receipt`* + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="deduped committed effect; skipped re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. 2. * 1. `st0` == "reconciled_committed" - **receipt = > json.get value=`rec` key="result_ref"** + We retain **`receipt` = [Read the result_ref field](json.get(value=`rec`, key="result_ref"))**. 1. not `receipt` - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=True status="succeeded" summary="deduped reconciled effect; skipped re-exec" structured_content=`rec` effect_receipt_ref=`receipt`* + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="deduped reconciled effect; skipped re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. 2. * 1. `st0` == "unknown" - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=False status="unknown_effect" summary="prior effect unknown; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`* + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="prior effect unknown; reconcile before retry", structured_content=`rec`, effect_receipt_ref=`receipt`))*. 2. * 1. `st0` == "started" - > agent_effects_transition operation_id=`opid` state="unknown" note="retry saw started without commit; mark unknown" ledger_dir=`ledger_dir` - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=False status="unknown_effect" summary="interrupted after started; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`* + We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="unknown", note="retry saw started without commit; mark unknown", ledger_dir=`ledger_dir`))**. + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="interrupted after started; reconcile before retry", structured_content=`rec`, effect_receipt_ref=`receipt`))*. 2. * 1. `st0` == "needs_input" - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=False status="needs_input" summary="effect needs_input; will not re-exec" structured_content=`rec` effect_receipt_ref=`receipt`* + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="needs_input", summary="effect needs_input; will not re-exec", structured_content=`rec`, effect_receipt_ref=`receipt`))*. 2. * - > agent_effects_transition operation_id=`opid` state="started" ledger_dir=`ledger_dir` + We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="started", ledger_dir=`ledger_dir`))**. **_ = 1** 2. * **_ = 1** -**id = > subtask.spawn fn=`name`** -**raw = > subtask.wait id=`id`** +We retain **`id` = [Spawn](subtask.spawn(fn=`name`))**. +We retain **`raw` = [Wait](subtask.wait(id=`id`))**. 1. `needs` - **raw_s = > json.stringify value=`raw`** + We retain **`raw_s` = [Encode the structured value as JSON text](json.stringify(value=`raw`))**. 1. not `raw` - > agent_effects_transition operation_id=`opid` state="unknown" note="empty tool outcome; reconcile required" ledger_dir=`ledger_dir` - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=False status="unknown_effect" summary="tool outcome empty after started; ledger=unknown" structured_content=`raw` effect_receipt_ref=`receipt`* + We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="unknown", note="empty tool outcome; reconcile required", ledger_dir=`ledger_dir`))**. + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="unknown_effect", summary="tool outcome empty after started; ledger=unknown", structured_content=`raw`, effect_receipt_ref=`receipt`))*. 2. * - **is_err = > text.starts_with text=`raw_s` prefix="Tool not allowed"** + We retain **`is_err` = [Starts with](text.starts_with(text=`raw_s`, prefix="Tool not allowed"))**. 1. `is_err` - > agent_effects_transition operation_id=`opid` state="failed_no_effect" note="rejected before effect" ledger_dir=`ledger_dir` - **receipt = "effect:" + `opid`** - *> agent_tools_wrap_result ok=False status="failed" summary=`raw_s` effect_receipt_ref=`receipt`* + We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="failed_no_effect", note="rejected before effect", ledger_dir=`ledger_dir`))**. + We retain **receipt = "effect:" + `opid`**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=False, status="failed", summary=`raw_s`, effect_receipt_ref=`receipt`))*. 2. * - **receipt = "effect:" + `opid`** - > agent_effects_transition operation_id=`opid` state="committed" result_ref=`receipt` ledger_dir=`ledger_dir` - *> agent_tools_wrap_result ok=True status="succeeded" summary="tool executed; effect committed" structured_content=`raw` effect_receipt_ref=`receipt`* + We retain **receipt = "effect:" + `opid`**. + We **[Effects transition](agent_effects_transition(operation_id=`opid`, state="committed", result_ref=`receipt`, ledger_dir=`ledger_dir`))**. + Return *[Tools wrap result](agent_tools_wrap_result(ok=True, status="succeeded", summary="tool executed; effect committed", structured_content=`raw`, effect_receipt_ref=`receipt`))*. 2. * - *raw* + Return *raw*. ## tools_register - + `spec`=None - + `specs`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| spec | any | None | One structured tool or operation specification | +| specs | any | None | List of structured specifications | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Register ToolSpecV1 document(s). Unsupported schema keywords are refused. | + +Use `spec`=None, `specs`=None as the inputs for this operation. Register ToolSpecV1 document(s). Unsupported schema keywords are refused. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_register spec=`spec` specs=`specs`* +Return *[Tools register](agent_tools_register(spec=`spec`, specs=`specs`))*. ## tools_clear +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Clear the in-process ToolSpec registry (tests / reseeding). | + Clear the in-process ToolSpec registry (tests / reseeding). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_clear* +Return *[Tools clear](agent_tools_clear())*. ## tools_search - + `query`="" - + `tools`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| query | any | "" | Text used to search the bounded catalog or tool registry | +| tools | any | None | Explicit tool whitelist or tool-specification records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Search authorized registered tools (summaries only). | + +Use `query`="", `tools`=None as the inputs for this operation. Search authorized registered tools (summaries only). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_search query=`query` tools=`tools`* +Return *[Tools search](agent_tools_search(query=`query`, tools=`tools`))*. ## tools_describe - + `id` - + `tools`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| tools | any | None | Explicit tool whitelist or tool-specification records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Return full ToolSpecV1 for an authorized tool id. | + +Use `id`, `tools`=None as the inputs for this operation. Return full ToolSpecV1 for an authorized tool id. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_describe id=`id` tools=`tools`* +Return *[Tools describe](agent_tools_describe(id=`id`, tools=`tools`))*. ## tools_register_eng_defaults +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Seed the five engineering tool specs (`tool_find` … `tool_summarize`). | + Seed the five engineering tool specs (`tool_find` … `tool_summarize`). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_register_eng_defaults* +Return *[Tools register eng defaults](agent_tools_register_eng_defaults())*. ## tools_prepare_call - + `tool_id` - + `arguments`=None - + `tools`=None - + `call_id`=None - + `operation_id`=None - + `logical_run_id`=None - + `step_id`=None - + `idempotency_key`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| tool_id | any | required | Registered tool identifier, not an arbitrary function name | +| arguments | any | None | Named argument record for the selected registered tool | +| tools | any | None | Explicit tool whitelist or tool-specification records | +| call_id | any | None | Identifier of this tool invocation | +| operation_id | any | None | Stable idempotent operation identifier | +| logical_run_id | any | None | Stable logical execution identifier shared by retries | +| step_id | any | None | Identifier of the current workbook step | +| idempotency_key | any | None | Key identifying the same logical effect across retries | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). Also returns `args_digest` / `idempotency_key` / `needs_ledger` for EffectLedger wiring. | + +Use `tool_id`, `arguments`=None, `tools`=None, `call_id`=None, `operation_id`=None, `logical_run_id`=None, `step_id`=None, `idempotency_key`=None as the inputs for this operation. Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). Also returns `args_digest` / `idempotency_key` / `needs_ledger` for EffectLedger wiring. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_tools_prepare_call tool_id=`tool_id` arguments=`arguments` tools=`tools` call_id=`call_id` operation_id=`operation_id` logical_run_id=`logical_run_id` step_id=`step_id` idempotency_key=`idempotency_key`* +Return *[Tools prepare call](agent_tools_prepare_call(tool_id=`tool_id`, arguments=`arguments`, tools=`tools`, call_id=`call_id`, operation_id=`operation_id`, logical_run_id=`logical_run_id`, step_id=`step_id`, idempotency_key=`idempotency_key`))*. ## output_build - + `status`="succeeded" - + `text`="" - + `format`="markdown" - + `answer`=None - + `artifacts`=None - + `citations`=None - + `validation`=None - + `finish_reason`=None - + `recovery_options`=None - + `channels`=None - + `allow_passed_without_report`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| status | any | "succeeded" | Domain status recorded in the structured result | +| text | any | "" | Text supplied to the transformation or adapter | +| format | any | "markdown" | Output representation selected by the caller | +| answer | any | None | Final answer text to project into the output | +| artifacts | any | None | Structured artifact references accompanying the result | +| citations | any | None | Source references accompanying the result | +| validation | any | None | Explicit validation evidence; not a self-reported success flag | +| finish_reason | any | None | Reason the operation stopped | +| recovery_options | any | None | Allowed recovery choices for the caller | +| channels | any | None | Structured output-channel records | +| allow_passed_without_report | any | False | Whether policy permits a passed status without a validation report | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Build an `AgentOutputV1` document (M-A4). `validation.status=passed` requires `report_ref`. | + +Use `status`="succeeded", `text`="", `format`="markdown", `answer`=None, `artifacts`=None, `citations`=None, `validation`=None, `finish_reason`=None, `recovery_options`=None, `channels`=None, `allow_passed_without_report`=False as the inputs for this operation. Build an `AgentOutputV1` document (M-A4). `validation.status=passed` requires `report_ref`. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_output_build status=`status` text=`text` format=`format` answer=`answer` artifacts=`artifacts` citations=`citations` validation=`validation` finish_reason=`finish_reason` recovery_options=`recovery_options` channels=`channels` allow_passed_without_report=`allow_passed_without_report`* +Return *[Output build](agent_output_build(status=`status`, text=`text`, format=`format`, answer=`answer`, artifacts=`artifacts`, citations=`citations`, validation=`validation`, finish_reason=`finish_reason`, recovery_options=`recovery_options`, channels=`channels`, allow_passed_without_report=`allow_passed_without_report`))*. ## output_apply_policy - + `status`="succeeded" - + `text`="" - + `format`="markdown" - + `answer`=None - + `artifacts`=None - + `citations`=None - + `validation`=None - + `policy`=None - + `schema`=None - + `schema_version`=None - + `finish_reason`=None - + `recovery_options`=None - + `channels`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| status | any | "succeeded" | Domain status recorded in the structured result | +| text | any | "" | Text supplied to the transformation or adapter | +| format | any | "markdown" | Output representation selected by the caller | +| answer | any | None | Final answer text to project into the output | +| artifacts | any | None | Structured artifact references accompanying the result | +| citations | any | None | Source references accompanying the result | +| validation | any | None | Explicit validation evidence; not a self-reported success flag | +| policy | any | None | Policy data governing this operation | +| schema | any | None | Structured schema used to validate or project output | +| schema_version | any | None | Version of the structured schema | +| finish_reason | any | None | Reason the operation stopped | +| recovery_options | any | None | Allowed recovery choices for the caller | +| channels | any | None | Structured output-channel records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply `ResponsePolicy` (detail / max_chars / max_output_tokens / artifact_allowed) to an AgentOutputV1 or raw text. | + +Use `status`="succeeded", `text`="", `format`="markdown", `answer`=None, `artifacts`=None, `citations`=None, `validation`=None, `policy`=None, `schema`=None, `schema_version`=None, `finish_reason`=None, `recovery_options`=None, `channels`=None as the inputs for this operation. Apply `ResponsePolicy` (detail / max_chars / max_output_tokens / artifact_allowed) to an AgentOutputV1 or raw text. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_output_apply_policy status=`status` text=`text` format=`format` answer=`answer` artifacts=`artifacts` citations=`citations` validation=`validation` policy=`policy` schema=`schema` schema_version=`schema_version` finish_reason=`finish_reason` recovery_options=`recovery_options` channels=`channels`* +Return *[Output apply policy](agent_output_apply_policy(status=`status`, text=`text`, format=`format`, answer=`answer`, artifacts=`artifacts`, citations=`citations`, validation=`validation`, policy=`policy`, schema=`schema`, schema_version=`schema_version`, finish_reason=`finish_reason`, recovery_options=`recovery_options`, channels=`channels`))*. ## output_channel_event - + `channel` - + `delta`="" - + `resource_id`=None - + `meta`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| channel | any | required | Output channel identifier | +| delta | any | "" | Incremental text or record update | +| resource_id | any | None | Referenced resource identifier | +| meta | any | None | Metadata associated with the structured item | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Split a stream delta by channel. Only `answer` sets `append_to_chat=true`. | + +Use `channel`, `delta`="", `resource_id`=None, `meta`=None as the inputs for this operation. Split a stream delta by channel. Only `answer` sets `append_to_chat=true`. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_output_channel_event channel=`channel` delta=`delta` resource_id=`resource_id` meta=`meta`* +Return *[Output channel event](agent_output_channel_event(channel=`channel`, delta=`delta`, resource_id=`resource_id`, meta=`meta`))*. ## output_project_conclusion - + `document`="" - + `text`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| document | any | "" | Document record being packed or projected | +| text | any | "" | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Deterministic chat projection from `# 结论` / `# conclusion` (F01 transition). Falls back to the first body paragraph. | + +Use `document`="", `text`="" as the inputs for this operation. Deterministic chat projection from `# 结论` / `# conclusion` (F01 transition). Falls back to the first body paragraph. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_output_project_conclusion document=`document` text=`text`* +Return *[Output project conclusion](agent_output_project_conclusion(document=`document`, text=`text`))*. ## context_pack_build - + `items`=None - + `budget_tokens`=8000 - + `output_reserve_pct`=20 - + `compact_threshold_pct`=70 - + `goal`=None - + `constraints`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| items | any | None | Ordered context or output items | +| budget_tokens | any | 8000 | Maximum context token budget | +| output_reserve_pct | any | 20 | Percentage of the context budget reserved for output | +| compact_threshold_pct | any | 70 | Budget usage threshold triggering compaction | +| goal | any | None | Human task goal represented by this operation | +| constraints | any | None | Explicit task constraints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Assemble `ContextPackV2` with origin/trust/priority. Web/tool items cannot be `trust=trusted`. | + +Use `items`=None, `budget_tokens`=8000, `output_reserve_pct`=20, `compact_threshold_pct`=70, `goal`=None, `constraints`=None as the inputs for this operation. Assemble `ContextPackV2` with origin/trust/priority. Web/tool items cannot be `trust=trusted`. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_context_pack_build items=`items` budget_tokens=`budget_tokens` output_reserve_pct=`output_reserve_pct` compact_threshold_pct=`compact_threshold_pct` goal=`goal` constraints=`constraints`* +Return *[Context pack build](agent_context_pack_build(items=`items`, budget_tokens=`budget_tokens`, output_reserve_pct=`output_reserve_pct`, compact_threshold_pct=`compact_threshold_pct`, goal=`goal`, constraints=`constraints`))*. ## context_pack_compact - + `items`=None - + `budget_tokens`=8000 - + `output_reserve_pct`=20 - + `compact_threshold_pct`=70 - + `goal`=None - + `constraints`=None - + `schema`=None - + `schema_version`=None - + `available_tokens`=None - + `used_tokens`=None - + `source_event_range`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| items | any | None | Ordered context or output items | +| budget_tokens | any | 8000 | Maximum context token budget | +| output_reserve_pct | any | 20 | Percentage of the context budget reserved for output | +| compact_threshold_pct | any | 70 | Budget usage threshold triggering compaction | +| goal | any | None | Human task goal represented by this operation | +| constraints | any | None | Explicit task constraints | +| schema | any | None | Structured schema used to validate or project output | +| schema_version | any | None | Version of the structured schema | +| available_tokens | any | None | Token budget available to the next turn | +| used_tokens | any | None | Observed token usage, not a guessed count | +| source_event_range | any | None | Event range represented by a compacted context item | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Compact over-threshold packs; retain goal/constraints/pending_write/plan/trusted anchors (F19). | + +Use `items`=None, `budget_tokens`=8000, `output_reserve_pct`=20, `compact_threshold_pct`=70, `goal`=None, `constraints`=None, `schema`=None, `schema_version`=None, `available_tokens`=None, `used_tokens`=None, `source_event_range`=None as the inputs for this operation. Compact over-threshold packs; retain goal/constraints/pending_write/plan/trusted anchors (F19). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_context_pack_compact items=`items` budget_tokens=`budget_tokens` output_reserve_pct=`output_reserve_pct` compact_threshold_pct=`compact_threshold_pct` goal=`goal` constraints=`constraints` schema=`schema` schema_version=`schema_version` available_tokens=`available_tokens` used_tokens=`used_tokens` source_event_range=`source_event_range`* +Return *[Context pack compact](agent_context_pack_compact(items=`items`, budget_tokens=`budget_tokens`, output_reserve_pct=`output_reserve_pct`, compact_threshold_pct=`compact_threshold_pct`, goal=`goal`, constraints=`constraints`, schema=`schema`, schema_version=`schema_version`, available_tokens=`available_tokens`, used_tokens=`used_tokens`, source_event_range=`source_event_range`))*. ## render_workbook_skeleton - + `goal` - + `skeleton`=single + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| goal | any | required | Human task goal represented by this operation | +| skeleton | any | "single" | Workbook source template to instantiate | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer. | + +Use `goal`, `skeleton`="single" as the inputs for this operation. Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer. -**q = > json.quote text=`goal`** -**esc = > json.parse text={"h":"---\ntitle: agent workbook\nimport:\n llm: ext/ai/llm.mq.md\n agent: ext/ai/agent.mq.md\n json: lib/json.mq.md\n sys: lib/sys.mq.md\n table: lib/table.mq.md\n wb: lib/writeback.mq.md\n subtask: lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u002a\u0060env_model\u0060 = > sys.env_get name=\"OPENAI_MODEL\"\u002a\u002a\n\u002a\u002a\u0060env_base\u0060 = > sys.env_get name=\"OPENAI_BASE_URL\"\u002a\u002a\n\u002a\u002a\u0060env_key\u0060 = > sys.env_get name=\"OPENAI_API_KEY\"\u002a\u002a\n\u002a\u002a\u0060model\u0060 = > llm.create model=\u0060env_model\u0060 base_url=\u0060env_base\u0060 api_key=\u0060env_key\u0060 backend=\"openai-compatible\" name=\"workbook\"\u002a\u002a\n","s2":"\u002a\u002a\u0060tools\u0060 = > table.empty_list\u002a\u002a\n","s3":"\u002a\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools.\"\u002a\u002a\n","s4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"}\u002a\u002a\n","s6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=\"task\"\u002a\u002a\n","s7":"\u002a\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","s7b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=\"result\"\u002a\u002a\n","s8":"\u002a\u0060text\u0060\u002a\n","d3":"\u002a\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You gather facts for the goal. Be concise. Do not invent tools.\"\u002a\u002a\n","d3b":"\u002a\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You write the final answer from research notes. Do not invent tools.\"\u002a\u002a\n","d4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"}\u002a\u002a\n","d6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=\"task\"\u002a\u002a\n","d7":"\u002a\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","d8":"\u002a\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060\u002a\u002a\n","d9":"\u002a\u002a\u0060wt\u0060 = \"Write the final answer. Research notes:\"\u002a\u002a\n","d10":"\u002a\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060\u002a\u002a\n","d11":"\u002a\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=True\u002a\u002a\n","d11b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=\"result\"\u002a\u002a\n","d12":"\u002a\u0060text\u0060\u002a\n"}** -**h = > json.get value=`esc` key="h"** -**s1 = > json.get value=`esc` key="s1"** -**s2 = > json.get value=`esc` key="s2"** +This function produces source text, not a running worker. The caller owns choosing a destination, writing that text, starting the child, and inspecting the child's exit status and returned value. Generation alone neither proves the task solved nor freezes a reusable skill. The templates are data in this function: their marker characters must remain literal until a later Marqdo process parses the generated workbook. + +The common header names the libraries the generated program imports. Its Goal section explains where the parent goal is embedded, while its Solidify section explains who may freeze the answer. The entry begins by loading environment configuration. This makes the generated program usable by the existing workbook runner without adding a second template interpreter or hidden workflow format. + +The single-worker branch creates one model and an empty tools list, then asks one worker to solve the embedded task. The empty whitelist is intentional: mentioning a capability in the task does not register a callable tool. A worker must answer directly unless the author later adds an actual tool definition and explicitly supplies it. The returned child value is the result field from the worker's structured turn. + +The dual-worker branch uses the same model configuration for two roles. A research worker first returns notes. Those notes are serialized into the writing worker's task, and the writing worker returns the final text. The roles describe sequencing; they do not imply independent evidence collection, browser access, or any permission beyond the configured whitelist and runtime grants. + +The goal is JSON-quoted before it is inserted into either source template. Quotes and line breaks in a user's goal therefore stay data rather than becoming workbook statements. The surrounding fragments retain the exact original newlines, imports and return markers. When changing this generator, review both complete outputs, parse them as ordinary source, and test goals containing quotes, backticks and newlines. + +Environment variables are looked up when the child runs. No credentials are fetched or written by this generator. Missing model configuration consequently belongs to the execution result, not to template construction. A parent should await that result before deciding RUN, CONTINUE or DONE. Successful execution may then be solidified by the existing runtime mechanism; this function does not silently promote its generated text into trusted knowledge. + +We retain **`q` = [Quote the JSON text value](json.quote(text=`goal`))**. +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_h_lines` = + +| line | +|---| +| "---" | +| "title: agent workbook" | +| "import:" | +| " llm: ext/ai/llm.mq.md" | +| " agent: ext/ai/agent.mq.md" | +| " json: lib/json.mq.md" | +| " sys: lib/sys.mq.md" | +| " table: lib/table.mq.md" | +| " wb: lib/writeback.mq.md" | +| " subtask: lib/subtask.mq.md" | +| "---" | +| "" | +| "# Goal" | +| "" | +| "Parent goal is embedded as JSON in # main." | +| "" | +| "## Solidify" | +| "" | +| "When the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE)." | +| "" | +| "# main" | +| "" | +| "> llm.load_env" | +| "" | +| "" | + +Join exactly those lines into **_literal_esc_h_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_h_lines`, sep="\n"))**. + +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_s1_lines` = + +| line | +|---| +| "**\x60env_model\x60 = > sys.env_get name=\"OPENAI_MODEL\"**" | +| "**\x60env_base\x60 = > sys.env_get name=\"OPENAI_BASE_URL\"**" | +| "**\x60env_key\x60 = > sys.env_get name=\"OPENAI_API_KEY\"**" | +| "**\x60model\x60 = > llm.create model=\x60env_model\x60 base_url=\x60env_base\x60 api_key=\x60env_key\x60 backend=\"openai-compatible\" name=\"workbook\"**" | +| "" | + +Join exactly those lines into **_literal_esc_s1_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_s1_lines`, sep="\n"))**. + +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_s3_lines` = + +| line | +|---| +| "**\x60worker\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools.\"**" | +| "" | + +Join exactly those lines into **_literal_esc_s3_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_s3_lines`, sep="\n"))**. + +The following record names each literal field without a JSON construction chain. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "d10" | "**\x60wt\x60 = \x60wt\x60 + \x60ns\x60**\n" | +| 2 | "d11" | "**\x60out\x60 = > \x60writer\x60.step task=\x60wt\x60 stream=True**\n" | +| 3 | "d11b" | "**\x60text\x60 = > json.get value=\x60out\x60 key=\"result\"**\n" | +| 4 | "d12" | "*\x60text\x60*\n" | +| 5 | "d3" | "**\x60research\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You gather facts for the goal. Be concise. Do not invent tools.\"**\n" | +| 6 | "d3b" | "**\x60writer\x60 = > agent.agent model=\x60model\x60 tools=\x60tools\x60 standing=\"You write the final answer from research notes. Do not invent tools.\"**\n" | +| 7 | "d4" | "**\x60wrap\x60 = > json.parse text={\"task\":" | +| 8 | "d5" | "}**\n" | +| 9 | "d6" | "**\x60task\x60 = > json.get value=\x60wrap\x60 key=\"task\"**\n" | +| 10 | "d7" | "**\x60notes\x60 = > \x60research\x60.step task=\x60task\x60 stream=True**\n" | +| 11 | "d8" | "**\x60ns\x60 = > json.stringify value=\x60notes\x60**\n" | +| 12 | "d9" | "**\x60wt\x60 = \"Write the final answer. Research notes:\"**\n" | +| 13 | "h" | `_literal_esc_h_text` | +| 14 | "s1" | `_literal_esc_s1_text` | +| 15 | "s2" | "**\x60tools\x60 = > table.empty_list**\n" | +| 16 | "s3" | `_literal_esc_s3_text` | +| 17 | "s4" | "**\x60wrap\x60 = > json.parse text={\"task\":" | +| 18 | "s5" | "}**\n" | +| 19 | "s6" | "**\x60task\x60 = > json.get value=\x60wrap\x60 key=\"task\"**\n" | +| 20 | "s7" | "**\x60out\x60 = > \x60worker\x60.step task=\x60task\x60 stream=True**\n" | +| 21 | "s7b" | "**\x60text\x60 = > json.get value=\x60out\x60 key=\"result\"**\n" | +| 22 | "s8" | "*\x60text\x60*\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`h` = [Read the h field](json.get(value=`esc`, key="h"))**. +We retain **`s1` = [Read the s1 field](json.get(value=`esc`, key="s1"))**. +We retain **`s2` = [Read the s2 field](json.get(value=`esc`, key="s2"))**. 1. `skeleton` == dual - **s3 = > json.get value=`esc` key="d3"** - **s3b = > json.get value=`esc` key="d3b"** - **s4 = > json.get value=`esc` key="d4"** - **s5 = > json.get value=`esc` key="d5"** - **s6 = > json.get value=`esc` key="d6"** - **s7 = > json.get value=`esc` key="d7"** - **s8 = > json.get value=`esc` key="d8"** - **s9 = > json.get value=`esc` key="d9"** - **s10 = > json.get value=`esc` key="d10"** - **s11 = > json.get value=`esc` key="d11"** - **s11b = > json.get value=`esc` key="d11b"** - **s12 = > json.get value=`esc` key="d12"** - *h + s1 + s2 + s3 + s3b + s4 + q + s5 + s6 + s7 + s8 + s9 + s10 + s11 + s11b + s12* + We retain **`s3` = [Read the d3 field](json.get(value=`esc`, key="d3"))**. + We retain **`s3b` = [Read the d3b field](json.get(value=`esc`, key="d3b"))**. + We retain **`s4` = [Read the d4 field](json.get(value=`esc`, key="d4"))**. + We retain **`s5` = [Read the d5 field](json.get(value=`esc`, key="d5"))**. + We retain **`s6` = [Read the d6 field](json.get(value=`esc`, key="d6"))**. + We retain **`s7` = [Read the d7 field](json.get(value=`esc`, key="d7"))**. + We retain **`s8` = [Read the d8 field](json.get(value=`esc`, key="d8"))**. + We retain **`s9` = [Read the d9 field](json.get(value=`esc`, key="d9"))**. + We retain **`s10` = [Read the d10 field](json.get(value=`esc`, key="d10"))**. + We retain **`s11` = [Read the d11 field](json.get(value=`esc`, key="d11"))**. + We retain **`s11b` = [Read the d11b field](json.get(value=`esc`, key="d11b"))**. + We retain **`s12` = [Read the d12 field](json.get(value=`esc`, key="d12"))**. + Return *h + s1 + s2 + s3 + s3b + s4 + q + s5 + s6 + s7 + s8 + s9 + s10 + s11 + s11b + s12*. 2. * - **s3 = > json.get value=`esc` key="s3"** - **s4 = > json.get value=`esc` key="s4"** - **s5 = > json.get value=`esc` key="s5"** - **s6 = > json.get value=`esc` key="s6"** - **s7 = > json.get value=`esc` key="s7"** - **s7b = > json.get value=`esc` key="s7b"** - **s8 = > json.get value=`esc` key="s8"** - *h + s1 + s2 + s3 + s4 + q + s5 + s6 + s7 + s7b + s8* + We retain **`s3` = [Read the s3 field](json.get(value=`esc`, key="s3"))**. + We retain **`s4` = [Read the s4 field](json.get(value=`esc`, key="s4"))**. + We retain **`s5` = [Read the s5 field](json.get(value=`esc`, key="s5"))**. + We retain **`s6` = [Read the s6 field](json.get(value=`esc`, key="s6"))**. + We retain **`s7` = [Read the s7 field](json.get(value=`esc`, key="s7"))**. + We retain **`s7b` = [Read the s7b field](json.get(value=`esc`, key="s7b"))**. + We retain **`s8` = [Read the s8 field](json.get(value=`esc`, key="s8"))**. + Return *h + s1 + s2 + s3 + s4 + q + s5 + s6 + s7 + s7b + s8*. --- ## inspect_workbook - + `path` - + `exit_code`=None - + `value`=None - + `stdout`=None - + `stderr`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| exit_code | any | None | Child process or tool exit status | +| value | any | None | Value supplied to this operation; immutable transformations return a new value | +| stdout | any | None | Captured standard output | +| stderr | any | None | Captured standard error | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O. | + +Use `path`, `exit_code`=None, `value`=None, `stdout`=None, `stderr`=None as the inputs for this operation. Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O. -**source = > fs.read_text path=`path`** -**slots = > wb.scan_path path=`path`** +We retain **`source` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. +We retain **`slots` = [Scan path](wb.scan_path(path=`path`))**. + `obs` = | path | source | slots | exit_code | @@ -575,95 +889,104 @@ Structured observation for the parent developer-agent: source, named writeback s | `path` | `source` | `slots` | `exit_code` | 1. `value` - **obs = table.put in=`obs` at="value" value=`value`** + We retain **`obs` = [Set the value field in the new record](table.put(in=`obs`, at="value", value=`value`))**. 2. * **_ = 1** 1. `stdout` - **obs = table.put in=`obs` at="stdout" value=`stdout`** + We retain **`obs` = [Set the stdout field in the new record](table.put(in=`obs`, at="stdout", value=`stdout`))**. 2. * **_ = 1** 1. `stderr` - **obs = table.put in=`obs` at="stderr" value=`stderr`** + We retain **`obs` = [Set the stderr field in the new record](table.put(in=`obs`, at="stderr", value=`stderr`))**. 2. * **_ = 1** -**last_ok = None** -**last_error = None** +We retain **last_ok = None**. +We retain **last_error = None**. - [slot](遍历 `slots` 为 `slot`) - **k = > json.get value=`slot` key="key"** - **body = > json.get value=`slot` key="body"** + We retain **`k` = [Read the key field](json.get(value=`slot`, key="key"))**. + We retain **`body` = [Read the body field](json.get(value=`slot`, key="body"))**. 1. `k` == "ok" - **last_ok = body** + We retain **last_ok = body**. 2. `k` == "error" - **last_error = body** + We retain **last_error = body**. 3. * **_ = 1** 1. `last_ok` - **obs = table.put in=`obs` at="last_ok" value=`last_ok`** + We retain **`obs` = [Set the last_ok field in the new record](table.put(in=`obs`, at="last_ok", value=`last_ok`))**. 2. * **_ = 1** 1. `last_error` - **obs = table.put in=`obs` at="last_error" value=`last_error`** + We retain **`obs` = [Set the last_error field in the new record](table.put(in=`obs`, at="last_error", value=`last_error`))**. 2. * **_ = 1** -*obs* +Return *obs*. --- ## trial - + `path`=None - + `source`=None - + `root`=None - + `write_path`=None - + `text`=None - + `commit`=True - + `profile`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| source | any | None | Source text inspected or prepared by this operation | +| root | any | None | Explicit root directory for discovery or isolated execution | +| write_path | any | None | Explicit output path or None | +| text | any | None | Text supplied to the transformation or adapter | +| commit | any | True | Whether to promote trial changes after successful validation | +| profile | any | "default" | Capability profile selected for the trial | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard. Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable). | + +Use `path`=None, `source`=None, `root`=None, `write_path`=None, `text`=None, `commit`=True, `profile`="default" as the inputs for this operation. Opt-in CoW trial (O1): open → optional upper write → optional run → diff → commit on success else discard. Host tree unchanged until a successful commit. Return map is a GFM table (link-index readable). -**sb = sandbox.open root=`root` profile=`profile`** -**id = > json.get value=`sb` key="id"** -**prof = > json.get value=`sb` key="profile"** -**ok = True** -**stdout = ""** -**stderr = ""** +We retain **`sb` = [Open](sandbox.open(root=`root`, profile=`profile`))**. +We retain **`id` = [Read the id field](json.get(value=`sb`, key="id"))**. +We retain **`prof` = [Read the profile field](json.get(value=`sb`, key="profile"))**. +We retain **ok = True**. +We retain **stdout = ""**. +We retain **stderr = ""**. 1. `write_path` 1. `text` - > sandbox.write id=`id` path=`write_path` text=`text` + We **[Write](sandbox.write(id=`id`, path=`write_path`, text=`text`))**. 2. * **_ = 1** 2. * **_ = 1** 1. `source` - **ret = sandbox.run id=`id` source=`source`** - **ok = > json.get value=`ret` key="ok"** - **stdout = > json.get value=`ret` key="stdout"** - **stderr = > json.get value=`ret` key="stderr"** + We retain **`ret` = [Run](sandbox.run(id=`id`, source=`source`))**. + We retain **`ok` = [Read the ok field](json.get(value=`ret`, key="ok"))**. + We retain **`stdout` = [Read the stdout field](json.get(value=`ret`, key="stdout"))**. + We retain **`stderr` = [Read the stderr field](json.get(value=`ret`, key="stderr"))**. 2. `path` - **ret = sandbox.run id=`id` path=`path`** - **ok = > json.get value=`ret` key="ok"** - **stdout = > json.get value=`ret` key="stdout"** - **stderr = > json.get value=`ret` key="stderr"** + We retain **`ret` = [Run](sandbox.run(id=`id`, path=`path`))**. + We retain **`ok` = [Read the ok field](json.get(value=`ret`, key="ok"))**. + We retain **`stdout` = [Read the stdout field](json.get(value=`ret`, key="stdout"))**. + We retain **`stderr` = [Read the stderr field](json.get(value=`ret`, key="stderr"))**. 3. * **_ = 1** -**pending = sandbox.diff id=`id`** -**committed = False** +We retain **`pending` = [Diff](sandbox.diff(id=`id`))**. +We retain **committed = False**. 1. `ok` 1. `commit` - > sandbox.commit id=`id` - **committed = True** + We **[Commit](sandbox.commit(id=`id`))**. + We retain **committed = True**. 2. * - > sandbox.discard id=`id` + We **[Discard](sandbox.discard(id=`id`))**. 2. * - > sandbox.discard id=`id` + We **[Discard](sandbox.discard(id=`id`))**. **out = ** @@ -671,600 +994,952 @@ Host tree unchanged until a successful commit. Return map is a GFM table (link-i |----|-----------|------|--------|--------|-----|---------| | `ok` | `committed` | `pending` | `stdout` | `stderr` | `id` | `prof` | -*out* +Return *out*. ## step_route - + `kind`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kind | any | "default" | Operation or factorization kind listed in this function's behavior | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend. Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads). | + +Use `kind`="default" as the inputs for this operation. O3: map step class (`lookup` | `patch` | `sandbox_run` | `net` | `default`) → Adaptive Routing backend. Authority is the GFM table in `ext/ai/policies/step-route.mq.md` (mirrored here for offline reads). 1. `kind` == "lookup" - **backend = "marqdo"** + We retain **backend = "marqdo"**. 2. `kind` == "patch" - **backend = "small-llm"** + We retain **backend = "small-llm"**. 3. `kind` == "sandbox_run" - **backend = "marqdo"** + We retain **backend = "marqdo"**. 4. `kind` == "net" - **backend = "llm"** + We retain **backend = "llm"**. 5. * - **backend = "auto"** + We retain **backend = "auto"**. -**out = table.put in=None at="kind" value=`kind`** -**out = table.put in=`out` at="backend" value=`backend`** -*out* +We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value=`kind`))**. +We retain **`out` = [Set the backend field in the new record](table.put(in=`out`, at="backend", value=`backend`))**. +Return *out*. ## await_workbook - + `path` - + `sandbox`=False - + `sandbox_root`=None - + `sandbox_profile`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| sandbox | any | False | Whether to use the CoW trial path | +| sandbox_root | any | None | Root directory of the CoW trial | +| sandbox_profile | any | "default" | Capability profile for CoW execution | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Spawn a workbook file (quiet by default), wait, and inspect. With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit. | + +Use `path`, `sandbox`=False, `sandbox_root`=None, `sandbox_profile`="default" as the inputs for this operation. Spawn a workbook file (quiet by default), wait, and inspect. With `sandbox=True`, run via `## trial` first (commit on ok); host unchanged until that commit. 1. `sandbox` - **tr = trial path=`path` root=`sandbox_root` profile=`sandbox_profile` commit=True** - **ok = > json.get value=`tr` key="ok"** - **stdout = > json.get value=`tr` key="stdout"** - **stderr = > json.get value=`tr` key="stderr"** + We retain **`tr` = [Trial](trial(path=`path`, root=`sandbox_root`, profile=`sandbox_profile`, commit=True))**. + We retain **`ok` = [Read the ok field](json.get(value=`tr`, key="ok"))**. + We retain **`stdout` = [Read the stdout field](json.get(value=`tr`, key="stdout"))**. + We retain **`stderr` = [Read the stderr field](json.get(value=`tr`, key="stderr"))**. 1. `ok` - **code = 0** + We retain **code = 0**. 2. * - **code = 1** - **value = stdout** - **obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`** + We retain **code = 1**. + We retain **value = stdout**. + We retain **`obs` = [Inspect workbook](inspect_workbook(path=`path`, exit_code=`code`, value=`value`, stdout=`stdout`, stderr=`stderr`))**. **out = ** | code | value | observation | sandbox | |------|-------|-------------|---------| | `code` | `value` | `obs` | `tr` | - *out* + Return *out*. 2. * - **id = subtask.spawn path=`path`** - **waited = subtask.wait id=`id`** - **code = > json.get value=`waited` key="code"** - **value = > json.get value=`waited` key="value"** - **stdout = > json.get value=`waited` key="stdout"** - **stderr = > json.get value=`waited` key="stderr"** - **obs = inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr`** + We retain **`id` = [Spawn](subtask.spawn(path=`path`))**. + We retain **`waited` = [Wait](subtask.wait(id=`id`))**. + We retain **`code` = [Read the code field](json.get(value=`waited`, key="code"))**. + We retain **`value` = [Read the value field](json.get(value=`waited`, key="value"))**. + We retain **`stdout` = [Read the stdout field](json.get(value=`waited`, key="stdout"))**. + We retain **`stderr` = [Read the stderr field](json.get(value=`waited`, key="stderr"))**. + We retain **`obs` = [Inspect workbook](inspect_workbook(path=`path`, exit_code=`code`, value=`value`, stdout=`stdout`, stderr=`stderr`))**. **out = ** | code | value | observation | |------|-------|-------------| | `code` | `value` | `obs` | - *out* + Return *out*. --- ## text_head_lines - + `text` - + `max_lines`=80 - + `max_chars`=4000 -**esc = > json.parse text={"nl":"\n"}** -**nl = > json.get value=`esc` key="nl"** -**raw = > str value=`text`** -**lines = > split value=`raw` sep=`nl`** -**acc = > table.empty_list** -**chars = 0** -**count = 0** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | any | required | Text supplied to the transformation or adapter | +| max_lines | any | 80 | Maximum retained lines in the text excerpt | +| max_chars | any | 4000 | Maximum retained characters in the text excerpt | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Keep at most the requested leading lines of text when preparing a bounded context excerpt. | + +Use `text`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. + +Keep at most the requested leading lines of text when preparing a bounded context excerpt. + +Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`raw` = [Str](str(value=`text`))**. +We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. +We retain **`acc` = [Empty list](table.empty_list())**. +We retain **chars = 0**. +We retain **count = 0**. - [line](遍历 `lines` 为 `line`) 1. `count` < `max_lines` - **ln = > len value=`line`** - **next = chars + ln** + We retain **`ln` = [Len](len(value=`line`))**. + We retain **next = chars + ln**. 1. `next` > `max_chars` - **count = max_lines** + We retain **count = max_lines**. 2. * - **acc = > table.append list=`acc` item=`line`** - **chars = next** - **count = count + 1** + We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. + We retain **chars = next**. + We retain **count = count + 1**. 2. * **_ = 1** -*> join value=`acc` sep=`nl`* +Return *[Join](join(value=`acc`, sep=`nl`))*. --- ## text_tail_lines - + `text` - + `max_lines`=40 - + `max_chars`=2000 -**esc = > json.parse text={"nl":"\n"}** -**nl = > json.get value=`esc` key="nl"** -**raw = > str value=`text`** -**lines = > split value=`raw` sep=`nl`** -**n = > len value=`lines`** -**start = n - max_lines** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | any | required | Text supplied to the transformation or adapter | +| max_lines | any | 40 | Maximum retained lines in the text excerpt | +| max_chars | any | 2000 | Maximum retained characters in the text excerpt | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Keep at most the requested trailing lines of text when preparing a bounded context excerpt. | + +Use `text`, `max_lines`=40, `max_chars`=2000 as the inputs for this operation. + +Keep at most the requested trailing lines of text when preparing a bounded context excerpt. + +Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`raw` = [Str](str(value=`text`))**. +We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. +We retain **`n` = [Len](len(value=`lines`))**. +We retain **start = n - max_lines**. 1. `start` < 0 - **start = 0** + We retain **start = 0**. 2. * **_ = 1** -**acc = > table.empty_list** -**i = 0** -**chars = 0** +We retain **`acc` = [Empty list](table.empty_list())**. +We retain **i = 0**. +We retain **chars = 0**. - [line](遍历 `lines` 为 `line`) 1. `i` >= `start` - **ln = > len value=`line`** - **next = chars + ln** + We retain **`ln` = [Len](len(value=`line`))**. + We retain **next = chars + ln**. 1. `next` > `max_chars` - **i = n** + We retain **i = n**. 2. * - **acc = > table.append list=`acc` item=`line`** - **chars = next** + We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. + We retain **chars = next**. 2. * **_ = 1** - **i = i + 1** -*> join value=`acc` sep=`nl`* + We retain **i = i + 1**. +Return *[Join](join(value=`acc`, sep=`nl`))*. --- ## strip_html_comments - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | any | required | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Drop `` blocks (including marqdo-out bodies) so parent excerpts stay structural. | + +Use `text` as the inputs for this operation. Drop `` blocks (including marqdo-out bodies) so parent excerpts stay structural. -**esc = > json.parse text={"nl":"\n"}** -**nl = > json.get value=`esc` key="nl"** -**raw = > str value=`text`** -**lines = > split value=`raw` sep=`nl`** -**acc = > table.empty_list** -**skip = None** +This is a line-oriented removal helper for workbook inspection. It tracks whether a comment span is open across lines, so hidden author notes do not inflate the excerpt. It is not an HTML parser and does not sanitize rendered pages. + +Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`raw` = [Str](str(value=`text`))**. +We retain **`lines` = [Split](split(value=`raw`, sep=`nl`))**. +We retain **`acc` = [Empty list](table.empty_list())**. +We retain **skip = None**. - [line](遍历 `lines` 为 `line`) 1. `skip` - **end_parts = > split value=`line` sep="-->"** - **en = > len value=`end_parts`** + We retain **`end_parts` = [Split](split(value=`line`, sep="-->"))**. + We retain **`en` = [Len](len(value=`end_parts`))**. 1. `en` > 1 - **skip = None** + We retain **skip = None**. 2. * **_ = 1** 2. * - **start_parts = > split value=`line` sep=""** - **en = > len value=`end_parts`** + We retain **`tail` = [At](at(value=`start_parts`, index=1))**. + We retain **`end_parts` = [Split](split(value=`tail`, sep="-->"))**. + We retain **`en` = [Len](len(value=`end_parts`))**. 1. `en` > 1 - **skip = None** + We retain **skip = None**. 2. * - **skip = 1** + We retain **skip = 1**. 2. * - **acc = > table.append list=`acc` item=`line`** -*> join value=`acc` sep=`nl`* + We retain **`acc` = [Append this item to the new list](table.append(list=`acc`, item=`line`))**. +Return *[Join](join(value=`acc`, sep=`nl`))*. --- ## workbook_source_excerpt - + `source` - + `max_lines`=80 - + `max_chars`=4000 -**clean = > strip_html_comments text=`source`** -*> text_head_lines text=`clean` max_lines=`max_lines` max_chars=`max_chars`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| source | any | required | Source text inspected or prepared by this operation | +| max_lines | any | 80 | Maximum retained lines in the text excerpt | +| max_chars | any | 4000 | Maximum retained characters in the text excerpt | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Select a bounded excerpt from workbook source for the next planning observation. | + +Use `source`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. + +Select a bounded excerpt from workbook source for the next planning observation. + +We retain **`clean` = [Strip html comments](strip_html_comments(text=`source`))**. +Return *[Text head lines](text_head_lines(text=`clean`, max_lines=`max_lines`, max_chars=`max_chars`))*. --- ## workbook_excerpt - + `path` - + `max_lines`=80 - + `max_chars`=4000 -**src = > fs.read_text path=`path`** -*> workbook_source_excerpt source=`src` max_lines=`max_lines` max_chars=`max_chars`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| max_lines | any | 80 | Maximum retained lines in the text excerpt | +| max_chars | any | 4000 | Maximum retained characters in the text excerpt | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read a workbook excerpt using explicit depth and length budgets. | + +Use `path`, `max_lines`=80, `max_chars`=4000 as the inputs for this operation. + +Read a workbook excerpt using explicit depth and length budgets. + +We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. +Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=`max_lines`, max_chars=`max_chars`))*. --- ## workbook_read - + `path` - + `depth`=default -**src = > fs.read_text path=`path`** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| depth | any | "default" | Requested context or discovery depth | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read a workbook by path and expose the budgeted view required by the planner. | + +Use `path`, `depth`="default" as the inputs for this operation. + +We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. 1. `depth` == deep - *> workbook_source_excerpt source=`src` max_lines=200 max_chars=12000* + Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=200, max_chars=12000))*. 2. * - *> workbook_source_excerpt source=`src` max_lines=80 max_chars=4000* + Return *[Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=80, max_chars=4000))*. --- ## lib_catalog +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports. Parent also exposes evidence tools `corpus_search` / `mcp_list_tools` / `mcp_call` (not authority). | + Callable dotted names (whitelist for `CALL:lib…`) plus static module file list for workbook imports. Parent also exposes evidence tools `corpus_search` / `mcp_list_tools` / `mcp_call` (not authority). -**out = > json.parse text={"note":"Direct CALL:lib.. + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/.mq.md then PATCH / scratch_tool_write. Evidence tools: CALL:corpus_search | mcp_list_tools | mcp_call (fixture RAG/MCP) — workbook .mq.md remains authority.","files":["fs.mq.md","json.mq.md","subtask.mq.md","sys.mq.md","writeback.mq.md","text.mq.md","time.mq.md","math.mq.md","net.mq.md","table.mq.md","plugin.mq.md","foreign.mq.md"],"callable":[{"name":"lib.fs.read_text","desc":"Read UTF-8 text file"},{"name":"lib.fs.exists","desc":"Path exists?"},{"name":"lib.fs.list_dir","desc":"List directory entries"},{"name":"lib.json.parse","desc":"Parse JSON text"},{"name":"lib.json.stringify","desc":"Serialize JSON"},{"name":"lib.sys.cwd","desc":"Process working directory"},{"name":"corpus_search","desc":"Local markdown/text keyword search (evidence)"},{"name":"mcp_list_tools","desc":"List tools from MCP JSON fixture"},{"name":"mcp_call","desc":"Call a tool from MCP JSON fixture"}]}** -*out* +The import files are a list of source modules. They are not all enabled as direct parent tools. + +The two lists answer different questions: files can be imported into a workbook, while callable records name the limited actions understood by the parent dispatcher. This is not a complete catalog of the standard library. New source functions remain discoverable through the normal source catalog and MLSP; adding a file here does not grant it execution permission. + +`_literal_files` = + +| file | +|---| +| "fs.mq.md" | +| "json.mq.md" | +| "subtask.mq.md" | +| "sys.mq.md" | +| "writeback.mq.md" | +| "text.mq.md" | +| "time.mq.md" | +| "math.mq.md" | +| "net.mq.md" | +| "table.mq.md" | +| "plugin.mq.md" | +| "foreign.mq.md" | + +Only the following names belong to this parent dispatcher. The description explains the action; +a name still passes through the normal allowlist and its effect boundary at execution. + +`_literal_callable` = + +| @ | desc | name | +|---|---|---| +| 1 | "Read UTF-8 text file" | "lib.fs.read_text" | +| 2 | "Path exists?" | "lib.fs.exists" | +| 3 | "List directory entries" | "lib.fs.list_dir" | +| 4 | "Parse JSON text" | "lib.json.parse" | +| 5 | "Serialize JSON" | "lib.json.stringify" | +| 6 | "Process working directory" | "lib.sys.cwd" | +| 7 | "Local markdown/text keyword search (evidence)" | "corpus_search" | +| 8 | "List tools from MCP JSON fixture" | "mcp_list_tools" | +| 9 | "Call a tool from MCP JSON fixture" | "mcp_call" | + +The note is returned with both lists, so a caller can distinguish an importable file from an +allowed CALL name. Evidence adapters read fixtures here; they do not establish workbook authority. + +`out` = + +| callable | files | note | +|---|---|---| +| `_literal_callable` | `_literal_files` | "Direct CALL:lib.. + optional ARGS:{json} for whitelist only. Or import via frontmatter > lib/.mq.md then PATCH / scratch_tool_write. Evidence tools: CALL:corpus_search \| mcp_list_tools \| mcp_call (fixture RAG/MCP) — workbook .mq.md remains authority." | +Return *out*. --- ## corpus_search - + `query` - + `root`=.marqdo/agent-corpus - + `limit`=6 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| query | any | required | Text used to search the bounded catalog or tool registry | +| root | any | ".marqdo/agent-corpus" | Explicit root directory for discovery or isolated execution | +| limit | any | 6 | Maximum returned entries or candidates; this is not a success threshold | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Local keyword search over `.md` / `.mq.md` / `.txt` under `root`. Returns ranked excerpts. Evidence only — runnable workbook / OKF skill stays authority (`authority=workbook`). Ensures the native agent plugin is loaded so plain `marqdo run` (without constructing `# agent`) can call this. | + +Use `query`, `root`=".marqdo/agent-corpus", `limit`=6 as the inputs for this operation. Local keyword search over `.md` / `.mq.md` / `.txt` under `root`. Returns ranked excerpts. Evidence only — runnable workbook / OKF skill stays authority (`authority=workbook`). Ensures the native agent plugin is loaded so plain `marqdo run` (without constructing `# agent`) can call this. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_corpus_search query=`query` root=`root` limit=`limit`* +Return *[Corpus search](agent_corpus_search(query=`query`, root=`root`, limit=`limit`))*. --- ## mcp_list_tools - + `fixture` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| fixture | any | required | Deterministic fixture data used for offline behavior | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List tools from an offline MCP-shaped JSON fixture (`tools` array). Evidence only. | + +Use `fixture` as the inputs for this operation. List tools from an offline MCP-shaped JSON fixture (`tools` array). Evidence only. -*> agent_mcp_fixture action="list" fixture=`fixture`* +Return *[Mcp fixture](agent_mcp_fixture(action="list", fixture=`fixture`))*. --- ## mcp_call - + `name` - + `fixture` - + `arguments`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| fixture | any | required | Deterministic fixture data used for offline behavior | +| arguments | any | None | Named argument record for the selected registered tool | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Call a named tool from a MCP-shaped fixture (`results` / `calls` map). Optional `arguments` echoed; fixture results are keyed by name. Evidence only. | + +Use `name`, `fixture`, `arguments`=None as the inputs for this operation. Call a named tool from a MCP-shaped fixture (`results` / `calls` map). Optional `arguments` echoed; fixture results are keyed by name. Evidence only. 1. `arguments` - *> agent_mcp_fixture action="call" fixture=`fixture` name=`name` arguments=`arguments`* + Return *[Mcp fixture](agent_mcp_fixture(action="call", fixture=`fixture`, name=`name`, arguments=`arguments`))*. 2. * - *> agent_mcp_fixture action="call" fixture=`fixture` name=`name`* + Return *[Mcp fixture](agent_mcp_fixture(action="call", fixture=`fixture`, name=`name`))*. --- ## mcp_connect - + `command` - + `args`=None - + `session`="default" - + `name`="mcp" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| command | any | required | Configured external command | +| args | any | None | Arguments passed to the selected command or operation | +| session | any | "default" | Existing session handle returned by the corresponding connector | +| name | any | "mcp" | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Open a stdio MCP client session (spawn `command` + `args`, JSON-RPC initialize). Evidence only — workbook remains authority. | + +Use `command`, `args`=None, `session`="default", `name`="mcp" as the inputs for this operation. Open a stdio MCP client session (spawn `command` + `args`, JSON-RPC initialize). Evidence only — workbook remains authority. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. 1. `args` - *> agent_mcp_client action="connect" command=`command` args=`args` session=`session` name=`name`* + Return *[Mcp client](agent_mcp_client(action="connect", command=`command`, args=`args`, session=`session`, name=`name`))*. 2. * - *> agent_mcp_client action="connect" command=`command` session=`session` name=`name`* + Return *[Mcp client](agent_mcp_client(action="connect", command=`command`, session=`session`, name=`name`))*. ## mcp_client_list - + `session`="default" - + `command`=None - + `args`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| session | any | "default" | Existing session handle returned by the corresponding connector | +| command | any | None | Configured external command | +| args | any | None | Arguments passed to the selected command or operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List tools from an open MCP session, or one-shot when `command=` is set (no session retained). | + +Use `session`="default", `command`=None, `args`=None as the inputs for this operation. List tools from an open MCP session, or one-shot when `command=` is set (no session retained). 1. `command` 1. `args` - *> agent_mcp_client action="list" command=`command` args=`args`* + Return *[Mcp client](agent_mcp_client(action="list", command=`command`, args=`args`))*. 2. * - *> agent_mcp_client action="list" command=`command`* + Return *[Mcp client](agent_mcp_client(action="list", command=`command`))*. 2. * - *> agent_mcp_client action="list" session=`session`* + Return *[Mcp client](agent_mcp_client(action="list", session=`session`))*. ## mcp_client_call - + `name`=None - + `session`="default" - + `arguments`=None - + `command`=None - + `args`=None - + `tool`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | None | Name registered or looked up by this operation | +| session | any | "default" | Existing session handle returned by the corresponding connector | +| arguments | any | None | Named argument record for the selected registered tool | +| command | any | None | Configured external command | +| args | any | None | Arguments passed to the selected command or operation | +| tool | any | None | Registered tool or tool name selected by policy | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Call a tool on an open MCP session, or one-shot when `command=` is set. Prefer `tool=` for oneshot when `name` would collide with server name. | + +Use `name`=None, `session`="default", `arguments`=None, `command`=None, `args`=None, `tool`=None as the inputs for this operation. Call a tool on an open MCP session, or one-shot when `command=` is set. Prefer `tool=` for oneshot when `name` would collide with server name. 1. `command` 1. `tool` - **tn = tool** + We retain **tn = tool**. 2. * - **tn = name** + We retain **tn = name**. 1. `args` - *> agent_mcp_client action="call" command=`command` args=`args` tool=`tn` arguments=`arguments`* + Return *[Mcp client](agent_mcp_client(action="call", command=`command`, args=`args`, tool=`tn`, arguments=`arguments`))*. 2. * - *> agent_mcp_client action="call" command=`command` tool=`tn` arguments=`arguments`* + Return *[Mcp client](agent_mcp_client(action="call", command=`command`, tool=`tn`, arguments=`arguments`))*. 2. * - *> agent_mcp_client action="call" session=`session` name=`name` arguments=`arguments`* + Return *[Mcp client](agent_mcp_client(action="call", session=`session`, name=`name`, arguments=`arguments`))*. ## mcp_disconnect - + `session`="default" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| session | any | "default" | Existing session handle returned by the corresponding connector | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Close a stdio MCP client session. | + +Use `session`="default" as the inputs for this operation. Close a stdio MCP client session. -*> agent_mcp_client action="close" session=`session`* +Return *[Mcp client](agent_mcp_client(action="close", session=`session`))*. --- ## resume_save - + `id` - + `goal`=None - + `task`=None - + `status`=running - + `round`=0 - + `workbook`=None - + `events`=None - + `route`=None - + `result`=None - + `resume_dir`=.marqdo/agent-resume - + `checkpoint_v2`=False - + `attempt_id`=None - + `effect_ledger_watermark`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| goal | any | None | Human task goal represented by this operation | +| task | any | None | Structured task or text supplied to the agent | +| status | any | "running" | Domain status recorded in the structured result | +| round | any | 0 | Current planning round number | +| workbook | any | None | Workbook path or structured workbook reference | +| events | any | None | Ordered semantic or provider stream-event records | +| route | any | None | Selected route or route-policy data | +| result | any | None | Structured result from the preceding operation | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | +| checkpoint_v2 | any | False | Versioned continuation checkpoint record | +| attempt_id | any | None | Identifier for this execution attempt | +| effect_ledger_watermark | any | None | Last durable effect-ledger position included by the checkpoint | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Persist a plan/run checkpoint as `.marqdo/agent-resume/.json` (atomic write). Pass `checkpoint_v2=True` for CheckpointV2 schema. `resume_dir` must be host-relative. | + +Use `id`, `goal`=None, `task`=None, `status`="running", `round`=0, `workbook`=None, `events`=None, `route`=None, `result`=None, `resume_dir`=".marqdo/agent-resume", `checkpoint_v2`=False, `attempt_id`=None, `effect_ledger_watermark`=None as the inputs for this operation. Persist a plan/run checkpoint as `.marqdo/agent-resume/.json` (atomic write). Pass `checkpoint_v2=True` for CheckpointV2 schema. `resume_dir` must be host-relative. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_resume_save id=`id` goal=`goal` task=`task` status=`status` round=`round` workbook=`workbook` events=`events` route=`route` result=`result` resume_dir=`resume_dir` checkpoint_v2=`checkpoint_v2` attempt_id=`attempt_id` effect_ledger_watermark=`effect_ledger_watermark`* +Return *[Resume save](agent_resume_save(id=`id`, goal=`goal`, task=`task`, status=`status`, round=`round`, workbook=`workbook`, events=`events`, route=`route`, result=`result`, resume_dir=`resume_dir`, checkpoint_v2=`checkpoint_v2`, attempt_id=`attempt_id`, effect_ledger_watermark=`effect_ledger_watermark`))*. ## resume_load - + `id` - + `resume_dir`=.marqdo/agent-resume + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load a resume checkpoint (or `{ok:false,found:false}`). Legacy / missing effect ledger → `recovery_mode=manual_review`, `write_auto_resume=false`. | + +Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. Load a resume checkpoint (or `{ok:false,found:false}`). Legacy / missing effect ledger → `recovery_mode=manual_review`, `write_auto_resume=false`. -*> agent_resume_load id=`id` resume_dir=`resume_dir`* +Return *[Resume load](agent_resume_load(id=`id`, resume_dir=`resume_dir`))*. ## error_make - + `code` - + `message`=None - + `category`=None - + `stage`=agent - + `retryable`=None - + `effect_state`=none - + `recovery_action`=None - + `call_id`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | any | required | Stable failure category or bound code value, as stated by this function | +| message | any | None | Outgoing WebSocket or application message | +| category | any | None | Failure category used by recovery policy | +| stage | any | "agent" | Execution stage where the failure occurred | +| retryable | any | None | Whether policy considers this failure eligible for retry | +| effect_state | any | "none" | Observed state of the logical effect | +| recovery_action | any | None | Selected recovery operation | +| call_id | any | None | Identifier of this tool invocation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Build an `AgentErrorV1` document (M-A1). | + +Use `code`, `message`=None, `category`=None, `stage`="agent", `retryable`=None, `effect_state`="none", `recovery_action`=None, `call_id`=None as the inputs for this operation. Build an `AgentErrorV1` document (M-A1). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_error_make code=`code` message=`message` category=`category` stage=`stage` retryable=`retryable` effect_state=`effect_state` recovery_action=`recovery_action` call_id=`call_id`* +Return *[Error make](agent_error_make(code=`code`, message=`message`, category=`category`, stage=`stage`, retryable=`retryable`, effect_state=`effect_state`, recovery_action=`recovery_action`, call_id=`call_id`))*. ## error_decide_retry - + `error` - + `attempts`=0 - + `effect_class`=read - + `cancelled`=False - + `fingerprint_repeats`=0 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| error | any | required | Structured failure information supplied by the caller | +| attempts | any | 0 | Retry or exploration attempts already performed | +| effect_class | any | "read" | Declared kind of effect for this operation | +| cancelled | any | False | Whether cancellation has already been requested | +| fingerprint_repeats | any | 0 | Number of repeated identical failure fingerprints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Bounded recovery decision. Write / unknown effect → `manual_review` (no auto redo). | + +Use `error`, `attempts`=0, `effect_class`="read", `cancelled`=False, `fingerprint_repeats`=0 as the inputs for this operation. Bounded recovery decision. Write / unknown effect → `manual_review` (no auto redo). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_error_decide_retry error=`error` attempts=`attempts` effect_class=`effect_class` cancelled=`cancelled` fingerprint_repeats=`fingerprint_repeats`* +Return *[Error decide retry](agent_error_decide_retry(error=`error`, attempts=`attempts`, effect_class=`effect_class`, cancelled=`cancelled`, fingerprint_repeats=`fingerprint_repeats`))*. ## resume_clear - + `id` - + `resume_dir`=.marqdo/agent-resume + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delete a resume checkpoint. | + +Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. Delete a resume checkpoint. -*> agent_resume_clear id=`id` resume_dir=`resume_dir`* +Return *[Resume clear](agent_resume_clear(id=`id`, resume_dir=`resume_dir`))*. ## resume_list - + `resume_dir`=.marqdo/agent-resume + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List checkpoint ids under `resume_dir`. | + +Use `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. List checkpoint ids under `resume_dir`. -*> agent_resume_list resume_dir=`resume_dir`* +Return *[Resume list](agent_resume_list(resume_dir=`resume_dir`))*. ## resume - + `id` - + `resume_dir`=.marqdo/agent-resume + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Author entry: load checkpoint for continuation. Returns the checkpoint map (`found`/`round`/`workbook`/…). Callers continue with `plan`/`run` using saved fields; clear when done. | + +Use `id`, `resume_dir`=".marqdo/agent-resume" as the inputs for this operation. Author entry: load checkpoint for continuation. Returns the checkpoint map (`found`/`round`/`workbook`/…). Callers continue with `plan`/`run` using saved fields; clear when done. -*> resume_load id=`id` resume_dir=`resume_dir`* +Return *[Resume load](resume_load(id=`id`, resume_dir=`resume_dir`))*. ## effects_prepare - + `operation_id` - + `idempotency_key` - + `args_digest` - + `effect_class`="write" - + `resource_scope`=None - + `expected_revision`=None - + `result_ref`=None - + `logical_run_id`=None - + `step_id`=None - + `attempt_id`=None - + `ledger_dir`=.marqdo/agent-effects + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| operation_id | any | required | Stable idempotent operation identifier | +| idempotency_key | any | required | Key identifying the same logical effect across retries | +| args_digest | any | required | Digest of the exact operation arguments | +| effect_class | any | "write" | Declared kind of effect for this operation | +| resource_scope | any | None | Resource boundary to which the operation applies | +| expected_revision | any | None | Revision the controlled update expects | +| result_ref | any | None | Durable reference to an already-produced result | +| logical_run_id | any | None | Stable logical execution identifier shared by retries | +| step_id | any | None | Identifier of the current workbook step | +| attempt_id | any | None | Identifier for this execution attempt | +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Create (or dedupe) an `EffectLedgerRecordV1` in `prepared`. Same idempotency_key + args_digest returns the existing record; same key with different digest is rejected. | + +Use `operation_id`, `idempotency_key`, `args_digest`, `effect_class`="write", `resource_scope`=None, `expected_revision`=None, `result_ref`=None, `logical_run_id`=None, `step_id`=None, `attempt_id`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. Create (or dedupe) an `EffectLedgerRecordV1` in `prepared`. Same idempotency_key + args_digest returns the existing record; same key with different digest is rejected. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_prepare operation_id=`operation_id` idempotency_key=`idempotency_key` args_digest=`args_digest` effect_class=`effect_class` resource_scope=`resource_scope` expected_revision=`expected_revision` result_ref=`result_ref` logical_run_id=`logical_run_id` step_id=`step_id` attempt_id=`attempt_id` ledger_dir=`ledger_dir`* +Return *[Effects prepare](agent_effects_prepare(operation_id=`operation_id`, idempotency_key=`idempotency_key`, args_digest=`args_digest`, effect_class=`effect_class`, resource_scope=`resource_scope`, expected_revision=`expected_revision`, result_ref=`result_ref`, logical_run_id=`logical_run_id`, step_id=`step_id`, attempt_id=`attempt_id`, ledger_dir=`ledger_dir`))*. ## effects_transition - + `operation_id` - + `state` - + `result_ref`=None - + `note`=None - + `reconcile_hint`=None - + `ledger_dir`=.marqdo/agent-effects + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| operation_id | any | required | Stable idempotent operation identifier | +| state | any | required | Structured current state | +| result_ref | any | None | Durable reference to an already-produced result | +| note | any | None | Human-readable context associated with the record | +| reconcile_hint | any | None | Hint for reconciling an uncertain effect, not authorization to repeat it | +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Advance ledger state (`prepared→started→committed|failed_no_effect|unknown→reconciled_*`). | + +Use `operation_id`, `state`, `result_ref`=None, `note`=None, `reconcile_hint`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. Advance ledger state (`prepared→started→committed|failed_no_effect|unknown→reconciled_*`). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_transition operation_id=`operation_id` state=`state` result_ref=`result_ref` note=`note` reconcile_hint=`reconcile_hint` ledger_dir=`ledger_dir`* +Return *[Effects transition](agent_effects_transition(operation_id=`operation_id`, state=`state`, result_ref=`result_ref`, note=`note`, reconcile_hint=`reconcile_hint`, ledger_dir=`ledger_dir`))*. ## effects_get - + `operation_id` - + `ledger_dir`=.marqdo/agent-effects + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| operation_id | any | required | Stable idempotent operation identifier | +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load one ledger record. | + +Use `operation_id`, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. Load one ledger record. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_get operation_id=`operation_id` ledger_dir=`ledger_dir`* +Return *[Effects get](agent_effects_get(operation_id=`operation_id`, ledger_dir=`ledger_dir`))*. ## effects_list - + `ledger_dir`=.marqdo/agent-effects - + `logical_run_id`=None - + `state`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | +| logical_run_id | any | None | Stable logical execution identifier shared by retries | +| state | any | None | Structured current state | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List ledger records (optional filters). | + +Use `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None, `state`=None as the inputs for this operation. List ledger records (optional filters). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_list ledger_dir=`ledger_dir` logical_run_id=`logical_run_id` state=`state`* +Return *[Effects list](agent_effects_list(ledger_dir=`ledger_dir`, logical_run_id=`logical_run_id`, state=`state`))*. ## effects_watermark - + `ledger_dir`=.marqdo/agent-effects - + `logical_run_id`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | +| logical_run_id | any | None | Stable logical execution identifier shared by retries | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Digest committed/open effects for CheckpointV2. `write_auto_resume_safe` is false while unknown or pending writes remain. | + +Use `ledger_dir`=".marqdo/agent-effects", `logical_run_id`=None as the inputs for this operation. Digest committed/open effects for CheckpointV2. `write_auto_resume_safe` is false while unknown or pending writes remain. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_watermark ledger_dir=`ledger_dir` logical_run_id=`logical_run_id`* +Return *[Effects watermark](agent_effects_watermark(ledger_dir=`ledger_dir`, logical_run_id=`logical_run_id`))*. ## effects_reconcile - + `operation_id` - + `outcome` - + `result_ref`=None - + `note`=None - + `ledger_dir`=.marqdo/agent-effects + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| operation_id | any | required | Stable idempotent operation identifier | +| outcome | any | required | Observed domain result | +| result_ref | any | None | Durable reference to an already-produced result | +| note | any | None | Human-readable context associated with the record | +| ledger_dir | any | ".marqdo/agent-effects" | Directory holding the durable effect ledger | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Reconcile an `unknown` record: `outcome` = committed | no_effect | needs_input. | + +Use `operation_id`, `outcome`, `result_ref`=None, `note`=None, `ledger_dir`=".marqdo/agent-effects" as the inputs for this operation. Reconcile an `unknown` record: `outcome` = committed | no_effect | needs_input. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. -*> agent_effects_reconcile operation_id=`operation_id` outcome=`outcome` result_ref=`result_ref` note=`note` ledger_dir=`ledger_dir`* +Return *[Effects reconcile](agent_effects_reconcile(operation_id=`operation_id`, outcome=`outcome`, result_ref=`result_ref`, note=`note`, ledger_dir=`ledger_dir`))*. --- ## extract_call_args - + `reply`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse `ARGS:{…}` JSON line, or a bare `{…}` line after CALL. | + +Use `reply`=None as the inputs for this operation. Parse `ARGS:{…}` JSON line, or a bare `{…}` line after CALL. -**esc = > json.parse text={"nl":"\n","mark":"ARGS:","brace":"{"}** -**nl = > json.get value=`esc` key="nl"** -**mark = > json.get value=`esc` key="mark"** -**brace = > json.get value=`esc` key="brace"** -**empty = > table.empty_map** +The following record names each literal field without a JSON construction chain. + +Only the explicit ARGS line is parsed as JSON. Other reply prose remains inert, and absent arguments stay absent. This extraction does not validate the selected tool's schema or execute the reply; the dispatcher performs those later checks. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "brace" | "{" | +| 2 | "mark" | "ARGS:" | +| 3 | "nl" | "\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`mark` = [Read the mark field](json.get(value=`esc`, key="mark"))**. +We retain **`brace` = [Read the brace field](json.get(value=`esc`, key="brace"))**. +We retain **`empty` = [Empty map](table.empty_map())**. 1. `reply` - **text = > trim value=`reply`** - **lines = > split value=`text` sep=`nl`** - **found = None** + We retain **`text` = [Trim](trim(value=`reply`))**. + We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. + We retain **found = None**. - [line](遍历 `lines` 为 `line`) 1. `found` **_ = 1** 2. * - **t = > trim value=`line`** - **chunks = > split value=`t` sep=`mark`** - **cn = > len value=`chunks`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`chunks` = [Split](split(value=`t`, sep=`mark`))**. + We retain **`cn` = [Len](len(value=`chunks`))**. 1. `cn` > 1 - **rest = > at value=`chunks` index=1** - **found = > trim value=`rest`** + We retain **`rest` = [At](at(value=`chunks`, index=1))**. + We retain **`found` = [Trim](trim(value=`rest`))**. 2. * - **chunks = > split value=`t` sep=`brace`** - **cn = > len value=`chunks`** - **prefix = > at value=`chunks` index=0** + We retain **`chunks` = [Split](split(value=`t`, sep=`brace`))**. + We retain **`cn` = [Len](len(value=`chunks`))**. + We retain **`prefix` = [At](at(value=`chunks`, index=0))**. 1. `cn` > 1 1. `prefix` **_ = 1** 2. * - **found = t** + We retain **found = t**. 2. * **_ = 1** 1. `found` - *> json.parse text=`found`* + Return *[Parse the JSON transport text](json.parse(text=`found`))*. 2. * - *empty* + Return *empty*. 2. * - *empty* + Return *empty*. --- ## tool_result_brief - + `value`=None - + `max_chars`=1024 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | None | Value supplied to this operation; immutable transformations return a new value | +| max_chars | any | 1024 | Maximum retained characters in the text excerpt | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Truncate a tool result for `tool_end` events (~1KiB). | + +Use `value`=None, `max_chars`=1024 as the inputs for this operation. Truncate a tool result for `tool_end` events (~1KiB). 1. `value` - **s = > json.stringify value=`value`** - *> text_head_lines text=`s` max_lines=40 max_chars=`max_chars`* + We retain **`s` = [Encode the structured value as JSON text](json.stringify(value=`value`))**. + Return *[Text head lines](text_head_lines(text=`s`, max_lines=40, max_chars=`max_chars`))*. 2. * - **** + Return *None*. --- ## plan_append_tool - + `events` - + `type` - + `name` - + `kind` - + `result`=None - + `stream`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | +| type | any | required | Structured item or event type | +| name | any | required | Name registered or looked up by this operation | +| kind | any | required | Operation or factorization kind listed in this function's behavior | +| result | any | None | Structured result from the preceding operation | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Always append `tool_start` / `tool_end` to `events` for audit / view process cards. SSE publish only when `stream=True`. | + +Use `events`, `type`, `name`, `kind`, `result`=None, `stream`=False as the inputs for this operation. Always append `tool_start` / `tool_end` to `events` for audit / view process cards. SSE publish only when `stream=True`. @@ -1275,464 +1950,680 @@ Always append `tool_start` / `tool_end` to `events` for audit / view process car | `type` | `name` | `kind` | 1. `result` - **ev = table.put in=`ev` at="result" value=`result`** + We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. 2. * **_ = 1** -**events = > table.append list=`events` item=`ev`** +We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 1. `stream` - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 2. * **_ = 1** -*events* +Return *events*. --- ## run_lib_call - + `name` - + `reply`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Whitelist `CALL:lib..` (+ ARGS). Rejects net/exec/write/delete. | + +Use `name`, `reply`=None as the inputs for this operation. Whitelist `CALL:lib..` (+ ARGS). Rejects net/exec/write/delete. -**args = > extract_call_args reply=`reply`** -**errs = > json.parse text={"deny":"Lib CALL not allowed: "}** +We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. +Keep the literal separator as **errs = [Keep the exact separator](table.put(in=None, at="deny", value="Lib CALL not allowed: "))**. 1. `name` == lib.fs.exists - **path = > json.get value=`args` key="path"** - *> fs.exists path=`path`* + We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. + Return *[Exists](fs.exists(path=`path`))*. 2. `name` == lib.fs.read_text - **path = > json.get value=`args` key="path"** - *> fs.read_text path=`path`* + We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. + Return *[Read UTF-8 text from the selected file](fs.read_text(path=`path`))*. 3. `name` == lib.fs.list_dir - **path = > json.get value=`args` key="path"** - *> fs.list_dir path=`path`* + We retain **`path` = [Read the path field](json.get(value=`args`, key="path"))**. + Return *[List dir](fs.list_dir(path=`path`))*. 4. `name` == lib.json.parse - **text = > json.get value=`args` key="text"** - *> json.parse text=`text`* + We retain **`text` = [Read the text field](json.get(value=`args`, key="text"))**. + Return *[Parse the JSON transport text](json.parse(text=`text`))*. 5. `name` == lib.json.stringify - **value = > json.get value=`args` key="value"** - *> json.stringify value=`value`* + We retain **`value` = [Read the value field](json.get(value=`args`, key="value"))**. + Return *[Encode the structured value as JSON text](json.stringify(value=`value`))*. 6. `name` == lib.sys.cwd - *> sys.cwd* + Return *[Cwd](sys.cwd())*. 7. * - **deny = > json.get value=`errs` key="deny"** - *deny + name* + We retain **`deny` = [Read the deny field](json.get(value=`errs`, key="deny"))**. + Return *deny + name*. --- ## scratch_tool_write - + `name` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| text | any | required | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Write a scratch tool workbook under `.marqdo/agent-runs/tools/.mq.md`. | + +Use `name`, `text` as the inputs for this operation. 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"** -> fs.make_dir path=`dir` -**path = a + name + b** -> fs.write_text path=`path` text=`text` +The following record names each literal field without a JSON construction chain. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "a" | ".marqdo/agent-runs/tools/" | +| 2 | "b" | ".mq.md" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. +We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. +We retain **dir = ".marqdo/agent-runs/tools"**. +We **[Make dir](fs.make_dir(path=`dir`))**. +We retain **path = a + name + b**. +We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`text`))**. + `out` = | ok | path | |----|------| | True | `path` | -*out* +Return *out*. --- ## skill_core_card +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget. | + Protected v2.1 Occlusion card always prepended to skill_brief (M05). Must not be truncated by budget. -**esc = > json.parse text={"card":"## CORE SYNTAX (v2.1 Occlusion)\n1. Print with > print / > 打印 — never use bold markers to print.\n2. Bold markers = statement; italic markers = return.\n3. [desc](payload) = occlusion; brackets never execute.\n4. Read with access(coll, key) — never Classic [key](map) index.\n5. Foreach: - [desc](for coll as item). import + one language per file.\n6. # type · ## function · + params · numbered branches · - loops.\n"}** -*> json.get value=`esc` key="card"* +The card is kept as ordered lines so changes to any syntax instruction remain visible in review. + +These rules precede the budgeted skill excerpt so essential marker meanings remain available when a long skill is shortened. The card describes the runtime surface, including legacy explicit parameters; new library authors use narrative parameters as required by the development guide. Keep both explanations consistent when evolving the language. + +`_literal_core_lines` = + +| line | +|---| +| "## CORE SYNTAX (v2.1 Occlusion)" | +| "1. Print with > print / > 打印 — never use bold markers to print." | +| "2. Bold markers = statement; italic markers = return." | +| "3. [desc](payload) = occlusion; brackets never execute." | +| "4. Read with access(coll, key) — never Classic [key](map) index." | +| "5. Foreach: - [desc](for coll as item). import + one language per file." | +| "6. # type · ## function · + params · numbered branches · - loops." | +| "" | + +We preserve **_literal_core_text = [Join the protected instructions with their exact newlines](text.str_join(xs=`_literal_core_lines`, sep="\n"))** +and retain **esc = [Name the complete protected card](table.put(in=None, at="card", value=`_literal_core_text`))**. +Return *[Read the card field](json.get(value=`esc`, key="card"))*. --- ## skill_brief - + `max_chars`=1200 - + `depth`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| max_chars | any | 1200 | Maximum retained characters in the text excerpt | +| depth | any | "default" | Requested context or discovery depth | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Budgeted marqdo skill text for prompts. Core Occlusion card is always included; remaining budget truncates the rest. `depth=deep` raises the char budget. | + +Use `max_chars`=1200, `depth`="default" as the inputs for this operation. Budgeted marqdo skill text for prompts. Core Occlusion card is always included; remaining budget truncates the rest. `depth=deep` raises the char budget. 1. `depth` == deep - **budget = 4000** + We retain **budget = 4000**. 2. * - **budget = max_chars** -**core = > skill_core_card** -**core_len = > len value=`core`** -**rest_budget = budget - core_len - 2** + We retain **budget = max_chars**. +We retain **`core` = [Skill core card](skill_core_card())**. +We retain **`core_len` = [Len](len(value=`core`))**. +We retain **rest_budget = budget - core_len - 2**. 1. `rest_budget` < 200 - **rest_budget = 200** + We retain **rest_budget = 200**. 2. * **_ = 1** -**skill = > agent_marqdo_skill** -**full = > len value=`skill`** -**rest = > text_head_lines text=`skill` max_lines=80 max_chars=`rest_budget`** -**esc = > json.parse text={"nl":"\n\n"}** -**nl = > json.get value=`esc` key="nl"** -**ex = core + nl + rest** -**used = > len value=`ex`** +We retain **`skill` = [Marqdo skill](agent_marqdo_skill())**. +We retain **`full` = [Len](len(value=`skill`))**. +We retain **`rest` = [Text head lines](text_head_lines(text=`skill`, max_lines=80, max_chars=`rest_budget`))**. +Keep the literal separator as **esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n\n"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **ex = core + nl + rest**. +We retain **`used` = [Len](len(value=`ex`))**. 1. `used` < `full` + `core_len` - **esc2 = > json.parse text={"a":"\n…[truncated skill_len=","b":" budget_chars=","c":"; emit READ:skill to deepen]"}** - **a = > json.get value=`esc2` key="a"** - **b = > json.get value=`esc2` key="b"** - **c = > json.get value=`esc2` key="c"** - *ex + a + full + b + budget + c* + The following record names each literal field without a JSON construction chain. + + `_literal_esc2_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "\n…[truncated skill_len=" | + | 2 | "b" | " budget_chars=" | + | 3 | "c" | "; emit READ:skill to deepen]" | + + We build **esc2 = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc2_fields`))**. + + + We retain **`a` = [Read the a field](json.get(value=`esc2`, key="a"))**. + We retain **`b` = [Read the b field](json.get(value=`esc2`, key="b"))**. + We retain **`c` = [Read the c field](json.get(value=`esc2`, key="c"))**. + Return *ex + a + full + b + budget + c*. 2. * - *ex* + Return *ex*. --- ## source_brief - + `depth`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| depth | any | "default" | Requested context or discovery depth | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Budgeted current-module `.mq.md` source for `step` prompts. Default ~80 lines / 4KiB; `depth=deep` ~200 / 12KiB. | + +Use `depth`="default" as the inputs for this operation. Budgeted current-module `.mq.md` source for `step` prompts. Default ~80 lines / 4KiB; `depth=deep` ~200 / 12KiB. -**src = > agent_module_source** -**full = > len value=`src`** +We retain **`src` = [Module source](agent_module_source())**. +We retain **`full` = [Len](len(value=`src`))**. 1. `depth` == deep - **ex = > workbook_source_excerpt source=`src` max_lines=200 max_chars=12000** - **budget = 12000** + We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=200, max_chars=12000))**. + We retain **budget = 12000**. 2. * - **ex = > workbook_source_excerpt source=`src` max_lines=80 max_chars=4000** - **budget = 4000** -**used = > len value=`ex`** + We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`src`, max_lines=80, max_chars=4000))**. + We retain **budget = 4000**. +We retain **`used` = [Len](len(value=`ex`))**. 1. `used` < `full` - **esc = > json.parse text={"a":"\n…[truncated source_len=","b":" budget_chars=","c":"; emit READ:source to deepen]"}** - **a = > json.get value=`esc` key="a"** - **b = > json.get value=`esc` key="b"** - **c = > json.get value=`esc` key="c"** - *ex + a + full + b + budget + c* + The following record names each literal field without a JSON construction chain. + + `_literal_esc_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "\n…[truncated source_len=" | + | 2 | "b" | " budget_chars=" | + | 3 | "c" | "; emit READ:source to deepen]" | + + We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + + We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. + We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. + We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. + Return *ex + a + full + b + budget + c*. 2. * - *ex* + Return *ex*. --- ## extract_plan_read - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse READ:source|stderr|stdout|slots|skill (Chinese: 读取:…). | + +Use `reply` as the inputs for this operation. Parse READ:source|stderr|stdout|slots|skill (Chinese: 读取:…). -**esc = > json.parse text={"nl":"\n","fw":":"}** -**nl = > json.get value=`esc` key="nl"** -**fw = > json.get value=`esc` key="fw"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**found = None** +The following record names each literal field without a JSON construction chain. + +A READ request asks the orchestration loop for a bounded excerpt, rather than reading a file directly. The parser extracts the named context kind from a reply line. The caller still chooses which kinds it supports and how many additional turns it permits. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "fw" | ":" | +| 2 | "nl" | "\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **found = None**. - [line](遍历 `lines` 为 `line`) - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == READ - **found = rest** + We retain **found = rest**. 2. `head` == 读取 - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * - **parts = > split value=`t` sep=`fw`** - **n = > len value=`parts`** + We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == 读取 - **found = rest** + We retain **found = rest**. 2. `head` == READ - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * **_ = 1** -*found* +Return *found*. --- ## extract_plan_act - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Priority: CALL → READ → DECISION. Returns `{kind,name}`. | + +Use `reply` as the inputs for this operation. Priority: CALL → READ → DECISION. Returns `{kind,name}`. -**tool = > extract_tool_name reply=`reply`** +We retain **`tool` = [Extract tool name](extract_tool_name(reply=`reply`))**. 1. `tool` + `out` = | kind | name | |------|------| | call | `tool` | - *out* + Return *out*. 2. * **_ = 1** -**rk = > extract_plan_read reply=`reply`** +We retain **`rk` = [Extract plan read](extract_plan_read(reply=`reply`))**. 1. `rk` + `out` = | kind | name | |------|------| | read | `rk` | - *out* + Return *out*. 2. * **_ = 1** -**dec = > extract_plan_decision reply=`reply`** +We retain **`dec` = [Extract plan decision](extract_plan_decision(reply=`reply`))**. 1. `dec` + `out` = | kind | name | |------|------| | decision | `dec` | - *out* + Return *out*. 2. * + `out` = | kind | |------| | unknown | - *out* + Return *out*. --- ## extract_scratch_tool - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write. | + +Use `reply` as the inputs for this operation. Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write. -**esc = > json.parse text={"nl":"\n","open":"<<<","close":">>>"}** -**nl = > json.get value=`esc` key="nl"** -**open = > json.get value=`esc` key="open"** -**close = > json.get value=`esc` key="close"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**name = None** -**body_lines = > table.empty_list** -**in_body = None** +The following record names each literal field without a JSON construction chain. + +The tool name and source body are returned as data. The body starts only at the explicit triple-angle opening line and ends at its matching closing line; surrounding commentary is excluded. This function does not write or run that source. The scratch writer remains responsible for destination checks, and the dispatcher still decides whether the requested tool is allowed. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "close" | ">>>" | +| 2 | "nl" | "\n" | +| 3 | "open" | "<<<" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`open` = [Read the open field](json.get(value=`esc`, key="open"))**. +We retain **`close` = [Read the close field](json.get(value=`esc`, key="close"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **name = None**. +We retain **`body_lines` = [Empty list](table.empty_list())**. +We retain **in_body = None**. - [line](遍历 `lines` 为 `line`) 1. `in_body` - **t = > trim value=`line`** + We retain **`t` = [Trim](trim(value=`line`))**. 1. `t` == `close` - **in_body = None** + We retain **in_body = None**. 2. * - **body_lines = > table.append list=`body_lines` item=`line`** + We retain **`body_lines` = [Append this item to the new list](table.append(list=`body_lines`, item=`line`))**. 2. * - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == NAME - **name = rest** + We retain **name = rest**. 2. `head` == 名称 - **name = rest** + We retain **name = rest**. 3. * **_ = 1** 2. * **_ = 1** 1. `t` == `open` - **in_body = 1** + We retain **in_body = 1**. 2. * **_ = 1** -**body = > join value=`body_lines` sep=`nl`** +We retain **`body` = [Join](join(value=`body_lines`, sep=`nl`))**. + `out` = | name | text | |------|------| | `name` | `body` | -*out* +Return *out*. --- ## run_parent_tool - + `name` - + `path` - + `observation`=None - + `reply`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| observation | any | None | Tool observation or workbook result retained for the next turn | +| reply | any | None | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`). | + +Use `name`, `path`, `observation`=None, `reply`=None as the inputs for this operation. Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`). 1. `name` == workbook_read - *> workbook_read path=`path` depth="deep"* +This dispatcher has a fixed set of parent operations. Workbook readers operate on the selected workbook path; catalog lookup returns data; scratch creation first extracts a name and body. The corpus and MCP-shaped evidence branches parse explicit ARGS records and report missing required fields before calling their adapters. Those fixture adapters are not a live MCP transport. + +Arguments are deliberately read only after the value has been recognized as a record. Optional root, limit and argument fields are passed only when present, allowing the target helper to apply its own defaults. An unknown name reaches the restricted library dispatcher; it does not become an arbitrary function call. Editing this branch list therefore changes the parent tool surface and needs an allowlist regression, in addition to a prose update. + + Return *[Workbook read](workbook_read(path=`path`, depth="deep"))*. 2. `name` == workbook_excerpt - *> workbook_excerpt path=`path`* + Return *[Workbook excerpt](workbook_excerpt(path=`path`))*. 3. `name` == lib_catalog - *> lib_catalog* + Return *[Lib catalog](lib_catalog())*. 4. `name` == scratch_tool_write - **parsed = > extract_scratch_tool reply=`reply`** - **parsed_s = > json.stringify value=`parsed`** - **parsed_map = > text.starts_with text=`parsed_s` prefix="{"** - **tn = None** - **tt = None** + We retain **`parsed` = [Extract scratch tool](extract_scratch_tool(reply=`reply`))**. + We retain **`parsed_s` = [Encode the structured value as JSON text](json.stringify(value=`parsed`))**. + We retain **`parsed_map` = [Starts with](text.starts_with(text=`parsed_s`, prefix="{"))**. + We retain **tn = None**. + We retain **tt = None**. 1. `parsed_map` - **tn = > json.get value=`parsed` key="name"** - **tt = > json.get value=`parsed` key="text"** + We retain **`tn` = [Read the name field](json.get(value=`parsed`, key="name"))**. + We retain **`tt` = [Read the text field](json.get(value=`parsed`, key="text"))**. 2. * **_ = 1** - **errs = > json.parse text={"a":"scratch_tool_write needs NAME line and fenced body","b":"scratch_tool_write needs NAME id"}** + The following record names each literal field without a JSON construction chain. + + `_literal_errs_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "scratch_tool_write needs NAME line and fenced body" | + | 2 | "b" | "scratch_tool_write needs NAME id" | + + We build **errs = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_errs_fields`))**. + + 1. `tn` 1. `tt` - *> scratch_tool_write name=`tn` text=`tt`* + Return *[Scratch tool write](scratch_tool_write(name=`tn`, text=`tt`))*. 2. * - *> json.get value=`errs` key="a"* + Return *[Read the a field](json.get(value=`errs`, key="a"))*. 2. * - *> json.get value=`errs` key="b"* + Return *[Read the b field](json.get(value=`errs`, key="b"))*. 5. `name` == corpus_search - **args = > extract_call_args reply=`reply`** - **args_s = > json.stringify value=`args`** - **args_map = > text.starts_with text=`args_s` prefix="{"** - **q = None** - **root = None** - **limit = None** + We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. + We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. + We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. + We retain **q = None**. + We retain **root = None**. + We retain **limit = None**. 1. `args_map` - **q = > json.get value=`args` key="query"** - **root = > json.get value=`args` key="root"** - **limit = > json.get value=`args` key="limit"** + We retain **`q` = [Read the query field](json.get(value=`args`, key="query"))**. + We retain **`root` = [Read the root field](json.get(value=`args`, key="root"))**. + We retain **`limit` = [Read the limit field](json.get(value=`args`, key="limit"))**. 2. * **_ = 1** - **cerrs = > json.parse text={"q":"corpus_search needs ARGS.query"}** + Keep the literal separator as **cerrs = [Keep the exact separator](table.put(in=None, at="q", value="corpus_search needs ARGS.query"))**. 1. not `q` - *> json.get value=`cerrs` key="q"* + Return *[Read the q field](json.get(value=`cerrs`, key="q"))*. 2. `root` 1. `limit` - *> corpus_search query=`q` root=`root` limit=`limit`* + Return *[Corpus search](corpus_search(query=`q`, root=`root`, limit=`limit`))*. 2. * - *> corpus_search query=`q` root=`root`* + Return *[Corpus search](corpus_search(query=`q`, root=`root`))*. 3. `limit` - *> corpus_search query=`q` limit=`limit`* + Return *[Corpus search](corpus_search(query=`q`, limit=`limit`))*. 4. * - *> corpus_search query=`q`* + Return *[Corpus search](corpus_search(query=`q`))*. 6. `name` == mcp_list_tools - **args = > extract_call_args reply=`reply`** - **args_s = > json.stringify value=`args`** - **args_map = > text.starts_with text=`args_s` prefix="{"** - **fx = None** + We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. + We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. + We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. + We retain **fx = None**. 1. `args_map` - **fx = > json.get value=`args` key="fixture"** + We retain **`fx` = [Read the fixture field](json.get(value=`args`, key="fixture"))**. 2. * **_ = 1** - **merrs = > json.parse text={"f":"mcp_list_tools needs ARGS.fixture"}** + Keep the literal separator as **merrs = [Keep the exact separator](table.put(in=None, at="f", value="mcp_list_tools needs ARGS.fixture"))**. 1. `fx` - *> mcp_list_tools fixture=`fx`* + Return *[Mcp list tools](mcp_list_tools(fixture=`fx`))*. 2. * - *> json.get value=`merrs` key="f"* + Return *[Read the f field](json.get(value=`merrs`, key="f"))*. 7. `name` == mcp_call - **args = > extract_call_args reply=`reply`** - **args_s = > json.stringify value=`args`** - **args_map = > text.starts_with text=`args_s` prefix="{"** - **fx = None** - **tn = None** - **targ = None** + We retain **`args` = [Extract call args](extract_call_args(reply=`reply`))**. + We retain **`args_s` = [Encode the structured value as JSON text](json.stringify(value=`args`))**. + We retain **`args_map` = [Starts with](text.starts_with(text=`args_s`, prefix="{"))**. + We retain **fx = None**. + We retain **tn = None**. + We retain **targ = None**. 1. `args_map` - **fx = > json.get value=`args` key="fixture"** - **tn = > json.get value=`args` key="name"** - **targ = > json.get value=`args` key="arguments"** + We retain **`fx` = [Read the fixture field](json.get(value=`args`, key="fixture"))**. + We retain **`tn` = [Read the name field](json.get(value=`args`, key="name"))**. + We retain **`targ` = [Read the arguments field](json.get(value=`args`, key="arguments"))**. 2. * **_ = 1** - **xerrs = > json.parse text={"f":"mcp_call needs ARGS.fixture","n":"mcp_call needs ARGS.name"}** + The following record names each literal field without a JSON construction chain. + + `_literal_xerrs_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "f" | "mcp_call needs ARGS.fixture" | + | 2 | "n" | "mcp_call needs ARGS.name" | + + We build **xerrs = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_xerrs_fields`))**. + + 1. `fx` 1. `tn` 1. `targ` - *> mcp_call name=`tn` fixture=`fx` arguments=`targ`* + Return *[Mcp call](mcp_call(name=`tn`, fixture=`fx`, arguments=`targ`))*. 2. * - *> mcp_call name=`tn` fixture=`fx`* + Return *[Mcp call](mcp_call(name=`tn`, fixture=`fx`))*. 2. * - *> json.get value=`xerrs` key="n"* + Return *[Read the n field](json.get(value=`xerrs`, key="n"))*. 2. * - *> json.get value=`xerrs` key="f"* + Return *[Read the f field](json.get(value=`xerrs`, key="f"))*. 8. * - **dots = > split value=`name` sep=".*"** - **head = > at value=`dots` index=0** + We retain **`dots` = [Split](split(value=`name`, sep=".*"))**. + We retain **`head` = [At](at(value=`dots`, index=0))**. 1. `head` == lib - *> run_lib_call name=`name` reply=`reply`* + Return *[Run lib call](run_lib_call(name=`name`, reply=`reply`))*. 2. * - **msg = "Parent tool not allowed:"** - *msg + name* + We retain **msg = "Parent tool not allowed:"**. + Return *msg + name*. --- ## plan_read_deepen - + `observation` - + `kind` - + `path` -**obs = observation** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| observation | any | required | Tool observation or workbook result retained for the next turn | +| kind | any | required | Operation or factorization kind listed in this function's behavior | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply the requested source or skill depth increase before preparing another planning turn. | + +Use `observation`, `kind`, `path` as the inputs for this operation. + +We retain **obs = observation**. 1. `kind` == source - **ex = > workbook_read path=`path` depth="deep"** - **obs = table.put in=`obs` at="source_excerpt" value=`ex`** - **obs = table.put in=`obs` at="read_source" value=True** + We retain **`ex` = [Workbook read](workbook_read(path=`path`, depth="deep"))**. + We retain **`obs` = [Set the source_excerpt field in the new record](table.put(in=`obs`, at="source_excerpt", value=`ex`))**. + We retain **`obs` = [Set the read_source field in the new record](table.put(in=`obs`, at="read_source", value=True))**. 2. `kind` == stderr - **err = > json.get value=`obs` key="stderr"** - **tail = > text_tail_lines text=`err` max_lines=80 max_chars=6000** - **obs = table.put in=`obs` at="stderr_tail" value=`tail`** - **obs = table.put in=`obs` at="read_stderr" value=True** + We retain **`err` = [Read the stderr field](json.get(value=`obs`, key="stderr"))**. + We retain **`tail` = [Text tail lines](text_tail_lines(text=`err`, max_lines=80, max_chars=6000))**. + We retain **`obs` = [Set the stderr_tail field in the new record](table.put(in=`obs`, at="stderr_tail", value=`tail`))**. + We retain **`obs` = [Set the read_stderr field in the new record](table.put(in=`obs`, at="read_stderr", value=True))**. 3. `kind` == stdout - **out = > json.get value=`obs` key="stdout"** - **tail = > text_tail_lines text=`out` max_lines=80 max_chars=6000** - **obs = table.put in=`obs` at="stdout_tail" value=`tail`** - **obs = table.put in=`obs` at="read_stdout" value=True** + We retain **`out` = [Read the stdout field](json.get(value=`obs`, key="stdout"))**. + We retain **`tail` = [Text tail lines](text_tail_lines(text=`out`, max_lines=80, max_chars=6000))**. + We retain **`obs` = [Set the stdout_tail field in the new record](table.put(in=`obs`, at="stdout_tail", value=`tail`))**. + We retain **`obs` = [Set the read_stdout field in the new record](table.put(in=`obs`, at="read_stdout", value=True))**. 4. `kind` == slots - **slots = > json.get value=`obs` key="slots"** - **obs = table.put in=`obs` at="slots_detail" value=`slots`** - **obs = table.put in=`obs` at="read_slots" value=True** + We retain **`slots` = [Read the slots field](json.get(value=`obs`, key="slots"))**. + We retain **`obs` = [Set the slots_detail field in the new record](table.put(in=`obs`, at="slots_detail", value=`slots`))**. + We retain **`obs` = [Set the read_slots field in the new record](table.put(in=`obs`, at="read_slots", value=True))**. 5. `kind` == skill - **brief = > skill_brief depth="deep"** - **obs = table.put in=`obs` at="skill_brief" value=`brief`** - **obs = table.put in=`obs` at="read_skill" value=True** + We retain **`brief` = [Skill brief](skill_brief(depth="deep"))**. + We retain **`obs` = [Set the skill_brief field in the new record](table.put(in=`obs`, at="skill_brief", value=`brief`))**. + We retain **`obs` = [Set the read_skill field in the new record](table.put(in=`obs`, at="read_skill", value=True))**. 6. * **_ = 1** -*obs* +Return *obs*. --- ## compact_plan_observation - + `observation` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| observation | any | required | Tool observation or workbook result retained for the next turn | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Bounded observation for the parent prompt (actionable, short). Tolerates missing/non-map observation (empty compact) instead of `json get needs map`. Map check via stringify prefix `{` — never hard-get on None / bare text / list. | + +Use `observation` as the inputs for this operation. Bounded observation for the parent prompt (actionable, short). Tolerates missing/non-map observation (empty compact) instead of `json get needs map`. Map check via stringify prefix `{` — never hard-get on None / bare text / list. -**obs_path = None** -**obs_code = None** -**obs_val = None** -**obs_slots = None** -**obs_src = None** -**obs_stdout = None** -**obs_stderr = None** -**obs_s = > json.stringify value=`observation`** -**obs_map = > text.starts_with text=`obs_s` prefix="{"** +A child observation can contain a full workbook, process output and slot values. Sending all of that on every parent turn wastes context and can obscure the next decision. This projection retains the execution path and exit status, records source size, and carries selected excerpts or tails for repair. It returns a new record; it neither edits the workbook nor changes the original observation. + +The source marker check is a structural hint: it looks for worker.step in the source text. That hint is not evidence that a model ran or that its answer is correct. Likewise, an exit status of zero is useful execution evidence, but a parent still needs a returned value and task-specific verification before DONE. The compact record's note communicates that decision protocol without granting the helper authority to declare success. + +When an observation already supplies a source excerpt or an output tail, that bounded view is reused. Otherwise the existing excerpt and tail helpers derive it from the full field. This keeps the same repair window available without transporting every log line. Missing source, output or slots simply leave the corresponding optional information absent. + +The initial record test protects None, ordinary text and lists from map-only access. A compact observation is therefore usable even after a child fails before producing its usual record. Consumers should read the available status and diagnostic fields instead of assuming that absence means an empty successful result. To investigate beyond these bounds, request an explicit deeper read through the parent protocol. + +For example, a failed child may provide stderr and source but no value. Keep the diagnostic tail for repair and leave result absent; replacing the missing value with a successful placeholder would destroy that evidence. + +We retain **obs_path = None**. +We retain **obs_code = None**. +We retain **obs_val = None**. +We retain **obs_slots = None**. +We retain **obs_src = None**. +We retain **obs_stdout = None**. +We retain **obs_stderr = None**. +We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`observation`))**. +We retain **`obs_map` = [Starts with](text.starts_with(text=`obs_s`, prefix="{"))**. 1. `obs_map` - **obs_path = > json.get value=`observation` key="path"** - **obs_code = > json.get value=`observation` key="exit_code"** - **obs_val = > json.get value=`observation` key="value"** - **obs_slots = > json.get value=`observation` key="slots"** - **obs_src = > json.get value=`observation` key="source"** - **obs_stdout = > json.get value=`observation` key="stdout"** - **obs_stderr = > json.get value=`observation` key="stderr"** + We retain **`obs_path` = [Read the path field](json.get(value=`observation`, key="path"))**. + We retain **`obs_code` = [Read the exit_code field](json.get(value=`observation`, key="exit_code"))**. + We retain **`obs_val` = [Read the value field](json.get(value=`observation`, key="value"))**. + We retain **`obs_slots` = [Read the slots field](json.get(value=`observation`, key="slots"))**. + We retain **`obs_src` = [Read the source field](json.get(value=`observation`, key="source"))**. + We retain **`obs_stdout` = [Read the stdout field](json.get(value=`observation`, key="stdout"))**. + We retain **`obs_stderr` = [Read the stderr field](json.get(value=`observation`, key="stderr"))**. 2. * **_ = 1** -**src_len = 0** -**has_step = False** +We retain **src_len = 0**. +We retain **has_step = False**. 1. `obs_src` - **src_len = > len value=`obs_src`** - **step_parts = > split value=`obs_src` sep="worker.step"** - **n_step = > len value=`step_parts`** + We retain **`src_len` = [Len](len(value=`obs_src`))**. + We retain **`step_parts` = [Split](split(value=`obs_src`, sep="worker.step"))**. + We retain **`n_step` = [Len](len(value=`step_parts`))**. 1. `n_step` > 1 - **has_step = True** + We retain **has_step = True**. 2. * **_ = 1** 2. * @@ -1746,55 +2637,56 @@ Map check via stringify prefix `{` — never hard-get on None / bare text / list 1. `obs_map` 1. `obs_src` - **ex = > json.get value=`observation` key="source_excerpt"** + We retain **`ex` = [Read the source_excerpt field](json.get(value=`observation`, key="source_excerpt"))**. 1. `ex` - **compact = table.put in=`compact` at="source_excerpt" value=`ex`** + We retain **`compact` = [Set the source_excerpt field in the new record](table.put(in=`compact`, at="source_excerpt", value=`ex`))**. 2. * - **ex = > workbook_source_excerpt source=`obs_src`** - **compact = table.put in=`compact` at="source_excerpt" value=`ex`** + We retain **`ex` = [Workbook source excerpt](workbook_source_excerpt(source=`obs_src`))**. + We retain **`compact` = [Set the source_excerpt field in the new record](table.put(in=`compact`, at="source_excerpt", value=`ex`))**. 2. * **_ = 1** 1. `obs_stderr` - **tail = > json.get value=`observation` key="stderr_tail"** + We retain **`tail` = [Read the stderr_tail field](json.get(value=`observation`, key="stderr_tail"))**. 1. `tail` - **compact = table.put in=`compact` at="stderr_tail" value=`tail`** + We retain **`compact` = [Set the stderr_tail field in the new record](table.put(in=`compact`, at="stderr_tail", value=`tail`))**. 2. * - **tail = > text_tail_lines text=`obs_stderr`** - **compact = table.put in=`compact` at="stderr_tail" value=`tail`** + We retain **`tail` = [Text tail lines](text_tail_lines(text=`obs_stderr`))**. + We retain **`compact` = [Set the stderr_tail field in the new record](table.put(in=`compact`, at="stderr_tail", value=`tail`))**. 2. * **_ = 1** 1. `obs_stdout` - **tail = > json.get value=`observation` key="stdout_tail"** + We retain **`tail` = [Read the stdout_tail field](json.get(value=`observation`, key="stdout_tail"))**. 1. `tail` - **compact = table.put in=`compact` at="stdout_tail" value=`tail`** + We retain **`compact` = [Set the stdout_tail field in the new record](table.put(in=`compact`, at="stdout_tail", value=`tail`))**. 2. * - **tail = > text_tail_lines text=`obs_stdout`** - **compact = table.put in=`compact` at="stdout_tail" value=`tail`** + We retain **`tail` = [Text tail lines](text_tail_lines(text=`obs_stdout`))**. + We retain **`compact` = [Set the stdout_tail field in the new record](table.put(in=`compact`, at="stdout_tail", value=`tail`))**. 2. * **_ = 1** - **val_txt = > str value=`obs_val`** - **val_len = > len value=`val_txt`** + We retain **`val_txt` = [Str](str(value=`obs_val`))**. + We retain **`val_len` = [Len](len(value=`val_txt`))**. 1. `obs_val` - **compact = table.put in=`compact` at="has_value" value=True** - **compact = table.put in=`compact` at="value_len" value=`val_len`** + We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=True))**. + We retain **`compact` = [Set the value_len field in the new record](table.put(in=`compact`, at="value_len", value=`val_len`))**. 1. `val_len` > 200 - **preview = > text_head_lines text=`val_txt` max_lines=4 max_chars=200** - **compact = table.put in=`compact` at="value_preview" value=`preview`** + We retain **`preview` = [Text head lines](text_head_lines(text=`val_txt`, max_lines=4, max_chars=200))**. + We retain **`compact` = [Set the value_preview field in the new record](table.put(in=`compact`, at="value_preview", value=`preview`))**. 2. * - **compact = table.put in=`compact` at="value" value=`obs_val`** + We retain **`compact` = [Set the value field in the new record](table.put(in=`compact`, at="value", value=`obs_val`))**. 2. * - **compact = table.put in=`compact` at="has_value" value=False** + We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=False))**. - **slots_brief = > table.empty_list** + We retain **`slots_brief` = [Empty list](table.empty_list())**. 1. `obs_slots` - [slot](遍历 `obs_slots` 为 `slot`) - **sk = > json.get value=`slot` key="key"** - **sl = > json.get value=`slot` key="line"** - **sb = > json.get value=`slot` key="body"** - **sb_txt = > str value=`sb`** - **sb_len = > len value=`sb_txt`** + We retain **`sk` = [Read the key field](json.get(value=`slot`, key="key"))**. + We retain **`sl` = [Read the line field](json.get(value=`slot`, key="line"))**. + We retain **`sb` = [Read the body field](json.get(value=`slot`, key="body"))**. + We retain **`sb_txt` = [Str](str(value=`sb`))**. + We retain **`sb_len` = [Len](len(value=`sb_txt`))**. + `brief` = | key | line | body_len | @@ -1802,92 +2694,114 @@ Map check via stringify prefix `{` — never hard-get on None / bare text / list | `sk` | `sl` | `sb_len` | 1. `sk` == error - **prev = > text_head_lines text=`sb_txt` max_lines=8 max_chars=400** - **brief = table.put in=`brief` at="body_preview" value=`prev`** + We retain **`prev` = [Text head lines](text_head_lines(text=`sb_txt`, max_lines=8, max_chars=400))**. + We retain **`brief` = [Set the body_preview field in the new record](table.put(in=`brief`, at="body_preview", value=`prev`))**. 2. * **_ = 1** - **slots_brief = > table.append list=`slots_brief` item=`brief`** + We retain **`slots_brief` = [Append this item to the new list](table.append(list=`slots_brief`, item=`brief`))**. 2. * **_ = 1** - **compact = table.put in=`compact` at="slots" value=`slots_brief`** - **detail = > json.get value=`observation` key="slots_detail"** + We retain **`compact` = [Set the slots field in the new record](table.put(in=`compact`, at="slots", value=`slots_brief`))**. + We retain **`detail` = [Read the slots_detail field](json.get(value=`observation`, key="slots_detail"))**. 1. `detail` - **compact = table.put in=`compact` at="slots_detail" value=`detail`** + We retain **`compact` = [Set the slots_detail field in the new record](table.put(in=`compact`, at="slots_detail", value=`detail`))**. 2. * **_ = 1** - **tool_result = > json.get value=`observation` key="tool_result"** + We retain **`tool_result` = [Read the tool_result field](json.get(value=`observation`, key="tool_result"))**. 1. `tool_result` - **tr = > str value=`tool_result`** - **tr = > text_head_lines text=`tr` max_lines=40 max_chars=3000** - **compact = table.put in=`compact` at="tool_result" value=`tr`** + We retain **`tr` = [Str](str(value=`tool_result`))**. + We retain **`tr` = [Text head lines](text_head_lines(text=`tr`, max_lines=40, max_chars=3000))**. + We retain **`compact` = [Set the tool_result field in the new record](table.put(in=`compact`, at="tool_result", value=`tr`))**. 2. * **_ = 1** - **last_error = > json.get value=`observation` key="last_error"** + We retain **`last_error` = [Read the last_error field](json.get(value=`observation`, key="last_error"))**. 1. `last_error` - **err_txt = > str value=`last_error`** - **err_len = > len value=`err_txt`** + We retain **`err_txt` = [Str](str(value=`last_error`))**. + We retain **`err_len` = [Len](len(value=`err_txt`))**. 1. `err_len` > 200 - **prev = > text_head_lines text=`err_txt` max_lines=8 max_chars=400** - **compact = table.put in=`compact` at="last_error_preview" value=`prev`** - **compact = table.put in=`compact` at="last_error_len" value=`err_len`** + We retain **`prev` = [Text head lines](text_head_lines(text=`err_txt`, max_lines=8, max_chars=400))**. + We retain **`compact` = [Set the last_error_preview field in the new record](table.put(in=`compact`, at="last_error_preview", value=`prev`))**. + We retain **`compact` = [Set the last_error_len field in the new record](table.put(in=`compact`, at="last_error_len", value=`err_len`))**. 2. * - **compact = table.put in=`compact` at="last_error" value=`last_error`** + We retain **`compact` = [Set the last_error field in the new record](table.put(in=`compact`, at="last_error", value=`last_error`))**. 2. * **_ = 1** 2. * - **compact = table.put in=`compact` at="has_value" value=False** - **empty_slots = > table.empty_list** - **compact = table.put in=`compact` at="slots" value=`empty_slots`** + We retain **`compact` = [Set the has_value field in the new record](table.put(in=`compact`, at="has_value", value=False))**. + We retain **`empty_slots` = [Empty list](table.empty_list())**. + We retain **`compact` = [Set the slots field in the new record](table.put(in=`compact`, at="slots", value=`empty_slots`))**. -*compact* +Return *compact*. --- ## extract_plan_decision - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继续` / `运行`). First matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply). | + +Use `reply` as the inputs for this operation. Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继续` / `运行`). First matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply). -**esc = > json.parse text={"nl":"\n","fw":":"}** -**nl = > json.get value=`esc` key="nl"** -**fw = > json.get value=`esc` key="fw"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**found = None** +The following record names each literal field without a JSON construction chain. + +A decision is extracted from the model's protocol text and returned to the orchestration loop. It is not executed here. The loop must still distinguish RUN, CONTINUE and DONE and verify whether the workbook has a usable result. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "fw" | ":" | +| 2 | "nl" | "\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **found = None**. - [line](遍历 `lines` 为 `line`) 1. `found` **_ = 1** 2. * - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == DECISION - **found = rest** + We retain **found = rest**. 2. `head` == 决定 - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * - **parts = > split value=`t` sep=`fw`** - **n = > len value=`parts`** + We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == 决定 - **found = rest** + We retain **found = rest**. 2. `head` == DECISION - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * @@ -1895,382 +2809,602 @@ First matching DECISION / 决定 line wins (ignore later conflicting decisions i 1. `found` Take the first token only (`DECISION: RUN please` → RUN). - **toks = > split value=`found` sep=" "** - **found = > at value=`toks` index=0** - **found = > trim value=`found`** + We retain **`toks` = [Split](split(value=`found`, sep=" "))**. + We retain **`found` = [At](at(value=`toks`, index=0))**. + We retain **`found` = [Trim](trim(value=`found`))**. 2. * **_ = 1** 1. `found` == DONE - *"DONE"* + Return *"DONE"*. 2. `found` == CONTINUE - *"CONTINUE"* + Return *"CONTINUE"*. 3. `found` == RUN - *"RUN"* + Return *"RUN"*. 4. `found` == REUSE - *"REUSE"* + Return *"REUSE"*. 5. `found` == NEW - *"NEW"* + Return *"NEW"*. 6. `found` == 完成 - *"DONE"* + Return *"DONE"*. 7. `found` == 继续 - *"CONTINUE"* + Return *"CONTINUE"*. 8. `found` == 运行 - *"RUN"* + Return *"RUN"*. 9. `found` == 复用 - *"REUSE"* + Return *"REUSE"*. 10. `found` == 新建 - *"NEW"* + Return *"NEW"*. 11. `found` == PATCH Models sometimes invent `DECISION: PATCH` — treat as CONTINUE. - *"CONTINUE"* + Return *"CONTINUE"*. 12. * If the reply carries a FIND/REPLACE block, treat unknown labels as CONTINUE. - **has_find = > split value=`text` sep="<<<"** - **n_find = > len value=`has_find`** + We retain **`has_find` = [Split](split(value=`text`, sep="<<<"))**. + We retain **`n_find` = [Len](len(value=`has_find`))**. 1. `n_find` > 1 - *"CONTINUE"* + Return *"CONTINUE"*. 2. * - *found* + Return *found*. --- ## extract_soft_match_slug - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse `SLUG: …` / `标识:…` after a soft-match REUSE decision. | + +Use `reply` as the inputs for this operation. Parse `SLUG: …` / `标识:…` after a soft-match REUSE decision. -**esc = > json.parse text={"nl":"\n","fw":":"}** -**nl = > json.get value=`esc` key="nl"** -**fw = > json.get value=`esc` key="fw"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**found = None** +The following record names each literal field without a JSON construction chain. + +The returned slug identifies a candidate from the proposed knowledge entries. It is a lookup result rather than a filesystem authorization. The later route-application stage must resolve it against the knowledge directory before any workbook is executed. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "fw" | ":" | +| 2 | "nl" | "\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **found = None**. - [line](遍历 `lines` 为 `line`) - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == SLUG - **found = rest** + We retain **found = rest**. 2. `head` == 标识 - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * - **parts = > split value=`t` sep=`fw`** - **n = > len value=`parts`** + We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == 标识 - **found = rest** + We retain **found = rest**. 2. `head` == SLUG - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * **_ = 1** -*found* +Return *found*. --- ## build_soft_match_prompt - + `goal` - + `tasks` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| goal | any | required | Human task goal represented by this operation | +| tasks | any | required | Ordered task records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical `score` (prefer higher). `list_tasks` rows may also carry `description` / `status` / `llm_free`. | + +Use `goal`, `tasks` as the inputs for this operation. Short parent prompt: REUSE+SLUG or NEW only. Candidates may include lexical `score` (prefer higher). `list_tasks` rows may also carry `description` / `status` / `llm_free`. -**esc = > json.parse text={"a":"\n\n--- goal ---\n","b":"\n\n--- candidate tasks (slug | title | meta) ---\n","c":"\n\n--- how to act ---\nExact reuse miss; candidates are ranked by local n-gram score when present. Prefer higher scores and llm_free=true skills. Reply with ONE protocol only:\nDECISION: REUSE\nSLUG: \nor\nDECISION: NEW\nNo other prose.\n","nl":"\n","sep":" | ","sp":"score=","st":"status=","lf":"llm_free="}** -**a = > json.get value=`esc` key="a"** -**b = > json.get value=`esc` key="b"** -**c = > json.get value=`esc` key="c"** -**nl = > json.get value=`esc` key="nl"** -**sep = > json.get value=`esc` key="sep"** -**sp = > json.get value=`esc` key="sp"** -**st = > json.get value=`esc` key="st"** -**lf = > json.get value=`esc` key="lf"** -**lines = > table.empty_list** +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +Candidate rows are evidence for a reuse choice, not executable instructions. Their slugs identify existing knowledge; titles and optional metadata help the parent compare task fit. A lexical score measures local text similarity, while llm_free describes whether the selected skill can run without a parent model. Neither alone establishes that its answer satisfies this new goal. + +The output protocol deliberately permits only REUSE with a listed slug or NEW. The caller parses that decision and applies the selected resource through the ordinary route path. Building this prompt does not execute a candidate, alter its status, or add model-generated names to the tool whitelist. + +`_literal_esc_c_lines` = + +| line | +|---| +| "" | +| "" | +| "--- how to act ---" | +| "Exact reuse miss; candidates are ranked by local n-gram score when present. Prefer higher scores and llm_free=true skills. Reply with ONE protocol only:" | +| "DECISION: REUSE" | +| "SLUG: " | +| "or" | +| "DECISION: NEW" | +| "No other prose." | +| "" | + +Join exactly those lines into **_literal_esc_c_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_c_lines`, sep="\n"))**. + +The following record names each literal field without a JSON construction chain. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "a" | "\n\n--- goal ---\n" | +| 2 | "b" | "\n\n--- candidate tasks (slug \| title \| meta) ---\n" | +| 3 | "c" | `_literal_esc_c_text` | +| 4 | "lf" | "llm_free=" | +| 5 | "nl" | "\n" | +| 6 | "sep" | " \| " | +| 7 | "sp" | "score=" | +| 8 | "st" | "status=" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. +We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. +We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`sep` = [Read the sep field](json.get(value=`esc`, key="sep"))**. +We retain **`sp` = [Read the sp field](json.get(value=`esc`, key="sp"))**. +We retain **`st` = [Read the st field](json.get(value=`esc`, key="st"))**. +We retain **`lf` = [Read the lf field](json.get(value=`esc`, key="lf"))**. +We retain **`lines` = [Empty list](table.empty_list())**. - [t](遍历 `tasks` 为 `t`) - **slug = > json.get value=`t` key="slug"** - **title = > json.get value=`t` key="title"** - **row = slug + sep + title** - **score = > json.get value=`t` key="score"** + We retain **`slug` = [Read the slug field](json.get(value=`t`, key="slug"))**. + We retain **`title` = [Read the title field](json.get(value=`t`, key="title"))**. + We retain **row = slug + sep + title**. + We retain **`score` = [Read the score field](json.get(value=`t`, key="score"))**. 1. `score` - **row = row + sep + sp + score** + We retain **row = row + sep + sp + score**. 2. * **_ = 1** - **status = > json.get value=`t` key="status"** + We retain **`status` = [Read the status field](json.get(value=`t`, key="status"))**. 1. `status` - **row = row + sep + st + status** + We retain **row = row + sep + st + status**. 2. * **_ = 1** - **free = > json.get value=`t` key="llm_free"** + We retain **`free` = [Read the llm_free field](json.get(value=`t`, key="llm_free"))**. 1. `free` == True - **row = row + sep + lf + "true"** + We retain **row = row + sep + lf + "true"**. 2. `free` == true - **row = row + sep + lf + "true"** + We retain **row = row + sep + lf + "true"**. 3. `free` == False - **row = row + sep + lf + "false"** + We retain **row = row + sep + lf + "false"**. 4. `free` == false - **row = row + sep + lf + "false"** + We retain **row = row + sep + lf + "false"**. 5. * **_ = 1** - **desc = > json.get value=`t` key="description"** + We retain **`desc` = [Read the description field](json.get(value=`t`, key="description"))**. 1. `desc` - **row = row + sep + desc** + We retain **row = row + sep + desc**. 2. * **_ = 1** - **lines = > table.append list=`lines` item=`row`** -**catalog = > join value=`lines` sep=`nl`** -**p = "Soft-match: same task intent?"** -*p + a + goal + b + catalog + c* + We retain **`lines` = [Append this item to the new list](table.append(list=`lines`, item=`row`))**. +We retain **`catalog` = [Join](join(value=`lines`, sep=`nl`))**. +We retain **p = "Soft-match: same task intent?"**. +Return *p + a + goal + b + catalog + c*. --- ## extract_plan_summary - + `reply` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | First `SUMMARY:` / `汇总:` / `汇总:` line body, else trimmed reply. | + +Use `reply` as the inputs for this operation. First `SUMMARY:` / `汇总:` / `汇总:` line body, else trimmed reply. -**esc = > json.parse text={"nl":"\n","fw":":"}** -**nl = > json.get value=`esc` key="nl"** -**fw = > json.get value=`esc` key="fw"** -**text = > trim value=`reply`** -**lines = > split value=`text` sep=`nl`** -**found = None** +The following record names each literal field without a JSON construction chain. + +The summary is the short human-facing explanation attached to the plan result. It is kept separate from the decision so a sentence that happens to mention DONE does not itself finish a run. Source patches and tool requests are handled by their own extractors. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "fw" | ":" | +| 2 | "nl" | "\n" | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`nl` = [Read the nl field](json.get(value=`esc`, key="nl"))**. +We retain **`fw` = [Read the fw field](json.get(value=`esc`, key="fw"))**. +We retain **`text` = [Trim](trim(value=`reply`))**. +We retain **`lines` = [Split](split(value=`text`, sep=`nl`))**. +We retain **found = None**. - [line](遍历 `lines` 为 `line`) - **t = > trim value=`line`** - **parts = > split value=`t` sep=":"** - **n = > len value=`parts`** + We retain **`t` = [Trim](trim(value=`line`))**. + We retain **`parts` = [Split](split(value=`t`, sep=":"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == SUMMARY - **found = rest** + We retain **found = rest**. 2. `head` == 汇总 - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * - **parts = > split value=`t` sep=`fw`** - **n = > len value=`parts`** + We retain **`parts` = [Split](split(value=`t`, sep=`fw`))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + We retain **`head` = [At](at(value=`parts`, index=0))**. + We retain **`head` = [Trim](trim(value=`head`))**. + We retain **`rest` = [At](at(value=`parts`, index=1))**. + We retain **`rest` = [Trim](trim(value=`rest`))**. 1. `head` == 汇总 - **found = rest** + We retain **found = rest**. 2. `head` == SUMMARY - **found = rest** + We retain **found = rest**. 3. * **_ = 1** 2. * **_ = 1** 1. `found` - *found* + Return *found*. 2. * - *text* + Return *text*. --- ## build_plan_context - + `agent` - + `goal` - + `observation` - + `explore_attempt`=None - + `explore_n`=None - + `phase`=revise + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| agent | any | required | Agent configuration or receiver created by this package | +| goal | any | required | Human task goal represented by this operation | +| observation | any | required | Tool observation or workbook result retained for the next turn | +| explore_attempt | any | None | Current exploration attempt number | +| explore_n | any | None | Maximum configured exploration attempts | +| phase | any | "revise" | Named execution phase | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parent Plan-and-Move prompt. Short protocol only — no long monologues. | + +Use `agent`, `goal`, `observation`, `explore_attempt`=None, `explore_n`=None, `phase`="revise" as the inputs for this operation. Parent Plan-and-Move prompt. Short protocol only — no long monologues. -**standing = > json.get value=`agent` key="standing"** -1. `standing` - **up = standing** -2. * - **up = None** +The parent receives a decision surface rather than the whole child process. Its goal is serialized as data, standing instructions supply the agent role, and a compact observation conveys the last execution outcome. If the observation carries a skill brief, that already selected context is reused; otherwise the normal budgeted skill brief is loaded. Source remains authoritative even when an evidence adapter contributes useful facts. -**skill_from_obs = None** -**obs_probe = > json.stringify value=`observation`** -**obs_is_map = > text.starts_with text=`obs_probe` prefix="{"** +There are two instruction branches. Before the first run, the decompose phase checks whether the generated skeleton can be executed as written. It may request evidence, propose a short patch, or choose RUN. During revision, the parent sees the child's outcome and chooses whether to repair or finish. A successful child with a usable value can lead to DONE; the mere presence of a worker call is not a reason to keep rewriting the workbook. + +The protocol text is stored in visible line tables. Literal examples of CALL, READ, DECISION and patch delimiters are instructions for a later model reply, not commands executed while assembling the prompt. Their exact line breaks matter to the corresponding extractors. Do not replace this representation with a second workflow language, or hide a new tool behind a descriptive label without wiring its implementation. + +The parent-tools section explains the restricted workbook, source and evidence actions. An explicit library CALL uses the dispatcher's whitelist and argument parsing. READ requests deepen context through the caller's budget. Scratch tool creation returns to the ordinary source-and-tool path; a sentence in the prompt cannot bypass filesystem roots, runtime effects or ToolSpec preparation. + +Exploration metadata tells the parent which attempt it is inspecting and how many variants the surrounding planner configured. It does not create a loop here. This function only returns text; the plan loop owns round accounting, child execution, patch application and writeback. When debugging a wrong decision, inspect the returned sections alongside the actual observation and call site before changing model instructions. + +To extend a parent's capabilities, first implement a real dispatcher branch with its input contract and tests. Then update the visible tool instructions. Changing this prompt alone only changes what the model sees and cannot establish a callable implementation. + +We retain **`standing` = [Read the standing field](json.get(value=`agent`, key="standing"))**. +1. `standing` + We retain **up = standing**. +2. * + We retain **up = None**. + +We retain **skill_from_obs = None**. +We retain **`obs_probe` = [Encode the structured value as JSON text](json.stringify(value=`observation`))**. +We retain **`obs_is_map` = [Starts with](text.starts_with(text=`obs_probe`, prefix="{"))**. 1. `obs_is_map` - **skill_from_obs = > json.get value=`observation` key="skill_brief"** + We retain **`skill_from_obs` = [Read the skill_brief field](json.get(value=`observation`, key="skill_brief"))**. 2. * **_ = 1** 1. `skill_from_obs` - **skill = skill_from_obs** + We retain **skill = skill_from_obs**. 2. * - **skill = > skill_brief** -**compact = > compact_plan_observation observation=`observation`** -**obs_s = > json.stringify value=`compact`** -**goal_s = > json.stringify value=`goal`** -**esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:corpus_search | mcp_list_tools | mcp_call (ARGS:{…}; evidence only — workbook authority)\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots | skill\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\n4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses nested import: map (llm/agent/json…).\nPATCH must use triple-angle blocks only:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\nDo not use \u0060\u0060\u0060find, \u0060\u0060\u0060replace, or *** Begin Patch ***.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already nested import: (llm/agent/…).\n2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog / corpus_search / mcp_call.\n3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nPATCH must use <<< FIND === REPLACE >>> only (no \u0060\u0060\u0060find / Begin Patch).\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","f":"\n\n--- explore ---\n"}** -**a = > json.get value=`esc` key="a"** -**b = > json.get value=`esc` key="b"** -**c = > json.get value=`esc` key="c"** -**d = > json.get value=`esc` key="d"** -**tools = > json.get value=`esc` key="tools"** -**f = > json.get value=`esc` key="f"** + We retain **`skill` = [Skill brief](skill_brief())**. +We retain **`compact` = [Compact plan observation](compact_plan_observation(observation=`observation`))**. +We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`compact`))**. +We retain **`goal_s` = [Encode the structured value as JSON text](json.stringify(value=`goal`))**. +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_e_dec_lines` = + +| line | +|---| +| "" | +| "" | +| "--- how to act ---" | +| "PRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line." | +| "1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already nested import: (llm/agent/…)." | +| "2) Need evidence → READ:source or READ:skill or CALL:workbook_read / lib_catalog / corpus_search / mcp_call." | +| "3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines)." | +| "4) Fixed answer without LLM → PATCH to return, then RUN or DONE." | +| "PATCH must use <<< FIND === REPLACE >>> only (no \x60\x60\x60find / Begin Patch)." | +| "Protocols:" | +| "CALL:name" | +| "READ:kind" | +| "DECISION: RUN" | +| "DECISION: DONE" | +| "SUMMARY: one line" | +| "DECISION: CONTINUE" | +| "" | + +Join exactly those lines into **_literal_esc_e_dec_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_e_dec_lines`, sep="\n"))**. + +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_e_rev_lines` = + +| line | +|---| +| "" | +| "" | +| "--- how to act ---" | +| "Plan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line." | +| "1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step." | +| "2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted)." | +| "3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE." | +| "4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses nested import: map (llm/agent/json…)." | +| "PATCH must use triple-angle blocks only:" | +| "<<<" | +| "FIND" | +| "" | +| "===" | +| "REPLACE" | +| "" | +| ">>>" | +| "Do not use \x60\x60\x60find, \x60\x60\x60replace, or *** Begin Patch ***." | +| "Protocols:" | +| "CALL:name" | +| "READ:kind" | +| "DECISION: DONE" | +| "SUMMARY: one line" | +| "DECISION: CONTINUE" | +| "" | + +Join exactly those lines into **_literal_esc_e_rev_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_e_rev_lines`, sep="\n"))**. + +Keep this text as ordered lines so its instructions and blank-line boundaries can be read directly. + +`_literal_esc_tools_lines` = + +| line | +|---| +| "" | +| "" | +| "--- parent tools ---" | +| "CALL:workbook_read \| workbook_excerpt \| lib_catalog \| scratch_tool_write" | +| "CALL:corpus_search \| mcp_list_tools \| mcp_call (ARGS:{…}; evidence only — workbook authority)" | +| "CALL:lib.fs.read_text\|exists\|list_dir \| lib.json.parse\|stringify \| lib.sys.cwd (+ ARGS:{json})" | +| "READ:source \| stderr \| stdout \| slots \| skill" | +| "Create tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body." | +| "" | + +Join exactly those lines into **_literal_esc_tools_text = [Retain the original newline boundaries](text.str_join(xs=`_literal_esc_tools_lines`, sep="\n"))**. + +The following record names each literal field without a JSON construction chain. + +`_literal_esc_fields` = + +| @ | key | value | +|---|---|---| +| 1 | "a" | "\n\n--- standing ---\n" | +| 2 | "b" | "\n\n--- goal ---\n" | +| 3 | "c" | "\n\n--- observation ---\n" | +| 4 | "d" | "\n\n--- skill brief ---\n" | +| 5 | "e_dec" | `_literal_esc_e_dec_text` | +| 6 | "e_rev" | `_literal_esc_e_rev_text` | +| 7 | "f" | "\n\n--- explore ---\n" | +| 8 | "tools" | `_literal_esc_tools_text` | + +We build **esc = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_esc_fields`))**. + + +We retain **`a` = [Read the a field](json.get(value=`esc`, key="a"))**. +We retain **`b` = [Read the b field](json.get(value=`esc`, key="b"))**. +We retain **`c` = [Read the c field](json.get(value=`esc`, key="c"))**. +We retain **`d` = [Read the d field](json.get(value=`esc`, key="d"))**. +We retain **`tools` = [Read the tools field](json.get(value=`esc`, key="tools"))**. +We retain **`f` = [Read the f field](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."** + We retain **`e` = [Read the e_dec field](json.get(value=`esc`, key="e_dec"))**. + We retain **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 = p + a + up + b + goal_s + c + obs_s + tools + d + skill + e** + We retain **`e` = [Read the e_rev field](json.get(value=`esc`, key="e_rev"))**. + We retain **p = "Plan-and-Move: revise after child run."**. +We retain **p = p + a + up + b + goal_s + c + obs_s + tools + d + skill + e**. 1. `explore_attempt` - **p = p + f** - **p = p + "Attempt"** - **p = p + explore_attempt** - **p = p + "of"** - **p = p + explore_n** - **p = p + ". Different path; prefer code when fixed."** + We retain **p = p + f**. + We retain **p = p + "Attempt"**. + We retain **p = p + explore_attempt**. + We retain **p = p + "of"**. + We retain **p = p + explore_n**. + We retain **p = p + ". Different path; prefer code when fixed."**. 2. * **_ = 1** -*p* +Return *p*. --- ## plan_llm_act_loop - + `agent` - + `goal` - + `path` - + `observation` - + `phase`=revise - + `explore_attempt`=None - + `explore_n`=None - + `stream`=False - + `echo`=False - + `events` - + `max_acts`=6 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| agent | any | required | Agent configuration or receiver created by this package | +| goal | any | required | Human task goal represented by this operation | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| observation | any | required | Tool observation or workbook result retained for the next turn | +| phase | any | "revise" | Named execution phase | +| explore_attempt | any | None | Current exploration attempt number | +| explore_n | any | None | Maximum configured exploration attempts | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| events | any | required | Ordered semantic or provider stream-event records | +| max_acts | any | 6 | Maximum model/tool actions for this planning loop | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,events,llm_calls,tokens}`. | + +Use `agent`, `goal`, `path`, `observation`, `phase`="revise", `explore_attempt`=None, `explore_n`=None, `stream`=False, `echo`=False, `events`, `max_acts`=6 as the inputs for this operation. LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,events,llm_calls,tokens}`. -**model = > json.get value=`agent` key="model"** -**last_obs = observation** -**left = max_acts** -**decision = None** -**last_reply = None** -**evs_all = events** -**llm_calls = 0** -**tokens = 0** +Each model turn may answer directly, request context, or ask for one allowed parent action. The loop records the resulting observation and rebuilds context before asking again. Its bounded iteration prevents an endless READ or CALL exchange; it does not automatically authorize a tool mentioned by the model. Transport errors and exhausted budgets remain visible to the enclosing planner. -**transport_err = None** +We retain **`model` = [Read the model field](json.get(value=`agent`, key="model"))**. +We retain **last_obs = observation**. +We retain **left = max_acts**. +We retain **decision = None**. +We retain **last_reply = None**. +We retain **evs_all = events**. +We retain **llm_calls = 0**. +We retain **tokens = 0**. + +We retain **transport_err = None**. - `left` > 0 1. `decision` - **left = 0** + We retain **left = 0**. 2. `transport_err` - **left = 0** + We retain **left = 0**. 3. * - **ctx = > build_plan_context agent=`agent` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=`phase`** + We retain **`ctx` = [Build plan context](build_plan_context(agent=`agent`, goal=`goal`, observation=`last_obs`, explore_attempt=`explore_attempt`, explore_n=`explore_n`, phase=`phase`))**. Plan protocol streams as `stream_kind=plan` (process trail). Answer tokens still come from workbook `worker.step stream=True` (`stream_kind=delta`). 1. `stream` - **turn = > model_turn model=`model` prompt=`ctx` stream=True echo=`echo` stream_kind="plan"** + We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=True, echo=`echo`, stream_kind="plan"))**. 2. * - **turn = > model_turn model=`model` prompt=`ctx` stream=False echo=`echo`** - **turn_s = > json.stringify value=`turn`** - **turn_map = > text.starts_with text=`turn_s` prefix="{"** - **terr = None** - **last_reply = ""** + We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=False, echo=`echo`))**. + We retain **`turn_s` = [Encode the structured value as JSON text](json.stringify(value=`turn`))**. + We retain **`turn_map` = [Starts with](text.starts_with(text=`turn_s`, prefix="{"))**. + We retain **terr = None**. + We retain **last_reply = ""**. 1. not `turn_map` - **transport_err = "model_turn_not_map"** - **left = 0** + We retain **transport_err = "model_turn_not_map"**. + We retain **left = 0**. 2. * - **terr = > json.get value=`turn` key="error"** + We retain **`terr` = [Read the error field](json.get(value=`turn`, key="error"))**. 1. `terr` - **transport_err = `terr`** - **left = 0** + We retain **transport_err = `terr`**. + We retain **left = 0**. 2. * - **last_reply = > json.get value=`turn` key="text"** - **c = > json.get value=`turn` key="llm_calls"** - **t = > json.get value=`turn` key="tokens"** + We retain **`last_reply` = [Read the text field](json.get(value=`turn`, key="text"))**. + We retain **`c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. + We retain **`t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. 1. not `c` - **c = 0** + We retain **c = 0**. 2. * **_ = 1** 1. not `t` - **t = 0** + We retain **t = 0**. 2. * **_ = 1** - **llm_calls = llm_calls + c** - **tokens = tokens + t** + We retain **llm_calls = llm_calls + c**. + We retain **tokens = tokens + t**. 1. `transport_err` - **decision = "TRANSPORT_ERROR"** - **last_reply = `transport_err`** - **left = 0** + We retain **decision = "TRANSPORT_ERROR"**. + We retain **last_reply = `transport_err`**. + We retain **left = 0**. 2. * 1. not `last_reply` - **last_reply = ""** + We retain **last_reply = ""**. 2. * - **last_reply = > trim value=`last_reply`** + We retain **`last_reply` = [Trim](trim(value=`last_reply`))**. Plan replies often embed CALL: inside PATCH bodies — prefer an explicit DECISION line when present so protocol exit is not stolen by a false CALL. - **dec_line = > extract_plan_decision reply=`last_reply`** - **kind = "unknown"** - **name = None** + We retain **`dec_line` = [Extract plan decision](extract_plan_decision(reply=`last_reply`))**. + We retain **kind = "unknown"**. + We retain **name = None**. 1. `dec_line` - **kind = "decision"** - **name = `dec_line`** + We retain **kind = "decision"**. + We retain **name = `dec_line`**. 2. * - **act = > extract_plan_act reply=`last_reply`** - **act_s = > json.stringify value=`act`** - **act_map = > text.starts_with text=`act_s` prefix="{"** + We retain **`act` = [Extract plan act](extract_plan_act(reply=`last_reply`))**. + We retain **`act_s` = [Encode the structured value as JSON text](json.stringify(value=`act`))**. + We retain **`act_map` = [Starts with](text.starts_with(text=`act_s`, prefix="{"))**. 1. `act_map` - **kind = > json.get value=`act` key="kind"** - **name = > json.get value=`act` key="name"** + We retain **`kind` = [Read the kind field](json.get(value=`act`, key="kind"))**. + We retain **`name` = [Read the name field](json.get(value=`act`, key="name"))**. 2. * **_ = 1** Live act marker so the UI never goes silent between plan tokens and the next step. 1. `stream` + `act_ev` = | type | kind | name | |------|------|------| | plan_act | `kind` | `name` | - > sys.stream_publish event=`act_ev` + We **[Stream publish](sys.stream_publish(event=`act_ev`))**. 2. * **_ = 1** 1. `kind` == call - **evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="call" stream=`stream`** - **tool_out = > run_parent_tool name=`name` path=`path` observation=`last_obs` reply=`last_reply`** - **brief = > tool_result_brief value=`tool_out`** - **evs_all = > plan_append_tool events=`evs_all` type="tool_end" name=`name` kind="call" result=`brief` stream=`stream`** - **obs_s = > json.stringify value=`last_obs`** - **obs_map = > text.starts_with text=`obs_s` prefix="{"** + We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_start", name=`name`, kind="call", stream=`stream`))**. + We retain **`tool_out` = [Run parent tool](run_parent_tool(name=`name`, path=`path`, observation=`last_obs`, reply=`last_reply`))**. + We retain **`brief` = [Tool result brief](tool_result_brief(value=`tool_out`))**. + We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_end", name=`name`, kind="call", result=`brief`, stream=`stream`))**. + We retain **`obs_s` = [Encode the structured value as JSON text](json.stringify(value=`last_obs`))**. + We retain **`obs_map` = [Starts with](text.starts_with(text=`obs_s`, prefix="{"))**. 1. `obs_map` - **last_obs = table.put in=`last_obs` at="tool_result" value=`tool_out`** + We retain **`last_obs` = [Set the tool_result field in the new record](table.put(in=`last_obs`, at="tool_result", value=`tool_out`))**. 2. * **_ = 1** - **left = left - 1** + We retain **left = left - 1**. 2. `kind` == read - **evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="read" stream=`stream`** - **last_obs = > plan_read_deepen observation=`last_obs` kind=`name` path=`path`** - **brief = > tool_result_brief value=`last_obs`** - **evs_all = > plan_append_tool events=`evs_all` type="tool_end" name=`name` kind="read" result=`brief` stream=`stream`** - **left = left - 1** + We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_start", name=`name`, kind="read", stream=`stream`))**. + We retain **`last_obs` = [Plan read deepen](plan_read_deepen(observation=`last_obs`, kind=`name`, path=`path`))**. + We retain **`brief` = [Tool result brief](tool_result_brief(value=`last_obs`))**. + We retain **`evs_all` = [Plan append tool](plan_append_tool(events=`evs_all`, type="tool_end", name=`name`, kind="read", result=`brief`, stream=`stream`))**. + We retain **left = left - 1**. 3. `kind` == decision - **decision = name** - **evs_all = > plan_append_decision events=`evs_all` decision=`decision` stream=`stream`** - **left = 0** + We retain **decision = name**. + We retain **`evs_all` = [Plan append decision](plan_append_decision(events=`evs_all`, decision=`decision`, stream=`stream`))**. + We retain **left = 0**. 4. * - **decision = "unknown"** - **left = 0** + We retain **decision = "unknown"**. + We retain **left = 0**. `out` = @@ -2279,86 +3413,124 @@ LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,event | `decision` | `last_reply` | `last_obs` | `evs_all` | `llm_calls` | `tokens` | 1. `transport_err` - **out = table.put in=`out` at="error" value=`transport_err`** + We retain **`out` = [Set the error field in the new record](table.put(in=`out`, at="error", value=`transport_err`))**. 2. * **_ = 1** -*out* +Return *out*. --- ## plan_echo_decompose - + `workbook` - + `stream`=False - + `echo`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| workbook | any | required | Workbook path or structured workbook reference | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Pre-run parent decompose marker. With `stream=True`, publish `{type:decompose}` so view is not silent before the first child. | + +Use `workbook`, `stream`=False, `echo`=False as the inputs for this operation. Pre-run parent decompose marker. With `stream=True`, publish `{type:decompose}` so view is not silent before the first child. 1. `stream` + `ev` = | type | workbook | |------|----------| | decompose | `workbook` | - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 1. `echo` - > print text=plan:decompose + We **[Print the prepared message](print(text="plan:decompose"))**. 2. * **_ = 1** - *ev* + Return *ev*. 2. * - **** + Return *None*. ## plan_echo_await - + `round` - + `workbook` - + `stream`=False - + `echo`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| round | any | required | Current planning round number | +| workbook | any | required | Workbook path or structured workbook reference | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Marker before `await_workbook`. With `stream=True`, publish `{type:await,round,workbook}` so the Stream panel shows progress while the quiet child runs (TTY `echo` optional). | + +Use `round`, `workbook`, `stream`=False, `echo`=False as the inputs for this operation. Marker before `await_workbook`. With `stream=True`, publish `{type:await,round,workbook}` so the Stream panel shows progress while the quiet child runs (TTY `echo` optional). 1. `stream` + `ev` = | type | round | workbook | |------|-------|----------| | await | `round` | `workbook` | - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 1. `echo` - > print text=plan:await - > print text=`round` + We **[Print the prepared message](print(text="plan:await"))**. + We **[Print the prepared message](print(text=`round`))**. 2. * **_ = 1** - *ev* + Return *ev*. 2. * - **** + Return *None*. ## workbook_has_worker_step - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | True when source still contains `worker.step` or `.单步`. | + +Use `path` as the inputs for this operation. True when source still contains `worker.step` or `.单步`. -**src = > fs.read_text path=`path`** -**a = > split value=`src` sep="worker.step"** -**na = > len value=`a`** -**b = > split value=`src` sep=".单步"** -**nb = > len value=`b`** +We retain **`src` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. +We retain **`a` = [Split](split(value=`src`, sep="worker.step"))**. +We retain **`na` = [Len](len(value=`a`))**. +We retain **`b` = [Split](split(value=`src`, sep=".单步"))**. +We retain **`nb` = [Len](len(value=`b`))**. 1. `na` > 1 - *1* + Return *1*. 2. `nb` > 1 - *1* + Return *1*. 3. * - *0* + Return *0*. ## plan_append_round - + `events` - + `round` - + `workbook` - + `exit_code` - + `result`=None - + `stream`=False - + `echo`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | +| round | any | required | Current planning round number | +| workbook | any | required | Workbook path or structured workbook reference | +| exit_code | any | required | Child process or tool exit status | +| result | any | None | Structured result from the preceding operation | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Always append a `round` event (child workbook finished) for audit / view. Optional `result` is the child `# main` return. SSE + optional TTY `plan:round` only when `stream` / `echo`. | + +Use `events`, `round`, `workbook`, `exit_code`, `result`=None, `stream`=False, `echo`=False as the inputs for this operation. Always append a `round` event (child workbook finished) for audit / view. Optional `result` is the child `# main` return. SSE + optional TTY `plan:round` only when `stream` / `echo`. @@ -2369,26 +3541,35 @@ Always append a `round` event (child workbook finished) for audit / view. Option | round | `round` | `workbook` | `exit_code` | 1. `result` - **ev = table.put in=`ev` at="result" value=`result`** + We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. 2. * **_ = 1** -**events = > table.append list=`events` item=`ev`** +We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 1. `stream` - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 2. * **_ = 1** 1. `echo` - > print text=plan:round + We **[Print the prepared message](print(text="plan:round"))**. 2. * **_ = 1** -*events* +Return *events*. ## plan_append_decision - + `events` - + `decision` - + `stream`=False - + `summary`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | +| decision | any | required | Structured planning decision | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| summary | any | None | Summary text or record from the preceding phase | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Always append a `decision` event. SSE publish only when `stream=True`. | + +Use `events`, `decision`, `stream`=False, `summary`=None as the inputs for this operation. Always append a `decision` event. SSE publish only when `stream=True`. @@ -2399,90 +3580,118 @@ Always append a `decision` event. SSE publish only when `stream=True`. | decision | `decision` | 1. `summary` - **ev = table.put in=`ev` at="summary" value=`summary`** + We retain **`ev` = [Set the summary field in the new record](table.put(in=`ev`, at="summary", value=`summary`))**. 2. * **_ = 1** -**events = > table.append list=`events` item=`ev`** +We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 1. `stream` - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 2. * **_ = 1** -*events* +Return *events*. ## plan_merge_deltas - + `events` - + `from` - + `stream`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | +| from | any | required | Source value of the transformation | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Bubble parent `complete stream=True` reasoning/deltas (and errors) into the plan event list. Skip nested `done` so plan owns the final `done`. Always merge into `events` when present; `stream` reserved for callers that also SSE-publish upstream. | + +Use `events`, `from`, `stream`=False as the inputs for this operation. Bubble parent `complete stream=True` reasoning/deltas (and errors) into the plan event list. Skip nested `done` so plan owns the final `done`. Always merge into `events` when present; `stream` reserved for callers that also SSE-publish upstream. - [ev](遍历 `from` 为 `ev`) - **t = > json.get value=`ev` key="type"** + We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. 1. `t` == delta - **events = > table.append list=`events` item=`ev`** + We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 2. `t` == reasoning - **events = > table.append list=`events` item=`ev`** + We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 3. `t` == error - **events = > table.append list=`events` item=`ev`** + We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 4. * **_ = 1** -*events* +Return *events*. ## plan_finish_stream - + `out` - + `events` - + `stream`=False - + `trace`=False - + `result`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| out | any | required | Structured output accumulated by the operation | +| events | any | required | Ordered semantic or provider stream-event records | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| trace | any | False | Whether to retain the documented execution trace | +| result | any | None | Structured result from the preceding operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Always append `done` and attach `events` on the result map (process audit even when not streaming). SSE publish of `done` only when `stream=True`. Optional `trace=True` writes the event list to writeback slot `trace`. | + +Use `out`, `events`, `stream`=False, `trace`=False, `result`=None as the inputs for this operation. Always append `done` and attach `events` on the result map (process audit even when not streaming). SSE publish of `done` only when `stream=True`. Optional `trace=True` writes the event list to writeback slot `trace`. -**ev = > table.put in=None at="type" value="done"** +We retain **`ev` = [Set the type field in the new record](table.put(in=None, at="type", value="done"))**. 1. `result` - **ev = > table.put in=`ev` at="result" value=`result`** + We retain **`ev` = [Set the result field in the new record](table.put(in=`ev`, at="result", value=`result`))**. 2. * **_ = 1** 1. `events` - **events = > table.append list=`events` item=`ev`** + We retain **`events` = [Append this item to the new list](table.append(list=`events`, item=`ev`))**. 2. * - **events = > table.append list=None item=`ev`** + We retain **`events` = [Append this item to the new list](table.append(list=None, item=`ev`))**. 1. `stream` - > sys.stream_publish event=`ev` + We **[Stream publish](sys.stream_publish(event=`ev`))**. 2. * **_ = 1** 1. not `out` - **out = > table.empty_map** + We retain **`out` = [Empty map](table.empty_map())**. 2. * **_ = 1** -**out = > table.put in=`out` at="events" value=`events`** +We retain **`out` = [Set the events field in the new record](table.put(in=`out`, at="events", value=`events`))**. 1. `trace` - **body = > json.stringify value=`events`** - > wb.record value=`body` key="trace" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`events`))**. + We **[Record](wb.record(value=`body`, key="trace"))**. 2. * **_ = 1** -*out* +Return *out*. --- # agent - + `model` - + `tools` - + `standing` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | required | Model resource or provider model identifier, as required by this operation | +| tools | any | required | Explicit tool whitelist or tool-specification records | +| standing | any | required | Standing instructions supplied by the author | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load ABI v2 agent plugin once (session bag + context queries). | + +Use `model`, `tools`, `standing` as the inputs for this operation. Load ABI v2 agent plugin once (session bag + context queries). -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. + +We retain **`id` = [Alloc](agent_alloc())**. -**id = > agent_alloc** `h` = | _type | id | model | tools | @@ -2490,233 +3699,351 @@ Load ABI v2 agent plugin once (session bag + context queries). | agent | `id` | `model` | `tools` | 1. `standing` - **h = table.put in=`h` at="standing" value=`standing`** + We retain **`h` = [Set the standing field in the new record](table.put(in=`h`, at="standing", value=`standing`))**. 2. * **_ = 1** -*h* +Return *h*. ## clear_history +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Clear the plugin session bag for this agent id. | + Clear the plugin session bag for this agent id. -**id = > json.get value=`self` key="id"** -> agent_history_clear id=`id` -**** +We retain **`id` = [Read the id field](json.get(value=`self`, key="id"))**. +We **[History clear](agent_history_clear(id=`id`))**. +Return *None*. ## resolve - + `task` - + `kb_dir`=.marqdo/agent-kb - + `near_match`=True - + `near_threshold`=0.78 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| near_match | any | True | Whether to consider near-match candidates | +| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `resource` / `llm_free` / `confidence`. Plugin ABI — no core host_* calls. | + +Use `task`, `kb_dir`=".marqdo/agent-kb", `near_match`=True, `near_threshold`=0.78 as the inputs for this operation. Skill resolver (v2): exact → alias → canonical → near. Returns `mode` / `resource` / `llm_free` / `confidence`. Plugin ABI — no core host_* calls. -**tools = > json.get value=`self` key="tools"** -*> agent_resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold` tools=`tools`* +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. +Return *[Resolve](agent_resolve(task=`task`, kb_dir=`kb_dir`, near_match=`near_match`, near_threshold=`near_threshold`, tools=`tools`))*. ## route - + `task` - + `backend`=auto - + `kb_dir`=.marqdo/agent-kb - + `memory_dir`=.marqdo/agent-memory - + `threshold`=0.78 - + `step_kind`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| backend | any | "auto" | Configured execution or provider backend | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| threshold | any | 0.78 | Policy threshold required by this operation | +| step_kind | any | None | Class of workbook step | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`. Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call. | + +Use `task`, `backend`="auto", `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `threshold`=0.78, `step_kind`=None as the inputs for this operation. Adaptive Routing (Phase 4): abstract router — `marqdo` | `small-llm` | `llm` | `auto`. `jev` is accepted as a **compat alias** of `small-llm` (not a first-class backend). `auto` cascades policy → kb → small-llm request. May return `needs_llm=True` + `prompt` for the caller to complete with `router_model` (any llm handle), then `route_apply`. Optional `step_kind=` (O3) selects backend via module `## step_route` before the ABI call. 1. `step_kind` - **sr = step_route kind=`step_kind`** - **backend = > json.get value=`sr` key="backend"** + We retain **`sr` = [Step route](step_route(kind=`step_kind`))**. + We retain **`backend` = [Read the backend field](json.get(value=`sr`, key="backend"))**. 2. * **_ = 1** -**tools = > json.get value=`self` key="tools"** -*> agent_route task=`task` backend=`backend` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`threshold` tools=`tools`* +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. +Return *[Route](agent_route(task=`task`, backend=`backend`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, threshold=`threshold`, tools=`tools`))*. ## route_apply - + `task` - + `reply` - + `kb_dir`=.marqdo/agent-kb - + `backend`=small-llm + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| reply | any | required | Model reply to parse as data; it is not permission to execute arbitrary code | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| backend | any | "small-llm" | Configured execution or provider backend | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply a router model line (`SKILL:` / `EXPLORE`) to a kb skill hit. | + +Use `task`, `reply`, `kb_dir`=".marqdo/agent-kb", `backend`="small-llm" as the inputs for this operation. Apply a router model line (`SKILL:` / `EXPLORE`) to a kb skill hit. -*> agent_route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`backend`* +Return *[Route apply](agent_route_apply(task=`task`, reply=`reply`, kb_dir=`kb_dir`, backend=`backend`))*. ## compile_policy - + `memory_dir`=.marqdo/agent-memory - + `min_evidence`=3 - + `force`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| min_evidence | any | 3 | Minimum evidence count required before promotion | +| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Policy Compilation: stable episode skill selections → `policies/router.mq.md` (deterministic Marqdo rules). | + +Use `memory_dir`=".marqdo/agent-memory", `min_evidence`=3, `force`=False as the inputs for this operation. Policy Compilation: stable episode skill selections → `policies/router.mq.md` (deterministic Marqdo rules). -*> agent_compile_policy memory_dir=`memory_dir` min_evidence=`min_evidence` force=`force`* +Return *[Compile policy](agent_compile_policy(memory_dir=`memory_dir`, min_evidence=`min_evidence`, force=`force`))*. ## maybe_compile_policy - + `memory_dir`=.marqdo/agent-memory - + `min_evidence`=3 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| min_evidence | any | 3 | Minimum evidence count required before promotion | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Learn gate for the Adaptive Router policy layer. | + +Use `memory_dir`=".marqdo/agent-memory", `min_evidence`=3 as the inputs for this operation. Learn gate for the Adaptive Router policy layer. -*> agent_maybe_compile_policy memory_dir=`memory_dir` min_evidence=`min_evidence`* +Return *[Maybe compile policy](agent_maybe_compile_policy(memory_dir=`memory_dir`, min_evidence=`min_evidence`))*. ## record_episode - + `task` - + `status`=ok - + `result`=None - + `mode`=explore - + `skill`=none - + `observation`=None - + `workbook`=None - + `cache`=None - + `match`=None - + `llm_calls`=0 - + `tool_calls`=0 - + `error`=None - + `memory_dir`=.marqdo/agent-memory + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| status | any | "ok" | Domain status recorded in the structured result | +| result | any | None | Structured result from the preceding operation | +| mode | any | "explore" | Operation mode listed in the function behavior | +| skill | any | "none" | Skill source or identifier selected for inspection | +| observation | any | None | Tool observation or workbook result retained for the next turn | +| workbook | any | None | Workbook path or structured workbook reference | +| cache | any | None | Whether to use the documented result cache | +| match | any | None | Resolved match or match policy | +| llm_calls | any | 0 | Observed model-call count | +| tool_calls | any | 0 | Observed tool-call count | +| error | any | None | Structured failure information supplied by the caller | +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). Memory is executable documentation, not a vector bag. | + +Use `task`, `status`="ok", `result`=None, `mode`="explore", `skill`="none", `observation`=None, `workbook`=None, `cache`=None, `match`=None, `llm_calls`=0, `tool_calls`=0, `error`=None, `memory_dir`=".marqdo/agent-memory" as the inputs for this operation. Persist one run as `.mq.md` under `memory_dir/episodes/YYYY/MM/` (v2 Phase 1). Memory is executable documentation, not a vector bag. -*> agent_record_episode task=`task` status=`status` result=`result` mode=`mode` skill=`skill` observation=`observation` workbook=`workbook` cache=`cache` match=`match` llm_calls=`llm_calls` tool_calls=`tool_calls` error=`error` memory_dir=`memory_dir`* +Return *[Record episode](agent_record_episode(task=`task`, status=`status`, result=`result`, mode=`mode`, skill=`skill`, observation=`observation`, workbook=`workbook`, cache=`cache`, match=`match`, llm_calls=`llm_calls`, tool_calls=`tool_calls`, error=`error`, memory_dir=`memory_dir`))*. ## quarantine - + `slug` - + `kb_dir`=.marqdo/agent-kb - + `reason`=sandbox_or_harness_failed + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| slug | any | required | Knowledge entry identifier within the configured knowledge directory | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| reason | any | "sandbox_or_harness_failed" | Human-readable explanation for the recorded decision | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug. | + +Use `slug`, `kb_dir`=".marqdo/agent-kb", `reason`="sandbox_or_harness_failed" as the inputs for this operation. O5: mark OKF skill `status: quarantine` and force `llm_free: false`. Regression fixtures stay with the slug. -*> agent_kb_quarantine kb_dir=`kb_dir` slug=`slug` reason=`reason`* +Return *[Kb quarantine](agent_kb_quarantine(kb_dir=`kb_dir`, slug=`slug`, reason=`reason`))*. ## maybe_learn - + `task` - + `kb_dir`=.marqdo/agent-kb - + `memory_dir`=.marqdo/agent-memory - + `improve_every`=3 - + `promote`=True - + `candidate_only`=False - + `product_gate_ok`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| improve_every | any | 3 | Number of observations between improvement attempts | +| promote | any | True | Whether successful evidence may be promoted | +| candidate_only | any | False | Whether to retain a candidate without publishing it | +| product_gate_ok | any | True | Result of the external product gate | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing. O2: promote path requires sandbox proof unless `require_proof=false`. M04: `candidate_only=True` or `product_gate_ok=False` forces promote off via eng_publish_gate. | + +Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `improve_every`=3, `promote`=True, `candidate_only`=False, `product_gate_ok`=True as the inputs for this operation. Offline learn gate: when ≥ `improve_every` successful episodes share a task hash, generalize → synthesize → compile → optional OKF promote (`llm_free`). Also attempts Policy Compilation for Adaptive Routing. O2: promote path requires sandbox proof unless `require_proof=false`. M04: `candidate_only=True` or `product_gate_ok=False` forces promote off via eng_publish_gate. -**gate = > `self`.eng_publish_gate project="." candidate_only=`candidate_only` product_gate_ok=`product_gate_ok`** -**may_prom = > json.get value=`gate` key="may_promote"** +We retain **`gate` = [Eng publish gate](> `self`.eng_publish_gate project="." candidate_only=`candidate_only` product_gate_ok=`product_gate_ok` )**. +We retain **`may_prom` = [Read the may_promote field](json.get(value=`gate`, key="may_promote"))**. 1. not `may_prom` - **promote = False** + We retain **promote = False**. 2. * **_ = 1** -**skill_learn = > agent_maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote`** -**policy_learn = > agent_maybe_compile_policy memory_dir=`memory_dir` min_evidence=`improve_every`** -**sl = > json.get value=`skill_learn` key="learned"** +We retain **`skill_learn` = [Maybe learn](agent_maybe_learn(task=`task`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, improve_every=`improve_every`, promote=`promote`))**. +We retain **`policy_learn` = [Maybe compile policy](agent_maybe_compile_policy(memory_dir=`memory_dir`, min_evidence=`improve_every`))**. +We retain **`sl` = [Read the learned field](json.get(value=`skill_learn`, key="learned"))**. + `out` = | learned | skill | policy | promote_allowed | gate | |---------|-------|--------|-----------------|------| | `sl` | `skill_learn` | `policy_learn` | `may_prom` | `gate` | -*out* +Return *out*. ## compile - + `task` - + `kb_dir`=.marqdo/agent-kb - + `memory_dir`=.marqdo/agent-memory - + `min_evidence`=3 - + `promote`=True - + `force`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| min_evidence | any | 3 | Minimum evidence count required before promotion | +| promote | any | True | Whether successful evidence may be promoted | +| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Compile a candidate skill into versioned `skills//vN.mq.md` and optionally promote into agent-kb. | + +Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `min_evidence`=3, `promote`=True, `force`=False as the inputs for this operation. Compile a candidate skill into versioned `skills//vN.mq.md` and optionally promote into agent-kb. -*> agent_compile_skill task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` min_evidence=`min_evidence` promote=`promote` force=`force`* +Return *[Compile skill](agent_compile_skill(task=`task`, kb_dir=`kb_dir`, memory_dir=`memory_dir`, min_evidence=`min_evidence`, promote=`promote`, force=`force`))*. ## metrics - + `memory_dir`=.marqdo/agent-memory + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_runs`, …). | + +Use `memory_dir`=".marqdo/agent-memory" as the inputs for this operation. Reasoning amortization stats over recorded episodes (`avg_llm_calls`, `compiled_runs`, …). -*> agent_metrics memory_dir=`memory_dir`* +Return *[Metrics](agent_metrics(memory_dir=`memory_dir`))*. ## run - + `task` - + `kb_dir`=.marqdo/agent-kb - + `memory_dir`=.marqdo/agent-memory - + `learn`=True - + `verify`=True - + `writeback`=True - + `reuse`=True - + `near_match`=True - + `near_threshold`=0.78 - + `promote`=True - + `improve_every`=3 - + `explore_n`=3 - + `max_rounds`=4 - + `stream`=False - + `echo`=False - + `trace`=False - + `force`=False - + `router`=auto - + `router_model`=None - + `resume_id`=None - + `resume_dir`=.marqdo/agent-resume - + `sandbox`=False - + `sandbox_profile`=default - + `efi`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| memory_dir | any | ".marqdo/agent-memory" | Directory holding learned episodes or policy memory | +| learn | any | True | Whether to record or learn from this operation | +| verify | any | True | Whether to run the documented verifier | +| writeback | any | True | Whether to write the observation back to its author document | +| reuse | any | True | Whether to search for reusable knowledge before new work | +| near_match | any | True | Whether to consider near-match candidates | +| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | +| promote | any | True | Whether successful evidence may be promoted | +| improve_every | any | 3 | Number of observations between improvement attempts | +| explore_n | any | 3 | Maximum configured exploration attempts | +| max_rounds | any | 4 | Maximum workbook planning rounds | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| trace | any | False | Whether to retain the documented execution trace | +| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | +| router | any | "auto" | Router configuration or route-policy resource | +| router_model | any | None | Model resource used for routing | +| resume_id | any | None | Identifier of the stored continuation checkpoint | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | +| sandbox | any | False | Whether to use the CoW trial path | +| sandbox_profile | any | "default" | Capability profile for CoW execution | +| efi | any | True | Structured effect and failure information | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome. | + +Use `task`, `kb_dir`=".marqdo/agent-kb", `memory_dir`=".marqdo/agent-memory", `learn`=True, `verify`=True, `writeback`=True, `reuse`=True, `near_match`=True, `near_threshold`=0.78, `promote`=True, `improve_every`=3, `explore_n`=3, `max_rounds`=4, `stream`=False, `echo`=False, `trace`=False, `force`=False, `router`="auto", `router_model`=None, `resume_id`=None, `resume_dir`=".marqdo/agent-resume", `sandbox`=False, `sandbox_profile`="default", `efi`=True as the inputs for this operation. Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) or `plan` → record episode → maybe_learn (skill + policy). `router` = `auto`|`marqdo`|`small-llm`|`llm` (`jev`→`small-llm` alias). Optional `router_model` (llm handle) answers `needs_llm` prompts — small models welcome. `sandbox=True` (O1 opt-in): workbook paths run via CoW trial before host commit. `efi=True` (O3): EKC preflight before explore; REUSE short-circuits. Pass `efi=False` to keep legacy golds that skip eng knowledge. -**efi_pf = None** +Use this entry when the application wants the full reuse-and-learning lifecycle. A single conversational turn belongs in step; run first tries existing executable knowledge and can fall back to a workbook plan. The output records which execution mode actually supplied the result, allowing callers to distinguish compiled reuse, router-assisted reuse and exploration instead of inferring that distinction from answer text. + +Routing precedes exploration. A matched resource is awaited as a workbook; a failed child does not count as a reusable success. When a route needs a model, the configured routing model, or the agent's normal model, produces the restricted selection reply. Applying that reply resolves it to an actual knowledge resource. Model words alone never stand in for the child's returned value. + +Engineering preflight supplies an additional reuse gate. A REUSE result can bind and execute an existing engineering capability; a refusal to create is returned as an error rather than ignored. Missing engineering knowledge is distinguished from a positive refusal. The lower resolver then checks reusable skills, including whether an entry is marked llm_free, before a new plan is requested. Preserve this order when extending the method so new capabilities do not quietly skip existing knowledge. + +The workbook await helper owns the execution boundary. With sandbox enabled it uses the configured CoW path; attaching a profile name to an answer is insufficient. Native plugin loading and explicit runtime grants are still required by the selected resource. A successful reused child can therefore avoid parent model calls, while an exploratory result carries the usage reported by its plan. + +After execution, the method extracts task status, result, skill and observation for the episode record. Verification here is a recorded execution-status check; it is not an independent domain proof of the answer. Applications with stronger requirements must validate the returned value using their own task-specific assertions. Do not interpret a status string as evidence that files, network writes or generated source were reviewed. + +Episodes persist the observed outcome for later reuse decisions. Learning is attempted only for successful outcomes when enabled, and promotion follows the existing evidence path. The result attaches execution details, model usage, routing information and the episode reference. An optional resume identifier also saves a checkpoint and effect-ledger watermark. These records describe what happened; they do not make an uncertain external effect safe to repeat. + +For a reproducible investigation, retain the returned workbook reference and observation together. The same goal text can resolve differently after knowledge promotion, so a later rerun of the request is not a substitute for examining the recorded resource. + +We retain **efi_pf = None**. 1. `efi` - **efi_pf = > `self`.preflight task=`task`** + We retain **`efi_pf` = [Preflight](> `self`.preflight task=`task` )**. 2. * **_ = 1** -**routed = > `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold`** -**route_matched = > json.get value=`routed` key="matched"** -**needs_llm = > json.get value=`routed` key="needs_llm"** -**exec_mode = "explore"** -**llm_calls = 0** -**tokens = 0** -**token_cost = 0** -**out = None** -**route_backend = > json.get value=`routed` key="backend"** +We retain **`routed` = [Route](> `self`.route task=`task` backend=`router` kb_dir=`kb_dir` memory_dir=`memory_dir` threshold=`near_threshold` )**. +We retain **`route_matched` = [Read the matched field](json.get(value=`routed`, key="matched"))**. +We retain **`needs_llm` = [Read the needs_llm field](json.get(value=`routed`, key="needs_llm"))**. +We retain **exec_mode = "explore"**. +We retain **llm_calls = 0**. +We retain **tokens = 0**. +We retain **token_cost = 0**. +We retain **out = None**. +We retain **`route_backend` = [Read the backend field](json.get(value=`routed`, key="backend"))**. 1. `route_matched` - **path = > json.get value=`routed` key="resource"** + We retain **`path` = [Read the resource field](json.get(value=`routed`, key="resource"))**. 1. `path` - **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. 1. `code` == 0 - > agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every` - **lf = > json.get value=`routed` key="llm_free"** + We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`task`, improve_every=`improve_every`))**. + We retain **`lf` = [Read the llm_free field](json.get(value=`routed`, key="llm_free"))**. 1. `lf` - **exec_mode = "compiled"** + We retain **exec_mode = "compiled"**. 2. * - **exec_mode = "routed"** - **rmode = > json.get value=`routed` key="mode"** - **sk = > json.get value=`routed` key="skill"** + We retain **exec_mode = "routed"**. + We retain **`rmode` = [Read the mode field](json.get(value=`routed`, key="mode"))**. + We retain **`sk` = [Read the skill field](json.get(value=`routed`, key="skill"))**. **out = ** | status | goal | result | workbook | cache | match | skill | observation | summary | route | |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------| | ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` | - **llm_calls = 0** + We retain **llm_calls = 0**. 1. `stream` - **_ev = > table.empty_list** - **_ev = > plan_append_decision events=`_ev` decision="REUSE" stream=True summary="adaptive route hit"** - **_ev = > plan_append_round events=`_ev` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=True** + We retain **`_ev` = [Empty list](table.empty_list())**. + We retain **`_ev` = [Plan append decision](plan_append_decision(events=`_ev`, decision="REUSE", stream=True, summary="adaptive route hit"))**. + We retain **`_ev` = [Plan append round](plan_append_round(events=`_ev`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=True))**. 2. * **_ = 1** 2. * - **route_matched = False** + We retain **route_matched = False**. 2. * - **route_matched = False** + We retain **route_matched = False**. 2. * **_ = 1** @@ -2724,35 +4051,35 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o **_ = 1** 2. `needs_llm` 1. `router_model` - **prompt = > json.get value=`routed` key="prompt"** - **turn = model_turn model=`router_model` prompt=`prompt` stream=`stream` echo=`echo`** - **reply = > json.get value=`turn` key="text"** - **llm_calls = > json.get value=`turn` key="llm_calls"** - **tokens = > json.get value=`turn` key="tokens"** - **applied = > `self`.route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`router`** - **am = > json.get value=`applied` key="matched"** + We retain **`prompt` = [Read the prompt field](json.get(value=`routed`, key="prompt"))**. + We retain **`turn` = [Model turn](model_turn(model=`router_model`, prompt=`prompt`, stream=`stream`, echo=`echo`))**. + We retain **`reply` = [Read the text field](json.get(value=`turn`, key="text"))**. + We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. + We retain **`tokens` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. + We retain **`applied` = [Route apply](> `self`.route_apply task=`task` reply=`reply` kb_dir=`kb_dir` backend=`router` )**. + We retain **`am` = [Read the matched field](json.get(value=`applied`, key="matched"))**. 1. `am` - **path = > json.get value=`applied` key="resource"** - **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We retain **`path` = [Read the resource field](json.get(value=`applied`, key="resource"))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. 1. `code` == 0 - **exec_mode = "routed"** - **sk = > json.get value=`applied` key="skill"** + We retain **exec_mode = "routed"**. + We retain **`sk` = [Read the skill field](json.get(value=`applied`, key="skill"))**. **out = ** | status | goal | result | workbook | cache | match | skill | observation | summary | route | |--------|------|--------|----------|-------|-------|-------|-------------|---------|-------| | ok | `task` | `child_val` | `path` | soft-hit | routed | `sk` | `last_obs` | router model selected skill | `applied` | - **route_matched = True** + We retain **route_matched = True**. 2. * - **route_matched = False** + We retain **route_matched = False**. 2. * - **route_matched = False** + We retain **route_matched = False**. 2. * - **route_matched = False** + We retain **route_matched = False**. 3. * **_ = 1** @@ -2760,16 +4087,16 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o **_ = 1** 2. * 1. `efi_pf` - **efi_st = > json.get value=`efi_pf` key="status"** - **efi_dec = > json.get value=`efi_pf` key="decision"** - **efi_allow = > json.get value=`efi_pf` key="create_allowed"** + We retain **`efi_st` = [Read the status field](json.get(value=`efi_pf`, key="status"))**. + We retain **`efi_dec` = [Read the decision field](json.get(value=`efi_pf`, key="decision"))**. + We retain **`efi_allow` = [Read the create_allowed field](json.get(value=`efi_pf`, key="create_allowed"))**. 1. `efi_st` == "missing_knowledge" **_ = 1** 2. `efi_dec` == "REUSE" - **efi_exec = > agent_eng_bind_execute project="." query=`task` policy="pure" candidate_only=False** - **efi_ok = > json.get value=`efi_exec` key="ok"** + We retain **`efi_exec` = [Eng bind execute](agent_eng_bind_execute(project=".", query=`task`, policy="pure", candidate_only=False))**. + We retain **`efi_ok` = [Read the ok field](json.get(value=`efi_exec`, key="ok"))**. 1. `efi_ok` - **exec_mode = "efi_bound"** + We retain **exec_mode = "efi_bound"**. **out = ** | status | goal | result | summary | efi | reuse_trace | @@ -2789,93 +4116,93 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o |--------|------|-------|---------|-----| | error | `task` | efi_create_denied | EKC preflight denied CREATE | `efi_pf` | - **exec_mode = "efi"** + We retain **exec_mode = "efi"**. 2. * **_ = 1** 1. `out` **_ = 1** 2. * - **resolved = > `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold`** - **mode = > json.get value=`resolved` key="mode"** - **llm_free = > json.get value=`resolved` key="llm_free"** + We retain **`resolved` = [Resolve](> `self`.resolve task=`task` kb_dir=`kb_dir` near_match=`near_match` near_threshold=`near_threshold` )**. + We retain **`mode` = [Read the mode field](json.get(value=`resolved`, key="mode"))**. + We retain **`llm_free` = [Read the llm_free field](json.get(value=`resolved`, key="llm_free"))**. 1. not `llm_free` - **llm_free = False** + We retain **llm_free = False**. 1. `llm_free` - **path = > json.get value=`resolved` key="resource"** - **aw = await_workbook path=`path` sandbox=`sandbox` sandbox_profile=`sandbox_profile`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We retain **`path` = [Read the resource field](json.get(value=`resolved`, key="resource"))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`, sandbox=`sandbox`, sandbox_profile=`sandbox_profile`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. 1. `code` == 0 - > agent_kb_record_hit kb_dir=`kb_dir` goal=`task` improve_every=`improve_every` - **exec_mode = "compiled"** - **sk = > json.get value=`resolved` key="skill"** + We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`task`, improve_every=`improve_every`))**. + We retain **exec_mode = "compiled"**. + We retain **`sk` = [Read the skill field](json.get(value=`resolved`, key="skill"))**. **out = ** | status | goal | result | workbook | cache | match | skill | observation | summary | |--------|------|--------|----------|-------|-------|-------|-------------|--------| | ok | `task` | `child_val` | `path` | hit | `mode` | `sk` | `last_obs` | compiled skill (llm_free) | - **llm_calls = 0** + We retain **llm_calls = 0**. 2. * - **out = > `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force`** - **exec_mode = "explore"** - **llm_calls = > json.get value=`out` key="llm_calls"** - **tokens = > json.get value=`out` key="tokens"** + We retain **`out` = [Plan](> `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force` )**. + We retain **exec_mode = "explore"**. + We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`out`, key="llm_calls"))**. + We retain **`tokens` = [Read the tokens field](json.get(value=`out`, key="tokens"))**. 1. `llm_calls` == None - **llm_calls = 1** + We retain **llm_calls = 1**. 1. `tokens` == None - **tokens = 0** + We retain **tokens = 0**. 2. * - **out = > `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force`** - **cache = > json.get value=`out` key="cache"** + We retain **`out` = [Plan](> `self`.plan goal=`task` kb_dir=`kb_dir` writeback=`writeback` reuse=`reuse` near_match=`near_match` near_threshold=`near_threshold` promote=`promote` improve_every=`improve_every` explore_n=`explore_n` max_rounds=`max_rounds` stream=`stream` echo=`echo` trace=`trace` force=`force` )**. + We retain **`cache` = [Read the cache field](json.get(value=`out`, key="cache"))**. 1. `cache` == "hit" - **exec_mode = "compiled"** - **llm_calls = 0** - **tokens = 0** + We retain **exec_mode = "compiled"**. + We retain **llm_calls = 0**. + We retain **tokens = 0**. 2. `cache` == "soft-hit" - **exec_mode = "near"** - **llm_calls = 0** - **tokens = 0** + We retain **exec_mode = "near"**. + We retain **llm_calls = 0**. + We retain **tokens = 0**. 3. * - **exec_mode = "explore"** - **llm_calls = > json.get value=`out` key="llm_calls"** - **tokens = > json.get value=`out` key="tokens"** + We retain **exec_mode = "explore"**. + We retain **`llm_calls` = [Read the llm_calls field](json.get(value=`out`, key="llm_calls"))**. + We retain **`tokens` = [Read the tokens field](json.get(value=`out`, key="tokens"))**. 1. `llm_calls` == None - **llm_calls = 1** + We retain **llm_calls = 1**. 1. `tokens` == None - **tokens = 0** + We retain **tokens = 0**. -**st = > json.get value=`out` key="status"** -**res = > json.get value=`out` key="result"** -**wb_path = > json.get value=`out` key="workbook"** -**obs = > json.get value=`out` key="observation"** -**sk2 = > json.get value=`out` key="skill"** -**cache2 = > json.get value=`out` key="cache"** -**match2 = > json.get value=`out` key="match"** -**err = > json.get value=`out` key="error"** +We retain **`st` = [Read the status field](json.get(value=`out`, key="status"))**. +We retain **`res` = [Read the result field](json.get(value=`out`, key="result"))**. +We retain **`wb_path` = [Read the workbook field](json.get(value=`out`, key="workbook"))**. +We retain **`obs` = [Read the observation field](json.get(value=`out`, key="observation"))**. +We retain **`sk2` = [Read the skill field](json.get(value=`out`, key="skill"))**. +We retain **`cache2` = [Read the cache field](json.get(value=`out`, key="cache"))**. +We retain **`match2` = [Read the match field](json.get(value=`out`, key="match"))**. +We retain **`err` = [Read the error field](json.get(value=`out`, key="error"))**. 1. `verify` 1. `st` == "ok" - **verification = "status: passed"** + We retain **verification = "status: passed"**. 2. * - **verification = "status: failed"** + We retain **verification = "status: failed"**. 2. * - **verification = "status: skipped"** + We retain **verification = "status: skipped"**. -**ep = > `self`.record_episode task=`task` status=`st` result=`res` mode=`exec_mode` skill=`sk2` observation=`obs` workbook=`wb_path` cache=`cache2` match=`match2` llm_calls=`llm_calls` tokens=`tokens` error=`err` memory_dir=`memory_dir`** +We retain **`ep` = [Record episode](> `self`.record_episode task=`task` status=`st` result=`res` mode=`exec_mode` skill=`sk2` observation=`obs` workbook=`wb_path` cache=`cache2` match=`match2` llm_calls=`llm_calls` tokens=`tokens` error=`err` memory_dir=`memory_dir` )**. -**learning = None** +We retain **learning = None**. 1. `learn` 1. `st` == "ok" - **learning = > `self`.maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote`** + We retain **`learning` = [Maybe learn](> `self`.maybe_learn task=`task` kb_dir=`kb_dir` memory_dir=`memory_dir` improve_every=`improve_every` promote=`promote` )**. 2. * - **learning = None** + We retain **learning = None**. 2. * **_ = 1** -**token_cost = tokens** +We retain **token_cost = tokens**. **usage = ** | llm_calls | tokens | token_cost | @@ -2888,40 +4215,49 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o |------|-----------|--------|------------|-------|--------| | `exec_mode` | `llm_calls` | `tokens` | `token_cost` | `sk2` | `route_backend` | -**out = table.put in=`out` at="execution" value=`execution`** -**out = table.put in=`out` at="episode" value=`ep`** -**out = table.put in=`out` at="route" value=`routed`** -**out = table.put in=`out` at="usage" value=`usage`** -**out = table.put in=`out` at="token_cost" value=`token_cost`** +We retain **`out` = [Set the execution field in the new record](table.put(in=`out`, at="execution", value=`execution`))**. +We retain **`out` = [Set the episode field in the new record](table.put(in=`out`, at="episode", value=`ep`))**. +We retain **`out` = [Set the route field in the new record](table.put(in=`out`, at="route", value=`routed`))**. +We retain **`out` = [Set the usage field in the new record](table.put(in=`out`, at="usage", value=`usage`))**. +We retain **`out` = [Set the token_cost field in the new record](table.put(in=`out`, at="token_cost", value=`token_cost`))**. 1. `learning` - **out = table.put in=`out` at="learning" value=`learning`** + We retain **`out` = [Set the learning field in the new record](table.put(in=`out`, at="learning", value=`learning`))**. 2. * **_ = 1** 1. `efi_pf` - **out = table.put in=`out` at="efi" value=`efi_pf`** + We retain **`out` = [Set the efi field in the new record](table.put(in=`out`, at="efi", value=`efi_pf`))**. 2. * **_ = 1** 1. `resume_id` - **_wm = > effects_watermark ledger_dir=".marqdo/agent-effects" logical_run_id=`resume_id`** - **_ckpt = resume_save id=`resume_id` goal=`task` task=`task` status=`st` round=1 workbook=`wb_path` result=`res` route=`routed` resume_dir=`resume_dir` checkpoint_v2=True attempt_id="attempt_1" effect_ledger_watermark=`_wm`** - **out = table.put in=`out` at="resume" value=`_ckpt`** - **out = table.put in=`out` at="effect_ledger_watermark" value=`_wm`** + We retain **`_wm` = [Effects watermark](effects_watermark(ledger_dir=".marqdo/agent-effects", logical_run_id=`resume_id`))**. + We retain **`_ckpt` = [Resume save](resume_save(id=`resume_id`, goal=`task`, task=`task`, status=`st`, round=1, workbook=`wb_path`, result=`res`, route=`routed`, resume_dir=`resume_dir`, checkpoint_v2=True, attempt_id="attempt_1", effect_ledger_watermark=`_wm`))**. + We retain **`out` = [Set the resume field in the new record](table.put(in=`out`, at="resume", value=`_ckpt`))**. + We retain **`out` = [Set the effect_ledger_watermark field in the new record](table.put(in=`out`, at="effect_ledger_watermark", value=`_wm`))**. 2. * **_ = 1** -*out* +Return *out*. ## step - + `task` - + `writeback`=True - + `stream`=False - + `echo`=False - + `max_reads`=2 - + `sandbox`=False - + `sandbox_profile`=default - + `resume_id`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| writeback | any | True | Whether to write the observation back to its author document | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| max_reads | any | 2 | Maximum context-deepening reads | +| sandbox | any | False | Whether to use the CoW trial path | +| sandbox_profile | any | "default" | Capability profile for CoW execution | +| resume_id | any | None | Identifier of the stored continuation checkpoint | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip. Optional `resume_id` scopes EffectLedger idempotency for mutating tools. With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer. | + +Use `task`, `writeback`=True, `stream`=False, `echo`=False, `max_reads`=2, `sandbox`=False, `sandbox_profile`="default", `resume_id`=None as the inputs for this operation. One atomic turn: budgeted context → LLM → optional `READ:` deepen → optional tool via subtask. Returns a *map* (`status`, `task`, `decision`, and on success `result` plus optional `tool` / `tool_result`; on failure `error`). By default (`writeback=True`) persists that map under named slots `ok` / `error` at the call site; pass `writeback=False` to skip. Optional `resume_id` scopes EffectLedger idempotency for mutating tools. @@ -2929,9 +4265,9 @@ Optional `resume_id` scopes EffectLedger idempotency for mutating tools. With `stream=True`, the model call uses SSE; `echo=True` prints delta text to stdout as it arrives. The returned map is unchanged (final `result` string). Context source/skill start at default budget; up to `max_reads` of `READ:source` / `READ:skill` deepen before CALL/answer. `sandbox=True` (O1 opt-in): attach the sandbox profile row on the result map (trial via `## trial` / `run sandbox=`). -**id = > json.get value=`self` key="id"** -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** +We retain **`id` = [Read the id field](json.get(value=`self`, key="id"))**. +We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. `user_turn` = @@ -2939,57 +4275,58 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st |------|---------| | user | `task` | -> agent_history_append id=`id` item=`user_turn` +We **[Append this item to the new list](agent_history_append(id=`id`, item=`user_turn`))**. -**source_depth = "default"** -**skill_depth = "default"** -**reads_left = max_reads** -**reply = None** -**decision = None** -**llm_calls = 0** -**tokens = 0** +We retain **source_depth = "default"**. +We retain **skill_depth = "default"**. +We retain **reads_left = max_reads**. +We retain **reply = None**. +We retain **decision = None**. +We retain **llm_calls = 0**. +We retain **tokens = 0**. -**transport_err = None** +We retain **transport_err = None**. - `reads_left` > 0 1. `decision` - **reads_left = 0** + We retain **reads_left = 0**. 2. `transport_err` - **reads_left = 0** + We retain **reads_left = 0**. 3. * - **ctx = > build_step_context agent=`self` task=`task` source_depth=`source_depth` skill_depth=`skill_depth`** - **turn = > model_turn model=`model` prompt=`ctx` stream=`stream` echo=`echo`** - **terr = > json.get value=`turn` key="error"** + We retain **`ctx` = [Build step context](build_step_context(agent=`self`, task=`task`, source_depth=`source_depth`, skill_depth=`skill_depth`))**. + We retain **`turn` = [Model turn](model_turn(model=`model`, prompt=`ctx`, stream=`stream`, echo=`echo`))**. + We retain **`terr` = [Read the error field](json.get(value=`turn`, key="error"))**. 1. `terr` - **transport_err = `terr`** - **reads_left = 0** + We retain **transport_err = `terr`**. + We retain **reads_left = 0**. 2. * - **reply = > json.get value=`turn` key="text"** - **c = > json.get value=`turn` key="llm_calls"** - **t = > json.get value=`turn` key="tokens"** + We retain **`reply` = [Read the text field](json.get(value=`turn`, key="text"))**. + We retain **`c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. + We retain **`t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. 1. not `c` - **c = 0** + We retain **c = 0**. 2. * **_ = 1** 1. not `t` - **t = 0** + We retain **t = 0**. 2. * **_ = 1** - **llm_calls = llm_calls + c** - **tokens = tokens + t** - **reply = > trim value=`reply`** - **rk = > extract_plan_read reply=`reply`** + We retain **llm_calls = llm_calls + c**. + We retain **tokens = tokens + t**. + We retain **`reply` = [Trim](trim(value=`reply`))**. + We retain **`rk` = [Extract plan read](extract_plan_read(reply=`reply`))**. 1. `rk` == source - **source_depth = "deep"** - **reads_left = reads_left - 1** + We retain **source_depth = "deep"**. + We retain **reads_left = reads_left - 1**. 2. `rk` == skill - **skill_depth = "deep"** - **reads_left = reads_left - 1** + We retain **skill_depth = "deep"**. + We retain **reads_left = reads_left - 1**. 3. * - **decision = reply** - **reads_left = 0** + We retain **decision = reply**. + We retain **reads_left = 0**. 1. `transport_err` + `out` = | status | task | error | llm_calls | tokens | @@ -2997,17 +4334,18 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st | error | `task` | `transport_err` | `llm_calls` | `tokens` | 1. `writeback` - **body = > json.stringify value=`out`** - > wb.record value=`body` key="error" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We **[Record](wb.record(value=`body`, key="error"))**. 2. * **_ = 1** - *out* + Return *out*. 2. * **_ = 1** -**reply = > trim value=`reply`** -**decision = reply** -**tool_name = > extract_tool_name reply=`reply`** +We retain **`reply` = [Trim](trim(value=`reply`))**. +We retain **decision = reply**. +We retain **`tool_name` = [Extract tool name](extract_tool_name(reply=`reply`))**. + `out` = | status | task | decision | @@ -3015,65 +4353,65 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st | ok | `task` | `decision` | 1. `tool_name` - **tool_out = > run_tool tools=`tools` name=`tool_name` logical_run_id=`resume_id`** - **tool_s = > json.stringify value=`tool_out`** - **deny = > split value=`tool_s` sep="Tool not allowed"** - **deny_n = > len value=`deny`** + We retain **`tool_out` = [Run tool](run_tool(tools=`tools`, name=`tool_name`, logical_run_id=`resume_id`))**. + We retain **`tool_s` = [Encode the structured value as JSON text](json.stringify(value=`tool_out`))**. + We retain **`deny` = [Split](split(value=`tool_s`, sep="Tool not allowed"))**. + We retain **`deny_n` = [Len](len(value=`deny`))**. 1. `deny_n` > 1 - **task_s = > json.stringify value=`task`** - **fp = "Tool CALL was rejected (not on the tools whitelist). Do NOT emit CALL. Answer the user task directly with the final answer only.\n\nUser task:\n"** - **fp = fp + task_s** - **turn2 = > model_turn model=`model` prompt=`fp` stream=`stream` echo=`echo`** - **reply = > json.get value=`turn2` key="text"** - **c = > json.get value=`turn2` key="llm_calls"** - **t = > json.get value=`turn2` key="tokens"** + We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. + We retain **fp = "Tool CALL was rejected (not on the tools whitelist). Do NOT emit CALL. Answer the user task directly with the final answer only.\n\nUser task:\n"**. + We retain **fp = fp + task_s**. + We retain **`turn2` = [Model turn](model_turn(model=`model`, prompt=`fp`, stream=`stream`, echo=`echo`))**. + We retain **`reply` = [Read the text field](json.get(value=`turn2`, key="text"))**. + We retain **`c` = [Read the llm_calls field](json.get(value=`turn2`, key="llm_calls"))**. + We retain **`t` = [Read the tokens field](json.get(value=`turn2`, key="tokens"))**. 1. not `c` - **c = 0** + We retain **c = 0**. 2. * **_ = 1** 1. not `t` - **t = 0** + We retain **t = 0**. 2. * **_ = 1** - **llm_calls = llm_calls + c** - **tokens = tokens + t** - **out = table.put in=`out` at="denied_tool" value=`tool_name`** - **out = table.put in=`out` at="result" value=`reply`** + We retain **llm_calls = llm_calls + c**. + We retain **tokens = tokens + t**. + We retain **`out` = [Set the denied_tool field in the new record](table.put(in=`out`, at="denied_tool", value=`tool_name`))**. + We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. 2. * - **task_s = > json.stringify value=`task`** - **fp = "The user asked:"** - **fp = fp + task_s** - **fp = fp + ". Tool"** - **fp = fp + tool_name** - **fp = fp + "ran via subtask and returned:"** - **fp = fp + tool_s** - **fp = fp + ". Reply to the user briefly."** - **turn2 = > model_turn model=`model` prompt=`fp` stream=`stream` echo=`echo`** - **reply = > json.get value=`turn2` key="text"** - **c = > json.get value=`turn2` key="llm_calls"** - **t = > json.get value=`turn2` key="tokens"** + We retain **`task_s` = [Encode the structured value as JSON text](json.stringify(value=`task`))**. + We retain **fp = "The user asked:"**. + We retain **fp = fp + task_s**. + We retain **fp = fp + ". Tool"**. + We retain **fp = fp + tool_name**. + We retain **fp = fp + "ran via subtask and returned:"**. + We retain **fp = fp + tool_s**. + We retain **fp = fp + ". Reply to the user briefly."**. + We retain **`turn2` = [Model turn](model_turn(model=`model`, prompt=`fp`, stream=`stream`, echo=`echo`))**. + We retain **`reply` = [Read the text field](json.get(value=`turn2`, key="text"))**. + We retain **`c` = [Read the llm_calls field](json.get(value=`turn2`, key="llm_calls"))**. + We retain **`t` = [Read the tokens field](json.get(value=`turn2`, key="tokens"))**. 1. not `c` - **c = 0** + We retain **c = 0**. 2. * **_ = 1** 1. not `t` - **t = 0** + We retain **t = 0**. 2. * **_ = 1** - **llm_calls = llm_calls + c** - **tokens = tokens + t** - **out = table.put in=`out` at="tool" value=`tool_name`** - **out = table.put in=`out` at="tool_result" value=`tool_s`** - **out = table.put in=`out` at="result" value=`reply`** + We retain **llm_calls = llm_calls + c**. + We retain **tokens = tokens + t**. + We retain **`out` = [Set the tool field in the new record](table.put(in=`out`, at="tool", value=`tool_name`))**. + We retain **`out` = [Set the tool_result field in the new record](table.put(in=`out`, at="tool_result", value=`tool_s`))**. + We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. 2. * - **out = table.put in=`out` at="result" value=`reply`** + We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`reply`))**. -**out = table.put in=`out` at="llm_calls" value=`llm_calls`** -**out = table.put in=`out` at="tokens" value=`tokens`** +We retain **`out` = [Set the llm_calls field in the new record](table.put(in=`out`, at="llm_calls", value=`llm_calls`))**. +We retain **`out` = [Set the tokens field in the new record](table.put(in=`out`, at="tokens", value=`tokens`))**. 1. `sandbox` - **prof = sandbox.profile name=`sandbox_profile`** - **out = table.put in=`out` at="sandbox_profile" value=`prof`** + We retain **`prof` = [Profile](sandbox.profile(name=`sandbox_profile`))**. + We retain **`out` = [Set the sandbox_profile field in the new record](table.put(in=`out`, at="sandbox_profile", value=`prof`))**. 2. * **_ = 1** @@ -3083,120 +4421,174 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st |------|---------| | assistant | `reply` | -> agent_history_append id=`id` item=`as_turn` +We **[Append this item to the new list](agent_history_append(id=`id`, item=`as_turn`))**. 1. `writeback` - **body = > json.stringify value=`out`** - **st = > json.get value=`out` key="status"** + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We retain **`st` = [Read the status field](json.get(value=`out`, key="status"))**. 1. `st` == "ok" - > wb.record value=`body` key="ok" + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * - > wb.record value=`body` key="error" + We **[Record](wb.record(value=`body`, key="error"))**. 2. * **_ = 1** -*out* +Return *out*. ## preflight - + `task` - + `root`="." - + `marqdo_dir`=None - + `min_candidates`=3 - + `allow_create_after`=2 - + `reuse_threshold`=0.72 - + `adapt_threshold`=0.45 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| root | any | "." | Explicit root directory for discovery or isolated execution | +| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | +| min_candidates | any | 3 | Minimum reusable candidates to seek before adaptation | +| allow_create_after | any | 2 | Number of bounded attempts before new work may be proposed | +| reuse_threshold | any | 0.72 | Score required to choose reuse | +| adapt_threshold | any | 0.45 | Score required to choose adaptation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Engineering First Information gate (008 / EKC). Reads compiled `.marqdo` knowledge. Returns `{status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}`. Hard rule: generate only when `create_allowed` is true (or decision is REUSE/ADAPT). | + +Use `task`, `root`=".", `marqdo_dir`=None, `min_candidates`=3, `allow_create_after`=2, `reuse_threshold`=0.72, `adapt_threshold`=0.45 as the inputs for this operation. Engineering First Information gate (008 / EKC). Reads compiled `.marqdo` knowledge. Returns `{status,decision,create_allowed,existing,constraints,decisions,failures,recommended,context_path}`. Hard rule: generate only when `create_allowed` is true (or decision is REUSE/ADAPT). 1. `marqdo_dir` - **pf = > agent_eng_preflight task=`task` root=`root` marqdo_dir=`marqdo_dir` min_candidates=`min_candidates` allow_create_after=`allow_create_after` reuse_threshold=`reuse_threshold` adapt_threshold=`adapt_threshold`** + We retain **`pf` = [Eng preflight](agent_eng_preflight(task=`task`, root=`root`, marqdo_dir=`marqdo_dir`, min_candidates=`min_candidates`, allow_create_after=`allow_create_after`, reuse_threshold=`reuse_threshold`, adapt_threshold=`adapt_threshold`))**. 2. * - **pf = > agent_eng_preflight task=`task` root=`root` min_candidates=`min_candidates` allow_create_after=`allow_create_after` reuse_threshold=`reuse_threshold` adapt_threshold=`adapt_threshold`** + We retain **`pf` = [Eng preflight](agent_eng_preflight(task=`task`, root=`root`, min_candidates=`min_candidates`, allow_create_after=`allow_create_after`, reuse_threshold=`reuse_threshold`, adapt_threshold=`adapt_threshold`))**. -*pf* +Return *pf*. ## eng_reuse - + `task` - + `root`="." - + `marqdo_dir`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| task | any | required | Structured task or text supplied to the agent | +| root | any | "." | Explicit root directory for discovery or isolated execution | +| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Alias of `preflight` focused on REUSE / ADAPT / CREATE payload (discovery_only). | + +Use `task`, `root`=".", `marqdo_dir`=None as the inputs for this operation. Alias of `preflight` focused on REUSE / ADAPT / CREATE payload (discovery_only). 1. `marqdo_dir` - *> agent_eng_reuse task=`task` root=`root` marqdo_dir=`marqdo_dir`* + Return *[Eng reuse](agent_eng_reuse(task=`task`, root=`root`, marqdo_dir=`marqdo_dir`))*. 2. * - *> agent_eng_reuse task=`task` root=`root`* + Return *[Eng reuse](agent_eng_reuse(task=`task`, root=`root`))*. --- ## eng_bind_execute - + `project`="." - + `query` - + `policy`="pure" - + `inputs`=None - + `candidate_only`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| project | any | "." | Project root or project metadata | +| query | any | required | Text used to search the bounded catalog or tool registry | +| policy | any | "pure" | Policy data governing this operation | +| inputs | any | None | Structured input record for the bound engineering capability | +| candidate_only | any | False | Whether to retain a candidate without publishing it | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | M04: discover → bind → execute → record. Prefer over treating eng_reuse scores as execution. | + +Use `project`=".", `query`, `policy`="pure", `inputs`=None, `candidate_only`=False as the inputs for this operation. M04: discover → bind → execute → record. Prefer over treating eng_reuse scores as execution. 1. `inputs` - *> agent_eng_bind_execute project=`project` query=`query` policy=`policy` inputs=`inputs` candidate_only=`candidate_only`* + Return *[Eng bind execute](agent_eng_bind_execute(project=`project`, query=`query`, policy=`policy`, inputs=`inputs`, candidate_only=`candidate_only`))*. 2. * - *> agent_eng_bind_execute project=`project` query=`query` policy=`policy` candidate_only=`candidate_only`* + Return *[Eng bind execute](agent_eng_bind_execute(project=`project`, query=`query`, policy=`policy`, candidate_only=`candidate_only`))*. --- ## eng_publish_gate - + `project`="." - + `artifact_id`=None - + `candidate_only`=False - + `product_gate_ok`=True - + `policy`="business" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| project | any | "." | Project root or project metadata | +| artifact_id | any | None | Resolved artifact identifier from the compiler/catalog | +| candidate_only | any | False | Whether to retain a candidate without publishing it | +| product_gate_ok | any | True | Result of the external product gate | +| policy | any | "business" | Policy data governing this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Refuse promote when candidate_only or product/verification gate fails. | + +Use `project`=".", `artifact_id`=None, `candidate_only`=False, `product_gate_ok`=True, `policy`="business" as the inputs for this operation. Refuse promote when candidate_only or product/verification gate fails. -*> agent_eng_publish_gate project=`project` artifact_id=`artifact_id` candidate_only=`candidate_only` product_gate_ok=`product_gate_ok` policy=`policy`* +Return *[Eng publish gate](agent_eng_publish_gate(project=`project`, artifact_id=`artifact_id`, candidate_only=`candidate_only`, product_gate_ok=`product_gate_ok`, policy=`policy`))*. ## eng_record - + `decision` - + `root`="." - + `marqdo_dir`=None - + `duplicated`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| decision | any | required | Structured planning decision | +| root | any | "." | Explicit root directory for discovery or isolated execution | +| marqdo_dir | any | None | Marqdo project directory used for engineering discovery | +| duplicated | any | False | Whether a duplicate capability was detected | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Record REUSE/ADAPT/CREATE into `.marqdo/agent/episodes/reuse_metrics.json`. | + +Use `decision`, `root`=".", `marqdo_dir`=None, `duplicated`=False as the inputs for this operation. Record REUSE/ADAPT/CREATE into `.marqdo/agent/episodes/reuse_metrics.json`. 1. `marqdo_dir` - *> agent_eng_record decision=`decision` root=`root` marqdo_dir=`marqdo_dir` duplicated=`duplicated`* + Return *[Eng record](agent_eng_record(decision=`decision`, root=`root`, marqdo_dir=`marqdo_dir`, duplicated=`duplicated`))*. 2. * - *> agent_eng_record decision=`decision` root=`root` duplicated=`duplicated`* + Return *[Eng record](agent_eng_record(decision=`decision`, root=`root`, duplicated=`duplicated`))*. ## plan - + `goal` - + `workbook_dir`=None - + `workbook`=None - + `max_rounds`=4 - + `confirm`=False - + `writeback`=True - + `skeleton`=single - + `reuse`=True - + `optimize`=False - + `force`=False - + `soft_match`=False - + `near_match`=True - + `near_threshold`=0.78 - + `promote`=True - + `kb_dir`=.marqdo/agent-kb - + `improve_every`=3 - + `explore_n`=3 - + `stream`=False - + `echo`=False - + `trace`=False - + `resume_id`=None - + `resume_dir`=.marqdo/agent-resume - + `eng_preflight`=False - + `marqdo_dir`=.marqdo - + `allow_create_after`=2 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| goal | any | required | Human task goal represented by this operation | +| workbook_dir | any | None | Directory in which the planner owns its workbook files | +| workbook | any | None | Workbook path or structured workbook reference | +| max_rounds | any | 4 | Maximum workbook planning rounds | +| confirm | any | False | Whether decomposition confirmation is requested | +| writeback | any | True | Whether to write the observation back to its author document | +| skeleton | any | "single" | Workbook source template to instantiate | +| reuse | any | True | Whether to search for reusable knowledge before new work | +| optimize | any | False | Whether to run the documented improvement path | +| force | any | False | Explicit override supported by this operation; it does not bypass host authorization | +| soft_match | any | False | Whether bounded soft matching is enabled | +| near_match | any | True | Whether to consider near-match candidates | +| near_threshold | any | 0.78 | Minimum similarity score for near-match candidates | +| promote | any | True | Whether successful evidence may be promoted | +| kb_dir | any | ".marqdo/agent-kb" | Knowledge-library directory used for discovery and writeback | +| improve_every | any | 3 | Number of observations between improvement attempts | +| explore_n | any | 3 | Maximum configured exploration attempts | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| trace | any | False | Whether to retain the documented execution trace | +| resume_id | any | None | Identifier of the stored continuation checkpoint | +| resume_dir | any | ".marqdo/agent-resume" | Directory holding continuation checkpoints | +| eng_preflight | any | False | Whether to run engineering reuse preflight | +| marqdo_dir | any | ".marqdo" | Marqdo project directory used for engineering discovery | +| allow_create_after | any | 2 | Number of bounded attempts before new work may be proposed | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/.mq.md`. While task file count `< explore_n` and skill is not llm_free, force a new explore variant under `kb_dir/explore//`. Code-first: llm_free hits skip parent LLM. File children return via `# main`; `plan` exposes that as `result`. Engineering Knowledge preflight when `eng_preflight=True`: REUSE/ADAPT preferred; CREATE only if `create_allowed`. Production agents should enable this; tests that only exercise agent-kb may leave it false. Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when `near_match=True` and score ≥ `near_threshold`. Non-hit path: optional `soft_match=True` parent REUSE/NEW over ranked `agent_kb_near_match` candidates; else decompose before first child spawn (`DECISION: RUN` / `CONTINUE`+patch / solidified `DONE`). Then `await` → revise loop. Process events (`decision` / `round` / `done` / tools) are always attached on the result map for audit and view process cards; `stream=True` additionally SSE-publishes them (and parent `delta`). `echo=True` prints `plan:decompose` / `plan:await` / deltas. `trace=True` writes events to writeback slot `trace`. Quiet child subtasks stay quiet. | + +Use `goal`, `workbook_dir`=None, `workbook`=None, `max_rounds`=4, `confirm`=False, `writeback`=True, `skeleton`="single", `reuse`=True, `optimize`=False, `force`=False, `soft_match`=False, `near_match`=True, `near_threshold`=0.78, `promote`=True, `kb_dir`=".marqdo/agent-kb", `improve_every`=3, `explore_n`=3, `stream`=False, `echo`=False, `trace`=False, `resume_id`=None, `resume_dir`=".marqdo/agent-resume", `eng_preflight`=False, `marqdo_dir`=".marqdo", `allow_create_after`=2 as the inputs for this operation. Multi-step with OKF agent-kb. Default workbook is `kb_dir/resources/.mq.md`. While task file count `< explore_n` and skill is not llm_free, force a new explore variant under `kb_dir/explore//`. Code-first: llm_free hits skip parent LLM. File children return via `# main`; `plan` exposes that as `result`. @@ -3204,85 +4596,120 @@ Engineering Knowledge preflight when `eng_preflight=True`: REUSE/ADAPT preferred Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when `near_match=True` and score ≥ `near_threshold`. Non-hit path: optional `soft_match=True` parent REUSE/NEW over ranked `agent_kb_near_match` candidates; else decompose before first child spawn (`DECISION: RUN` / `CONTINUE`+patch / solidified `DONE`). Then `await` → revise loop. Process events (`decision` / `round` / `done` / tools) are always attached on the result map for audit and view process cards; `stream=True` additionally SSE-publishes them (and parent `delta`). `echo=True` prints `plan:decompose` / `plan:await` / deltas. `trace=True` writes events to writeback slot `trace`. Quiet child subtasks stay quiet. -**tools = > json.get value=`self` key="tools"** -**cache = "miss"** -**path = None** -**improve = None** -**explore = None** -**explore_attempt = None** -**skel_kind = skeleton** -**events = > table.empty_list** -**eng = None** +This method coordinates a workbook lifecycle. The workbook is an ordinary executable document with a main entry, not a private planner data format. The parent proposes decisions and short repairs; the runtime writes or awaits source, captures an observation and returns the child's actual value. Choose this method when reuse and a bounded revise loop are appropriate. Choose step for a single model turn with an optional tool. + +The first gate can consult engineering knowledge. REUSE and ADAPT are recorded as such; creating new work requires the configured create decision. A missing knowledge store is a separate state from an explicit denial. This gate does not manufacture a candidate merely to satisfy a minimum count. Callers should retain its diagnostics when deciding whether their project has enough reusable context. + +Knowledge lookup then establishes the resource and cache state. Exact, alias and canonical matches are tried before optional near matches. A similarity threshold filters candidates but does not prove semantic equivalence. An llm_free resource can execute through the existing code path without a parent model. The returned cache, match and resource fields let the application explain which path was chosen and inspect the source that ran. + +Exploration uses owned workbook files. With no explicit workbook path, the configured knowledge directory supplies the resource location; bounded variants live under its exploration subtree. The exploration count controls attempts to establish useful reusable evidence. It should not be confused with the maximum revision rounds of one workbook. Keep both directory ownership and attempt accounting intact when changing the planner. + +An optional soft-match turn compares existing candidates and produces either REUSE with a concrete slug or NEW. The reply is parsed and resolved before execution. It cannot authorize an invented slug or silently replace a failed child with model prose. When reuse does not yield a result, the chosen single-worker or dual-worker template provides a starting document, with the goal embedded as quoted data. + +Before the first child execution, decomposition asks whether that starting document is sufficient. RUN accepts the structure. CONTINUE supplies a bounded source patch, and evidence requests go through the restricted parent tool dispatcher. DONE belongs to the existing solidification path and must have a usable value. Rewriting already valid imports is not itself progress toward the user's goal. + +Child execution is awaited before revision. The observation contains process status, returned value, slots and bounded output; the parent prompt uses a compact projection so large logs do not drown out the next repair. If the child fails or its value is unsuitable, a short patch can be applied and another round attempted. Exhausting the round budget is reported by the result path, rather than hidden behind a fabricated successful answer. + +The confirm option concerns the decomposition stage; it is not a substitute for host permissions. File creation, source patches, subprocess execution and model transport retain their own effect boundaries. Quiet subtasks remain quiet. Turning on echo changes incremental terminal output, while stream publishes process events. Neither option changes the requirement to inspect the final structured result. + +Events are retained for audit even when streaming is disabled. Decisions, rounds and completion events describe the work that actually ran. Trace writeback is separately controlled, and normal writeback stores the result at its source call site. Consumers should use these fields to diagnose a plan instead of scraping console messages or assuming every emitted event represents a completed child. + +Successful outcomes may be promoted through the knowledge mechanism when enabled. Promotion preserves the workbook as inspectable source and uses the configured evidence process; generating a file alone is not compilation into a trusted skill. Optimization and force options select existing improvement behavior, while the regular reuse gates remain visible in the outcome. A later author can open the resulting resource and reproduce its invocation. + +With a resume identifier, checkpoint records connect the goal, round, workbook and result to a logical run. The checkpoint is continuation data, not a replay authorization for uncertain external writes. Tools with effects still use their own ledger and reconciliation rules. Preserve these references when integrating a scheduler or another application so continuation does not duplicate work that already committed. + +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. +We retain **cache = "miss"**. +We retain **path = None**. +We retain **improve = None**. +We retain **explore = None**. +We retain **explore_attempt = None**. +We retain **skel_kind = skeleton**. +We retain **`events` = [Empty list](table.empty_list())**. +We retain **eng = None**. 1. `eng_preflight` - **eng = > agent_eng_preflight task=`goal` marqdo_dir=`marqdo_dir` allow_create_after=`allow_create_after`** - **eng_status = > json.get value=`eng` key="status"** - **eng_decision = > json.get value=`eng` key="decision"** - **eng_allowed = > json.get value=`eng` key="create_allowed"** + We retain **`eng` = [Eng preflight](agent_eng_preflight(task=`goal`, marqdo_dir=`marqdo_dir`, allow_create_after=`allow_create_after`))**. + We retain **`eng_status` = [Read the status field](json.get(value=`eng`, key="status"))**. + We retain **`eng_decision` = [Read the decision field](json.get(value=`eng`, key="decision"))**. + We retain **`eng_allowed` = [Read the create_allowed field](json.get(value=`eng`, key="create_allowed"))**. 1. `eng_status` == missing_knowledge **_ = 1** 2. `eng_decision` == REUSE - > agent_eng_record decision="REUSE" marqdo_dir=`marqdo_dir` + We **[Eng record](agent_eng_record(decision="REUSE", marqdo_dir=`marqdo_dir`))**. **_ = 1** 3. `eng_decision` == ADAPT - > agent_eng_record decision="ADAPT" marqdo_dir=`marqdo_dir` + We **[Eng record](agent_eng_record(decision="ADAPT", marqdo_dir=`marqdo_dir`))**. **_ = 1** 4. `eng_allowed` - > agent_eng_record decision="CREATE" marqdo_dir=`marqdo_dir` + We **[Eng record](agent_eng_record(decision="CREATE", marqdo_dir=`marqdo_dir`))**. **_ = 1** 5. * + `out` = | status | cache | eng | decision | preflight | events | |--------|-------|-----|----------|-----------|--------| | blocked | eng-block | true | BLOCKED | `eng` | `events` | - *out* + Return *out*. 2. * **_ = 1** -**tf = > agent_kb_task_files kb_dir=`kb_dir` goal=`goal` tools=`tools`** -**nfiles = > json.get value=`tf` key="count"** +We retain **`tf` = [Kb task files](agent_kb_task_files(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`))**. +We retain **`nfiles` = [Read the count field](json.get(value=`tf`, key="count"))**. 1. `force` **_ = 1** 2. `optimize` **_ = 1** 3. `reuse` - **hit = > agent_kb_lookup kb_dir=`kb_dir` goal=`goal` tools=`tools` near_match=`near_match` near_threshold=`near_threshold`** + We retain **`hit` = [Kb lookup](agent_kb_lookup(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, near_match=`near_match`, near_threshold=`near_threshold`))**. 1. `hit` - **match_kind = > json.get value=`hit` key="match"** + We retain **`match_kind` = [Read the match field](json.get(value=`hit`, key="match"))**. 1. `match_kind` == alias - **cache_label = "soft-hit"** + We retain **cache_label = "soft-hit"**. 2. `match_kind` == canonical - **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` + We retain **cache_label = "soft-hit"**. + We retain **`hit_slug` = [Read the slug field](json.get(value=`hit`, key="slug"))**. + We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`hit_slug`, alias=`goal`))**. 3. `match_kind` == near - **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` + We retain **cache_label = "soft-hit"**. + We retain **`hit_slug` = [Read the slug field](json.get(value=`hit`, key="slug"))**. + We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`hit_slug`, alias=`goal`))**. 4. `match_kind` == soft - **cache_label = "soft-hit"** + We retain **cache_label = "soft-hit"**. 5. * - **cache_label = "hit"** - **lf = > json.get value=`hit` key="llm_free"** + We retain **cache_label = "hit"**. + We retain **`lf` = [Read the llm_free field](json.get(value=`hit`, key="llm_free"))**. 1. `lf` - **path = > json.get value=`hit` key="resource"** - **aw = > await_workbook path=`path`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](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 = cache_label** - **hit_score = > json.get value=`hit` key="score"** - **sk = > json.get value=`hit` key="skill"** - **st = > json.get value=`hit` key="status"** - **sum = > json.parse text={"a":"OKF llm_free skill hit (","b":"); spawned resource"}** - **suma = > json.get value=`sum` key="a"** - **sumb = > json.get value=`sum` key="b"** - **sum = suma + match_kind + sumb** + We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. + We retain **cache = cache_label**. + We retain **`hit_score` = [Read the score field](json.get(value=`hit`, key="score"))**. + We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. + We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. + The following record names each literal field without a JSON construction chain. + + `_literal_sum_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "OKF llm_free skill hit (" | + | 2 | "b" | "); spawned resource" | + + We build **sum = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_sum_fields`))**. + + + We retain **`suma` = [Read the a field](json.get(value=`sum`, key="a"))**. + We retain **`sumb` = [Read the b field](json.get(value=`sum`, key="b"))**. + We retain **sum = suma + match_kind + sumb**. + `out` = | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | @@ -3290,50 +4717,62 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` | ok | `goal` | `path` | 1 | `cache_label` | `match_kind` | `sk` | `st` | `sum` | `last_obs` | `child_val` | 1. `hit_score` - **out = table.put in=`out` at="score" value=`hit_score`** + We retain **`out` = [Set the score field in the new record](table.put(in=`out`, at="score", value=`hit_score`))**. 2. * **_ = 1** - **events = > plan_append_decision events=`events` decision="REUSE" stream=`stream` summary=`sum`** - **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`** + We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. + We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. 1. `writeback` - **body = > json.stringify value=`out`** - > wb.record value=`body` key="ok" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * **_ = 1** - **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`** - *out* + We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. + Return *out*. 2. * - **path = None** + We retain **path = None**. 2. `nfiles` < `explore_n` - **explore = 1** - **cache = "explore"** - **path = None** - **explore_attempt = nfiles + 1** + We retain **explore = 1**. + We retain **cache = "explore"**. + We retain **path = None**. + We retain **explore_attempt = nfiles + 1**. 1. `explore_attempt` == 2 - **skel_kind = "dual"** + We retain **skel_kind = "dual"**. 2. * - **skel_kind = skeleton** + We retain **skel_kind = skeleton**. 3. * - **path = > json.get value=`hit` key="resource"** - **aw = > await_workbook path=`path`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. 1. `code` == 0 - **rec = > agent_kb_record_hit kb_dir=`kb_dir` goal=`goal` tools=`tools` improve_every=`improve_every`** - **due = > json.get value=`rec` key="improve_due"** + We retain **`rec` = [Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. + We retain **`due` = [Read the improve_due field](json.get(value=`rec`, key="improve_due"))**. 1. `due` - **improve = 1** - **cache = "improve"** + We retain **improve = 1**. + We retain **cache = "improve"**. 2. * - **cache = cache_label** - **hit_score = > json.get value=`hit` key="score"** - **sk = > json.get value=`hit` key="skill"** - **st = > json.get value=`hit` key="status"** - **sum = > json.parse text={"a":"OKF skill hit (","b":"); spawned resource"}** - **suma = > json.get value=`sum` key="a"** - **sumb = > json.get value=`sum` key="b"** - **sum = suma + match_kind + sumb** + We retain **cache = cache_label**. + We retain **`hit_score` = [Read the score field](json.get(value=`hit`, key="score"))**. + We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. + We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. + The following record names each literal field without a JSON construction chain. + + `_literal_sum_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "OKF skill hit (" | + | 2 | "b" | "); spawned resource" | + + We build **sum = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_sum_fields`))**. + + + We retain **`suma` = [Read the a field](json.get(value=`sum`, key="a"))**. + We retain **`sumb` = [Read the b field](json.get(value=`sum`, key="b"))**. + We retain **sum = suma + match_kind + sumb**. + `out` = | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | @@ -3341,78 +4780,79 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` | ok | `goal` | `path` | 1 | `cache_label` | `match_kind` | `sk` | `st` | `sum` | `last_obs` | `child_val` | 1. `hit_score` - **out = table.put in=`out` at="score" value=`hit_score`** + We retain **`out` = [Set the score field in the new record](table.put(in=`out`, at="score", value=`hit_score`))**. 2. * **_ = 1** - **events = > plan_append_decision events=`events` decision="REUSE" stream=`stream` summary=`sum`** - **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`** + We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. + We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. 1. `writeback` - **body = > json.stringify value=`out`** - > wb.record value=`body` key="ok" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * **_ = 1** - **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`** - *out* + We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. + Return *out*. 2. * - **path = None** + We retain **path = None**. 2. * 1. `soft_match` - **near = > agent_kb_near_match kb_dir=`kb_dir` goal=`goal`** - **tasks = > json.get value=`near` key="candidates"** - **tn = > len value=`tasks`** + We retain **`near` = [Kb near match](agent_kb_near_match(kb_dir=`kb_dir`, goal=`goal`))**. + We retain **`tasks` = [Read the candidates field](json.get(value=`near`, key="candidates"))**. + We retain **`tn` = [Len](len(value=`tasks`))**. 1. `tn` < 1 - **listed = > agent_kb_list_tasks kb_dir=`kb_dir`** - **tasks = > json.get value=`listed` key="tasks"** - **tn = > len value=`tasks`** + We retain **`listed` = [Kb list tasks](agent_kb_list_tasks(kb_dir=`kb_dir`))**. + We retain **`tasks` = [Read the tasks field](json.get(value=`listed`, key="tasks"))**. + We retain **`tn` = [Len](len(value=`tasks`))**. 2. * **_ = 1** 1. `tn` > 0 - **soft_prompt = > build_soft_match_prompt goal=`goal` tasks=`tasks`** - **model = > json.get value=`self` key="model"** + We retain **`soft_prompt` = [Build soft match prompt](build_soft_match_prompt(goal=`goal`, tasks=`tasks`))**. + We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. 1. `stream` - **evs = > model.stream prompt=`soft_prompt` echo=`echo`** - **soft_reply = > llm.collect events=`evs`** - **events = > plan_merge_deltas events=`events` from=`evs` stream=`stream`** + We retain **`evs` = [Stream](model.stream(prompt=`soft_prompt`, echo=`echo`))**. + We retain **`soft_reply` = [Collect](llm.collect(events=`evs`))**. + We retain **`events` = [Plan merge deltas](plan_merge_deltas(events=`events`, from=`evs`, stream=`stream`))**. 2. * - **soft_turn = > model_turn model=`model` prompt=`soft_prompt` stream=False echo=`echo`** - **soft_reply = > json.get value=`soft_turn` key="text"** - **soft_reply = > trim value=`soft_reply`** - **soft_dec = > extract_plan_decision reply=`soft_reply`** - **events = > plan_append_decision events=`events` decision=`soft_dec` stream=`stream`** + We retain **`soft_turn` = [Model turn](model_turn(model=`model`, prompt=`soft_prompt`, stream=False, echo=`echo`))**. + We retain **`soft_reply` = [Read the text field](json.get(value=`soft_turn`, key="text"))**. + We retain **`soft_reply` = [Trim](trim(value=`soft_reply`))**. + We retain **`soft_dec` = [Extract plan decision](extract_plan_decision(reply=`soft_reply`))**. + We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision=`soft_dec`, stream=`stream`))**. 1. `soft_dec` == REUSE - **reuse_slug = > extract_soft_match_slug reply=`soft_reply`** + We retain **`reuse_slug` = [Extract soft match slug](extract_soft_match_slug(reply=`soft_reply`))**. 1. `reuse_slug` - **hit = > agent_kb_lookup kb_dir=`kb_dir` slug=`reuse_slug` goal=`goal` tools=`tools`** + We retain **`hit` = [Kb lookup](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"** - **path = > json.get value=`hit` key="resource"** - **aw = > await_workbook path=`path`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** + We **[Kb add alias](agent_kb_add_alias(kb_dir=`kb_dir`, slug=`reuse_slug`, alias=`goal`))**. + We retain **cache_label = "soft-hit"**. + We retain **`path` = [Read the resource field](json.get(value=`hit`, key="resource"))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](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"** - **sk = > json.get value=`hit` key="skill"** - **st = > json.get value=`hit` key="status"** - **sum = "OKF soft_match REUSE; spawned resource"** + We **[Kb record hit](agent_kb_record_hit(kb_dir=`kb_dir`, goal=`goal`, tools=`tools`, improve_every=`improve_every`))**. + We retain **cache = "soft-hit"**. + We retain **`sk` = [Read the skill field](json.get(value=`hit`, key="skill"))**. + We retain **`st` = [Read the status field](json.get(value=`hit`, key="status"))**. + We retain **sum = "OKF soft_match REUSE; spawned resource"**. + `out` = | status | goal | workbook | rounds | cache | match | skill | skill_status | summary | observation | result | |--------|------|----------|--------|-------|-------|-------|--------------|---------|-------------|--------| | ok | `goal` | `path` | 1 | soft-hit | soft | `sk` | `st` | `sum` | `last_obs` | `child_val` | - **events = > plan_append_decision events=`events` decision="REUSE" stream=`stream` summary=`sum`** - **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`** + We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision="REUSE", stream=`stream`, summary=`sum`))**. + We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=1, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. 1. `writeback` - **body = > json.stringify value=`out`** - > wb.record value=`body` key="ok" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * **_ = 1** - **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`** - *out* + We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`child_val`))**. + Return *out*. 2. * - **path = None** + We retain **path = None**. 2. * **_ = 1** 2. * @@ -3424,160 +4864,196 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` 2. * **_ = 1** 1. `nfiles` < `explore_n` - **explore = 1** - **cache = "explore"** - **explore_attempt = nfiles + 1** + We retain **explore = 1**. + We retain **cache = "explore"**. + We retain **explore_attempt = nfiles + 1**. 1. `explore_attempt` == 2 - **skel_kind = "dual"** + We retain **skel_kind = "dual"**. 2. * - **skel_kind = skeleton** + We retain **skel_kind = skeleton**. 2. * **_ = 1** 4. * 1. `nfiles` < `explore_n` - **explore = 1** - **cache = "explore"** - **explore_attempt = nfiles + 1** + We retain **explore = 1**. + We retain **cache = "explore"**. + We retain **explore_attempt = nfiles + 1**. 2. * **_ = 1** -**skel = > render_workbook_skeleton goal=`goal` skeleton=`skel_kind`** +We retain **`skel` = [Render workbook skeleton](render_workbook_skeleton(goal=`goal`, skeleton=`skel_kind`))**. 1. `workbook` - **path = workbook** - **ex = > fs.exists path=`path`** + We retain **path = workbook**. + We retain **`ex` = [Exists](fs.exists(path=`path`))**. 1. `ex` **_ = 1** 2. * - > fs.write_text path=`path` text=`skel` + We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. 2. * 1. `path` **_ = 1** 2. * - **slug = > agent_goal_slug goal=`goal`** + We retain **`slug` = [Goal slug](agent_goal_slug(goal=`goal`))**. 1. `workbook_dir` - > fs.make_dir path=`workbook_dir` - **ts = > time.now_ms** - **parts = > json.parse text={"a":"/workbook-","b":"-","c":".mq.md"}** - **a = > json.get value=`parts` key="a"** - **b = > json.get value=`parts` key="b"** - **c = > json.get value=`parts` key="c"** - **path = workbook_dir + a + slug + b + ts + c** - > fs.write_text path=`path` text=`skel` + We **[Make dir](fs.make_dir(path=`workbook_dir`))**. + We retain **`ts` = [Now ms](time.now_ms())**. + The following record names each literal field without a JSON construction chain. + + `_literal_parts_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "/workbook-" | + | 2 | "b" | "-" | + | 3 | "c" | ".mq.md" | + + We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. + + + We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. + We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. + We retain **`c` = [Read the c field](json.get(value=`parts`, key="c"))**. + We retain **path = workbook_dir + a + slug + b + ts + c**. + We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. 2. `explore` - **parts = > json.parse text={"a":"/explore/","b":"/","c":".mq.md"}** - **a = > json.get value=`parts` key="a"** - **b = > json.get value=`parts` key="b"** - **c = > json.get value=`parts` key="c"** - **path = kb_dir + a + slug + b + explore_attempt + c** - **ex = > fs.exists path=`path`** + The following record names each literal field without a JSON construction chain. + + `_literal_parts_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "/explore/" | + | 2 | "b" | "/" | + | 3 | "c" | ".mq.md" | + + We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. + + + We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. + We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. + We retain **`c` = [Read the c field](json.get(value=`parts`, key="c"))**. + We retain **path = kb_dir + a + slug + b + explore_attempt + c**. + We retain **`ex` = [Exists](fs.exists(path=`path`))**. 1. `ex` **_ = 1** 2. * - > fs.write_text path=`path` text=`skel` + We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. 3. * - **parts = > json.parse text={"a":"/resources/","b":".mq.md"}** - **a = > json.get value=`parts` key="a"** - **b = > json.get value=`parts` key="b"** - **path = kb_dir + a + slug + b** - **ex = > fs.exists path=`path`** + The following record names each literal field without a JSON construction chain. + + `_literal_parts_fields` = + + | @ | key | value | + |---|---|---| + | 1 | "a" | "/resources/" | + | 2 | "b" | ".mq.md" | + + We build **parts = [Collect these named fields into one record](table.from_pairs(pairs=`_literal_parts_fields`))**. + + + We retain **`a` = [Read the a field](json.get(value=`parts`, key="a"))**. + We retain **`b` = [Read the b field](json.get(value=`parts`, key="b"))**. + We retain **path = kb_dir + a + slug + b**. + We retain **`ex` = [Exists](fs.exists(path=`path`))**. 1. `ex` **_ = 1** 2. * - > fs.write_text path=`path` text=`skel` + We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`skel`))**. 1. `confirm` + `out` = | status | goal | workbook | summary | cache | |--------|------|----------|---------|-------| | pending | `goal` | `path` | workbook created; confirm to run | bypass | 1. `writeback` - **body = > json.stringify value=`out`** - > wb.record value=`body` key="ok" + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * **_ = 1** - **out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace`** - *out* + We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`))**. + Return *out*. 2. * **_ = 1** -**model = > json.get value=`self` key="model"** -**round = 0** -**last_obs = None** -**last_reply = None** -**child_val = None** -**done = None** -**summary = None** -**status = "error"** -**err = "max_rounds exhausted"** -**skip_loop = None** -**plan_llm_calls = 0** -**plan_tokens = 0** +We retain **`model` = [Read the model field](json.get(value=`self`, key="model"))**. +We retain **round = 0**. +We retain **last_obs = None**. +We retain **last_reply = None**. +We retain **child_val = None**. +We retain **done = None**. +We retain **summary = None**. +We retain **status = "error"**. +We retain **err = "max_rounds exhausted"**. +We retain **skip_loop = None**. +We retain **plan_llm_calls = 0**. +We retain **plan_tokens = 0**. -> plan_echo_decompose workbook=`path` stream=`stream` echo=`echo` -**last_obs = > inspect_workbook path=`path`** -**turn = > plan_llm_act_loop agent=`self` goal=`goal` path=`path` observation=`last_obs` phase="decompose" explore_attempt=`explore_attempt` explore_n=`explore_n` stream=`stream` echo=`echo` events=`events`** -**turn_s = > json.stringify value=`turn`** -**turn_map = > text.starts_with text=`turn_s` prefix="{"** -**dec = None** -**last_reply = None** +We **[Plan echo decompose](plan_echo_decompose(workbook=`path`, stream=`stream`, echo=`echo`))**. +We retain **`last_obs` = [Inspect workbook](inspect_workbook(path=`path`))**. +We retain **`turn` = [Plan llm act loop](plan_llm_act_loop(agent=`self`, goal=`goal`, path=`path`, observation=`last_obs`, phase="decompose", explore_attempt=`explore_attempt`, explore_n=`explore_n`, stream=`stream`, echo=`echo`, events=`events`))**. +We retain **`turn_s` = [Encode the structured value as JSON text](json.stringify(value=`turn`))**. +We retain **`turn_map` = [Starts with](text.starts_with(text=`turn_s`, prefix="{"))**. +We retain **dec = None**. +We retain **last_reply = None**. 1. `turn_map` - **dec = > json.get value=`turn` key="decision"** - **last_reply = > json.get value=`turn` key="reply"** - **last_obs = > json.get value=`turn` key="observation"** - **events = > json.get value=`turn` key="events"** - **_c = > json.get value=`turn` key="llm_calls"** - **_t = > json.get value=`turn` key="tokens"** + We retain **`dec` = [Read the decision field](json.get(value=`turn`, key="decision"))**. + We retain **`last_reply` = [Read the reply field](json.get(value=`turn`, key="reply"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`turn`, key="observation"))**. + We retain **`events` = [Read the events field](json.get(value=`turn`, key="events"))**. + We retain **`_c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. + We retain **`_t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. 1. `_c` != None - **plan_llm_calls = plan_llm_calls + _c** + We retain **plan_llm_calls = plan_llm_calls + _c**. 1. `_t` != None - **plan_tokens = plan_tokens + _t** + We retain **plan_tokens = plan_tokens + _t**. 2. * - **dec = "TRANSPORT_ERROR"** - **last_reply = "plan_llm_act_loop_not_map"** - **err = `last_reply`** + We retain **dec = "TRANSPORT_ERROR"**. + We retain **last_reply = "plan_llm_act_loop_not_map"**. + We retain **err = `last_reply`**. 1. `dec` == "TRANSPORT_ERROR" - **done = 1** - **status = "error"** - **err = `last_reply`** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = `last_reply`**. 1. `turn_map` - **e2 = > json.get value=`turn` key="error"** + We retain **`e2` = [Read the error field](json.get(value=`turn`, key="error"))**. 1. `e2` - **err = `e2`** - **summary = "llm transport error"** - **skip_loop = 1** + We retain **err = `e2`**. + We retain **summary = "llm transport error"**. + We retain **skip_loop = 1**. 2. `dec` == CONTINUE - **n = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True** + We retain **`n` = [Apply patch blocks](fs.apply_patch_blocks(path=`path`, text=`last_reply`, soft=True))**. 1. `n` **_ = 1** 2. * - **done = 1** - **status = "error"** - **err = "no patches applied"** - **summary = > extract_plan_summary reply=`last_reply`** - **skip_loop = 1** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "no patches applied"**. + We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. + We retain **skip_loop = 1**. 3. `dec` == RUN **_ = 1** 4. `dec` == DONE - **has_step = > workbook_has_worker_step path=`path`** + We retain **`has_step` = [Workbook has worker step](workbook_has_worker_step(path=`path`))**. 1. `has_step` **_ = 1** 2. * - > plan_echo_await round=1 workbook=`path` stream=`stream` echo=`echo` - **aw = > await_workbook path=`path`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** - **round = 1** - **events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`** + We **[Plan echo await](plan_echo_await(round=1, workbook=`path`, stream=`stream`, echo=`echo`))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. + We retain **round = 1**. + We retain **`events` = [Plan append round](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"** - **summary = > extract_plan_summary reply=`last_reply`** - **err = None** - **skip_loop = 1** + We retain **done = 1**. + We retain **status = "ok"**. + We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. + We retain **err = None**. + We retain **skip_loop = 1**. 2. * **_ = 1** 5. * @@ -3585,123 +5061,123 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near` when there is prose — chat soft-recover depends on result/summary surviving. 1. `dec` == "unknown" 1. `last_reply` - **done = 1** - **status = "ok"** - **err = None** - **summary = `last_reply`** - **skip_loop = 1** + We retain **done = 1**. + We retain **status = "ok"**. + We retain **err = None**. + We retain **summary = `last_reply`**. + We retain **skip_loop = 1**. 2. * - **done = 1** - **status = "error"** - **err = "unrecognized plan decision"** - **summary = last_reply** - **skip_loop = 1** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "unrecognized plan decision"**. + We retain **summary = last_reply**. + We retain **skip_loop = 1**. 2. * - **done = 1** - **status = "error"** - **err = "unrecognized plan decision"** - **summary = last_reply** - **skip_loop = 1** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "unrecognized plan decision"**. + We retain **summary = last_reply**. + We retain **skip_loop = 1**. 1. `skip_loop` - **left = 0** + We retain **left = 0**. 2. `improve` - **left = 1** + We retain **left = 1**. 3. * - **left = max_rounds** + We retain **left = max_rounds**. - `left` > 0 1. `done` - **left = 0** + We retain **left = 0**. 2. * - **round = round + 1** - > plan_echo_await round=`round` workbook=`path` stream=`stream` echo=`echo` - **aw = > await_workbook path=`path`** - **code = > json.get value=`aw` key="code"** - **child_val = > json.get value=`aw` key="value"** - **last_obs = > json.get value=`aw` key="observation"** - **events = > plan_append_round events=`events` round=`round` workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`** + We retain **round = round + 1**. + We **[Plan echo await](plan_echo_await(round=`round`, workbook=`path`, stream=`stream`, echo=`echo`))**. + We retain **`aw` = [Await workbook](await_workbook(path=`path`))**. + We retain **`code` = [Read the code field](json.get(value=`aw`, key="code"))**. + We retain **`child_val` = [Read the value field](json.get(value=`aw`, key="value"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`aw`, key="observation"))**. + We retain **`events` = [Plan append round](plan_append_round(events=`events`, round=`round`, workbook=`path`, exit_code=`code`, result=`child_val`, stream=`stream`, echo=`echo`))**. Deterministic success stop (loop engineering): when the child already returned a value, do not ask the parent LLM to invent solidify patches — DONE + runtime solidify. 1. `code` == 0 1. `child_val` 1. `improve` - **auto_done = None** + We retain **auto_done = None**. 2. * - **auto_done = 1** + We retain **auto_done = 1**. 2. * - **auto_done = None** + We retain **auto_done = None**. 2. * - **auto_done = None** + We retain **auto_done = None**. 1. `auto_done` - > agent_workbook_solidify path=`path` observation=`last_obs` - **done = 1** - **status = "ok"** - **summary = "child returned value; solidified"** - **err = None** - **dec = "DONE"** - **events = > plan_append_decision events=`events` decision=`dec` stream=`stream` summary=`summary`** - **left = 0** + We **[Workbook solidify](agent_workbook_solidify(path=`path`, observation=`last_obs`))**. + We retain **done = 1**. + We retain **status = "ok"**. + We retain **summary = "child returned value; solidified"**. + We retain **err = None**. + We retain **dec = "DONE"**. + We retain **`events` = [Plan append decision](plan_append_decision(events=`events`, decision=`dec`, stream=`stream`, summary=`summary`))**. + We retain **left = 0**. 2. * - **turn = > plan_llm_act_loop agent=`self` goal=`goal` path=`path` observation=`last_obs` phase="revise" explore_attempt=`explore_attempt` explore_n=`explore_n` stream=`stream` echo=`echo` events=`events`** - **dec = > json.get value=`turn` key="decision"** - **last_reply = > json.get value=`turn` key="reply"** - **last_obs = > json.get value=`turn` key="observation"** - **events = > json.get value=`turn` key="events"** - **_c = > json.get value=`turn` key="llm_calls"** - **_t = > json.get value=`turn` key="tokens"** + We retain **`turn` = [Plan llm act loop](plan_llm_act_loop(agent=`self`, goal=`goal`, path=`path`, observation=`last_obs`, phase="revise", explore_attempt=`explore_attempt`, explore_n=`explore_n`, stream=`stream`, echo=`echo`, events=`events`))**. + We retain **`dec` = [Read the decision field](json.get(value=`turn`, key="decision"))**. + We retain **`last_reply` = [Read the reply field](json.get(value=`turn`, key="reply"))**. + We retain **`last_obs` = [Read the observation field](json.get(value=`turn`, key="observation"))**. + We retain **`events` = [Read the events field](json.get(value=`turn`, key="events"))**. + We retain **`_c` = [Read the llm_calls field](json.get(value=`turn`, key="llm_calls"))**. + We retain **`_t` = [Read the tokens field](json.get(value=`turn`, key="tokens"))**. 1. `_c` != None - **plan_llm_calls = plan_llm_calls + _c** + We retain **plan_llm_calls = plan_llm_calls + _c**. 1. `_t` != None - **plan_tokens = plan_tokens + _t** + We retain **plan_tokens = plan_tokens + _t**. 1. `dec` == DONE - > agent_workbook_solidify path=`path` observation=`last_obs` - **done = 1** - **status = "ok"** - **summary = > extract_plan_summary reply=`last_reply`** - **err = None** - **left = 0** + We **[Workbook solidify](agent_workbook_solidify(path=`path`, observation=`last_obs`))**. + We retain **done = 1**. + We retain **status = "ok"**. + We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. + We retain **err = None**. + We retain **left = 0**. 2. `dec` == CONTINUE - **n = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True** + We retain **`n` = [Apply patch blocks](fs.apply_patch_blocks(path=`path`, text=`last_reply`, soft=True))**. 1. `n` - **left = left - 1** + We retain **left = left - 1**. 2. * - **done = 1** - **status = "error"** - **err = "no patches applied"** - **summary = > extract_plan_summary reply=`last_reply`** - **left = 0** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "no patches applied"**. + We retain **`summary` = [Extract plan summary](extract_plan_summary(reply=`last_reply`))**. + We retain **left = 0**. 3. `dec` == RUN - **left = left - 1** + We retain **left = left - 1**. 4. * 1. `dec` == "unknown" 1. `last_reply` - **done = 1** - **status = "ok"** - **err = None** - **summary = `last_reply`** - **left = 0** + We retain **done = 1**. + We retain **status = "ok"**. + We retain **err = None**. + We retain **summary = `last_reply`**. + We retain **left = 0**. 2. * - **done = 1** - **status = "error"** - **err = "unrecognized plan decision"** - **summary = last_reply** - **left = 0** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "unrecognized plan decision"**. + We retain **summary = last_reply**. + We retain **left = 0**. 2. * - **done = 1** - **status = "error"** - **err = "unrecognized plan decision"** - **summary = last_reply** - **left = 0** + We retain **done = 1**. + We retain **status = "error"**. + We retain **err = "unrecognized plan decision"**. + We retain **summary = last_reply**. + We retain **left = 0**. 1. `status` == "ok" 1. `promote` - **prom = > agent_kb_promote kb_dir=`kb_dir` goal=`goal` workbook=`path` tools=`tools`** - **cache = "refreshed"** + We retain **`prom` = [Kb promote](agent_kb_promote(kb_dir=`kb_dir`, goal=`goal`, workbook=`path`, tools=`tools`))**. + We retain **cache = "refreshed"**. 2. * - **cache = "miss"** + We retain **cache = "miss"**. 2. * **_ = 1** @@ -3712,92 +5188,121 @@ Deterministic success stop (loop engineering): when the child already returned a | `status` | `goal` | `path` | `round` | `cache` | `plan_llm_calls` | `plan_tokens` | 1. `summary` - **out = table.put in=`out` at="summary" value=`summary`** + We retain **`out` = [Set the summary field in the new record](table.put(in=`out`, at="summary", value=`summary`))**. 2. * **_ = 1** 1. `err` - **out = table.put in=`out` at="error" value=`err`** + We retain **`out` = [Set the error field in the new record](table.put(in=`out`, at="error", value=`err`))**. 2. * **_ = 1** 1. `last_obs` - **out = table.put in=`out` at="observation" value=`last_obs`** + We retain **`out` = [Set the observation field in the new record](table.put(in=`out`, at="observation", value=`last_obs`))**. 2. * **_ = 1** 1. `child_val` - **out = table.put in=`out` at="result" value=`child_val`** - **plan_result = child_val** + We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`child_val`))**. + We retain **plan_result = child_val**. 2. `summary` - **out = table.put in=`out` at="result" value=`summary`** - **plan_result = summary** + We retain **`out` = [Set the result field in the new record](table.put(in=`out`, at="result", value=`summary`))**. + We retain **plan_result = summary**. 3. * - **plan_result = None** + We retain **plan_result = None**. 1. `writeback` - **body = > json.stringify value=`out`** + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`out`))**. 1. `status` == "ok" - > wb.record value=`body` key="ok" + We **[Record](wb.record(value=`body`, key="ok"))**. 2. * - > wb.record value=`body` key="error" + We **[Record](wb.record(value=`body`, key="error"))**. 2. * **_ = 1** -**out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`plan_result`** -*out* +We retain **`out` = [Plan finish stream](plan_finish_stream(out=`out`, events=`events`, stream=`stream`, trace=`trace`, result=`plan_result`))**. +Return *out*. --- # mcp_server - + `name`=marqdo + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | "marqdo" | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Minimal MCP Server host (stdio JSON-RPC / Streamable HTTP). Tools point at entry-module `lib.member` functions (same bridge as `ext/web` invoke). Evidence/results may carry `authority=workbook`. | + +Use `name`="marqdo" as the inputs for this operation. Minimal MCP Server host (stdio JSON-RPC / Streamable HTTP). Tools point at entry-module `lib.member` functions (same bridge as `ext/web` invoke). Evidence/results may carry `authority=workbook`. -**p = > plugin.native_path name="agent"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/agent: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. + +We retain **`tools0` = [Empty list](table.empty_list())**. -**tools0 = > table.empty_list** `h` = | _type | tools | name | |-------|-------|------| | mcp_server | `tools0` | `name` | -*h* +Return *h*. ## tool - + `name` - + `fn` - + `description`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| fn | any | required | Registered function target | +| description | any | "" | Human-readable tool description | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Register one tool. `fn` must be `lib.member` imported on the entry workbook. | + +Use `name`, `fn`, `description`="" as the inputs for this operation. Register one tool. `fn` must be `lib.member` imported on the entry workbook. -**tools = > json.get value=`self` key="tools"** +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. 1. not `tools` - **tools = > table.empty_list** + We retain **`tools` = [Empty list](table.empty_list())**. + `row` = | name | fn | description | |------|-----|-------------| | `name` | `fn` | `description` | -**tools = > table.append list=`tools` item=`row`** -**h = table.put in=`self` at="tools" value=`tools`** -*h* +We retain **`tools` = [Append this item to the new list](table.append(list=`tools`, item=`row`))**. +We retain **`h` = [Set the tools field in the new record](table.put(in=`self`, at="tools", value=`tools`))**. +Return *h*. ## serve - + `transport`=stdio - + `host`="127.0.0.1" - + `port`=7434 - + `path`="/mcp" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| transport | any | "stdio" | Connector transport type | +| host | any | "127.0.0.1" | Explicit bind or remote host | +| port | any | 7434 | Explicit server port | +| path | any | "/mcp" | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Block on MCP: `stdio` (line JSON-RPC) or `http` / `streamable-http` (Streamable HTTP, POST JSON-RPC + optional GET SSE). Spec 2025-03-26. | + +Use `transport`="stdio", `host`="127.0.0.1", `port`=7434, `path`="/mcp" as the inputs for this operation. Block on MCP: `stdio` (line JSON-RPC) or `http` / `streamable-http` (Streamable HTTP, POST JSON-RPC + optional GET SSE). Spec 2025-03-26. -**name = > json.get value=`self` key="name"** -**tools = > json.get value=`self` key="tools"** -*> agent_mcp_serve name=`name` tools=`tools` transport=`transport` host=`host` port=`port` path=`path`* +We retain **`name` = [Read the name field](json.get(value=`self`, key="name"))**. +We retain **`tools` = [Read the tools field](json.get(value=`self`, key="tools"))**. +Return *[Mcp serve](agent_mcp_serve(name=`name`, tools=`tools`, transport=`transport`, host=`host`, port=`port`, path=`path`))*. diff --git a/ext/ai/index.mq.md b/ext/ai/index.mq.md new file mode 100644 index 0000000..70ac986 --- /dev/null +++ b/ext/ai/index.mq.md @@ -0,0 +1,72 @@ +--- +markup: occlusion +title: AI workflows — model adapters, agents, workbooks and trials +import: + model_api: ext/ai/llm.mq.md +--- + +Start here to choose an AI task. [Model calls](llm.mq.md) own prompts, model configuration, +stream collection and usage; [provider adapters](llm/index.mq.md) describe OpenAI-compatible +and Ollama requests. [Agents](agent.mq.md) own call-site context, the explicit tool registry, +policy routing, observations, workbook planning and continuation. [CoW trials](sandbox.mq.md) +own isolated file changes and promotion. [Step routing](policies/step-route.mq.md) is readable +policy data, not a second agent language. Chinese users can start at [索引](索引.mq.md). + +Begin with this offline stream example; it does not request credentials, install a plugin or +contact a model. Commands run from the repository root: + +```sh +marqdo call ext/ai/index.mq.md offline_example --json +``` + +For a live model call, configure its provider and credentials before invoking the existing llm +resource. A configured language or adapter does not prove a remote endpoint is available. +Agent operations require the native agent plugin, an explicit model and the permitted tools; +use cargo build -p marqdo_plugin_agent in this checkout. Never let a generated CALL line select +an arbitrary internal function. File, process and network permissions remain bounded by the host. + +Develop one responsibility at a time: provider request shaping belongs under llm/, common model +state in llm.mq.md, planner orchestration in agent.mq.md and trial behavior in sandbox.mq.md. +Keep the agent's call-site and source budgets intact when changing its internal helpers; moving +an operation can affect context and replay. Review effect preparation, transitions and saved +results before adding retries, and do not repeat writes merely to reconstruct a checkpoint. + +Use deterministic stream fixtures and local provider substitutes before live tests. Verify text, +usage, failed tools, lost responses, cancellation, context limits and durable continuation; +model output is data until an authorized tool target and arguments have been resolved. + +## collect_events + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | list | required | Ordered semantic or supported provider stream-event records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Final text assembled by the public stream collector | + +The supplied `events` are an already-observed stream, not instructions to request a new model +response or execute a tool. The shared collector understands delta/text, done.result and its +existing provider-frame conventions. We return *[Collect the existing stream into final text](model_api.collect(events=`events`))* +so offline processing and live transport use the same public assembly behavior. + +## offline_example + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Hello world, assembled from actual semantic events without a model request | + +The event table is a deterministic stream fixture. A delta introduces partial text, then the +final done result supplies the completed answer. Passing these through the public collector +verifies useful behavior; this tool does not manufacture a passed flag or a fake model answer. + +`events` = + +| @ | type | text | result | +|---|---|---|---| +| 1 | delta | "Hello " | None | +| 2 | done | None | "Hello world" | + +We return *[Assemble the final text from the displayed stream](collect_events(events=`events`))*. +A real transport failure still needs its domain error handling; this fixture only demonstrates +stream assembly, and it deliberately performs no network operation. diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md index bdac7e7..cb99275 100644 --- a/ext/ai/llm.mq.md +++ b/ext/ai/llm.mq.md @@ -13,68 +13,88 @@ import: openai: ext/ai/llm/openai.mq.md --- +Choose the public model resource here for ask, stream and collected response behavior. [The AI entry](index.mq.md) provides an offline event workflow; [the adapter entry](llm/index.mq.md) owns provider configuration and transport shapes. Agents and workbook orchestration belong in agent.mq.md. A created handle is configuration, not proof that authentication or a model request succeeded. Keep transport errors, semantic events and usage counters visible when extending this file. + ## load_env - + `path`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load `.env` from cwd (optional `path=`). Does not override existing variables. | + +Use `path`=None as the inputs for this operation. Load `.env` from cwd (optional `path=`). Does not override existing variables. -*> sys.load_dotenv path=`path`* +Return *[Load dotenv](sys.load_dotenv(path=`path`))*. ## collect - + `events` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Collapse a stream event list to final answer text. Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`). Alias: `stream_result`. | + +Use `events` as the inputs for this operation. Collapse a stream event list to final answer text. Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`). Alias: `stream_result`. -**answer = ""** +We retain **answer = ""**. - [ev](遍历 events 为 ev) - **t = > json.get value=`ev` key="type"** + We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. 1. `t` == "done" - **done_r = > json.get value=`ev` key="result"** + We retain **`done_r` = [Read the result field](json.get(value=`ev`, key="result"))**. 1. `done_r` - **answer = `done_r`** + We retain **answer = `done_r`**. 2. * **_ = 1** 2. `t` == "error" - **em = > json.get value=`ev` key="message"** + We retain **`em` = [Read the message field](json.get(value=`ev`, key="message"))**. 1. `em` - **answer = `em`** + We retain **answer = `em`**. 2. * **_ = 1** 3. `t` == "delta" 4. `t` == "text" - **chunk = > json.get value=`ev` key="text"** + We retain **`chunk` = [Read the text field](json.get(value=`ev`, key="text"))**. 1. `chunk` - **answer = answer + chunk** + We retain **answer = answer + chunk**. 2. * **_ = 1** 5. `t` == "data" - **raw = > json.get value=`ev` key="data"** + We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**. 1. `raw` 1. `raw` == "[DONE]" **_ = 1** 2. * - **parsed = > json.parse text=`raw`** + We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**. 1. `parsed` - **choices = > json.get value=`parsed` key="choices"** + We retain **`choices` = [Read the choices field](json.get(value=`parsed`, key="choices"))**. 1. `choices` - **c0 = [1](access(choices, "1"))** - **delta = > json.get value=`c0` key="delta"** + We retain **`c0` = [Read 1 field](access(`choices`, "1"))**. + We retain **`delta` = [Read the delta field](json.get(value=`c0`, key="delta"))**. 1. `delta` - **piece = > json.get value=`delta` key="content"** + We retain **`piece` = [Read the content field](json.get(value=`delta`, key="content"))**. 1. `piece` - **answer = answer + piece** + We retain **answer = answer + piece**. 2. * **_ = 1** 2. * - **msg = > json.get value=`c0` key="message"** + We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**. 1. `msg` - **piece = > json.get value=`msg` key="content"** + We retain **`piece` = [Read the content field](json.get(value=`msg`, key="content"))**. 1. `piece` - **answer = answer + piece** + We retain **answer = answer + piece**. 2. * **_ = 1** 2. * @@ -89,173 +109,272 @@ Alias: `stream_result`. **_ = 1** 1. not `answer` - **answer = ""** -*answer* + We retain **answer = ""**. +Return *answer*. ## collect_usage - + `events` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`). | + +Use `events` as the inputs for this operation. Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`). -**tokens = None** +We retain **tokens = None**. 1. `events` - [ev](遍历 events 为 ev) - **t = > json.get value=`ev` key="type"** - **raw = None** + We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**. + We retain **raw = None**. 1. `t` == "data" - **raw = > json.get value=`ev` key="data"** + We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**. 2. * - **u0 = > json.get value=`ev` key="usage"** + We retain **`u0` = [Read the usage field](json.get(value=`ev`, key="usage"))**. 1. `u0` - **tt0 = > json.get value=`u0` key="total_tokens"** + We retain **`tt0` = [Read the total_tokens field](json.get(value=`u0`, key="total_tokens"))**. 1. `tt0` != None - **tokens = `tt0`** + We retain **tokens = `tt0`**. 1. `raw` 1. not `raw` == "[DONE]" - **parsed = > json.parse text=`raw`** + We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**. 1. `parsed` - **u = > json.get value=`parsed` key="usage"** + We retain **`u` = [Read the usage field](json.get(value=`parsed`, key="usage"))**. 1. `u` - **tt = > json.get value=`u` key="total_tokens"** + We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**. 1. `tt` != None - **tokens = `tt`** -*tokens* + We retain **tokens = `tt`**. +Return *tokens*. ## stream_result - + `events` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| events | any | required | Ordered semantic or provider stream-event records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Compatibility alias for `collect`. | + +Use `events` as the inputs for this operation. Compatibility alias for `collect`. -*> collect events=`events`* +Return *[Collect](collect(events=`events`))*. ## usage_from - + `data` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros). | + +Use `data` as the inputs for this operation. Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros). -*> openai.usage_from data=`data`* +Return *[Usage from](openai.usage_from(data=`data`))*. ## create - + `model`=None - + `base_url`=None - + `api_key`=None - + `backend`=openai-compatible - + `name`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | +| backend | any | "openai-compatible" | Configured execution or provider backend | +| name | any | None | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`). | + +Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation. Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`). -**h = > llm model=`model` base_url=`base_url` api_key=`api_key` backend=`backend` name=`name`** -*h* +We retain **`h` = [Llm](llm(model=`model`, base_url=`base_url`, api_key=`api_key`, backend=`backend`, name=`name`))**. +Return *h*. ## fast - + `model`=None - + `base_url`=None - + `api_key`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model. | + +Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model. 1. `model` - **mdl = `model`** + We retain **mdl = `model`**. 2. * - **mdl = > sys.env_get name="MARQDO_LLM_FAST_MODEL"** + We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_FAST_MODEL"))**. -*> create model=`mdl` base_url=`base_url` api_key=`api_key` name="fast" backend="openai-compatible"* +Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="fast", backend="openai-compatible"))*. ## reasoning - + `model`=None - + `base_url`=None - + `api_key`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model. | + +Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model. 1. `model` - **mdl = `model`** + We retain **mdl = `model`**. 2. * - **mdl = > sys.env_get name="MARQDO_LLM_REASONING_MODEL"** + We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_REASONING_MODEL"))**. -*> create model=`mdl` base_url=`base_url` api_key=`api_key` name="reasoning" backend="openai-compatible"* +Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="reasoning", backend="openai-compatible"))*. ## prompt_body - + `src` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | any | required | Prompt source or source-reference value | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged. | + +Use `src` as the inputs for this operation. If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged. -**sw = > text.starts_with text=`src` prefix="---"** +We retain **`sw` = [Starts with](text.starts_with(text=`src`, prefix="---"))**. 1. not `sw` - *src* + Return *src*. 2. * - **parts = > split value=`src` sep="\n---\n"** - **n = > len value=`parts`** + We retain **`parts` = [Split](split(value=`src`, sep="\n---\n"))**. + We retain **`n` = [Len](len(value=`parts`))**. 1. `n` < 2 - *src* + Return *src*. 2. * - **fm = > at value=`parts` index=0** - **is_p = > text.contains text=`fm` sub="type: prompt"** + We retain **`fm` = [At](at(value=`parts`, index=0))**. + We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="type: prompt"))**. 1. not `is_p` - **is_p = > text.contains text=`fm` sub="类型: 提示"** + We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="类型: 提示"))**. 2. * **_ = 1** 1. `is_p` - **body = > at value=`parts` index=1** - *> text.str_trim s=`body`* + We retain **`body` = [At](at(value=`parts`, index=1))**. + Return *[Str trim](text.str_trim(s=`body`))*. 2. * - *src* + Return *src*. ## prompt_load - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`. | + +Use `path` as the inputs for this operation. Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`. -**raw = > fs.read_text path=`path`** -*> prompt_body src=`raw`* +We retain **`raw` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**. +Return *[Prompt body](prompt_body(src=`raw`))*. ## prompt - + `path`=None - + `text`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| text | any | None | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string. | + +Use `path`=None, `text`=None as the inputs for this operation. Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string. 1. `path` - *> prompt_load path=`path`* + Return *[Prompt load](prompt_load(path=`path`))*. 2. `text` - *> prompt_body src=`text`* + Return *[Prompt body](prompt_body(src=`text`))*. 3. * - > print text=ext/ai/llm.prompt: pass path= or text= - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/llm.prompt: pass", path="or", text=""))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. ## ask - + `prompt`=None - + `path`=None - + `model`=None - + `base_url`=None - + `api_key`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | None | Prompt text or structured prompt expected by this adapter | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`). | + +Use `prompt`=None, `path`=None, `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`). -**p = `prompt`** +We retain **p = `prompt`**. 1. `path` - **p = > prompt_load path=`path`** + We retain **`p` = [Prompt load](prompt_load(path=`path`))**. 2. `prompt` - **p = `prompt`** + We retain **p = `prompt`**. 3. * - **raw = > sys.module_source** + We retain **`raw` = [Module source](sys.module_source())**. 1. not `raw` - > print text=ext/ai/llm.ask: pass prompt= or path= (or run a prompt document as entry) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/llm.ask: pass", prompt="or", path="(or run a prompt document as entry)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. 2. * - **p = > prompt_body src=`raw`** + We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. -**m = > create model=`model` base_url=`base_url` api_key=`api_key`** -**r = > m.ask prompt=`p`** -**_ret = > json.get value=`r` key="text"** -*_ret* +We retain **`m` = [Create](create(model=`model`, base_url=`base_url`, api_key=`api_key`))**. +We retain **`r` = [Ask](m.ask(prompt=`p`))**. +We retain **`_ret` = [Read the text field](json.get(value=`r`, key="text"))**. +Return *_ret*. # llm - + `model`=None - + `base_url`=None - + `api_key`=None - + `backend`=openai-compatible - + `name`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | +| backend | any | "openai-compatible" | Configured execution or provider backend | +| name | any | None | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | LLM handle — intelligence primitive, not an HTTP client. Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`) → `sys.env_get` → defaults. Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names. | + +Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation. LLM handle — intelligence primitive, not an HTTP client. @@ -263,13 +382,13 @@ Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`) Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names. 1. `api_key` - **key = `api_key`** + We retain **key = `api_key`**. 2. * - **key = > sys.meta_get key="api_key"** + We retain **`key` = [Meta get](sys.meta_get(key="api_key"))**. 1. not `key` - **key = > sys.env_get name="OPENAI_API_KEY"** + We retain **`key` = [Env get](sys.env_get(name="OPENAI_API_KEY"))**. 1. not `key` - **key = > sys.env_get name="MARQDO_LLM_API_KEY"** + We retain **`key` = [Env get](sys.env_get(name="MARQDO_LLM_API_KEY"))**. 2. * **_ = 1** 2. * @@ -277,62 +396,62 @@ Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then u 1. `backend` == ollama 1. not `key` - **key = "ollama"** + We retain **key = "ollama"**. 2. * **_ = 1** 2. not `key` - > print text=ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY (or pass api_key= / metadata api_key) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY (or pass api_key= / metadata api_key)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. 3. * **_ = 1** 1. `base_url` - **url = `base_url`** + We retain **url = `base_url`**. 2. * - **url = > sys.meta_get key="base_url"** + We retain **`url` = [Meta get](sys.meta_get(key="base_url"))**. 1. `url` **_ = 1** 2. `backend` == ollama - **url = > sys.env_get name="OLLAMA_HOST"** + We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**. 1. not `url` - **url = "http://127.0.0.1:11434/v1"** + We retain **url = "http://127.0.0.1:11434/v1"**. 2. * **_ = 1** 3. * - **url = > sys.env_get name="OPENAI_BASE_URL"** + We retain **`url` = [Env get](sys.env_get(name="OPENAI_BASE_URL"))**. 1. not `url` - **url = > sys.env_get name="MARQDO_LLM_BASE_URL"** + We retain **`url` = [Env get](sys.env_get(name="MARQDO_LLM_BASE_URL"))**. 2. * **_ = 1** 1. not `url` - **url = "https://api.openai.com/v1"** + We retain **url = "https://api.openai.com/v1"**. 2. * **_ = 1** 1. `model` - **mdl = `model`** + We retain **mdl = `model`**. 2. * - **mdl = > sys.meta_get key="model"** + We retain **`mdl` = [Meta get](sys.meta_get(key="model"))**. 1. `mdl` **_ = 1** 2. * - **mdl = > sys.env_get name="OPENAI_MODEL"** + We retain **`mdl` = [Env get](sys.env_get(name="OPENAI_MODEL"))**. 1. not `mdl` - **mdl = > sys.env_get name="MARQDO_LLM_MODEL"** + We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**. 2. * **_ = 1** 1. not `mdl` 1. `backend` == ollama - **mdl = "llama3.2"** + We retain **mdl = "llama3.2"**. 2. * - **mdl = "gpt-4o-mini"** + We retain **mdl = "gpt-4o-mini"**. 2. * **_ = 1** 1. `name` - **nm = `name`** + We retain **nm = `name`**. 2. * - **nm = None** + We retain **nm = None**. `h` = @@ -340,49 +459,58 @@ Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then u |-------|---------|---------|----------|-------|--------|--------|------| | llm | `backend` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` | -*h* +Return *h*. ## ask - + `prompt`=None - + `path`=None - + `messages`=None - + `selection`=None - + `strict_selection`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | None | Prompt text or structured prompt expected by this adapter | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| messages | any | None | Ordered chat message records | +| selection | any | None | Explicit runtime/model selection | +| strict_selection | any | False | Whether an unresolved selection is an error | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback. | + +Use `prompt`=None, `path`=None, `messages`=None, `selection`=None, `strict_selection`=False as the inputs for this operation. Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback. -**p = `prompt`** +We retain **p = `prompt`**. 1. `messages` - **p = None** + We retain **p = None**. 2. `path` - **p = > prompt_load path=`path`** + We retain **`p` = [Prompt load](prompt_load(path=`path`))**. 3. `prompt` - **p = `prompt`** + We retain **p = `prompt`**. 4. * - **raw = > sys.module_source** + We retain **`raw` = [Module source](sys.module_source())**. 1. not `raw` - **p = ""** + We retain **p = ""**. 2. * - **p = > prompt_body src=`raw`** -**pack = > self.complete_result prompt=`p` messages=`messages` selection=`selection` strict_selection=`strict_selection` stream=False echo=False** -**text = > json.get value=`pack` key="text"** -**usage = > json.get value=`pack` key="usage"** -**finish = > json.get value=`pack` key="finish"** -**err = > json.get value=`pack` key="error"** -**tc = > json.get value=`pack` key="tool_calls"** + We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. +We retain **`pack` = [Complete result](self.complete_result(prompt=`p`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=False, echo=False))**. +We retain **`text` = [Read the text field](json.get(value=`pack`, key="text"))**. +We retain **`usage` = [Read the usage field](json.get(value=`pack`, key="usage"))**. +We retain **`finish` = [Read the finish field](json.get(value=`pack`, key="finish"))**. +We retain **`err` = [Read the error field](json.get(value=`pack`, key="error"))**. +We retain **`tc` = [Read the tool_calls field](json.get(value=`pack`, key="tool_calls"))**. 1. not `tc` - **tc = > table.empty_list** + We retain **`tc` = [Empty list](table.empty_list())**. 2. * **_ = 1** 1. not `text` - **text = ""** + We retain **text = ""**. 2. * **_ = 1** 1. not `finish` 1. `err` - **finish = "error"** + We retain **finish = "error"**. 2. * - **finish = "stop"** + We retain **finish = "stop"**. 2. * **_ = 1** @@ -390,26 +518,26 @@ Hoist receiver fields before the result table — table cells can shadow `self` column names (`model`, `usage`), so `[model](self)` / `[total_tokens](usage)` inside the table is unsafe. -**mdl = > json.get value=`self` key="model"** -**b = > json.get value=`self` key="backend"** -**nm = > json.get value=`self` key="name"** +We retain **`mdl` = [Read the model field](json.get(value=`self`, key="model"))**. +We retain **`b` = [Read the backend field](json.get(value=`self`, key="backend"))**. +We retain **`nm` = [Read the name field](json.get(value=`self`, key="name"))**. 1. `usage` - **tt = > json.get value=`usage` key="total_tokens"** - **ustate = > json.get value=`usage` key="usage_state"** + We retain **`tt` = [Read the total_tokens field](json.get(value=`usage`, key="total_tokens"))**. + We retain **`ustate` = [Read the usage_state field](json.get(value=`usage`, key="usage_state"))**. 2. * - **tt = None** - **ustate = "unknown"** + We retain **tt = None**. + We retain **ustate = "unknown"**. 1. `ustate` == "unknown" Keep null — never coerce missing usage to zero tokens (M02 / F04). - **tt = None** + We retain **tt = None**. 2. not `tt` - **tt = None** + We retain **tt = None**. 3. * **_ = 1** 1. `err` - **calls = 0** + We retain **calls = 0**. 2. * - **calls = 1** + We retain **calls = 1**. `result` = @@ -417,66 +545,102 @@ inside the table is unsafe. |------|-------|--------|---------|-------|------|-----------|--------|------------|-------|-----------| | `text` | `mdl` | `finish` | `b` | `usage` | `nm` | `calls` | `tt` | `tc` | `err` | `selection` | -*result* +Return *result*. ## stream - + `prompt`=None - + `path`=None - + `echo`=False - + `stream_kind`="delta" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | None | Prompt text or structured prompt expected by this adapter | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document. | + +Use `prompt`=None, `path`=None, `echo`=False, `stream_kind`="delta" as the inputs for this operation. Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document. `stream_kind=plan` tags EventBus frames for the parent plan protocol (process trail). 1. `path` - **p = > prompt_load path=`path`** + We retain **`p` = [Prompt load](prompt_load(path=`path`))**. 2. `prompt` - **p = `prompt`** + We retain **p = `prompt`**. 3. * - **raw = > sys.module_source** + We retain **`raw` = [Module source](sys.module_source())**. 1. not `raw` - **p = ""** + We retain **p = ""**. 2. * - **p = > prompt_body src=`raw`** + We retain **`p` = [Prompt body](prompt_body(src=`raw`))**. -*> self.complete prompt=`p` stream=True echo=`echo` stream_kind=`stream_kind`* +Return *[Complete](self.complete(prompt=`p`, stream=True, echo=`echo`, stream_kind=`stream_kind`))*. ## complete_result - + `prompt`=None - + `messages`=None - + `selection`=None - + `strict_selection`=False - + `stream`=False - + `echo`=False - + `stream_kind`="delta" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | None | Prompt text or structured prompt expected by this adapter | +| messages | any | None | Ordered chat message records | +| selection | any | None | Explicit runtime/model selection | +| strict_selection | any | False | Whether an unresolved selection is an error | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01). | + +Use `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01). -*> openai.chat_completions base_url=[base_url](access(self, "base_url")) api_key=[api_key](access(self, "api_key")) model=[model](access(self, "model")) prompt=`prompt` messages=`messages` selection=`selection` strict_selection=`strict_selection` stream=`stream` echo=`echo` stream_kind=`stream_kind` suffix=[suffix](access(self, "suffix")) bearer=[bearer](access(self, "bearer"))* +Return *[Chat completions](openai.chat_completions(base_url=[base_url](access(`self`, "base_url")), api_key=[api_key](access(`self`, "api_key")), model=[model](access(`self`, "model")), prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=[suffix](access(`self`, "suffix")), bearer=[bearer](access(`self`, "bearer"))))*. ## complete - + `prompt` - + `stream`=False - + `echo`=False - + `stream_kind`="delta" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | required | Prompt text or structured prompt expected by this adapter | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Internal / compatibility primitive. Prefer `ask` / `stream` in new code. | + +Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. Internal / compatibility primitive. Prefer `ask` / `stream` in new code. 1. `stream` - **pack = > self.complete_result prompt=`prompt` stream=True echo=`echo` stream_kind=`stream_kind`** - **_ret = > json.get value=`pack` key="events"** - *_ret* + We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=True, echo=`echo`, stream_kind=`stream_kind`))**. + We retain **`_ret` = [Read the events field](json.get(value=`pack`, key="events"))**. + Return *_ret*. 2. * - **pack = > self.complete_result prompt=`prompt` stream=False echo=`echo` stream_kind=`stream_kind`** - **_ret = > json.get value=`pack` key="text"** - *_ret* + We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=False, echo=`echo`, stream_kind=`stream_kind`))**. + We retain **`_ret` = [Read the text field](json.get(value=`pack`, key="text"))**. + Return *_ret*. ## chat - + `prompt` - + `stream`=False - + `echo`=False - + `stream_kind`="delta" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prompt | any | required | Prompt text or structured prompt expected by this adapter | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Alias for `complete` (compat). | + +Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation. Alias for `complete` (compat). -*> self.complete prompt=`prompt` stream=`stream` echo=`echo` stream_kind=`stream_kind`* +Return *[Complete](self.complete(prompt=`prompt`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`))*. diff --git a/ext/ai/llm/index.mq.md b/ext/ai/llm/index.mq.md new file mode 100644 index 0000000..4431cae --- /dev/null +++ b/ext/ai/llm/index.mq.md @@ -0,0 +1,60 @@ +--- +markup: occlusion +title: Provider adapters — requests, configuration and usage +import: + ollama: ext/ai/llm/ollama.mq.md + openai: ext/ai/llm/openai.mq.md +--- + +This directory owns provider adaptation. [OpenAI-compatible requests](openai.mq.md) encode chat +messages, decode replies and usage, and retain streaming/error conventions. [Ollama](ollama.mq.md) +selects its documented local defaults while reusing compatible transport. The parent [model API](../llm.mq.md) +creates author model resources; [the AI root](../index.mq.md) explains agent and trial responsibilities. + +This offline usage example inspects response data only. It does not read credentials, load a +plugin or contact the provider: + +```sh +marqdo call ext/ai/llm/index.mq.md usage 'data={"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}' --json +``` + +For local configuration, resolve_local reads the documented environment fallbacks and therefore +needs environment.read. Sending chat_completions is a real HTTP effect and requires an explicitly +configured endpoint, timeout and credential handling. Do not print a live configuration record +containing secrets merely to prove that an adapter exists. + +When adding a provider, preserve semantic message/event/result shapes at the public model boundary. +Keep provider-specific headers and endpoint paths in the adapter, document supported response +variants and test them against local fixtures before live traffic. A usage fixture does not verify +provider availability, streaming latency or authentication. + +## usage + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | map | required | Already received OpenAI-compatible response record | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Public prompt_tokens/completion_tokens/total_tokens usage projection | + +The `data` record is an observation rather than a request body. Missing counters follow the +public adapter convention; the example above contains two input tokens, three output tokens and +five total tokens. We return *[Read actual usage counters from the supplied response](openai.usage_from(data=`data`))* +without claiming to have measured a new model invocation. + +## resolve_local + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Explicit local model override; None uses the adapter fallback | +| base_url | any | None | Explicit local API base URL; None uses the documented environment/default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Actual Ollama configuration selected by the existing resolver | + +The caller may supply `model`=None and `base_url`=None to use the shared local configuration +rules. Resolving the configuration does not launch a service or ask the model for a response. +We return *[Resolve local model fields with the existing adapter](ollama.resolve(model=`model`, base_url=`base_url`))*. +Treat the resulting configuration as runtime data and only execute a request after granting its effects. diff --git a/ext/ai/llm/ollama.mq.md b/ext/ai/llm/ollama.mq.md index 7778331..4dda90c 100644 --- a/ext/ai/llm/ollama.mq.md +++ b/ext/ai/llm/ollama.mq.md @@ -9,32 +9,41 @@ import: --- ## resolve - + `model`=None - + `base_url`=None - + `api_key`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| model | any | None | Model resource or provider model identifier, as required by this operation | +| base_url | any | None | Provider API base URL | +| api_key | any | None | Provider credential from trusted runtime configuration | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`. | + +Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation. Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`. 1. `api_key` - **key = api_key** + We retain **key = api_key**. 2. * - **key = "ollama"** + We retain **key = "ollama"**. 1. `base_url` - **url = base_url** + We retain **url = base_url**. 2. * - **url = > sys.env_get name="OLLAMA_HOST"** + We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**. 1. not `url` - **url = "http://127.0.0.1:11434/v1"** + We retain **url = "http://127.0.0.1:11434/v1"**. 2. * **_ = 1** 1. `model` - **mdl = model** + We retain **mdl = model**. 2. * - **mdl = > sys.env_get name="MARQDO_LLM_MODEL"** + We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**. 1. not `mdl` - **mdl = "llama3.2"** + We retain **mdl = "llama3.2"**. 2. * **_ = 1** @@ -44,14 +53,25 @@ Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `oll |---------|---------|----------|-------| | ollama | `key` | `url` | `mdl` | -*cfg* +Return *cfg*. ## chat_completions - + `base_url` - + `api_key` - + `model` - + `prompt` - + `stream`=False - + `echo`=False -*> openai.chat_completions base_url=`base_url` api_key=`api_key` model=`model` prompt=`prompt` stream=`stream` echo=`echo`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| base_url | any | required | Provider API base URL | +| api_key | any | required | Provider credential from trusted runtime configuration | +| model | any | required | Model resource or provider model identifier, as required by this operation | +| prompt | any | required | Prompt text or structured prompt expected by this adapter | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions. | + +Use `base_url`, `api_key`, `model`, `prompt`, `stream`=False, `echo`=False as the inputs for this operation. + +Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions. + +Return *[Chat completions](openai.chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, stream=`stream`, echo=`echo`))*. diff --git a/ext/ai/llm/openai.mq.md b/ext/ai/llm/openai.mq.md index d810ed6..7236b96 100644 --- a/ext/ai/llm/openai.mq.md +++ b/ext/ai/llm/openai.mq.md @@ -15,31 +15,40 @@ import: --- ## usage_from - + `data` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map. | + +Use `data` as the inputs for this operation. Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map. -**u = > json.get value=`data` key="usage"** +We retain **`u` = [Read the usage field](json.get(value=`data`, key="usage"))**. 1. `u` - **pt = > json.get value=`u` key="prompt_tokens"** - **ct = > json.get value=`u` key="completion_tokens"** - **tt = > json.get value=`u` key="total_tokens"** + We retain **`pt` = [Read the prompt_tokens field](json.get(value=`u`, key="prompt_tokens"))**. + We retain **`ct` = [Read the completion_tokens field](json.get(value=`u`, key="completion_tokens"))**. + We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**. 1. not `pt` - **pt = 0** + We retain **pt = 0**. 2. * **_ = 1** 1. not `ct` - **ct = 0** + We retain **ct = 0**. 2. * **_ = 1** 1. not `tt` - **tt = pt + ct** + We retain **tt = pt + ct**. 2. * **_ = 1** 2. * - **pt = 0** - **ct = 0** - **tt = 0** + We retain **pt = 0**. + We retain **ct = 0**. + We retain **tt = 0**. `usage` = @@ -47,58 +56,77 @@ Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped r |---------------|-------------------|--------------| | `pt` | `ct` | `tt` | -*usage* +Return *usage*. ## tool_calls_from - + `data` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list). | + +Use `data` as the inputs for this operation. Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list). -**choices = > json.get value=`data` key="choices"** +We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**. 1. not `choices` - *> table.empty_list* + Return *[Empty list](table.empty_list())*. 2. * - **c0 = [1](access(choices, "1"))** - **msg = > json.get value=`c0` key="message"** + We retain **`c0` = [Read 1 field](access(`choices`, "1"))**. + We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**. 1. not `msg` - *> table.empty_list* + Return *[Empty list](table.empty_list())*. 2. * - **tc = > json.get value=`msg` key="tool_calls"** + We retain **`tc` = [Read the tool_calls field](json.get(value=`msg`, key="tool_calls"))**. 1. `tc` - *tc* + Return *tc*. 2. * - *> table.empty_list* + Return *[Empty list](table.empty_list())*. ## chat_completions - + `base_url` - + `api_key` - + `model` - + `prompt`=None - + `messages`=None - + `selection`=None - + `strict_selection`=False - + `auth_mode`=None - + `stream`=False - + `echo`=False - + `stream_kind`="delta" - + `suffix`=/chat/completions - + `bearer`="Bearer " + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| base_url | any | required | Provider API base URL | +| api_key | any | required | Provider credential from trusted runtime configuration | +| model | any | required | Model resource or provider model identifier, as required by this operation | +| prompt | any | None | Prompt text or structured prompt expected by this adapter | +| messages | any | None | Ordered chat message records | +| selection | any | None | Explicit runtime/model selection | +| strict_selection | any | False | Whether an unresolved selection is an error | +| auth_mode | any | None | Authentication mode used by the provider adapter | +| stream | any | False | Whether to preserve streaming behavior or emit stream events | +| echo | any | False | Whether to print the documented incremental output | +| stream_kind | any | "delta" | Streaming event projection selected by the caller | +| suffix | any | "/chat/completions" | Provider endpoint suffix | +| bearer | any | "Bearer " | Bearer credential supplied by the configured provider | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. Soft transport / HTTP failures return `finish=error` packs (never abort the VM). Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin. | + +Use `base_url`, `api_key`, `model`, `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `auth_mode`=None, `stream`=False, `echo`=False, `stream_kind`="delta", `suffix`="/chat/completions", `bearer`="Bearer " as the inputs for this operation. POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. Soft transport / HTTP failures return `finish=error` packs (never abort the VM). Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin. `stream_kind` tags live EventBus frames: `delta` (answer tokens) or `plan` (parent protocol — UI process trail, not the bubble). -**p = > plugin.native_path name="llm"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="llm"))**. 1. `p` - > plugin.load path=`p` - *> llm_chat_completions base_url=`base_url` api_key=`api_key` model=`model` prompt=`prompt` messages=`messages` selection=`selection` strict_selection=`strict_selection` auth_mode=`auth_mode` stream=`stream` echo=`echo` stream_kind=`stream_kind` suffix=`suffix` bearer=`bearer`* + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. + Return *[Llm chat completions](llm_chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, auth_mode=`auth_mode`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=`suffix`, bearer=`bearer`))*. 2. * - **url = base_url + suffix** - **auth = bearer + api_key** - **headers = > table.put in=None at="Authorization" value=`auth`** + We retain **url = base_url + suffix**. + We retain **auth = bearer + api_key**. + We retain **`headers` = [Set the Authorization field in the new record](table.put(in=None, at="Authorization", value=`auth`))**. 1. not `messages` + `messages` = | @ | role | content | @@ -114,19 +142,20 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes | `model` | `messages` | 1. `stream` - **req = > table.put in=`req` at="stream" value=True** + We retain **`req` = [Set the stream field in the new record](table.put(in=`req`, at="stream", value=True))**. + `stream_opts` = | include_usage | |---------------| | True | - **req = > table.put in=`req` at="stream_options" value=`stream_opts`** - **body = > json.stringify value=`req`** - **resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo`** - **st = > json.get value=`resp` key="status"** + We retain **`req` = [Set the stream_options field in the new record](table.put(in=`req`, at="stream_options", value=`stream_opts`))**. + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**. + We retain **`resp` = [Http post sse](net.http_post_sse(url=`url`, body=`body`, headers=`headers`, echo=`echo`))**. + We retain **`st` = [Read the status field](json.get(value=`resp`, key="status"))**. 1. `st` == 200 - **evs = > json.get value=`resp` key="events"** + We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**. `pack` = @@ -134,45 +163,46 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes |--------|--------| | stop | `evs` | - *pack* + Return *pack*. 2. * Soft transport / HTTP failure — structured pack, never abort the VM. - **msg = "HTTP " + `st`** - **evs = > json.get value=`resp` key="events"** + We retain **msg = "HTTP " + `st`**. + We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**. 1. `evs` - **e0 = > at value=`evs` index=0** - **m2 = > json.get value=`e0` key="message"** + We retain **`e0` = [At](at(value=`evs`, index=0))**. + We retain **`m2` = [Read the message field](json.get(value=`e0`, key="message"))**. 1. `m2` - **msg = `m2`** + We retain **msg = `m2`**. + `pack` = | finish | text | error | events | |--------|------|-------|--------| | error | "" | `msg` | `evs` | - *pack* + Return *pack*. 2. * - **body = > json.stringify value=`req`** - **resp = > net.http_post url=`url` body=`body` headers=`headers`** - **st = > json.get value=`resp` key="status"** + We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**. + We retain **`resp` = [Http post](net.http_post(url=`url`, body=`body`, headers=`headers`))**. + We retain **`st` = [Read the status field](json.get(value=`resp`, key="status"))**. 1. `st` == 200 - **raw = > json.get value=`resp` key="body"** - **data = > json.parse text=`raw`** - **choices = > json.get value=`data` key="choices"** - **choice0 = > at value=`choices` index=0** - **msg = > json.get value=`choice0` key="message"** - **text = > json.get value=`msg` key="content"** + We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**. + We retain **`data` = [Parse the JSON transport text](json.parse(text=`raw`))**. + We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**. + We retain **`choice0` = [At](at(value=`choices`, index=0))**. + We retain **`msg` = [Read the message field](json.get(value=`choice0`, key="message"))**. + We retain **`text` = [Read the content field](json.get(value=`msg`, key="content"))**. 1. not `text` - **text = ""** + We retain **text = ""**. 2. * **_ = 1** - **usage = > usage_from data=`data`** - **fr = > json.get value=`choice0` key="finish_reason"** + We retain **`usage` = [Usage from](usage_from(data=`data`))**. + We retain **`fr` = [Read the finish_reason field](json.get(value=`choice0`, key="finish_reason"))**. 1. not `fr` - **fr = "stop"** + We retain **fr = "stop"**. 2. * **_ = 1** - **tc = > tool_calls_from data=`data`** + We retain **`tc` = [Tool calls from](tool_calls_from(data=`data`))**. `pack` = @@ -180,20 +210,21 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes |--------|------|-------|------------| | `fr` | `text` | `usage` | `tc` | - *pack* + Return *pack*. 2. * Soft transport / HTTP failure — structured pack, never abort the VM. - **raw = > json.get value=`resp` key="body"** - **msg = "HTTP " + `st`** + We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**. + We retain **msg = "HTTP " + `st`**. 1. `raw` - **msg = `msg` + ": " + `raw`** + We retain **msg = `msg` + ": " + `raw`**. + `usage0` = | prompt_tokens | completion_tokens | total_tokens | |---------------|-------------------|--------------| | 0 | 0 | 0 | - **empty_tc = > table.empty_list** + We retain **`empty_tc` = [Empty list](table.empty_list())**. `pack` = @@ -201,4 +232,4 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes |--------|------|-------|-------|------------| | error | "" | `msg` | `usage0` | `empty_tc` | - *pack* + Return *pack*. diff --git a/ext/ai/policies/step-route.mq.md b/ext/ai/policies/step-route.mq.md index 6db848c..896f10f 100644 --- a/ext/ai/policies/step-route.mq.md +++ b/ext/ai/policies/step-route.mq.md @@ -6,21 +6,39 @@ description: > Readable authority for agent.step_route; do not invent a second dialect. --- -# Step class → backend +Step class to backend. Authors and `agent.step_route` read this table. Backends match Adaptive Routing: `marqdo` | `small-llm` | `llm` | `auto`. +## routes + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Return the same readable route table used by the agent policy reader. | + +Return the same readable route table used by the agent policy reader. + +Each column is a list with the same row order. Lookup and sandbox execution prefer Marqdo, patch work prefers the small model, and network-oriented work uses the model route. The default row leaves the final choice to the existing router. Returning these values does not load or invoke a backend. + **routes = ** | kind | backend | note | |------|---------|------| | lookup | marqdo | OKF / kb skill hit — no parent LLM | | patch | small-llm | Local patch / soft match | -| sandbox_run | marqdo | CoW trial of `.mq.md` | +| sandbox_run | marqdo | "CoW trial of .mq.md" | | net | llm | Needs network / toolful turn | | default | auto | Cascade policy → kb → small-llm | +Return *routes*. + # main -*routes* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | The entry returns the policy data without creating a second routing dialect. | + +The entry returns the policy data without creating a second routing dialect. + +Return *[Routes](routes())*. diff --git a/ext/ai/sandbox.mq.md b/ext/ai/sandbox.mq.md index 3520603..ddf2bc3 100644 --- a/ext/ai/sandbox.mq.md +++ b/ext/ai/sandbox.mq.md @@ -15,17 +15,34 @@ Load the agent plugin once per call (same pattern as other `ext/ai` helpers). Capability profiles are GFM tables under `## profile` (readable authority; `open` / `inspect` echo them). Do not invent a second table dialect. +CoW trial operations belong here; attaching a sandbox profile to another result does not isolate execution. [The AI entry](index.mq.md) explains the relation to model and agent resources. A trial produces inspectable changes; promotion is a separate existing operation with its own checks. Keep cancellation, failed execution and explicit promotion visible, and never equate a generated source file with a committed successful outcome. + ## ensure_plugin -**p = plugin.native_path name="agent"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the required native ABI plugin; missing binaries report a diagnostic message and stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent) - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. ## profile - + `name`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | "default" | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`. Catalog (documentation + authority): | + +Use `name`="default" as the inputs for this operation. Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`. @@ -50,139 +67,249 @@ Catalog (documentation + authority): |------|----------|------|-----|--------| | default | true | false | false | false | -*row* +Return *row*. ## open_native - + `root`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | any | None | Explicit root directory for discovery or isolated execution | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade. | + +Use `root`=None as the inputs for this operation. Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade. -> ensure_plugin +We **[Load the native plugin required by this operation](ensure_plugin())**. 1. `root` - *> sandbox_open root=`root`* + Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open(root=`root`))*. 2. * - *> sandbox_open* + Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open())*. ## open - + `root`=None - + `profile`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | any | None | Explicit root directory for discovery or isolated execution | +| profile | any | "default" | Capability profile selected for the trial | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Open a CoW session. Optional `root=` (directory). Default: entry file directory. | + +Use `root`=None, `profile`="default" as the inputs for this operation. Open a CoW session. Optional `root=` (directory). Default: entry file directory. `profile=` selects the caps row from `## profile` (echoed by `inspect`). -**sess = open_native root=`root`** -**prof = profile name=`profile`** -**sess = table.put in=`sess` at="profile" value=`prof`** -*sess* +We retain **`sess` = [Open native](open_native(root=`root`))**. +We retain **`prof` = [Profile](profile(name=`profile`))**. +We retain **`sess` = [Set the profile field in the new record](table.put(in=`sess`, at="profile", value=`prof`))**. +Return *sess*. ## write - + `id` - + `path` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| text | any | required | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Write text into the session upper layer (host tree unchanged until `commit`). | + +Use `id`, `path`, `text` as the inputs for this operation. Write text into the session upper layer (host tree unchanged until `commit`). -> ensure_plugin -*> sandbox_write id=`id` path=`path` text=`text`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Write text into the session upper layer (host tree unchanged until commit).](sandbox_write(id=`id`, path=`path`, text=`text`))*. ## read - + `id` - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read through CoW (upper, else lower; whiteout misses). | + +Use `id`, `path` as the inputs for this operation. Read through CoW (upper, else lower; whiteout misses). -> ensure_plugin -*> sandbox_read id=`id` path=`path`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Read through CoW (upper, else lower; whiteout misses).](sandbox_read(id=`id`, path=`path`))*. ## remove - + `id` - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Logical delete (whiteout). | + +Use `id`, `path` as the inputs for this operation. Logical delete (whiteout). -> ensure_plugin -*> sandbox_remove id=`id` path=`path`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Logical delete (whiteout).](sandbox_remove(id=`id`, path=`path`))*. ## diff - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List of `{ path, kind }` pending changes (`write` | `remove`). | + +Use `id` as the inputs for this operation. List of `{ path, kind }` pending changes (`write` | `remove`). -> ensure_plugin -*> sandbox_diff id=`id`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[List of { path, kind } pending changes (write | remove).](sandbox_diff(id=`id`))*. ## commit - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply upper / whiteout to the real workspace root. | + +Use `id` as the inputs for this operation. Apply upper / whiteout to the real workspace root. -> ensure_plugin -*> sandbox_commit id=`id`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Apply upper / whiteout to the real workspace root.](sandbox_commit(id=`id`))*. ## discard - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Drop the session without writing the host tree. | + +Use `id` as the inputs for this operation. Drop the session without writing the host tree. -> ensure_plugin -*> sandbox_discard id=`id`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Drop the session without writing the host tree.](sandbox_discard(id=`id`))*. ## run - + `id` - + `source`=None - + `path`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| source | any | None | Source text inspected or prepared by this operation | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW). Pass `source=` or `path=` (relative to session root). | + +Use `id`, `source`=None, `path`=None as the inputs for this operation. Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW). Pass `source=` or `path=` (relative to session root). -> ensure_plugin +We **[Load the native plugin required by this operation](ensure_plugin())**. 1. `source` - *> sandbox_run id=`id` source=`source`* + Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, source=`source`))*. 2. `path` - *> sandbox_run id=`id` path=`path`* + Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, path=`path`))*. 3. * - > print text=ext/ai/sandbox.run: need source= or path= - > sys.exit code=1 + We **[Print the prepared message](print(text="ext/ai/sandbox.run: need", source="or", path=""))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. ## inspect_native - + `id` -> ensure_plugin -*> sandbox_inspect id=`id`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Inspect an existing native CoW session without promoting its writes. | + +Use `id` as the inputs for this operation. + +Inspect an existing native CoW session without promoting its writes. + +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Inspect an existing native CoW session without promoting its writes.](sandbox_inspect(id=`id`))*. ## inspect - + `id` - + `profile`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| profile | any | "default" | Capability profile selected for the trial | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native caps / change counts, plus the GFM `## profile` row under key `profile`. | + +Use `id`, `profile`="default" as the inputs for this operation. Native caps / change counts, plus the GFM `## profile` row under key `profile`. -**raw = inspect_native id=`id`** -**prof = profile name=`profile`** -**out = table.put in=`raw` at="profile" value=`prof`** -*out* +We retain **`raw` = [Inspect native](inspect_native(id=`id`))**. +We retain **`prof` = [Profile](profile(name=`profile`))**. +We retain **`out` = [Set the profile field in the new record](table.put(in=`raw`, at="profile", value=`prof`))**. +Return *out*. ## report - + `id` - + `path`=sandbox-diff.md + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| path | any | "sandbox-diff.md" | Explicit filesystem path; honor the documented filesystem root and operation effects | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite). | + +Use `id`, `path`="sandbox-diff.md" as the inputs for this operation. O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite). -**pending = diff id=`id`** -**n = len value=`pending`** -**body = "# Sandbox diff report\n\nPending changes: "** -**body = body + n** -**body = body + "\n\n| path | kind |\n|------|------|\n"** +We retain **`pending` = [Diff](diff(id=`id`))**. +We retain **`n` = [Len](len(value=`pending`))**. +We retain **body = "# Sandbox diff report\n\nPending changes: "**. +We retain **body = body + n**. +We retain **body = body + "\n\n| path | kind |\n|------|------|\n"**. - [row](遍历 pending 为 row) - **p = [path](access(row, "path"))** - **k = [kind](access(row, "kind"))** - **body = body + "| "** - **body = body + p** - **body = body + " | "** - **body = body + k** - **body = body + " |\n"** -> fs.write_text path=`path` text=`body` + We retain **`p` = [Read path field](access(`row`, "path"))**. + We retain **`k` = [Read kind field](access(`row`, "kind"))**. + We retain **body = body + "| "**. + We retain **body = body + p**. + We retain **body = body + " | "**. + We retain **body = body + k**. + We retain **body = body + " |\n"**. +We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`body`))**. **out = ** @@ -190,4 +317,4 @@ O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report |------|-------| | `path` | `n` | -*out* +Return *out*. diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md index 2e890a1..8fe04d7 100644 --- a/ext/ai/大模型.mq.md +++ b/ext/ai/大模型.mq.md @@ -5,6 +5,7 @@ description: >- Marqdo 大模型智能原语 — 提问 / 流式 / 收集 / 命名句柄。 OpenAI 兼容与 Ollama HTTP 藏在语义面之后。 导入: + table: lib/table.mq.md 系统: lib/系统.mq.md json: lib/json.mq.md 文件: lib/文件.mq.md @@ -12,64 +13,90 @@ description: >- openai: ext/ai/llm/openai.mq.md --- -## 加载环境 - + `路径`=None +本文件是中文模型资源门面;从[中文入口](索引.mq.md)可以先运行无需联网的事件收集示例。提供方请求实现位于 llm 子目录,智能体编排位于智能体文件。创建资源只解析配置;真实请求还需插件、服务和授权。修改时同时核对英文模型面、语义事件、用量字段与传输失败,不把空文本当作可靠的成功信号。 -*> 系统.加载环境 路径=`路径`* +## 加载环境 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权根目录内的文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。 | + +这里使用`路径`=None。 + +读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。 + +完成后返回*[调用 加载环境](系统.加载环境(路径=`路径`))*。 ## 收集 - + `事件` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 事件 | any | 必填 | 按顺序排列的流事件记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | Collapse stream events to text. Supports semantic `delta`/`done.result` and native-plugin raw frames (`type=data` + OpenAI chunk JSON). | + +这里使用`事件`。 Collapse stream events to text. Supports semantic `delta`/`done.result` and native-plugin raw frames (`type=data` + OpenAI chunk JSON). -**answer = ""** +例如先收到两个 delta 再收到 done 时,以最后非空 result 为准;只收到无内容事件则返回空文本。按事件顺序处理文本:delta 与 text 的 text 字段追加到当前回答;done 中非空的 result 覆盖累积文本;error 中非空的 message 也成为当前文本。因此返回的是收集文本,不是独立的成功状态。调用方若需区分失败,应同时检查原始事件,不能把非空文本当成请求成功。 + +兼容的 data 事件承载提供方 JSON。结束标记 [DONE] 不作为正文;普通数据从首条 choice 的 delta.content 或 message.content 读取。缺失内容不会凭空产生片段,JSON 解码失败仍遵循解析库的诊断。这里不排序、不重试,也不发送模型请求;输入顺序决定最终文字,空事件序列得到空字符串。 + +得到**answer = ""**。 - [ev](遍历 事件 为 ev) - **t = [type](access(ev, "type"))** + 得到**`t` = [读取 type 字段](access(`ev`, "type"))**。 1. `t` == "done" - **done_r = [result](access(ev, "result"))** + 得到**`done_r` = [读取 result 字段](access(`ev`, "result"))**。 1. `done_r` - **answer = `done_r`** + 得到**answer = `done_r`**。 2. * **_ = 1** 2. `t` == "error" - **em = [message](access(ev, "message"))** + 得到**`em` = [读取 message 字段](access(`ev`, "message"))**。 1. `em` - **answer = `em`** + 得到**answer = `em`**。 2. * **_ = 1** 3. `t` == "delta" 4. `t` == "text" - **chunk = [text](access(ev, "text"))** + 得到**`chunk` = [读取 text 字段](access(`ev`, "text"))**。 1. `chunk` - **answer = answer + chunk** + 得到**answer = answer + chunk**。 2. * **_ = 1** 5. `t` == "data" - **raw = [data](access(ev, "data"))** + 得到**`raw` = [读取 data 字段](access(`ev`, "data"))**。 1. `raw` 1. `raw` == "[DONE]" **_ = 1** 2. * - **parsed = > json.parse text=`raw`** + 得到**`parsed` = [解析 JSON 传输文本](json.parse(text=`raw`))**。 1. `parsed` - **choices = [choices](access(parsed, "choices"))** + 得到**`choices` = [读取 choices 字段](access(`parsed`, "choices"))**。 1. `choices` - **c0 = [1](access(choices, "1"))** - **delta = [delta](access(c0, "delta"))** + 得到**`c0` = [读取 1 字段](access(`choices`, "1"))**。 + 得到**`delta` = [读取 delta 字段](access(`c0`, "delta"))**。 1. `delta` - **piece = [content](access(delta, "content"))** + 得到**`piece` = [读取 content 字段](access(`delta`, "content"))**。 1. `piece` - **answer = answer + piece** + 得到**answer = answer + piece**。 2. * **_ = 1** 2. * - **msg = [message](access(c0, "message"))** + 得到**`msg` = [读取 message 字段](access(`c0`, "message"))**。 1. `msg` - **piece = [content](access(msg, "content"))** + 得到**`piece` = [读取 content 字段](access(`msg`, "content"))**。 1. `piece` - **answer = answer + piece** + 得到**answer = answer + piece**。 2. * **_ = 1** 2. * @@ -84,180 +111,291 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON). **_ = 1** 1. not `answer` - **answer = ""** -*answer* + 得到**answer = ""**。 +完成后返回*answer*。 ## 流式结果 - + `事件` -*> 收集 事件=`事件`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 事件 | any | 必填 | 按顺序排列的流事件记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将流事件交给同源收集器,返回最终回答文本。 | + +这里使用`事件`。 + +将流事件交给同源收集器,返回最终回答文本。 + +完成后返回*[调用 收集](收集(事件=`事件`))*。 ## 用量 - + `数据` -*> openai.usage_from data=`数据`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | any | 必填 | 交给本操作处理的结构化数据 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 从提供方响应中提取 token 用量,缺失计数采用公开实现约定。 | + +这里使用`数据`。 + +从提供方响应中提取 token 用量,缺失计数采用公开实现约定。 + +完成后返回*[调用 usage from](openai.usage_from(data=`数据`))*。 ## 创建 - + `模型`=None - + `基址`=None - + `密钥`=None - + `后端`=openai-compatible - + `名`=None -**h = > 大模型 模型=`模型` 基址=`基址` 密钥=`密钥` 后端=`后端` 名=`名`** -*h* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 模型 | any | None | 已配置的模型资源或模型标识 | +| 基址 | any | None | 提供方 API 基址 | +| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | +| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 | +| 名 | any | None | 本操作注册或查找的名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。 | + +这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。 + +按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。 + +得到**`h` = [调用 大模型](大模型(模型=`模型`, 基址=`基址`, 密钥=`密钥`, 后端=`后端`, 名=`名`))**。 +完成后返回*h*。 ## 快速 - + `模型`=None - + `基址`=None - + `密钥`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 模型 | any | None | 已配置的模型资源或模型标识 | +| 基址 | any | None | 提供方 API 基址 | +| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 | + +这里使用`模型`=None、`基址`=None、`密钥`=None。 1. `模型` - **mdl = 模型** + 得到**mdl = 模型**。 2. * - **mdl = > 系统.取环境 名="MARQDO_LLM_FAST_MODEL"** + 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_FAST_MODEL"))**。 -*> 创建 模型=`mdl` 基址=`基址` 密钥=`密钥` 名="fast" 后端="openai-compatible"* +完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="fast", 后端="openai-compatible"))*。 ## 推理 - + `模型`=None - + `基址`=None - + `密钥`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 模型 | any | None | 已配置的模型资源或模型标识 | +| 基址 | any | None | 提供方 API 基址 | +| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 | + +这里使用`模型`=None、`基址`=None、`密钥`=None。 1. `模型` - **mdl = 模型** + 得到**mdl = 模型**。 2. * - **mdl = > 系统.取环境 名="MARQDO_LLM_REASONING_MODEL"** + 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_REASONING_MODEL"))**。 -*> 创建 模型=`mdl` 基址=`基址` 密钥=`密钥` 名="reasoning" 后端="openai-compatible"* +完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="reasoning", 后端="openai-compatible"))*。 ## 提示正文 - + `源` -**sw = > 文本.开头是 内容=`源` 前缀="---"** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 源 | any | 必填 | 提示正文或源码来源 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 从指定文本构造提示正文,保留输入内容而不请求模型。 | + +这里使用`源`。 + +从指定文本构造提示正文,保留输入内容而不请求模型。 + +这里只识别源文本开头的前置元数据,且仅对声明为 prompt 或提示的文档提取正文。普通 Markdown、没有结束分隔线的文本和其他类型文档原样保留。正文只取当前分隔实现得到的首段并去掉两端空白,不承担通用 YAML 解析或提示模板插值;需要完整文件时使用文件库读取。 + +得到**`sw` = [调用 开头是](文本.开头是(内容=`源`, 前缀="---"))**。 1. 非 `sw` - *源* + 完成后返回*源*。 2. * - **parts = > split value=`源` sep="\n---\n"** - **n = > len value=`parts`** + 得到**`parts` = [调用 split](split(value=`源`, sep="\n---\n"))**。 + 得到**`n` = [调用 len](len(value=`parts`))**。 1. `n` < 2 - *源* + 完成后返回*源*。 2. * - **fm = > at value=`parts` index=0** - **is_p = > 文本.包含 内容=`fm` 子串="type: prompt"** + 得到**`fm` = [调用 at](at(value=`parts`, index=0))**。 + 得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="type: prompt"))**。 1. 非 `is_p` - **is_p = > 文本.包含 内容=`fm` 子串="类型: 提示"** + 得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="类型: 提示"))**。 2. * **_ = 1** 1. `is_p` - **body = > at value=`parts` index=1** - *> 文本.去空白 s=`body`* + 得到**`body` = [调用 at](at(value=`parts`, index=1))**。 + 完成后返回*[调用 去空白](文本.去空白(s=`body`))*。 2. * - *源* + 完成后返回*源*。 ## 加载提示 - + `路径` -**raw = > 文件.读文本 路径=`路径`** -*> 提示正文 源=`raw`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权根目录内的文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 从指定文件加载提示正文;文件访问仍受宿主文件权限限制。 | + +这里使用`路径`。 + +从指定文件加载提示正文;文件访问仍受宿主文件权限限制。 + +得到**`raw` = [读取指定文件的 UTF-8 正文](文件.读文本(路径=`路径`))**。 +完成后返回*[调用 提示正文](提示正文(源=`raw`))*。 ## 提示 - + `路径`=None - + `文本`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权根目录内的文件路径 | +| 文本 | any | None | 本操作接收的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 提示正文,保留同源能力的返回值和失败语义。 | + +这里使用`路径`=None、`文本`=None。 1. `路径` - *> 加载提示 路径=`路径`* + 完成后返回*[调用 加载提示](加载提示(路径=`路径`))*。 2. `文本` - *> 提示正文 源=`文本`* + 完成后返回*[调用 提示正文](提示正文(源=`文本`))*。 3. * - > 打印 内容=ext/ai/大模型.提示: 请传 路径= 或 文本= - > 系统.退出 码=1 + 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提示: 请传", 路径="或", 文本=""))**。 + 这里**[调用 退出](系统.退出(码=1))**。 ## 提问 - + `提示`=None - + `路径`=None - + `模型`=None - + `基址`=None - + `密钥`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | None | 提供给模型的提示内容 | +| 路径 | any | None | 授权根目录内的文件路径 | +| 模型 | any | None | 已配置的模型资源或模型标识 | +| 基址 | any | None | 提供方 API 基址 | +| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | +| p | any | 必填 | Prompt value passed to the selected model | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | + +这里使用`提示`=None、`路径`=None、`模型`=None、`基址`=None、`密钥`=None、`p`。 1. `路径` - **p = > 加载提示 路径=`路径`** + 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 2. `提示` - **p = 提示** + 得到**p = 提示**。 3. * - > 打印 内容=ext/ai/大模型.提问: 请传 提示= 或 路径= - > 系统.退出 码=1 + 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提问: 请传", 提示="或", 路径=""))**。 + 这里**[调用 退出](系统.退出(码=1))**。 -**m = > 创建 模型=`模型` 基址=`基址` 密钥=`密钥`** -**r = > m.提问 提示=`p`** -*[text](access(r, "text"))* +得到**`m` = [调用 创建](创建(模型=`模型`, 基址=`基址`, 密钥=`密钥`))**。 +得到**`r` = [调用 提问](m.提问(提示=`p`))**。 +完成后返回*[text](access(r, "text"))*。 # 大模型 - + `模型`=None - + `基址`=None - + `密钥`=None - + `后端`=openai-compatible - + `名`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 模型 | any | None | 已配置的模型资源或模型标识 | +| 基址 | any | None | 提供方 API 基址 | +| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 | +| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 | +| 名 | any | None | 本操作注册或查找的名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 | + +这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。 1. `密钥` - **key = 密钥** +构造器只整理连接配置并返回资源记录,不在此请求回答。显式传入的密钥优先,其后依次读取 OPENAI_API_KEY 与 MARQDO_LLM_API_KEY。兼容后端没有密钥会输出原因并以非零状态结束;本地 ollama 使用占位凭据以维持相同资源结构。记录包含实际凭据,应由调用方保管,避免直接打印整个句柄。 + +基址的选择同样保留显式值。ollama 未配置时使用本机兼容接口;其他后端依次尝试 OPENAI_BASE_URL、MARQDO_LLM_BASE_URL,最后采用公开默认地址。模型名依次来自显式值、OPENAI_MODEL、MARQDO_LLM_MODEL,最后按后端选用默认模型。默认模型名称只是现有运行约定,不保证提供方已开通、服务器已安装或网络可达。 + +返回记录保存后续请求所需的模型、后端、请求后缀、认证前缀和可选名称。实例方法从这个记录读取配置;改变环境不会自动重建已有句柄。需要切换配置时重新构造,不要把资源创建成功等同于鉴权或连通性验证。真实请求还要准备对应原生插件与运行授权;离线读取配置和真实网络调用是两个阶段。 + +例如在没有外部服务的离线配置检查中,可以显式选择 ollama、提供模型名与本地基址,只核对返回字段而不调用提问。在线验收则必须再检查真实请求的结束原因和用量。删除或覆盖环境配置前,也应考虑已有句柄仍保存旧凭据;本构造器不会主动清理其他资源或替调用方撤销密钥。 + + 得到**key = 密钥**。 2. * - **key = > 系统.取环境 名="OPENAI_API_KEY"** + 得到**`key` = [调用 取环境](系统.取环境(名="OPENAI_API_KEY"))**。 1. 非 `key` - **key = > 系统.取环境 名="MARQDO_LLM_API_KEY"** + 得到**`key` = [调用 取环境](系统.取环境(名="MARQDO_LLM_API_KEY"))**。 2. * **_ = 1** 1. `后端` == ollama 1. 非 `key` - **key = "ollama"** + 得到**key = "ollama"**。 2. * **_ = 1** 2. 非 `key` - > 打印 内容=ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY - > 系统.退出 码=1 + 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY"))**。 + 这里**[调用 退出](系统.退出(码=1))**。 3. * **_ = 1** 1. `基址` - **url = 基址** + 得到**url = 基址**。 2. `后端` == ollama - **url = > 系统.取环境 名="OLLAMA_HOST"** + 得到**`url` = [调用 取环境](系统.取环境(名="OLLAMA_HOST"))**。 1. 非 `url` - **url = "http://127.0.0.1:11434/v1"** + 得到**url = "http://127.0.0.1:11434/v1"**。 2. * **_ = 1** 3. * - **url = > 系统.取环境 名="OPENAI_BASE_URL"** + 得到**`url` = [调用 取环境](系统.取环境(名="OPENAI_BASE_URL"))**。 1. 非 `url` - **url = > 系统.取环境 名="MARQDO_LLM_BASE_URL"** + 得到**`url` = [调用 取环境](系统.取环境(名="MARQDO_LLM_BASE_URL"))**。 2. * **_ = 1** 1. 非 `url` - **url = "https://api.openai.com/v1"** + 得到**url = "https://api.openai.com/v1"**。 2. * **_ = 1** 1. `模型` - **mdl = 模型** + 得到**mdl = 模型**。 2. * - **mdl = > 系统.取环境 名="OPENAI_MODEL"** + 得到**`mdl` = [调用 取环境](系统.取环境(名="OPENAI_MODEL"))**。 1. 非 `mdl` - **mdl = > 系统.取环境 名="MARQDO_LLM_MODEL"** + 得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_MODEL"))**。 2. * **_ = 1** 1. 非 `mdl` 1. `后端` == ollama - **mdl = "llama3.2"** + 得到**mdl = "llama3.2"**。 2. * - **mdl = "gpt-4o-mini"** + 得到**mdl = "gpt-4o-mini"**。 2. * **_ = 1** 1. `名` - **nm = 名** + 得到**nm = 名**。 2. * - **nm = None** + 得到**nm = None**。 `h` = @@ -265,36 +403,52 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON). |-------|---------|---------|----------|-------|--------|--------|------| | 大模型 | `后端` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` | -*h* +完成后返回*h*。 ## 提问 - + `提示`=None - + `路径`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | None | 提供给模型的提示内容 | +| 路径 | any | None | 授权根目录内的文件路径 | +| p | any | 必填 | Prompt value passed to the selected model | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | + +这里使用`提示`=None、`路径`=None、`p`。 1. `路径` - **p = > 加载提示 路径=`路径`** -2. `提示` - **p = 提示** -3. * - > 打印 内容=ext/ai/大模型: 提问需要 提示= 或 路径= - > 系统.退出 码=1 +路径与直接提示同时存在时,先从路径加载提示;否则使用非空提示。两者都缺失时明确结束运行。当前接口还保留历史推断得到的 p 输入,表中如实列出其签名;本方法实际按上述分支重新设置请求正文,调用方不应把这个内部兼容参数当成另一种提示来源。 -**pack = > 自.完整结果 提示=`p` 流式=False 打印增量=False** -**text = > json.get value=`pack` key="text"** -**usage = > json.get value=`pack` key="usage"** -**finish = > json.get value=`pack` key="finish"** -**tc = > json.get value=`pack` key="tool_calls"** +完整结果提供文本、结束原因、工具调用与用量。这里将它们整理为含模型与后端的记录;工具调用缺失时给出空列表。tokens 取 usage 中的 total_tokens,不能由回答字符数推算。llm_calls 是该接口的调用计数字段,并非计费凭据或独立的成功证明。网络失败应按完整结果的 finish 和相关诊断处理,不能只看 text 是否非空。 + +例如消费返回值时,先确认 finish,再取 text 展示;若 tool_calls 非空,则由上层明确决定是否进入受授权的工具流程。本方法只整理模型响应,不会看到工具请求就自动执行,也不会为调用方写入会话记录或文件。 + + 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 +2. `提示` + 得到**p = 提示**。 +3. * + 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 提问需要", 提示="或", 路径=""))**。 + 这里**[调用 退出](系统.退出(码=1))**。 + +得到**`pack` = [调用 完整结果](自.完整结果(提示=`p`, 流式=False, 打印增量=False))**。 +得到**`text` = [读取 text 字段](json.get(value=`pack`, key="text"))**。 +得到**`usage` = [读取 usage 字段](json.get(value=`pack`, key="usage"))**。 +得到**`finish` = [读取 finish 字段](json.get(value=`pack`, key="finish"))**。 +得到**`tc` = [读取 tool_calls 字段](json.get(value=`pack`, key="tool_calls"))**。 1. not `tc` - **tc = > json.parse text=[]** + 没有工具调用时,使用**tc = [创建空工具调用列表](table.empty_list())**,避免将缺失值误作一条调用。 2. * **_ = 1** 表单元格会遮蔽 `自` / 列名,先取出字段再组结果表。 -**mdl = [model](access(自, "model"))** -**b = [backend](access(自, "backend"))** -**nm = [name](access(自, "name"))** -**tt = [total_tokens](access(usage, "total_tokens"))** +得到**`mdl` = [读取 model 字段](access(`自`, "model"))**。 +得到**`b` = [读取 backend 字段](access(`自`, "backend"))**。 +得到**`nm` = [读取 name 字段](access(`自`, "name"))**。 +得到**`tt` = [读取 total_tokens 字段](access(`usage`, "total_tokens"))**。 `result` = @@ -302,45 +456,86 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON). |------|-------|--------|---------|-------|------|-----------|--------|------------| | `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` | -*result* +完成后返回*result*。 ## 流式 - + `提示`=None - + `路径`=None - + `打印增量`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | None | 提供给模型的提示内容 | +| 路径 | any | None | 授权根目录内的文件路径 | +| 打印增量 | any | False | 是否输出流式增量文本 | +| p | any | 必填 | Prompt value passed to the selected model | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 | + +这里使用`提示`=None、`路径`=None、`打印增量`=False、`p`。 1. `路径` - **p = > 加载提示 路径=`路径`** + 得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。 2. `提示` - **p = 提示** + 得到**p = 提示**。 3. * - > 打印 内容=ext/ai/大模型: 流式需要 提示= 或 路径= - > 系统.退出 码=1 + 这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 流式需要", 提示="或", 路径=""))**。 + 这里**[调用 退出](系统.退出(码=1))**。 -*> 自.运行 提示=`p` 流式=True 打印增量=`打印增量`* +完成后返回*[调用 运行](自.运行(提示=`p`, 流式=True, 打印增量=`打印增量`))*。 ## 完整结果 - + `提示` - + `流式`=False - + `打印增量`=False -*> openai.chat_completions base_url=[base_url](access(自, "base_url")) api_key=[api_key](access(自, "api_key")) model=[model](access(自, "model")) prompt=`提示` stream=`流式` echo=`打印增量` suffix=[suffix](access(自, "suffix")) bearer=[bearer](access(自, "bearer"))* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | 必填 | 提供给模型的提示内容 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 使用此大模型资源请求完整响应,保留文本、用量和失败信息。 | + +这里使用`提示`、`流式`=False、`打印增量`=False。 + +使用此大模型资源请求完整响应,保留文本、用量和失败信息。 + +完成后返回*[调用 chat completions](openai.chat_completions(base_url=[base_url](access(`自`, "base_url")), api_key=[api_key](access(`自`, "api_key")), model=[model](access(`自`, "model")), prompt=`提示`, stream=`流式`, echo=`打印增量`, suffix=[suffix](access(`自`, "suffix")), bearer=[bearer](access(`自`, "bearer"))))*。 ## 运行 - + `提示` - + `流式`=False - + `打印增量`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | 必填 | 提供给模型的提示内容 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 | + +这里使用`提示`、`流式`=False、`打印增量`=False。 1. `流式` - **pack = > 自.完整结果 提示=`提示` 流式=True 打印增量=`打印增量`** - *[events](access(pack, "events"))* + 得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=True, 打印增量=`打印增量`))**。 + 完成后返回*[events](access(pack, "events"))*。 2. * - **pack = > 自.完整结果 提示=`提示` 流式=False 打印增量=`打印增量`** - *[text](access(pack, "text"))* + 得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=False, 打印增量=`打印增量`))**。 + 完成后返回*[text](access(pack, "text"))*。 ## 聊天 - + `提示` - + `流式`=False - + `打印增量`=False -*> 自.运行 提示=`提示` 流式=`流式` 打印增量=`打印增量`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 提示 | any | 必填 | 提供给模型的提示内容 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。 | + +这里使用`提示`、`流式`=False、`打印增量`=False。 + +使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。 + +完成后返回*[调用 运行](自.运行(提示=`提示`, 流式=`流式`, 打印增量=`打印增量`))*。 diff --git a/ext/ai/智能体.mq.md b/ext/ai/智能体.mq.md index ec468ed..1a725a9 100644 --- a/ext/ai/智能体.mq.md +++ b/ext/ai/智能体.mq.md @@ -14,82 +14,127 @@ description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编 插件: lib/插件.mq.md --- +本文件保留中文智能体的模型运行接口与工具调用流程。[中文入口](索引.mq.md)说明模型、编排与试跑的职责边界。内部函数的存在不代表它已进入模型白名单;工具请求必须由作者明确授权。开发时用离线模型替身核对历史、调用点、结果与写回,再测试真实传输。需要隔离执行时使用实际试跑入口,不能仅向结果附加配置记录。 + ## 构建单步上下文 - + `智能体` - + `任务` - + `源码深度`=default - + `技能深度`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 智能体 | any | 必填 | 本库创建的智能体配置或接收者 | +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 源码深度 | any | "default" | 源码上下文读取深度,默认遵循预算 | +| 技能深度 | any | "default" | 技能上下文读取深度,默认遵循预算 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。 编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。 实现委托 `agent.build_step_context`(与英文版同源)。 | + +这里使用`智能体`、`任务`、`源码深度`="default"、`技能深度`="default"。 组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。 编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。 实现委托 `agent.build_step_context`(与英文版同源)。 -*> agent.build_step_context agent=`智能体` task=`任务` source_depth=`源码深度` skill_depth=`技能深度`* +完成后返回*[调用 build step context](agent.build_step_context(agent=`智能体`, task=`任务`, source_depth=`源码深度`, skill_depth=`技能深度`))*。 --- ## 提取工具名 - + `回复` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 回复 | any | 必填 | 待解析的模型回复,不直接作为执行授权 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。 | + +这里使用`回复`。 解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。 -**esc = > json.parse text={"nl":"\n"}** -**nl = > json.get value=`esc` key="nl"** -**text = > trim value=`回复`** -**lines = > split value=`text` sep=`nl`** -**found = 空** +这里按行识别工具协议,先去掉行两端空白,再按半角冒号分隔。CALL 或“调用”作为前缀时,后面的片段成为候选工具名;没有匹配则返回空值。当前实现不把任意自然语言中的函数名当作请求,也不在这里执行函数。候选值仍要经过运行工具的白名单判断。 + +注意实际分隔符是半角冒号,全角冒号的示意不能保证被本函数识别。同一回复包含多个有效协议行时,后面的匹配会覆盖前面的候选;工具名中的额外冒号也不作为完整名称保留。生成端应只输出一条明确的 CALL:name,避免依赖这种兼容解析。 + +保留所需的文本分隔符,先**esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**。 +得到**`nl` = [读取 nl 字段](json.get(value=`esc`, key="nl"))**。 +得到**`text` = [调用 trim](trim(value=`回复`))**。 +得到**`lines` = [调用 split](split(value=`text`, sep=`nl`))**。 +得到**found = 空**。 - [line](遍历 `lines` 为 `line`) - **t = > trim value=`line`** - **parts = > split value=`t` sep=:** - **n = > len value=`parts`** + 得到**`t` = [调用 trim](trim(value=`line`))**。 + 得到**`parts` = [调用 split](split(value=`t`, sep=":"))**。 + 得到**`n` = [调用 len](len(value=`parts`))**。 1. `n` > 1 - **head = > at value=`parts` index=0** - **head = > trim value=`head`** - **rest = > at value=`parts` index=1** - **rest = > trim value=`rest`** + 得到**`head` = [调用 at](at(value=`parts`, index=0))**。 + 得到**`head` = [调用 trim](trim(value=`head`))**。 + 得到**`rest` = [调用 at](at(value=`parts`, index=1))**。 + 得到**`rest` = [调用 trim](trim(value=`rest`))**。 1. `head` == CALL - **found = rest** + 得到**found = rest**。 2. `head` == 调用 - **found = rest** + 得到**found = rest**。 3. * **_ = 1** 2. * **_ = 1** -*found* +完成后返回*found*。 --- ## 运行工具 - + `工具` - + `名` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 | +| 名 | any | 必填 | 本操作注册或查找的名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。 | + +这里使用`工具`、`名`。 白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。 -**allowed = > agent_tool_allowed tools=`工具` name=`名`** +得到**`allowed` = [调用 tool allowed](agent_tool_allowed(tools=`工具`, name=`名`))**。 1. `allowed` - **id = > 子任务.启动 函数=`名`** - *> 子任务.等待 id=`id`* + 得到**`id` = [调用 启动](子任务.启动(函数=`名`))**。 + 完成后返回*[调用 等待](子任务.等待(id=`id`))*。 2. * - **msg = "Tool not allowed:"** - *msg + `名`* + 得到**msg = "Tool not allowed:"**。 + 完成后返回*msg + `名`*。 # 智能体 - + `大模型` - + `工具` - + `站立提示` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 大模型 | any | 必填 | 按提供方配置创建的模型资源 | +| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 | +| 站立提示 | any | 必填 | 作者提供的常驻任务说明 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 加载 ABI v2 agent 插件(会话袋 + 上下文查询)。 | + +这里使用`大模型`、`工具`、`站立提示`。 加载 ABI v2 agent 插件(会话袋 + 上下文查询)。 -**p = > 插件.原生路径 名="agent"** +创建记录同时注册历史会话;传入的模型应提供运行方法,工具来自作者明确给出的清单。构造成功表示资源就绪,不表示已执行任务。 + +得到**`p` = [定位已安装的原生插件](插件.原生路径(名="agent"))**。 1. `p` - > 插件.加载 路径=`p` + 这里**[调用 加载](插件.加载(路径=`p`))**。 2. * - > 打印 内容=ext/ai/智能体: 未找到原生 agent 插件(请先 cargo build -p marqdo_plugin_agent 或 marqdo ext add agent) - > 系统.退出 码=1 + 这里**[输出本步已准备的消息](打印(内容="ext/ai/智能体: 未找到原生 agent 插件(请先 cargo build -p marqdo_plugin_agent 或 marqdo ext add agent)"))**。 + 这里**[调用 退出](系统.退出(码=1))**。 + +得到**`id` = [调用 alloc](agent_alloc())**。 -**id = > agent_alloc** `h` = | _type | id | model | tools | @@ -97,49 +142,81 @@ description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编 | 智能体 | `id` | `大模型` | `工具` | 1. `站立提示` - **h = table.put in=`h` at="standing" value=`站立提示`** + 得到**`h` = [在新记录中设置 standing 字段](table.put(in=`h`, at="standing", value=`站立提示`))**。 2. * **_ = 1** -*h* +完成后返回*h*。 ## 清空历史 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 清空本智能体 id 的插件会话袋。 | + 清空本智能体 id 的插件会话袋。 -**id = > json.get value=`自` key="id"** -> agent_history_clear id=`id` -**** +得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。 +这里**[调用 history clear](agent_history_clear(id=`id`))**。 +完成后返回*None*。 ## 试跑 - + `路径`=None - + `源码`=None - + `根目录`=None - + `写入路径`=None - + `文本`=None - + `提交`=真 - + `配置`=default + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权根目录内的文件路径 | +| 源码 | any | None | 本次检查或试跑的源码文本 | +| 根目录 | any | None | 明确选择的工程或试运行根目录 | +| 写入路径 | any | None | 明确的产物路径,或不写出时使用 None | +| 文本 | any | None | 本操作接收的文本 | +| 提交 | any | True | 是否在验证完成后晋升试运行变更 | +| 配置 | any | "default" | 试运行使用的能力配置 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。 | + +这里使用`路径`=None、`源码`=None、`根目录`=None、`写入路径`=None、`文本`=None、`提交`=True、`配置`="default"。 O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。 -*> agent.trial path=`路径` source=`源码` root=`根目录` write_path=`写入路径` text=`文本` commit=`提交` profile=`配置`* +完成后返回*[调用 trial](agent.trial(path=`路径`, source=`源码`, root=`根目录`, write_path=`写入路径`, text=`文本`, commit=`提交`, profile=`配置`))*。 ## 单步 - + `任务` - + `写回`=真 - + `流式`=假 - + `打印增量`=假 - + `沙盒`=假 - + `沙盒配置`=default -原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 写回 | any | True | 是否向任务文档写回观察结果 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | +| 沙盒 | any | False | 是否采用 CoW 试运行路径 | +| 沙盒配置 | any | "default" | CoW 试运行能力配置 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。 | + +这里使用`任务`、`写回`=True、`流式`=False、`打印增量`=False、`沙盒`=False、`沙盒配置`="default"。 + +原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。 -**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`** -**id = > json.get value=`自` key="id"** -**model = > json.get value=`自` key="model"** -**tools = > json.get value=`自` key="tools"** +默认会写回调用文档;若只想观察结果,请显式传入写回=False,避免演示修改任务源码。这一轮先把用户任务写入当前会话历史,再用调用点上下文请求模型。流式分支先收集事件得到最终文本,普通分支直接取得回复。随后只把明确的工具协议视作调用候选;其余文字作为回答保留。中文兼容面使用模型的运行方法,并不要求调用方假装它具有英文资源的全部接口。 + +有工具候选时,运行工具负责核对作者白名单并等待子任务。拒绝结果进入 error 字段;成功结果被序列化后提供给模型,再形成面向用户的回答。tool_result 因而保存的是序列化文本,消费它时不要误当原始业务记录。没有工具候选时直接使用本次回复,避免重复请求。 + +这一步会把最终助手回复追加到同一历史,并按写回开关将完整记录放入调用点的 ok 或 error 槽。演示或只读任务应明确关闭写回,生产流程则要为实际文件操作准备权限。返回记录中的 status、decision、result 和工具字段分别说明流程状态、原始决定与最终答案,它们不能相互替代;任务特有的正确性仍由调用方验证。 + +这里的沙盒开关只给返回记录附加所选配置行,不会把上述模型或工具调用迁移到 CoW 环境。需要隔离试运行,应调用试跑入口或使用具有实际 CoW 执行边界的工程运行流程。不要依据 sandbox_profile 字段的存在宣称副作用已经隔离。写回失败、插件失败和传输失败仍沿既有运行诊断报告,函数没有通用事务回滚能力。 + +开发此方法时,先使用只返回固定文本的离线模型替身确认上下文、历史与结果字段,再分别验证工具允许、工具拒绝和写回开关。涉及真实模型的测试还应覆盖流式结束、错误事件和无文本结果。保持这两类验证分开,才能判断错误来自编排还是传输,避免用一次线上回答掩盖未执行的分支。 + +得到**`ctx` = [调用 构建单步上下文](构建单步上下文(智能体=`自`, 任务=`任务`))**。 +得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。 +得到**`model` = [读取 model 字段](json.get(value=`自`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`自`, key="tools"))**。 `user_turn` = @@ -147,17 +224,18 @@ O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成 |------|---------| | user | `任务` | -> agent_history_append id=`id` item=`user_turn` +这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`user_turn`))**。 1. `流式` - **evs = > model.运行 提示=`ctx` 流式=真 打印增量=`打印增量`** - **reply = > 大模型.流式结果 事件=`evs`** + 得到**`evs` = [调用 运行](model.运行(提示=`ctx`, 流式=True, 打印增量=`打印增量`))**。 + 得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs`))**。 2. * - **reply = > model.运行 提示=`ctx`** + 得到**`reply` = [调用 运行](model.运行(提示=`ctx`))**。 + +得到**`reply` = [调用 trim](trim(value=`reply`))**。 +得到**decision = reply**。 +得到**`tool_name` = [调用 提取工具名](提取工具名(回复=`reply`))**。 -**reply = > trim value=`reply`** -**decision = reply** -**tool_name = > 提取工具名 回复=`reply`** `out` = | status | task | decision | @@ -165,208 +243,280 @@ O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成 | ok | `任务` | `decision` | 1. `tool_name` - **tool_out = > 运行工具 工具=`tools` 名=`tool_name`** - **tool_s = > json.stringify value=`tool_out`** - **deny = > split value=`tool_s` sep="Tool not allowed"** - **deny_n = > len value=`deny`** + 得到**`tool_out` = [调用 运行工具](运行工具(工具=`tools`, 名=`tool_name`))**。 + 得到**`tool_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`tool_out`))**。 + 得到**`deny` = [调用 split](split(value=`tool_s`, sep="Tool not allowed"))**。 + 得到**`deny_n` = [调用 len](len(value=`deny`))**。 1. `deny_n` > 1 - **out = table.put in=`out` at="status" value="error"** - **out = table.put in=`out` at="error" value=`tool_s`** - **reply = tool_s** + 得到**`out` = [在新记录中设置 status 字段](table.put(in=`out`, at="status", value="error"))**。 + 得到**`out` = [在新记录中设置 error 字段](table.put(in=`out`, at="error", value=`tool_s`))**。 + 得到**reply = tool_s**。 2. * - **task_s = > json.stringify value=`任务`** - **fp = "The user asked:"** - **fp = fp + task_s** - **fp = fp + ". Tool"** - **fp = fp + tool_name** - **fp = fp + "ran via subtask and returned:"** - **fp = fp + tool_s** - **fp = fp + ". Reply to the user briefly."** + 得到**`task_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`任务`))**。 + 得到**fp = "The user asked:"**。 + 得到**fp = fp + task_s**。 + 得到**fp = fp + ". Tool"**。 + 得到**fp = fp + tool_name**。 + 得到**fp = fp + "ran via subtask and returned:"**。 + 得到**fp = fp + tool_s**。 + 得到**fp = fp + ". Reply to the user briefly."**。 1. `流式` - **evs2 = > model.运行 提示=`fp` 流式=真 打印增量=`打印增量`** - **reply = > 大模型.流式结果 事件=`evs2`** + 得到**`evs2` = [调用 运行](model.运行(提示=`fp`, 流式=True, 打印增量=`打印增量`))**。 + 得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs2`))**。 2. * - **reply = > model.运行 提示=`fp`** - **out = table.put in=`out` at="tool" value=`tool_name`** - **out = table.put in=`out` at="tool_result" value=`tool_s`** - **out = table.put in=`out` at="result" value=`reply`** + 得到**`reply` = [调用 运行](model.运行(提示=`fp`))**。 + 得到**`out` = [在新记录中设置 tool 字段](table.put(in=`out`, at="tool", value=`tool_name`))**。 + 得到**`out` = [在新记录中设置 tool_result 字段](table.put(in=`out`, at="tool_result", value=`tool_s`))**。 + 得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。 2. * - **out = table.put in=`out` at="result" value=`reply`** + 得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。 `as_turn` = | role | content | |------|---------| | assistant | `reply` | -> agent_history_append id=`id` item=`as_turn` +这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`as_turn`))**。 1. `沙盒` - **配置行 = sandbox.profile name=`沙盒配置`** - **out = table.put in=`out` at="sandbox_profile" value=`配置行`** + 得到**`配置行` = [调用 profile](sandbox.profile(name=`沙盒配置`))**。 + 得到**`out` = [在新记录中设置 sandbox_profile 字段](table.put(in=`out`, at="sandbox_profile", value=`配置行`))**。 2. * **_ = 1** 1. `写回` - **body = > json.stringify value=`out`** - **st = > json.get value=`out` key="status"** + 得到**`body` = [将结构化值编码为 JSON 文本](json.stringify(value=`out`))**。 + 得到**`st` = [读取 status 字段](json.get(value=`out`, key="status"))**。 1. `st` == "ok" - > 自写回.写回 值=`body` 键="ok" + 这里**[调用 写回](自写回.写回(值=`body`, 键="ok"))**。 2. * - > 自写回.写回 值=`body` 键="error" + 这里**[调用 写回](自写回.写回(值=`body`, 键="error"))**。 2. * **_ = 1** -*out* +完成后返回*out*。 ## 工程预检 - + `任务` - + `根目录`="." - + `知识目录`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 根目录 | any | "." | 明确选择的工程或试运行根目录 | +| 知识目录 | any | None | 检索和写回所用的知识目录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | Engineering First Information 门闩。转发 `agent.preflight`。 | + +这里使用`任务`、`根目录`="."、`知识目录`=None。 Engineering First Information 门闩。转发 `agent.preflight`。 -*> agent.preflight task=`任务` root=`根目录` marqdo_dir=`知识目录`* +完成后返回*[调用 preflight](agent.preflight(task=`任务`, root=`根目录`, marqdo_dir=`知识目录`))*。 ## 多步 - + `目标` - + `工作簿目录`=None - + `工作簿`=None - + `最大轮次`=4 - + `确认分解`=False - + `写回`=True - + `骨架`=single - + `复用`=True - + `优化`=False - + `强制`=False - + `软命中`=False - + `近义命中`=True - + `近义阈值`=0.78 - + `晋升`=True - + `知识库目录`=.marqdo/agent-kb - + `改进周期`=3 - + `探索次数`=3 - + `流式`=False - + `打印增量`=False - + `轨迹`=False - + `工程预检`=False - + `工程知识目录`=.marqdo + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 目标 | any | 必填 | 当前人类任务目标 | +| 工作簿目录 | any | None | 本次规划拥有的工作簿目录 | +| 工作簿 | any | None | 工作簿路径或工作簿引用 | +| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 | +| 确认分解 | any | False | 是否要求确认任务分解 | +| 写回 | any | True | 是否向任务文档写回观察结果 | +| 骨架 | any | "single" | 用于生成工作簿的源码模板 | +| 复用 | any | True | 是否先检索已有能力 | +| 优化 | any | False | 是否采用已说明的改进路径 | +| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | +| 软命中 | any | False | 是否考虑有界近似匹配 | +| 近义命中 | any | True | 是否考虑近义能力候选 | +| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | +| 晋升 | any | True | 是否允许将已验证证据晋升 | +| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | +| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | +| 探索次数 | any | 3 | 有界探索尝试次数上限 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | +| 轨迹 | any | False | 是否保留已说明的执行轨迹 | +| 工程预检 | any | False | 是否进行工程能力复用预检 | +| 工程知识目录 | any | ".marqdo" | 工程检索使用的知识目录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 多步工作簿默认写入 OKF `知识库目录/resources/.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。 | + +这里使用`目标`、`工作簿目录`=None、`工作簿`=None、`最大轮次`=4、`确认分解`=False、`写回`=True、`骨架`="single"、`复用`=True、`优化`=False、`强制`=False、`软命中`=False、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`知识库目录`=".marqdo/agent-kb"、`改进周期`=3、`探索次数`=3、`流式`=False、`打印增量`=False、`轨迹`=False、`工程预检`=False、`工程知识目录`=".marqdo"。 多步工作簿默认写入 OKF `知识库目录/resources/.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.plan goal=`目标` workbook_dir=`工作簿目录` workbook=`工作簿` max_rounds=`最大轮次` confirm=`确认分解` writeback=`写回` skeleton=`骨架` reuse=`复用` optimize=`优化` force=`强制` soft_match=`软命中` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` kb_dir=`知识库目录` improve_every=`改进周期` explore_n=`探索次数` stream=`流式` echo=`打印增量` trace=`轨迹` eng_preflight=`工程预检` marqdo_dir=`工程知识目录`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 plan](en.plan(goal=`目标`, workbook_dir=`工作簿目录`, workbook=`工作簿`, max_rounds=`最大轮次`, confirm=`确认分解`, writeback=`写回`, skeleton=`骨架`, reuse=`复用`, optimize=`优化`, force=`强制`, soft_match=`软命中`, near_match=`近义命中`, near_threshold=`近义阈值`, promote=`晋升`, kb_dir=`知识库目录`, improve_every=`改进周期`, explore_n=`探索次数`, stream=`流式`, echo=`打印增量`, trace=`轨迹`, eng_preflight=`工程预检`, marqdo_dir=`工程知识目录`))*。 ## 解析 - + `任务` - + `知识库目录`=.marqdo/agent-kb - + `近义命中`=True - + `近义阈值`=0.78 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | +| 近义命中 | any | True | 是否考虑近义能力候选 | +| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 技能解析(v2):exact → alias → canonical → near。 | + +这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`近义命中`=True、`近义阈值`=0.78。 技能解析(v2):exact → alias → canonical → near。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.resolve task=`任务` kb_dir=`知识库目录` near_match=`近义命中` near_threshold=`近义阈值`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 resolve](en.resolve(task=`任务`, kb_dir=`知识库目录`, near_match=`近义命中`, near_threshold=`近义阈值`))*。 ## 记录情景 - + `任务` - + `状态`=ok - + `结果`=None - + `模式`=explore - + `技能`=none - + `观察`=None - + `工作簿`=None - + `缓存`=None - + `匹配`=None - + `大模型次数`=0 - + `工具次数`=0 - + `错误`=None - + `记忆目录`=.marqdo/agent-memory + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 状态 | any | "ok" | 当前结构化执行状态 | +| 结果 | any | None | 前一步返回的结构化结果 | +| 模式 | any | "explore" | 本函数说明支持的操作模式 | +| 技能 | any | "none" | 准备检查或调用的技能引用 | +| 观察 | any | None | 保留给后续步骤的工具或工作簿观察 | +| 工作簿 | any | None | 工作簿路径或工作簿引用 | +| 缓存 | any | None | 是否使用已说明的结果缓存 | +| 匹配 | any | None | 已解析的能力匹配结果 | +| 大模型次数 | any | 0 | 实际观测到的模型调用次数 | +| 工具次数 | any | 0 | 实际观测到的工具调用次数 | +| 错误 | any | None | 可恢复失败记录 | +| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将一次执行沉淀为 `.mq.md` 情景记忆。 | + +这里使用`任务`、`状态`="ok"、`结果`=None、`模式`="explore"、`技能`="none"、`观察`=None、`工作簿`=None、`缓存`=None、`匹配`=None、`大模型次数`=0、`工具次数`=0、`错误`=None、`记忆目录`=".marqdo/agent-memory"。 将一次执行沉淀为 `.mq.md` 情景记忆。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.record_episode task=`任务` status=`状态` result=`结果` mode=`模式` skill=`技能` observation=`观察` workbook=`工作簿` cache=`缓存` match=`匹配` llm_calls=`大模型次数` tool_calls=`工具次数` error=`错误` memory_dir=`记忆目录`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 record episode](en.record_episode(task=`任务`, status=`状态`, result=`结果`, mode=`模式`, skill=`技能`, observation=`观察`, workbook=`工作簿`, cache=`缓存`, match=`匹配`, llm_calls=`大模型次数`, tool_calls=`工具次数`, error=`错误`, memory_dir=`记忆目录`))*。 ## 尝试学习 - + `任务` - + `知识库目录`=.marqdo/agent-kb - + `记忆目录`=.marqdo/agent-memory - + `改进周期`=3 - + `晋升`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | +| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | +| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | +| 晋升 | any | True | 是否允许将已验证证据晋升 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。 | + +这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`改进周期`=3、`晋升`=True。 情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.maybe_learn task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` improve_every=`改进周期` promote=`晋升`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 maybe learn](en.maybe_learn(task=`任务`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, improve_every=`改进周期`, promote=`晋升`))*。 ## 运行 - + `任务` - + `知识库目录`=.marqdo/agent-kb - + `记忆目录`=.marqdo/agent-memory - + `学习`=True - + `校验`=True - + `写回`=True - + `复用`=True - + `近义命中`=True - + `近义阈值`=0.78 - + `晋升`=True - + `改进周期`=3 - + `探索次数`=3 - + `最大轮次`=4 - + `流式`=False - + `打印增量`=False - + `轨迹`=False - + `强制`=False - + `路由`=auto - + `路由模型`=None - + `沙盒`=False - + `沙盒配置`=default - + `工程预检`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | +| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | +| 学习 | any | True | 是否记录观察或进行学习 | +| 校验 | any | True | 是否运行已说明的校验器 | +| 写回 | any | True | 是否向任务文档写回观察结果 | +| 复用 | any | True | 是否先检索已有能力 | +| 近义命中 | any | True | 是否考虑近义能力候选 | +| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 | +| 晋升 | any | True | 是否允许将已验证证据晋升 | +| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 | +| 探索次数 | any | 3 | 有界探索尝试次数上限 | +| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 | +| 流式 | any | False | 是否使用流式调用 | +| 打印增量 | any | False | 是否输出流式增量文本 | +| 轨迹 | any | False | 是否保留已说明的执行轨迹 | +| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | +| 路由 | any | "auto" | 路由配置或已选路由 | +| 路由模型 | any | None | 用于路由决策的模型资源 | +| 沙盒 | any | False | 是否采用 CoW 试运行路径 | +| 沙盒配置 | any | "default" | CoW 试运行能力配置 | +| 工程预检 | any | True | 是否进行工程能力复用预检 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。 | + +这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`学习`=True、`校验`=True、`写回`=True、`复用`=True、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`改进周期`=3、`探索次数`=3、`最大轮次`=4、`流式`=False、`打印增量`=False、`轨迹`=False、`强制`=False、`路由`="auto"、`路由模型`=None、`沙盒`=False、`沙盒配置`="default"、`工程预检`=True。 v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型` sandbox=`沙盒` sandbox_profile=`沙盒配置` efi=`工程预检`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 run](en.run(task=`任务`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, learn=`学习`, verify=`校验`, writeback=`写回`, reuse=`复用`, near_match=`近义命中`, near_threshold=`近义阈值`, promote=`晋升`, improve_every=`改进周期`, explore_n=`探索次数`, max_rounds=`最大轮次`, stream=`流式`, echo=`打印增量`, trace=`轨迹`, force=`强制`, router=`路由`, router_model=`路由模型`, sandbox=`沙盒`, sandbox_profile=`沙盒配置`, efi=`工程预检`))*。 ## 路由 - + `任务` - + `后端`=auto - + `知识库目录`=.marqdo/agent-kb - + `记忆目录`=.marqdo/agent-memory - + `阈值`=0.78 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 | +| 后端 | any | "auto" | 明确选择的执行或模型后端 | +| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 | +| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | +| 阈值 | any | 0.78 | 当前操作要求满足的策略阈值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。 | + +这里使用`任务`、`后端`="auto"、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`阈值`=0.78。 自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.route task=`任务` backend=`后端` kb_dir=`知识库目录` memory_dir=`记忆目录` threshold=`阈值`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 route](en.route(task=`任务`, backend=`后端`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, threshold=`阈值`))*。 ## 编译策略 - + `记忆目录`=.marqdo/agent-memory - + `最少证据`=3 - + `强制`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 | +| 最少证据 | any | 3 | 允许晋升前所需的证据数量 | +| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。 | + +这里使用`记忆目录`=".marqdo/agent-memory"、`最少证据`=3、`强制`=False。 策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。 -**model = > json.get value=`self` key="model"** -**tools = > json.get value=`self` key="tools"** -**standing = > json.get value=`self` key="standing"** -**en = > agent.agent model=`model` tools=`tools` standing=`standing`** -*> en.compile_policy memory_dir=`记忆目录` min_evidence=`最少证据` force=`强制`* +得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。 +得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。 +得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。 +得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。 +完成后返回*[调用 compile policy](en.compile_policy(memory_dir=`记忆目录`, min_evidence=`最少证据`, force=`强制`))*。 diff --git a/ext/ai/沙盒.mq.md b/ext/ai/沙盒.mq.md index 45f9bac..724d2ea 100644 --- a/ext/ai/沙盒.mq.md +++ b/ext/ai/沙盒.mq.md @@ -7,59 +7,158 @@ import: sandbox: ext/ai/sandbox.mq.md --- -## 打开 - + `根`=None +本文件提供中文试跑门面,对应[试跑实现](sandbox.mq.md)。先读[中文入口](索引.mq.md)了解模型调用与 CoW 试跑的区别。试跑产生的文件变更和诊断供调用者检查,提升变更必须走已有显式流程;试跑返回不等于宿主工作区已经更新。保持失败、取消和提升的结果可区分,避免复制一份隔离实现。 -*> sandbox.open root=`根`* +## 打开 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 根 | any | None | 当前会话或工程明确授权的根目录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。 | + +这里使用`根`=None。 + +按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。 + +完成后返回*[调用 open](sandbox.open(root=`根`))*。 ## 写入 - + `id` - + `路径` - + `文本` -*> sandbox.write id=`id` path=`路径` text=`文本`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | +| 路径 | any | 必填 | 授权根目录内的文件路径 | +| 文本 | any | 必填 | 本操作接收的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 把文本写入试运行会话的覆盖层,提交前不改真实文件。 | + +这里使用`id`、`路径`、`文本`。 + +把文本写入试运行会话的覆盖层,提交前不改真实文件。 + +完成后返回*[调用 write](sandbox.write(id=`id`, path=`路径`, text=`文本`))*。 ## 读取 - + `id` - + `路径` -*> sandbox.read id=`id` path=`路径`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | +| 路径 | any | 必填 | 授权根目录内的文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。 | + +这里使用`id`、`路径`。 + +透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。 + +完成后返回*[调用 read](sandbox.read(id=`id`, path=`路径`))*。 ## 删除 - + `id` - + `路径` -*> sandbox.remove id=`id` path=`路径`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | +| 路径 | any | 必填 | 授权根目录内的文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 在试运行覆盖层标记删除,不直接删除宿主文件。 | + +这里使用`id`、`路径`。 + +在试运行覆盖层标记删除,不直接删除宿主文件。 + +完成后返回*[调用 remove](sandbox.remove(id=`id`, path=`路径`))*。 ## 差异 - + `id` -*> sandbox.diff id=`id`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 读取会话中的真实变更清单,供决定提交或丢弃。 | + +这里使用`id`。 + +读取会话中的真实变更清单,供决定提交或丢弃。 + +完成后返回*[调用 diff](sandbox.diff(id=`id`))*。 ## 提交 - + `id` -*> sandbox.commit id=`id`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。 | + +这里使用`id`。 + +把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。 + +完成后返回*[调用 commit](sandbox.commit(id=`id`))*。 ## 丢弃 - + `id` -*> sandbox.discard id=`id`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 丢弃会话覆盖层中的变更,保留原始宿主文件。 | + +这里使用`id`。 + +丢弃会话覆盖层中的变更,保留原始宿主文件。 + +完成后返回*[调用 discard](sandbox.discard(id=`id`))*。 ## 运行 - + `id` - + `源码`=None - + `路径`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | +| 源码 | any | None | 本次检查或试跑的源码文本 | +| 路径 | any | None | 授权根目录内的文件路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 run,保留同源能力的返回值和失败语义。 | + +这里使用`id`、`源码`=None、`路径`=None。 1. `源码` - *> sandbox.run id=`id` source=`源码`* + 完成后返回*[调用 run](sandbox.run(id=`id`, source=`源码`))*。 2. `路径` - *> sandbox.run id=`id` path=`路径`* + 完成后返回*[调用 run](sandbox.run(id=`id`, path=`路径`))*。 3. * - > print text=沙盒.运行: 需要 源码= 或 路径= - > sys.exit code=1 + 这里**[输出本步已准备的消息](print(text="沙盒.运行: 需要", 源码="或", 路径=""))**。 + 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 ## 检查 - + `id` -*> sandbox.inspect id=`id`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 检查当前试运行会话及能力配置,不把检查等同于提交成功。 | + +这里使用`id`。 + +检查当前试运行会话及能力配置,不把检查等同于提交成功。 + +完成后返回*[调用 inspect](sandbox.inspect(id=`id`))*。 diff --git a/ext/ai/索引.mq.md b/ext/ai/索引.mq.md new file mode 100644 index 0000000..19506a5 --- /dev/null +++ b/ext/ai/索引.mq.md @@ -0,0 +1,60 @@ +--- +markup: occlusion +title: AI 工程入口:模型、智能体与试运行 +import: + 大模型: ext/ai/大模型.mq.md +--- + +从本入口选择任务:[大模型](大模型.mq.md)负责提示、配置、请求和流收集; +[智能体](智能体.mq.md)提供中文使用面,[同源编排实现](agent.mq.md)负责上下文、 +白名单工具、路由、工作簿和继续执行;[沙盒](沙盒.mq.md)管理试运行覆盖层及晋升。 +[提供方适配入口](llm/index.mq.md)解释 HTTP 适配,[路由策略](policies/step-route.mq.md) +保留可读表数据。[英文入口](index.mq.md)给出相同职责划分。 + +可以先运行完全离线的流收集,不需要凭据、模型服务或原生插件: + +```sh +marqdo call ext/ai/索引.mq.md 离线示例 --json +``` + +真实请求前明确模型基址和可信凭据,智能体还需要已构建的 agent 插件与工具白名单。 +生成的调用文本不是执行授权,文件写入、网络和进程仍受宿主限制。工具失败、取消、 +超预算或恢复时应保留观察与效果状态,不因继续工作簿而重复不可逆操作。 + +新增提供方去适配目录,公共模型行为去大模型模块,规划和上下文去智能体模块, +隔离修改去沙盒模块;保持中英文默认值与行为一致。先用本地可控替身验证成功与失败, +再在明确运行配置下测试真实服务。不能用固定完成标记冒充已经调用模型或验证了工具。 + +## 收集事件 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 事件 | list | 必填 | 按顺序排列的语义流或公开收集器支持的提供方事件 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | text | 由公共收集器组装的最终回答文本 | + +输入`事件`是已经观测的数据,不会触发新请求或执行其中的工具文本。 +本工具复用公开大模型库的 delta/text 与 done.result 收集约定, +直接返回*[把已有事件组装成最终文本](大模型.收集(事件=`事件`))*, +使离线处理与真实传输复用同一份组装规则。 + +## 离线示例 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | text | Hello world,由下面的实际事件组装得到 | + +下面是一条确定的增量事件和一条完成事件。表格把输入内容完整列出, +读者可以比较局部文本与完成结果,不需要相信一个自报通过的标志。 +此流程只验证流收集,不暗示模型服务或网络已经可用。 + +`事件` = + +| @ | type | text | result | +|---|---|---|---| +| 1 | delta | "Hello " | None | +| 2 | done | None | "Hello world" | + +最后返回*[根据列出的事件得到最终文本](收集事件(事件=`事件`))*,供下一步展示或保存。 diff --git a/ext/data/cache.mq.md b/ext/data/cache.mq.md index 66b8ab1..4c245b0 100644 --- a/ext/data/cache.mq.md +++ b/ext/data/cache.mq.md @@ -8,55 +8,124 @@ import: table: lib/table.mq.md --- +Cache values belong to the selected backend and process lifetime. Use memory: only for process-local demonstration; choose and configure persistent backends explicitly. [The data entry](index.mq.md) demonstrates set, get and deletion through one receiver. Retain native ok/error fields and expiry behavior when extending this leaf; a cache miss is not evidence that a remote write succeeded. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/data: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # cache - + `url`="memory:" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | "memory:" | Resource connection URL; scheme selects the documented backend | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis. | + +Use `url`="memory:" as the inputs for this operation. Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis. -> _load -*> web_cache_new url=`url`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Key–value cache. Use memory: for in-process (tests / single process) or redis://host:6379/0 for Redis.](web_cache_new(url=`url`))*. ## get - + `key` -**url = [url](access(self, "url"))** -*> web_cache_get url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read the cached value associated with a key; a miss is reported by the cache result. | + +Use `key` as the inputs for this operation. + +Read the cached value associated with a key; a miss is reported by the cache result. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Read the cached value associated with a key; a miss is reported by the cache result.](web_cache_get(url=`url`, key=`key`))*. ## set - + `key` - + `value` - + `ttl`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | +| value | any | required | Value supplied to this operation; immutable transformations return a new value | +| ttl | any | None | Expiry duration in seconds; None uses the backend default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Optional `ttl` is seconds until expiry. | + +Use `key`, `value`, `ttl`=None as the inputs for this operation. Optional `ttl` is seconds until expiry. -**url = [url](access(self, "url"))** -*> web_cache_set url=`url` key=`key` value=`value` ttl=`ttl`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Optional ttl is seconds until expiry.](web_cache_set(url=`url`, key=`key`, value=`value`, ttl=`ttl`))*. ## del - + `key` -**url = [url](access(self, "url"))** -*> web_cache_del url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delete a cached key without changing other entries. | + +Use `key` as the inputs for this operation. + +Delete a cached key without changing other entries. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Delete a cached key without changing other entries.](web_cache_del(url=`url`, key=`key`))*. ## exists - + `key` -**url = [url](access(self, "url"))** -*> web_cache_exists url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Test whether the cache currently holds the selected key. | + +Use `key` as the inputs for this operation. + +Test whether the cache currently holds the selected key. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Test whether the cache currently holds the selected key.](web_cache_exists(url=`url`, key=`key`))*. ## ttl - + `key` -**url = [url](access(self, "url"))** -*> web_cache_ttl url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read the remaining lifetime of a cached key using the backend TTL convention. | + +Use `key` as the inputs for this operation. + +Read the remaining lifetime of a cached key using the backend TTL convention. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Read the remaining lifetime of a cached key using the backend TTL convention.](web_cache_ttl(url=`url`, key=`key`))*. diff --git a/ext/data/db.mq.md b/ext/data/db.mq.md index 5ea4192..80e3583 100644 --- a/ext/data/db.mq.md +++ b/ext/data/db.mq.md @@ -8,246 +8,491 @@ import: table: lib/table.mq.md --- +Database receivers own a connection URL. Begin a transaction with the database receiver, use its returned identifier for transaction operations, then commit or roll back explicitly. Read [the data workflow](index.mq.md) for a real isolated SQLite example and temporary-directory ownership. Native URLs resolve differently from filesystem helpers: validate an absolute SQLite path inside the granted root before passing it to the plugin. New query behavior belongs in the native web database implementation; schema and filters remain readable tables here. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/data: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # db - + `url`="sqlite:site.db" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | "sqlite:site.db" | Resource connection URL; scheme selects the documented backend | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods). | + +Use `url`="sqlite:site.db" as the inputs for this operation. Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods). -> _load -*> web_db_new url=`url`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Open a database handle. URL schemes: sqlite:path (default), postgres://… / postgresql://… (same CRUD methods).](web_db_new(url=`url`))*. ## init - + `name` - + `fields` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| fields | any | required | Readable field definitions with the columns described by this resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present. | + +Use `name`, `fields` as the inputs for this operation. Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present. -**url = [url](access(self, "url"))** -*> web_db_init url=`url` name=`name` fields=`fields`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Create a table from a schema table](web_db_init(url=`url`, name=`name`, fields=`fields`))*. ## insert - + `table` - + `rows` - + `txn`=None -**url = [url](access(self, "url"))** -*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| rows | any | required | Input row records to insert or process | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Insert the supplied row records, optionally within the selected open transaction. | + +Use `table`, `rows`, `txn`=None as the inputs for this operation. + +Insert the supplied row records, optionally within the selected open transaction. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Insert the supplied row records, optionally within the selected open transaction.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*. ## select - + `table` - + `where`=None - + `limit`=200 - + `order`=None - + `txn`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | +| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | +| order | any | None | Field order specification, with a leading minus for descending database order | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`. | + +Use `table`, `where`=None, `limit`=200, `order`=None, `txn`=None as the inputs for this operation. Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`. -**url = [url](access(self, "url"))** -**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`** -*[rows](access(r, "rows"))* +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`r` = [Simple filters: one-row map of column→value (AND =), or rows |字段|操作|值| (= != > >= < <= like in between is null; add |或| = 是 to join a row with OR)](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**. +Return *[rows](access(r, "rows"))*. ## paginate - + `table` - + `where`=None - + `limit`=200 - + `order`=None - + `跳过`=0 - + `txn`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | +| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | +| order | any | None | Field order specification, with a leading minus for descending database order | +| 跳过 | any | 0 | Number of matching rows skipped before the database page | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10). | + +Use `table`, `where`=None, `limit`=200, `order`=None, `跳过`=0, `txn`=None as the inputs for this operation. Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10). -**url = [url](access(self, "url"))** -*> web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=`跳过` txn=`txn`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Like select but returns { rows, total } — the total counts rows matching where regardless of limit/跳过, so you can render 上一页 / 下一页](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=`跳过`, txn=`txn`))*. ## get - + `table` - + `id` - + `txn`=None -**url = [url](access(self, "url"))** -*> web_db_get url=`url` table=`table` id=`id` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read a single row by its identifier from the selected database table. | + +Use `table`, `id`, `txn`=None as the inputs for this operation. + +Read a single row by its identifier from the selected database table. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Read a single row by its identifier from the selected database table.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*. ## update - + `table` - + `id` - + `row` - + `txn`=None -**url = [url](access(self, "url"))** -*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| row | any | required | Field/value record to apply to the selected row | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Update the supplied fields of the selected row; use update_if when a revision comparison is required. | + +Use `table`, `id`, `row`, `txn`=None as the inputs for this operation. + +Update the supplied fields of the selected row; use update_if when a revision comparison is required. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Update the supplied fields of the selected row; use update_if when a revision comparison is required.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*. ## update_if - + `table` - + `id` - + `row` - + `expect_col` - + `expect_val` - + `txn`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| row | any | required | Field/value record to apply to the selected row | +| expect_col | any | required | Column checked atomically in the conditional database update | +| expect_val | any | required | Expected current value of the comparison column | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`. | + +Use `table`, `id`, `row`, `expect_col`, `expect_val`, `txn`=None as the inputs for this operation. Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`. -**url = [url](access(self, "url"))** -*> web_db_update_if url=`url` table=`table` id=`id` row=`row` expect_col=`expect_col` expect_val=`expect_val` txn=`txn`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Conditional update (CAS) for task/revision control: UPDATE … WHERE id=? AND expect_col=expect_val](web_db_update_if(url=`url`, table=`table`, id=`id`, row=`row`, expect_col=`expect_col`, expect_val=`expect_val`, txn=`txn`))*. ## delete - + `table` - + `id` - + `txn`=None -**url = [url](access(self, "url"))** -*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delete the selected row, optionally inside the caller-owned transaction. | + +Use `table`, `id`, `txn`=None as the inputs for this operation. + +Delete the selected row, optionally inside the caller-owned transaction. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Delete the selected row, optionally inside the caller-owned transaction.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*. ## exec - + `sql` - + `args`=None - + `txn`=None -**url = [url](access(self, "url"))** -*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | +| args | any | None | Arguments passed to the selected command or operation | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Execute SQL with bound arguments and return the native execution outcome. | + +Use `sql`, `args`=None, `txn`=None as the inputs for this operation. + +Execute SQL with bound arguments and return the native execution outcome. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Execute SQL with bound arguments and return the native execution outcome.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. ## query - + `sql` - + `args`=None - + `txn`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | +| args | any | None | Arguments passed to the selected command or operation | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`. | + +Use `sql`, `args`=None, `txn`=None as the inputs for this operation. Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`. -**url = [url](access(self, "url"))** -*> web_db_query url=`url` sql=`sql` args=`args` txn=`txn`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Run bare SQL and return the result set — count / join / group / subqueries. Returns { rows, count }.](web_db_query(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. ## count - + `table` - + `where`=None - + `txn`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | +| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Count rows matching a `where` filter (same syntax as `select`). Returns a number. | + +Use `table`, `where`=None, `txn`=None as the inputs for this operation. Count rows matching a `where` filter (same syntax as `select`). Returns a number. -**url = [url](access(self, "url"))** -**r = > web_db_count url=`url` table=`table` where=`where` txn=`txn`** -*[count](access(r, "count"))* +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`r` = [Count rows matching a where filter (same syntax as select). Returns a number.](web_db_count(url=`url`, table=`table`, where=`where`, txn=`txn`))**. +Return *[count](access(r, "count"))*. ## migrate - + `steps` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| steps | any | required | Ordered migration or operation records in the documented table shape | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. | + +Use `steps` as the inputs for this operation. Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. -**url = [url](access(self, "url"))** -*> web_db_migrate url=`url` steps=`steps`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Apply versioned SQL migrations](web_db_migrate(url=`url`, steps=`steps`))*. ## fts - + `table` - + `columns` - + `name`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| columns | any | required | Column-name list or column definitions required by this operation | +| name | any | None | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. | + +Use `table`, `columns`, `name`=None as the inputs for this operation. Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. -**url = [url](access(self, "url"))** -*> web_db_fts_create url=`url` table=`table` columns=`columns` name=`name`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Create an FTS5 index on table for the listed content columns (CSV string or list)](web_db_fts_create(url=`url`, table=`table`, columns=`columns`, name=`name`))*. ## search - + `table` - + `q` - + `limit`=20 - + `name`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| q | any | required | Full-text search query | +| limit | any | 20 | Maximum returned entries or candidates; this is not a success threshold | +| name | any | None | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. | + +Use `table`, `q`, `limit`=20, `name`=None as the inputs for this operation. Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. -**url = [url](access(self, "url"))** -*> web_db_search url=`url` table=`table` q=`q` limit=`limit` name=`name`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Full-text search (MATCH) against the FTS5 index from fts. Returns { rows, count } with a rank column (bm25). SQLite only.](web_db_search(url=`url`, table=`table`, q=`q`, limit=`limit`, name=`name`))*. ## 事务 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic. | + Begin a transaction: borrows the pooled connection exclusively and returns a `txn` handle. Write inside it, then `提交` (commit) or `回滚` (roll back). Every statement runs on the same connection, so a batch is atomic. -**url = [url](access(self, "url"))** -*> web_db_begin url=`url`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic.](web_db_begin(url=`url`))*. # txn - + `txn` - + `url` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| txn | any | required | Open transaction returned by the same database resource; None runs outside a transaction | +| url | any | required | Resource connection URL; scheme selects the documented backend | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | A transaction handle from `db.事务`. All CRUD here runs on the transaction's connection; finish with `提交` or `回滚`. The transaction identifier and connection URL remain explicit fields for every method. | + +Use `txn`, `url` as the inputs for this operation. A transaction handle from `db.事务`. All CRUD here runs on the transaction's connection; finish with `提交` or `回滚`. -*self* +The transaction identifier and connection URL remain explicit fields for every method. + +`handle` = + +| txn | url | +|---|---| +| `txn` | `url` | + +Return *handle*. ## insert - + `table` - + `rows` -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| rows | any | required | Input row records to insert or process | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior. | + +Use `table`, `rows` as the inputs for this operation. + +Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*. ## select - + `table` - + `where`=None - + `limit`=200 - + `order`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter | +| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold | +| order | any | None | Field order specification, with a leading minus for descending database order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Same filters as `db.select`; runs inside the transaction. | + +Use `table`, `where`=None, `limit`=200, `order`=None as the inputs for this operation. Same filters as `db.select`; runs inside the transaction. -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`** -*[rows](access(r, "rows"))* +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +We retain **`r` = [Same filters as db.select; runs inside the transaction.](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**. +Return *[rows](access(r, "rows"))*. ## get - + `table` - + `id` -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -*> web_db_get url=`url` table=`table` id=`id` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior. | + +Use `table`, `id` as the inputs for this operation. + +Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*. ## update - + `table` - + `id` - + `row` -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | +| row | any | required | Field/value record to apply to the selected row | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior. | + +Use `table`, `id`, `row` as the inputs for this operation. + +Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*. ## delete - + `table` - + `id` -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | +| id | any | required | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior. | + +Use `table`, `id` as the inputs for this operation. + +Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*. ## exec - + `sql` - + `args`=None -**url = [url](access(self, "url"))** -**txn = [txn](access(self, "txn"))** -*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL | +| args | any | None | Arguments passed to the selected command or operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior. | + +Use `sql`, `args`=None as the inputs for this operation. + +Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*. ## 提交 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Commit the transaction and return its connection to the pool. | + Commit the transaction and return its connection to the pool. -**txn = [txn](access(self, "txn"))** -*> web_db_commit txn=`txn`* +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Commit the transaction and return its connection to the pool.](web_db_commit(txn=`txn`))*. ## 回滚 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Roll the transaction back (undo every write) and return its connection. | + Roll the transaction back (undo every write) and return its connection. -**txn = [txn](access(self, "txn"))** -*> web_db_rollback txn=`txn`* - +We retain **`txn` = [Read txn field](access(`self`, "txn"))**. +Return *[Roll the transaction back (undo every write) and return its connection.](web_db_rollback(txn=`txn`))*. diff --git a/ext/data/form.mq.md b/ext/data/form.mq.md index b62b513..a567917 100644 --- a/ext/data/form.mq.md +++ b/ext/data/form.mq.md @@ -8,62 +8,142 @@ import: table: lib/table.mq.md --- +This leaf projects form schema and submission operations through the native web runtime. Read [the data entry](index.mq.md) before connecting a form to persistent storage. Schema validation and route authorization are different responsibilities: an accepted field value does not authenticate its submitter. Keep schema rows, validation failures and persistence results visible when changing this resource. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/data: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # form - + `table`=None - + `action`=insert - + `id`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | None | Database table name or form submission table | +| action | any | "insert" | Form submission action such as insert or update | +| id | any | None | Identifier produced or selected by the corresponding resource operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Field table + rules table; submit writes through `# db`. | + +Use `table`=None, `action`="insert", `id`=None as the inputs for this operation. Field table + rules table; submit writes through `# db`. -> _load -*> web_form_new table=`table` action=`action` id=`id`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Field table + rules table; submit writes through # db.](web_form_new(table=`table`, action=`action`, id=`id`))*. ## fields - + `fields` -*> web_form_fields form=`self` fields=`fields`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| fields | any | required | Readable field definitions with the columns described by this resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Attach the readable field definitions to this form and return the updated resource. | + +Use `fields` as the inputs for this operation. + +Attach the readable field definitions to this form and return the updated resource. + +Return *[Attach the readable field definitions to this form and return the updated resource.](web_form_fields(form=`self`, fields=`fields`))*. ## rules - + `rules` -*> web_form_rules form=`self` rules=`rules`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rules | any | required | Readable validation-rule records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Attach validation rules to this form without submitting user data. | + +Use `rules` as the inputs for this operation. + +Attach validation rules to this form without submitting user data. + +Return *[Attach validation rules to this form without submitting user data.](web_form_rules(form=`self`, rules=`rules`))*. ## labels - + `submit`="Submit" - + `cancel`="cancel" - + `cancel_href`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| submit | any | "Submit" | Displayed submit-button label | +| cancel | any | "cancel" | Displayed cancel-button label | +| cancel_href | any | "" | Navigation target of the cancel action | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Localized submit / cancel copy for rendered forms. | + +Use `submit`="Submit", `cancel`="cancel", `cancel_href`="" as the inputs for this operation. Localized submit / cancel copy for rendered forms. -*> web_form_labels form=`self` submit=`submit` cancel=`cancel` cancel_href=`cancel_href`* +Return *[Localized submit / cancel copy for rendered forms.](web_form_labels(form=`self`, submit=`submit`, cancel=`cancel`, cancel_href=`cancel_href`))*. ## validate - + `rules`=None - + `data` -*> web_form_validate form=`self` rules=`rules` data=`data`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rules | any | None | Readable validation-rule records | +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Validate supplied field values and return the native validation result; this does not submit to the database. | + +Use `rules`=None, `data` as the inputs for this operation. + +Validate supplied field values and return the native validation result; this does not submit to the database. + +Return *[Validate supplied field values and return the native validation result; this does not submit to the database.](web_form_validate(form=`self`, rules=`rules`, data=`data`))*. ## render - + `id`=form - + `data`=None - + `errors`=None -*> web_form_render form=`self` id=`id` data=`data` errors=`errors`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | "form" | Identifier produced or selected by the corresponding resource operation | +| data | any | None | Structured input supplied to this adapter or resource | +| errors | any | None | Field/error record returned by validation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Render this form using its data and field errors; rendering is separate from database submission. | + +Use `id`="form", `data`=None, `errors`=None as the inputs for this operation. + +Render this form using its data and field errors; rendering is separate from database submission. + +Return *[Render this form using its data and field errors; rendering is separate from database submission.](web_form_render(form=`self`, id=`id`, data=`data`, errors=`errors`))*. ## submit - + `data` - + `db` -**url = [url](access(db, "url"))** -*> web_form_submit form=`self` data=`data` url=`url`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | +| db | any | required | Database resource created by the public database constructor | +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Submit validated form data through the selected database resource and configured action. | + +Use `data`, `db` as the inputs for this operation. + +Submit validated form data through the selected database resource and configured action. + +We retain **`url` = [Read url field](access(`db`, "url"))**. +Return *[Submit validated form data through the selected database resource and configured action.](web_form_submit(form=`self`, data=`data`, url=`url`))*. diff --git a/ext/data/index.mq.md b/ext/data/index.mq.md new file mode 100644 index 0000000..acfd3e0 --- /dev/null +++ b/ext/data/index.mq.md @@ -0,0 +1,121 @@ +--- +markup: occlusion +title: Data resources — database, cache, storage and forms +import: + cache_api: ext/data/cache.mq.md + db_api: ext/data/db.mq.md + fs: lib/fs.mq.md + path: lib/path.mq.md +--- + +Start here when a program needs persistent records, short-lived values, object storage or forms. +The public resource files remain the implementation: [database](db.mq.md) owns schemas and +transactions, [cache](cache.mq.md) owns expiry, [storage](storage.mq.md) owns blobs and upload +validation, and [forms](form.mq.md) separates validation, rendering and submission. + +These modules use the native web plugin. In this source checkout build it with +scripts/build-web-plugin.sh; installed packages follow the web package installation route. +Commands below run at the repository root. The cache example uses memory only. The transaction example creates a SQLite file +in an owned temporary directory. Prepare an existing disposable directory and export MQ_WORK to its +absolute path; the transaction report returns work_dir for cleanup after this process exits. +Neither example needs a cloud account, credentials or an external service. + +```sh +marqdo call ext/data/index.mq.md memory_cache 'key="manual"' 'value="ready"' --effects plugin --json +marqdo call ext/data/index.mq.md transaction_roundtrip "root=\"$MQ_WORK\"" --effects plugin,fs.write --fs-root "$MQ_WORK" --json +``` + +A resource constructor creates an object; its methods need that actual receiver. Use the free +workflow tools below for a single CLI call, or import the resource file and keep the object in +your program. Do not pass an instance method to call without its receiver or reconstruct a +transaction from guessed fields. Native resource URLs select their own backend: the marqdo +filesystem root does not rewrite a SQLite, S3 or Redis URL. Grant plugin access deliberately. + +For development, keep backend operations in the native web resource implementation and expose +small, documented compositions here. Specify row/filter shapes, transaction ownership, conflicts, +expiry units and cleanup. Add an operation to its responsible leaf file and exercise it through +this facade or a real author program. Run the source-handbook regression and database/cache gold +cases on both backends. A successful transport record is not proof that a business update matched. + +## memory_cache + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | "manual" | Key owned by this short-lived demonstration | +| value | any | "ready" | Value written and then read back from the in-process cache | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Actual cache get result; value contains the stored value | + +Use `key`="manual" and `value`="ready" unless the caller supplies different data. This +workflow uses memory: storage, so values belong to the current native plugin process. +It removes its key after reading; do not use a production key for an illustrative roundtrip. + +First **cache = [Create a process-local cache](cache_api.cache(url="memory:"))**. +We then **[Store the supplied value with a sixty-second expiry](> `cache`.set key=`key` value=`value` ttl=60 )** +and retain **stored = [Read the same cache entry](> `cache`.get key=`key` )**. +Once the value has been captured, **[Remove the demonstration key](> `cache`.del key=`key` )** +so another operation does not inherit it. Return *stored* as observed, including its backend fields. + +## transaction_roundtrip + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | required | Absolute disposable root, matching --fs-root; native resource URLs need an absolute path | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | The committed row list and native commit/rollback outcomes; the second insert is rolled back | + +Use the absolute `root` supplied for --fs-root. This isolated-file example shows the whole ownership sequence: create a schema, begin a transaction, +write through its receiver, finish it, and read outside it. A second transaction is explicitly +rolled back. The standalone txn constructor wraps the actual native identifier and connection URL; +it does not begin another transaction or invent an identifier. + +First **directory = [Create an owned temporary directory under the granted root](fs.temp_dir(prefix="data-manual"))**. +The filesystem helper returns a root-relative name. We retain **work_dir = [Resolve that owned name against the explicit root](path.join(a=`root`, b=`directory`))** +and **[Check that this absolute directory is inside the granted filesystem root](fs.stat(path=`work_dir`))** +before giving any path to the native database. We select **database_path = [Choose the SQLite file inside that directory](path.join(a=`work_dir`, b="manual.db"))** +and select **database_url = "sqlite:" + database_path** before creating +the receiver **store = [Open only that explicitly selected SQLite resource](db_api.db(url=`database_url`))**. +The table schema is ordinary readable data; both columns and their nullability remain visible. + +`fields` = + +| 字段 | 类型 | 可空 | +|---|---|---| +| title | text | False | +| body | text | True | + +We **[Create the isolated demonstration table](> `store`.init name="manual_notes" fields=`fields` )** +before borrowing the transaction connection. Next **native = [Begin the first transaction](> `store`.事务 )**. +To retain the exact identifier, **identifier = [Read the returned transaction identifier](access(native, "txn"))** +and **connection = [Read its connection URL](access(native, "url"))**. +Now **transaction = [Wrap those actual fields as a transaction receiver](db_api.txn(txn=`identifier`, url=`connection`))**. + +`row` = + +| title | body | +|---|---| +| committed | kept | + +We **[Insert the first row inside its transaction](> `transaction`.insert table="manual_notes" rows=`row` )** +and keep **committed = [Commit that transaction](> `transaction`.提交 )**. +The second **cancelled = [Begin an independent transaction](> `store`.事务 )** is a native +transaction receiver, which can be used directly because its type and resource fields are retained. +We **[Insert a row that will be discarded](> `cancelled`.insert table="manual_notes" rows=`row` )** +then capture **rolled_back = [Roll back the second transaction](> `cancelled`.回滚 )**. +Finally **rows = [Read the committed state outside a transaction](> `store`.select table="manual_notes" order="id" )**. + +`report` = + +| rows | committed | rolled_back | work_dir | +|---|---|---|---| +| `rows` | `committed` | `rolled_back` | `work_dir` | + +This example ends with one committed row. Real programs must also arrange rollback when a later +operation fails. This plugin pools open connections, so remove the owned work_dir only after this +CLI process exits and the connection is closed, including on failure. Do not assume sqlite::memory: +is in-memory through this ABI: relative resource paths are resolved against the module directory. +Return *report* with the real row data, completion records and cleanup location. diff --git a/ext/data/storage.mq.md b/ext/data/storage.mq.md index c6cb610..5c86262 100644 --- a/ext/data/storage.mq.md +++ b/ext/data/storage.mq.md @@ -8,81 +8,168 @@ import: table: lib/table.mq.md --- +Use this resource for explicitly configured storage URLs; use lib/fs.mq.md for ordinary rooted filesystem operations. [The data entry](index.mq.md) explains resource ownership and the native web dependency. File bodies and byte encodings follow the native storage contract, so callers must inspect the returned operation result before publishing a resource URL. Add backend support in the existing plugin rather than encoding transport logic in callers. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/data: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # storage - + `url`="file:data/blobs" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | "file:data/blobs" | Resource connection URL; scheme selects the documented backend | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3. | + +Use `url`="file:data/blobs" as the inputs for this operation. Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3. -> _load -*> web_storage_new url=`url`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Object storage. file:dir stores blobs on disk (offline / gold). s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=… talks to MinIO / S3.](web_storage_new(url=`url`))*. ## put - + `key` - + `body`=None - + `path`=None - + `content_type`="application/octet-stream" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | +| body | any | None | Object or request content, as described by the operation | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Provide either `body` (text) or `path` (local file to upload). | + +Use `key`, `body`=None, `path`=None, `content_type`="application/octet-stream" as the inputs for this operation. Provide either `body` (text) or `path` (local file to upload). -**url = [url](access(self, "url"))** -*> web_storage_put url=`url` key=`key` body=`body` path=`path` content_type=`content_type`* +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Provide either body (text) or path (local file to upload).](web_storage_put(url=`url`, key=`key`, body=`body`, path=`path`, content_type=`content_type`))*. ## get - + `key` -**url = [url](access(self, "url"))** -*> web_storage_get url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read the object selected by its storage key and retain the backend result shape. | + +Use `key` as the inputs for this operation. + +Read the object selected by its storage key and retain the backend result shape. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Read the object selected by its storage key and retain the backend result shape.](web_storage_get(url=`url`, key=`key`))*. ## delete - + `key` -**url = [url](access(self, "url"))** -*> web_storage_delete url=`url` key=`key`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | any | required | Entry or field key within the selected resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Delete the selected object from this storage resource. | + +Use `key` as the inputs for this operation. + +Delete the selected object from this storage resource. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[Delete the selected object from this storage resource.](web_storage_delete(url=`url`, key=`key`))*. ## list - + `prefix`="" -**url = [url](access(self, "url"))** -*> web_storage_list url=`url` prefix=`prefix`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prefix | any | "" | Object-key or generated-name prefix | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List object entries under the supplied key prefix. | + +Use `prefix`="" as the inputs for this operation. + +List object entries under the supplied key prefix. + +We retain **`url` = [Read url field](access(`self`, "url"))**. +Return *[List object entries under the supplied key prefix.](web_storage_list(url=`url`, prefix=`prefix`))*. # media - + `storage`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| storage | any | None | Storage resource created by the public storage constructor | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`). | + +Use `storage`=None as the inputs for this operation. Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`). -> _load -*> web_media_new storage=`storage`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Offline helpers for upload validation and saving into # storage (also used by HTTP app.upload).](web_media_new(storage=`storage`))*. ## validate - + `filename` - + `content_type`="application/octet-stream" - + `size` - + `max_bytes`=5242880 - + `types`=None -*> web_upload_validate filename=`filename` content_type=`content_type` size=`size` max_bytes=`max_bytes` types=`types`* +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| filename | any | required | Original or suggested filename | +| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | +| size | any | required | Byte size checked by upload validation | +| max_bytes | any | 5242880 | Maximum accepted byte count; exceeding the limit must fail explicitly | +| types | any | None | Allowed MIME types for upload validation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Validate an upload filename, MIME type and byte size against explicit limits before storing anything. | + +Use `filename`, `content_type`="application/octet-stream", `size`, `max_bytes`=5242880, `types`=None as the inputs for this operation. + +Validate an upload filename, MIME type and byte size against explicit limits before storing anything. + +Return *[Validate an upload filename, MIME type and byte size against explicit limits before storing anything.](web_upload_validate(filename=`filename`, content_type=`content_type`, size=`size`, max_bytes=`max_bytes`, types=`types`))*. ## save - + `path` - + `key`=None - + `content_type`="application/octet-stream" - + `prefix`=uploads/ - + `storage`=None -**st = storage** +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects | +| key | any | None | Entry or field key within the selected resource | +| content_type | any | "application/octet-stream" | MIME type associated with the supplied content | +| prefix | any | "uploads/" | Object-key or generated-name prefix | +| storage | any | None | Storage resource created by the public storage constructor | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Save the selected local upload through the configured storage resource and return its storage result. | + +Use `path`, `key`=None, `content_type`="application/octet-stream", `prefix`="uploads/", `storage`=None as the inputs for this operation. + +We retain **st = storage**. 1. `st` == None - **st = [storage](access(self, "storage"))** + We retain **`st` = [Read storage field](access(`self`, "storage"))**. 2. * -*> web_upload_save storage=`st` path=`path` key=`key` content_type=`content_type` prefix=`prefix`* - +Return *[Save the selected local upload through the configured storage resource and return its storage result.](web_upload_save(storage=`st`, path=`path`, key=`key`, content_type=`content_type`, prefix=`prefix`))*. diff --git a/ext/linalg/index.mq.md b/ext/linalg/index.mq.md new file mode 100644 index 0000000..d479440 --- /dev/null +++ b/ext/linalg/index.mq.md @@ -0,0 +1,54 @@ +--- +markup: occlusion +title: Linear algebra — readable matrix workflows +import: + algebra: ext/linalg/linalg.mq.md +--- + +Start here for a complete matrix workflow, then read [the English API](linalg.mq.md) or +[the Chinese API](线性代数.mq.md). Both expose matrix construction, symbolic expressions, +dense evaluation, solving and reusable factorization. Author matrix methods require an actual +receiver; the free functions accept the expression or matrix explicitly. + +Build the native dependency with cargo build -p marqdo_plugin_linalg. This offline workflow +needs plugin permission and no files, network, live services or guessed handles: + +```sh +marqdo call ext/linalg/index.mq.md solve_example --effects plugin --json +``` + +The source matrix and right-hand side below are visible as native matrix formulas. A factorization is a native +structured result, not a string that should be parsed by callers. Reuse a factor only with +compatible dimensions. Rendering is separate: show/draw can write SVG when a path is supplied, +so production examples must state output ownership and cleanup. + +Develop matrix semantics in the native linalg implementation and keep public wrappers readable. +Add a new free operation and its EN/ZH counterpart, then update object conveniences only where +useful. Verify dimensions, singular systems and the numeric tolerance appropriate to the method; +a successful call alone does not prove that a numerical result is accurate. + +## solve_example + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native solve result with x.data equal to [[2], [1]] for the displayed system | + +This example solves two x plus y equals five, and x plus three y equals five. The matrix is +factored once as LU and then reused with the right-hand side. It demonstrates the real data +path without introducing a second formula parser or embedding an external language program. + +`coefficients` = +$$ +\begin{bmatrix}2&1\\1&3\end{bmatrix} +$$ + +`right_hand_side` = +$$ +\begin{pmatrix}5\\5\end{pmatrix} +$$ + +We create **matrix = [Construct the coefficient matrix](algebra.from_formula(formula=`coefficients`))** +and **right = [Construct the right-hand-side column](algebra.from_formula(formula=`right_hand_side`))**. +Next **factor = [Factor the coefficient matrix once](algebra.factorize(matrix=`matrix`, kind="lu"))** +retains the native factor for this system. We return *[Solve using the prepared factor](algebra.solve(b=`right`, factor=`factor`))*. +The expected entries are two and one; use the solve result fields rather than interpreting a display string. diff --git a/ext/linalg/linalg.mq.md b/ext/linalg/linalg.mq.md index b0aeeef..1b96ef8 100644 --- a/ext/linalg/linalg.mq.md +++ b/ext/linalg/linalg.mq.md @@ -9,420 +9,817 @@ import: Formula-first linear algebra (English). MatExpr simplify + display; ABI plugin. +Use [the linear-algebra workflow](index.mq.md) to build a matrix from readable formula data, factor it once and solve through its receiver. This leaf owns the shared native matrix expression API. Keep dimensions, tolerance units, lazy expressions and materialized data distinct in new operations. Native ABI changes belong in marqdo_plugin_linalg; numeric validation should compare results and residuals rather than accepting a nonempty handle. + ## ensure_plugin +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + Load the ABI v2 `linalg` plugin once. -**p = > plugin.native_path name="linalg"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="linalg"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg) - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. ## ping +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Plugin health check. | + Plugin health check. -> ensure_plugin -*> linalg_ping* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Plugin health check.](linalg_ping())*. ## mul - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix product (lazy MatMul; shape-checked). | + +Use `a`, `b` as the inputs for this operation. Matrix product (lazy MatMul; shape-checked). -> ensure_plugin -*> linalg_mul a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix product (lazy MatMul; shape-checked).](linalg_mul(a=`a`, b=`b`))*. ## add - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix / expression addition. | + +Use `a`, `b` as the inputs for this operation. Matrix / expression addition. -> ensure_plugin -*> linalg_add a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix / expression addition.](linalg_add(a=`a`, b=`b`))*. ## sub - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix / expression subtraction. | + +Use `a`, `b` as the inputs for this operation. Matrix / expression subtraction. -> ensure_plugin -*> linalg_sub a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix / expression subtraction.](linalg_sub(a=`a`, b=`b`))*. ## transpose - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Transpose expression. | + +Use `expr` as the inputs for this operation. Transpose expression. -> ensure_plugin -*> linalg_transpose expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Transpose expression.](linalg_transpose(expr=`expr`))*. ## inv - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Symbolic inverse (lazy). | + +Use `expr` as the inputs for this operation. Symbolic inverse (lazy). -> ensure_plugin -*> linalg_inv expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Symbolic inverse (lazy).](linalg_inv(expr=`expr`))*. ## simplify - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply MatExpr rewrite rules (R1–R5). | + +Use `expr` as the inputs for this operation. Apply MatExpr rewrite rules (R1–R5). -> ensure_plugin -*> linalg_simplify expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Apply MatExpr rewrite rules (R1–R5).](linalg_simplify(expr=`expr`))*. ## ascii - + `expr` - + `raw`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | +| raw | any | False | Whether to keep the unsimplified expression tree while rendering | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Display ASCII (default simplify first). Pass `raw=True` to keep the written tree. | + +Use `expr`, `raw`=False as the inputs for this operation. Display ASCII (default simplify first). Pass `raw=True` to keep the written tree. -> ensure_plugin -*> linalg_ascii expr=`expr` raw=`raw`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Display ASCII (default simplify first). Pass raw=True to keep the written tree.](linalg_ascii(expr=`expr`, raw=`raw`))*. ## latex - + `expr` - + `raw`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | +| raw | any | False | Whether to keep the unsimplified expression tree while rendering | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | LaTeX display. | + +Use `expr`, `raw`=False as the inputs for this operation. LaTeX display. -> ensure_plugin -*> linalg_latex expr=`expr` raw=`raw`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[LaTeX display.](linalg_latex(expr=`expr`, raw=`raw`))*. ## shape - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix shape (rows, cols). | + +Use `expr` as the inputs for this operation. Matrix shape (rows, cols). -> ensure_plugin -*> linalg_shape expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix shape (rows, cols).](linalg_shape(expr=`expr`))*. ## show - + `expr` - + `path`=None - + `raw`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| raw | any | False | Whether to keep the unsimplified expression tree while rendering | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Record a formula SVG via host plot channel (default simplify). Returns the expr map. | + +Use `expr`, `path`=None, `raw`=False as the inputs for this operation. Record a formula SVG via host plot channel (default simplify). Returns the expr map. -> ensure_plugin -*> linalg_show expr=`expr` path=`path` raw=`raw`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Record a formula SVG via host plot channel (default simplify). Returns the expr map.](linalg_show(expr=`expr`, path=`path`, raw=`raw`))*. ## eye - + `n` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | required | Matrix order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Identity matrix of order n. | + +Use `n` as the inputs for this operation. Identity matrix of order n. -> ensure_plugin -*> linalg_eye n=`n`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Identity matrix of order n.](linalg_eye(n=`n`))*. ## zeros - + `rows` - + `cols` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | any | required | Input row records to insert or process | +| cols | any | required | Matrix column count | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Zero matrix. | + +Use `rows`, `cols` as the inputs for this operation. Zero matrix. -> ensure_plugin -*> linalg_zeros rows=`rows` cols=`cols`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*. ## from_list - + `data` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Dense leaf from nested list. | + +Use `data` as the inputs for this operation. Dense leaf from nested list. -> ensure_plugin -*> linalg_from_list data=`data`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Dense leaf from nested list.](linalg_from_list(data=`data`))*. ## from_formula - + `formula` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula accepted by the documented parser | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf. | + +Use `formula` as the inputs for this operation. Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf. -> ensure_plugin -*> linalg_from_formula formula=`formula`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Absorb a $$ numeric matrix formula (or nested list / dense map) as a dense leaf.](linalg_from_formula(formula=`formula`))*. ## explicit - + `expr` - + `raw`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | +| raw | any | False | Whether to keep the unsimplified expression tree while rendering | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Evaluate to dense (default simplify first). | + +Use `expr`, `raw`=False as the inputs for this operation. Evaluate to dense (default simplify first). -> ensure_plugin -*> linalg_explicit expr=`expr` raw=`raw`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Evaluate to dense (default simplify first).](linalg_explicit(expr=`expr`, raw=`raw`))*. ## det - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Determinant. | + +Use `expr` as the inputs for this operation. Determinant. -> ensure_plugin -*> linalg_det expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Determinant.](linalg_det(expr=`expr`))*. ## trace - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Trace. | + +Use `expr` as the inputs for this operation. Trace. -> ensure_plugin -*> linalg_trace expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Trace.](linalg_trace(expr=`expr`))*. ## solve - + `a`=None - + `b` - + `factor`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | None | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | +| factor | any | None | Reusable factorization returned by factorize | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`. | + +Use `a`=None, `b`, `factor`=None as the inputs for this operation. Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`. -> ensure_plugin -*> linalg_solve a=`a` b=`b` factor=`factor`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Solve a x = b (Gaussian elimination), or reuse factorize kind=lu via factor + b.](linalg_solve(a=`a`, b=`b`, factor=`factor`))*. ## matmul - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Dense matrix product → `linalg_dense`. | + +Use `a`, `b` as the inputs for this operation. Dense matrix product → `linalg_dense`. -> ensure_plugin -*> linalg_matmul a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Dense matrix product → linalg_dense.](linalg_matmul(a=`a`, b=`b`))*. ## kron - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Lazy Kronecker product (does not expand). | + +Use `a`, `b` as the inputs for this operation. Lazy Kronecker product (does not expand). -> ensure_plugin -*> linalg_kron a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Lazy Kronecker product (does not expand).](linalg_kron(a=`a`, b=`b`))*. ## block - + `blocks` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| blocks | any | required | Nested row list of block matrix expressions | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Block matrix from a nested list of expressions. | + +Use `blocks` as the inputs for this operation. Block matrix from a nested list of expressions. -> ensure_plugin -*> linalg_block blocks=`blocks`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Block matrix from a nested list of expressions.](linalg_block(blocks=`blocks`))*. ## collapse - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Block-level collapse (`Block*Block` → block of products). | + +Use `expr` as the inputs for this operation. Block-level collapse (`Block*Block` → block of products). -> ensure_plugin -*> linalg_collapse expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Block-level collapse (Block*Block → block of products).](linalg_collapse(expr=`expr`))*. ## factorize - + `matrix` - + `kind`="lu" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| matrix | any | required | Matrix value supplied for evaluation or factorization | +| kind | any | "lu" | Operation or factorization kind listed in this function's behavior | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` | `chol`). | + +Use `matrix`, `kind`="lu" as the inputs for this operation. Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` | `chol`). -> ensure_plugin -*> linalg_factorize matrix=`matrix` kind=`kind`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Dense factorization → linalg_factor (kind = lu | qr | svd | eig | chol).](linalg_factorize(matrix=`matrix`, kind=`kind`))*. ## draw - + `factor` - + `kind`=None - + `path`=None - + `theme`="light" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| factor | any | required | Reusable factorization returned by factorize | +| kind | any | None | Operation or factorization kind listed in this function's behavior | +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| theme | any | "light" | Rendering theme token supported by the implementation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`. | + +Use `factor`, `kind`=None, `path`=None, `theme`="light" as the inputs for this operation. Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`. -> ensure_plugin -*> linalg_draw factor=`factor` kind=`kind` path=`path` theme=`theme`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Structure SVG (eig | svd | qr | lu | ge | chol | structure | heatmap | hinton). Theme tokens match quantum Q8: light | dark | bw.](linalg_draw(factor=`factor`, kind=`kind`, path=`path`, theme=`theme`))*. ## lstsq - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Left matrix or numeric operand | +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Least squares `min ||a x - b||` (QR if tall, SVD if wide). | + +Use `a`, `b` as the inputs for this operation. Least squares `min ||a x - b||` (QR if tall, SVD if wide). -> ensure_plugin -*> linalg_lstsq a=`a` b=`b`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Least squares min ||a x - b|| (QR if tall, SVD if wide).](linalg_lstsq(a=`a`, b=`b`))*. ## norm - + `expr` - + `ord`="fro" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | +| ord | any | "fro" | Norm order accepted by the native norm implementation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only. | + +Use `expr`, `ord`="fro" as the inputs for this operation. Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only. -> ensure_plugin -*> linalg_norm expr=`expr` ord=`ord`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix norm: fro | 1 | inf | 2. Complex dense supports fro only.](linalg_norm(expr=`expr`, ord=`ord`))*. ## cond - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Spectral condition number via SVD (`ord=2`). | + +Use `expr` as the inputs for this operation. Spectral condition number via SVD (`ord=2`). -> ensure_plugin -*> linalg_cond expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Spectral condition number via SVD (ord=2).](linalg_cond(expr=`expr`))*. ## rank - + `expr` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Numerical rank (SVD). | + +Use `expr` as the inputs for this operation. Numerical rank (SVD). -> ensure_plugin -*> linalg_rank expr=`expr`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Numerical rank (SVD).](linalg_rank(expr=`expr`))*. ## declare - + `table` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | Database table name or form submission table | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env. | + +Use `table` as the inputs for this operation. Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env. -> ensure_plugin -*> linalg_declare table=`table` type_tag="matrix"* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Declare several matrix symbols from an @ record table (name / rows / cols). Returns a map env.](linalg_declare(table=`table`, type_tag="matrix"))*. ## symbol - + `name` - + `rows` - + `cols` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | required | Name registered or looked up by this operation | +| rows | any | required | Input row records to insert or process | +| cols | any | required | Matrix column count | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). | + +Use `name`, `rows`, `cols` as the inputs for this operation. Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). -> ensure_plugin -*> matrix name=`name` rows=`rows` cols=`cols`* +We **[Load the native plugin required by this operation](ensure_plugin())**. +Return *[Matrix](matrix(name=`name`, rows=`rows`, cols=`cols`))*. # matrix - + `name`=None - + `rows`=None - + `cols`=None - + `data`=None - + `formula`=None - + `n`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | None | Name registered or looked up by this operation | +| rows | any | None | Input row records to insert or process | +| cols | any | None | Matrix column count | +| data | any | None | Structured input supplied to this adapter or resource | +| formula | any | None | Symbolic formula accepted by the documented parser | +| n | any | None | Matrix order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. | + +Use `name`=None, `rows`=None, `cols`=None, `data`=None, `formula`=None, `n`=None as the inputs for this operation. Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. -> ensure_plugin +We **[Load the native plugin required by this operation](ensure_plugin())**. 1. `formula` - *> linalg_from_formula formula=`formula`* + Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_formula(formula=`formula`))*. 2. `data` - *> linalg_from_list data=`data`* + Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_list(data=`data`))*. 3. `name` - *> linalg_symbol name=`name` rows=`rows` cols=`cols`* + Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_symbol(name=`name`, rows=`rows`, cols=`cols`))*. 4. `n` - *> linalg_eye n=`n`* + Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_eye(n=`n`))*. 5. `rows` - *> linalg_zeros rows=`rows` cols=`cols`* + Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_zeros(rows=`rows`, cols=`cols`))*. 6. * - > print text=ext/linalg: matrix needs name= / data= / formula= / n= / rows= - *None* + We **[Print the prepared message](print(text="ext/linalg: matrix needs", name="/", data="/", formula="/", n="/", rows=""))**. + Return *None*. ## T +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Transpose (method). | + Transpose (method). -*> linalg_transpose expr=`self`* +Return *[Transpose (method).](linalg_transpose(expr=`self`))*. ## T_ascii +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Transpose then display ASCII (auto-simplified). Handy for lecture identities. | + Transpose then display ASCII (auto-simplified). Handy for lecture identities. -**`Pt` = > linalg_transpose expr=`self`** -*> linalg_ascii expr=`Pt` raw=False* +We retain **`Pt` = [Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_transpose(expr=`self`))**. +Return *[Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_ascii(expr=`Pt`, raw=False))*. ## add - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix / expression addition. | + +Use `b` as the inputs for this operation. Matrix / expression addition. -*> linalg_add a=`self` b=`b`* +Return *[Matrix / expression addition.](linalg_add(a=`self`, b=`b`))*. ## sub - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix / expression subtraction. | + +Use `b` as the inputs for this operation. Matrix / expression subtraction. -*> linalg_sub a=`self` b=`b`* +Return *[Matrix / expression subtraction.](linalg_sub(a=`self`, b=`b`))*. ## mul - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| b | any | required | Right matrix, right-hand side or numeric operand | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix / expression product. | + +Use `b` as the inputs for this operation. Matrix / expression product. -*> linalg_mul a=`self` b=`b`* +Return *[Matrix / expression product.](linalg_mul(a=`self`, b=`b`))*. ## inv +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Inverse. | + Inverse. -*> linalg_inv expr=`self`* +Return *[Inverse.](linalg_inv(expr=`self`))*. ## simplify +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Simplify MatExpr. | + Simplify MatExpr. -*> linalg_simplify expr=`self`* +Return *[Simplify MatExpr.](linalg_simplify(expr=`self`))*. ## ascii +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | ASCII display. | + ASCII display. -*> linalg_ascii expr=`self` raw=False* +Return *[ASCII display.](linalg_ascii(expr=`self`, raw=False))*. ## latex +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | LaTeX display. | + LaTeX display. -*> linalg_latex expr=`self` raw=False* +Return *[LaTeX display.](linalg_latex(expr=`self`, raw=False))*. ## explicit +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Evaluate to an explicit matrix. | + Evaluate to an explicit matrix. -*> linalg_explicit expr=`self` raw=False* +Return *[Evaluate to an explicit matrix.](linalg_explicit(expr=`self`, raw=False))*. ## det +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Determinant. | + Determinant. -*> linalg_det expr=`self`* +Return *[Determinant.](linalg_det(expr=`self`))*. ## trace +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Trace. | + Trace. -*> linalg_trace expr=`self`* +Return *[Trace.](linalg_trace(expr=`self`))*. ## show - + `path`=None - + `raw`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects | +| raw | any | False | Whether to keep the unsimplified expression tree while rendering | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Show / export the expression. | + +Use `path`=None, `raw`=False as the inputs for this operation. Show / export the expression. -*> linalg_show expr=`self` path=`path` raw=`raw`* +Return *[Show / export the expression.](linalg_show(expr=`self`, path=`path`, raw=`raw`))*. ## eye - + `n` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | required | Matrix order | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Identity matrix of order n. | + +Use `n` as the inputs for this operation. Identity matrix of order n. -*> linalg_eye n=`n`* +Return *[Identity matrix of order n.](linalg_eye(n=`n`))*. ## zeros - + `rows` - + `cols` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | any | required | Input row records to insert or process | +| cols | any | required | Matrix column count | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Zero matrix. | + +Use `rows`, `cols` as the inputs for this operation. Zero matrix. -*> linalg_zeros rows=`rows` cols=`cols`* +Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*. ## from_list - + `data` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | any | required | Structured input supplied to this adapter or resource | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix from nested list. | + +Use `data` as the inputs for this operation. Matrix from nested list. -*> linalg_from_list data=`data`* +Return *[Matrix from nested list.](linalg_from_list(data=`data`))*. ## from_formula - + `formula` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula accepted by the documented parser | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Matrix from formula text. | + +Use `formula` as the inputs for this operation. Matrix from formula text. -*> linalg_from_formula formula=`formula`* +Return *[Matrix from formula text.](linalg_from_formula(formula=`formula`))*. diff --git a/ext/linalg/索引.mq.md b/ext/linalg/索引.mq.md new file mode 100644 index 0000000..c9c78e2 --- /dev/null +++ b/ext/linalg/索引.mq.md @@ -0,0 +1,45 @@ +--- +markup: occlusion +title: 线性代数工程入口 +import: + 代数: ext/linalg/线性代数.mq.md +--- + +从本入口运行完整矩阵流程,再阅读[中文接口](线性代数.mq.md)中每个工具的契约与说明。 +[英文入口](index.mq.md)与此流程同义,表达式构造、求值、求解与分解复用共用原生实现。 +对象方法必须有真实矩阵接收者;独立函数则明确传入矩阵或表达式。 + +在本源码工作区先用 cargo build -p marqdo_plugin_linalg 构建依赖,再执行: + +```sh +marqdo call ext/linalg/索引.mq.md 求解示例 --effects plugin --json +``` + +本例只做离线计算,不写文件、不连接外部服务。新增能力应在原生 linalg 中实现边界算法, +公开文件补齐中英文契约和错误示例,并验证维度、奇异性及容差。绘图输出是另一种效果, +指定路径时要明确产物归属与清理责任,不把展示字符串当可计算的矩阵数据。 + +## 求解示例 + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 原生求解记录;其中 x.data 对应列向量 [[2], [1]] | + +本例求解二乘 x 加 y 等于五、x 加三乘 y 等于五。系数和右端都用原生矩阵公式给出, +先分解一次再求解,不复制另一份矩阵解析或消元程序。分解值只能用于维度兼容的系统。 + +`系数` = +$$ +\begin{bmatrix}2&1\\1&3\end{bmatrix} +$$ + +`右端` = +$$ +\begin{pmatrix}5\\5\end{pmatrix} +$$ + +先**矩阵 = [由系数公式构造矩阵](代数.自公式(公式=`系数`))**, +再**向量 = [由右端公式构造列向量](代数.自公式(公式=`右端`))**。 +接着**分解 = [对系数矩阵进行一次 LU 分解](代数.分解(矩阵=`矩阵`, 类型="lu"))**, +最后返回*[复用分解结果求解本系统](代数.求解(右=`向量`, 分解=`分解`))*。 +调用者应检查实际结果中的数值,不将函数调用成功等同于任意系统都满足精度要求。 diff --git a/ext/linalg/线性代数.mq.md b/ext/linalg/线性代数.mq.md index a61c632..2d674a4 100644 --- a/ext/linalg/线性代数.mq.md +++ b/ext/linalg/线性代数.mq.md @@ -9,421 +9,825 @@ import: 公式优先的线性代数(中文)。矩阵表达式化简与展示;ABI 插件。 +从[求解入口](索引.mq.md)可运行由公式构造矩阵、复用分解并求解的真实示例。本文件是中文数值门面,原生算法位于 marqdo_plugin_linalg。新增操作需说明形状、容差单位、惰性表达式和物化结果的区别;用数值与残差验证算法,不能把非空句柄当成正确结果。保持中英文入口同源,不复制一套矩阵运行时。 + ## 确保插件 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 完成后不返回业务数据;插件缺失会报告原因并结束运行。 | + 加载 ABI v2 `linalg` 插件一次。 -**p = > plugin.native_path name="linalg"** +这里只负责定位并加载现有原生库,不创建矩阵,也不会自动下载或编译插件。缺少插件时结束当前运行,让调用者修复安装路径后重试;不能返回一个伪造的矩阵句柄继续计算。加载成功后返回空值,真实数值结果由后续运算产生。 + +得到**`p` = [定位已安装的原生插件](plugin.native_path(name="linalg"))**。 1. `p` - > plugin.load path=`p` + 这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。 2. * - > print text=ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg) - > sys.exit code=1 -**** + 这里**[输出本步已准备的消息](print(text="ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg)"))**。 + 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 +完成后返回*None*。 ## 探测 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 插件探活。 | + 插件探活。 -> 确保插件 -*> linalg_ping* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[插件探活。](linalg_ping())*。 ## 乘 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵乘(惰性;检查形状)。 | + +这里使用`左`、`右`。 矩阵乘(惰性;检查形状)。 -> 确保插件 -*> linalg_mul a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[矩阵乘(惰性;检查形状)。](linalg_mul(a=`左`, b=`右`))*。 ## 加 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵 / 表达式加法。 | + +这里使用`左`、`右`。 矩阵 / 表达式加法。 -> 确保插件 -*> linalg_add a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`左`, b=`右`))*。 ## 减 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵 / 表达式减法。 | + +这里使用`左`、`右`。 矩阵 / 表达式减法。 -> 确保插件 -*> linalg_sub a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`左`, b=`右`))*。 ## 转置 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 | + +这里使用`式`。 转置。 -> 确保插件 -*> linalg_transpose expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`式`))*。 ## 逆 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 求逆。 | + +这里使用`式`。 求逆。 -> 确保插件 -*> linalg_inv expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[求逆。](linalg_inv(expr=`式`))*。 ## 化简 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 应用矩阵表达式重写规则(R1–R5)。 | + +这里使用`式`。 应用矩阵表达式重写规则(R1–R5)。 -> 确保插件 -*> linalg_simplify expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[应用矩阵表达式重写规则(R1–R5)。](linalg_simplify(expr=`式`))*。 ## 文本 - + `式` - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 展示 ASCII(默认先 化简)。`原始=True` 保留书写树。 | + +这里使用`式`、`原始`=False。 展示 ASCII(默认先 化简)。`原始=True` 保留书写树。 -> 确保插件 -*> linalg_ascii expr=`式` raw=`原始`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[展示 ASCII(默认先 化简)。原始=True 保留书写树。](linalg_ascii(expr=`式`, raw=`原始`))*。 ## 乳胶 - + `式` - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | LaTeX 展示。 | + +这里使用`式`、`原始`=False。 LaTeX 展示。 -> 确保插件 -*> linalg_latex expr=`式` raw=`原始`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[LaTeX 展示。](linalg_latex(expr=`式`, raw=`原始`))*。 ## 形状 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。 | + +这里使用`式`。 形状。 -> 确保插件 -*> linalg_shape expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。](linalg_shape(expr=`式`))*。 ## 展示 - + `式` - + `路径`=None - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | +| 路径 | any | None | 授权根目录内的文件路径 | +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 写入公式 SVG(默认化简)。 | + +这里使用`式`、`路径`=None、`原始`=False。 写入公式 SVG(默认化简)。 -> 确保插件 -*> linalg_show expr=`式` path=`路径` raw=`原始`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[写入公式 SVG(默认化简)。](linalg_show(expr=`式`, path=`路径`, raw=`原始`))*。 ## 单位 - + `阶` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 阶 | any | 必填 | 方阵阶数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 对比特施加单位门 / 单位矩阵。 | + +这里使用`阶`。 对比特施加单位门 / 单位矩阵。 -> 确保插件 -*> linalg_eye n=`阶`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。 ## 零阵 - + `行` - + `列` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | any | 必填 | 矩阵行数 | +| 列 | any | 必填 | 矩阵列数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 零矩阵。 | + +这里使用`行`、`列`。 零矩阵。 -> 确保插件 -*> linalg_zeros rows=`行` cols=`列`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。 ## 自列表 - + `数据` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | any | 必填 | 交给本操作处理的结构化数据 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 由嵌套列表构造矩阵。 | + +这里使用`数据`。 由嵌套列表构造矩阵。 -> 确保插件 -*> linalg_from_list data=`数据`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。 ## 自公式 - + `公式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 吸收 `$$` 数值矩阵公式为稠密叶。 | + +这里使用`公式`。 吸收 `$$` 数值矩阵公式为稠密叶。 -> 确保插件 -*> linalg_from_formula formula=`公式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[吸收 $$ 数值矩阵公式为稠密叶。](linalg_from_formula(formula=`公式`))*。 ## 求值 - + `式` - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 求成稠密(默认先 化简)。 | + +这里使用`式`、`原始`=False。 求成稠密(默认先 化简)。 -> 确保插件 -*> linalg_explicit expr=`式` raw=`原始`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[求成稠密(默认先 化简)。](linalg_explicit(expr=`式`, raw=`原始`))*。 ## 行列式 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 | + +这里使用`式`。 行列式。 -> 确保插件 -*> linalg_det expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`式`))*。 ## 迹 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 | + +这里使用`式`。 迹。 -> 确保插件 -*> linalg_trace expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`式`))*。 ## 求解 - + `左`=None - + `右` - + `分解`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | None | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | +| 分解 | any | None | 分解函数返回的可复用分解记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。 | + +这里使用`左`=None、`右`、`分解`=None。 解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。 -> 确保插件 -*> linalg_solve a=`左` b=`右` factor=`分解`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[解 左 · x = 右,或复用 分解(kind=lu)+ 右。](linalg_solve(a=`左`, b=`右`, factor=`分解`))*。 ## 稠密乘 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。 | + +这里使用`左`、`右`。 稠密乘。 -> 确保插件 -*> linalg_matmul a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。](linalg_matmul(a=`左`, b=`右`))*。 ## 克罗内克 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 惰性 Kronecker 积(默认不展开)。 | + +这里使用`左`、`右`。 惰性 Kronecker 积(默认不展开)。 -> 确保插件 -*> linalg_kron a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[惰性 Kronecker 积(默认不展开)。](linalg_kron(a=`左`, b=`右`))*。 ## 分块 - + `块` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 块 | any | 必填 | 按行列排列的分块矩阵表达式列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 由嵌套表达式列表构造分块矩阵。 | + +这里使用`块`。 由嵌套表达式列表构造分块矩阵。 -> 确保插件 -*> linalg_block blocks=`块`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[由嵌套表达式列表构造分块矩阵。](linalg_block(blocks=`块`))*。 ## 分块化简 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 分块级塌缩(`Block*Block` → 块乘加)。 | + +这里使用`式`。 分块级塌缩(`Block*Block` → 块乘加)。 -> 确保插件 -*> linalg_collapse expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[分块级塌缩(Block*Block → 块乘加)。](linalg_collapse(expr=`式`))*。 ## 分解 - + `矩阵` - + `类型`="lu" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 矩阵 | any | 必填 | 本次求值或分解的矩阵值 | +| 类型 | any | "lu" | 本操作说明支持的分解或表示类型 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 稠密分解 → `linalg_factor`(`类型` = `lu` | `qr` | `svd` | `eig` | `chol`)。 | + +这里使用`矩阵`、`类型`="lu"。 稠密分解 → `linalg_factor`(`类型` = `lu` | `qr` | `svd` | `eig` | `chol`)。 -> 确保插件 -*> linalg_factorize matrix=`矩阵` kind=`类型`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[稠密分解 → linalg_factor(类型 = lu | qr | svd | eig | chol)。](linalg_factorize(matrix=`矩阵`, kind=`类型`))*。 ## 绘图 - + `分解` - + `类型`=None - + `路径`=None - + `主题`="light" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 分解 | any | 必填 | 分解函数返回的可复用分解记录 | +| 类型 | any | None | 本操作说明支持的分解或表示类型 | +| 路径 | any | None | 授权根目录内的文件路径 | +| 主题 | any | "light" | 渲染主题标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。 | + +这里使用`分解`、`类型`=None、`路径`=None、`主题`="light"。 结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。 -> 确保插件 -*> linalg_draw factor=`分解` kind=`类型` path=`路径` theme=`主题`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[结构 SVG(eig | svd | qr | lu | ge | chol | structure | heatmap | hinton)。主题与 quantum Q8 对齐:light | dark | bw。](linalg_draw(factor=`分解`, kind=`类型`, path=`路径`, theme=`主题`))*。 ## 最小二乘 - + `左` - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | any | 必填 | 运算左侧的矩阵或表达式 | +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。 | + +这里使用`左`、`右`。 最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。 -> 确保插件 -*> linalg_lstsq a=`左` b=`右`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[最小二乘 min ||左 · x - 右||(高瘦用 QR,宽用 SVD)。](linalg_lstsq(a=`左`, b=`右`))*。 ## 范数 - + `式` - + `范数`="fro" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | +| 范数 | any | "fro" | 范数函数支持的阶数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。 | + +这里使用`式`、`范数`="fro"。 矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。 -> 确保插件 -*> linalg_norm expr=`式` ord=`范数`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[矩阵范数:fro | 1 | inf | 2。复数稠密暂仅 fro。](linalg_norm(expr=`式`, ord=`范数`))*。 ## 条件数 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 谱条件数(SVD,`ord=2`)。 | + +这里使用`式`。 谱条件数(SVD,`ord=2`)。 -> 确保插件 -*> linalg_cond expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[谱条件数(SVD,ord=2)。](linalg_cond(expr=`式`))*。 ## 秩 - + `式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 式 | any | 必填 | 本库产生的矩阵表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 数值秩(SVD)。 | + +这里使用`式`。 数值秩(SVD)。 -> 确保插件 -*> linalg_rank expr=`式`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[数值秩(SVD)。](linalg_rank(expr=`式`))*。 ## 声明 - + `表` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 表 | any | 必填 | 可读声明记录表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。 | + +这里使用`表`。 用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。 -> 确保插件 -*> linalg_declare table=`表` type_tag="矩阵"* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[用 @ 记录表一次声明多个符号矩阵(名 / 行 / 列)。返回环境 map。](linalg_declare(table=`表`, type_tag="矩阵"))*。 ## 符号 - + `名` - + `行` - + `列` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | 必填 | 本操作注册或查找的名称 | +| 行 | any | 必填 | 矩阵行数 | +| 列 | any | 必填 | 矩阵列数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 | + +这里使用`名`、`行`、`列`。 抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 -> 确保插件 -*> 矩阵 名=`名` 行=`行` 列=`列`* +这里**[加载本操作依赖的原生插件](确保插件())**。 +完成后返回*[调用 矩阵](矩阵(名=`名`, 行=`行`, 列=`列`))*。 # 矩阵 - + `名`=None - + `行`=None - + `列`=None - + `数据`=None - + `公式`=None - + `阶`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | None | 本操作注册或查找的名称 | +| 行 | any | None | 矩阵行数 | +| 列 | any | None | 矩阵列数 | +| 数据 | any | None | 交给本操作处理的结构化数据 | +| 公式 | any | None | 原生矩阵解析器接受的符号公式 | +| 阶 | any | None | 方阵阶数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 | + +这里使用`名`=None、`行`=None、`列`=None、`数据`=None、`公式`=None、`阶`=None。 矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 -> 确保插件 +这里**[加载本操作依赖的原生插件](确保插件())**。 1. `公式` - *> linalg_from_formula formula=`公式`* + 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_formula(formula=`公式`))*。 2. `数据` - *> linalg_from_list data=`数据`* + 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_list(data=`数据`))*。 3. `名` - *> linalg_symbol name=`名` rows=`行` cols=`列`* + 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_symbol(name=`名`, rows=`行`, cols=`列`))*。 4. `阶` - *> linalg_eye n=`阶`* + 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_eye(n=`阶`))*。 5. `行` - *> linalg_zeros rows=`行` cols=`列`* + 完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_zeros(rows=`行`, cols=`列`))*。 6. * - > print text=ext/linalg: 矩阵需要 名= / 数据= / 公式= / 阶= / 行= - *None* + 这里**[输出本步已准备的消息](print(text="ext/linalg: 矩阵需要", 名="/", 数据="/", 公式="/", 阶="/", 行=""))**。 + 完成后返回*None*。 ## 转置 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 | + 转置。 -*> linalg_transpose expr=`self`* +完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`self`))*。 ## 转置文本 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 转置后输出 ASCII(默认化简)。适合讲义恒等式验收。 | + 转置后输出 ASCII(默认化简)。适合讲义恒等式验收。 -**`转` = > linalg_transpose expr=`self`** -*> linalg_ascii expr=`转` raw=False* +得到**`转` = [转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_transpose(expr=`self`))**。 +完成后返回*[转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_ascii(expr=`转`, raw=False))*。 ## 加 - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵 / 表达式加法。 | + +这里使用`右`。 矩阵 / 表达式加法。 -*> linalg_add a=`self` b=`右`* +完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`self`, b=`右`))*。 ## 减 - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵 / 表达式减法。 | + +这里使用`右`。 矩阵 / 表达式减法。 -*> linalg_sub a=`self` b=`右`* +完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`self`, b=`右`))*。 ## 乘 - + `右` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 矩阵 / 表达式乘法。 | + +这里使用`右`。 矩阵 / 表达式乘法。 -*> linalg_mul a=`self` b=`右`* +完成后返回*[矩阵 / 表达式乘法。](linalg_mul(a=`self`, b=`右`))*。 ## 逆 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 求逆。 | + 求逆。 -*> linalg_inv expr=`self`* +完成后返回*[求逆。](linalg_inv(expr=`self`))*。 ## 化简 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 化简矩阵表达式。 | + 化简矩阵表达式。 -*> linalg_simplify expr=`self`* +完成后返回*[化简矩阵表达式。](linalg_simplify(expr=`self`))*。 ## 文本 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | ASCII 展示。 | + ASCII 展示。 -*> linalg_ascii expr=`self` raw=False* +完成后返回*[ASCII 展示。](linalg_ascii(expr=`self`, raw=False))*。 ## 乳胶 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | LaTeX 展示。 | + LaTeX 展示。 -*> linalg_latex expr=`self` raw=False* +完成后返回*[LaTeX 展示。](linalg_latex(expr=`self`, raw=False))*。 ## 求值 - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 求成显式矩阵。 | + +这里使用`原始`=False。 求成显式矩阵。 -*> linalg_explicit expr=`self` raw=`原始`* +完成后返回*[求成显式矩阵。](linalg_explicit(expr=`self`, raw=`原始`))*。 ## 行列式 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 | + 行列式。 -*> linalg_det expr=`self`* +完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`self`))*。 ## 迹 +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 | + 迹。 -*> linalg_trace expr=`self`* +完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`self`))*。 ## 展示 - + `路径`=None - + `原始`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权根目录内的文件路径 | +| 原始 | any | False | 渲染时是否保留未化简表达式树 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 展示 / 导出表达式。 | + +这里使用`路径`=None、`原始`=False。 展示 / 导出表达式。 -*> linalg_show expr=`self` path=`路径` raw=`原始`* +完成后返回*[展示 / 导出表达式。](linalg_show(expr=`self`, path=`路径`, raw=`原始`))*。 ## 单位 - + `阶` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 阶 | any | 必填 | 方阵阶数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 对比特施加单位门 / 单位矩阵。 | + +这里使用`阶`。 对比特施加单位门 / 单位矩阵。 -*> linalg_eye n=`阶`* +完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。 ## 零阵 - + `行` - + `列` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | any | 必填 | 矩阵行数 | +| 列 | any | 必填 | 矩阵列数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 零矩阵。 | + +这里使用`行`、`列`。 零矩阵。 -*> linalg_zeros rows=`行` cols=`列`* +完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。 ## 自列表 - + `数据` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | any | 必填 | 交给本操作处理的结构化数据 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 由嵌套列表构造矩阵。 | + +这里使用`数据`。 由嵌套列表构造矩阵。 -*> linalg_from_list data=`数据`* +完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。 ## 自公式 - + `公式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | any | 由公式文本构造矩阵。 | + +这里使用`公式`。 由公式文本构造矩阵。 -*> linalg_from_formula formula=`公式`* +完成后返回*[由公式文本构造矩阵。](linalg_from_formula(formula=`公式`))*。 diff --git a/ext/net/http.mq.md b/ext/net/http.mq.md index 36cf1ad..d2d5c74 100644 --- a/ext/net/http.mq.md +++ b/ext/net/http.mq.md @@ -7,20 +7,37 @@ import: sys: lib/sys.mq.md --- +This file constructs the application Result record only; it does not implement an HTTP transport. For real HTTP requests, response limits and downloads, import lib/net.mq.md. The [network entry](index.mq.md) distinguishes pure URL transformations from native WebSocket exchanges. Keep these responsibilities explicit when extending the package so a readable tool name never implies a missing capability. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/net: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. ## result - + `ok` - + `value`=None - + `error`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ok | any | required | Whether this application-level operation succeeded | +| value | any | None | Value supplied to this operation; immutable transformations return a new value | +| error | any | None | Structured failure information supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Unified Result map `{ok, value, error}`. | + +Use `ok`, `value`=None, `error`=None as the inputs for this operation. Unified Result map `{ok, value, error}`. @@ -30,4 +47,4 @@ Unified Result map `{ok, value, error}`. |----|-------|-------| | `ok` | `value` | `error` | -*out* +Return *out*. diff --git a/ext/net/index.mq.md b/ext/net/index.mq.md new file mode 100644 index 0000000..1f90120 --- /dev/null +++ b/ext/net/index.mq.md @@ -0,0 +1,62 @@ +--- +markup: occlusion +title: Network resources — URL data and WebSocket exchanges +import: + url_api: ext/net/url.mq.md + socket_api: ext/net/websocket.mq.md +--- + +This package provides [URL encoding](url.mq.md), the small [HTTP result constructor](http.mq.md), +and a native [WebSocket request/response resource](websocket.mq.md). For HTTP clients with +status, timeout, response limits and downloads, read the standard library net.mq.md directly. +The HTTP leaf here constructs a result record; its name does not imply an implemented HTTP client. + +URL encoding is pure and needs no plugin. This command is ready to run from the repository root: + +```sh +marqdo call ext/net/index.mq.md encode 'text="Marqdo notes/one"' --json +``` + +WebSocket exchanges need the native web plugin and an explicitly chosen server. Build the plugin +with scripts/build-web-plugin.sh, then supply a controlled endpoint to exchange. No example opens +a public socket implicitly. The resource closes after one bounded exchange; it is not a persistent +subscription API. Read the returned ok/error as well as the reply data before using the outcome. + +Develop URL transformations by composing the public standard library; native transport belongs in +the web plugin. Preserve timeout units, byte/reply caps and close behavior. Add controlled local +server tests for transport failures and timeouts instead of treating an empty reply as success. + +## encode + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text component to percent-encode; this does not fetch a URL | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Encoded URL component returned by the public encoding helper | + +The input `text` is content for an encoded component, not an already assembled URL to navigate. +Keeping this transformation separate makes it possible to build request data without network +permission. We return *[Percent-encode the selected component](url_api.encode(text=`text`))* +so the caller can place it in the intended path or query according to its own URL structure. + +## exchange + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Explicit ws/wss endpoint controlled by the caller | +| message | text | "" | Single outgoing text message | +| timeout_sec | number | 30 | Positive exchange timeout in seconds | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Native exchange result; failures carry ok=false/error instead of an empty successful reply | + +The caller supplies `url`, optionally `message`="" and `timeout_sec`=30. This tool performs a +real exchange, so it needs plugin permission and an available endpoint. The native leaf caps +replies and frame sizes and closes the connection before returning; it does not retry a send. + +We create **socket = [Configure a bounded WebSocket receiver](socket_api.ws(timeout_sec=`timeout_sec`))**, +then return *[Send the message and collect the bounded reply](> `socket`.connect url=`url` message=`message` )*. +Inspect the actual result before deciding whether a follow-up request is appropriate. diff --git a/ext/net/url.mq.md b/ext/net/url.mq.md index fe4dfec..0d85304 100644 --- a/ext/net/url.mq.md +++ b/ext/net/url.mq.md @@ -6,7 +6,20 @@ import: net: lib/net.mq.md --- -## encode - + `text` +Use this leaf to encode data for a URL component, not to fetch or validate a remote service. The [network entry](index.mq.md) provides a directly runnable encoding example. Whole URLs, path components and query values have different escaping responsibilities; pass the intended component and let the caller assemble the final URL. Prefer composing lib/url.mq.md when adding pure transformations. -*> net.url_encode text=`text`* +## encode + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | any | required | Text supplied to the transformation or adapter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Percent-encode the supplied text using the public standard library URL helper. | + +Use `text` as the inputs for this operation. + +Percent-encode the supplied text using the public standard library URL helper. + +Return *[Url encode](net.url_encode(text=`text`))*. diff --git a/ext/net/websocket.mq.md b/ext/net/websocket.mq.md index 0bb25f8..413058f 100644 --- a/ext/net/websocket.mq.md +++ b/ext/net/websocket.mq.md @@ -8,36 +8,63 @@ import: table: lib/table.mq.md --- +This resource performs one bounded native WebSocket exchange and closes it. The [network entry](index.mq.md) shows the input contract and the distinction from pure URL encoding. Configure a controlled ws/wss endpoint and inspect ok/error, timeout and reply data before acting. New transport behavior belongs in the web plugin, with local tests for failed connections and oversized replies; this resource is not a persistent subscription service. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/net: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # ws - + `timeout_sec`=30 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| timeout_sec | any | 30 | Request/response timeout in seconds | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | WebSocket client helper. | + +Use `timeout_sec`=30 as the inputs for this operation. WebSocket client helper. -> _load +We **[Load the native plugin required by this operation](_load())**. + `out` = | timeout_sec | _type | |-------------|-------| | `timeout_sec` | ws | -*out* +Return *out*. ## connect - + `url` - + `message`="" - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | required | Resource connection URL; scheme selects the documented backend | +| message | any | "" | Outgoing WebSocket or application message | +| headers | any | None | HTTP request header record or None | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply. | + +Use `url`, `message`="", `headers`=None as the inputs for this operation. Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply. -**timeout = [timeout_sec](access(self, "timeout_sec"))** -*> web_ws_connect url=`url` message=`message` headers=`headers` timeout_sec=`timeout`* +We retain **`timeout` = [Read timeout_sec field](access(`self`, "timeout_sec"))**. +Return *[Single request–response: connect to url, send message, collect up to 256 server text replies (each up to 1 MiB), close](web_ws_connect(url=`url`, message=`message`, headers=`headers`, timeout_sec=`timeout`))*. diff --git a/ext/quantum/_capability/index.mq.md b/ext/quantum/_capability/index.mq.md index 19d883d..6829053 100644 --- a/ext/quantum/_capability/index.mq.md +++ b/ext/quantum/_capability/index.mq.md @@ -30,6 +30,10 @@ and tests/call_cli.rs before returning to [circuit](../circuit/index.mq.md). ## load +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | null after a successful load | + Locate the ABI v2 quantum shared library through plugin.native_path, then plugin.load it. If the library is missing, print a short install hint and exit non-zero so CI and agents fail loudly. After a successful load, later quantum @@ -39,14 +43,10 @@ start of each tool that needs the simulator. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | null after a successful load | - -**p = > plugin.native_path name="quantum"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="quantum"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum) - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. diff --git a/ext/quantum/circuit/index.mq.md b/ext/quantum/circuit/index.mq.md index cd6fd33..df04943 100644 --- a/ext/quantum/circuit/index.mq.md +++ b/ext/quantum/circuit/index.mq.md @@ -58,588 +58,599 @@ and the existing tests/ext/quantum-steps-smoke.mq.md author example. ## new -| 参数 | 类型 | 说明 | -|------|------|------| -| qubits | number | wire count | -| steps | any | optional gate table or None | - -Create a state-vector circuit of width `qubits`=1 by default. Optional -`steps`=None means no preloaded gates; when a table is provided it is parsed -like the author API. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubits | number | 1 | wire count | +| steps | any | None | optional gate table or None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | new circuit handle | -> cap.load -*> quantum_circuit_new qubits=`qubits` steps=`steps`* +Use `qubits`=1, `steps`=None as the inputs for this operation. + +Create a state-vector circuit of width `qubits`=1 by default. Optional + +`steps`=None means no preloaded gates; when a table is provided it is parsed +like the author API. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Create a state-vector circuit of width qubits=1 by default. Optional like the author API.](quantum_circuit_new(qubits=`qubits`, steps=`steps`))*. ## hadamard -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | target wire | +| circuit | any | required | existing circuit | + +| 返回 | 类型 | 说明 | |------|------|------| -| circuit | any | existing circuit | -| qubit | number | target wire | +| result | any | updated circuit | + +Use `qubit`=0, `circuit` as the inputs for this operation. Apply Hadamard on wire `qubit`=0 of an existing `circuit` by default. Prefer this when an agent already holds a circuit from new or toget. +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply Hadamard on wire qubit=0 of an existing circuit by default. Prefer this when an agent already holds a circuit from new or toget.](quantum_h(circuit=`circuit`, qubit=`qubit`))*. + +## cnot + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | existing circuit | +| control | number | 0 | control wire | +| target | number | 1 | target wire | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | updated circuit | -> cap.load -*> quantum_h circuit=`circuit` qubit=`qubit`* - -## cnot - -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | existing circuit | -| control | number | control wire | -| target | number | target wire | +Use `circuit`, `control`=0, `target`=1 as the inputs for this operation. Controlled-NOT on `circuit` from `control`=0 to `target`=1 by default. Together with hadamard this prepares a Bell pair on two wires. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | updated circuit | - -> cap.load -*> quantum_cx circuit=`circuit` control=`control` target=`target`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Controlled-NOT on circuit from control=0 to target=1 by default. Together with hadamard this prepares a Bell pair on two wires.](quantum_cx(circuit=`circuit`, control=`control`, target=`target`))*. ## barrier -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | existing circuit | - -Insert a visual barrier on `circuit`. The state does not change; drawings show a -separator so lectures can mark logical layers. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | existing circuit | | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with barrier recorded | -> cap.load -*> quantum_barrier circuit=`circuit`* +Use `circuit` as the inputs for this operation. + +Insert a visual barrier on `circuit`. The state does not change; drawings show a +separator so lectures can mark logical layers. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Insert a visual barrier on circuit. The state does not change; drawings show a separator so lectures can mark logical layers.](quantum_barrier(circuit=`circuit`))*. ## measure_mark -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | existing circuit | -| qubits | any | wire list or None for all | - -Mark computational-basis readout on `circuit` for later simulate.run. This does -not collapse the ideal state used by probabilities. Pass `qubits`=None to mark -every wire. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | existing circuit | +| qubits | any | None | wire list or None for all | | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with measure markers | -> cap.load -*> quantum_measure circuit=`circuit` qubits=`qubits`* +Use `circuit`, `qubits`=None as the inputs for this operation. + +Mark computational-basis readout on `circuit` for later simulate.run. This does +not collapse the ideal state used by probabilities. Pass `qubits`=None to mark +every wire. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Mark computational-basis readout on circuit for later simulate](quantum_measure(circuit=`circuit`, qubits=`qubits`))*. ## x -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_x circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply Pauli X (bit flip) on the chosen wire](quantum_x(circuit=`circuit`, qubit=`qubit`))*. ## y -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_y circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply Pauli Y on the chosen wire](quantum_y(circuit=`circuit`, qubit=`qubit`))*. ## z -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_z circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply Pauli Z (phase flip) on the chosen wire](quantum_z(circuit=`circuit`, qubit=`qubit`))*. ## s -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_s circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply the phase gate S (√Z) on the chosen wire](quantum_s(circuit=`circuit`, qubit=`qubit`))*. ## t -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_t circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply the phase gate T (π/8) on the chosen wire](quantum_t(circuit=`circuit`, qubit=`qubit`))*. ## i -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0 (input). +Use `qubit`=0, `circuit` as the inputs for this operation. Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_i circuit=`circuit` qubit=`qubit`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply the identity on the chosen wire](quantum_i(circuit=`circuit`, qubit=`qubit`))*. ## rx -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_rx circuit=`circuit` qubit=`qubit` theta=`theta`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Rotate the chosen wire about the X axis by angle theta in radians](quantum_rx(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. ## ry -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_ry circuit=`circuit` qubit=`qubit` theta=`theta`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Rotate the chosen wire about the Y axis by angle theta in radians](quantum_ry(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. ## rz -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta`, `circuit` as the inputs for this operation. Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_rz circuit=`circuit` qubit=`qubit` theta=`theta`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Rotate the chosen wire about the Z axis by angle theta in radians](quantum_rz(circuit=`circuit`, qubit=`qubit`, theta=`theta`))*. ## cz -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| control | number | Default 0 | -| target | number | Default 1 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| control | number | 0 | Default 0 | +| target | number | 1 | Default 1 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `control`=0, `target`=1 (input). +Use `control`=0, `target`=1, `circuit` as the inputs for this operation. Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_cz circuit=`circuit` control=`control` target=`target`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply controlled-Z between control and target](quantum_cz(circuit=`circuit`, control=`control`, target=`target`))*. ## swap -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| a | number | Default 0 | -| b | number | Default 1 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | number | 0 | Default 0 | +| b | number | 1 | Default 1 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `a`=0, `b`=1 (input). +Use `a`=0, `b`=1, `circuit` as the inputs for this operation. Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_swap circuit=`circuit` a=`a` b=`b`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Exchange the two wires named by a and b](quantum_swap(circuit=`circuit`, a=`a`, b=`b`))*. ## append -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| op | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| op | any | required | Required | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `op` (input). +Use `op`, `circuit` as the inputs for this operation. Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_append circuit=`circuit` op=`op`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Append this item to the new list](quantum_append(circuit=`circuit`, op=`op`))*. ## apply -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | Existing circuit; returns a new value | -| gate | any | Required | -| qubits | any | Default 0 (input) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| gate | any | required | Required | +| qubits | any | 0 | Default 0 (input) | +| circuit | any | required | Existing circuit; returns a new value | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Updated circuit | -Inputs: `gate`, `qubits`=0 (input). +Use `gate`, `qubits`=0, `circuit` as the inputs for this operation. Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. -> cap.load -*> quantum_apply circuit=`circuit` gate=`gate` qubits=`qubits`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list](quantum_apply(circuit=`circuit`, gate=`gate`, qubits=`qubits`))*. # circuit -| 参数 | 类型 | 说明 | -|------|------|------| -| qubits | number | Default 1 | -| steps | any | Default None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubits | number | 1 | Default 1 | +| steps | any | None | Default None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubits`=1, `steps`=None (input). +Use `qubits`=1, `steps`=None as the inputs for this operation. State-vector circuit on n wires (default all-zero ket). Optional steps= preloads a gate table. Methods append gates and return a fresh handle for chaining. Agents should prefer the ## call tools above; authors use this object for readable method chains in programs. -> cap.load -*> quantum_circuit_new qubits=`qubits` steps=`steps`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[State-vector circuit on n wires (default all-zero ket)](quantum_circuit_new(qubits=`qubits`, steps=`steps`))*. ## h -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply the Hadamard gate on the chosen wire. This creates equal superposition from computational basis states and is the first step of Bell and GHZ recipes. Returns an updated circuit handle so authors can chain without in-place mutation. -*> quantum_h circuit=`self` qubit=`qubit`* +Return *[Apply the Hadamard gate on the chosen wire](quantum_h(circuit=`self`, qubit=`qubit`))*. ## x -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. -*> quantum_x circuit=`self` qubit=`qubit`* +Return *[Apply Pauli X (bit flip) on the chosen wire](quantum_x(circuit=`self`, qubit=`qubit`))*. ## y -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. -*> quantum_y circuit=`self` qubit=`qubit`* +Return *[Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs.](quantum_y(circuit=`self`, qubit=`qubit`))*. ## z -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. -*> quantum_z circuit=`self` qubit=`qubit`* +Return *[Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle.](quantum_z(circuit=`self`, qubit=`qubit`))*. ## s -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. -*> quantum_s circuit=`self` qubit=`qubit`* +Return *[Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits.](quantum_s(circuit=`self`, qubit=`qubit`))*. ## t -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. -*> quantum_t circuit=`self` qubit=`qubit`* +Return *[Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits.](quantum_t(circuit=`self`, qubit=`qubit`))*. ## i -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0 (input). +Use `qubit`=0 as the inputs for this operation. Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. -*> quantum_i circuit=`self` qubit=`qubit`* +Return *[Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle.](quantum_i(circuit=`self`, qubit=`qubit`))*. ## rx -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta` as the inputs for this operation. Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. -*> quantum_rx circuit=`self` qubit=`qubit` theta=`theta`* +Return *[Rotate the chosen wire about the X axis by angle theta in radians](quantum_rx(circuit=`self`, qubit=`qubit`, theta=`theta`))*. ## ry -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta` as the inputs for this operation. Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. -*> quantum_ry circuit=`self` qubit=`qubit` theta=`theta`* +Return *[Rotate the chosen wire about the Y axis by angle theta in radians](quantum_ry(circuit=`self`, qubit=`qubit`, theta=`theta`))*. ## rz -| 参数 | 类型 | 说明 | -|------|------|------| -| qubit | number | Default 0 | -| theta | number | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | Default 0 | +| theta | number | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubit`=0, `theta` (input). +Use `qubit`=0, `theta` as the inputs for this operation. Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. -*> quantum_rz circuit=`self` qubit=`qubit` theta=`theta`* +Return *[Rotate the chosen wire about the Z axis by angle theta in radians](quantum_rz(circuit=`self`, qubit=`qubit`, theta=`theta`))*. ## cx -| 参数 | 类型 | 说明 | -|------|------|------| -| control | number | Default 0 | -| target | number | Default 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| control | number | 0 | Default 0 | +| target | number | 1 | Default 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `control`=0, `target`=1 (input). +Use `control`=0, `target`=1 as the inputs for this operation. Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining. -*> quantum_cx circuit=`self` control=`control` target=`target`* +Return *[Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining.](quantum_cx(circuit=`self`, control=`control`, target=`target`))*. ## cz -| 参数 | 类型 | 说明 | -|------|------|------| -| control | number | Default 0 | -| target | number | Default 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| control | number | 0 | Default 0 | +| target | number | 1 | Default 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `control`=0, `target`=1 (input). +Use `control`=0, `target`=1 as the inputs for this operation. Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. -*> quantum_cz circuit=`self` control=`control` target=`target`* +Return *[Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining.](quantum_cz(circuit=`self`, control=`control`, target=`target`))*. ## swap -| 参数 | 类型 | 说明 | -|------|------|------| -| a | number | Default 0 | -| b | number | Default 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | number | 0 | Default 0 | +| b | number | 1 | Default 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `a`=0, `b`=1 (input). +Use `a`=0, `b`=1 as the inputs for this operation. Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. -*> quantum_swap circuit=`self` a=`a` b=`b`* +Return *[Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle.](quantum_swap(circuit=`self`, a=`a`, b=`b`))*. ## barrier @@ -649,73 +660,73 @@ Exchange the two wires named by a and b. Useful when routing logical qubits in a Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails. -*> quantum_barrier circuit=`self`* +Return *[Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails.](quantum_barrier(circuit=`self`))*. ## measure -| 参数 | 类型 | 说明 | -|------|------|------| -| qubits | any | Default None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubits | any | None | Default None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `qubits`=None (input). +Use `qubits`=None as the inputs for this operation. Mark computational-basis readout wires for later run sampling. This does not collapse the ideal state used by probabilities. Pass qubits=None to mark every wire. -*> quantum_measure circuit=`self` qubits=`qubits`* +Return *[Mark computational-basis readout wires for later run sampling](quantum_measure(circuit=`self`, qubits=`qubits`))*. ## append -| 参数 | 类型 | 说明 | -|------|------|------| -| op | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| op | any | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `op` (input). +Use `op` as the inputs for this operation. Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. -*> quantum_append circuit=`self` op=`op`* +Return *[Append this item to the new list](quantum_append(circuit=`self`, op=`op`))*. ## apply -| 参数 | 类型 | 说明 | -|------|------|------| -| gate | any | Required | -| qubits | any | Default 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| gate | any | required | Required | +| qubits | any | 0 | Default 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `gate`, `qubits`=0 (input). +Use `gate`, `qubits`=0 as the inputs for this operation. Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. -*> quantum_apply circuit=`self` gate=`gate` qubits=`qubits`* +Return *[Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining.](quantum_apply(circuit=`self`, gate=`gate`, qubits=`qubits`))*. ## noise -| 参数 | 类型 | 说明 | -|------|------|------| -| kind | any | Required | -| p | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kind | any | required | Required | +| p | any | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | New circuit value; keep it to continue | -Inputs: `kind`, `p` (input). +Use `kind`, `p` as the inputs for this operation. Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design. -*> quantum_noise circuit=`self` kind=`kind` p=`p`* +Return *[Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design.](quantum_noise(circuit=`self`, kind=`kind`, p=`p`))*. ## simulate @@ -725,7 +736,7 @@ Attach teaching noise of the given kind and strength for run trajectories. Ideal Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path. -*> quantum_simulate circuit=`self`* +Return *[Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path.](quantum_simulate(circuit=`self`))*. ## state @@ -735,7 +746,7 @@ Return ideal state-vector amplitudes as re/im pairs for the current circuit. Tea Return the ideal state object with the same amplitudes as simulate. Prefer this when later fidelity or density tools expect a state handle rather than raw amplitudes. -*> quantum_state circuit=`self`* +Return *[Return the ideal state object with the same amplitudes as simulate](quantum_state(circuit=`self`))*. ## probabilities @@ -745,43 +756,43 @@ Return the ideal state object with the same amplitudes as simulate. Prefer this Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story. -*> quantum_probabilities circuit=`self`* +Return *[Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story.](quantum_probabilities(circuit=`self`))*. ## run -| 参数 | 类型 | 说明 | -|------|------|------| -| shots | number | Default 1024 | -| seed | number | Default 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| shots | number | 1024 | Default 1024 | +| seed | number | 1 | Default 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Shot metadata and counts | -Inputs: `shots`=1024, `seed`=1 (input). +Use `shots`=1024, `seed`=1 as the inputs for this operation. Sample computational-basis shots from this circuit. Defaults are shots=1024 and seed=1 for reproducible replays. Applies teaching noise when a noise channel was attached. -*> quantum_run circuit=`self` shots=`shots` seed=`seed`* +Return *[Sample computational-basis shots from this circuit](quantum_run(circuit=`self`, shots=`shots`, seed=`seed`))*. ## draw -| 参数 | 类型 | 说明 | -|------|------|------| -| path | any | Default None | -| kind | any | Default circuit | -| qubit | number | Default 0 | -| theme | any | Default dark | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Default None | +| kind | any | "circuit" | Default circuit | +| qubit | number | 0 | Default 0 | +| theme | any | "dark" | Default dark | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg with kind and svg | -Inputs: `path`=None, `kind`="circuit", `qubit`=0, `theme`="dark" (input). +Use `path`=None, `kind`="circuit", `qubit`=0, `theme`="dark" as the inputs for this operation. Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds. Theme tokens are dark, light, and bw. Optional path writes the file for CLI or view embedding. -*> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit` theme=`theme`* +Return *[Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds](quantum_draw_circuit(circuit=`self`, path=`path`, kind=`kind`, qubit=`qubit`, theme=`theme`))*. ## density @@ -791,36 +802,36 @@ Render an SVG figure for circuit rails, probability bars, Bloch spheres, or adva Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces. -*> quantum_density_from_state state=`self`* +Return *[Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces.](quantum_density_from_state(state=`self`))*. ## expect -| 参数 | 类型 | 说明 | -|------|------|------| -| obs | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| obs | any | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | number | Scalar observation | -Inputs: `obs` (input). +Use `obs` as the inputs for this operation. Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored. -*> quantum_density_expect density=`self` obs=`obs`* +Return *[Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored.](quantum_density_expect(density=`self`, obs=`obs`))*. ## schmidt -| 参数 | 类型 | 说明 | -|------|------|------| -| cut | number | Default 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| cut | number | 1 | Default 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Coefficients, subsystem bases and entropy | -Inputs: `cut`=1 (input). +Use `cut`=1 as the inputs for this operation. Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits. -*> quantum_schmidt state=`self` cut=`cut`* +Return *[Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits.](quantum_schmidt(state=`self`, cut=`cut`))*. diff --git a/ext/quantum/density/index.mq.md b/ext/quantum/density/index.mq.md index f1a816b..371ef6c 100644 --- a/ext/quantum/density/index.mq.md +++ b/ext/quantum/density/index.mq.md @@ -46,142 +46,156 @@ independent matrices in tests/ext/quantum-linalg-smoke.mq.md. ## from_state -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| state | any | required | pure state or circuit | + +| 返回 | 类型 | 说明 | |------|------|------| -| state | any | pure state or circuit | +| result | any | density handle | + +Use `state` as the inputs for this operation. Form rho as the outer product of a pure `state` (or the ideal state of a circuit). Use this when you trust the pure-state picture and want mixed-state tools without writing a matrix by hand. +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Form rho as the outer product of a pure state (or the ideal state of a circuit)](quantum_density_from_state(state=`state`))*. + +## from_matrix + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| matrix | any | required | Hermitian matrix | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | density handle | -> cap.load -*> quantum_density_from_state state=`state`* - -## from_matrix - -| 参数 | 类型 | 说明 | -|------|------|------| -| matrix | any | Hermitian matrix | +Use `matrix` as the inputs for this operation. Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the lecture so the matrix on the page is the matrix in the simulator. Size is limited by the plugin. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | density handle | - -> cap.load -*> quantum_density_from_matrix matrix=`matrix`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Build rho from an explicit Hermitian matrix](quantum_density_from_matrix(matrix=`matrix`))*. ## purity -| 参数 | 类型 | 说明 | -|------|------|------| -| density | any | density operator | - -Compute the trace of rho squared for `density`. Values near one mean nearly -pure; lower values mean classical mixing or traced-out entanglement. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| density | any | required | density operator | | 返回 | 类型 | 说明 | |------|------|------| | result | number | purity | -> cap.load -*> quantum_density_purity density=`density`* +Use `density` as the inputs for this operation. + +Compute the trace of rho squared for `density`. Values near one mean nearly +pure; lower values mean classical mixing or traced-out entanglement. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Compute the trace of rho squared for density. Values near one mean nearly pure; lower values mean classical mixing or traced-out entanglement.](quantum_density_purity(density=`density`))*. ## partial_trace -| 参数 | 类型 | 说明 | -|------|------|------| -| density | any | joint density | -| keep | any | qubit index list to keep | - -Keep listed qubits in `keep` and trace out the rest of `density`. Indices use -LSB equals zero. The result is generally mixed even when the joint state was -pure. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| keep | any | required | qubit index list to keep | +| density | any | required | joint density | | 返回 | 类型 | 说明 | |------|------|------| | result | any | reduced density | -> cap.load -*> quantum_density_partial_trace density=`density` keep=`keep`* +Use `keep`, `density` as the inputs for this operation. + +Keep listed qubits in `keep` and trace out the rest of `density`. Indices use +LSB equals zero. The result is generally mixed even when the joint state was +pure. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Keep listed qubits in keep and trace out the rest of density](quantum_density_partial_trace(density=`density`, keep=`keep`))*. ## expect -| 参数 | 类型 | 说明 | -|------|------|------| -| density | any | density operator | -| obs | any | Pauli string or matrix | - -Expectation of observable `obs` on `density`. Pauli strings use left equals -high bit. Pass a matrix when the observable is not a Pauli product. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| obs | any | required | Pauli string or matrix | +| density | any | required | density operator | | 返回 | 类型 | 说明 | |------|------|------| | result | number | expectation value | -> cap.load -*> quantum_density_expect density=`density` obs=`obs`* +Use `obs`, `density` as the inputs for this operation. + +Expectation of observable `obs` on `density`. Pauli strings use left equals +high bit. Pass a matrix when the observable is not a Pauli product. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Expectation of observable obs on density. Pauli strings use left equals high bit. Pass a matrix when the observable is not a Pauli product.](quantum_density_expect(density=`density`, obs=`obs`))*. ## eig -| 参数 | 类型 | 说明 | -|------|------|------| -| density | any | Hermitian density | - -Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a -lecture needs the eigenbasis of rho. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| density | any | required | Hermitian density | | 返回 | 类型 | 说明 | |------|------|------| | result | any | eigenvalues and eigenvectors | -> cap.load -*> quantum_density_eig density=`density`* +Use `density` as the inputs for this operation. + +Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a +lecture needs the eigenbasis of rho. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Hermitian spectrum of density as eigenvalues and eigenvectors. Useful when a lecture needs the eigenbasis of rho.](quantum_density_eig(density=`density`))*. ## matrix -| 参数 | 类型 | 说明 | -|------|------|------| -| density | any | Density handle / 密度句柄 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| density | any | required | Density handle / 密度句柄 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Nested complex entries with re and im | +Use `density` as the inputs for this operation. + Export the explicit nested complex matrix of `density`. Reading entries does not change the density operator. Use the exported entries for an independent trace check or further linear algebra; the caller remains responsible for physicality. -> cap.load -*> quantum_density_matrix density=`density`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Export the explicit nested complex matrix of density](quantum_density_matrix(density=`density`))*. # density -| 参数 | 类型 | 说明 | -|------|------|------| -| state | any | Default None | -| matrix | any | Default None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| state | any | None | Default None | +| matrix | any | None | Default None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Returned value | -Inputs: `state`=None, `matrix`=None (input). +Use `state`=None, `matrix`=None as the inputs for this operation. Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=. Density operations support at most six qubits. Pure and mixed states share this object surface for purity, partial trace, and expectation. -> cap.load +We **[Load the native plugin required by this operation](cap.load())**. 1. `matrix` - *> quantum_density_from_matrix matrix=`matrix`* + Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_matrix(matrix=`matrix`))*. 2. * - *> quantum_density_from_state state=`state`* + Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_state(state=`state`))*. ## matrix @@ -191,7 +205,7 @@ Construct a density operator from a pure state or circuit (state=) or from an ex Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package. -*> quantum_density_matrix density=`self`* +Return *[Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package](quantum_density_matrix(density=`self`))*. ## purity @@ -201,23 +215,23 @@ Return the explicit matrix of this density operator so authors can inspect entri Compute Tr(ρ²). Values near one mean a pure state; mixed states are strictly less than one. Use this as a quick entanglement or decoherence check after a partial trace. -*> quantum_density_purity density=`self`* +Return *[Compute Tr(ρ²)](quantum_density_purity(density=`self`))*. ## partial_trace -| 参数 | 类型 | 说明 | -|------|------|------| -| keep | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| keep | any | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Density operator handle | -Inputs: `keep` (input). +Use `keep` as the inputs for this operation. Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks. -*> quantum_density_partial_trace density=`self` keep=`keep`* +Return *[Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks.](quantum_density_partial_trace(density=`self`, keep=`keep`))*. ## eig @@ -227,37 +241,37 @@ Trace out every qubit except those listed in keep (LSB index 0). Returns the red Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors. Handy for lecture plots and for verifying that a constructed rho is physical. -*> quantum_density_eig density=`self`* +Return *[Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors](quantum_density_eig(density=`self`))*. ## expect -| 参数 | 类型 | 说明 | -|------|------|------| -| obs | any | Required | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| obs | any | required | Required | | 返回 | 类型 | 说明 | |------|------|------| | result | number | Scalar observation | -Inputs: `obs` (input). +Use `obs` as the inputs for this operation. Expectation value of observable obs on this density. obs may be a Pauli string with the left end as the high bit, or an explicit matrix matching the density dimension. -*> quantum_density_expect density=`self` obs=`obs`* +Return *[Expectation value of observable obs on this density](quantum_density_expect(density=`self`, obs=`obs`))*. ## draw -| 参数 | 类型 | 说明 | -|------|------|------| -| path | any | Default None | -| kind | any | Default hinton | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Default None | +| kind | any | "hinton" | Default hinton | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg with kind and svg | -Inputs: `path`=None, `kind`="hinton" (input). +Use `path`=None, `kind`="hinton" as the inputs for this operation. Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density. Optional path writes SVG; kind selects which visual metaphor the lecture uses. -*> quantum_density_draw density=`self` path=`path` kind=`kind`* +Return *[Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density](quantum_density_draw(density=`self`, path=`path`, kind=`kind`))*. diff --git a/ext/quantum/gate/index.mq.md b/ext/quantum/gate/index.mq.md index 019fa43..0ddbd27 100644 --- a/ext/quantum/gate/index.mq.md +++ b/ext/quantum/gate/index.mq.md @@ -45,6 +45,10 @@ which binds the Hadamard formula directly into the author gate constructor. ## hadamard +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Hadamard gate handle | + The Hadamard gate creates equal superposition from computational basis states. Its matrix in the computational basis is one over square-root two times the matrix with ones on the first row and one then minus one on the second row. @@ -53,43 +57,43 @@ equal minus combination. This tool returns a named gate handle for later apply. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Hadamard gate handle | - -> cap.load -*> quantum_gate_new name="H" theta=None matrix=None* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[The Hadamard gate creates equal superposition from computational basis states](quantum_gate_new(name="H", theta=None, matrix=None))*. ## pauli_x +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Pauli X handle | + Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and ket-one. Use it when a lecture needs an explicit NOT on the computational basis. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Pauli X handle | - -> cap.load -*> quantum_gate_new name="X" theta=None matrix=None* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and ket-one](quantum_gate_new(name="X", theta=None, matrix=None))*. ## pauli_z +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Pauli Z handle | + Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone. Its diagonal matrix is the standard computational-basis Z. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Pauli Z handle | - -> cap.load -*> quantum_gate_new name="Z" theta=None matrix=None* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone](quantum_gate_new(name="Z", theta=None, matrix=None))*. ## cnot +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | CNOT gate handle | + The controlled-NOT on two qubits flips the target when the control is ket-one. Wire order and bit-endianness follow the package convention where qubit 0 is the rightmost label bit. Prefer applying via circuit tools with explicit control and @@ -97,103 +101,108 @@ target indices when building lectures step by step. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | CNOT gate handle | - -> cap.load -*> quantum_gate_new name="CX" theta=None matrix=None* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[The controlled-NOT on two qubits flips the target when the control is ket-one](quantum_gate_new(name="CX", theta=None, matrix=None))*. ## custom -| 参数 | 类型 | 说明 | -|------|------|------| -| matrix | any | unitary matrix formula or list | -| name | text | optional label defaulting to U | - -Build a gate from an explicit unitary given as `matrix`. Authors usually bind a -formula matrix first, then pass that binding. Optional label `name`="U" marks -drawings when the caller omits a name. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| matrix | any | required | unitary matrix formula or list | +| name | text | "U" | optional label defaulting to U | | 返回 | 类型 | 说明 | |------|------|------| | result | any | custom gate handle | -> cap.load -*> quantum_gate_new name=`name` theta=None matrix=`matrix`* +Use `matrix`, `name`="U" as the inputs for this operation. + +Build a gate from an explicit unitary given as `matrix`. Authors usually bind a +formula matrix first, then pass that binding. Optional label `name`="U" marks +drawings when the caller omits a name. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Build a gate from an explicit unitary given as matrix](quantum_gate_new(name=`name`, theta=None, matrix=`matrix`))*. ## matches -| 参数 | 类型 | 说明 | -|------|------|------| -| gate | any | gate handle to test | -| matrix | any | expected unitary | -| tol | number | absolute tolerance | - -Teaching check: does `gate` match expected `matrix` within absolute tolerance -`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator -cannot drift apart. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| gate | any | required | gate handle to test | +| matrix | any | required | expected unitary | +| tol | number | 0.000000001 | absolute tolerance | | 返回 | 类型 | 说明 | |------|------|------| | result | bool | True when matrices match | -> cap.load -*> quantum_gate_matches_matrix gate=`gate` matrix=`matrix` tol=`tol`* +Use `gate`, `matrix`, `tol`=0.000000001 as the inputs for this operation. + +Teaching check: does `gate` match expected `matrix` within absolute tolerance + +`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator +cannot drift apart. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Teaching check: does gate match expected matrix within absolute tolerance cannot drift apart.](quantum_gate_matches_matrix(gate=`gate`, matrix=`matrix`, tol=`tol`))*. ## named -| 参数 | 类型 | 说明 | -|------|------|------| -| name | text | Built-in gate name | -| theta | any | Rotation angle or None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | "H" | Built-in gate name | +| theta | any | None | Rotation angle or None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Gate handle for circuit.apply | +Use `name`="H", `theta`=None as the inputs for this operation. + Construct built-in `name`="H" with optional `theta`=None . Rx, Ry and Rz require a numeric angle in radians. The returned gate can be passed to circuit.apply; creating it never changes a circuit. Supported names are listed above. -> cap.load -*> quantum_gate_new name=`name` theta=`theta` matrix=None* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Construct built-in name="H" with optional theta=None ](quantum_gate_new(name=`name`, theta=`theta`, matrix=None))*. ## matrix -| 参数 | 类型 | 说明 | -|------|------|------| -| gate | any | Gate handle | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| gate | any | required | Gate handle | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Nested complex entries with re and im | +Use `gate` as the inputs for this operation. + Export the explicit unitary of `gate`. Each complex entry has re and im fields. Use this to compare a formula with independent expected entries. Reading a gate matrix neither modifies its handle nor applies the operator to any circuit. -> cap.load -*> quantum_gate_matrix gate=`gate`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Export the explicit unitary of gate](quantum_gate_matrix(gate=`gate`))*. # gate -| 参数 | 类型 | 说明 | -|------|------|------| -| name | any | Default None | -| theta | number | Default None | -| matrix | any | Default None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | any | None | Default None | +| theta | number | None | Default None | +| matrix | any | None | Default None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | Gate handle for circuit.apply | -Inputs: `name`=None, `theta`=None, `matrix`=None (input). +Use `name`=None, `theta`=None, `matrix`=None as the inputs for this operation. Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence). Custom gates may set name= (default U). Authors and call-style tools share this object surface. -> cap.load -*> quantum_gate_new name=`name` theta=`theta` matrix=`matrix`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence)](quantum_gate_new(name=`name`, theta=`theta`, matrix=`matrix`))*. ## matrix @@ -203,38 +212,38 @@ Named built-in gate (name=H) or a custom unitary defined by matrix= (nested list Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula. -*> quantum_gate_matrix gate=`self`* +Return *[Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula.](quantum_gate_matrix(gate=`self`))*. ## matches_matrix -| 参数 | 类型 | 说明 | -|------|------|------| -| matrix | any | Required | -| tol | any | Default 0.000000001 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| matrix | any | required | Required | +| tol | any | 0.000000001 | Default 0.000000001 | | 返回 | 类型 | 说明 | |------|------|------| | result | bool | Match within absolute tolerance | -Inputs: `matrix`, `tol`=0.000000001 (input). +Use `matrix`, `tol`=0.000000001 as the inputs for this operation. Check whether this gate matches the given matrix within absolute tolerance tol. Typical after building a custom gate from a Markdown formula fence in a lecture notebook. -*> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`* +Return *[Check whether this gate matches the given matrix within absolute tolerance tol](quantum_gate_matches_matrix(gate=`self`, matrix=`matrix`, tol=`tol`))*. ## draw -| 参数 | 类型 | 说明 | -|------|------|------| -| path | any | Default None | -| kind | any | Default gate | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Default None | +| kind | any | "gate" | Default gate | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg with kind and svg | -Inputs: `path`=None, `kind`="gate" (input). +Use `path`=None, `kind`="gate" as the inputs for this operation. Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix). Optional path writes SVG to disk; plots also enter view/CLI through record_plot for the session. -*> quantum_gate_draw gate=`self` path=`path` kind=`kind`* +Return *[Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix)](quantum_gate_draw(gate=`self`, path=`path`, kind=`kind`))*. diff --git a/ext/quantum/index.mq.md b/ext/quantum/index.mq.md index 1bb84b8..5851388 100644 --- a/ext/quantum/index.mq.md +++ b/ext/quantum/index.mq.md @@ -219,12 +219,12 @@ control the other. The resulting amplitudes correlate 00 with 11. Return the circuit so a caller can apply another gate, attach noise, draw it or independently test entanglement. Every step keeps the returned new value. -**qc = circuit.new qubits=2 steps=None** +We retain **`qc` = [New](circuit.new(qubits=2, steps=None))**. Make two equal paths on the low wire, then propagate the path label to the other wire. -**qc = circuit.hadamard circuit=`qc` qubit=0** -*> circuit.cnot circuit=`qc` control=0 target=1* +We retain **`qc` = [Hadamard](circuit.hadamard(circuit=`qc`, qubit=0))**. +Return *[Cnot](circuit.cnot(circuit=`qc`, control=0, target=1))*. ## bell_phi_plus @@ -237,8 +237,8 @@ returns only ideal probabilities. Expect equal weights on 00 and 11 and zero elsewhere. Computational-basis correlation alone does not prove entanglement; use bell_analysis for reduced purity, ZZ expectation and Schmidt evidence. -**qc = > bell_circuit** -*> simulate.probabilities circuit=`qc`* +We retain **`qc` = [Bell circuit](bell_circuit())**. +Return *[Probabilities](simulate.probabilities(circuit=`qc`))*. ## bell_analysis @@ -253,23 +253,24 @@ or persistent session for the intermediate observations. Expect joint purity one, reduced purity one-half, ZZ one and Schmidt entropy ln(2), within 1e-9. All paths here describe ideal evolution rather than noisy trajectory averages. -**qc = > bell_circuit** -**probs = simulate.probabilities circuit=`qc`** +We retain **`qc` = [Bell circuit](bell_circuit())**. +We retain **`probs` = [Probabilities](simulate.probabilities(circuit=`qc`))**. Build the joint density and compute purity. A pure joint state need not have pure subsystems. Keep only the low wire and test the mixedness that appears when information about the other wire is discarded. -**rho = density.from_state state=`qc`** -**whole = density.purity density=`rho`** +We retain **`rho` = [From state](density.from_state(state=`qc`))**. +We retain **`whole` = [Purity](density.purity(density=`rho`))**. + `kept` = | qubit | |-------| | 0 | -**reduced = density.partial_trace density=`rho` keep=`kept`** -**local = density.purity density=`reduced`** +We retain **`reduced` = [Partial trace](density.partial_trace(density=`rho`, keep=`kept`))**. +We retain **`local` = [Purity](density.purity(density=`reduced`))**. ZZ measures correlation and is not an entanglement witness by itself. The Schmidt decomposition supplies pure-state coefficients and entropy. @@ -277,8 +278,8 @@ Together these observations distinguish a Bell pure state from a classical mixture with identical basis probabilities. Keep the measured values in the return table rather than hiding them behind a pass label with an implicit threshold. -**correlation = density.expect density=`rho` obs="ZZ"** -**split = state.schmidt state=`qc` cut=1** +We retain **`correlation` = [Expect](density.expect(density=`rho`, obs="ZZ"))**. +We retain **`split` = [Schmidt](state.schmidt(state=`qc`, cut=1))**. `report` = @@ -286,4 +287,4 @@ return table rather than hiding them behind a pass label with an implicit thresh |---------------|--------|----------------|----|---------| | `probs` | `whole` | `local` | `correlation` | `split` | -*report* +Return *report*. diff --git a/ext/quantum/simulate/index.mq.md b/ext/quantum/simulate/index.mq.md index 4c0f352..1f39600 100644 --- a/ext/quantum/simulate/index.mq.md +++ b/ext/quantum/simulate/index.mq.md @@ -51,85 +51,95 @@ For entanglement go to [state](../state/index.mq.md); for mixed states use ## simulate -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to evolve | - -Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise -channels attached to the circuit are ignored here. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to evolve | | 返回 | 类型 | 说明 | |------|------|------| | result | any | amplitude list | -> cap.load -*> quantum_simulate circuit=`circuit`* +Use `circuit` as the inputs for this operation. + +Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise +channels attached to the circuit are ignored here. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Return ideal state-vector amplitudes for circuit as re/im entries. Noise channels attached to the circuit are ignored here.](quantum_simulate(circuit=`circuit`))*. ## state -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to evolve | - -Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state -object. Prefer this when later fidelity or density tools expect a state handle. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to evolve | | 返回 | 类型 | 说明 | |------|------|------| | result | any | ideal state | -> cap.load -*> quantum_state circuit=`circuit`* +Use `circuit` as the inputs for this operation. + +Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state +object. Prefer this when later fidelity or density tools expect a state handle. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Same ideal amplitudes as simulate for circuit, packaged as the plugin state object. Prefer this when later fidelity or density tools expect a state handle.](quantum_state(circuit=`circuit`))*. ## probabilities -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to read | - -Map basis label to probability for the ideal state of `circuit`. Labels use -qubit 0 as the rightmost bit. Noise is ignored. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to read | | 返回 | 类型 | 说明 | |------|------|------| | result | any | probability map | -> cap.load -*> quantum_probabilities circuit=`circuit`* +Use `circuit` as the inputs for this operation. + +Map basis label to probability for the ideal state of `circuit`. Labels use +qubit 0 as the rightmost bit. Noise is ignored. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Map basis label to probability for the ideal state of circuit. Labels use qubit 0 as the rightmost bit. Noise is ignored.](quantum_probabilities(circuit=`circuit`))*. ## run -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to sample | -| shots | number | sample count | -| seed | number | RNG seed | - -Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 -and `seed`=1 so replays are deterministic. Teaching noise is applied when set. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to sample | +| shots | number | 1024 | sample count | +| seed | number | 1 | RNG seed | | 返回 | 类型 | 说明 | |------|------|------| | result | any | counts or shot result | -> cap.load -*> quantum_run circuit=`circuit` shots=`shots` seed=`seed`* +Use `circuit`, `shots`=1024, `seed`=1 as the inputs for this operation. + +Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 +and `seed`=1 so replays are deterministic. Teaching noise is applied when set. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Sample computational-basis outcomes from circuit. Defaults are shots=1024 and seed=1 so replays are deterministic. Teaching noise is applied when set.](quantum_run(circuit=`circuit`, shots=`shots`, seed=`seed`))*. ## noise -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to annotate | -| kind | text | noise family name | -| p | number | strength in the unit interval | - -Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal -simulate and probability tools ignore it. Keep p small unless demonstrating -decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kind | text | required | noise family name | +| p | number | required | strength in the unit interval | +| circuit | any | required | circuit to annotate | | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with noise metadata | -> cap.load -*> quantum_noise circuit=`circuit` kind=`kind` p=`p`* +Use `kind`, `p`, `circuit` as the inputs for this operation. + +Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal +simulate and probability tools ignore it. Keep p small unless demonstrating +decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Attach teaching noise of kind kind with strength p on circuit](quantum_noise(circuit=`circuit`, kind=`kind`, p=`p`))*. diff --git a/ext/quantum/state/index.mq.md b/ext/quantum/state/index.mq.md index f56abac..ea22d02 100644 --- a/ext/quantum/state/index.mq.md +++ b/ext/quantum/state/index.mq.md @@ -48,10 +48,16 @@ new implementation only with itself. Draw a single wire through ## kron -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | left factor state or matrix | +| b | any | required | right factor state or matrix | + +| 返回 | 类型 | 说明 | |------|------|------| -| a | any | left factor state or matrix | -| b | any | right factor state or matrix | +| result | any | tensor product | + +Use `a`, `b` as the inputs for this operation. The Kronecker product of `a` and `b` builds a larger space from two smaller ones. For state vectors this writes product states; for matrices it enlarges @@ -60,46 +66,47 @@ operators. Pass handles the plugin already understands. For a pure-state product, convert circuits with simulate.state first. Matrix factors take the operator branch; raw amplitude lists are not accepted as states. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | tensor product | - -> cap.load -*> quantum_kron a=`a` b=`b`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[The Kronecker product of a and b builds a larger space from two smaller ones](quantum_kron(a=`a`, b=`b`))*. ## fidelity -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | first pure state or circuit | +| b | any | required | second pure state or circuit | + +| 返回 | 类型 | 说明 | |------|------|------| -| a | any | first pure state or circuit | -| b | any | second pure state or circuit | +| result | number | fidelity in the unit interval | + +Use `a`, `b` as the inputs for this operation. Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is one when the states coincide and zero when they are orthogonal. You may pass a circuit handle; the plugin uses the ideal simulated state. Teaching noise is ignored. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | number | fidelity in the unit interval | - -> cap.load -*> quantum_fidelity a=`a` b=`b`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Pure-state fidelity between a and b is the squared absolute overlap](quantum_fidelity(a=`a`, b=`b`))*. ## schmidt -| 参数 | 类型 | 说明 | -|------|------|------| -| state | any | pure state or circuit | -| cut | number | qubits in subsystem A low bits | - -Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest -`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show -entanglement across the bipartition. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| state | any | required | pure state or circuit | +| cut | number | 1 | qubits in subsystem A low bits | | 返回 | 类型 | 说明 | |------|------|------| | result | any | singular values and factors | -> cap.load -*> quantum_schmidt state=`state` cut=`cut`* +Use `state`, `cut`=1 as the inputs for this operation. + +Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest + +`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show +entanglement across the bipartition. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Schmidt decomposition of state across a cut. Subsystem A owns the lowest entanglement across the bipartition.](quantum_schmidt(state=`state`, cut=`cut`))*. diff --git a/ext/quantum/viz/index.mq.md b/ext/quantum/viz/index.mq.md index 16267f7..6e65ec9 100644 --- a/ext/quantum/viz/index.mq.md +++ b/ext/quantum/viz/index.mq.md @@ -62,107 +62,124 @@ For input preparation follow [circuit](../circuit/index.mq.md), ## draw_circuit -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to render | +| theme | text | "dark" | dark light or bw | +| path | any | None | optional output path or None | + +| 返回 | 类型 | 说明 | |------|------|------| -| circuit | any | circuit to render | -| path | any | optional output path or None | -| theme | text | dark light or bw | +| result | any | drawing result | + +Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation. Render `circuit` as gate rails and barriers. Choose `theme`="dark" by default; light and bw preserve the same geometry. Optional `path`=None returns SVG without a file. A nonempty path is available to author programs under run. +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Render circuit as gate rails and barriers](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="circuit", qubit=0, theme=`theme`))*. + +## draw_probs + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | circuit to render | +| theme | text | "dark" | dark light or bw | +| path | any | None | optional output path or None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | -> cap.load -*> quantum_draw_circuit circuit=`circuit` path=`path` kind="circuit" qubit=0 theme=`theme`* - -## draw_probs - -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit to render | -| path | any | optional output path or None | -| theme | text | dark light or bw | +Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation. Plot ideal basis probabilities of `circuit`. Default `theme`="dark" supports light and bw alternatives. Optional `path`=None returns SVG without a file. The bars ignore teaching noise, just like simulate.probabilities. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -> cap.load -*> quantum_draw_circuit circuit=`circuit` path=`path` kind="probs" qubit=0 theme=`theme`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Plot ideal basis probabilities of circuit](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="probs", qubit=0, theme=`theme`))*. ## draw_bloch -| 参数 | 类型 | 说明 | -|------|------|------| -| circuit | any | circuit source | -| path | any | optional output path or None | -| qubit | number | which wire | -| theme | text | dark light or bw | - -Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default -`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit -circuit still produces one reduced wire picture, not a joint-state sphere. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| qubit | number | 0 | which wire | +| circuit | any | required | circuit source | +| theme | text | "dark" | dark light or bw | +| path | any | None | optional output path or None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | -> cap.load -*> quantum_draw_circuit circuit=`circuit` path=`path` kind="bloch" qubit=`qubit` theme=`theme`* +Use `qubit`=0, `circuit`, `theme`="dark", `path`=None as the inputs for this operation. + +Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default + +`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit +circuit still produces one reduced wire picture, not a joint-state sphere. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Show the reduced Bloch sphere of wire qubit=0 from circuit. Default circuit still produces one reduced wire picture, not a joint-state sphere.](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="bloch", qubit=`qubit`, theme=`theme`))*. ## draw_density -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| density | any | required | density operator | +| kind | text | "hinton" | hinton city density or paulivec | +| path | any | None | optional output path or None | + +| 返回 | 类型 | 说明 | |------|------|------| -| density | any | density operator | -| path | any | optional output path or None | -| kind | text | hinton city density or paulivec | +| result | any | drawing result | + +Use `density`, `kind`="hinton", `path`=None as the inputs for this operation. Plot `density` using `kind`="hinton" by default. Alternatives are city, density and paulivec. Optional `path`=None returns SVG without a file. Use the density module to construct the mixed-state input before drawing. +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Plot density using kind="hinton" by default](quantum_density_draw(density=`density`, path=`path`, kind=`kind`))*. + +## draw_gate + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| gate | any | required | gate handle | +| kind | text | "gate" | gate or matrix | +| path | any | None | optional output path or None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | -> cap.load -*> quantum_density_draw density=`density` path=`path` kind=`kind`* - -## draw_gate - -| 参数 | 类型 | 说明 | -|------|------|------| -| gate | any | gate handle | -| path | any | optional output path or None | -| kind | text | gate or matrix | +Use `gate`, `kind`="gate", `path`=None as the inputs for this operation. Plot `gate` using `kind`="gate" by default. Choose matrix for a complex-entry heatmap. Optional `path`=None returns SVG without a file. This observes the operator rather than applying it or changing any circuit. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | drawing result | - -> cap.load -*> quantum_gate_draw gate=`gate` path=`path` kind=`kind`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Plot gate using kind="gate" by default](quantum_gate_draw(gate=`gate`, path=`path`, kind=`kind`))*. ## draw_state -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| circuit | any | required | Circuit evolved ideally | +| kind | text | "qsphere" | qsphere or multibloch | +| path | any | None | SVG output path or None | + +| 返回 | 类型 | 说明 | |------|------|------| -| circuit | any | Circuit evolved ideally | -| kind | text | qsphere or multibloch | -| path | any | SVG output path or None | +| result | any | quantum_svg with kind and svg | + +Use `circuit`, `kind`="qsphere", `path`=None as the inputs for this operation. Observe the ideal state of `circuit` as a basis-amplitude/phase sphere or one reduced Bloch sphere per wire. Default `kind`="qsphere"; use multibloch for the @@ -171,9 +188,5 @@ local Bloch vectors alone cannot certify joint entanglement. Both advanced figures currently use fixed styling; theme support remains Q8c work and is not offered as a nonfunctional parameter here. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg with kind and svg | - -> cap.load -*> quantum_draw_circuit circuit=`circuit` path=`path` kind=`kind` qubit=0 theme="dark"* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Observe the ideal state of circuit as a basis-amplitude/phase sphere or one reduced Bloch sphere per wire](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind=`kind`, qubit=0, theme="dark"))*. diff --git a/ext/quantum/量子/可视化/索引.mq.md b/ext/quantum/量子/可视化/索引.mq.md index 584cb0b..3d78f87 100644 --- a/ext/quantum/量子/可视化/索引.mq.md +++ b/ext/quantum/量子/可视化/索引.mq.md @@ -55,116 +55,128 @@ record_plot 桥接。新增图类时同步本页和英文入口,别把文件 ## 画电路 -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 调用方提供的电路 | +| 主题 | text | "dark" | dark light 或 bw | +| 路径 | any | None | 可选输出路径或 None | + +| 返回 | 类型 | 说明 | |------|------|------| -| 电路 | any | 电路 | -| 路径 | any | 可选输出路径或 None | -| 主题 | text | dark light 或 bw | +| result | any | 绘图结果 | + +这里使用`电路`、`主题`="dark"、`路径`=None。 把 `电路` 的门和屏障画成轨线。默认 `主题`="dark",也可选择 light 或 bw。 可选 `路径`=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 主题选择只改变配色,不改变线路几何与计算含义。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[把 电路 的门和屏障画成轨线。默认 主题="dark",也可选择 light 或 bw。 可选 路径=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 主题选择只改变配色,不改变线路几何与计算含义。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="circuit", qubit=0, theme=`主题`))*。 + +## 画概率 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 调用方提供的电路 | +| 主题 | text | "dark" | dark light 或 bw | +| 路径 | any | None | 可选路径或 None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | -> 能力.加载 -*> quantum_draw_circuit circuit=`电路` path=`路径` kind="circuit" qubit=0 theme=`主题`* - -## 画概率 - -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路 | -| 路径 | any | 可选路径或 None | -| 主题 | text | dark light 或 bw | +这里使用`电路`、`主题`="dark"、`路径`=None。 绘制 `电路` 的理想基矢概率条。默认 `主题`="dark",可改为 light 或 bw。 可选 `路径`=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, 忽略已附加的教学噪声,不能用它替代含噪采样结果。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[绘制 电路 的理想基矢概率条。默认 主题="dark",可改为 light 或 bw。 可选 路径=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, 忽略已附加的教学噪声,不能用它替代含噪采样结果。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="probs", qubit=0, theme=`主题`))*。 + +## 画布洛赫 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 调用方提供的电路 | +| 比特 | number | 0 | 哪一根线 | +| 主题 | text | "dark" | dark light 或 bw | +| 路径 | any | None | 可选路径或 None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | -> 能力.加载 -*> quantum_draw_circuit circuit=`电路` path=`路径` kind="probs" qubit=0 theme=`主题`* - -## 画布洛赫 - -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路 | -| 路径 | any | 可选路径或 None | -| 比特 | number | 哪一根线 | -| 主题 | text | dark light 或 bw | +这里使用`电路`、`比特`=0、`主题`="dark"、`路径`=None。 绘制 `电路` 上 `比特`=0 的约化布洛赫球。默认 `主题`="dark"。 可选 `路径`=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, 不能把这张图解释为整个多比特纯态的完整表示。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[绘制 电路 上 比特=0 的约化布洛赫球。默认 主题="dark"。 可选 路径=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, 不能把这张图解释为整个多比特纯态的完整表示。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="bloch", qubit=`比特`, theme=`主题`))*。 + +## 画密度 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | 密度算符 | +| 种类 | text | "hinton" | hinton city density 或 paulivec | +| 路径 | any | None | 可选路径或 None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | -> 能力.加载 -*> quantum_draw_circuit circuit=`电路` path=`路径` kind="bloch" qubit=`比特` theme=`主题`* - -## 画密度 - -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | 密度算符 | -| 路径 | any | 可选路径或 None | -| 种类 | text | hinton city density 或 paulivec | +这里使用`密度`、`种类`="hinton"、`路径`=None。 绘制 `密度`,默认 `种类`="hinton",也可选 city、density 或 paulivec。 可选 `路径`=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, 再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[绘制 密度,默认 种类="hinton",也可选 city、density 或 paulivec。 可选 路径=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, 再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。](quantum_density_draw(density=`密度`, path=`路径`, kind=`种类`))*。 + +## 画门 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 门 | any | 必填 | 门句柄 | +| 种类 | text | "gate" | gate 或 matrix | +| 路径 | any | None | 可选路径或 None | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | -> 能力.加载 -*> quantum_density_draw density=`密度` path=`路径` kind=`种类`* - -## 画门 - -| 参数 | 类型 | 说明 | -|------|------|------| -| 门 | any | 门句柄 | -| 路径 | any | 可选路径或 None | -| 种类 | text | gate 或 matrix | +这里使用`门`、`种类`="gate"、`路径`=None。 绘制 `门`,默认 `种类`="gate",选择 matrix 可观察复数矩阵热图。 可选 `路径`=None 只返回 SVG,不写文件。图形用于观察算符, 不会把门作用到任何电路,也不会改变算符的数值条目。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 绘图结果 | - -> 能力.加载 -*> quantum_gate_draw gate=`门` path=`路径` kind=`种类`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[绘制 门,默认 种类="gate",选择 matrix 可观察复数矩阵热图。 可选 路径=None 只返回 SVG,不写文件。图形用于观察算符, 不会把门作用到任何电路,也不会改变算符的数值条目。](quantum_gate_draw(gate=`门`, path=`路径`, kind=`种类`))*。 ## 画态 -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 源电路,作理想演化 | +| 种类 | text | "qsphere" | qsphere 或 multibloch | +| 路径 | any | None | SVG 输出路径或 None | + +| 返回 | 类型 | 说明 | |------|------|------| -| 电路 | any | 源电路,作理想演化 | -| 种类 | text | qsphere 或 multibloch | -| 路径 | any | SVG 输出路径或 None | +| result | any | quantum_svg,含 kind 和 svg | + +这里使用`电路`、`种类`="qsphere"、`路径`=None。 从 `电路` 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 默认 `种类`="qsphere",可改为 multibloch;默认 `路径`=None,不显式落盘。 qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | quantum_svg,含 kind 和 svg | - -> 能力.加载 -*> quantum_draw_circuit circuit=`电路` path=`路径` kind=`种类` qubit=0 theme="dark"* +这里**[调用 加载](能力.加载())**。 +完成后返回*[从 电路 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 默认 种类="qsphere",可改为 multibloch;默认 路径=None,不显式落盘。 qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind=`种类`, qubit=0, theme="dark"))*。 diff --git a/ext/quantum/量子/密度/索引.mq.md b/ext/quantum/量子/密度/索引.mq.md index 8270a93..84590e8 100644 --- a/ext/quantum/量子/密度/索引.mq.md +++ b/ext/quantum/量子/密度/索引.mq.md @@ -37,132 +37,150 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect ## 从态 -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 态 | any | 必填 | 纯态或电路 | + +| 返回 | 类型 | 说明 | |------|------|------| -| 态 | any | 纯态或电路 | +| result | any | 密度句柄 | + +这里使用`态`。 由纯态或电路句柄 `态` 的理想态构造 rho。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 密度句柄 | - -> 能力.加载 -*> quantum_density_from_state state=`态`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[由纯态或电路句柄 态 的理想态构造 rho。](quantum_density_from_state(state=`态`))*。 ## 从矩阵 -| 参数 | 类型 | 说明 | -|------|------|------| -| 矩阵 | any | 厄米矩阵 | - -由显式厄米 `矩阵` 构造 rho。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 矩阵 | any | 必填 | 厄米矩阵 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 密度句柄 | -> 能力.加载 -*> quantum_density_from_matrix matrix=`矩阵`* +这里使用`矩阵`。 + +由显式厄米 `矩阵` 构造 rho。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[由显式厄米 矩阵 构造 rho。](quantum_density_from_matrix(matrix=`矩阵`))*。 ## 纯度 -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | 密度算符 | - -计算 `密度` 的 Tr(rho^2)。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | 密度算符 | | 返回 | 类型 | 说明 | |------|------|------| | result | number | 纯度 | -> 能力.加载 -*> quantum_density_purity density=`密度`* +这里使用`密度`。 + +计算 `密度` 的 Tr(rho^2)。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[计算 密度 的 Tr(rho^2)。](quantum_density_purity(density=`密度`))*。 ## 部分迹 -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | 联合密度 | -| 保留 | any | 保留的比特下标列表 | - -对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | 联合密度 | +| 保留 | any | 必填 | 保留的比特下标列表 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 约化密度 | -> 能力.加载 -*> quantum_density_partial_trace density=`密度` keep=`保留`* +这里使用`密度`、`保留`。 + +对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[对联合密度 密度 保留 保留 所列比特,对其余求迹。](quantum_density_partial_trace(density=`密度`, keep=`保留`))*。 ## 期望 -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | 密度算符 | -| 可观测量 | any | 泡利串或矩阵 | - -`密度` 上可观测量 `可观测量` 的期望值。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | 密度算符 | +| 可观测量 | any | 必填 | 泡利串或矩阵 | | 返回 | 类型 | 说明 | |------|------|------| | result | number | 期望值 | -> 能力.加载 -*> quantum_density_expect density=`密度` obs=`可观测量`* +这里使用`密度`、`可观测量`。 + +将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。 + +`密度` 上可观测量 `可观测量` 的期望值。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。](quantum_density_expect(density=`密度`, obs=`可观测量`))*。 ## 本征 -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | 密度算符 | - -`密度` 的厄米谱。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | 密度算符 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 本征值与本征矢 | -> 能力.加载 -*> quantum_density_eig density=`密度`* +这里使用`密度`。 + +将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。 + +`密度` 的厄米谱。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。](quantum_density_eig(density=`密度`))*。 ## 矩阵 -| 参数 | 类型 | 说明 | -|------|------|------| -| 密度 | any | Density handle / 密度句柄 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密度 | any | 必填 | Density handle / 密度句柄 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 复数矩阵条目,每项含 re 与 im | +这里使用`密度`。 + 导出 `密度` 的显式复数嵌套矩阵。观察条目不会改变密度算符, 可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。 -> 能力.加载 -*> quantum_density_matrix density=`密度`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[导出 密度 的显式复数嵌套矩阵。观察条目不会改变密度算符, 可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。](quantum_density_matrix(density=`密度`))*。 # 密度 -| 参数 | 类型 | 说明 | -|------|------|------| -| 态 | any | 默认 None | -| 矩阵 | any | 默认 None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 态 | any | None | 默认 None | +| 矩阵 | any | None | 默认 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 返回结果 | -输入:`态`=None, `矩阵`=None。 +这里使用`态`=None、`矩阵`=None。 由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。 -> 能力.加载 +这里**[调用 加载](能力.加载())**。 1. `矩阵` - *> quantum_density_from_matrix matrix=`矩阵`* + 完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_matrix(matrix=`矩阵`))*。 2. * - *> quantum_density_from_state state=`态`* + 完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_state(state=`态`))*。 ## 矩阵 @@ -172,7 +190,7 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect 返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。 -*> quantum_density_matrix density=`self`* +完成后返回*[返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。](quantum_density_matrix(density=`self`))*。 ## 纯度 @@ -182,23 +200,23 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect 计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。 -*> quantum_density_purity density=`self`* +完成后返回*[计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。](quantum_density_purity(density=`self`))*。 ## 部分迹 -| 参数 | 类型 | 说明 | -|------|------|------| -| 保留 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 保留 | any | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 密度算符句柄 | -输入:`保留`。 +这里使用`保留`。 保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。 -*> quantum_density_partial_trace density=`self` keep=`保留`* +完成后返回*[保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。](quantum_density_partial_trace(density=`self`, keep=`保留`))*。 ## 本征 @@ -208,37 +226,37 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect 计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。 -*> quantum_density_eig density=`self`* +完成后返回*[计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。](quantum_density_eig(density=`self`))*。 ## 期望 -| 参数 | 类型 | 说明 | -|------|------|------| -| 可观测量 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 可观测量 | any | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | number | 标量观察值 | -输入:`可观测量`。 +这里使用`可观测量`。 可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。 -*> quantum_density_expect density=`self` obs=`可观测量`* +完成后返回*[可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。](quantum_density_expect(density=`self`, obs=`可观测量`))*。 ## 绘图 -| 参数 | 类型 | 说明 | -|------|------|------| -| 路径 | any | 默认 None | -| 种类 | any | 默认 hinton | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 默认 None | +| 种类 | any | "hinton" | 默认 hinton | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg,含 kind 与 svg | -输入:`路径`=None, `种类`="hinton"。 +这里使用`路径`=None、`种类`="hinton"。 绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。 -*> quantum_density_draw density=`self` path=`路径` kind=`种类`* +完成后返回*[绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。](quantum_density_draw(density=`self`, path=`路径`, kind=`种类`))*。 diff --git a/ext/quantum/量子/态/索引.mq.md b/ext/quantum/量子/态/索引.mq.md index 4c0ae39..7b530c7 100644 --- a/ext/quantum/量子/态/索引.mq.md +++ b/ext/quantum/量子/态/索引.mq.md @@ -40,49 +40,55 @@ entropy 单位为自然对数 nats,贝尔态为 ln(2),两个系数各约 1/ ## 张量积 -| 参数 | 类型 | 说明 | -|------|------|------| -| a | any | 左因子 | -| b | any | 右因子 | - -将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 左因子 | +| b | any | 必填 | 右因子 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 张量积结果 | -> 能力.加载 -*> quantum_kron a=`a` b=`b`* +这里使用`a`、`b`。 + +将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[将 a 与 b 做张量积,得到更大空间上的态或算符。](quantum_kron(a=`a`, b=`b`))*。 ## 保真度 -| 参数 | 类型 | 说明 | -|------|------|------| -| a | any | 第一态或电路 | -| b | any | 第二态或电路 | - -纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 -教学噪声忽略。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一态或电路 | +| b | any | 必填 | 第二态或电路 | | 返回 | 类型 | 说明 | |------|------|------| | result | number | 保真度 | -> 能力.加载 -*> quantum_fidelity a=`a` b=`b`* +这里使用`a`、`b`。 + +纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 +教学噪声忽略。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[纯态 a 与 b 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 教学噪声忽略。](quantum_fidelity(a=`a`, b=`b`))*。 ## 施密特分解 -| 参数 | 类型 | 说明 | -|------|------|------| -| 态 | any | 纯态或电路 | -| 分割 | number | 子系统 A 比特数 | - -对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 态 | any | 必填 | 纯态或电路 | +| 分割 | number | 1 | 子系统 A 比特数 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 施密特数据 | -> 能力.加载 -*> quantum_schmidt state=`态` cut=`分割`* +这里使用`态`、`分割`=1。 + +对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[对纯态或电路 态 做施密特分解。分割=1 表示子系统 A 的比特数(低位)。](quantum_schmidt(state=`态`, cut=`分割`))*。 diff --git a/ext/quantum/量子/模拟/索引.mq.md b/ext/quantum/量子/模拟/索引.mq.md index c2db2d0..589ca17 100644 --- a/ext/quantum/量子/模拟/索引.mq.md +++ b/ext/quantum/量子/模拟/索引.mq.md @@ -46,79 +46,91 @@ plugins/quantum/src/sim.rs,导出位于同目录 src/lib.rs。保持中英理 ## 模拟 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 待演化电路 | - -返回 `电路` 的理想态矢量振幅。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 待演化电路 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 振幅列表 | -> 能力.加载 -*> quantum_simulate circuit=`电路`* +这里使用`电路`。 + +返回 `电路` 的理想态矢量振幅。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[返回 电路 的理想态矢量振幅。](quantum_simulate(circuit=`电路`))*。 ## 态 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 待演化电路 | - -与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 待演化电路 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 理想态 | -> 能力.加载 -*> quantum_state circuit=`电路`* +这里使用`电路`。 + +与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[与模拟相同:取 电路 的理想振幅,打包为态对象,便于后续保真度或密度构造。](quantum_state(circuit=`电路`))*。 ## 概率 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 待读取电路 | - -`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 待读取电路 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 概率映射 | -> 能力.加载 -*> quantum_probabilities circuit=`电路`* +这里使用`电路`。 + +将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。 + +`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。](quantum_probabilities(circuit=`电路`))*。 ## 运行 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 待采样电路 | -| 次数 | number | 采样次数 | -| 种子 | number | 随机种子 | - -对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 待采样电路 | +| 次数 | number | 1024 | 采样次数 | +| 种子 | number | 1 | 随机种子 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 计数或采样结果 | -> 能力.加载 -*> quantum_run circuit=`电路` shots=`次数` seed=`种子`* +这里使用`电路`、`次数`=1024、`种子`=1。 + +对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[对 电路 采样。默认 次数=1024、种子=1。若有教学噪声则轨迹含噪声。](quantum_run(circuit=`电路`, shots=`次数`, seed=`种子`))*。 ## 噪声 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路 | -| 种类 | text | 噪声族名 | -| 强度 | number | 单位区间强度 | - -在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 调用方提供的电路 | +| 种类 | text | 必填 | 噪声族名 | +| 强度 | number | 必填 | 单位区间强度 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带噪声元数据的电路 | -> 能力.加载 -*> quantum_noise circuit=`电路` kind=`种类` p=`强度`* +这里使用`电路`、`种类`、`强度`。 + +在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[在 电路 上附着种类 种类、强度 强度 的教学噪声。理想概率工具忽略它。](quantum_noise(circuit=`电路`, kind=`种类`, p=`强度`))*。 diff --git a/ext/quantum/量子/电路/索引.mq.md b/ext/quantum/量子/电路/索引.mq.md index b3efdce..6fe7e02 100644 --- a/ext/quantum/量子/电路/索引.mq.md +++ b/ext/quantum/量子/电路/索引.mq.md @@ -50,581 +50,591 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects ## 新建 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特数 | number | 线宽 | -| 步骤 | any | 可选门表或 None | - -创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特数 | number | 1 | 线宽 | +| 步骤 | any | None | 可选门表或 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新电路句柄 | -> 能力.加载 -*> quantum_circuit_new qubits=`比特数` steps=`步骤`* +这里使用`比特数`=1、`步骤`=None。 + +创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[创建宽度为 比特数=1 的态矢量电路。可选 步骤=None 表示不预载门表。](quantum_circuit_new(qubits=`比特数`, steps=`步骤`))*。 ## 哈达玛 -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 电路句柄 | +| 比特 | number | 0 | 目标线 | + +| 返回 | 类型 | 说明 | |------|------|------| -| 电路 | any | 电路句柄 | -| 比特 | number | 目标线 | +| result | any | 更新后的电路 | + +这里使用`电路`、`比特`=0。 对已有 `电路` 的 `比特`=0 施加哈达玛。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 更新后的电路 | - -> 能力.加载 -*> quantum_h circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对已有 电路 的 比特=0 施加哈达玛。](quantum_h(circuit=`电路`, qubit=`比特`))*。 ## 控非 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路句柄 | -| 控制 | number | 控制位 | -| 目标 | number | 目标位 | - -对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 电路句柄 | +| 控制 | number | 0 | 控制位 | +| 目标 | number | 1 | 目标位 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -> 能力.加载 -*> quantum_cx circuit=`电路` control=`控制` target=`目标`* +这里使用`电路`、`控制`=0、`目标`=1。 + +对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[对 电路 从 控制=0 到 目标=1 施加控非。](quantum_cx(circuit=`电路`, control=`控制`, target=`目标`))*。 ## 屏障 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路句柄 | - -在 `电路` 上记录可视化屏障(不改态)。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 电路句柄 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带屏障的电路 | -> 能力.加载 -*> quantum_barrier circuit=`电路`* +这里使用`电路`。 + +在 `电路` 上记录可视化屏障(不改态)。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[在 电路 上记录可视化屏障(不改态)。](quantum_barrier(circuit=`电路`))*。 ## 测量标记 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 电路句柄 | -| 比特 | any | 线列表或 None | - -为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 电路 | any | 必填 | 电路句柄 | +| 比特 | any | None | 线列表或 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带测量标记的电路 | -> 能力.加载 -*> quantum_measure circuit=`电路` qubits=`比特`* +这里使用`电路`、`比特`=None。 + +为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[为后续运行在 电路 上标记计算基读出。比特=None 表示全部线。不坍缩理想态。](quantum_measure(circuit=`电路`, qubits=`比特`))*。 ## 泡利X -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_x circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_x(circuit=`电路`, qubit=`比特`))*。 ## 泡利Y -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_y circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_y(circuit=`电路`, qubit=`比特`))*。 ## 泡利Z -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_z circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_z(circuit=`电路`, qubit=`比特`))*。 ## 相位S -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_s circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_s(circuit=`电路`, qubit=`比特`))*。 ## 相位T -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_t circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_t(circuit=`电路`, qubit=`比特`))*。 ## 单位 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0。 +这里使用`比特`=0、`电路`。 对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_i circuit=`电路` qubit=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_i(circuit=`电路`, qubit=`比特`))*。 ## 绕X -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`、`电路`。 绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_rx circuit=`电路` qubit=`比特` theta=`参数`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_rx(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 ## 绕Y -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`、`电路`。 绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_ry circuit=`电路` qubit=`比特` theta=`参数`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_ry(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 ## 绕Z -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`、`电路`。 绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_rz circuit=`电路` qubit=`比特` theta=`参数`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_rz(circuit=`电路`, qubit=`比特`, theta=`参数`))*。 ## 控相 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 控制 | number | 默认 0 | -| 目标 | number | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 控制 | number | 0 | 默认 0 | +| 目标 | number | 1 | 默认 1 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`控制`=0, `目标`=1。 +这里使用`控制`=0、`目标`=1、`电路`。 在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_cz circuit=`电路` control=`控制` target=`目标`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_cz(circuit=`电路`, control=`控制`, target=`目标`))*。 ## 交换 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 比特甲 | any | 默认 0 | -| 比特乙 | any | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特甲 | any | 0 | 默认 0 | +| 比特乙 | any | 1 | 默认 1 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`比特甲`=0, `比特乙`=1。 +这里使用`比特甲`=0、`比特乙`=1、`电路`。 交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_swap circuit=`电路` a=`比特甲` b=`比特乙`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_swap(circuit=`电路`, a=`比特甲`, b=`比特乙`))*。 ## 追加 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 操作 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 操作 | any | 必填 | 必填 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`操作`。 +这里使用`操作`、`电路`。 把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_append circuit=`电路` op=`操作`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[将本项追加到新列表](quantum_append(circuit=`电路`, op=`操作`))*。 ## 施加 -| 参数 | 类型 | 说明 | -|------|------|------| -| 电路 | any | 已有电路;返回新值 | -| 门 | any | 必填 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 门 | any | 必填 | 必填 | +| 比特 | any | 0 | 默认 0 | +| 电路 | any | 必填 | 已有电路;返回新值 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | -输入:`门`, `比特`=0。 +这里使用`门`、`比特`=0、`电路`。 把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 -> 能力.加载 -*> quantum_apply circuit=`电路` gate=`门` qubits=`比特`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 电路输入为 电路,返回新值;使用同一会话的 --toget qc 接住它。](quantum_apply(circuit=`电路`, gate=`门`, qubits=`比特`))*。 # 电路 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特数 | number | 默认 1 | -| 步骤 | any | 默认 None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特数 | number | 1 | 默认 1 | +| 步骤 | any | None | 默认 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特数`=1, `步骤`=None。 +这里使用`比特数`=1、`步骤`=None。 状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。 -> 能力.加载 -*> quantum_circuit_new qubits=`比特数` steps=`步骤`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。](quantum_circuit_new(qubits=`比特数`, steps=`步骤`))*。 ## 哈达玛 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。 -*> quantum_h circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。](quantum_h(circuit=`self`, qubit=`比特`))*。 ## 泡利X -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 -*> quantum_x circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。](quantum_x(circuit=`self`, qubit=`比特`))*。 ## 泡利Y -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 -*> quantum_y circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。](quantum_y(circuit=`self`, qubit=`比特`))*。 ## 泡利Z -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 -*> quantum_z circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。](quantum_z(circuit=`self`, qubit=`比特`))*。 ## 相位S -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 -*> quantum_s circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。](quantum_s(circuit=`self`, qubit=`比特`))*。 ## 相位T -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 -*> quantum_t circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。](quantum_t(circuit=`self`, qubit=`比特`))*。 ## 单位 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0。 +这里使用`比特`=0。 对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 -*> quantum_i circuit=`self` qubit=`比特`* +完成后返回*[对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。](quantum_i(circuit=`self`, qubit=`比特`))*。 ## 绕X -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`。 绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -*> quantum_rx circuit=`self` qubit=`比特` theta=`参数`* +完成后返回*[绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_rx(circuit=`self`, qubit=`比特`, theta=`参数`))*。 ## 绕Y -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`。 绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -*> quantum_ry circuit=`self` qubit=`比特` theta=`参数`* +完成后返回*[绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_ry(circuit=`self`, qubit=`比特`, theta=`参数`))*。 ## 绕Z -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 0 | -| 参数 | number | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | 0 | 默认 0 | +| 参数 | number | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=0, `参数`。 +这里使用`比特`=0、`参数`。 绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -*> quantum_rz circuit=`self` qubit=`比特` theta=`参数`* +完成后返回*[绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。](quantum_rz(circuit=`self`, qubit=`比特`, theta=`参数`))*。 ## 控非 -| 参数 | 类型 | 说明 | -|------|------|------| -| 控制 | number | 默认 0 | -| 目标 | number | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 控制 | number | 0 | 默认 0 | +| 目标 | number | 1 | 默认 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`控制`=0, `目标`=1。 +这里使用`控制`=0、`目标`=1。 从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。 -*> quantum_cx circuit=`self` control=`控制` target=`目标`* +完成后返回*[从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。](quantum_cx(circuit=`self`, control=`控制`, target=`目标`))*。 ## 控相 -| 参数 | 类型 | 说明 | -|------|------|------| -| 控制 | number | 默认 0 | -| 目标 | number | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 控制 | number | 0 | 默认 0 | +| 目标 | number | 1 | 默认 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`控制`=0, `目标`=1。 +这里使用`控制`=0、`目标`=1。 在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 -*> quantum_cz circuit=`self` control=`控制` target=`目标`* +完成后返回*[在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。](quantum_cz(circuit=`self`, control=`控制`, target=`目标`))*。 ## 交换 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特甲 | any | 默认 0 | -| 比特乙 | any | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特甲 | any | 0 | 默认 0 | +| 比特乙 | any | 1 | 默认 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特甲`=0, `比特乙`=1。 +这里使用`比特甲`=0、`比特乙`=1。 交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 -*> quantum_swap circuit=`self` a=`比特甲` b=`比特乙`* +完成后返回*[交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。](quantum_swap(circuit=`self`, a=`比特甲`, b=`比特乙`))*。 ## 屏障 @@ -634,73 +644,73 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。 -*> quantum_barrier circuit=`self`* +完成后返回*[仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。](quantum_barrier(circuit=`self`))*。 ## 测量 -| 参数 | 类型 | 说明 | -|------|------|------| -| 比特 | any | 默认 None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 比特 | any | None | 默认 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`比特`=None。 +这里使用`比特`=None。 为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。 -*> quantum_measure circuit=`self` qubits=`比特`* +完成后返回*[为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。](quantum_measure(circuit=`self`, qubits=`比特`))*。 ## 追加 -| 参数 | 类型 | 说明 | -|------|------|------| -| 操作 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 操作 | any | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`操作`。 +这里使用`操作`。 把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 -*> quantum_append circuit=`self` op=`操作`* +完成后返回*[将本项追加到新列表](quantum_append(circuit=`self`, op=`操作`))*。 ## 施加 -| 参数 | 类型 | 说明 | -|------|------|------| -| 门 | any | 必填 | -| 比特 | any | 默认 0 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 门 | any | 必填 | 必填 | +| 比特 | any | 0 | 默认 0 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`门`, `比特`=0。 +这里使用`门`、`比特`=0。 把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 -*> quantum_apply circuit=`self` gate=`门` qubits=`比特`* +完成后返回*[把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。](quantum_apply(circuit=`self`, gate=`门`, qubits=`比特`))*。 ## 噪声 -| 参数 | 类型 | 说明 | -|------|------|------| -| 种类 | any | 必填 | -| 概率 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 种类 | any | 必填 | 必填 | +| 概率 | any | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新的电路值,接住返回值以继续 | -输入:`种类`, `概率`。 +这里使用`种类`、`概率`。 附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。 -*> quantum_noise circuit=`self` kind=`种类` p=`概率`* +完成后返回*[附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。](quantum_noise(circuit=`self`, kind=`种类`, p=`概率`))*。 ## 模拟 @@ -710,7 +720,7 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。 -*> quantum_simulate circuit=`self`* +完成后返回*[返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。](quantum_simulate(circuit=`self`))*。 ## 态 @@ -720,7 +730,7 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。 -*> quantum_state circuit=`self`* +完成后返回*[返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。](quantum_state(circuit=`self`))*。 ## 概率 @@ -730,43 +740,43 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。 -*> quantum_probabilities circuit=`self`* +完成后返回*[基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。](quantum_probabilities(circuit=`self`))*。 ## 运行 -| 参数 | 类型 | 说明 | -|------|------|------| -| 次数 | number | 默认 1024 | -| 种子 | number | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 次数 | number | 1024 | 默认 1024 | +| 种子 | number | 1 | 默认 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 采样信息与 counts | -输入:`次数`=1024, `种子`=1。 +这里使用`次数`=1024、`种子`=1。 对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。 -*> quantum_run circuit=`self` shots=`次数` seed=`种子`* +完成后返回*[对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。](quantum_run(circuit=`self`, shots=`次数`, seed=`种子`))*。 ## 绘图 -| 参数 | 类型 | 说明 | -|------|------|------| -| 路径 | any | 默认 None | -| 种类 | any | 默认 circuit | -| 比特 | any | 默认 0 | -| 主题 | any | 默认 dark | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 默认 None | +| 种类 | any | "circuit" | 默认 circuit | +| 比特 | any | 0 | 默认 0 | +| 主题 | any | "dark" | 默认 dark | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg,含 kind 与 svg | -输入:`路径`=None, `种类`="circuit", `比特`=0, `主题`="dark"。 +这里使用`路径`=None、`种类`="circuit"、`比特`=0、`主题`="dark"。 绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。 -*> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特` theme=`主题`* +完成后返回*[绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。](quantum_draw_circuit(circuit=`self`, path=`路径`, kind=`种类`, qubit=`比特`, theme=`主题`))*。 ## 密度 @@ -776,36 +786,36 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。 -*> quantum_density_from_state state=`self`* +完成后返回*[对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。](quantum_density_from_state(state=`self`))*。 ## 期望 -| 参数 | 类型 | 说明 | -|------|------|------| -| 可观测量 | any | 必填 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 可观测量 | any | 必填 | 必填 | | 返回 | 类型 | 说明 | |------|------|------| | result | number | 标量观察值 | -输入:`可观测量`。 +这里使用`可观测量`。 在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。 -*> quantum_density_expect density=`self` obs=`可观测量`* +完成后返回*[在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。](quantum_density_expect(density=`self`, obs=`可观测量`))*。 ## 施密特 -| 参数 | 类型 | 说明 | -|------|------|------| -| 分割 | number | 默认 1 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 分割 | number | 1 | 默认 1 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 系数、两侧基与熵 | -输入:`分割`=1。 +这里使用`分割`=1。 对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。 -*> quantum_schmidt state=`self` cut=`分割`* +完成后返回*[对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。](quantum_schmidt(state=`self`, cut=`分割`))*。 diff --git a/ext/quantum/量子/索引.mq.md b/ext/quantum/量子/索引.mq.md index 8746ac0..77eabe2 100644 --- a/ext/quantum/量子/索引.mq.md +++ b/ext/quantum/量子/索引.mq.md @@ -179,12 +179,12 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高 工具返回线路而非概率,便于继续施门、设置噪声或独立验证纠缠。 每一步接住新电路值,原值不被隐式修改。 -**qc = 电路.新建 比特数=2 步骤=None** +得到**`qc` = [调用 新建](电路.新建(比特数=2, 步骤=None))**。 先让最低位具有两条等权路径,再把路径信息传播给第二条线。 -**qc = 电路.哈达玛 电路=`qc` 比特=0** -*> 电路.控非 电路=`qc` 控制=0 目标=1* +得到**`qc` = [调用 哈达玛](电路.哈达玛(电路=`qc`, 比特=0))**。 +完成后返回*[调用 控非](电路.控非(电路=`qc`, 控制=0, 目标=1))*。 ## 贝尔态 @@ -196,8 +196,8 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高 00 和 11 各约一半,其余基矢为零;这是计算基关联,单靠概率还不能证明纠缠, 因此需要纠缠证据时继续调用本页纠缠分析,对照约化纯度与 ZZ 期望。 -**qc = > 贝尔电路** -*> 模拟.概率 电路=`qc`* +得到**`qc` = [调用 贝尔电路](贝尔电路())**。 +完成后返回*[调用 概率](模拟.概率(电路=`qc`))*。 ## 纠缠分析 @@ -211,29 +211,32 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高 整体纯度应为 1,约化纯度应为 0.5,ZZ 应为 1,施密特熵为 ln(2)。 所有数值按 1e-9 容差核对;纯态概率与密度构造均使用理想演化。 -**qc = > 贝尔电路** -**probs = 模拟.概率 电路=`qc`** +这里分析的是同一次制备的状态,避免分别重建电路导致比较对象不同。 + +得到**`qc` = [调用 贝尔电路](贝尔电路())**。 +得到**`probs` = [调用 概率](模拟.概率(电路=`qc`))**。 先构造整体密度并计算纯度。整体纯不意味着每个局部也纯, 接着只保留最低位,检查丢弃另一个比特后出现的混合性。 -**rho = 密度.从态 态=`qc`** -**whole = 密度.纯度 密度=`rho`** +得到**`rho` = [调用 从态](密度.从态(态=`qc`))**。 +得到**`whole` = [调用 纯度](密度.纯度(密度=`rho`))**。 + `kept` = | 比特 | |------| | 0 | -**reduced = 密度.部分迹 密度=`rho` 保留=`kept`** -**local = 密度.纯度 密度=`reduced`** +得到**`reduced` = [调用 部分迹](密度.部分迹(密度=`rho`, 保留=`kept`))**。 +得到**`local` = [调用 纯度](密度.纯度(密度=`reduced`))**。 ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯态两侧的 系数与熵;联合这些观察才能解释为何这是贝尔纯态而非经典概率混合。 返回表将各观察保留原值,便于调用者自行检查,而不是输出一个隐藏阈值的通过标签。 -**correlation = 密度.期望 密度=`rho` 可观测量="ZZ"** -**split = 态.施密特分解 态=`qc` 分割=1** +得到**`correlation` = [调用 期望](密度.期望(密度=`rho`, 可观测量="ZZ"))**。 +得到**`split` = [调用 施密特分解](态.施密特分解(态=`qc`, 分割=1))**。 `report` = @@ -241,4 +244,4 @@ ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯 |---------------|--------|----------------|----|---------| | `probs` | `whole` | `local` | `correlation` | `split` | -*report* +完成后返回*report*。 diff --git a/ext/quantum/量子/能力/索引.mq.md b/ext/quantum/量子/能力/索引.mq.md index bffcb13..916383a 100644 --- a/ext/quantum/量子/能力/索引.mq.md +++ b/ext/quantum/量子/能力/索引.mq.md @@ -26,20 +26,20 @@ marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --jso ## 加载 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 加载成功后为空 | + 通过 plugin.native_path 找到 ABI v2 quantum 共享库,再 plugin.load。若缺失则打印 安装提示并以非零退出。成功后本进程内可用 quantum_* 符号。本包中只有这里应直接 接触 lib/plugin。领域模块在需要模拟器的工具开头调用加载。 本工具无参数。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 加载成功后为空 | - -**p = > plugin.native_path name="quantum"** +得到**`p` = [定位已安装的原生插件](plugin.native_path(name="quantum"))**。 1. `p` - > plugin.load path=`p` + 这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。 2. * - > print text=ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum) - > sys.exit code=1 -**** + 这里**[输出本步已准备的消息](print(text="ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum)"))**。 + 这里**[按指定退出码结束本次运行](sys.exit(code=1))**。 +完成后返回*None*。 diff --git a/ext/quantum/量子/门/索引.mq.md b/ext/quantum/量子/门/索引.mq.md index 9984115..0876a23 100644 --- a/ext/quantum/量子/门/索引.mq.md +++ b/ext/quantum/量子/门/索引.mq.md @@ -38,140 +38,148 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects ## 哈达玛 -哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 - -本工具无参数。 - | 返回 | 类型 | 说明 | |------|------|------| | result | any | 哈达玛门句柄 | -> 能力.加载 -*> quantum_gate_new name="H" theta=None matrix=None* - -## 泡利X - -泡利 X 是比特翻转门。 +哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 本工具无参数。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 本工具无参数。](quantum_gate_new(name="H", theta=None, matrix=None))*。 + +## 泡利X + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 泡利 X 句柄 | -> 能力.加载 -*> quantum_gate_new name="X" theta=None matrix=None* - -## 泡利Z - -泡利 Z 给 ket-one 乘上负号相位。 +泡利 X 是比特翻转门。 本工具无参数。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[泡利 X 是比特翻转门。 本工具无参数。](quantum_gate_new(name="X", theta=None, matrix=None))*。 + +## 泡利Z + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 泡利 Z 句柄 | -> 能力.加载 -*> quantum_gate_new name="Z" theta=None matrix=None* - -## 控非门 - -两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 +泡利 Z 给 ket-one 乘上负号相位。 本工具无参数。 +这里**[调用 加载](能力.加载())**。 +完成后返回*[泡利 Z 给 ket-one 乘上负号相位。 本工具无参数。](quantum_gate_new(name="Z", theta=None, matrix=None))*。 + +## 控非门 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | CNOT 门句柄 | -> 能力.加载 -*> quantum_gate_new name="CX" theta=None matrix=None* +两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 + +本工具无参数。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 本工具无参数。](quantum_gate_new(name="CX", theta=None, matrix=None))*。 ## 自定义 -| 参数 | 类型 | 说明 | -|------|------|------| -| 矩阵 | any | 酉矩阵公式或列表 | -| 名 | text | 可选标签,默认 U | - -用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 矩阵 | any | 必填 | 酉矩阵公式或列表 | +| 名 | text | "U" | 可选标签,默认 U | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 自定义门句柄 | -> 能力.加载 -*> quantum_gate_new name=`名` theta=None matrix=`矩阵`* +这里使用`矩阵`、`名`="U"。 + +用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[用显式酉矩阵 矩阵 构造门。可选标签 名="U"。](quantum_gate_new(name=`名`, theta=None, matrix=`矩阵`))*。 ## 匹配 -| 参数 | 类型 | 说明 | -|------|------|------| -| 门 | any | 门句柄 | -| 矩阵 | any | 期望酉矩阵 | -| 容差 | number | 绝对容差 | - -检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 门 | any | 必填 | 门句柄 | +| 容差 | number | 0.000000001 | 绝对容差 | +| 矩阵 | any | 必填 | 期望酉矩阵 | | 返回 | 类型 | 说明 | |------|------|------| | result | bool | 匹配则为 True | -> 能力.加载 -*> quantum_gate_matches_matrix gate=`门` matrix=`矩阵` tol=`容差`* +这里使用`门`、`容差`=0.000000001、`矩阵`。 + +检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 + +这里**[调用 加载](能力.加载())**。 +完成后返回*[检查 门 是否在容差 容差=0.000000001 内匹配 矩阵。](quantum_gate_matches_matrix(gate=`门`, matrix=`矩阵`, tol=`容差`))*。 ## 具名 -| 参数 | 类型 | 说明 | -|------|------|------| -| 名 | text | 内置门名 | -| 参数 | any | 旋转角或 None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | text | "H" | 内置门名 | +| 参数 | any | None | 旋转角或 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 可交给施加工具的门句柄 | +这里使用`名`="H"、`参数`=None。 + 构造内置门 `名`="H";可选 `参数`=None,Rx、Ry、Rz 必须给出弧度角。 返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。 -> 能力.加载 -*> quantum_gate_new name=`名` theta=`参数` matrix=None* +这里**[调用 加载](能力.加载())**。 +完成后返回*[构造内置门 名="H";可选 参数=None,Rx、Ry、Rz 必须给出弧度角。 返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。](quantum_gate_new(name=`名`, theta=`参数`, matrix=None))*。 ## 矩阵 -| 参数 | 类型 | 说明 | -|------|------|------| -| 门 | any | 门句柄 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 门 | any | 必填 | 门句柄 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 复数矩阵条目,每项含 re 与 im | +这里使用`门`。 + 导出 `门` 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; 本工具仅观察算符,不改变句柄,也不把门应用到任何电路。 -> 能力.加载 -*> quantum_gate_matrix gate=`门`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[导出 门 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; 本工具仅观察算符,不改变句柄,也不把门应用到任何电路。](quantum_gate_matrix(gate=`门`))*。 # 门 -| 参数 | 类型 | 说明 | -|------|------|------| -| 名 | any | 默认 None | -| 参数 | number | 默认 None | -| 矩阵 | any | 默认 None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | None | 默认 None | +| 参数 | number | None | 默认 None | +| 矩阵 | any | None | 默认 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 可交给施加工具的门句柄 | -输入:`名`=None, `参数`=None, `矩阵`=None。 +这里使用`名`=None、`参数`=None、`矩阵`=None。 具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。 -> 能力.加载 -*> quantum_gate_new name=`名` theta=`参数` matrix=`矩阵`* +这里**[调用 加载](能力.加载())**。 +完成后返回*[具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。](quantum_gate_new(name=`名`, theta=`参数`, matrix=`矩阵`))*。 ## 矩阵 @@ -181,38 +189,38 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects 返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。 -*> quantum_gate_matrix gate=`self`* +完成后返回*[返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。](quantum_gate_matrix(gate=`self`))*。 ## 匹配矩阵 -| 参数 | 类型 | 说明 | -|------|------|------| -| 矩阵 | any | 必填 | -| 容差 | any | 默认 0.000000001 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 矩阵 | any | 必填 | 必填 | +| 容差 | any | 0.000000001 | 默认 0.000000001 | | 返回 | 类型 | 说明 | |------|------|------| | result | bool | 容差内匹配 | -输入:`矩阵`, `容差`=0.000000001。 +这里使用`矩阵`、`容差`=0.000000001。 检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。 -*> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`* +完成后返回*[检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。](quantum_gate_matches_matrix(gate=`self`, matrix=`矩阵`, tol=`容差`))*。 ## 绘图 -| 参数 | 类型 | 说明 | -|------|------|------| -| 路径 | any | 默认 None | -| 种类 | any | 默认 gate | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 默认 None | +| 种类 | any | "gate" | 默认 gate | | 返回 | 类型 | 说明 | |------|------|------| | result | any | quantum_svg,含 kind 与 svg | -输入:`路径`=None, `种类`="gate"。 +这里使用`路径`=None、`种类`="gate"。 绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。 -*> quantum_gate_draw gate=`self` path=`路径` kind=`种类`* +完成后返回*[绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。](quantum_gate_draw(gate=`self`, path=`路径`, kind=`种类`))*。 diff --git a/ext/security/auth.mq.md b/ext/security/auth.mq.md index 1d4d200..19b0025 100644 --- a/ext/security/auth.mq.md +++ b/ext/security/auth.mq.md @@ -8,53 +8,105 @@ import: table: lib/table.mq.md --- +Read [the security entry](index.mq.md) to distinguish credential/session operations, role checks and OIDC integration. This leaf owns the native authentication resource; endpoint metadata still controls route authorization. Prepare the native web plugin, keep secrets out of examples and logs, and verify both denied and accepted credentials before changing session behavior. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/security: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # auth - + `users` - + `session_ttl`=3600 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| users | any | required | Configured user store used by authentication | +| session_ttl | any | 3600 | Session lifetime in seconds | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead. | + +Use `users`, `session_ttl`=3600 as the inputs for this operation. Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead. -> _load -*> web_auth_new users=`users` session_ttl=`session_ttl`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Session/auth helper. Constructs a config object; login validates against the users table. To gate /admin on this app, use app.auth users=… instead.](web_auth_new(users=`users`, session_ttl=`session_ttl`))*. ## login - + `username` - + `password` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| username | any | required | User name in the configured user store | +| password | any | required | Credential supplied for verification or hashing; do not log it | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`. | + +Use `username`, `password` as the inputs for this operation. Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`. -**users = [users](access(self, "users"))** -**ttl = [session_ttl](access(self, "session_ttl"))** -*> web_auth_login username=`username` password=`password` users=`users` session_ttl=`ttl`* +We retain **`users` = [Read users field](access(`self`, "users"))**. +We retain **`ttl` = [Read session_ttl field](access(`self`, "session_ttl"))**. +Return *[Validate credentials against the users table and create a session. Returns {ok, session_id, username, role}.](web_auth_login(username=`username`, password=`password`, users=`users`, session_ttl=`ttl`))*. ## check - + `session_id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| session_id | any | required | Session identifier returned by login | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Returns `{ok, username, role}` when the session is valid. | + +Use `session_id` as the inputs for this operation. Returns `{ok, username, role}` when the session is valid. -*> web_auth_check session_id=`session_id`* +Return *[Returns {ok, username, role} when the session is valid.](web_auth_check(session_id=`session_id`))*. ## logout - + `session_id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| session_id | any | required | Session identifier returned by login | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Destroy the session. | + +Use `session_id` as the inputs for this operation. Destroy the session. -*> web_auth_logout session_id=`session_id`* +Return *[Destroy the session.](web_auth_logout(session_id=`session_id`))*. ## hash_password - + `password` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| password | any | required | Credential supplied for verification or hashing; do not log it | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically. | + +Use `password` as the inputs for this operation. Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically. -*> web_password_hash password=`password`* - +Return *[Hash a plaintext password for storage in admin user tables (argon2id). Store the returned hash in the password column; login verifies automatically.](web_password_hash(password=`password`))*. diff --git a/ext/security/index.mq.md b/ext/security/index.mq.md new file mode 100644 index 0000000..fa36b07 --- /dev/null +++ b/ext/security/index.mq.md @@ -0,0 +1,48 @@ +--- +markup: occlusion +title: Security resources — authentication, roles and OIDC +import: + permissions_api: ext/security/rbac.mq.md +--- + +Use [auth](auth.mq.md) for credential/session operations, [rbac](rbac.mq.md) for role permissions, +and [OIDC](oidc.mq.md) for attaching an external identity provider to an existing web app. +Endpoint authorization remains explicit in the web artifact metadata; a script permission check +does not automatically protect an HTTP route. + +The resources use the native web plugin. Build it with scripts/build-web-plugin.sh in this checkout. +This entry's deterministic permission check does not contact an identity provider or change users: + +```sh +marqdo call ext/security/index.mq.md check_permission 'held="notes:read"' 'needed="notes:read"' --effects plugin --json +``` + +Constructors create receivers that are used by resource methods. The free function below makes +that pattern available to CLI callers without copying opaque object fields. For OIDC, configure +registered callback URLs and origin restrictions in oidc.mq.md; never copy production credentials +into a source example. Transport success and authorization success are distinct fields. + +Develop native security policy in the existing web security implementation, then document the +public contract and exercise both allow and deny cases. Keep permission delimiters, wildcard +behavior, session lifetime and credential handling explicit. Use local fixtures for login and +OIDC tests; the reusable source must not require a live identity service merely to be inspected. + +## check_permission + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| held | text | required | Comma-separated permissions held by the subject; wildcard follows the native RBAC policy | +| needed | text | required | Comma-separated required permissions interpreted by the documented RBAC checker | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Native ok/allowed record; inspect allowed to decide authorization | + +The inputs `held` and `needed` describe one explicit permission decision, not a role assignment +or a request to modify the user database. The native checker currently accepts any matching +required permission; held wildcard permits all. Use the leaf API when changing a role catalog. + +The checker is an associated tool: it does not read self, so this workflow calls its definition +path directly rather than pretending it is an instance method. We return *[Evaluate this subject against the requested permission set](permissions_api.rbac.can(permissions=`held`, needed=`needed`))* . +The returned allowed field is the authorization decision; the outer CLI ok only reports whether +this function call completed. A denied decision remains a valid, observable result. diff --git a/ext/security/oidc.mq.md b/ext/security/oidc.mq.md index 8864ae3..00ba92f 100644 --- a/ext/security/oidc.mq.md +++ b/ext/security/oidc.mq.md @@ -7,28 +7,45 @@ import: sys: lib/sys.mq.md --- +OIDC attaches provider configuration to an existing web application. Read [the security entry](index.mq.md) for the ownership boundaries before configuring a live identity provider. Registered callback URLs, origin checks and credentials require real deployment configuration; constructing a record alone does not validate a login flow. Keep provider failures distinct from permission decisions and exercise callbacks with controlled fixtures. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/security: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. ## attach - + `app` - + `issuer`=None - + `client_id` - + `client_secret` - + `redirect_uri` - + `redirect_origins`=None - + `scopes`="openid profile email" - + `callback_path`=None - + `authorize_url`=None - + `token_url`=None - + `userinfo_url`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | required | Existing web application resource | +| issuer | any | None | OIDC issuer URL; None requires explicit provider endpoint configuration | +| client_id | any | required | Client identifier registered with the identity provider | +| client_secret | any | required | Client credential; supply through trusted runtime configuration | +| redirect_uri | any | required | Registered absolute callback URL or callback path | +| redirect_origins | any | None | Comma-separated callback origin allowlist when using a path callback | +| scopes | any | "openid profile email" | Space-separated identity-provider scopes | +| callback_path | any | None | Explicit callback route override or None for the implementation default | +| authorize_url | any | None | Authorization endpoint override | +| token_url | any | None | Token-exchange endpoint override | +| userinfo_url | any | None | User-info endpoint override | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | (`/oidc/callback`). Path mode resolves the absolute callback from the login request Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores it in the session so token exchange uses the same string. Optional `redirect_origins` is a comma-separated allowlist (`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. The IdP must still register every absolute callback URL that will be used. | + +Use `app`, `issuer`=None, `client_id`, `client_secret`, `redirect_uri`, `redirect_origins`=None, `scopes`="openid profile email", `callback_path`=None, `authorize_url`=None, `token_url`=None, `userinfo_url`=None as the inputs for this operation. `redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path (`/oidc/callback`). Path mode resolves the absolute callback from the login request @@ -39,5 +56,5 @@ Optional `redirect_origins` is a comma-separated allowlist (`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. The IdP must still register every absolute callback URL that will be used. -> _load -*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` redirect_origins=`redirect_origins` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`* +We **[Load the native plugin required by this operation](_load())**. +Return *[(/oidc/callback)](web_app_oidc(app=`app`, issuer=`issuer`, client_id=`client_id`, client_secret=`client_secret`, redirect_uri=`redirect_uri`, redirect_origins=`redirect_origins`, scopes=`scopes`, callback_path=`callback_path`, authorize_url=`authorize_url`, token_url=`token_url`, userinfo_url=`userinfo_url`))*. diff --git a/ext/security/rbac.mq.md b/ext/security/rbac.mq.md index 6e0a732..43fbf8e 100644 --- a/ext/security/rbac.mq.md +++ b/ext/security/rbac.mq.md @@ -8,56 +8,103 @@ import: table: lib/table.mq.md --- +Role and permission data are explicit inputs to the native web checker. The [security entry](index.mq.md) executes allow and deny cases without an identity provider. The can tool is associated with rbac rather than a receiver method because it reads only its arguments. Held wildcard and any-match needed permissions follow the native policy; do not reinterpret that as an all-permissions check. + ## _load -**p = > plugin.native_path name="web"** +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. | + +Resolve and load the native web plugin before resource operations; missing binaries stop this run. + +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/security: native web plugin not found - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. # rbac +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests. | + Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests. ## can - + `permissions` - + `needed` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| permissions | any | required | Comma-separated permission names held by the current role or subject | +| needed | any | required | Permission names required by the operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all. | + +Use `permissions`, `needed` as the inputs for this operation. Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all. -> _load -*> web_rbac_can permissions=`permissions` needed=`needed`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Return {ok, allowed} — whether held permission CSV includes any of needed (CSV). Held * allows all.](web_rbac_can(permissions=`permissions`, needed=`needed`))*. ## assign_role - + `url` - + `username` - + `role` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | required | Resource connection URL; scheme selects the documented backend | +| username | any | required | User name in the configured user store | +| role | any | required | Role name within the selected user store | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Bind `username` (in `web_users`) to role name. | + +Use `url`, `username`, `role` as the inputs for this operation. Bind `username` (in `web_users`) to role name. -> _load -*> web_rbac_assign_role url=`url` username=`username` role=`role`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Bind username (in web_users) to role name.](web_rbac_assign_role(url=`url`, username=`username`, role=`role`))*. ## create_role - + `url` - + `name` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | required | Resource connection URL; scheme selects the documented backend | +| name | any | required | Name registered or looked up by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Create a non-system role; returns `{ok, id, name}`. | + +Use `url`, `name` as the inputs for this operation. Create a non-system role; returns `{ok, id, name}`. -> _load -*> web_rbac_create_role url=`url` name=`name`* +We **[Load the native plugin required by this operation](_load())**. +Return *[Create a non-system role; returns {ok, id, name}.](web_rbac_create_role(url=`url`, name=`name`))*. ## set_role_permissions - + `url` - + `role` - + `permissions` - + `grantable`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | any | required | Resource connection URL; scheme selects the documented backend | +| role | any | required | Role name within the selected user store | +| permissions | any | required | Comma-separated permission names held by the current role or subject | +| grantable | any | "" | Permission catalog limiting which permissions may be granted | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog. | + +Use `url`, `role`, `permissions`, `grantable`="" as the inputs for this operation. Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog. -> _load -*> web_rbac_set_role_permissions url=`url` role=`role` permissions=`permissions` grantable=`grantable`* - +We **[Load the native plugin required by this operation](_load())**. +Return *[Replace permissions on a non-system role (CSV). grantable restricts grants (anti-escalation); empty = full catalog.](web_rbac_set_role_permissions(url=`url`, role=`role`, permissions=`permissions`, grantable=`grantable`))*. diff --git a/ext/web/_capability/index.mq.md b/ext/web/_capability/index.mq.md index 2bc6a4d..f9a5b13 100644 --- a/ext/web/_capability/index.mq.md +++ b/ext/web/_capability/index.mq.md @@ -22,6 +22,10 @@ Only this boundary imports lib/plugin, including through the Chinese facade. ## load +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | null after a successful load | + Locate the ABI v2 web shared library through plugin.native_path, then plugin.load it. If the library is missing, print a short install hint and exit non-zero so CI and agents fail loudly. After a successful load, later web star @@ -31,14 +35,10 @@ of each tool that needs the native server or renderer. This tool takes no parameters. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | null after a successful load | - -**p = > plugin.native_path name="web"** +We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**. 1. `p` - > plugin.load path=`p` + We **[Load the native plugin required by this operation](plugin.load(path=`p`))**. 2. * - > print text=ext/web: native web plugin not found (build plugins/web or marqdo ext add web) - > sys.exit code=1 -**** + We **[Print the prepared message](print(text="ext/web: native web plugin not found (build plugins/web or marqdo ext add web)"))**. + We **[End this run with the selected exit status](sys.exit(code=1))**. +Return *None*. diff --git a/ext/web/client/index.mq.md b/ext/web/client/index.mq.md index 85833c5..0a4ae3e 100644 --- a/ext/web/client/index.mq.md +++ b/ext/web/client/index.mq.md @@ -24,71 +24,80 @@ browser bridge tests and matching Chinese entry points. ## embed -| 参数 | 类型 | 说明 | -|------|------|------| -| bridge | text | bridge script URL | -| wasm | text | wasm URL | -| source | text | optional source URL | -| boot | bool | auto boot | - -HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults: -`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", -`source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author -JS. Not a substitute for file-partitioned Document layout. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| bridge | text | "/static/marqdo-bridge.js" | bridge script URL | +| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | +| source | text | "" | optional source URL | +| boot | bool | True | auto boot | | 返回 | 类型 | 说明 | |------|------|------| | result | text | HTML script tag | +Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation. + +HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults: + +`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", + +`source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author +JS. Not a substitute for file-partitioned Document layout. + 1. `boot` 1. `source` != "" - *""* + Return *""*. 2. * - *""* + Return *""*. 2. * - *""* + Return *""*. ## text_patch -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | text | required | CSS selector | +| text | text | required | text content | + +| 返回 | 类型 | 说明 | |------|------|------| -| sel | text | CSS selector | -| text | text | text content | +| result | any | effects map | + +Use `sel`, `text` as the inputs for this operation. Build a `set_text` effects map for selector `sel` with string `text`. Prefer lib/browser in client .mq.md programs; this helper is for call-side sketches. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | effects map | - -**`m` = > table.put in=None at=sel value=text** -*> table.put in=None at="set_text" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`text`))**. +Return *[Set the set_text field in the new record](table.put(in=None, at="set_text", value=`m`))*. ## dom_patch -| 参数 | 类型 | 说明 | -|------|------|------| -| sel | text | CSS selector | -| html | text | optional HTML | -| attrs | any | optional attrs map | -| remove | bool | remove node | - -Build a `dom` effects map for selector `sel`. Optional `html`="", `attrs`=None, -`remove`=False . Prefer View/Markdown over raw html patches for page shells. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | text | required | CSS selector | +| html | text | "" | optional HTML | +| attrs | any | None | optional attrs map | +| remove | bool | False | remove node | | 返回 | 类型 | 说明 | |------|------|------| | result | any | effects map | -**`spec` = > table.put in=None at="html" value=html** +Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation. + +Build a `dom` effects map for selector `sel`. Optional `html`="", `attrs`=None, + +`remove`=False . Prefer View/Markdown over raw html patches for page shells. + +We retain **`spec` = [Set the html field in the new record](table.put(in=None, at="html", value=`html`))**. 1. `attrs` - **`spec` = > table.put in=`spec` at="attrs" value=attrs** + We retain **`spec` = [Set the attrs field in the new record](table.put(in=`spec`, at="attrs", value=`attrs`))**. 2. * **_ = 1** 1. `remove` - **`spec` = > table.put in=`spec` at="remove" value=True** + We retain **`spec` = [Set the remove field in the new record](table.put(in=`spec`, at="remove", value=True))**. 2. * **_ = 1** -**`m` = > table.put in=None at=sel value=spec** -*> table.put in=None at="dom" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`spec`))**. +Return *[Set the dom field in the new record](table.put(in=None, at="dom", value=`m`))*. diff --git a/ext/web/component/index.mq.md b/ext/web/component/index.mq.md index a85a354..347dc55 100644 --- a/ext/web/component/index.mq.md +++ b/ext/web/component/index.mq.md @@ -32,50 +32,56 @@ Never put rendered HTML strings in parent value cells to simulate nesting. ## nodes -| 参数 | 类型 | 说明 | -|------|------|------| -| table | any | View table | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | View table | | 返回 | 类型 | 说明 | |------|------|------| -| result | any | Result | +| result | any | The supplied View table unchanged, preserving its original list or column-table shape | + +Use `table` as the inputs for this operation. Return View `table` unchanged. This preserves the existing identity helper for column tables as well as record lists. Prefer @ record lists for reusable components, because list composition can retain typed nested value cells. -*table* +Return *table*. ## merge -| 参数 | 类型 | 说明 | -|------|------|------| -| a | list | First node record list | -| b | list | Second node record list | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First node record list | +| b | list | required | Second node record list | | 返回 | 类型 | 说明 | |------|------|------| | result | list | Ordered sibling rows | +Use `a`, `b` as the inputs for this operation. + Concatenate `a` and `b` without rendering or flattening child containers. Both inputs must be lists of View rows, normally @ record tables. To place two components side by side, concatenate their wrapped columns then use layout.columns; concatenation alone only establishes sibling order. -*> table.concat a=`a` b=`b`* +Return *[Concat](table.concat(a=`a`, b=`b`))*. ## markdown -| 参数 | 类型 | 说明 | -|------|------|------| -| text | text | Plain Markdown content | -| slot | text | Stable component name | -| style | text | Optional class name | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Plain Markdown content | +| slot | text | "" | Stable component name | +| style | text | "" | Optional class name | | 返回 | 类型 | 说明 | |------|------|------| | result | list | One Markdown leaf | +Use `text`, `slot`="", `style`="" as the inputs for this operation. + Make a leaf from Markdown `text`. Default `slot`="" and `style`="" keep content independent of placement and theme. The returned list contains one markdown row; the runtime renders headings, links, lists and tables. No native @@ -87,21 +93,23 @@ plugin is loaded here, and no HTML is inserted into the authored component. |---|------|------|-------|-------|-------| | 1 | markdown | `slot` | `text` | "" | `style` | -*nodes* +Return *nodes*. ## wrap -| 参数 | 类型 | 说明 | -|------|------|------| -| children | list | Child node records | -| kind | text | Container kind | -| slot | text | Stable region name | -| style | text | Optional class name | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| children | list | required | Child node records | +| kind | text | "column" | Container kind | +| slot | text | "" | Stable region name | +| style | text | "" | Optional class name | | 返回 | 类型 | 说明 | |------|------|------| | result | list | One parent containing its child rows | +Use `children`, `kind`="column", `slot`="", `style`="" as the inputs for this operation. + Wrap `children` in one structural row. Default `kind`="column", `slot`="" and `style`="" . Use row or column for geometry, nav/header/footer/section/aside for a semantic region. The value cell holds the child list itself, not rendered @@ -114,4 +122,4 @@ this pure constructor does not claim to validate a full site. |---|------|------|-------|-------|-------| | 1 | `kind` | `slot` | `children` | "" | `style` | -*nodes* +Return *nodes*. diff --git a/ext/web/dom/index.mq.md b/ext/web/dom/index.mq.md index 82e30d5..4a888bc 100644 --- a/ext/web/dom/index.mq.md +++ b/ext/web/dom/index.mq.md @@ -24,42 +24,52 @@ raw path; do not use raw to compensate for missing decomposition. ## from_markdown -| 参数 | 类型 | 说明 | -|------|------|------| -| text | text | Markdown source | - -Turn Markdown `text` into a simple DOM map `{kind:"markdown", text}` for -`page.render` / `web.render`. This is the default body path for Document prose. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Markdown source | | 返回 | 类型 | 说明 | |------|------|------| | result | any | DOM map | -**`out` = > table.put in=None at="kind" value="markdown"** -*> table.put in=`out` at="text" value=text* +Use `text` as the inputs for this operation. + +Turn Markdown `text` into a simple DOM map `{kind:"markdown", text}` for +`page.render` / `web.render`. This is the default body path for Document prose. + +We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="markdown"))**. +Return *[Set the text field in the new record](table.put(in=`out`, at="text", value=`text`))*. ## raw -| 参数 | 类型 | 说明 | -|------|------|------| -| html | text | raw HTML (escape hatch) | - -Escape hatch — wrap raw `html`. Prefer Markdown / View nodes. Allowed only when -table-driven layout cannot express a host constraint; document the why next to -the call. Forbidden as the primary implementation of nav/sidebar/footer/home. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| html | text | required | raw HTML (escape hatch) | | 返回 | 类型 | 说明 | |------|------|------| | result | any | DOM map kind=raw | -**`out` = > table.put in=None at="kind" value="raw"** -*> table.put in=`out` at="html" value=html* +Use `html` as the inputs for this operation. + +Escape hatch — wrap raw `html`. Prefer Markdown / View nodes. Allowed only when +table-driven layout cannot express a host constraint; document the why next to +the call. Forbidden as the primary implementation of nav/sidebar/footer/home. + +We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="raw"))**. +Return *[Set the html field in the new record](table.put(in=`out`, at="html", value=`html`))*. ## render -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dom | any | required | DOM map from from_markdown or raw | + +| 返回 | 类型 | 说明 | |------|------|------| -| dom | any | DOM map from from_markdown or raw | +| result | any | HTML text | + +Use `dom` as the inputs for this operation. Render DOM Artifact `dom` (from from_markdown or raw) to HTML via the native plugin. When kind is markdown, @@ -69,15 +79,11 @@ escape hatch documented on raw, not for assembling a full site shell. Prefer feeding markdown DOM produced by from_markdown, or skip this helper and use page.render / web.render on View tables from file-partitioned components. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML text | - -> cap.load -**kind = [kind](access(dom, "kind"))** +We **[Load the native plugin required by this operation](cap.load())**. +We retain **`kind` = [Read kind field](access(`dom`, "kind"))**. 1. `kind` == "raw" - **html = [html](access(dom, "html"))** - *html* + We retain **`html` = [Read html field](access(`dom`, "html"))**. + Return *html*. 2. * - **text = [text](access(dom, "text"))** - *> web_dom_markdown text=`text`* + We retain **`text` = [Read text field](access(`dom`, "text"))**. + Return *[Render DOM Artifact dom (from from_markdown or raw) to HTML via the native plugin](web_dom_markdown(text=`text`))*. diff --git a/ext/web/index.mq.md b/ext/web/index.mq.md index b43b9ae..a32fb09 100644 --- a/ext/web/index.mq.md +++ b/ext/web/index.mq.md @@ -182,6 +182,8 @@ Return the workflow and stopping rule without creating files or claiming to accept a particular site. Define the region tree, author parents and Markdown leaves, then start and test the declared HTTP surface. +The returned rows are a planning aid, not a generated site or a validation certificate. Start with the component tree, give each parent one placement decision, then write the leaves as ordinary Markdown. Declare request-time handlers separately from startup assembly. Preview the composed result before starting the server, and compare real routes and narrow-screen geometry against that same source tree. + `workflow` = | key | value | @@ -196,7 +198,7 @@ leaves, then start and test the declared HTTP surface. | step_G | compare preview and live output; test routes and browser geometry | | stopping_rule | one Markdown responsibility and no internal layout | -*workflow* +Return *workflow*. ## layout_rules @@ -208,40 +210,44 @@ Reuse the layout module convention without a second rule catalog. No parameters or plugin. Actual acceptance still inspects leaf responsibilities, parent relationships and the running result. -*> layout.rules* +Return *[Rules](layout.rules())*. ## preview_markdown -| 参数 | 类型 | 说明 | -|------|------|------| -| body | text | Markdown content | -| title | text | Document title | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | text | "" | Markdown content | +| title | text | "Preview" | Document title | | 返回 | 类型 | 说明 | |------|------|------| | result | text | HTML document | +Use `body`="", `title`="Preview" as the inputs for this operation. + Render Markdown `body`="" with default `title`="Preview" . Return HTML text without writing files or registering routes. For a complex page split the layout first; raw HTML strings are not the content strategy. This tool needs the native plugin. -*> web.render body=`body` title=`title`* +Return *[Render](web.render(body=`body`, title=`title`))*. ## preview_nodes -| 参数 | 类型 | 说明 | -|------|------|------| -| nodes | list | Nested View rows | -| title | text | Document title | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| nodes | list | required | Nested View rows | +| title | text | "Preview" | Document title | | 返回 | 类型 | 说明 | |------|------|------| | result | text | HTML document | +Use `nodes`, `title`="Preview" as the inputs for this operation. + Render decomposed `nodes` with default `title`="Preview" . Parent values retain child rows, while leaf values hold Markdown. Returning HTML starts no server. The same renderer serves composed Documents, so this preview checks that column relationships survive assembly. -*> web.render nodes=`nodes` title=`title`* +Return *[Render](web.render(nodes=`nodes`, title=`title`))*. diff --git a/ext/web/layout/index.mq.md b/ext/web/layout/index.mq.md index 3ae9d55..42ced02 100644 --- a/ext/web/layout/index.mq.md +++ b/ext/web/layout/index.mq.md @@ -37,12 +37,14 @@ plugins/web/internal/artifact with bilingual helpers and web_handbook tests. | 返回 | 类型 | 说明 | |------|------|------| -| result | any | Result | +| result | any | Column table with aligned key/value lists describing layout rules; no source inspection | Return the engineering convention and stopping rule. No parameters or plugin. This is guidance rather than evidence that a particular source file passes; acceptance also requires reading the leaves and exercising the resulting page. +Apply the stopping rule to responsibilities rather than file size. A footer with two independent groups still needs child regions even if its text is short. A leaf containing several ordinary paragraphs may remain one Markdown responsibility when it needs no internal geometry. The parent imports those children and places them; the renderer supplies the resulting container structure. This table records that convention but does not inspect your files or certify that a layout works. + `out` = | key | value | @@ -56,7 +58,7 @@ acceptance also requires reading the leaves and exercising the resulting page. | geometry | merge gives siblings; stack and columns give placement | | verify | offline render; live routes; narrow and wide browser geometry | -*out* +Return *out*. ## view_schema @@ -78,73 +80,83 @@ layout within one representation instead of adding a private fragment dialect. | attrs | | style | -*cols* +Return *cols*. ## merge_nodes -| 参数 | 类型 | 说明 | -|------|------|------| -| a | list | First node records | -| b | list | Second node records | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First node records | +| b | list | required | Second node records | | 返回 | 类型 | 说明 | |------|------|------| | result | list | Ordered sibling nodes | +Use `a`, `b` as the inputs for this operation. + Concatenate `a` and `b` as siblings. This helper preserves structure and order but does not imply geometry; use columns for side-by-side placement or stack for a vertical page. The @ record lists retain nested values throughout. -*> component.merge a=`a` b=`b`* +Return *[Merge](component.merge(a=`a`, b=`b`))*. ## stack -| 参数 | 类型 | 说明 | -|------|------|------| -| children | list | Child component records | -| slot | text | Parent region name | -| style | text | Optional class name | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| children | list | required | Child component records | +| slot | text | "" | Parent region name | +| style | text | "" | Optional class name | | 返回 | 类型 | 说明 | |------|------|------| | result | list | Parent container rows | +Use `children`, `slot`="", `style`="" as the inputs for this operation. + Declare one vertical relationship for `children`. Default `slot`="" and + `style`="" . The parent owns placement while each imported child owns content or its next decomposition level. Return View rows so another parent can wrap them without first serializing any HTML. -*> component.wrap children=`children` kind="column" slot=`slot` style=`style`* +Return *[Wrap](component.wrap(children=`children`, kind="column", slot=`slot`, style=`style`))*. ## columns -| 参数 | 类型 | 说明 | -|------|------|------| -| children | list | Child component records | -| slot | text | Parent region name | -| style | text | Optional class name | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| children | list | required | Child component records | +| slot | text | "" | Parent region name | +| style | text | "" | Optional class name | | 返回 | 类型 | 说明 | |------|------|------| | result | list | Parent container rows | +Use `children`, `slot`="", `style`="" as the inputs for this operation. + Declare one responsive multi-column relationship for `children`. Default `slot`="" and + `style`="" . The parent owns placement while each imported child owns content or its next decomposition level. Return View rows so another parent can wrap them without first serializing any HTML. -*> component.wrap children=`children` kind="row" slot=`slot` style=`style`* +Return *[Wrap](component.wrap(children=`children`, kind="row", slot=`slot`, style=`style`))*. ## accept_component -| 参数 | 类型 | 说明 | -|------|------|------| -| name | text | Component name | -| duty | text | One responsibility | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Component name | +| duty | text | required | One responsibility | | 返回 | 类型 | 说明 | |------|------|------| -| result | any | Result | +| result | any | Checklist record with status, name, duty and check; it does not certify a component | + +Use `name`, `duty` as the inputs for this operation. Return a review checklist for component `name` and stated `duty`. Two strings cannot establish source quality or a working layout, so this tool does not @@ -157,4 +169,4 @@ before accepting the component. It never writes or scans files. |--------|------|------|-------| | checklist | `name` | `duty` | one Markdown leaf or one parent relationship; no raw HTML shell | -*row* +Return *row*. diff --git a/ext/web/page/index.mq.md b/ext/web/page/index.mq.md index e8e275a..6bb4c50 100644 --- a/ext/web/page/index.mq.md +++ b/ext/web/page/index.mq.md @@ -26,45 +26,57 @@ preserve tests/ext/web-artifact-render-smoke.mq.md and the handbook tests. ## new -| 参数 | 类型 | 说明 | -|------|------|------| -| title | text | document title | -| route | text | path | -| method | text | HTTP method | -| body | text | Markdown body | -| nodes | any | View table or None | -| data_source | text | table name | -| data_order | text | order key | -| data_where | text | filters | - -Construct a Document handle with `title`="", `route`="/", `method`="GET", -`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", -`data_where`="" keys. Prefer Artifact discovery via serve for production pages; -use this tool for previews and stepwise agent sessions. nodes must be the -unified View schema, never a private dialect or an HTML string shell. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| title | text | "" | document title | +| route | text | "/" | path | +| method | text | "GET" | HTTP method | +| body | text | "" | Markdown body | +| nodes | any | None | View table or None | +| data_source | text | "" | table name | +| data_order | text | "" | order key | +| data_where | text | "" | filters | | 返回 | 类型 | 说明 | |------|------|------| | result | any | page handle | -> cap.load +Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. + +Construct a Document handle with `title`="", `route`="/", `method`="GET", + +`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", + +`data_where`="" keys. Prefer Artifact discovery via serve for production pages; +use this tool for previews and stepwise agent sessions. nodes must be the +unified View schema, never a private dialect or an HTML string shell. + +We **[Load the native plugin required by this operation](cap.load())**. + `out` = | _type | title | route | method | body | nodes | data_source | data_order | data_where | |-------|-------|-------|--------|------|-------|-------------|------------|------------| | page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` | -*out* +Return *out*. ## render -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| page | any | required | Document handle | +| nodes | any | None | View table or None | +| db | any | None | optional database handle | + +| 返回 | 类型 | 说明 | |------|------|------| -| page | any | Document handle | -| nodes | any | View table or None | -| db | any | optional database handle | +| result | any | HTML or render payload | + +Use `page`, `nodes`=None, `db`=None as the inputs for this operation. Render Document handle `page` to HTML for preview or response. Optional + `nodes`=None is the unified View table; when None, uses the page's own nodes or Markdown body. Optional `db`=None is retained for facade compatibility. This offline renderer does not populate data_source; automatic row binding belongs to served ordinary @@ -74,64 +86,65 @@ handmade HTML string as the page shell. This is the sole compose path (ADR 0007); there is no compose_main or fragment DSL. Agents should call this free tool (not a method chain) under `--effects plugin`. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML or render payload | - -> cap.load -**n = nodes** +We **[Load the native plugin required by this operation](cap.load())**. +We retain **n = nodes**. 1. `n` == None - **n = [nodes](access(page, "nodes"))** + We retain **`n` = [Read nodes field](access(`page`, "nodes"))**. 2. * **_ = 1** -**title = [title](access(page, "title"))** +We retain **`title` = [Read title field](access(`page`, "title"))**. 1. `n` - *> web_render_nodes page=`page` nodes=`n` db=`db` title=`title`* + Return *[Render Document handle page to HTML for preview or response](web_render_nodes(page=`page`, nodes=`n`, db=`db`, title=`title`))*. 2. * - **body = [body](access(page, "body"))** - *> web_render_document page=`page` body=`body` db=`db` title=`title`* + We retain **`body` = [Read body field](access(`page`, "body"))**. + Return *[Render Document handle page to HTML for preview or response](web_render_document(page=`page`, body=`body`, db=`db`, title=`title`))*. # page -| 参数 | 类型 | 说明 | -|------|------|------| -| title | any | See prose default / 见叙述默认值 | -| route | any | See prose default / 见叙述默认值 | -| method | any | See prose default / 见叙述默认值 | -| body | any | See prose default / 见叙述默认值 | -| nodes | any | See prose default / 见叙述默认值 | -| data_source | any | See prose default / 见叙述默认值 | -| data_order | any | See prose default / 见叙述默认值 | -| data_where | any | See prose default / 见叙述默认值 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| title | any | "" | Document title used by preview and page rendering | +| route | any | "/" | Declared URL path at which this Document may be mounted | +| method | any | "GET" | HTTP request method for the declared route | +| body | any | "" | Markdown document content; complex sites use recursively split components | +| nodes | any | None | Nested View records, or None to retain document-body rendering | +| data_source | any | "" | Document data source declaration; empty means no automatic source | +| data_order | any | "" | Ordering declaration for the selected document data source | +| data_where | any | "" | Filter declaration for the selected document data source | -Inputs: `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Document handle retaining title, route, method, body, nodes and data declarations | + +Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. Web Document handle for author method chains. Prefer constructing from Artifact Metadata via `web.page` facade or the free `new` tool above. View tables use only `|type|slot|value|attrs|style|` (ZH `|类型|槽|值|属性|样式|`). Do not pass a raw HTML string as the primary `body` for a full site shell. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Constructed value / 构造结果 | +We **[Load the native plugin required by this operation](cap.load())**. -> cap.load `out` = | _type | title | route | method | body | nodes | data_source | data_order | data_where | |-------|-------|-------|--------|------|-------|-------------|------------|------------| | page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` | -*out* +Return *out*. ## render -| 参数 | 类型 | 说明 | -|------|------|------| -| nodes | any | View table or None | -| db | any | optional database handle | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| nodes | any | None | View table or None | +| db | any | None | optional database handle | -Inputs: `nodes`=None, `db`=None +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | HTML or render payload | + +Use `nodes`=None, `db`=None as the inputs for this operation. Render this Document to HTML for preview or response. Optional `nodes` is the unified View table (type/slot/value/attrs/style). When `nodes` is None, the @@ -141,39 +154,35 @@ file-partitioned components via component.merge — do not pass a handmade HTML string as the page shell. This is the sole compose path (ADR 0007); there is no compose_main or fragment DSL. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | HTML or render payload | - -> cap.load -**n = nodes** +We **[Load the native plugin required by this operation](cap.load())**. +We retain **n = nodes**. 1. `n` == None - **n = [nodes](access(self, "nodes"))** + We retain **`n` = [Read nodes field](access(`self`, "nodes"))**. 2. * **_ = 1** -**title = [title](access(self, "title"))** +We retain **`title` = [Read title field](access(`self`, "title"))**. 1. `n` - *> web_render_nodes page=`self` nodes=`n` db=`db` title=`title`* + Return *[Render this Document to HTML for preview or response](web_render_nodes(page=`self`, nodes=`n`, db=`db`, title=`title`))*. 2. * - **body = [body](access(self, "body"))** - *> web_render_document page=`self` body=`body` db=`db` title=`title`* + We retain **`body` = [Read body field](access(`self`, "body"))**. + Return *[Render this Document to HTML for preview or response](web_render_document(page=`self`, body=`body`, db=`db`, title=`title`))*. ## css -| 参数 | 类型 | 说明 | -|------|------|------| -| css | text | raw CSS (escape hatch) | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| css | text | required | raw CSS (escape hatch) | -Inputs: `css` +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | updated page handle | + +Use `css` as the inputs for this operation. Escape hatch — append raw CSS string `css` to this page. Named style tables and the View style column remain the default theme path. Use this only when a host constraint cannot be expressed as a named style row, and write that reason next to the call. Forbidden as the primary way to style nav, sidebar, or footer. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | updated page handle | - -> cap.load -*> web_page_css page=`self` css=`css`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Escape hatch — append raw CSS string css to this page](web_page_css(page=`self`, css=`css`))*. diff --git a/ext/web/route/index.mq.md b/ext/web/route/index.mq.md index 3f105a4..21525e1 100644 --- a/ext/web/route/index.mq.md +++ b/ext/web/route/index.mq.md @@ -25,44 +25,55 @@ changes; never introduce undeclared user URLs as a hidden convenience. ## new -| 参数 | 类型 | 说明 | -|------|------|------| -| app | any | app handle | -| path | text | URL path | -| method | text | HTTP method | -| page | any | Document or None | -| fn | text | endpoint member | -| request | text | request kind | -| response | text | response kind | -| auth | text | auth tag | -| class | text | route class | - -Build a declared route handle for `app` at `path` with `method`="GET" . -`page`=None holds a Document; `fn`="" names an Endpoint lib.member. -`request`="json", `response`="json", `auth`="", and `class`="" document the -contract. Optional class values: execute, short, read, control (empty → -heuristic / legacy_serial). This tool does not register yet — call `register` -or use the facade `web.route` which registers in one step. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | required | app handle | +| path | text | required | URL path | +| method | text | "GET" | HTTP method | +| page | any | None | Document or None | +| fn | text | "" | endpoint member | +| request | text | "json" | request kind | +| response | text | "json" | response kind | +| auth | text | "" | auth tag | +| class | text | "" | route class | | 返回 | 类型 | 说明 | |------|------|------| | result | any | route handle | -> cap.load +Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. + +Build a declared route handle for `app` at `path` with `method`="GET" . + +`page`=None holds a Document; `fn`="" names an Endpoint lib.member. + +`request`="json", `response`="json", `auth`="", and `class`="" document the +contract. Optional class values: execute, short, read, control (empty → +heuristic / legacy_serial). This tool does not register yet — call `register` +or use the facade `web.route` which registers in one step. + +We **[Load the native plugin required by this operation](cap.load())**. + `out` = | _type | app | path | method | page | fn | request | response | auth | class | |-------|-----|------|--------|------|----|---------|----------|------|-------| | route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` | -*out* +Return *out*. ## register -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| route | any | required | route handle | +| app | any | None | app or None | + +| 返回 | 类型 | 说明 | |------|------|------| -| route | any | route handle | -| app | any | app or None | +| result | any | registration result | + +Use `route`, `app`=None as the inputs for this operation. Register declared route handle `route` on an app. Optional `app`=None falls back to the app stored on the route object so stepwise agent sessions can omit it. @@ -73,108 +84,111 @@ free tool under `--effects plugin` rather than a method chain when driving registration from `marqdo call`. Soft-fails with ok=False when neither page nor fn is present, so callers can detect incomplete declarations early. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -> cap.load -**a = app** +We **[Load the native plugin required by this operation](cap.load())**. +We retain **a = app**. 1. `a` == None - **a = [app](access(route, "app"))** + We retain **`a` = [Read app field](access(`route`, "app"))**. 2. * **_ = 1** -**page = [page](access(route, "page"))** -**fn = [fn](access(route, "fn"))** +We retain **`page` = [Read page field](access(`route`, "page"))**. +We retain **`fn` = [Read fn field](access(`route`, "fn"))**. 1. `page` - **path = [path](access(route, "path"))** - *> web_app_route app=`a` path=`path` page=`page`* + We retain **`path` = [Read path field](access(`route`, "path"))**. + Return *[Register declared route handle route on an app](web_app_route(app=`a`, path=`path`, page=`page`))*. 2. `fn` - **path = [path](access(route, "path"))** - **method = [method](access(route, "method"))** - **request = [request](access(route, "request"))** - **response = [response](access(route, "response"))** - **class = [class](access(route, "class"))** - *> web_app_invoke app=`a` path=`path` method=`method` fn=`fn` body=`request` return=`response` class=`class`* + We retain **`path` = [Read path field](access(`route`, "path"))**. + We retain **`method` = [Read method field](access(`route`, "method"))**. + We retain **`request` = [Read request field](access(`route`, "request"))**. + We retain **`response` = [Read response field](access(`route`, "response"))**. + We retain **`class` = [Read class field](access(`route`, "class"))**. + Return *[Register declared route handle route on an app](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*. 3. * - *> table.put in=None at="ok" value=False* + Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*. ## use -| 参数 | 类型 | 说明 | -|------|------|------| -| route | any | route handle | -| middleware | any | middleware table | - -Attach middleware table `middleware` to declared route handle `route` -(`|header|value|` or named capability rows). Prefer first-class middleware tables -over configure junk drawers. Call this free tool with `--effects plugin`. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| middleware | any | required | middleware table | +| route | any | required | route handle | | 返回 | 类型 | 说明 | |------|------|------| | result | any | use result | -> cap.load -*> web_route_use route=`route` middleware=`middleware`* +Use `middleware`, `route` as the inputs for this operation. + +Attach middleware table `middleware` to declared route handle `route` +(`|header|value|` or named capability rows). Prefer first-class middleware tables +over configure junk drawers. Call this free tool with `--effects plugin`. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Attach middleware table middleware to declared route handle route (|header|value| or named capability rows)](web_route_use(route=`route`, middleware=`middleware`))*. # route -| 参数 | 类型 | 说明 | -|------|------|------| -| app | any | See prose default / 见叙述默认值 | -| path | any | See prose default / 见叙述默认值 | -| method | any | See prose default / 见叙述默认值 | -| page | any | See prose default / 见叙述默认值 | -| fn | any | See prose default / 见叙述默认值 | -| request | any | See prose default / 见叙述默认值 | -| response | any | See prose default / 见叙述默认值 | -| auth | any | See prose default / 见叙述默认值 | -| class | any | See prose default / 见叙述默认值 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | required | Application handle created by the public web app constructor | +| path | any | required | URL path declared for this route | +| method | any | "GET" | HTTP request method for the declared route | +| page | any | None | Initial Document/page resource, or None for explicit later route mounts | +| fn | any | "" | Endpoint member path; empty when mounting a Document page | +| request | any | "json" | Request body format passed to the native Endpoint dispatcher | +| response | any | "json" | Response format passed to the native Endpoint dispatcher | +| auth | any | "" | Explicit route authentication policy label | +| class | any | "" | Execution class: execute, short, read or control; empty keeps native heuristics | -Inputs: `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Declared route handle retaining app, path, method, page or endpoint and dispatch fields | + +Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. Declared route handle for author method chains. Prefer `web.route` / Artifact `type: endpoint` discovery via `web.serve`. Optional `class`: `execute` | `short` | `read` | `control` (empty → heuristic / `legacy_serial`). -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Constructed value / 构造结果 | +We **[Load the native plugin required by this operation](cap.load())**. -> cap.load `out` = | _type | app | path | method | page | fn | request | response | auth | class | |-------|-----|------|--------|------|----|---------|----------|------|-------| | route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` | -*out* +Return *out*. ## use -| 参数 | 类型 | 说明 | -|------|------|------| -| middleware | any | middleware table | - -Inputs: `middleware` - -Attach middleware table to this route (`|header|value|` or named capability -rows). Prefer explicit tables authors can read; do not restore a configure bag -for headers and cors. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| middleware | any | required | middleware table | | 返回 | 类型 | 说明 | |------|------|------| | result | any | use result | -> cap.load -*> web_route_use route=`self` middleware=`middleware`* +Use `middleware` as the inputs for this operation. + +Attach middleware table to this route (`|header|value|` or named capability +rows). Prefer explicit tables authors can read; do not restore a configure bag +for headers and cors. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Attach middleware table to this route (|header|value| or named capability rows)](web_route_use(route=`self`, middleware=`middleware`))*. ## register -| 参数 | 类型 | 说明 | -|------|------|------| -| app | any | app or None | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | None | app or None | -Inputs: `app`=None +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | registration result | + +Use `app`=None as the inputs for this operation. Register this declared route on an app handle. When optional `app` is None, use the app stored on this route object so author chains can omit the argument after @@ -187,27 +201,23 @@ page nor fn is set, so callers can detect an incomplete declaration without a hard crash. Never invents an undeclared path — registration only publishes what this handle already carries. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -> cap.load -**a = app** +We **[Load the native plugin required by this operation](cap.load())**. +We retain **a = app**. 1. `a` == None - **a = [app](access(self, "app"))** + We retain **`a` = [Read app field](access(`self`, "app"))**. 2. * **_ = 1** -**page = [page](access(self, "page"))** -**fn = [fn](access(self, "fn"))** +We retain **`page` = [Read page field](access(`self`, "page"))**. +We retain **`fn` = [Read fn field](access(`self`, "fn"))**. 1. `page` - **path = [path](access(self, "path"))** - *> web_app_route app=`a` path=`path` page=`page`* + We retain **`path` = [Read path field](access(`self`, "path"))**. + Return *[Register this declared route on an app handle](web_app_route(app=`a`, path=`path`, page=`page`))*. 2. `fn` - **path = [path](access(self, "path"))** - **method = [method](access(self, "method"))** - **request = [request](access(self, "request"))** - **response = [response](access(self, "response"))** - **class = [class](access(self, "class"))** - *> web_app_invoke app=`a` path=`path` method=`method` fn=`fn` body=`request` return=`response` class=`class`* + We retain **`path` = [Read path field](access(`self`, "path"))**. + We retain **`method` = [Read method field](access(`self`, "method"))**. + We retain **`request` = [Read request field](access(`self`, "request"))**. + We retain **`response` = [Read response field](access(`self`, "response"))**. + We retain **`class` = [Read class field](access(`self`, "class"))**. + Return *[Register this declared route on an app handle](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*. 3. * - *> table.put in=None at="ok" value=False* + Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*. diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 2dcde36..1a2605b 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -35,110 +35,128 @@ route API. Contracts precede execution; ordinary prose titles are not functions. ## page -| 参数 | 类型 | 说明 | -|------|------|------| -| title | text | document title | -| route | text | path | -| method | text | HTTP method | -| body | text | Markdown body | -| nodes | any | View table or None | -| data_source | text | table name | -| data_order | text | order key | -| data_where | text | filters | - -Construct a Document handle with `title`="", `route`="/", `method`="GET", -`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", -`data_where`="" keys. Prefer discovering type: web Artifact files via serve -rather than hand-building every page in memory. nodes must be the unified View -schema, never a private dialect or an HTML string shell. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| title | text | "" | document title | +| route | text | "/" | path | +| method | text | "GET" | HTTP method | +| body | text | "" | Markdown body | +| nodes | any | None | View table or None | +| data_source | text | "" | table name | +| data_order | text | "" | order key | +| data_where | text | "" | filters | | 返回 | 类型 | 说明 | |------|------|------| | result | any | page handle | -*> page_mod.page title=`title` route=`route` method=`method` body=`body` nodes=`nodes` data_source=`data_source` data_order=`data_order` data_where=`data_where`* +Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation. + +Construct a Document handle with `title`="", `route`="/", `method`="GET", + +`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="", + +`data_where`="" keys. Prefer discovering type: web Artifact files via serve +rather than hand-building every page in memory. nodes must be the unified View +schema, never a private dialect or an HTML string shell. + +Return *[Page](page_mod.page(title=`title`, route=`route`, method=`method`, body=`body`, nodes=`nodes`, data_source=`data_source`, data_order=`data_order`, data_where=`data_where`))*. ## route -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | required | app handle | +| path | text | required | URL path | +| method | text | "GET" | HTTP method | +| page | any | None | Document or None | +| fn | text | "" | endpoint member | +| request | text | "json" | request kind | +| response | text | "json" | response kind | +| auth | text | "" | auth tag | +| class | text | "" | route class | + +| 返回 | 类型 | 说明 | |------|------|------| -| app | any | app handle | -| path | text | URL path | -| method | text | HTTP method | -| page | any | Document or None | -| fn | text | endpoint member | -| request | text | request kind | -| response | text | response kind | -| auth | text | auth tag | -| class | text | route class | +| result | any | registration result | + +Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation. Register a declared Document page or Endpoint on `app` at `path` with + `method`="GET" . `page`=None holds a Document; `fn`="" names an Endpoint lib.member. `request`="json", `response`="json", `auth`="", and `class`="" document the contract. Optional class values include execute, short, read, control. User routes must be declared — never implicit. After building the route object this tool registers it on the app. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | registration result | - -**r = > route_mod.route app=`app` path=`path` method=`method` page=`page` fn=`fn` request=`request` response=`response` auth=`auth` class=`class`** -*> `r`.register app=`app`* +We retain **`r` = [Route](route_mod.route(app=`app`, path=`path`, method=`method`, page=`page`, fn=`fn`, request=`request`, response=`response`, auth=`auth`, class=`class`))**. +Return *[Register](> `r`.register app=`app` )*. ## render -| 参数 | 类型 | 说明 | -|------|------|------| -| doc | any | Document or None | -| nodes | any | View table or None | -| body | text | Markdown | -| title | text | title | -| db | any | optional db | - -Render a Document or View nodes to HTML for offline preview. Prefer nodes from -file-partitioned components. Optional `doc`=None is a Document handle; when set, -delegates to page.render. Optional `nodes`=None is a View table; when set without -doc, renders that table. Otherwise renders Markdown `body`="" with optional -`title`="" and `db`=None . Requires the native plugin. Do not treat this as -permission to paste a full HTML homepage — keep using View tables and Markdown. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| doc | any | None | Document or None | +| nodes | any | None | View table or None | +| body | text | "" | Markdown | +| title | text | "" | title supplied by the caller | +| db | any | None | optional db | | 返回 | 类型 | 说明 | |------|------|------| | result | any | HTML or payload | -> cap.load +Use `doc`=None, `nodes`=None, `body`="", `title`="", `db`=None as the inputs for this operation. + +Render a Document or View nodes to HTML for offline preview. Prefer nodes from +file-partitioned components. Optional `doc`=None is a Document handle; when set, +delegates to page.render. Optional `nodes`=None is a View table; when set without +doc, renders that table. Otherwise renders Markdown `body`="" with optional + +`title`="" and `db`=None . Requires the native plugin. Do not treat this as +permission to paste a full HTML homepage — keep using View tables and Markdown. + +We **[Load the native plugin required by this operation](cap.load())**. 1. `doc` - *> `doc`.render nodes=`nodes` db=`db`* + Return *[Render](> `doc`.render nodes=`nodes` db=`db` )*. 2. `nodes` - *> web_render_nodes page=`doc` nodes=`nodes` db=`db` title=`title`* + Return *[Render a Document or View nodes to HTML for offline preview](web_render_nodes(page=`doc`, nodes=`nodes`, db=`db`, title=`title`))*. 3. * - *> web_render_document page=`doc` body=`body` db=`db` title=`title`* + Return *[Render a Document or View nodes to HTML for offline preview](web_render_document(page=`doc`, body=`body`, db=`db`, title=`title`))*. ## use -| 参数 | 类型 | 说明 | -|------|------|------| -| app | any | app handle | -| middleware | any | middleware table | - -Attach first-class `middleware` to `app`. Pass a GFM table (security headers, -cors row, and similar). This replaces the old configure(...) junk drawer with an -explicit table authors can read. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| middleware | any | required | middleware table | +| app | any | required | app handle | | 返回 | 类型 | 说明 | |------|------|------| | result | any | app handle | -> cap.load -*> web_app_use app=`app` middleware=`middleware`* +Use `middleware`, `app` as the inputs for this operation. + +Attach first-class `middleware` to `app`. Pass a GFM table (security headers, +cors row, and similar). This replaces the old configure(...) junk drawer with an +explicit table authors can read. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Attach first-class middleware to app](web_app_use(app=`app`, middleware=`middleware`))*. ## inspect -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| app | any | None | app or None | +| root | text | "" | Site directory to inspect without listening | + +| 返回 | 类型 | 说明 | |------|------|------| -| app | any | app or None | -| root | text | Site directory to inspect without listening | +| result | any | {declared, system} | + +Use `app`=None, `root`="" as the inputs for this operation. Return declared versus system route tables for introspection. System routes such as /_part and /_form must appear here. Use this to verify a site after serve or @@ -146,23 +164,25 @@ manual registration. Optional `app`=None selects which application to inspect. Optional `root`="" scans a site directory when supplied; it does not start a server. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | {declared, system} | - -> cap.load -*> web_inspect app=`app` root=`root`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Return declared versus system route tables for introspection](web_inspect(app=`app`, root=`root`))*. ## serve -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| root | text | "." | site root | +| host | text | "127.0.0.1" | bind host | +| port | number | 18081 | Explicit server port | +| db | any | None | optional db | +| static_dir | text | "" | static files | +| middleware | any | None | optional middleware | + +| 返回 | 类型 | 说明 | |------|------|------| -| root | text | site root | -| host | text | bind host | -| port | number | port | -| db | any | optional db | -| static_dir | text | static files | -| middleware | any | optional middleware | +| result | any | serve result | + +Use `root`=".", `host`="127.0.0.1", `port`=18081, `db`=None, `static_dir`="", `middleware`=None as the inputs for this operation. Scan `root`="." for type web or endpoint Artifacts, register declared routes, attach system routes, and listen on `host`="127.0.0.1" and `port`=18081 . The @@ -170,138 +190,153 @@ site directory should already follow the layout law (components split until simple). Optional `db`=None, `static_dir`="", and `middleware`=None bind resources without stuffing them into this facade as author APIs. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | serve result | - -> cap.load -*> web_serve_root root=`root` host=`host` port=`port` db=`db` static_dir=`static_dir` middleware=`middleware`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Scan root="](web_serve_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*. ## client_embed -| 参数 | 类型 | 说明 | -|------|------|------| -| bridge | text | bridge script URL | -| wasm | text | wasm URL | -| source | text | optional source | -| boot | bool | auto boot | - -Describe WASM bridge embed tags for a page that needs client Marqdo. Defaults: -`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", -`source`="", `boot`=True . This is not a substitute for Document layout: still -partition nav and main in files, then embed the bridge where interaction needs -it. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| bridge | text | "/static/marqdo-bridge.js" | bridge script URL | +| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | +| source | text | "" | optional source | +| boot | bool | True | auto boot | | 返回 | 类型 | 说明 | |------|------|------| | result | any | embed descriptor | -*> client_mod.embed bridge=`bridge` wasm=`wasm` source=`source` boot=`boot`* +Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation. + +Describe WASM bridge embed tags for a page that needs client Marqdo. Defaults: + +`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", + +`source`="", `boot`=True . This is not a substitute for Document layout: still +partition nav and main in files, then embed the bridge where interaction needs +it. + +Return *[Embed](client_mod.embed(bridge=`bridge`, wasm=`wasm`, source=`source`, boot=`boot`))*. ## text_patch -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | text | required | CSS selector | +| text | text | required | new text | + +| 返回 | 类型 | 说明 | |------|------|------| -| sel | text | CSS selector | -| text | text | new text | +| result | any | patch descriptor | + +Use `sel`, `text` as the inputs for this operation. Client patch: set text content for CSS selector `sel` to string `text`. Use for small interactive updates after a Document is already laid out with View tables — not for building the initial homepage shell. +Return *[Text patch](client_mod.text_patch(sel=`sel`, text=`text`))*. + +## dom_patch + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | text | required | CSS selector | +| html | text | "" | optional HTML fragment | +| attrs | any | None | optional attrs | +| remove | bool | False | remove node | + | 返回 | 类型 | 说明 | |------|------|------| | result | any | patch descriptor | -*> client_mod.text_patch sel=`sel` text=`text`* - -## dom_patch - -| 参数 | 类型 | 说明 | -|------|------|------| -| sel | text | CSS selector | -| html | text | optional HTML fragment | -| attrs | any | optional attrs | -| remove | bool | remove node | +Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation. Client patch for selector `sel` with optional `html`="", `attrs`=None, or + `remove`=False . Treat html here as a surgical update, never as the primary way to author nav, sidebar, or footer. Layout law still applies to the Document that hosts the selector. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | patch descriptor | - -*> client_mod.dom_patch sel=`sel` html=`html` attrs=`attrs` remove=`remove`* +Return *[Dom patch](client_mod.dom_patch(sel=`sel`, html=`html`, attrs=`attrs`, remove=`remove`))*. ## make_style -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | property table | +| name | text | "" | style name | +| strict | bool | False | strict mode | + +| 返回 | 类型 | 说明 | |------|------|------| -| name | text | style name | -| table | any | property table | -| strict | bool | strict mode | +| result | any | CSS / style handle | + +Use `table`, `name`="", `strict`=False as the inputs for this operation. Compile a named style `table` into CSS. Optional `name`="" and `strict`=False . Styles remain data next to content; this is not a hidden page DSL. Prefer referencing style names from View style columns after file-partitioned components define their look. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | CSS / style handle | - -> cap.load -*> web_style name=`name` table=`table` strict=`strict`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Compile a named style table into CSS](web_style(name=`name`, table=`table`, strict=`strict`))*. ## make_images -| 参数 | 类型 | 说明 | -|------|------|------| -| table | any | images table | - -Build image descriptors from a readable `table` of sources and alts. Keep media -declarations in Markdown tables beside the Document that uses them. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | images table | | 返回 | 类型 | 说明 | |------|------|------| | result | any | images payload | -> cap.load -*> web_images table=`table`* +Use `table` as the inputs for this operation. + +Build image descriptors from a readable `table` of sources and alts. Keep media +declarations in Markdown tables beside the Document that uses them. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Build image descriptors from a readable table of sources and alts. Keep media declarations in Markdown tables beside the Document that uses them.](web_images(table=`table`))*. ## make_head -| 参数 | 类型 | 说明 | -|------|------|------| -| table | any | head table | - -Build head resource rows (link, script, icon) from a `table`. Prefer declaring -head needs as data rather than injecting opaque HTML head strings. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| table | any | required | head table | | 返回 | 类型 | 说明 | |------|------|------| | result | any | head payload | -> cap.load -*> web_head table=`table`* +Use `table` as the inputs for this operation. + +Build head resource rows (link, script, icon) from a `table`. Prefer declaring +head needs as data rather than injecting opaque HTML head strings. + +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Build head resource rows (link, script, icon) from a table. Prefer declaring head needs as data rather than injecting opaque HTML head strings.](web_head(table=`table`))*. # app -| 参数 | 类型 | 说明 | -|------|------|------| -| page | any | See prose default / 见叙述默认值 | -| db | any | See prose default / 见叙述默认值 | -| host | any | See prose default / 见叙述默认值 | -| port | any | See prose default / 见叙述默认值 | -| admin | any | See prose default / 见叙述默认值 | -| admin_prefix | any | See prose default / 见叙述默认值 | -| shell_css | any | See prose default / 见叙述默认值 | -| layout | any | See prose default / 见叙述默认值 | -| asset_version | any | See prose default / 见叙述默认值 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| page | any | None | Initial Document/page resource, or None for explicit later route mounts | +| db | any | None | Existing database resource used for document data and native application services | +| host | any | "127.0.0.1" | Listen address; the default binds only the local host | +| port | any | 18081 | TCP listen port selected for the application | +| admin | any | False | Whether to enable the native administration routes | +| admin_prefix | any | "/admin" | URL prefix under which native administration routes are mounted | +| shell_css | any | None | Optional native shell stylesheet configuration; None keeps the runtime default | +| layout | any | None | Optional native shell layout configuration; component geometry remains View data | +| asset_version | any | None | Optional resource version used by the native shell for asset URLs | -Inputs: `page`=None, `db`=None, `host`=127.0.0.1, `port`=18081, `admin`=False, `admin_prefix`="/admin", `shell_css`=None, `layout`=None, `asset_version`=None +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Native app resource for static mounts, route registration, gates and listening | + +Use `page`=None, `db`=None, `host`="127.0.0.1", `port`=18081, `admin`=False, `admin_prefix`="/admin", `shell_css`=None, `layout`=None, `asset_version`=None as the inputs for this operation. Low-level app handle for advanced mounts. Prefer web.serve for Artifact sites that already follow file-partition layout. Optional page, db, host, port, admin @@ -311,59 +346,60 @@ discovery should stay on serve; agents should not invent HTML shells on this object. Methods static, listen, and gate hang off the returned handle for mounts that remain table- and Metadata-driven. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | Constructed value / 构造结果 | - -> cap.load -*> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=None logout_redirect=None shell_css=`shell_css` layout=`layout` asset_version=`asset_version`* +We **[Load the native plugin required by this operation](cap.load())**. +Return *[Low-level app handle for advanced mounts](web_app_new(page=`page`, db=`db`, admin=`admin`, host=`host`, port=`port`, admin_prefix=`admin_prefix`, login_redirect=None, logout_redirect=None, shell_css=`shell_css`, layout=`layout`, asset_version=`asset_version`))*. ## static -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dir | text | required | filesystem directory | +| mount | text | "/static" | URL mount | + +| 返回 | 类型 | 说明 | |------|------|------| -| dir | text | filesystem directory | -| mount | text | URL mount | +| result | any | app handle | + +Use `dir`, `mount`="/static" as the inputs for this operation. Mount static files from `dir` at `mount`=/static on this app. Use for bridge scripts and assets referenced by Documents — not for dumping an HTML-only site tree that bypasses Artifact Documents. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | app handle | - -*> web_app_static app=`self` dir=`dir` mount=`mount`* +Return *[Mount static files from dir at mount=/static on this app](web_app_static(app=`self`, dir=`dir`, mount=`mount`))*. ## listen -Start listening with the already configured app host and port. Prefer serve for -root scanning; listen is for advanced app handles after manual route setup. - | 返回 | 类型 | 说明 | |------|------|------| | result | any | listen result | -*> web_listen app=`self`* +Start listening with the already configured app host and port. Prefer serve for +root scanning; listen is for advanced app handles after manual route setup. + +Return *[Start listening with the already configured app host and port. Prefer serve for root scanning; listen is for advanced app handles after manual route setup.](web_listen(app=`self`))*. ## gate -| 参数 | 类型 | 说明 | -|------|------|------| -| path | text | gated path | -| roles | any | roles | -| permissions | text | permissions | -| match | text | match mode | -| on_deny | text | deny behavior | -| exclude | any | exclusions | - -Attach an authorization gate on `path` for this app. Defaults: `roles`="admin", -`permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None . Auth -resources live in ext/security; this method only wires the gate onto the web -app surface. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | gated path | +| roles | any | "admin" | roles supplied by the caller | +| permissions | text | "" | Comma-separated permission names held by the current role or subject | +| match | text | "prefix" | match mode | +| on_deny | text | "forbid" | deny behavior | +| exclude | any | None | exclusions | | 返回 | 类型 | 说明 | |------|------|------| | result | any | app handle | -*> web_app_gate app=`self` path=`path` roles=`roles` permissions=`permissions` match=`match` on_deny=`on_deny` exclude=`exclude`* +Use `path`, `roles`="admin", `permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None as the inputs for this operation. + +Attach an authorization gate on `path` for this app. Defaults: `roles`="admin", + +`permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None . Auth +resources live in ext/security; this method only wires the gate onto the web +app surface. + +Return *[Attach an authorization gate on path for this app](web_app_gate(app=`self`, path=`path`, roles=`roles`, permissions=`permissions`, match=`match`, on_deny=`on_deny`, exclude=`exclude`))*. diff --git a/ext/web/布局/索引.mq.md b/ext/web/布局/索引.mq.md index 4d1b814..2b0105b 100644 --- a/ext/web/布局/索引.mq.md +++ b/ext/web/布局/索引.mq.md @@ -36,7 +36,7 @@ marqdo call ext/web/布局/索引.mq.md 分栏 '子节点=[{"type":"markdown","v 返回先拆布局、递归到 Markdown 叶子的工程约定。无参数; 规则是说明,不声称已静态审查某个文件。真正验收需要运行并检查站点。 -*> layout.rules* +完成后返回*[调用 rules](layout.rules())*。 ## 视图契约 @@ -47,72 +47,80 @@ marqdo call ext/web/布局/索引.mq.md 分栏 '子节点=[{"type":"markdown","v 返回五个公共列名。子块通过值列继续包含同样的 View 记录; 不增加第二种布局表方言,也不把任意属性名解释为 CSS。 -*> layout.view_schema* +完成后返回*[调用 view schema](layout.view_schema())*。 ## 合并节点 -| 参数 | 类型 | 说明 | -|------|------|------| -| 甲 | list | 第一组节点 | -| 乙 | list | 第二组节点 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 甲 | list | 必填 | 第一组节点 | +| 乙 | list | 必填 | 第二组节点 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 兄弟节点 | +这里使用`甲`、`乙`。 + 拼接 `甲` 与 `乙`,只保留顺序,不增加几何关系。 需要横向排列时使用分栏,需要上下分区时使用纵排。 -*> layout.merge_nodes a=`甲` b=`乙`* +完成后返回*[调用 merge nodes](layout.merge_nodes(a=`甲`, b=`乙`))*。 ## 纵排 -| 参数 | 类型 | 说明 | -|------|------|------| -| 子节点 | list | 子块列表 | -| 槽 | text | 父区域名 | -| 样式 | text | 可选类名 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 子节点 | list | 必填 | 子块列表 | +| 槽 | text | "" | 父区域名 | +| 样式 | text | "" | 可选类名 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 父容器节点 | +这里使用`子节点`、`槽`=""、`样式`=""。 + 为 `子节点` 声明一层上下顺序。默认 `槽`=""、`样式`=""。 父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表, 可以继续传给祖先组件或页面渲染,无需提前转为 HTML。 -*> layout.stack children=`子节点` slot=`槽` style=`样式`* +完成后返回*[调用 stack](layout.stack(children=`子节点`, slot=`槽`, style=`样式`))*。 ## 分栏 -| 参数 | 类型 | 说明 | -|------|------|------| -| 子节点 | list | 子块列表 | -| 槽 | text | 父区域名 | -| 样式 | text | 可选类名 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 子节点 | list | 必填 | 子块列表 | +| 槽 | text | "" | 父区域名 | +| 样式 | text | "" | 可选类名 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 父容器节点 | +这里使用`子节点`、`槽`=""、`样式`=""。 + 为 `子节点` 声明一层响应式多栏。默认 `槽`=""、`样式`=""。 父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表, 可以继续传给祖先组件或页面渲染,无需提前转为 HTML。 -*> layout.columns children=`子节点` slot=`槽` style=`样式`* +完成后返回*[调用 columns](layout.columns(children=`子节点`, slot=`槽`, style=`样式`))*。 ## 验收组件 -| 参数 | 类型 | 说明 | -|------|------|------| -| 名 | text | 组件名称 | -| 职责 | text | 单一职责描述 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | text | 必填 | 组件名称 | +| 职责 | text | 必填 | 单一职责描述 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 待人工或测试核对的清单 | +这里使用`名`、`职责`。 + 为 `名` 与 `职责` 返回待检查的条目。仅依据这两个文本无法证明组件合格, 所以结果明确标注为清单,调用者仍须检查文件内容与渲染结果,不自动发放通过标签。 -*> layout.accept_component name=`名` duty=`职责`* +完成后返回*[调用 accept component](layout.accept_component(name=`名`, duty=`职责`))*。 diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index 2ae72b6..d7de8fb 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -27,147 +27,165 @@ marqdo call ext/web/网页.mq.md 检视 '根="examples/web-layout-handbook"' --e ## 布局规则 -与 `布局.规则` 相同,便于只打开本文件的智能体。 - | 返回 | 类型 | 说明 | |------|------|------| | result | any | 布局规则映射 | -*> 布局.规则* +与 `布局.规则` 相同,便于只打开本文件的智能体。 + +完成后返回*[调用 规则](布局.规则())*。 ## 页面 -| 参数 | 类型 | 说明 | -|------|------|------| -| 标题 | text | 文档标题 | -| 路由 | text | 路径 | -| 方法 | text | HTTP 方法 | -| 正文 | text | Markdown 正文 | -| 节点 | any | View 表或 None | -| 数据源 | text | 表名 | -| 排序 | text | 如 -created_at | -| 条件 | text | col=val 列表 | - -构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 -`节点`=None、`数据源`=""、`排序`=""、`条件`=""。站点页面优先用 `类型: 网页` -Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点必须是统一 View 表, -不是 HTML。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标题 | text | "" | 文档标题 | +| 路由 | text | "/" | 路径 | +| 方法 | text | "GET" | HTTP 方法 | +| 正文 | text | "" | Markdown 正文 | +| 节点 | any | None | View 表或 None | +| 数据源 | text | "" | 表名 | +| 排序 | text | "" | 如 -created_at | +| 条件 | text | "" | col=val 列表 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 页面句柄 | -*> web.page title=`标题` route=`路由` method=`方法` body=`正文` nodes=`节点` data_source=`数据源` data_order=`排序` data_where=`条件`* +这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。 + +构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 + +`节点`=None、`数据源`=""、`排序`=""、`条件`=""。站点页面优先用 `类型: 网页` +Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点必须是统一 View 表, +不是 HTML。 + +完成后返回*[调用 page](web.page(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。 ## 路由 -| 参数 | 类型 | 说明 | -|------|------|------| -| 应用 | any | 应用句柄 | -| 路径 | text | URL 路径 | -| 方法 | text | HTTP 方法 | -| 页面 | any | Document 或 None | -| 函数 | text | Endpoint lib.member | -| 请求 | text | 请求体类型 | -| 响应 | text | 响应类型 | -| 鉴权 | text | 鉴权标签 | - -在 `应用` 上注册已声明 Document 或 Endpoint:`路径`、`方法`="GET"、`页面`=None、 -`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。不要隐式注册用户路由。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 应用 | any | 必填 | 应用句柄 | +| 路径 | text | 必填 | URL 路径 | +| 方法 | text | "GET" | HTTP 方法 | +| 页面 | any | None | Document 或 None | +| 函数 | text | "" | Endpoint lib.member | +| 请求 | text | "json" | 请求体类型 | +| 响应 | text | "json" | 响应类型 | +| 鉴权 | text | "" | 鉴权标签 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 路由结果 | -*> web.route app=`应用` path=`路径` method=`方法` page=`页面` fn=`函数` request=`请求` response=`响应` auth=`鉴权`* +这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。 + +在 `应用` 上注册已声明 Document 或 Endpoint:`路径`、`方法`="GET"、`页面`=None、 + +`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。不要隐式注册用户路由。 + +完成后返回*[调用 route](web.route(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`))*。 ## 渲染 -| 参数 | 类型 | 说明 | -|------|------|------| -| 文档 | any | Document 或 None | -| 节点 | any | View 表或 None | -| 正文 | text | Markdown | -| 标题 | text | 标题 | -| 数据库 | any | 可选 db | - -把 Document 或 View 节点渲染为 HTML(预览)。可选 `文档`=None、`节点`=None、 -`正文`=""、`标题`=""、`数据库`=None。输入应来自 Markdown/View,而不是手写 HTML -大字符串。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文档 | any | None | Document 或 None | +| 节点 | any | None | View 表或 None | +| 正文 | text | "" | Markdown | +| 标题 | text | "" | 调用方提供的标题 | +| 数据库 | any | None | 可选 db | | 返回 | 类型 | 说明 | |------|------|------| | result | any | HTML 或渲染结果 | -*> web.render doc=`文档` nodes=`节点` body=`正文` title=`标题` db=`数据库`* +这里使用`文档`=None、`节点`=None、`正文`=""、`标题`=""、`数据库`=None。 + +把 Document 或 View 节点渲染为 HTML(预览)。可选 `文档`=None、`节点`=None、 + +`正文`=""、`标题`=""、`数据库`=None。输入应来自 Markdown/View,而不是手写 HTML +大字符串。 + +完成后返回*[调用 render](web.render(doc=`文档`, nodes=`节点`, body=`正文`, title=`标题`, db=`数据库`))*。 ## 使用 -| 参数 | 类型 | 说明 | -|------|------|------| -| 应用 | any | 应用句柄 | -| 中间件 | any | 中间件表 | - -把 `中间件` 挂到 `应用`(表驱动)。禁止 `configure(...)` 垃圾抽屉。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 中间件 | any | 必填 | 中间件表 | +| 应用 | any | 必填 | 应用句柄 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 应用句柄 | -*> web.use app=`应用` middleware=`中间件`* +这里使用`中间件`、`应用`。 + +把 `中间件` 挂到 `应用`(表驱动)。禁止 `configure(...)` 垃圾抽屉。 + +完成后返回*[调用 use](web.use(app=`应用`, middleware=`中间件`))*。 ## 检视 -| 参数 | 类型 | 说明 | -|------|------|------| -| 应用 | any | 应用或 None | -| 根 | text | 离线扫描的站点目录 | - -返回 `{declared, system}` 路由表;可选 `应用`=None。 - -可选 `根`="",给出时扫描站点目录,不启动服务器。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 应用 | any | None | 应用或 None | +| 根 | text | "" | 离线扫描的站点目录 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 路由检视 | -*> web.inspect app=`应用` root=`根`* +这里使用`应用`=None、`根`=""。 + +返回 `{declared, system}` 路由表;可选 `应用`=None。 + +可选 `根`="",给出时扫描站点目录,不启动服务器。 + +完成后返回*[调用 inspect](web.inspect(app=`应用`, root=`根`))*。 ## 服务 -| 参数 | 类型 | 说明 | -|------|------|------| -| 根 | text | 站点根目录 | -| 主机 | text | 绑定主机 | -| 端口 | number | 端口 | -| 数据库 | any | 可选 db | -| 静态目录 | text | 静态资源 | -| 中间件 | any | 可选中间件 | - -扫描 `根`="." 下 `类型: 网页|端点` Artifact,注册声明路由并在 `主机`="127.0.0.1" -与 `端口`=18081 监听。可选 `数据库`=None、`静态目录`=""、`中间件`=None。站点 -目录应已按布局铁律拆好组件文件。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 根 | text | "." | 站点根目录 | +| 主机 | text | "127.0.0.1" | 绑定主机 | +| 端口 | number | 18081 | 调用方提供的端口 | +| 数据库 | any | None | 可选 db | +| 静态目录 | text | "" | 静态资源 | +| 中间件 | any | None | 可选中间件 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 服务结果 | -*> web.serve root=`根` host=`主机` port=`端口` db=`数据库` static_dir=`静态目录` middleware=`中间件`* +这里使用`根`="."、`主机`="127.0.0.1"、`端口`=18081、`数据库`=None、`静态目录`=""、`中间件`=None。 + +扫描 `根`="." 下 `类型: 网页|端点` Artifact,注册声明路由并在 `主机`="127.0.0.1" +与 `端口`=18081 监听。可选 `数据库`=None、`静态目录`=""、`中间件`=None。站点 +目录应已按布局铁律拆好组件文件。 + +完成后返回*[调用 serve](web.serve(root=`根`, host=`主机`, port=`端口`, db=`数据库`, static_dir=`静态目录`, middleware=`中间件`))*。 ## 客户端挂载 -| 参数 | 类型 | 说明 | -|------|------|------| -| 桥 | text | bridge 脚本路径 | -| wasm | text | wasm 路径 | -| 源 | text | 可选源 | -| 启动 | bool | 是否自动 boot | - -嵌入 WASM 桥,默认 `桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、 -`源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本路径 | +| wasm | text | "/static/marqdo_wasm.wasm" | wasm 路径 | +| 源 | text | "" | 可选源 | +| 启动 | bool | True | 是否自动 boot | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 挂载描述 | -*> web.client_embed bridge=`桥` wasm=`wasm` source=`源` boot=`启动`* +这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。 + +嵌入 WASM 桥,默认 `桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、 + +`源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。 + +完成后返回*[调用 client embed](web.client_embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。 diff --git a/ext/web/网页/客户端/索引.mq.md b/ext/web/网页/客户端/索引.mq.md index a87fd21..7e8ca05 100644 --- a/ext/web/网页/客户端/索引.mq.md +++ b/ext/web/网页/客户端/索引.mq.md @@ -24,51 +24,58 @@ marqdo call ext/web/网页/客户端/索引.mq.md 文本补丁 '选择器="#stat ## 挂载 -| 参数 | 类型 | 说明 | -|------|------|------| -| 桥 | text | bridge 脚本 URL | -| wasm | text | wasm URL | -| 源 | text | 可选源 | -| 启动 | bool | 自动启动 | - -返回加载官方浏览器桥的 HTML 片段。默认 `桥`="/static/marqdo-bridge.js"、 -`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。不是用 HTML 拼整页的 -借口。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本 URL | +| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL | +| 源 | text | "" | 可选源 | +| 启动 | bool | True | 自动启动 | | 返回 | 类型 | 说明 | |------|------|------| | result | text | script 标签 HTML | -*> client.embed bridge=`桥` wasm=`wasm` source=`源` boot=`启动`* +这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。 + +返回加载官方浏览器桥的 HTML 片段。默认 `桥`="/static/marqdo-bridge.js"、 + +`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。不是用 HTML 拼整页的 +借口。 + +完成后返回*[调用 embed](client.embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。 ## 文本补丁 -| 参数 | 类型 | 说明 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | text | 必填 | CSS 选择器 | +| 文本 | text | 必填 | 文本内容 | + +| 返回 | 类型 | 说明 | |------|------|------| -| 选择器 | text | CSS 选择器 | -| 文本 | text | 文本内容 | +| result | any | 效果表 | + +这里使用`选择器`、`文本`。 为选择器 `选择器` 构造 `set_text` 效果表,文本为 `文本`。 -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | 效果表 | - -*> client.text_patch sel=`选择器` text=`文本`* +完成后返回*[调用 text patch](client.text_patch(sel=`选择器`, text=`文本`))*。 ## 节点补丁 -| 参数 | 类型 | 说明 | -|------|------|------| -| 选择器 | text | CSS 选择器 | -| html | text | 可选 HTML | -| 属性 | any | 可选属性表 | -| 移除 | bool | 是否移除 | - -为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | text | 必填 | CSS 选择器 | +| html | text | "" | 可选 HTML | +| 属性 | any | None | 可选属性表 | +| 移除 | bool | False | 是否移除 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 效果表 | -*> client.dom_patch sel=`选择器` html=`html` attrs=`属性` remove=`移除`* +这里使用`选择器`、`html`=""、`属性`=None、`移除`=False。 + +为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。 + +完成后返回*[调用 dom patch](client.dom_patch(sel=`选择器`, html=`html`, attrs=`属性`, remove=`移除`))*。 diff --git a/ext/web/网页/文档对象模型/索引.mq.md b/ext/web/网页/文档对象模型/索引.mq.md index d812a3a..98a42d3 100644 --- a/ext/web/网页/文档对象模型/索引.mq.md +++ b/ext/web/网页/文档对象模型/索引.mq.md @@ -24,42 +24,48 @@ marqdo call ext/web/网页/文档对象模型/索引.mq.md 渲染 'dom=$body' -- ## 自Markdown -| 参数 | 类型 | 说明 | -|------|------|------| -| 文本 | text | Markdown 源 | - -把 Markdown `文本` 变成 `{kind:"markdown", text}`,供页面渲染。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文本 | text | 必填 | Markdown 源 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | DOM 映射 | -*> dom.from_markdown text=`文本`* +这里使用`文本`。 + +把 Markdown `文本` 变成 `{kind:"markdown", text}`,供页面渲染。 + +完成后返回*[调用 from markdown](dom.from_markdown(text=`文本`))*。 ## 原始 -| 参数 | 类型 | 说明 | -|------|------|------| -| html | text | 原始 HTML | - -逃逸舱 — 包装原始 `html`。仅当表驱动无法表达宿主约束时使用,并写明原因。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| html | text | 必填 | 原始 HTML | | 返回 | 类型 | 说明 | |------|------|------| | result | any | DOM 映射 kind=raw | -*> dom.raw html=`html`* +这里使用`html`。 + +逃逸舱 — 包装原始 `html`。仅当表驱动无法表达宿主约束时使用,并写明原因。 + +完成后返回*[调用 raw](dom.raw(html=`html`))*。 ## 渲染 -| 参数 | 类型 | 说明 | -|------|------|------| -| dom | any | 自Markdown 或 原始 的结果 | - -把 DOM 映射 `dom` 渲染为 HTML(须插件)。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dom | any | 必填 | 自Markdown 或 原始 的结果 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | HTML 文本 | -*> dom.render dom=`dom`* +这里使用`dom`。 + +把 DOM 映射 `dom` 渲染为 HTML(须插件)。 + +完成后返回*[调用 render](dom.render(dom=`dom`))*。 diff --git a/ext/web/网页/索引.mq.md b/ext/web/网页/索引.mq.md index 7434e9a..4db3eca 100644 --- a/ext/web/网页/索引.mq.md +++ b/ext/web/网页/索引.mq.md @@ -157,6 +157,12 @@ cargo test --locked --test gold ext_web -- --test-threads=1 返回建站流程与拆分终点,不执行文件操作,也不声称已经验收某个站点。 先建立区域树,再写父组件与 Markdown 叶子,最后按声明路由启动并测试。 +这张表返回工程步骤与停止条件,供作者安排实现顺序;它不会自动创建目录、拆分现有页面或替站点完成验收。先确定区域树,把首页拆成导航、主体与页脚。若页脚有品牌栏和链接栏,再拆子区域;链接有文档与社区两栏时继续拆分。父文件只表达一层布局,叶子只保留可直接阅读的 Markdown 内容。 + +区域树稳定后,首页用 Document 元数据声明路由并选择装配入口。其他页面各自声明路由,接口逻辑放到 Endpoint,使请求期间的业务计算与启动时的页面装配各有归属。不要在返回组件的函数里启动服务器,也不要把启动时运行一次的装配误当作每次请求都会执行的数据绑定。 + +实现过程中先离线预览,核对实际父子节点和区域内容;再从站点目录启动服务,检查首页、普通文档和 API 的真实响应。浏览器还需验证宽屏分栏与窄屏折叠。只看清单文本、返回固定 ready 或将整页 HTML 分成几个字符串文件,都不能证明已实现统一的文档架构。若某个块仍需独立内部排列,就返回布局拆分阶段继续细化。 + `workflow` = | key | value | @@ -171,7 +177,7 @@ cargo test --locked --test gold ext_web -- --test-threads=1 | step_G | compare preview and live output; test routes and browser geometry | | stopping_rule | one Markdown responsibility and no internal layout | -*workflow* +完成后返回*workflow*。 ## 布局规则 @@ -182,38 +188,42 @@ cargo test --locked --test gold ext_web -- --test-threads=1 复用布局模块的实践约定,保持一个真相源。无参数,不需要插件。 规则描述预期做法,实际站点仍需检查叶子、父关系与运行结果。 -*> 布局.规则* +完成后返回*[调用 规则](布局.规则())*。 ## 预览正文 -| 参数 | 类型 | 说明 | -|------|------|------| -| 正文 | text | Markdown content | -| 标题 | text | Document title | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 正文 | text | "" | Markdown content | +| 标题 | text | "Preview" | Document title | | 返回 | 类型 | 说明 | |------|------|------| | result | text | HTML document | +这里使用`正文`=""、`标题`="Preview"。 + 离线渲染 Markdown `正文`="",默认 `标题`="Preview"。 此工具只返回 HTML 文本,不写文件、不注册路由。复杂页面先拆布局, 不要用整页原生 HTML 字符串冒充正文。需要原生插件。 -*> 网页.渲染 正文=`正文` 标题=`标题`* +完成后返回*[调用 渲染](网页.渲染(正文=`正文`, 标题=`标题`))*。 ## 预览节点 -| 参数 | 类型 | 说明 | -|------|------|------| -| 节点 | list | Nested View rows | -| 标题 | text | Document title | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 节点 | list | 必填 | Nested View rows | +| 标题 | text | "Preview" | Document title | | 返回 | 类型 | 说明 | |------|------|------| | result | text | HTML document | +这里使用`节点`、`标题`="Preview"。 + 渲染已经按职责拆分的 `节点`,默认 `标题`="Preview"。 父节点的值继续持有子节点,叶子值为 Markdown;返回 HTML 不会启动服务。 与真实 Document 的装配使用同一渲染器,能检查双栏是否确实保留了层级。 -*> 网页.渲染 节点=`节点` 标题=`标题`* +完成后返回*[调用 渲染](网页.渲染(节点=`节点`, 标题=`标题`))*。 diff --git a/ext/web/网页/组件/索引.mq.md b/ext/web/网页/组件/索引.mq.md index 1d4816f..63cdd3f 100644 --- a/ext/web/网页/组件/索引.mq.md +++ b/ext/web/网页/组件/索引.mq.md @@ -25,68 +25,76 @@ marqdo call ext/web/网页/组件/索引.mq.md 合并 '甲=[{"type":"text","valu ## 节点 -| 参数 | 类型 | 说明 | -|------|------|------| -| 表 | any | View 表 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 表 | any | 必填 | View 表 | | 返回 | 类型 | 说明 | |------|------|------| -| result | any | Result | +| result | any | 原样返回输入 View 表,保留记录列表或列式表的实际形态 | + +这里使用`表`。 原样返回 `表`,保留已有恒等入口。可接受列式表或记录列表; 需要组合和嵌套时统一选择 @ 记录列表,让子表保持结构值而不是字符串。 -*> component.nodes table=`表`* +完成后返回*[调用 nodes](component.nodes(table=`表`))*。 ## 合并 -| 参数 | 类型 | 说明 | -|------|------|------| -| 甲 | list | 第一组节点记录 | -| 乙 | list | 第二组节点记录 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 甲 | list | 必填 | 第一组节点记录 | +| 乙 | list | 必填 | 第二组节点记录 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 有序兄弟节点 | +这里使用`甲`、`乙`。 + 拼接 `甲` 与 `乙`,保留顺序和内部父子关系。输入均为 @ 记录列表; 本工具不把平面节点变成两栏,需要双栏时再交给布局的分栏工具。 -*> component.merge a=`甲` b=`乙`* +完成后返回*[调用 merge](component.merge(a=`甲`, b=`乙`))*。 ## 正文 -| 参数 | 类型 | 说明 | -|------|------|------| -| 文本 | text | 普通 Markdown | -| 槽 | text | 区域名 | -| 样式 | text | 可选类名 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文本 | text | 必填 | 普通 Markdown | +| 槽 | text | "" | 区域名 | +| 样式 | text | "" | 可选类名 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 单个 Markdown 叶子 | +这里使用`文本`、`槽`=""、`样式`=""。 + 将 Markdown `文本` 包成叶子,默认 `槽`=""、`样式`=""。 不加载原生插件,输出仍为结构数据;标题、链接、列表与表格在渲染时处理。 叶子不关心自己位于页脚左栏还是其他位置,父组件负责几何关系。 -*> component.markdown text=`文本` slot=`槽` style=`样式`* +完成后返回*[调用 markdown](component.markdown(text=`文本`, slot=`槽`, style=`样式`))*。 ## 包裹 -| 参数 | 类型 | 说明 | -|------|------|------| -| 子节点 | list | 子块记录列表 | -| 种类 | text | 容器类型 | -| 槽 | text | 区域名 | -| 样式 | text | 可选类名 | +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 子节点 | list | 必填 | 子块记录列表 | +| 种类 | text | "column" | 容器类型 | +| 槽 | text | "" | 区域名 | +| 样式 | text | "" | 可选类名 | | 返回 | 类型 | 说明 | |------|------|------| | result | list | 包含子节点的父块 | +这里使用`子节点`、`种类`="column"、`槽`=""、`样式`=""。 + 将 `子节点` 放进一层父容器,默认 `种类`="column"、`槽`=""、`样式`=""。 几何类型为 row、column;语义类型包括 nav、header、footer、section、aside。 值单元格保留子表,不承载拼好的 HTML;构造器只生成结构,实际形状由渲染器检查。 -*> component.wrap children=`子节点` kind=`种类` slot=`槽` style=`样式`* +完成后返回*[调用 wrap](component.wrap(children=`子节点`, kind=`种类`, slot=`槽`, style=`样式`))*。 diff --git a/ext/web/网页/能力/索引.mq.md b/ext/web/网页/能力/索引.mq.md index df03211..8c4c083 100644 --- a/ext/web/网页/能力/索引.mq.md +++ b/ext/web/网页/能力/索引.mq.md @@ -23,11 +23,11 @@ marqdo call ext/web/网页/能力/索引.mq.md 加载 --effects plugin --json ## 加载 -通过 plugin.native_path 定位 ABI v2 web 动态库并 plugin.load。缺失时打印安装提 -示并以非零退出。无参数。 - | 返回 | 类型 | 说明 | |------|------|------| | result | any | 加载成功后为空 | -*> cap.load* +通过 plugin.native_path 定位 ABI v2 web 动态库并 plugin.load。缺失时打印安装提 +示并以非零退出。无参数。 + +完成后返回*[加载本操作依赖的原生插件](cap.load())*。 diff --git a/ext/web/网页/路由/索引.mq.md b/ext/web/网页/路由/索引.mq.md index 4845155..84844c6 100644 --- a/ext/web/网页/路由/索引.mq.md +++ b/ext/web/网页/路由/索引.mq.md @@ -24,54 +24,60 @@ marqdo call ext/web/网页/路由/索引.mq.md 注册 '路由=$route' --effects ## 新建 -| 参数 | 类型 | 说明 | -|------|------|------| -| 应用 | any | 应用句柄 | -| 路径 | text | URL 路径 | -| 方法 | text | HTTP 方法 | -| 页面 | any | Document 或 None | -| 函数 | text | Endpoint 成员 | -| 请求 | text | 请求体类型 | -| 响应 | text | 响应类型 | -| 鉴权 | text | 鉴权标签 | -| 类别 | text | 路由类别 | - -为 `应用` 在 `路径` 上构造路由句柄,`方法`="GET"。`页面`=None 或 `函数`="" 二 -选一。`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。本工具尚未注册——再 -调 `注册`,或用门面 `路由` 一步完成。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 应用 | any | 必填 | 应用句柄 | +| 路径 | text | 必填 | URL 路径 | +| 方法 | text | "GET" | HTTP 方法 | +| 页面 | any | None | Document 或 None | +| 函数 | text | "" | Endpoint 成员 | +| 请求 | text | "json" | 请求体类型 | +| 响应 | text | "json" | 响应类型 | +| 鉴权 | text | "" | 鉴权标签 | +| 类别 | text | "" | 路由类别 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 路由句柄 | -*> route.new app=`应用` path=`路径` method=`方法` page=`页面` fn=`函数` request=`请求` response=`响应` auth=`鉴权` class=`类别`* +这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。 + +为 `应用` 在 `路径` 上构造路由句柄,`方法`="GET"。`页面`=None 或 `函数`="" 二 +选一。`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。本工具尚未注册——再 +调 `注册`,或用门面 `路由` 一步完成。 + +完成后返回*[调用 new](route.new(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`, class=`类别`))*。 ## 注册 -| 参数 | 类型 | 说明 | -|------|------|------| -| 路由 | any | 路由句柄 | -| 应用 | any | 应用或 None | - -把路由句柄 `路由` 注册到应用;可选 `应用`=None 时用句柄内保存的应用。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路由 | any | 必填 | 路由句柄 | +| 应用 | any | None | 应用或 None | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 注册结果 | -*> route.register route=`路由` app=`应用`* +这里使用`路由`、`应用`=None。 + +把路由句柄 `路由` 注册到应用;可选 `应用`=None 时用句柄内保存的应用。 + +完成后返回*[调用 register](route.register(route=`路由`, app=`应用`))*。 ## 使用 -| 参数 | 类型 | 说明 | -|------|------|------| -| 路由 | any | 路由句柄 | -| 中间件 | any | 中间件表 | - -给路由句柄 `路由` 挂上中间件表 `中间件`。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路由 | any | 必填 | 路由句柄 | +| 中间件 | any | 必填 | 中间件表 | | 返回 | 类型 | 说明 | |------|------|------| -| result | any | 结果 | +| result | any | 带 middleware 字段的路由记录;此步骤不注册或启动路由 | -*> route.use route=`路由` middleware=`中间件`* +这里使用`路由`、`中间件`。 + +给路由句柄 `路由` 挂上中间件表 `中间件`。 + +完成后返回*[调用 use](route.use(route=`路由`, middleware=`中间件`))*。 diff --git a/ext/web/网页/页面/索引.mq.md b/ext/web/网页/页面/索引.mq.md index 044ec51..d33d229 100644 --- a/ext/web/网页/页面/索引.mq.md +++ b/ext/web/网页/页面/索引.mq.md @@ -24,39 +24,44 @@ marqdo call ext/web/网页/页面/索引.mq.md 渲染 '页面=$pg' --effects plu ## 新建 -| 参数 | 类型 | 说明 | -|------|------|------| -| 标题 | text | 文档标题 | -| 路由 | text | 路径 | -| 方法 | text | HTTP 方法 | -| 正文 | text | Markdown 正文 | -| 节点 | any | View 表或 None | -| 数据源 | text | 表名 | -| 排序 | text | 排序键 | -| 条件 | text | 过滤 | - -构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 -`节点`=None、`数据源`=""、`排序`=""、`条件`=""。节点必须是统一 View 表。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标题 | text | "" | 文档标题 | +| 路由 | text | "/" | 路径 | +| 方法 | text | "GET" | HTTP 方法 | +| 正文 | text | "" | Markdown 正文 | +| 节点 | any | None | View 表或 None | +| 数据源 | text | "" | 表名 | +| 排序 | text | "" | 排序键 | +| 条件 | text | "" | 过滤 | | 返回 | 类型 | 说明 | |------|------|------| | result | any | 页面句柄 | -*> page.new title=`标题` route=`路由` method=`方法` body=`正文` nodes=`节点` data_source=`数据源` data_order=`排序` data_where=`条件`* +这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。 + +构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、 + +`节点`=None、`数据源`=""、`排序`=""、`条件`=""。节点必须是统一 View 表。 + +完成后返回*[调用 new](page.new(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。 ## 渲染 -| 参数 | 类型 | 说明 | -|------|------|------| -| 页面 | any | Document 句柄 | -| 节点 | any | View 表或 None | -| 数据库 | any | 可选 db | - -渲染 Document 句柄 `页面`。可选 `节点`=None、`数据库`=None。不要把手写 HTML 当 -作页面壳。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 页面 | any | 必填 | Document 句柄 | +| 节点 | any | None | View 表或 None | +| 数据库 | any | None | 可选 db | | 返回 | 类型 | 说明 | |------|------|------| | result | any | HTML 或渲染结果 | -*> page.render page=`页面` nodes=`节点` db=`数据库`* +这里使用`页面`、`节点`=None、`数据库`=None。 + +渲染 Document 句柄 `页面`。可选 `节点`=None、`数据库`=None。不要把手写 HTML 当 +作页面壳。 + +完成后返回*[调用 render](page.render(page=`页面`, nodes=`节点`, db=`数据库`))*。 diff --git a/lib/archive.mq.md b/lib/archive.mq.md new file mode 100644 index 0000000..57863f3 --- /dev/null +++ b/lib/archive.mq.md @@ -0,0 +1,68 @@ +--- +markup: occlusion +--- + +Optional ZIP tasks: native defaults include ZIP; minimal/browser builds report unavailable. Returns Result. + +ZIP tasks are optional native capabilities, with no standalone plugin to install. +The pack/unpack contracts below define both operations. Both return +Result and require fs.write. Source and destination paths stay under the granted +root; output must not already exist. Extraction preflights paths, duplicate +entries, symlinks and the uncompressed byte limit before creating its directory. +Failed extraction removes only the newly-created destination. Minimal/browser +builds report unavailable; they never pretend to have written an archive. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. + +Implementation: [src/host/archive.rs](../src/host/archive.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + +## pack + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path; archive packing expects a directory | +| dest | text | required | Destination path; overwrite is allowed only where documented | +| max_bytes | number | 1073741824 | Maximum bytes read or expanded; exceeding it fails | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Result containing the count of archived regular files, or a structured error | + +Use `src`, `dest`, `max_bytes`=1073741824 as the inputs for this operation. + +Effects: fs.write. + +For this example, set MQ_WORK to an existing disposable directory with regular files in an input subdirectory. bundle.zip and output must not exist. Keep or clean the produced artifacts explicitly. + +```sh +marqdo call lib/archive.mq.md pack 'src="input"' 'dest="bundle.zip"' --fs-root "$MQ_WORK" --effects fs.write --json +marqdo call lib/archive.mq.md unpack 'src="bundle.zip"' 'dest="output"' --fs-root "$MQ_WORK" --effects fs.write --json +``` + +Destination must not exist. Caps total uncompressed bytes and 100000 entries; rejects symlinks and escaping paths. Pack includes regular files; failed unpack removes only its newly-created destination. + +Return *[Pack regular files into ZIP without overwriting an existing destination](> host_zip_pack src=`src` dest=`dest` max_bytes=`max_bytes`)*. + +## unpack + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path; archive packing expects a directory | +| dest | text | required | Destination path; overwrite is allowed only where documented | +| max_bytes | number | 1073741824 | Maximum bytes read or expanded; exceeding it fails | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Result containing the extracted entry count, or a structured error | + +Use `src`, `dest`, `max_bytes`=1073741824 as the inputs for this operation. + +Effects: fs.write. + +Destination must not exist. Caps total uncompressed bytes and 100000 entries; rejects symlinks and escaping paths. Pack includes regular files; failed unpack removes only its newly-created destination. + +Return *[Validate and extract ZIP entries without escaping the root or overwriting a destination](> host_zip_unpack src=`src` dest=`dest` max_bytes=`max_bytes`)*. diff --git a/lib/browser.mq.md b/lib/browser.mq.md index a8e9fb4..3fcf92d 100644 --- a/lib/browser.mq.md +++ b/lib/browser.mq.md @@ -10,107 +10,255 @@ import: Readable browser effect helpers for WASM clients. Prefer GFM tables + these helpers; do not build effects with json.set chains. +Build browser effects as ordinary structured values. + +Behavior and limits: Constructing an effect is pure; the official WASM bridge performs it in a browser. Native construction does not prove a DOM update occurred. Keep business logic in Marqdo. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [crates/marqdo-wasm/js/marqdo-bridge.js](../crates/marqdo-wasm/js/marqdo-bridge.js) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## set_text - + `sel` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_text effect map for the official bridge | + +Use `sel`, `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/browser.mq.md set_text 'sel="#status"' 'text="Ready"' --effects none --json +``` Build set_text effect map for the official bridge. -**`m` = > table.put in=None at=sel value=text** -*> table.put in=None at="set_text" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`text`))**. +Return *[Set the set_text field in the new record](table.put(in=None, at="set_text", value=`m`))*. ## set_html - + `sel` - + `html` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| html | any | required | HTML fragment; use set_text for ordinary untrusted text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_html effect map | + +Use `sel`, `html` as the inputs for this operation. + +Effects: pure. Build set_html effect map. -**`m` = > table.put in=None at=sel value=html** -*> table.put in=None at="set_html" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`html`))**. +Return *[Set the set_html field in the new record](table.put(in=None, at="set_html", value=`m`))*. ## set_value - + `sel` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_value effect map | + +Use `sel`, `value` as the inputs for this operation. + +Effects: pure. Build set_value effect map. -**`m` = > table.put in=None at=sel value=value** -*> table.put in=None at="set_value" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`value`))**. +Return *[Set the set_value field in the new record](table.put(in=None, at="set_value", value=`m`))*. ## set_class - + `sel` - + `class` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| class | any | required | Space-separated CSS class names | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_class effect map | + +Use `sel`, `class` as the inputs for this operation. + +Effects: pure. Build set_class effect map. -**`m` = > table.put in=None at=sel value=class** -*> table.put in=None at="set_class" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. +Return *[Set the set_class field in the new record](table.put(in=None, at="set_class", value=`m`))*. ## add_class - + `sel` - + `class` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| class | any | required | Space-separated CSS class names | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build add_class effect map (classList.add; space-separated names OK) | + +Use `sel`, `class` as the inputs for this operation. + +Effects: pure. Build add_class effect map (classList.add; space-separated names OK). -**`m` = > table.put in=None at=sel value=class** -*> table.put in=None at="add_class" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. +Return *[Set the add_class field in the new record](table.put(in=None, at="add_class", value=`m`))*. ## remove_class - + `sel` - + `class` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| class | any | required | Space-separated CSS class names | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build remove_class effect map | + +Use `sel`, `class` as the inputs for this operation. + +Effects: pure. Build remove_class effect map. -**`m` = > table.put in=None at=sel value=class** -*> table.put in=None at="remove_class" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. +Return *[Set the remove_class field in the new record](table.put(in=None, at="remove_class", value=`m`))*. ## toggle_class - + `sel` - + `class` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| class | any | required | Space-separated CSS class names | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build toggle_class effect map | + +Use `sel`, `class` as the inputs for this operation. + +Effects: pure. Build toggle_class effect map. -**`m` = > table.put in=None at=sel value=class** -*> table.put in=None at="toggle_class" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`class`))**. +Return *[Set the toggle_class field in the new record](table.put(in=None, at="toggle_class", value=`m`))*. ## set_style - + `sel` - + `style` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| style | any | required | CSS property/value record for the target element | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_style effect map; style is a map of CSS properties or a cssText string | + +Use `sel`, `style` as the inputs for this operation. + +Effects: pure. Build set_style effect map; style is a map of CSS properties or a cssText string. -**`m` = > table.put in=None at=sel value=style** -*> table.put in=None at="set_style" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`style`))**. +Return *[Set the set_style field in the new record](table.put(in=None, at="set_style", value=`m`))*. ## set_attr - + `sel` - + `attrs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| attrs | any | required | HTML attribute/value record for the target element | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build set_attr effect map; attrs is usually a small map of attribute names to values | + +Use `sel`, `attrs` as the inputs for this operation. + +Effects: pure. Build set_attr effect map; attrs is usually a small map of attribute names to values. -**`m` = > table.put in=None at=sel value=attrs** -*> table.put in=None at="set_attr" value=m* +We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`attrs`))**. +Return *[Set the set_attr field in the new record](table.put(in=None, at="set_attr", value=`m`))*. ## wrap - + `key` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Single-key effect map wrapper | + +Use `key`, `value` as the inputs for this operation. + +Effects: pure. Single-key effect map wrapper. -*> table.put in=None at=key value=value* +Return *[Return the updated structured value](table.put(in=None, at=`key`, value=`value`))*. ## merge - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First browser effect record | +| b | any | required | Browser effect record to merge over a | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Merge two effect maps; right-hand keys win | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. Merge two effect maps; right-hand keys win. -*> table.merge a=`a` b=`b`* +Return *[Merge](table.merge(a=`a`, b=`b`))*. ## canvas - + `sel` - + `commands` - + `clear`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| commands | any | required | Ordered list of canvas drawing commands | +| clear | any | True | Whether the canvas is cleared before drawing commands | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build canvas effect; commands is usually an @ GFM table | + +Use `sel`, `commands`, `clear`=True as the inputs for this operation. + +Effects: pure. Build canvas effect; commands is usually an @ GFM table. @@ -120,34 +268,58 @@ Build canvas effect; commands is usually an @ GFM table. |-----|-------|----------| | `sel` | `clear` | `commands` | -*> table.put in=None at="canvas" value=spec* +Return *[Set the canvas field in the new record](table.put(in=None, at="canvas", value=`spec`))*. ## audio - + `op`="play" - + `id`="default" - + `src`="" - + `freq`=None - + `ms`=None - + `sel`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| op | any | "play" | Audio command: play, pause or stop | +| id | any | "default" | Audio channel identifier | +| src | text | "" | Audio URL, or beep for a synthesized tone | +| freq | any | None | Oscillator frequency in hertz | +| ms | any | None | Duration or delay in milliseconds | +| sel | any | "" | CSS selector of the target browser element | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build audio effect for the bridge | + +Use `op`="play", `id`="default", `src`="", `freq`=None, `ms`=None, `sel`="" as the inputs for this operation. + +Effects: pure. Build audio effect for the bridge. -**`spec` = > table.put in=None at="op" value=op** -**`spec` = > table.put in=`spec` at="id" value=id** +This function returns an effect record and plays no sound immediately. The bridge selects a source, synthesized frequency or audio element; browsers may require a prior user gesture. + +We retain **`spec` = [Set the op field in the new record](table.put(in=None, at="op", value=`op`))**. +We retain **`spec` = [Set the id field in the new record](table.put(in=`spec`, at="id", value=`id`))**. 1. `src` != "" - **`spec` = > table.put in=`spec` at="src" value=src** + We retain **`spec` = [Set the src field in the new record](table.put(in=`spec`, at="src", value=`src`))**. 1. `freq` != None - **`spec` = > table.put in=`spec` at="freq" value=freq** + We retain **`spec` = [Set the freq field in the new record](table.put(in=`spec`, at="freq", value=`freq`))**. 1. `ms` != None - **`spec` = > table.put in=`spec` at="ms" value=ms** + We retain **`spec` = [Set the ms field in the new record](table.put(in=`spec`, at="ms", value=`ms`))**. 1. `sel` != "" - **`spec` = > table.put in=`spec` at="sel" value=sel** -*> table.put in=None at="audio" value=spec* + We retain **`spec` = [Set the sel field in the new record](table.put(in=`spec`, at="sel", value=`sel`))**. +Return *[Set the audio field in the new record](table.put(in=None, at="audio", value=`spec`))*. ## read_file - + `sel` - + `then` - + `as`="text" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | +| as | any | "text" | File content representation expected by the browser bridge | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build read_file effect | + +Use `sel`, `then`, `as`="text" as the inputs for this operation. + +Effects: pure. Build read_file effect. @@ -157,32 +329,80 @@ Build read_file effect. |-----|----|------| | `sel` | `as` | `then` | -*> table.put in=None at="read_file" value=spec* +Return *[Set the read_file field in the new record](table.put(in=None, at="read_file", value=`spec`))*. ## observe - + `specs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| specs | any | required | Effect specifications; use a record or an @ row-record list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build observe effect; specs is one map or an @ list of maps | + +Use `specs` as the inputs for this operation. + +Effects: pure. Build observe effect; specs is one map or an @ list of maps. -*> table.put in=None at="observe" value=specs* +Return *[Set the observe field in the new record](table.put(in=None, at="observe", value=`specs`))*. ## unobserve - + `specs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| specs | any | required | Effect specifications; use a record or an @ row-record list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build unobserve effect; specs is a map or @ list with id | + +Use `specs` as the inputs for this operation. + +Effects: pure. Build unobserve effect; specs is a map or @ list with id. -*> table.put in=None at="unobserve" value=specs* +Return *[Set the unobserve field in the new record](table.put(in=None, at="unobserve", value=`specs`))*. ## focus - + `sel` -focus. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| sel | any | required | CSS selector of the target browser element | -*> table.put in=None at="focus" value=sel* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build a focus effect for the selected element; the browser bridge applies it after the handler returns | + +Use `sel` as the inputs for this operation. + +Effects: pure. + +Build a focus effect for the selected element; the browser bridge applies it after the handler returns. + +Build the focus effect record. The browser bridge consumes this record; this function itself does not change the page. + +Return *[Set the focus field in the new record](table.put(in=None, at="focus", value=`sel`))*. ## navigate - + `url` - + `replace`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| replace | any | False | Whether navigation replaces the current history entry | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the navigate effect record | + +Use `url`, `replace`=False as the inputs for this operation. + +Effects: pure. + +Build the navigate effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -190,13 +410,24 @@ focus. |-----|---------| | `url` | `replace` | -*> table.put in=None at="navigate" value=spec* +Return *[Set the navigate field in the new record](table.put(in=None, at="navigate", value=`spec`))*. ## store_set - + `key` - + `value` - + `scope`="memory" - + `then`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | +| value | any | required | Value to transform or store, without mutating the input | +| scope | any | "memory" | Storage scope: memory, local or session | +| then | any | "" | Marqdo callback name for the bridge result; empty text omits callback | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | In-memory (or local/session) key write for SPA client state | + +Use `key`, `value`, `scope`="memory", `then`="" as the inputs for this operation. + +Effects: pure. In-memory (or local/session) key write for SPA client state. Prefer `scope=memory` for tab-local app state. Optional `then` is called after the write with `{ok, op, key, scope}`. @@ -204,31 +435,53 @@ Optional `then` is called after the write with `{ok, op, key, scope}`. `spec` = | op | key | value | scope | -|----|-----|-------|-------| +| ---- | ----- | ------- | ------- | | set | `key` | `value` | `scope` | 1. `then` != "" - **`spec` = > table.put in=spec at="then" value=then** -*> table.put in=None at="storage" value=spec* + We retain **`spec` = [Set the then field in the new record](table.put(in=`spec`, at="then", value=`then`))**. +Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. ## store_get - + `key` - + `then` - + `scope`="memory" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | +| scope | any | "memory" | Storage scope: memory, local or session | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Read a key then call `then` with `{ok, value, found, key, scope}` | + +Use `key`, `then`, `scope`="memory" as the inputs for this operation. + +Effects: pure. Read a key then call `then` with `{ok, value, found, key, scope}`. `spec` = | op | key | then | scope | -|----|-----|------|-------| +| ---- | ----- | ------ | ------- | | get | `key` | `then` | `scope` | -*> table.put in=None at="storage" value=spec* +Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. ## spa_goto - + `url` - + `replace`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| replace | any | False | Whether navigation replaces the current history entry | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | SPA navigation: `history.pushState` / `replaceState` via bridge `navigate` effect | + +Use `url`, `replace`=False as the inputs for this operation. + +Effects: pure. SPA navigation: `history.pushState` / `replaceState` via bridge `navigate` effect. @@ -238,19 +491,45 @@ SPA navigation: `history.pushState` / `replaceState` via bridge `navigate` effec |-----|---------| | `url` | `replace` | -*> table.put in=None at="navigate" value=spec* +Return *[Set the navigate field in the new record](table.put(in=None, at="navigate", value=`spec`))*. ## storage - + `spec` -storage. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| spec | any | required | Storage operation record: op, key, scope and optional value/then | -*> table.put in=None at="storage" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Wrap one storage specification as a browser effect; the bridge handles op, key, value, scope and then | + +Use `spec` as the inputs for this operation. + +Effects: pure. + +Wrap one storage specification as a browser effect; the bridge handles op, key, value, scope and then. + +Build the storage effect record. The browser bridge consumes this record; this function itself does not change the page. + +Return *[Set the storage field in the new record](table.put(in=None, at="storage", value=`spec`))*. ## interval - + `ms` - + `then` - + `id`="default" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ms | any | required | Duration or delay in milliseconds | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | +| id | any | "default" | Timer identifier, later passed to clear_interval | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the interval effect record | + +Use `ms`, `then`, `id`="default" as the inputs for this operation. + +Effects: pure. + +Build the interval effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -258,20 +537,46 @@ storage. |----|------|----| | `ms` | `then` | `id` | -*> table.put in=None at="interval" value=spec* +Return *[Set the interval field in the new record](table.put(in=None, at="interval", value=`spec`))*. ## clear_interval - + `id`="default" -clear_interval. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | "default" | Identifier returned by the corresponding create/spawn operation | -**`spec` = > table.put in=None at="id" value=id** -*> table.put in=None at="clear_interval" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build a cancellation effect using the same identifier previously supplied to interval | + +Use `id`="default" as the inputs for this operation. + +Effects: pure. + +Build a cancellation effect using the same identifier previously supplied to interval. + +Build the clear_interval effect record. The browser bridge consumes this record; this function itself does not change the page. + +We retain **`spec` = [Set the id field in the new record](table.put(in=None, at="id", value=`id`))**. +Return *[Set the clear_interval field in the new record](table.put(in=None, at="clear_interval", value=`spec`))*. ## fetch - + `url` - + `then` - + `method`="GET" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | +| method | text | "GET" | HTTP method, for example GET or POST | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the fetch effect record | + +Use `url`, `then`, `method`="GET" as the inputs for this operation. + +Effects: pure. + +Build the fetch effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -279,11 +584,24 @@ clear_interval. |-----|------|--------| | `url` | `then` | `method` | -*> table.put in=None at="fetch" value=spec* +Return *[Set the fetch field in the new record](table.put(in=None, at="fetch", value=`spec`))*. ## fetch_all - + `requests` - + `then` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| requests | any | required | Ordered list of browser request specification records | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the fetch_all effect record | + +Use `requests`, `then` as the inputs for this operation. + +Effects: pure. + +Build the fetch_all effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -291,11 +609,24 @@ clear_interval. |----------|------| | `requests` | `then` | -*> table.put in=None at="fetch_all" value=spec* +Return *[Set the fetch_all field in the new record](table.put(in=None, at="fetch_all", value=`spec`))*. ## after - + `ms` - + `then` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ms | any | required | Duration or delay in milliseconds | +| then | any | required | Marqdo callback name for the bridge result; empty text omits callback | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the after effect record | + +Use `ms`, `then` as the inputs for this operation. + +Effects: pure. + +Build the after effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -303,27 +634,66 @@ clear_interval. |----|------| | `ms` | `then` | -*> table.put in=None at="after" value=spec* +Return *[Set the after field in the new record](table.put(in=None, at="after", value=`spec`))*. ## ws - + `spec` -ws. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| spec | any | required | One bridge effect specification record | -*> table.put in=None at="ws" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Wrap a WebSocket operation specification for the browser bridge; this function opens no native socket | + +Use `spec` as the inputs for this operation. + +Effects: pure. + +Wrap a WebSocket operation specification for the browser bridge; this function opens no native socket. + +Build the ws effect record. The browser bridge consumes this record; this function itself does not change the page. + +Return *[Set the ws field in the new record](table.put(in=None, at="ws", value=`spec`))*. ## clipboard - + `text` -clipboard. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | -**`spec` = > table.put in=None at="text" value=text** -*> table.put in=None at="clipboard" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build a clipboard effect from the text; browser permissions and user-gesture requirements apply when consumed | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Build a clipboard effect from the text; browser permissions and user-gesture requirements apply when consumed. + +Build the clipboard effect record. The browser bridge consumes this record; this function itself does not change the page. + +We retain **`spec` = [Set the text field in the new record](table.put(in=None, at="text", value=`text`))**. +Return *[Set the clipboard field in the new record](table.put(in=None, at="clipboard", value=`spec`))*. ## download - + `body` - + `filename`="download.txt" - + `mime`="text/plain;charset=utf-8" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | any | required | Request body, or replacement text for document operations | +| filename | any | "download.txt" | Suggested download filename | +| mime | any | "text/plain;charset=utf-8" | Content MIME type | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Build the download effect record | + +Use `body`, `filename`="download.txt", `mime`="text/plain;charset=utf-8" as the inputs for this operation. + +Effects: pure. + +Build the download effect record. The browser bridge consumes this record; this function itself does not change the page. `spec` = @@ -331,4 +701,4 @@ clipboard. |------|----------|------| | `body` | `filename` | `mime` | -*> table.put in=None at="download" value=spec* +Return *[Set the download field in the new record](table.put(in=None, at="download", value=`spec`))*. diff --git a/lib/bytes.mq.md b/lib/bytes.mq.md new file mode 100644 index 0000000..cddaf8b --- /dev/null +++ b/lib/bytes.mq.md @@ -0,0 +1,132 @@ +--- +markup: occlusion +title: bytes +--- + +Bytes are ordinary records with `_type: bytes` and `base64`, portable across CLI, JSON, plugins and sessions; no new language type. + +Carry arbitrary binary data through ordinary portable records. + +Behavior and limits: A bytes record contains _type=bytes and canonical Base64. Byte offsets are zero-based; UTF-8 decoding is explicit and strict. read_chunk has no long-lived file handle. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/encoding.rs](../src/host/encoding.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + +## from_text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Encode text as UTF-8 bytes | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/bytes.mq.md from_text 'text="Marqdo"' --effects none --json +``` + +Encode text as UTF-8 bytes. + +Return *[Encode text as UTF-8 bytes](> host_bytes_from_text text=`text`)*. + +## from_base64 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Decode Base64 as arbitrary bytes; no UTF-8 assumption | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Decode Base64 as arbitrary bytes; no UTF-8 assumption. + +Return *[Decode Base64 as arbitrary bytes; no UTF-8 assumption](> host_bytes_from_base64 text=`text`)*. + +## to_text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | map | required | Portable bytes record containing _type=bytes and base64 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Decode UTF-8 strictly; invalid byte sequences fail | + +Use `data` as the inputs for this operation. + +Effects: pure. + +Decode UTF-8 strictly; invalid byte sequences fail. + +Return *[Decode UTF-8 strictly; invalid byte sequences fail](> host_bytes_to_text data=`data`)*. + +## to_base64 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | map | required | Portable bytes record containing _type=bytes and base64 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Return canonical padded Base64 | + +Use `data` as the inputs for this operation. + +Effects: pure. + +Return canonical padded Base64. + +Return *[Return canonical padded Base64](> host_bytes_to_base64 data=`data`)*. + +## len + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | map | required | Portable bytes record containing _type=bytes and base64 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Count bytes, not characters | + +Use `data` as the inputs for this operation. + +Effects: pure. + +Count bytes, not characters. + +Return *[Count bytes, not characters](> host_bytes_len data=`data`)*. + +## slice + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| data | map | required | Portable bytes record containing _type=bytes and base64 | +| start | number | required | Inclusive zero-based slice start | +| end | number | required | Exclusive zero-based slice end; None selects through the end | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Return a zero-based half-open byte slice; endpoints clamp to length | + +Use `data`, `start`, `end` as the inputs for this operation. + +Effects: pure. + +Return a zero-based half-open byte slice; endpoints clamp to length. + +Return *[Return a zero-based half-open byte slice; endpoints clamp to length](> host_bytes_slice data=`data` start=`start` end=`end`)*. diff --git a/lib/cli.mq.md b/lib/cli.mq.md index c6b673f..d5a021e 100644 --- a/lib/cli.mq.md +++ b/lib/cli.mq.md @@ -6,11 +6,38 @@ description: Parse argv flags (Mid M5). --key value / --key=value / --flag; posi Parse process argv into a map. Flags and positionals (under _). +Convert argv tokens to a small flag/positional map. + +Behavior and limits: Values stay text; bare flags become booleans and positionals live under _. Omitted args use host argv. This is a small parser, not an argparse schema system. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/cli.rs](../src/host/cli.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## parse - + `args`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| args | any | None | List of argv tokens; None reads the current host argv | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Parse --key value / --key=value / --flag | + +Use `args`=None as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/cli.mq.md parse 'args=["report","--count=3","--quiet"]' --effects none --json +``` Parse --key value / --key=value / --flag. A bare --flag must not be followed by a non-option token if you need it as boolean (put flags last, or use --flag=true). Positionals land under _. Omit args to use process argv. Caller: [cli.parse] -*> host_cli_parse args=`args`* +Return *[Parse --key value / --key=value / --flag](> host_cli_parse args=`args`)*. diff --git a/lib/csv.mq.md b/lib/csv.mq.md index a0793fd..7a36592 100644 --- a/lib/csv.mq.md +++ b/lib/csv.mq.md @@ -6,18 +6,74 @@ description: RFC4180-ish CSV parse/stringify (Mid M4). First row = headers → l CSV parse and stringify. First row is headers; rows become a list of maps. +Parse and serialize header-based CSV records. + +Behavior and limits: Parsed cells are text; use table.cast for explicit types. stringify follows the first row field order. Use row records, not a column map. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/csv.rs](../src/host/csv.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Parse CSV text into a list of maps | + +Use `text` as the inputs for this operation. + +Effects: pure. Parse CSV text into a list of maps. Caller: [csv.parse] text=`raw` -*> host_csv_parse text=`text`* +Return *[Parse CSV text into a list of maps](> host_csv_parse text=`text`)*. ## stringify - + `rows` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | list | required | List of row records | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Serialize a list of maps to CSV text | + +Use `rows` as the inputs for this operation. + +Effects: pure. Serialize a list of maps to CSV text. -*> host_csv_stringify rows=`rows`* +Return *[Serialize a list of maps to CSV text](> host_csv_stringify rows=`rows`)*. + +## try_parse + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Return {ok,value,error}; parse failures are recoverable data | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/csv.mq.md try_parse 'text="name,n"' --effects none --json +``` + +Return {ok,value,error}; parse failures are recoverable data. + +Return *[Return {ok,value,error}; parse failures are recoverable data](> host_try_csv_parse text=`text`)*. diff --git a/lib/datetime.mq.md b/lib/datetime.mq.md index 9c8a25c..7ea5879 100644 --- a/lib/datetime.mq.md +++ b/lib/datetime.mq.md @@ -1,63 +1,199 @@ --- markup: occlusion title: lib/datetime -description: Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets + a few IANA aliases. +description: Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets and embedded IANA timezone/DST rules. --- -Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets + a few IANA aliases. +Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets and embedded IANA timezone/DST rules. + +Convert timestamps, IANA zones and local calendar dates. + +Behavior and limits: zone remains the numeric offset; timezone preserves the IANA identity. add uses elapsed seconds; add_calendar preserves local wall time. DST gaps fail; folds require an explicit policy. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/datetime.rs](../src/host/datetime.rs)、[src/host/data_ops.rs](../src/host/data_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. ## now +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Read the clock and return the current UTC datetime record | + +Effects: time.read. + Current UTC moment map. -*> host_datetime_now* +Read the clock and return the current UTC datetime record. + +Return *[Read the clock and return the current UTC datetime record](host_datetime_now())*. ## from_unix - + `unix` - + `zone`=None -from_unix. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| unix | number | required | Unix timestamp in seconds | +| zone | any | None | Fixed offset or named timezone accepted by this operation | -*> host_datetime_from_unix unix=`unix` zone=`zone`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Convert Unix seconds to a datetime record in the selected zone; None means UTC | + +Use `unix`, `zone`=None as the inputs for this operation. + +Effects: pure. + +Convert Unix seconds to a datetime record in the selected zone; None means UTC. + +Return *[Convert Unix seconds to a datetime record in the selected zone; None means UTC](> host_datetime_from_unix unix=`unix` zone=`zone`)*. ## to_unix - + `dt` -to_unix. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dt | any | required | Datetime record returned by this library, not formatted text | -*> host_datetime_to_unix dt=`dt`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Read unix seconds from a datetime record; formatting and timezone do not change the instant | + +Use `dt` as the inputs for this operation. + +Effects: pure. + +Read unix seconds from a datetime record; formatting and timezone do not change the instant. + +Return *[Read unix seconds from a datetime record; formatting and timezone do not change the instant](> host_datetime_to_unix dt=`dt`)*. ## parse - + `text` - + `pattern`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | any | None | None for default parsing, rfc3339 or a strftime format | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339 | + +Use `text`, `pattern`=None as the inputs for this operation. + +Effects: pure. RFC3339 / `YYYY-MM-DD[ HH:MM:SS]` by default; `pattern=` is strftime or `rfc3339`. -*> host_datetime_parse text=`text` pattern=`pattern`* +Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339. + +Return *[Parse RFC3339 or YYYY-MM-DD with optional time; an explicit pattern uses strftime or rfc3339](> host_datetime_parse text=`text` pattern=`pattern`)*. ## format - + `dt` - + `style`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dt | any | required | Datetime record returned by this library, not formatted text | +| style | any | None | Formatting style accepted by the host date formatter | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Format a datetime record as rfc3339, date, time, or an explicit strftime pattern | + +Use `dt`, `style`=None as the inputs for this operation. + +Effects: pure. Styles: `rfc3339` (default), `date`, `time`, or a strftime pattern. -*> host_datetime_format dt=`dt` style=`style`* +Format a datetime record as rfc3339, date, time, or an explicit strftime pattern. + +Return *[Format a datetime record as rfc3339, date, time, or an explicit strftime pattern](> host_datetime_format dt=`dt` style=`style`)*. ## add - + `dt` - + `days`=None - + `hours`=None - + `minutes`=None - + `seconds`=None -add. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dt | any | required | Datetime record returned by this library, not formatted text | +| days | any | None | Number of elapsed 24-hour days to add | +| hours | any | None | Number of elapsed hours to add | +| minutes | any | None | Number of elapsed minutes to add | +| seconds | any | None | Number of elapsed seconds to add | -*> host_datetime_add dt=`dt` days=`days` hours=`hours` minutes=`minutes` seconds=`seconds`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours | + +Use `dt`, `days`=None, `hours`=None, `minutes`=None, `seconds`=None as the inputs for this operation. + +Effects: pure. + +Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours. Named zones recompute their offset after the move. + +Return *[Add elapsed days, hours, minutes and seconds; a day here is exactly 24 hours](> host_datetime_add dt=`dt` days=`days` hours=`hours` minutes=`minutes` seconds=`seconds`)*. ## in_zone - + `dt` - + `zone` -Re-express the same instant in `+08:00` / `UTC` / fixed aliases like `Asia/Shanghai`. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dt | any | required | Datetime record returned by this library, not formatted text | +| zone | any | required | Fixed offset or named timezone accepted by this operation | -*> host_datetime_in_zone dt=`dt` zone=`zone`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp | + +Use `dt`, `zone` as the inputs for this operation. + +Effects: pure. + +Re-express the same instant in `+08:00` / `UTC` / IANA zones like `Asia/Shanghai`. + +Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp. + +Return *[Re-express the same instant in a fixed offset or an IANA zone, retaining its Unix timestamp](> host_datetime_in_zone dt=`dt` zone=`zone`)*. + +## parse_local + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | +| zone | text | required | Fixed offset or named timezone accepted by this operation | +| ambiguity | text | "reject" | DST fold policy: reject, earliest or latest | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result | + +Use `text`, `zone`, `ambiguity`="reject" as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/datetime.mq.md parse_local 'text="2024-11-03 01:30:00"' 'zone="America/New_York"' 'ambiguity="earliest"' --effects none --json +``` + +Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result. DST gaps fail; folds require reject/earliest/latest. + +Return *[Parse YYYY-MM-DD HH:MM:SS in an IANA timezone as Result](> host_datetime_local text=`text` zone=`zone` ambiguity=`ambiguity`)*. + +## add_calendar + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| dt | map | required | Datetime record returned by this library, not formatted text | +| days | number | required | Local calendar days to add, preserving wall time across DST | +| ambiguity | text | "reject" | DST fold policy: reject, earliest or latest | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Add local calendar days as Result, preserving wall-clock time across DST | + +Use `dt`, `days`, `ambiguity`="reject" as the inputs for this operation. + +Effects: pure. + +Add local calendar days as Result, preserving wall-clock time across DST. Legacy add uses elapsed duration: one day is 24 hours. + +Return *[Add local calendar days as Result, preserving wall-clock time across DST](> host_datetime_calendar_add dt=`dt` days=`days` ambiguity=`ambiguity`)*. diff --git a/lib/document.mq.md b/lib/document.mq.md new file mode 100644 index 0000000..88f48b6 --- /dev/null +++ b/lib/document.mq.md @@ -0,0 +1,155 @@ +--- +markup: occlusion +--- + +Inert document operations share the renderer Markdown parser. Every function is pure. + +Inspect and transform Markdown without executing its contents. + +Behavior and limits: Shares the Markdown parser with rendering and recognizes YAML frontmatter. Spans are original UTF-8 byte offsets. Duplicate section names fail. Replacement preserves surrounding source; persist via fs.write_checked. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/document.rs](../src/host/document.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + +## sections + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/document.mq.md sections 'text="# Notes"' --effects none --json +``` + +List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading. No execution. + +Return *[List headings with original UTF-8 byte spans and body text; nested sections end at the next same-or-higher heading](> host_document_sections text=`text`)*. + +## section + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | +| title | text | required | Exact, unique Markdown heading title | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Read the body under one exact heading; missing or duplicate headings fail | + +Use `text`, `title` as the inputs for this operation. + +Effects: pure. + +Read the body under one exact heading; missing or duplicate headings fail. + +Return *[Read the body under one exact heading; missing or duplicate headings fail](> host_document_section text=`text` title=`title`)*. + +## replace_section + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | +| title | text | required | Exact, unique Markdown heading title | +| body | text | required | Request body, or replacement text for document operations | +| expected_sha256 | any | None | Digest of the exact prior text; None disables the check where allowed | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Return Result with replaced section body, preserving its heading and surrounding source | + +Use `text`, `title`, `body`, `expected_sha256`=None as the inputs for this operation. + +Effects: pure. + +Return Result with replaced section body, preserving its heading and surrounding source. Optional digest checks the whole source. Pure transform; persist via fs.write_checked. + +Return *[Return Result with replaced section body, preserving its heading and surrounding source](> host_document_replace_section text=`text` title=`title` body=`body` expected_sha256=`expected_sha256`)*. + +## tables + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated. + +Return *[Extract inert GFM headers and cell text, plus original byte ranges; cells are never evaluated](> host_document_tables text=`text`)*. + +## replace_table + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | +| index | number | required | Zero-based table index in source order | +| headers | list | required | Ordered list of table header text | +| rows | list | required | List of cell-text lists; each row must match the header width | +| expected_sha256 | any | None | Digest of the exact prior text; None disables the check where allowed | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result | + +Use `text`, `index`, `headers`, `rows`, `expected_sha256`=None as the inputs for this operation. + +Effects: pure. + +Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result. + +Return *[Replace the zero-based table from text headers and rows, preserving all surrounding source; return Result](> host_document_replace_table text=`text` index=`index` headers=`headers` rows=`rows` expected_sha256=`expected_sha256`)*. + +## links + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | List Markdown link labels and targets with byte spans; never follow or execute them | + +Use `text` as the inputs for this operation. + +Effects: pure. + +List Markdown link labels and targets with byte spans; never follow or execute them. + +Return *[List Markdown link labels and targets with byte spans; never follow or execute them](> host_document_links text=`text`)*. + +## code_blocks + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | List code fence language and literal source with byte spans; never run foreign or Marqdo code | + +Use `text` as the inputs for this operation. + +Effects: pure. + +List code fence language and literal source with byte spans; never run foreign or Marqdo code. + +Return *[List code fence language and literal source with byte spans; never run foreign or Marqdo code](> host_document_code_blocks text=`text`)*. diff --git a/lib/encoding.mq.md b/lib/encoding.mq.md index f81bf4a..27f179d 100644 --- a/lib/encoding.mq.md +++ b/lib/encoding.mq.md @@ -6,46 +6,128 @@ description: Base64, hex, and base32 encode/decode (Mid M1 + Mid2 M8). UTF-8 tex Base64, hex, and base32 encode/decode. UTF-8 text round-trip. +Encode and decode UTF-8 text as Base64, hex or Base32. + +Behavior and limits: These historical helpers round-trip text. Use bytes.from_base64 for arbitrary binary; decoding invalid UTF-8 as text is an error. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/encoding.rs](../src/host/encoding.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## base64_encode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Base64-encode text | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/encoding.mq.md base64_encode 'text="Marqdo"' --effects none --json +``` Base64-encode text. Caller: [encoding.base64_encode] text=`s` -*> host_encoding_base64_encode text=`text`* +Return *[Base64-encode text](> host_encoding_base64_encode text=`text`)*. ## base64_decode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Base64-decode text | + +Use `text` as the inputs for this operation. + +Effects: pure. Base64-decode text. -*> host_encoding_base64_decode text=`text`* +Return *[Base64-decode text](> host_encoding_base64_decode text=`text`)*. ## hex_encode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Hex-encode text | + +Use `text` as the inputs for this operation. + +Effects: pure. Hex-encode text. -*> host_encoding_hex_encode text=`text`* +Return *[Hex-encode text](> host_encoding_hex_encode text=`text`)*. ## hex_decode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Hex-decode text | + +Use `text` as the inputs for this operation. + +Effects: pure. Hex-decode text. -*> host_encoding_hex_decode text=`text`* +Return *[Hex-decode text](> host_encoding_hex_decode text=`text`)*. ## base32_encode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Base32-encode text (RFC 4648 alphabet; padding with =) | + +Use `text` as the inputs for this operation. + +Effects: pure. Base32-encode text (RFC 4648 alphabet; padding with =). -*> host_encoding_base32_encode text=`text`* +Return *[Base32-encode text (RFC 4648 alphabet; padding with =)](> host_encoding_base32_encode text=`text`)*. ## base32_decode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Base32-decode text | + +Use `text` as the inputs for this operation. + +Effects: pure. Base32-decode text. -*> host_encoding_base32_decode text=`text`* +Return *[Base32-decode text](> host_encoding_base32_decode text=`text`)*. diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md index 05d02d9..0f8f95f 100644 --- a/lib/foreign.mq.md +++ b/lib/foreign.mq.md @@ -8,59 +8,113 @@ import: Run bound code fences and inline sources via local interpreters. +Bridge explicit values to external language processes and sessions. + +Behavior and limits: Configured languages are not proof that interpreters are installed. invoke exposes exit/timeout/output limits. External execution requires process.exec; close owned persistent sessions. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/foreign.rs](../src/host/foreign.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## set_cmd - + `lang` - + `cmd` - + `args`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | text | required | Registered interpreter language identifier, such as python | +| cmd | any | required | Executable command or interpreter override | +| args | any | None | Argument list passed to the called command or function | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Bind interpreter command cmd for language lang; optional extra argv | + +Use `lang`, `cmd`, `args`=None as the inputs for this operation. + +Effects: pure. Bind interpreter command cmd for language lang; optional extra argv. -*> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`* +Return *[Bind interpreter command cmd for language lang; optional extra argv](> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`)*. ## run - + `code` - + `stdin`=None - + `env`=None - + `cwd`=None - + `timeout`=None - + `args`=None - + `max_output`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | any | required | Bound code-fence value; supply lang and source for inline text | +| stdin | any | None | Text written to the child process standard input | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | +| args | any | None | Argument list passed to the called command or function | +| max_output | any | None | Maximum captured output bytes; None uses the host default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), extra argv and output cap | + +Use `code`, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None as the inputs for this operation. + +Effects: process.exec. Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), extra argv and output cap. Returns stdout text; non-zero exit is an error. Caller: [foreign.run] code=`block` -*> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`* +Return *[Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds), extra argv and output cap](> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`)*. ## run_lang - + `lang` - + `source` - + `stdin`=None - + `env`=None - + `cwd`=None - + `timeout`=None - + `args`=None - + `max_output`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | text | required | Registered interpreter language identifier, such as python | +| source | any | required | Source text to run with the selected interpreter | +| stdin | any | None | Text written to the child process standard input | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | +| args | any | None | Argument list passed to the called command or function | +| max_output | any | None | Maximum captured output bytes; None uses the host default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run source text with language lang; same options as run | + +Use `lang`, `source`, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None as the inputs for this operation. + +Effects: process.exec. Run source text with language lang; same options as run. -*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`* +Return *[Run source text with language lang; same options as run](> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`)*. ## invoke - + `code`=None - + `lang`=None - + `source`=None - + `stdin`=None - + `input`=None - + `env`=None - + `cwd`=None - + `timeout`=None - + `args`=None - + `output`=auto - + `max_output`=None - + `cmd`=None - + `keep`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | any | None | Bound code-fence value; supply lang and source for inline text | +| lang | any | None | Registered interpreter language identifier, such as python | +| source | any | None | Source text to run with the selected interpreter | +| stdin | any | None | Text written to the child process standard input | +| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | +| args | any | None | Argument list passed to the called command or function | +| output | any | "auto" | Result decoding mode: auto, text, json or lines | +| max_output | any | None | Maximum captured output bytes; None uses the host default | +| cmd | any | None | Executable command or interpreter override | +| keep | any | False | Whether to retain the generated script for inspection | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run code or lang+source and return a record map instead of raising on process failure | + +Use `code`=None, `lang`=None, `source`=None, `stdin`=None, `input`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `output`="auto", `max_output`=None, `cmd`=None, `keep`=False as the inputs for this operation. + +Effects: process.exec. Run code or lang+source and return a record map instead of raising on process failure. Fields: ok, code, stdout, stderr, ms, lang, cmd, timed_out, truncated, @@ -69,200 +123,402 @@ result, result_error, error, script, cached. `input` is encoded as JSON on stdin (mutually exclusive with `stdin`). `output` is auto | text | json | lines. `cmd` overrides the interpreter for this call. -*> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`* +Return *[Run code or lang+source and return a record map instead of raising on process failure](> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`)*. ## probe - + `lang`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | any | None | Registered interpreter language identifier, such as python | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Probe one language, or every known language when lang is omitted | + +Use `lang`=None as the inputs for this operation. + +Effects: process.exec. Probe one language, or every known language when lang is omitted. Returns {lang, cmd, path, ok, version, error} (a list when lang is omitted). -*> host_foreign_probe lang=`lang`* +Return *[Probe one language, or every known language when lang is omitted](> host_foreign_probe lang=`lang`)*. ## register - + `lang` - + `cmd`=None - + `args`=None - + `template`=None - + `ext`=None - + `env`=None - + `version_args`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | text | required | Registered interpreter language identifier, such as python | +| cmd | any | None | Executable command or interpreter override | +| args | any | None | Argument list passed to the called command or function | +| template | any | None | Interpreter launch template | +| ext | any | None | Temporary script filename extension | +| env | any | None | Environment variable/value record for the child process | +| version_args | any | None | Arguments used to query the interpreter version | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Register a language invocation | + +Use `lang`, `cmd`=None, `args`=None, `template`=None, `ext`=None, `env`=None, `version_args`=None as the inputs for this operation. + +Effects: pure. Register a language invocation. Provide cmd (+args) or template (placeholders {file}, {dir}, {base}, {inline}, {lang}, {cwd}); they are mutually exclusive. -*> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`* +Return *[Register a language invocation](> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`)*. ## unset - + `lang` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | text | required | Registered interpreter language identifier, such as python | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Remove a process-local registration | + +Use `lang` as the inputs for this operation. + +Effects: pure. Remove a process-local registration. Presets/config/env still apply. -*> host_foreign_unset lang=`lang`* +Return *[Remove a process-local registration](> host_foreign_unset lang=`lang`)*. ## load_config - + `path`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load .marqdo/foreign.toml (or an explicit path); returns the number of language tables read | + +Use `path`=None as the inputs for this operation. + +Effects: fs.read. Load .marqdo/foreign.toml (or an explicit path); returns the number of language tables read. -*> host_foreign_load_config path=`path`* +Return *[Load .marqdo/foreign.toml (or an explicit path); returns the number of language tables read](> host_foreign_load_config path=`path`)*. ## call - + `code`=None - + `lang`=None - + `source`=None - + `input`=None - + `stdin`=None - + `env`=None - + `cwd`=None - + `timeout`=None - + `args`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | any | None | Bound code-fence value; supply lang and source for inline text | +| lang | any | None | Registered interpreter language identifier, such as python | +| source | any | None | Source text to run with the selected interpreter | +| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | +| stdin | any | None | Text written to the child process standard input | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | +| args | any | None | Argument list passed to the called command or function | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | JSON-in / JSON-out call: encode `input` on stdin, parse stdout JSON and return the value (empty stdout -> None) | + +Use `code`=None, `lang`=None, `source`=None, `input`=None, `stdin`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None as the inputs for this operation. + +Effects: process.exec. JSON-in / JSON-out call: encode `input` on stdin, parse stdout JSON and return the value (empty stdout -> None). Raises on process failure or invalid JSON. -*> host_foreign_call code=`code` lang=`lang` source=`source` input=`input` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args`* +Return *[JSON-in / JSON-out call: encode input on stdin, parse stdout JSON and return the value (empty stdout -> None)](> host_foreign_call code=`code` lang=`lang` source=`source` input=`input` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args`)*. ## run_many - + `runs` - + `concurrency`=4 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| runs | any | required | Ordered per-run code or language/source records | +| concurrency | any | 4 | Maximum number of concurrent operations | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run a list of code values or invoke-option maps in parallel; returns records in input order | + +Use `runs`, `concurrency`=4 as the inputs for this operation. + +Effects: process.exec. Run a list of code values or invoke-option maps in parallel; returns records in input order. One failing item does not stop the others. -*> host_foreign_run_many runs=`runs` concurrency=`concurrency`* +Return *[Run a list of code values or invoke-option maps in parallel; returns records in input order](> host_foreign_run_many runs=`runs` concurrency=`concurrency`)*. ## call_many - + `inputs` - + `code`=None - + `lang`=None - + `source`=None - + `cmd`=None - + `env`=None - + `cwd`=None - + `timeout`=None - + `args`=None - + `max_output`=None - + `concurrency`=4 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| inputs | any | required | Input values for the batched calls | +| code | any | None | Bound code-fence value; supply lang and source for inline text | +| lang | any | None | Registered interpreter language identifier, such as python | +| source | any | None | Source text to run with the selected interpreter | +| cmd | any | None | Executable command or interpreter override | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | +| args | any | None | Argument list passed to the called command or function | +| max_output | any | None | Maximum captured output bytes; None uses the host default | +| concurrency | any | 4 | Maximum number of concurrent operations | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply one code/function to each input in parallel; returns parsed JSON results in input order | + +Use `inputs`, `code`=None, `lang`=None, `source`=None, `cmd`=None, `env`=None, `cwd`=None, `timeout`=None, `args`=None, `max_output`=None, `concurrency`=4 as the inputs for this operation. + +Effects: process.exec. Apply one code/function to each input in parallel; returns parsed JSON results in input order. Raises with the failing index after all workers finish. -*> host_foreign_call_many inputs=`inputs` code=`code` lang=`lang` source=`source` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output` concurrency=`concurrency`* +Return *[Apply one code/function to each input in parallel; returns parsed JSON results in input order](> host_foreign_call_many inputs=`inputs` code=`code` lang=`lang` source=`source` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output` concurrency=`concurrency`)*. ## session - + `kernels`=None - + `cells`=None - + `values`=None - + `inputs`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kernels | any | None | Kernel/session specifications for persistent interpreters | +| cells | any | None | Code cells to evaluate in a persistent interpreter | +| values | any | None | Variable/value record to inject into a session | +| inputs | any | None | Input values for the batched calls | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Declare a document view session | + +Use `kernels`=None, `cells`=None, `values`=None, `inputs`=None as the inputs for this operation. + +Effects: pure. Declare a document view session. `kernels` and `cells` are ordinary tables: kernels are `|名称|语言|命令|` (ZH or EN), cells are `|单元|内核|`. Returns a foreign session handle consumed by `view`; without this handle the view has no persistent kernel state. -**p = > table.empty_map** -**p = > table.put in=`p` at="kind" value="foreign-session"** -**p = > table.put in=`p` at="kernels" value=`kernels`** -**p = > table.put in=`p` at="cells" value=`cells`** -**p = > table.put in=`p` at="values" value=`values`** -**p = > table.put in=`p` at="inputs" value=`inputs`** -*p* +We retain **`p` = [Empty map](table.empty_map())**. +We retain **`p` = [Set the kind field in the new record](table.put(in=`p`, at="kind", value="foreign-session"))**. +We retain **`p` = [Set the kernels field in the new record](table.put(in=`p`, at="kernels", value=`kernels`))**. +We retain **`p` = [Set the cells field in the new record](table.put(in=`p`, at="cells", value=`cells`))**. +We retain **`p` = [Set the values field in the new record](table.put(in=`p`, at="values", value=`values`))**. +We retain **`p` = [Set the inputs field in the new record](table.put(in=`p`, at="inputs", value=`inputs`))**. +Return *p*. ## session_open - + `lang` - + `cmd`=None - + `env`=None - + `cwd`=None - + `timeout`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| lang | text | required | Registered interpreter language identifier, such as python | +| cmd | any | None | Executable command or interpreter override | +| env | any | None | Environment variable/value record for the child process | +| cwd | any | None | Child process working directory | +| timeout | any | None | Execution timeout in seconds; None uses the host default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Start a persistent Python/Node kernel; returns an opaque `handle` value | + +Use `lang`, `cmd`=None, `env`=None, `cwd`=None, `timeout`=None as the inputs for this operation. + +Effects: process.exec. Start a persistent Python/Node kernel; returns an opaque `handle` value. Text fabrications are refused by session ops; handles cannot cross the JSON bridge. `timeout` is the default per-eval timeout. -*> host_foreign_session_open lang=`lang` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout`* +Return *[Start a persistent Python/Node kernel; returns an opaque handle value](> host_foreign_session_open lang=`lang` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout`)*. ## session_eval - + `id` - + `code`=None - + `source`=None - + `input`=None - + `stdin`=None - + `timeout`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | +| code | any | None | Bound code-fence value; supply lang and source for inline text | +| source | any | None | Source text to run with the selected interpreter | +| input | any | None | Structured value JSON-encoded on stdin; cannot combine with stdin | +| stdin | any | None | Text written to the child process standard input | +| timeout | any | None | Execution timeout in seconds; None uses the host default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Evaluate code (a code value) or source text in session id; returns a record with id/alive | + +Use `id`, `code`=None, `source`=None, `input`=None, `stdin`=None, `timeout`=None as the inputs for this operation. + +Effects: process.exec. Evaluate code (a code value) or source text in session id; returns a record with id/alive. `input` is JSON-encoded for the kernel; `stdin` is raw program stdin for this evaluation. -*> host_foreign_session_eval id=`id` code=`code` source=`source` input=`input` stdin=`stdin` timeout=`timeout`* +Return *[Evaluate code (a code value) or source text in session id; returns a record with id/alive](> host_foreign_session_eval id=`id` code=`code` source=`source` input=`input` stdin=`stdin` timeout=`timeout`)*. ## session_set - + `id` - + `name` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | +| name | text | required | Name to resolve, register or look up | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Set one kernel variable from a Marqdo value (JSON copy) | + +Use `id`, `name`, `value` as the inputs for this operation. + +Effects: process.exec. Set one kernel variable from a Marqdo value (JSON copy). -*> host_foreign_session_set id=`id` name=`name` value=`value`* +Return *[Set one kernel variable from a Marqdo value (JSON copy)](> host_foreign_session_set id=`id` name=`name` value=`value`)*. ## session_get - + `id` - + `name` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | +| name | text | required | Name to resolve, register or look up | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read one kernel variable as a Marqdo value | + +Use `id`, `name` as the inputs for this operation. + +Effects: process.exec. Read one kernel variable as a Marqdo value. -*> host_foreign_session_get id=`id` name=`name`* +Return *[Read one kernel variable as a Marqdo value](> host_foreign_session_get id=`id` name=`name`)*. ## session_names - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List kernel variable names | + +Use `id` as the inputs for this operation. + +Effects: process.exec. List kernel variable names. -*> host_foreign_session_names id=`id`* +Return *[List kernel variable names](> host_foreign_session_names id=`id`)*. ## session_close - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Consume (affine close) a live session handle: kill and remove it | + +Use `id` as the inputs for this operation. + +Effects: process.exec. Consume (affine close) a live session handle: kill and remove it. Returns `True` on success. Closing an unknown or already-closed id is a fault (`foreign session … not found`), matching use-after-close on eval/set/get. -*> host_foreign_session_close id=`id`* +Return *[Consume (affine close) a live session handle: kill and remove it](> host_foreign_session_close id=`id`)*. ## session_interrupt - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Interrupt the current evaluation of a persistent kernel | + +Use `id` as the inputs for this operation. + +Effects: process.exec. Interrupt the current evaluation of a persistent kernel. The session remains usable for the next evaluation when the worker supports interruption. -*> host_foreign_session_interrupt id=`id`* +Return *[Interrupt the current evaluation of a persistent kernel](> host_foreign_session_interrupt id=`id`)*. ## session_list +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List live sessions with id/lang/cmd/evals/alive/started_ms | + +Effects: process.exec. + List live sessions with id/lang/cmd/evals/alive/started_ms. -*> host_foreign_session_list* +Return *[List live sessions with id/lang/cmd/evals/alive/started_ms](host_foreign_session_list())*. ## langs +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | List configured foreign languages | + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/foreign.mq.md langs --effects none --json +``` + List configured foreign languages. -*> host_foreign_langs* +Return configured language definitions without launching interpreters. Use probe separately to check executable availability. + +Return *[List configured foreign languages](host_foreign_langs())*. ## oracle_journal +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Return this document evaluation's admitted eval/get/decode observations as ordinary records with index, channel, value | + +Effects: pure. + Return this document evaluation's admitted eval/get/decode observations as ordinary records with index, channel, value. Opening, setting and closing do not append observations. -*> host_oracle_journal * +Return *[Return this document evaluation's admitted eval/get/decode observations as ordinary records with index, channel, value](> host_oracle_journal )*. ## replay_check - + `expected` - + `observed` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| expected | any | required | Expected observation record used for replay comparison | +| observed | any | required | Actual observation record used for replay comparison | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Compare two oracle journals without executing foreign code | + +Use `expected`, `observed` as the inputs for this operation. + +Effects: pure. Compare two oracle journals without executing foreign code. Returns ok and the least mismatching index, with the expected and observed records. -*> host_oracle_replay_check expected=`expected` observed=`observed`* +Return *[Compare two oracle journals without executing foreign code](> host_oracle_replay_check expected=`expected` observed=`observed`)*. diff --git a/lib/fs.mq.md b/lib/fs.mq.md index cb771be..0022fa9 100644 --- a/lib/fs.mq.md +++ b/lib/fs.mq.md @@ -1,129 +1,773 @@ --- markup: occlusion +import: + json: lib/json.mq.md + csv: lib/csv.mq.md title: lib/fs description: English filesystem wrappers --- English filesystem wrappers +Read, write, find and organize files under an explicit root. + +Behavior and limits: Legacy remove recursively deletes directories. Prefer remove_file/remove_empty_dir. Atomic operations replace one file; directory batches are not transactions. Native-only operations state their CoW boundary. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. + +Implementation: [src/host/fs.rs](../src/host/fs.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/sandbox_fs.rs](../src/host/sandbox_fs.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## read_text - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Read UTF-8 text from path | + +Use `path` as the inputs for this operation. + +Effects: fs.read. Read UTF-8 text from path. -*> host_read_text path=`path`* +Return *[Read UTF-8 text from path](> host_read_text path=`path`)*. ## write_text - + `path` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `text` as the inputs for this operation. + +Effects: fs.write. Write text to path (overwrite). -*> host_write_text path=`path` text=`text`* +Return *[Write text to path (overwrite)](> host_write_text path=`path` text=`text`)*. ## append_text - + `path` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `text` as the inputs for this operation. + +Effects: fs.write. Append text to path. -*> host_append_text path=`path` text=`text`* +Return *[Append text to path](> host_append_text path=`path` text=`text`)*. ## exists - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether path exists | + +Use `path` as the inputs for this operation. + +Effects: fs.read. Whether path exists. -*> host_exists path=`path`* +Return *[Whether path exists](> host_exists path=`path`)*. ## list_dir - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | List directory entries at path | + +Use `path` as the inputs for this operation. + +Effects: fs.read. List directory entries at path. -*> host_list_dir path=`path`* +Return *[List directory entries at path](> host_list_dir path=`path`)*. ## make_dir - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. Create directory at path. -*> host_make_dir path=`path`* +Return *[Create directory at path](> host_make_dir path=`path`)*. ## make_dirs - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. Create directories recursively (`mkdir -p`). -*> host_make_dirs path=`path`* +Return *[Create directories recursively (mkdir -p)](> host_make_dirs path=`path`)*. ## remove - + `path` -Remove file or empty directory at path. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | -*> host_remove path=`path`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. + +Remove a file or recursively remove a directory. Legacy behavior; use remove_file or remove_empty_dir for narrow deletion. + +Remove a file or recursively remove a directory. For narrow deletion use remove_file or remove_empty_dir. + +Return *[Remove a file or recursively remove a directory](> host_remove path=`path`)*. ## remove_tree - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. Remove a directory recursively. Errors if `path` is a file. -*> host_remove_tree path=`path`* +Return *[Remove a directory recursively](> host_remove_tree path=`path`)*. ## stat - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Returns `{size, mtime_unix, is_file, is_dir}` | + +Use `path` as the inputs for this operation. + +Effects: fs.read. Returns `{size, mtime_unix, is_file, is_dir}`. -*> host_stat path=`path`* +Return *[Returns {size, mtime_unix, is_file, is_dir}](> host_stat path=`path`)*. ## walk - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Depth-first listing of relative paths under `path` (forward slashes) | + +Use `path` as the inputs for this operation. + +Effects: fs.read. Depth-first listing of relative paths under `path` (forward slashes). -*> host_walk path=`path`* +Return *[Depth-first listing of relative paths under path (forward slashes)](> host_walk path=`path`)*. ## copy_file - + `src` - + `dest` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path under the granted root | +| dest | text | required | Destination path under the granted root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `src`, `dest` as the inputs for this operation. + +Effects: fs.write. Copy a file (overwrites `dest` if it exists). Paths are sandboxed like other fs ops. -*> host_copy_file src=`src` dest=`dest`* +Return *[Copy a file (overwrites dest if it exists)](> host_copy_file src=`src` dest=`dest`)*. ## move - + `src` - + `dest` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path under the granted root | +| dest | text | required | Destination path under the granted root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `src`, `dest` as the inputs for this operation. + +Effects: fs.write. Rename / move within the sandbox. -*> host_move src=`src` dest=`dest`* +Return *[Rename / move within the sandbox](> host_move src=`src` dest=`dest`)*. ## make_temp - + `prefix`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prefix | any | None | Prefix added to the generated name or tested against text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Create an empty temp file under the program directory; return its relative path | + +Use `prefix`=None as the inputs for this operation. + +Effects: fs.write. Create an empty temp file under the program directory; return its relative path. -*> host_make_temp prefix=`prefix`* +Return *[Create an empty temp file under the program directory; return its relative path](> host_make_temp prefix=`prefix`)*. ## text_patch - + `path` - + `find` - + `replace` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | +| find | any | required | Exact text to locate before replacement | +| replace | any | required | Replacement text for each exact match | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Exact FIND→REPLACE once in a UTF-8 text file | + +Use `path`, `find`, `replace` as the inputs for this operation. + +Effects: fs.write. Exact FIND→REPLACE once in a UTF-8 text file. `find` must match exactly once. -*> host_text_patch path=`path` find=`find` replace=`replace`* +Return *[Exact FIND→REPLACE once in a UTF-8 text file](> host_text_patch path=`path` find=`find` replace=`replace`)*. ## apply_patch_blocks - + `path` - + `text` - + `soft`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | +| text | text | required | Text supplied by the caller | +| soft | bool | False | Whether a missing patch match becomes a recoverable outcome | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Apply plan-style triple-angle FIND/REPLACE blocks from `text` to `path` | + +Use `path`, `text`, `soft`=False as the inputs for this operation. + +Effects: fs.write. Apply plan-style triple-angle FIND/REPLACE blocks from `text` to `path`. Also accepts fenced find/replace pairs and minimal Begin Patch hunks. When `soft=True`, only “FIND not found” returns `0` (run continues). Empty FIND, multi-match, parse errors, and whole-file FIND still abort — whole-file rewrite is forbidden. -*> host_apply_patch_blocks path=`path` text=`text` soft=`soft`* +Return *[Apply plan-style triple-angle FIND/REPLACE blocks from text to path](> host_apply_patch_blocks path=`path` text=`text` soft=`soft`)*. + +## try_read_text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Read text as {ok,value,error}; file and permission failures are data | + +Use `path` as the inputs for this operation. + +Effects: fs.read. + +Call this function directly: + +```sh +marqdo call lib/fs.mq.md try_read_text 'path="lib/fs.mq.md"' --effects fs.read --fs-root . --json +``` + +Read at most 8 MiB of UTF-8 text as {ok,value,error}; file, encoding and permission failures are data. The function still requires fs.read. + +Return *[Read at most 8 MiB of UTF-8 text as {ok,value,error}; file, encoding and permission failures are data](> host_fs_try_read_text path=`path`)*. + +## try_write_text + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Overwrite UTF-8 text and return {ok,value,error}; requires fs | + +Use `path`, `text` as the inputs for this operation. + +Effects: fs.write. + +Overwrite UTF-8 text and return {ok,value,error}; requires fs.write. + +Return *[Overwrite UTF-8 text and return {ok,value,error}; requires fs.write](> host_fs_try_write_text path=`path` text=`text`)*. + +## read_bytes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Read binary data as a bytes record | + +Use `path`, `max_bytes`=8388608 as the inputs for this operation. + +Effects: fs.read. + +Read binary data as a bytes record. Default limit is 8 MiB, maximum is 64 MiB; decoding is explicit via lib/bytes. + +Return *[Read binary data as a bytes record](> host_fs_read_bytes path=`path` max_bytes=`max_bytes`)*. + +## write_bytes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| data | map | required | Portable bytes record containing _type=bytes and base64 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `data` as the inputs for this operation. + +Effects: fs.write. + +Atomically replace a file with bytes; no UTF-8 conversion. Requires fs.write. + +Return *[Atomically replace a file with bytes; no UTF-8 conversion](> host_fs_write_bytes path=`path` data=`data`)*. + +## read_chunk + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| offset | number | 0 | Zero-based byte offset of the next chunk | +| size | number | 65536 | Number of bytes to read in this chunk | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Read at most size bytes from offset, returning data/next_offset/eof | + +Use `path`, `offset`=0, `size`=65536 as the inputs for this operation. + +Effects: fs.read. + +Read at most size bytes from offset, returning data/next_offset/eof. Offsets are zero-based bytes; each call closes the file, so no handles escape sessions. + +Return *[Read at most size bytes from offset, returning data/next_offset/eof](> host_fs_read_chunk path=`path` offset=`offset` size=`size`)*. + +## append_bytes + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| data | map | required | Portable bytes record containing _type=bytes and base64 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `data` as the inputs for this operation. + +Effects: fs.write. + +Append bytes, creating a file if absent; parent directory must exist. + +Return *[Append bytes, creating a file if absent; parent directory must exist](> host_fs_append_bytes path=`path` data=`data`)*. + +## atomic_write + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `text` as the inputs for this operation. + +Effects: fs.write. + +Replace text through a reserved sibling temporary file and rename; failures remove that temp file. This is one-file replacement, not a multi-file transaction. + +Return *[Replace text through a reserved sibling temporary file and rename; failures remove that temp file](> host_fs_atomic_write path=`path` text=`text`)*. + +## write_changed + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | Write atomically only when content differs; return whether it was written | + +Use `path`, `text` as the inputs for this operation. + +Effects: fs.write. + +Write atomically only when content differs; return whether it was written. + +Return *[Write atomically only when content differs; return whether it was written](> host_fs_write_changed path=`path` text=`text`)*. + +## write_checked + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| text | text | required | Text to read, transform or emit as described by this operation | +| expected_sha256 | text | required | Digest of the exact prior text; None disables the check where allowed | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Check current SHA-256 before atomic replacement, returning Result | + +Use `path`, `text`, `expected_sha256` as the inputs for this operation. + +Effects: fs.write. + +Check current SHA-256 before atomic replacement, returning Result. Detects stale content; concurrent writers still need external coordination. + +Return *[Check current SHA-256 before atomic replacement, returning Result](> host_fs_write_checked path=`path` text=`text` expected_sha256=`expected_sha256`)*. + +## read_lines + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row | + +Use `path`, `max_bytes`=8388608 as the inputs for this operation. + +Effects: fs.read. + +Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row. + +Return *[Read bounded UTF-8 lines without terminators; CRLF is accepted and a final newline does not create a phantom row](> host_fs_read_lines path=`path` max_bytes=`max_bytes`)*. + +## write_lines + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| lines | list | required | List of text lines to write | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `lines` as the inputs for this operation. + +Effects: fs.write. + +Atomically write text lines using LF and one final newline for nonempty input. + +Return *[Atomically write text lines using LF and one final newline for nonempty input](> host_fs_write_lines path=`path` lines=`lines`)*. + +## remove_file + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. + +Delete a file, refusing directories; missing paths fail. Legacy remove remains recursive for compatibility. + +Return *[Delete a file, refusing directories; missing paths fail](> host_fs_remove_file path=`path`)*. + +## remove_empty_dir + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path` as the inputs for this operation. + +Effects: fs.write. + +Delete only an empty directory; refuses nonempty directories. Native filesystem only. + +Return *[Delete only an empty directory; refuses nonempty directories](> host_fs_remove_empty_dir path=`path`)*. + +## temp_dir + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| prefix | text | "mqtmp" | Prefix added to the generated name or tested against text | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Create a directory under the filesystem root and return its relative name | + +Use `prefix`="mqtmp" as the inputs for this operation. + +Effects: fs.write. + +Create a directory under the filesystem root and return its relative name. Caller owns cleanup with remove_tree; never uses a global OS temp directory. + +Return *[Create a directory under the filesystem root and return its relative name](> host_fs_temp_dir prefix=`prefix`)*. + +## file_hash + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file | + +Use `path` as the inputs for this operation. + +Effects: fs.read. + +Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file. + +Return *[Compute SHA-256 with a 64 KiB read buffer; supports binary and large files without loading the whole file](> host_fs_file_hash path=`path`)*. + +## find + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| pattern | text | "**" | Relative path glob supporting *, ** and ? | +| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | +| max_depth | number | 64 | Maximum traversal depth | +| kind | text | "file" | Entry kind filter: file, dir or any | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all | + +Use `path`, `pattern`="**", `exclude`=None, `max_depth`=64, `kind`="file" as the inputs for this operation. + +Effects: fs.read. + +Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all. No symlink traversal; at most 100000 results. Native filesystem snapshot. + +Return *[Find sorted relative paths with star, double-star and question-mark globs; exclude patterns prune directories; kind is file/dir/all](> host_fs_find path=`path` pattern=`pattern` exclude=`exclude` max_depth=`max_depth` kind=`kind`)*. + +## copy_tree + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path; archive packing expects a directory | +| dest | text | required | Destination path; overwrite is allowed only where documented | +| overwrite | bool | False | Whether an existing destination file may be replaced | +| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | +| dry_run | bool | False | Whether to return the plan without modifying files | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Copy files between disjoint trees | + +Use `src`, `dest`, `overwrite`=False, `exclude`=None, `dry_run`=False as the inputs for this operation. + +Effects: fs.write. + +Copy files between disjoint trees. Preflight conflicts; overwrite is opt-in. Returns relative changed files; dry_run plans only. Does not copy permissions, symlinks or empty directories. + +Return *[Copy files between disjoint trees](> host_fs_copy_tree src=`src` dest=`dest` overwrite=`overwrite` exclude=`exclude` dry_run=`dry_run`)*. + +## sync_tree + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| src | text | required | Source path; archive packing expects a directory | +| dest | text | required | Destination path; overwrite is allowed only where documented | +| overwrite | bool | False | Whether an existing destination file may be replaced | +| exclude | any | None | Glob pattern list pruned during traversal; None excludes nothing | +| dry_run | bool | False | Whether to return the plan without modifying files | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Copy new or changed files with copy_tree conflict rules | + +Use `src`, `dest`, `overwrite`=False, `exclude`=None, `dry_run`=False as the inputs for this operation. + +Effects: fs.write. + +Copy new or changed files with copy_tree conflict rules. Never deletes destination-only files; execution is not transactional. + +Return *[Copy new or changed files with copy_tree conflict rules](> host_fs_sync_tree src=`src` dest=`dest` overwrite=`overwrite` exclude=`exclude` dry_run=`dry_run`)*. + +## rename_many + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| moves | list | required | List of source/destination rename records | +| dry_run | bool | False | Whether to return the plan without modifying files | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order | + +Use `moves`, `dry_run`=False as the inputs for this operation. + +Effects: fs.write. + +Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order. No cycles or rollback; dry_run reports the planned count. + +Return *[Preflight src/dest file records, reject existing or duplicate destinations, then rename in input order](> host_fs_rename_many moves=`moves` dry_run=`dry_run`)*. + +## read_json + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 解析后的数据 | + +Use `path` as the inputs for this operation. + +Effects: fs.read. + +Read UTF-8 then use the standard parser; errors abort, so batch tasks should first use try_read_text. + +We retain **`body` = [Read UTF-8 text from the selected file](read_text(path=`path`))**. +Return *[Parse the JSON transport text](json.parse(text=`body`))*. + +## write_json + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to filesystem root | +| value | any | required | Data to serialize | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `value` as the inputs for this operation. + +Effects: fs.write. + +Serialize then atomically replace the file; formatting and comments are not preserved. + +We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`value`))**. +Return *[Atomic write](atomic_write(path=`path`, text=`body`))*. + +## read_csv + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to filesystem root | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 解析后的数据 | + +Use `path` as the inputs for this operation. + +Effects: fs.read. + +Read UTF-8 then use the standard parser; errors abort, so batch tasks should first use try_read_text. + +We retain **`body` = [Read UTF-8 text from the selected file](read_text(path=`path`))**. +Return *[Parse](csv.parse(text=`body`))*. + +## write_csv + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to filesystem root | +| value | list | required | Data to serialize | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | None after completion; filesystem failures produce a diagnostic | + +Use `path`, `value` as the inputs for this operation. + +Effects: fs.write. + +Serialize then atomically replace the file; formatting and comments are not preserved. + +We retain **`body` = [Stringify](csv.stringify(rows=`value`))**. +Return *[Atomic write](atomic_write(path=`path`, text=`body`))*. diff --git a/lib/hash.mq.md b/lib/hash.mq.md index aae98f7..eae5a5c 100644 --- a/lib/hash.mq.md +++ b/lib/hash.mq.md @@ -6,33 +6,93 @@ description: Digests and HMAC (Mid M3). Integrity / cache keys — not password Digests and HMAC. For integrity and cache keys — not password storage. +Compute content digests and keyed message authentication. + +Behavior and limits: MD5/SHA1 are compatibility checksums, not password storage. Use security auth for passwords and fs.file_hash for bounded-memory binary file hashing. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/hash.rs](../src/host/hash.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## sha256 - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | SHA-256 hex digest of text | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/hash.mq.md sha256 'text="abc"' --effects none --json +``` SHA-256 hex digest of text. Caller: [hash.sha256] text=`s` -*> host_hash_sha256 text=`text`* +Return *[SHA-256 hex digest of text](> host_hash_sha256 text=`text`)*. ## sha1 - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | SHA-1 hex digest of text | + +Use `text` as the inputs for this operation. + +Effects: pure. SHA-1 hex digest of text. -*> host_hash_sha1 text=`text`* +Return *[SHA-1 hex digest of text](> host_hash_sha1 text=`text`)*. ## md5 - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | MD5 hex digest of text | + +Use `text` as the inputs for this operation. + +Effects: pure. MD5 hex digest of text. -*> host_hash_md5 text=`text`* +Return *[MD5 hex digest of text](> host_hash_md5 text=`text`)*. ## hmac_sha256 - + `key` - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | HMAC-SHA256 of text with key | + +Use `key`, `text` as the inputs for this operation. + +Effects: pure. HMAC-SHA256 of text with key. -*> host_hash_hmac_sha256 key=`key` text=`text`* +Return *[HMAC-SHA256 of text with key](> host_hash_hmac_sha256 key=`key` text=`text`)*. diff --git a/lib/html.mq.md b/lib/html.mq.md index 5f85d45..3015359 100644 --- a/lib/html.mq.md +++ b/lib/html.mq.md @@ -6,18 +6,56 @@ description: HTML escape / unescape (Mid2 M8). XSS floor for string assembly. HTML escape helpers. Use before stitching untrusted text into markup. +Escape or unescape HTML text. + +Behavior and limits: Escaping text does not sanitize an arbitrary HTML document. Build web content as Markdown leaves and structured View nodes. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/html_ops.rs](../src/host/html_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## escape - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Escape text for HTML | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/html.mq.md escape 'text="&"' --effects none --json +``` Escape text for HTML. Caller: [html.escape] text=`s` -*> host_html_escape text=`text`* +Return *[Escape text for HTML](> host_html_escape text=`text`)*. ## unescape - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Unescape HTML entities in text | + +Use `text` as the inputs for this operation. + +Effects: pure. Unescape HTML entities in text. -*> host_html_unescape text=`text`* +Return *[Unescape HTML entities in text](> host_html_unescape text=`text`)*. diff --git a/lib/json.mq.md b/lib/json.mq.md index 49c6b88..84a8394 100644 --- a/lib/json.mq.md +++ b/lib/json.mq.md @@ -6,58 +6,169 @@ description: JSON parse/stringify (shared EN/ZH import). Not a dict builder — Parse and stringify JSON. For maps/lists prefer GFM tables and lib/table put; do not chain json.set / json.append in new code. +Parse and serialize JSON at the data boundary. + +Behavior and limits: Use table for collection operations. JSON boundary rejects unsafe integers, duplicate keys and nonfinite numbers; do not turn opaque handles into guessed records. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/json.rs](../src/host/json.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Parse JSON text into a Marqdo value | + +Use `text` as the inputs for this operation. + +Effects: pure. Parse JSON text into a Marqdo value. Caller: [json.parse] text="{}" -*> host_json_parse text=`text`* +Return *[Parse JSON text into a Marqdo value](> host_json_parse text=`text`)*. ## stringify - + `value` - + `indent`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | +| indent | any | None | JSON indentation setting; None uses compact output | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Serialize value to JSON text; optional indent | + +Use `value`, `indent`=None as the inputs for this operation. + +Effects: pure. Serialize value to JSON text; optional indent. -*> host_json_stringify value=`value` indent=`indent`* +Return *[Serialize value to JSON text; optional indent](> host_json_stringify value=`value` indent=`indent`)*. ## get - + `value` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | +| key | text | required | Field name or key required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Shallow get from JSON object value at key | + +Use `value`, `key` as the inputs for this operation. + +Effects: pure. Shallow get from JSON object value at key. Prefer link-index get or table.get in new code. -*> host_json_get value=`value` key=`key`* +Return *[Shallow get from JSON object value at key](> host_json_get value=`value` key=`key`)*. ## keys - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Keys of JSON object value | + +Use `value` as the inputs for this operation. + +Effects: pure. Keys of JSON object value. -*> host_json_keys value=`value`* +Return *[Keys of JSON object value](> host_json_keys value=`value`)*. ## quote - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | JSON-quote string text (for building request bodies) | + +Use `text` as the inputs for this operation. + +Effects: pure. JSON-quote string text (for building request bodies). -*> host_json_quote text=`text`* +Return *[JSON-quote string text (for building request bodies)](> host_json_quote text=`text`)*. ## set - + `map` - + `key` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | +| key | text | required | Field name or key required by this operation | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Compatibility shallow set | + +Use `map`, `key`, `value` as the inputs for this operation. + +Effects: pure. Compatibility shallow set. Prefer table.put / table.set. -*> host_map_set map=`map` key=`key` value=`value`* +Return *[Compatibility shallow set](> host_map_set map=`map` key=`key` value=`value`)*. ## append - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Compatibility append | + +Use `list`, `item` as the inputs for this operation. + +Effects: pure. Compatibility append. Prefer table.append. -*> host_list_append list=`list` item=`item`* +Return *[Compatibility append](> host_list_append list=`list` item=`item`)*. + +## try_parse + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Return {ok,value,error}; parse failures are recoverable data | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/json.mq.md try_parse 'text="{"name":"Marqdo","n":2}"' --effects none --json +``` + +Return {ok,value,error}; parse failures are recoverable data. + +Return *[Return {ok,value,error}; parse failures are recoverable data](> host_try_json_parse text=`text`)*. diff --git a/lib/lint/narrative.mq.md b/lib/lint/narrative.mq.md index 7434993..ad3aee8 100644 --- a/lib/lint/narrative.mq.md +++ b/lib/lint/narrative.mq.md @@ -12,30 +12,25 @@ its headings are tools. The canonical path checker lives in the host as marqdo check --narrative-ratio so directory dogfood does not need filesystem effects inside a pure call. -## For AI agents - -If you are an AI agent, run marqdo check --narrative-ratio on each extension -file you edit. Do not invent a second schema. Call remind on this file when you -need a short machine-readable reminder of the rule. Each double-hash heading is -a tool. - -*None* +For AI agents: run marqdo check --narrative-ratio on edited library files. +This is a readability signal; parsing, contracts, executable examples and real +behavior tests provide correctness evidence. Headings name actual tools only. ## remind +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | rule reminder map | + Return a small map stating the narration threshold and the CLI to run. Takes no parameters. Use this when an agent needs a tool-shaped reminder without opening design docs. The threshold is one half. Contract tables count as narration; call lines and bold statements count as code. -| 返回 | 类型 | 说明 | -|------|------|------| -| result | any | rule reminder map | - `out` = | threshold | cli | tables | |-----------|-----|--------| | 0.5 | marqdo check --narrative-ratio FILE | narration | -*out* +Return *out*. diff --git a/lib/log.mq.md b/lib/log.mq.md index 6251276..16df35d 100644 --- a/lib/log.mq.md +++ b/lib/log.mq.md @@ -6,57 +6,128 @@ description: Level-filtered one-line logs (Mid M6 + Mid2 M10 fields). Default le Level-filtered one-line logs (Mid M6 + Mid2 M10 fields). Default level info. +Emit level-filtered diagnostic lines. + +Behavior and limits: set_level changes this run only. Logs are side effects, not return values. call captures stdout separately from its JSON result. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/log.rs](../src/host/log.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## set_level - + `level` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| level | any | required | Log threshold: debug, info, warn or error | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | level is debug / info / warn / error | + +Use `level` as the inputs for this operation. + +Effects: pure. level is debug / info / warn / error. -*> host_log_set_level level=`level`* +Return *[level is debug / info / warn / error](> host_log_set_level level=`level`)*. ## debug - + `text` - + `fields`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| fields | any | None | Structured field/value record attached to the log event | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Emit a debug log line; optional fields map | + +Use `text`, `fields`=None as the inputs for this operation. + +Effects: output.write. Emit a debug log line; optional fields map. -**line = > host_log_line level="debug" text=`text` fields=`fields`** +We retain **`line` = [Log line]([Emit a debug log line; optional fields map](host_log_line(level="debug", text=`text`, fields=`fields`)))**. 1. `line` - > print text=`line` + We **[Print the prepared message](print(text=`line`))**. 2. * - **** + Return *None*. ## info - + `text` - + `fields`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| fields | any | None | Structured field/value record attached to the log event | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Emit an info log line; optional fields map | + +Use `text`, `fields`=None as the inputs for this operation. + +Effects: output.write. + +Call this function directly: + +```sh +marqdo call lib/log.mq.md info 'text="handbook example"' 'fields={"task":"sample"}' --effects output.write --json +``` Emit an info log line; optional fields map. -**line = > host_log_line level="info" text=`text` fields=`fields`** +We retain **`line` = [Log line]([Emit an info log line; optional fields map](host_log_line(level="info", text=`text`, fields=`fields`)))**. 1. `line` - > print text=`line` + We **[Print the prepared message](print(text=`line`))**. 2. * - **** + Return *None*. ## warn - + `text` - + `fields`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| fields | any | None | Structured field/value record attached to the log event | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Emit a warn log line; optional fields map | + +Use `text`, `fields`=None as the inputs for this operation. + +Effects: output.write. Emit a warn log line; optional fields map. -**line = > host_log_line level="warn" text=`text` fields=`fields`** +We retain **`line` = [Log line]([Emit a warn log line; optional fields map](host_log_line(level="warn", text=`text`, fields=`fields`)))**. 1. `line` - > print text=`line` + We **[Print the prepared message](print(text=`line`))**. 2. * - **** + Return *None*. ## error - + `text` - + `fields`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| fields | any | None | Structured field/value record attached to the log event | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Emit an error log line; optional fields map | + +Use `text`, `fields`=None as the inputs for this operation. + +Effects: output.write. Emit an error log line; optional fields map. -**line = > host_log_line level="error" text=`text` fields=`fields`** +We retain **`line` = [Log line]([Emit an error log line; optional fields map](host_log_line(level="error", text=`text`, fields=`fields`)))**. 1. `line` - > print text=`line` + We **[Print the prepared message](print(text=`line`))**. 2. * - **** + Return *None*. diff --git a/lib/math.mq.md b/lib/math.mq.md index 9896ba6..312c133 100644 --- a/lib/math.mq.md +++ b/lib/math.mq.md @@ -6,283 +6,680 @@ description: High-school math — num, random, formula, plot High-school math — num, random, formula, plot +Compute numbers, symbolic expressions and plots. + +Behavior and limits: Number contracts include symbolic formulas. Random values require random.read. Plotting emits an artifact and needs output.write; linear algebra and quantum workloads stay in ext. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/math.rs](../src/host/math.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## pi -pi. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return the mathematical constant pi | -*> host_pi* +Effects: pure. + +Return the mathematical constant pi. + +Return *[Return the mathematical constant pi](host_pi())*. ## e -e. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return Euler constant e | -*> host_e* +Effects: pure. + +Return Euler constant e. + +Return *[Return Euler constant e](host_e())*. ## num - + `value` -num. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_num value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Convert a numeric value or numeric text to a number | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Convert a numeric value or numeric text to a number. + +Return *[Convert a numeric value or numeric text to a number](> host_num value=`value`)*. ## add - + `a` - + `b` -add. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_add a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Add the two numeric or symbolic operands | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Add the two numeric or symbolic operands. + +Return *[Add the two numeric or symbolic operands](> host_math_add a=`a` b=`b`)*. ## sub - + `a` - + `b` -sub. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_sub a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Subtract b from a | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Subtract b from a. + +Return *[Subtract b from a](> host_math_sub a=`a` b=`b`)*. ## mul - + `a` - + `b` -mul. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_mul a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Multiply a by b | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Multiply a by b. + +Return *[Multiply a by b](> host_math_mul a=`a` b=`b`)*. ## div - + `a` - + `b` -div. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_div a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Divide a by b; zero divisor is an error | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Divide a by b; zero divisor is an error. + +Return *[Divide a by b; zero divisor is an error](> host_math_div a=`a` b=`b`)*. ## pow - + `a` - + `b` -pow. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_pow a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Raise a to the power b | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Raise a to the power b. + +Return *[Raise a to the power b](> host_math_pow a=`a` b=`b`)*. ## neg - + `value` -neg. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_neg value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Negate a numeric or symbolic value | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Negate a numeric or symbolic value. + +Return *[Negate a numeric or symbolic value](> host_math_neg value=`value`)*. ## sin - + `value` -sin. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_sin value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute sine; numeric angles are radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute sine; numeric angles are radians. + +Return *[Compute sine; numeric angles are radians](> host_math_sin value=`value`)*. ## cos - + `value` -cos. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_cos value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute cosine; numeric angles are radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute cosine; numeric angles are radians. + +Return *[Compute cosine; numeric angles are radians](> host_math_cos value=`value`)*. ## tan - + `value` -tan. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_tan value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute tangent; numeric angles are radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute tangent; numeric angles are radians. + +Return *[Compute tangent; numeric angles are radians](> host_math_tan value=`value`)*. ## asin - + `value` -asin. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_asin value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute arcsine in radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute arcsine in radians. + +Return *[Compute arcsine in radians](> host_math_asin value=`value`)*. ## acos - + `value` -acos. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_acos value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute arccosine in radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute arccosine in radians. + +Return *[Compute arccosine in radians](> host_math_acos value=`value`)*. ## atan - + `value` -atan. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_atan value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute arctangent in radians | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute arctangent in radians. + +Return *[Compute arctangent in radians](> host_math_atan value=`value`)*. ## sqrt - + `value` -sqrt. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_sqrt value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute the square root of value | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/math.mq.md sqrt value=9 --effects none --json +``` + +Compute the square root of value. + +Return *[Compute the square root of value](> host_math_sqrt value=`value`)*. ## abs - + `value` -abs. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_abs value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return absolute magnitude | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Return absolute magnitude. + +Return *[Return absolute magnitude](> host_math_abs value=`value`)*. ## ln - + `value` -ln. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_ln value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute natural logarithm | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute natural logarithm. + +Return *[Compute natural logarithm](> host_math_ln value=`value`)*. ## exp - + `value` -exp. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_exp value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Compute the exponential of value | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Compute the exponential of value. + +Return *[Compute the exponential of value](> host_math_exp value=`value`)*. ## floor - + `value` -floor. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_floor value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Round toward negative infinity | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Round toward negative infinity. + +Return *[Round toward negative infinity](> host_math_floor value=`value`)*. ## ceil - + `value` -ceil. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | -*> host_math_ceil value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Round toward positive infinity | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Round toward positive infinity. + +Return *[Round toward positive infinity](> host_math_ceil value=`value`)*. ## min - + `a` - + `b` -min. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_min a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return the smaller operand | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Return the smaller operand. + +Return *[Return the smaller operand](> host_math_min a=`a` b=`b`)*. ## max - + `a` - + `b` -max. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First operand; its domain is described by this operation | +| b | any | required | Second operand; its domain is described by this operation | -*> host_math_max a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return the larger operand | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Return the larger operand. + +Return *[Return the larger operand](> host_math_max a=`a` b=`b`)*. ## random -random. +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return a pseudo-random number; seed controls reproducibility | -*> host_random* +Effects: random.read. + +Return a pseudo-random number; seed controls reproducibility. + +Return *[Return a pseudo-random number; seed controls reproducibility](host_random())*. ## random_int - + `min` - + `max` -random_int. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| min | any | required | Inclusive lower bound or start of the search/plot interval | +| max | any | required | Upper bound or end of the search/plot interval | -*> host_random_int min=`min` max=`max`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return a pseudo-random integer in the documented bounds | + +Use `min`, `max` as the inputs for this operation. + +Effects: random.read. + +Return a pseudo-random integer in the documented bounds. + +Return *[Return a pseudo-random integer in the documented bounds](> host_random_int min=`min` max=`max`)*. ## seed - + `value` -seed. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Integer seed for reproducible random sequences | -*> host_seed value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Set this run pseudo-random generator seed; not suitable for secrets | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Set this run pseudo-random generator seed; not suitable for secrets. + +Return *[Set this run pseudo-random generator seed; not suitable for secrets](> host_seed value=`value`)*. ## formula - + `text` -formula. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | any | required | Text supplied by the caller | -*> host_formula value=`text`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic. + +Return *[Parse expression text into a symbolic formula for later algebra or evaluation; invalid syntax produces a diagnostic](> host_formula value=`text`)*. ## simplify - + `formula` -simplify. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -*> host_simplify value=`formula`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation | + +Use `formula` as the inputs for this operation. + +Effects: pure. + +Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation. + +Return *[Return a simplified formula without changing the input; this is symbolic algebra, not numeric evaluation](> host_simplify value=`formula`)*. ## expand - + `formula` -expand. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | -*> host_expand value=`formula`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Expand algebraic products and powers and return a new symbolic formula | + +Use `formula` as the inputs for this operation. + +Effects: pure. + +Expand algebraic products and powers and return a new symbolic formula. + +Return *[Expand algebraic products and powers and return a new symbolic formula](> host_expand value=`formula`)*. ## diff - + `formula` - + `var` -diff. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | +| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | -*> host_diff formula=`formula` var=`var`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Differentiate the formula with respect to the named symbol and return a symbolic derivative | + +Use `formula`, `var` as the inputs for this operation. + +Effects: pure. + +Differentiate the formula with respect to the named symbol and return a symbolic derivative. + +Return *[Differentiate the formula with respect to the named symbol and return a symbolic derivative](> host_diff formula=`formula` var=`var`)*. ## subs - + `formula` - + `var` - + `value` -subs. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | +| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | +| value | any | required | Value to transform or store, without mutating the input | -*> host_subs formula=`formula` var=`var` value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula | + +Use `formula`, `var`, `value` as the inputs for this operation. + +Effects: pure. + +Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula. + +Return *[Substitute a symbol with the supplied value; return a number if fully reduced, otherwise a formula](> host_subs formula=`formula` var=`var` value=`value`)*. ## eval - + `formula` - + `var` - + `value` -eval. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | +| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | +| value | any | required | Value to transform or store, without mutating the input | -*> host_eval formula=`formula` var=`var` value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic | + +Use `formula`, `var`, `value` as the inputs for this operation. + +Effects: pure. + +Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic. + +Return *[Evaluate a formula at one numeric variable value; unresolved symbols produce a diagnostic](> host_eval formula=`formula` var=`var` value=`value`)*. ## solve - + `formula` - + `var` - + `min`=None - + `max`=None -solve. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | +| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | +| min | any | None | Inclusive lower bound or start of the search/plot interval | +| max | any | None | Upper bound or end of the search/plot interval | -*> host_solve formula=`formula` var=`var` min=`min` max=`max`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Return roots for the named symbol within min and max; omitted bounds use -100 and 100 | + +Use `formula`, `var`, `min`=None, `max`=None as the inputs for this operation. + +Effects: pure. + +Return roots for the named symbol within min and max; omitted bounds use -100 and 100. + +Return *[Return roots for the named symbol within min and max; omitted bounds use -100 and 100](> host_solve formula=`formula` var=`var` min=`min` max=`max`)*. ## plot - + `formula` - + `var` - + `min` - + `max` - + `steps`=None - + `path`=None - + `derivative`=None - + `grid`=None -plot. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | required | Symbolic formula returned by formula or a prior symbolic operation | +| var | any | required | Symbol name to differentiate, substitute, evaluate or solve for | +| min | any | required | Inclusive lower bound or start of the search/plot interval | +| max | any | required | Upper bound or end of the search/plot interval | +| steps | any | None | Number of samples across the plotting interval | +| path | any | None | Path relative to the granted filesystem root | +| derivative | any | None | Whether to include the derivative in the plot | +| grid | any | None | Whether to draw a coordinate grid | -*> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root | + +Use `formula`, `var`, `min`, `max`, `steps`=None, `path`=None, `derivative`=None, `grid`=None as the inputs for this operation. + +Effects: output.write. + +Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root. + +Return *[Sample the formula over the interval and return SVG text; an optional path also writes the SVG under the granted root](> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`)*. ## plot_points - + `xs` - + `ys` - + `path`=None - + `grid`=None -plot_points. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | +| ys | any | required | Y-coordinate list paired with xs | +| path | any | None | Path relative to the granted filesystem root | +| grid | any | None | Whether to draw a coordinate grid | -*> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected | + +Use `xs`, `ys`, `path`=None, `grid`=None as the inputs for this operation. + +Effects: output.write. + +Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected. + +Return *[Plot paired x/y lists and return SVG text; unequal coordinate lengths are rejected](> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`)*. ## plot_conic - + `kind` - + `a` - + `b`=None - + `h`=None - + `k`=None - + `path`=None - + `grid`=None -plot_conic. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kind | any | required | Conic type accepted by plot_conic | +| a | any | required | First operand; its domain is described by this operation | +| b | any | None | Second operand; its domain is described by this operation | +| h | any | None | Horizontal shift of the conic center | +| k | any | None | Vertical shift of the conic center | +| path | any | None | Path relative to the granted filesystem root | +| grid | any | None | Whether to draw a coordinate grid | -*> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Draw the selected conic with its dimensions and center offsets and return SVG text | + +Use `kind`, `a`, `b`=None, `h`=None, `k`=None, `path`=None, `grid`=None as the inputs for this operation. + +Effects: output.write. + +Draw the selected conic with its dimensions and center offsets and return SVG text. + +Return *[Draw the selected conic with its dimensions and center offsets and return SVG text](> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`)*. diff --git a/lib/net.mq.md b/lib/net.mq.md index 88cc939..de098ee 100644 --- a/lib/net.mq.md +++ b/lib/net.mq.md @@ -1,85 +1,295 @@ --- markup: occlusion +import: + table: lib/table.mq.md + text: lib/text.mq.md title: lib/net description: English HTTP(S) wrappers. Optional headers / content_type via host aliases. --- English HTTP(S) wrappers. Optional headers / content_type via host aliases. +Use HTTP, response parsing and bounded downloads. + +Behavior and limits: get requires network.read; configurable request conservatively requires network.write because its method is dynamic. request/get return Result with response headers; legacy http_* retain their historical contracts. Downloads also require fs.write. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/net.rs](../src/host/net.rs)、[src/host/net_ops.rs](../src/host/net_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## http_get - + `url` - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| headers | any | None | HTTP header name/value record; None sends no extra headers | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | HTTPS supported | + +Use `url`, `headers`=None as the inputs for this operation. + +Effects: network.read. HTTPS supported. Optional named arg `headers=` (map). Responses are capped at 8 MiB before decoding, so an upstream cannot exhaust the interpreter's memory. -*> host_http_get url=`url` headers=`headers`* +Return *[HTTPS supported](> host_http_get url=`url` headers=`headers`)*. ## http_post - + `url` - + `body` - + `content_type`=None - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| body | any | required | Request body, or replacement text for document operations | +| content_type | any | None | HTTP content type override; None uses the helper default | +| headers | any | None | HTTP header name/value record; None sends no extra headers | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Default content type is JSON | + +Use `url`, `body`, `content_type`=None, `headers`=None as the inputs for this operation. + +Effects: network.write. Default content type is JSON. Optional `content_type=` / `headers=` (map). -*> host_http_post url=`url` body=`body` content_type=`content_type` headers=`headers`* +Return *[Default content type is JSON](> host_http_post url=`url` body=`body` content_type=`content_type` headers=`headers`)*. ## http_post_sse - + `url` - + `body` - + `content_type`=None - + `headers`=None - + `echo`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| body | any | required | Request body, or replacement text for document operations | +| content_type | any | None | HTTP content type override; None uses the helper default | +| headers | any | None | HTTP header name/value record; None sends no extra headers | +| echo | bool | False | Whether to print streamed SSE text as it arrives | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | POST and consume OpenAI-compatible SSE | + +Use `url`, `body`, `content_type`=None, `headers`=None, `echo`=False as the inputs for this operation. + +Effects: network.write. POST and consume OpenAI-compatible SSE. Returns `{status, events}` where `events` is a list of `{type, …}` maps (`delta` / `done` / `error`). Optional `echo=True` prints delta text to stdout as chunks arrive. -*> host_http_post_sse url=`url` body=`body` content_type=`content_type` headers=`headers` echo=`echo`* +Return *[POST and consume OpenAI-compatible SSE](> host_http_post_sse url=`url` body=`body` content_type=`content_type` headers=`headers` echo=`echo`)*. ## openai_sse_parse - + `text` - + `echo`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| echo | bool | False | Whether to print streamed SSE text as it arrives | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Offline: parse an OpenAI chat SSE body into the same event list (no network) | + +Use `text`, `echo`=False as the inputs for this operation. + +Effects: pure. Offline: parse an OpenAI chat SSE body into the same event list (no network). -*> host_openai_sse_parse text=`text` echo=`echo`* +Return *[Offline: parse an OpenAI chat SSE body into the same event list (no network)](> host_openai_sse_parse text=`text` echo=`echo`)*. ## http_request - + `method` - + `url` - + `body`=None - + `content_type`=None - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| method | text | required | HTTP method, for example GET or POST | +| url | text | required | Target URL; HTTP helpers accept http or https | +| body | any | None | Request body, or replacement text for document operations | +| content_type | any | None | HTTP content type override; None uses the helper default | +| headers | any | None | HTTP header name/value record; None sends no extra headers | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Optional `body=` / `content_type=` / `headers=` | + +Use `method`, `url`, `body`=None, `content_type`=None, `headers`=None as the inputs for this operation. + +Effects: network.write. Optional `body=` / `content_type=` / `headers=`. -*> host_http_request method=`method` url=`url` body=`body` content_type=`content_type` headers=`headers`* +Return *[Optional body= / content_type= / headers=](> host_http_request method=`method` url=`url` body=`body` content_type=`content_type` headers=`headers`)*. ## url_encode - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Percent-encode a URL segment | + +Use `text` as the inputs for this operation. + +Effects: pure. Percent-encode a URL segment. Spaces become `%20` (not form/query `+`), so literal `+` remains unambiguous in paths. -*> host_url_encode text=`text`* +Return *[Percent-encode a URL segment](> host_url_encode text=`text`)*. ## cookie_parse - + `text` - + `is_response`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| is_response | any | False | Whether to parse a response header block rather than a request | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Parse a `Cookie` request header (default) or one or more `Set-Cookie` response headers (`is_response=True`) into a list of `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` | + +Use `text`, `is_response`=False as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/net.mq.md cookie_parse 'text="a=1; b=2"' --effects none --json +``` Parse a `Cookie` request header (default) or one or more `Set-Cookie` response headers (`is_response=True`) into a list of `{name, value, path, domain, expires, max_age, secure, http_only, same_site}`. -*> host_cookie_parse text=`text` is_response=`is_response`* +Return *[Parse a Cookie request header (default) or one or more Set-Cookie response headers (is_response=True) into a list of {name, value, path, domain, expires, max_age, secure,](> host_cookie_parse text=`text` is_response=`is_response`)*. ## multipart_parse - + `body` - + `boundary` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| body | any | required | Request body, or replacement text for document operations | +| boundary | any | required | Multipart delimiter from the Content-Type header | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Parse a `multipart/form-data` request body (given its `boundary`) into a list of `{name, filename?, content_type?, value}` parts | + +Use `body`, `boundary` as the inputs for this operation. + +Effects: pure. Parse a `multipart/form-data` request body (given its `boundary`) into a list of `{name, filename?, content_type?, value}` parts. -*> host_multipart_parse body=`body` boundary=`boundary`* +Return *[Parse a multipart/form-data request body (given its boundary) into a list of {name, filename?, content_type?, value} parts](> host_multipart_parse body=`body` boundary=`boundary`)*. ## markdown_parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Parse Markdown / GFM into HTML (pure transform, no network I/O) | + +Use `text` as the inputs for this operation. + +Effects: pure. Parse Markdown / GFM into HTML (pure transform, no network I/O). -*> host_markdown_parse text=`text`* +Return *[Parse Markdown / GFM into HTML (pure transform, no network I/O)](> host_markdown_parse text=`text`)*. + +## request + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| method | text | required | HTTP method, for example GET or POST | +| url | text | required | Target URL; HTTP helpers accept http or https | +| body | any | None | Request body, or replacement text for document operations | +| headers | any | None | HTTP header name/value record; None sends no extra headers | +| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | +| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | +| response | text | "text" | Response body representation: text or bytes | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Return Result; value has status, headers and body | + +Use `method`, `url`, `body`=None, `headers`=None, `timeout_ms`=30000, `max_bytes`=8388608, `response`="text" as the inputs for this operation. + +Effects: network.write. + +Body is text, a bytes record or None; serialize JSON with json.stringify first. Request headers are a map; response headers are name/values records. Output options and destinations are checked before network IO. + +Return Result; value has status, headers and body. Timeout is milliseconds; response is text or bytes; headers are name/values records. HTTP error status is a valid response; transport failure is an error. + +Return *[Body is text, a bytes record or None; serialize JSON with json.stringify first](> host_http_request_result method=`method` url=`url` body=`body` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes` response=`response`)*. + +## download + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| path | text | required | Path within the granted filesystem root | +| headers | any | None | HTTP header name/value record; None sends no extra headers | +| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | +| max_bytes | number | 67108864 | Maximum bytes read or expanded; exceeding it fails | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Bounded streaming download; atomically replace destination only on successful status and complete transfer | + +Use `url`, `path`, `headers`=None, `timeout_ms`=30000, `max_bytes`=67108864 as the inputs for this operation. + +Effects: fs.write,network.read. + +Bounded streaming download; atomically replace destination only on successful status and complete transfer. Result value has status/headers/size/path; requires network.read and fs.write. + +Return *[Bounded streaming download; atomically replace destination only on successful status and complete transfer](> host_http_download url=`url` path=`path` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes`)*. + +## get + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | required | Target URL; HTTP helpers accept http or https | +| headers | any | None | HTTP header name/value record; None sends no extra headers | +| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | +| max_bytes | number | 8388608 | Maximum bytes read or expanded; exceeding it fails | +| response | text | "text" | Response body representation: text or bytes | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Read-only GET as Result, requiring only network | + +Use `url`, `headers`=None, `timeout_ms`=30000, `max_bytes`=8388608, `response`="text" as the inputs for this operation. + +Effects: network.read. + +Read-only GET as Result, requiring only network.read. Headers are name/values records; response is text or bytes. + +Return *[Read-only GET as Result, requiring only network.read](> host_http_get_result url=`url` headers=`headers` timeout_ms=`timeout_ms` max_bytes=`max_bytes` response=`response`)*. + +## header_values + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| headers | list | required | headers records from a response | +| name | text | required | Header name | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | All values for the header | + +Use `headers`, `name` as the inputs for this operation. + +Effects: pure. + +Return all values for a case-insensitive response header; missing yields an empty list. Request headers remain a map; response headers use records to preserve arbitrary names and repeated values. + +We retain **`lower` = [To lower](text.to_lower(text=`name`))**. +We retain **`matches` = [Where](table.where(list=`headers`, key="name", value=`lower`))**. +We retain **`values` = [Pluck](table.pluck(list=`matches`, key="values"))**. +Return *[Flatten](table.flatten(list=`values`))*. diff --git a/lib/path.mq.md b/lib/path.mq.md index b2f1a03..584b965 100644 --- a/lib/path.mq.md +++ b/lib/path.mq.md @@ -6,54 +6,185 @@ description: Path algebra (Mid M2). No I/O; OS separators. Path algebra only. No I/O; separators follow the host OS. +Manipulate paths without accessing the filesystem. + +Behavior and limits: Normalization is lexical, not an authorization check. IO paths are checked by the host filesystem root. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/path.rs](../src/host/path.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## join - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Base path | +| b | any | required | Path segment appended to the base | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Join path segments a and b | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. Join path segments a and b. Caller: [path.join] a="a" b="b" -*> host_path_join a=`a` b=`b`* +Return *[Join path segments a and b](> host_path_join a=`a` b=`b`)*. ## split - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Split path into parts | + +Use `path` as the inputs for this operation. + +Effects: pure. Split path into parts. -*> host_path_split path=`path`* +Return *[Split path into parts](> host_path_split path=`path`)*. ## file_name - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Final file name of path | + +Use `path` as the inputs for this operation. + +Effects: pure. Final file name of path. -*> host_path_file_name path=`path`* +Return *[Final file name of path](> host_path_file_name path=`path`)*. ## parent - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Parent directory of path | + +Use `path` as the inputs for this operation. + +Effects: pure. Parent directory of path. -*> host_path_parent path=`path`* +Return *[Parent directory of path](> host_path_parent path=`path`)*. ## extension - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | File extension of path | + +Use `path` as the inputs for this operation. + +Effects: pure. File extension of path. -*> host_path_extension path=`path`* +Return *[File extension of path](> host_path_extension path=`path`)*. ## normalize - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Normalize path (dot segments) | + +Use `path` as the inputs for this operation. + +Effects: pure. Normalize path (dot segments). -*> host_path_normalize path=`path`* +Return *[Normalize path (dot segments)](> host_path_normalize path=`path`)*. ## is_absolute - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether path is absolute | + +Use `path` as the inputs for this operation. + +Effects: pure. Whether path is absolute. -*> host_path_is_absolute path=`path`* +Return *[Whether path is absolute](> host_path_is_absolute path=`path`)*. + +## relative + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| base | text | required | Base directory for relative path calculation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Compute a lexical path relative to base; both arguments must share absolute/relative form | + +Use `path`, `base` as the inputs for this operation. + +Effects: pure. + +Compute a lexical path relative to base; both arguments must share absolute/relative form. No disk access. + +Return *[Compute a lexical path relative to base; both arguments must share absolute/relative form](> host_path_relative path=`path` base=`base`)*. + +## with_extension + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path within the granted filesystem root | +| extension | text | required | New extension, with or without a leading dot | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Replace the last extension; empty extension removes it | + +Use `path`, `extension` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/path.mq.md with_extension 'path="notes/draft.txt"' 'extension="md"' --effects none --json +``` + +Replace the last extension; empty extension removes it. + +Return *[Replace the last extension; empty extension removes it](> host_path_with_extension path=`path` extension=`extension`)*. diff --git a/lib/plugin.mq.md b/lib/plugin.mq.md index 3bb13fb..0923a92 100644 --- a/lib/plugin.mq.md +++ b/lib/plugin.mq.md @@ -6,30 +6,82 @@ description: Load optional native ABI plugins (.dll / .so / .dylib) Load optional native ABI plugins (.dll / .so / .dylib). +Locate and load native capabilities. + +Behavior and limits: An empty list means no plugin is loaded in this process. Loading requires plugin.call. Prefer the relevant domain index for normal work; plugins are native-only. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/plugin.rs](../src/host/plugin.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## load - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load a native plugin from path | + +Use `path` as the inputs for this operation. + +Effects: plugin.call. Load a native plugin from path. Caller: [plugin.load] path=`so` -*> host_plugin_load path=`path`* +Return *[Load a native plugin from path](> host_plugin_load path=`path`)*. ## unload +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Unload the current native plugin | + +Effects: plugin.call. + Unload the current native plugin. -*> host_plugin_unload* +Return *[Unload the current native plugin](host_plugin_unload())*. ## list +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | List loaded native plugins | + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/plugin.mq.md list --effects none --json +``` + List loaded native plugins. -*> host_plugin_list* +Return names loaded in this host process. Listing does not load a plugin, and a new process may have an empty list. + +Return *[List loaded native plugins](host_plugin_list())*. ## native_path - + `name` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Installed extension identifier, for example agent | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Resolve installed or local native plugin path (e.g | + +Use `name` as the inputs for this operation. + +Effects: plugin.call. Resolve installed or local native plugin path (e.g. agent). -*> host_ext_native_path name=`name`* +Return *[Resolve installed or local native plugin path (e.g](> host_ext_native_path name=`name`)*. diff --git a/lib/re.mq.md b/lib/re.mq.md index 1282c4c..baca4b3 100644 --- a/lib/re.mq.md +++ b/lib/re.mq.md @@ -6,46 +6,117 @@ description: Regular expressions (Mid M1). Unicode; no backreferences. Regular expressions. Unicode; no backreferences. Prefer lib/text for literal replace. +Match Unicode regular expressions. + +Behavior and limits: The engine has no backreferences. Current find functions return whole matches; capture groups and replacement callbacks are not promised. Literal replacement belongs in text. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/re.rs](../src/host/re.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## is_match - + `text` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | Regular expression supported by the regex host | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether text matches pattern | + +Use `text`, `pattern` as the inputs for this operation. + +Effects: pure. Whether text matches pattern. Caller: [re.is_match] text=`s` pattern="a+" -*> host_re_is_match text=`text` pattern=`pattern`* +Return *[Whether text matches pattern](> host_re_is_match text=`text` pattern=`pattern`)*. ## find - + `text` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | Regular expression supported by the regex host | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | First match of pattern in text, or None | + +Use `text`, `pattern` as the inputs for this operation. + +Effects: pure. First match of pattern in text, or None. -*> host_re_find text=`text` pattern=`pattern`* +Return *[First match of pattern in text, or None](> host_re_find text=`text` pattern=`pattern`)*. ## find_all - + `text` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | Regular expression supported by the regex host | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | All matches of pattern in text | + +Use `text`, `pattern` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/re.mq.md find_all 'text="a12 b34"' 'pattern="[0-9]+"' --effects none --json +``` All matches of pattern in text. -*> host_re_find_all text=`text` pattern=`pattern`* +Return *[All matches of pattern in text](> host_re_find_all text=`text` pattern=`pattern`)*. ## replace - + `text` - + `pattern` - + `with` - + `count`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | Regular expression supported by the regex host | +| with | any | required | Replacement text applied to matched spans | +| count | any | None | Maximum replacement count; None uses the documented default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Replace matches of pattern in text with with; optional count limits replacements (None = all) | + +Use `text`, `pattern`, `with`, `count`=None as the inputs for this operation. + +Effects: pure. Replace matches of pattern in text with with; optional count limits replacements (None = all). -*> host_re_replace text=`text` pattern=`pattern` with=`with` count=`count`* +Return *[Replace matches of pattern in text with with; optional count limits replacements (None = all)](> host_re_replace text=`text` pattern=`pattern` with=`with` count=`count`)*. ## split - + `text` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | Regular expression supported by the regex host | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Split text on pattern | + +Use `text`, `pattern` as the inputs for this operation. + +Effects: pure. Split text on pattern. -*> host_re_split text=`text` pattern=`pattern`* +Return *[Split text on pattern](> host_re_split text=`text` pattern=`pattern`)*. diff --git a/lib/result.mq.md b/lib/result.mq.md new file mode 100644 index 0000000..eafefba --- /dev/null +++ b/lib/result.mq.md @@ -0,0 +1,101 @@ +--- +markup: occlusion +--- + +Recoverable outcomes use one ordinary record: ok/value/error. A failure's error +contains code/message/operation. Inspect ok before consuming value. Host policy +checks still apply; a Result wrapper never authorizes an effect. + +Compose recoverable outcomes with one data contract. + +Behavior and limits: Check ok before value; HTTP status and child exit code remain domain-level results; errors have code/message/operation. Use try_ operations to recover known IO/parse failures. Result construction does not catch arbitrary runtime errors or grant permission. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/result.rs](../src/host/result.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + +## ok + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Successful operation value, including None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Successful Result | + +Use `value` as the inputs for this operation. + +Delegate to ok with the supplied inputs, preserving its result and failure behavior. + +Effects: pure. + +`out` = + +| ok | value | error | +|----|-------|-------| +| True | `value` | None | + +Return *out*. + +## error + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | text | required | Stable machine-readable category | +| message | text | required | Human-readable explanation | +| operation | text | "application" | Operation that failed | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Failed Result | + +Use `code`, `message`, `operation`="application" as the inputs for this operation. + +Delegate to error with the supplied inputs, preserving its result and failure behavior. + +Effects: pure. + +`failure` = + +| code | message | operation | +|------|---------|-----------| +| `code` | `message` | `operation` | + +`out` = + +| ok | value | error | +|----|-------|-------| +| False | None | `failure` | + +Return *out*. + +## value_or + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| result | map | required | Result from a recoverable operation | +| default | any | None | Explicit fallback on failure | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Successful value or fallback | + +Use `result`, `default`=None as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/result.mq.md value_or 'result={"ok":false,"value":null,"error":{"code":"missing","message":"absent","operation":"example"}}' 'default="fallback"' --effects none --json +``` + +Read value only when ok is true, including a successful None. Use the fallback only on failure; zero and empty text remain valid values. + +1. [operation succeeded](access(`result`, "ok")) + Return *[successful value](access(result, "value"))*. +2. * + Return *default*. diff --git a/lib/secrets.mq.md b/lib/secrets.mq.md index 68c4aea..d60f783 100644 --- a/lib/secrets.mq.md +++ b/lib/secrets.mq.md @@ -6,18 +6,56 @@ description: Cryptographic tokens (Mid M3). Do not use math.random for secrets. Cryptographic tokens. Do not use math.random for secrets. +Generate cryptographically random tokens. + +Behavior and limits: n counts input bytes. Do not use math.random for credentials. Browser entropy depends on the runtime bridge; do not silently substitute a pseudo-random generator. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/secrets.rs](../src/host/secrets.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## token_hex - + `n`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | None | Requested byte count; None uses the helper default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Byte length n (default 16) | + +Use `n`=None as the inputs for this operation. + +Effects: random.read. + +Call this function directly: + +```sh +marqdo call lib/secrets.mq.md token_hex n=16 --effects random.read --json +``` Byte length n (default 16). Returns lowercase hex of length 2*n. Caller: [secrets.token_hex] n=16 -*> host_secrets_token_hex n=`n`* +Return *[Byte length n (default 16)](> host_secrets_token_hex n=`n`)*. ## token_urlsafe - + `n`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| n | any | None | Requested byte count; None uses the helper default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Byte length n (default 16) | + +Use `n`=None as the inputs for this operation. + +Effects: random.read. Byte length n (default 16). URL-safe Base64 without padding. -*> host_secrets_token_urlsafe n=`n`* +Return *[Byte length n (default 16)](> host_secrets_token_urlsafe n=`n`)*. diff --git a/lib/stats.mq.md b/lib/stats.mq.md index 23e7c46..c94bc65 100644 --- a/lib/stats.mq.md +++ b/lib/stats.mq.md @@ -6,25 +6,74 @@ description: Thin mean / median / sample stdev (Mid2 M10). Not a dataframe libra Thin numeric summaries. Not a dataframe library. +Compute small descriptive statistics. + +Behavior and limits: mean/median require nonempty numeric lists. This is not a dataframe or numerical array runtime; ext/linalg owns matrix operations. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/stats.rs](../src/host/stats.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## mean - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Arithmetic mean of list | + +Use `list` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/stats.mq.md mean 'list=[1,2,3]' --effects none --json +``` Arithmetic mean of list. Caller: [stats.mean] list=`xs` -*> host_stats_mean list=`list`* +Return *[Arithmetic mean of list](> host_stats_mean list=`list`)*. ## median - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Median of list | + +Use `list` as the inputs for this operation. + +Effects: pure. Median of list. -*> host_stats_median list=`list`* +Return *[Median of list](> host_stats_median list=`list`)*. ## stdev - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Sample standard deviation; needs at least two values | + +Use `list` as the inputs for this operation. + +Effects: pure. Sample standard deviation; needs at least two values. -*> host_stats_stdev list=`list`* +Return *[Sample standard deviation; needs at least two values](> host_stats_stdev list=`list`)*. diff --git a/lib/subtask.mq.md b/lib/subtask.mq.md index 069a7f7..0ab5962 100644 --- a/lib/subtask.mq.md +++ b/lib/subtask.mq.md @@ -6,45 +6,165 @@ description: Concurrent subtasks — file, function, or foreign code Concurrent subtasks: file, function, or foreign code. +Run and observe concurrent work with explicit ownership. + +Behavior and limits: File batches inherit parent caps and root. Each Result.ok reports completion of the wait protocol; inspect value.code for child exit success. wait_timeout keeps its handle unless cancel is requested. OS tasks can be killed/reaped; function-thread cancellation is logical only. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. + +Implementation: [src/host/subtask.rs](../src/host/subtask.rs)、[src/host/task_ops.rs](../src/host/task_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## spawn - + `path`=None - + `fn`=None - + `args`=None - + `code`=None - + `lang`=None - + `source`=None - + `stdin`=None - + `quiet`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Path relative to the granted filesystem root | +| fn | any | None | Marqdo function target used instead of a file task | +| args | any | None | Arguments supplied to the selected task | +| code | any | None | Bound code-fence value; supply lang and source for inline text | +| lang | any | None | Registered interpreter language identifier, such as python | +| source | any | None | Source text to run with the selected interpreter | +| stdin | any | None | Text written to the child process standard input | +| quiet | bool | True | Whether to suppress child output while retaining its result | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Start a subtask | + +Use `path`=None, `fn`=None, `args`=None, `code`=None, `lang`=None, `source`=None, `stdin`=None, `quiet`=True as the inputs for this operation. + +Effects: process.exec. Start a subtask. File children are silent by default (quiet=True: piped capture). Set quiet=False to inherit parent stdout/stderr. File wait returns {code, value} plus optional stdout/stderr tails when quiet-captured. value is the child main return (not stdout). Caller: [subtask.spawn] path="child.mq.md" -*> host_subtask_spawn path=`path` fn=`fn` args=`args` code=`code` lang=`lang` source=`source` stdin=`stdin` quiet=`quiet`* +Return *[Start a subtask](> host_subtask_spawn path=`path` fn=`fn` args=`args` code=`code` lang=`lang` source=`source` stdin=`stdin` quiet=`quiet`)*. ## poll - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Non-blocking status for subtask id | + +Use `id` as the inputs for this operation. + +Effects: process.exec. Non-blocking status for subtask id. -*> host_subtask_poll id=`id`* +Return *[Non-blocking status for subtask id](> host_subtask_poll id=`id`)*. ## wait - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Block until subtask id finishes | + +Use `id` as the inputs for this operation. + +Effects: process.exec. Block until subtask id finishes. -*> host_subtask_join id=`id`* +Return *[Block until subtask id finishes](> host_subtask_join id=`id`)*. ## kill - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | required | Identifier returned by the corresponding create/spawn operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Kill subtask id | + +Use `id` as the inputs for this operation. + +Effects: process.exec. Kill subtask id. -*> host_subtask_kill id=`id`* +Return *[Kill subtask id](> host_subtask_kill id=`id`)*. ## wait_all +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Wait until every spawned subtask finishes | + +Effects: process.exec. + Wait until every spawned subtask finishes. -*> host_subtask_wait_all* +Return *[Wait until every spawned subtask finishes](host_subtask_wait_all())*. + +## wait_timeout + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | number | required | Identifier returned by the corresponding create/spawn operation | +| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | +| cancel | bool | False | Whether a timeout also cancels the outstanding task | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Wait as Result; timeout retains the handle unless cancel=True | + +Use `id`, `timeout_ms`=30000, `cancel`=False as the inputs for this operation. + +Effects: process.exec. + +Wait as Result; timeout retains the handle unless cancel=True. Cancellation reaps process tasks; function-thread cancellation is logical only. + +Return *[Wait as Result; timeout retains the handle unless cancel=True](> host_subtask_wait_timeout id=`id` timeout_ms=`timeout_ms` cancel=`cancel`)*. + +## cancel_all + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Cancel all subtasks, reaping process tasks; return count | + +Effects: process.exec. + +Cancel all subtasks, reaping process tasks; return count. Function threads only support logical cancellation. + +Return *[Cancel all subtasks, reaping process tasks; return count](> host_subtask_cancel_all )*. + +## run_many + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| tasks | list | required | Ordered file task records containing path and optional args | +| limit | number | 4 | Maximum simultaneous file tasks, from 1 through 64 | +| timeout_ms | number | 30000 | Timeout in milliseconds; inspect the operation result after waiting | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Run path/args file tasks with bounded concurrency; return ordered Results | + +Use `tasks`, `limit`=4, `timeout_ms`=30000 as the inputs for this operation. + +Effects: process.exec. + +Call this function directly: + +```sh +marqdo call lib/subtask.mq.md run_many 'tasks=[{"path":"examples/stdlib-handbook/worker.mq.md"}]' limit=2 --effects process.exec --fs-root . --json +``` + +Run path/args file tasks with bounded concurrency; return ordered Results. Timed-out children are killed and reaped; at most 10000 tasks, 64 workers; inherit parent caps and filesystem root. + +Return *[Run path/args file tasks with bounded concurrency; return ordered Results](> host_subtask_run_many tasks=`tasks` limit=`limit` timeout_ms=`timeout_ms`)*. diff --git a/lib/sys.mq.md b/lib/sys.mq.md index 1d2c524..44bd623 100644 --- a/lib/sys.mq.md +++ b/lib/sys.mq.md @@ -6,76 +6,188 @@ description: English system wrappers (load_dotenv accepts optional path via host English system wrappers (load_dotenv accepts optional path via host alias) +Inspect execution metadata and interact with the host system. + +Behavior and limits: Metadata describes the entry artifact. module_source is entry source, not the imported library. exec needs process.exec; environment operations declare separate effects. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/sys.rs](../src/host/sys.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## env_get - + `name` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Environment variable name | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Get environment variable name | + +Use `name` as the inputs for this operation. + +Effects: environment.read. Get environment variable name. -*> host_env_get name=`name`* +Return *[Get environment variable name](> host_env_get name=`name`)*. ## env_set - + `name` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| name | text | required | Environment variable name | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Set environment variable name to value | + +Use `name`, `value` as the inputs for this operation. + +Effects: environment.write. Set environment variable name to value. -*> host_env_set name=`name` value=`value`* +Return *[Set environment variable name to value](> host_env_set name=`name` value=`value`)*. ## load_dotenv - + `path`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | any | None | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Load `.env` (optional named arg `path=`) | + +Use `path`=None as the inputs for this operation. + +Effects: environment.write,fs.read. Load `.env` (optional named arg `path=`). Existing process env is not overridden. -*> host_dotenv_load path=`path`* +Return *[Load .env (optional named arg path=)](> host_dotenv_load path=`path`)*. ## args +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Process argv list | + +Effects: pure. + Process argv list. -*> host_args* +Return *[Process argv list](host_args())*. ## cwd +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Current working directory | + +Effects: pure. + Current working directory. -*> host_cwd* +Return *[Current working directory](host_cwd())*. ## meta +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Bound Artifact Metadata from the entry `.mq.md` (map) | + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/sys.mq.md meta --effects none --json +``` + Bound Artifact Metadata from the entry `.mq.md` (map). See `doc/design/binding.md`. -*> host_meta* +Return *[Bound Artifact Metadata from the entry .mq.md (map)](host_meta())*. ## meta_get - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Lookup one metadata key; missing → None | + +Use `key` as the inputs for this operation. + +Effects: pure. Lookup one metadata key; missing → None. -*> host_meta_get key=`key`* +Return *[Lookup one metadata key; missing → None](> host_meta_get key=`key`)*. ## artifact_kind +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Classify entry Artifact Metadata: `web` / `endpoint` / `prompt` / `other`, or None if no `type`/`类型` | + +Effects: pure. + Classify entry Artifact Metadata: `web` / `endpoint` / `prompt` / `other`, or None if no `type`/`类型`. ADR 0007. -*> host_artifact_kind* +Return *[Classify entry Artifact Metadata: web / endpoint / prompt / other, or None if no type/类型](host_artifact_kind())*. ## module_source +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Entry `.mq.md` source text (for document-as-prompt) | + +Effects: pure. + Entry `.mq.md` source text (for document-as-prompt). Empty string if unset. -*> host_module_source* +Return *[Entry .mq.md source text (for document-as-prompt)](host_module_source())*. ## exit - + `code` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| code | any | required | Process exit status; zero means success | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Exit process with code | + +Use `code` as the inputs for this operation. + +Effects: process.control. Exit process with code. -*> host_exit code=`code`* +Return *[Exit process with code](> host_exit code=`code`)*. ## exec - + `cmd` - + `args`=None - + `capture`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| cmd | any | required | Executable command or interpreter override | +| args | any | None | Argument list passed to the called command or function | +| capture | any | False | Whether to return command output instead of forwarding it | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Run a process | + +Use `cmd`, `args`=None, `capture`=False as the inputs for this operation. + +Effects: process.exec. Run a process. Default return is the exit code (int). @@ -83,11 +195,22 @@ With `capture=True`, return a map `{code, stdout, stderr}` (stdout/stderr may be Inside `**…**` prefer bare `args=args` (variable); `` args=`args` `` is also accepted. -*> host_exec cmd=`cmd` args=`args` capture=`capture`* +Return *[Run a process](> host_exec cmd=`cmd` args=`args` capture=`capture`)*. ## stream_publish - + `event` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| event | any | required | Structured event to publish to the active stream | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Publish a stream event map onto the process EventBus (`marqdo view` SSE) | + +Use `event` as the inputs for this operation. + +Effects: output.write. Publish a stream event map onto the process EventBus (`marqdo view` SSE). No-op when nothing is subscribed. -*> host_stream_publish event=`event`* +Return *[Publish a stream event map onto the process EventBus (marqdo view SSE)](> host_stream_publish event=`event`)*. diff --git a/lib/table.mq.md b/lib/table.mq.md index 2a29afa..afa0812 100644 --- a/lib/table.mq.md +++ b/lib/table.mq.md @@ -2,291 +2,1181 @@ markup: occlusion title: lib/table description: >- - List and map helpers. Prefer put (1-based path, same nesting as link-index get); + List and map helpers. Prefer put (1-based path, same nesting as access reads); at/set_at/slice are 0-based. Use lib/json only for parse/stringify. --- -List and map helpers. Prefer put for nested writes; authors should read with link-index get, not new footnote indexes. +List and map helpers. Prefer put for nested writes; authors should read with access reads, not new footnote indexes. + +Transform lists, maps and row records using explicit data shapes. + +Behavior and limits: put/access integer paths are one-based; at/slice/insert/remove_at are zero-based. Updates return new values: keep the result. rows is a length alias; from_columns/to_columns perform shape conversion. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/collection.rs](../src/host/collection.rs)、[src/host/collection_ops.rs](../src/host/collection_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. ## put - + `in` - + `at` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| in | any | required | Input collection; None seeds a new record | +| at | any | required | Text key, one-based index, or nested path of keys and indices | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Update one element of collection in at path at to value | + +Use `in`, `at`, `value` as the inputs for this operation. + +Effects: pure. Update one element of collection in at path at to value. -at is a text key, a 1-based list index, or a list of keys/indices (same nesting as link-index get). +at is a text key, a 1-based list index, or a list of keys/indices (same nesting as access reads). Caller: [table.put] in=None at="Authorization" value="Bearer-x" -*> host_collection_put in=`in` at=`at` value=`value`* +Return *[Update one element of collection in at path at to value](> host_collection_put in=`in` at=`at` value=`value`)*. ## len - + `xs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Length of list or map xs | + +Use `xs` as the inputs for this operation. + +Effects: pure. Length of list or map xs. -*> len `xs`* +Return *[Len](len(`xs`))*. ## rows - + `xs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Row count for list xs (alias of len) | + +Use `xs` as the inputs for this operation. + +Effects: pure. Row count for list xs (alias of len). -*> len `xs`* +Return *[Len](len(`xs`))*. ## at - + `xs` - + `i` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | +| i | number | required | Zero-based element or row index | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Zero-based index into xs at i (same as builtin at) | + +Use `xs`, `i` as the inputs for this operation. + +Effects: pure. Zero-based index into xs at i (same as builtin at). Out of range → None. -*> at value=`xs` index=`i`* +Return *[At](at(value=`xs`, index=`i`))*. ## row_at - + `xs` - + `i` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | +| i | number | required | Zero-based element or row index | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Zero-based row from xs at i | + +Use `xs`, `i` as the inputs for this operation. + +Effects: pure. Zero-based row from xs at i. -*> at value=`xs` index=`i`* +Return *[At](at(value=`xs`, index=`i`))*. ## append - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Append item to list | + +Use `list`, `item` as the inputs for this operation. + +Effects: pure. Append item to list. -*> host_list_append list=`list` item=`item`* +Return *[Append item to list](> host_list_append list=`list` item=`item`)*. ## prepend - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Prepend item to list | + +Use `list`, `item` as the inputs for this operation. + +Effects: pure. Prepend item to list. -*> host_list_prepend list=`list` item=`item`* +Return *[Prepend item to list](> host_list_prepend list=`list` item=`item`)*. ## concat - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First list; None is an empty-list seed | +| b | any | required | List appended after a | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Concatenate lists a and b | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. Concatenate lists a and b. -*> host_list_concat a=`a` b=`b`* +Return *[Concatenate lists a and b](> host_list_concat a=`a` b=`b`)*. ## insert - + `list` - + `index` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| index | number | required | Zero-based position to insert, replace or remove | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Insert item into list at zero-based index (may insert at len to append) | + +Use `list`, `index`, `item` as the inputs for this operation. + +Effects: pure. Insert item into list at zero-based index (may insert at len to append). -*> host_list_insert list=`list` index=`index` item=`item`* +Return *[Insert item into list at zero-based index (may insert at len to append)](> host_list_insert list=`list` index=`index` item=`item`)*. ## set_at - + `list` - + `index` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| index | number | required | Zero-based position to insert, replace or remove | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Zero-based replace of list at index with item | + +Use `list`, `index`, `item` as the inputs for this operation. + +Effects: pure. Zero-based replace of list at index with item. Prefer put with a 1-based index for author-facing edits. -*> host_list_set_at list=`list` index=`index` item=`item`* +Return *[Zero-based replace of list at index with item](> host_list_set_at list=`list` index=`index` item=`item`)*. ## remove_at - + `list` - + `index` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| index | number | required | Zero-based position to insert, replace or remove | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Remove zero-based index from list | + +Use `list`, `index` as the inputs for this operation. + +Effects: pure. Remove zero-based index from list. -*> host_list_remove_at list=`list` index=`index`* +Return *[Remove zero-based index from list](> host_list_remove_at list=`list` index=`index`)*. ## pop - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Drop the last item of list (errors if empty) | + +Use `list` as the inputs for this operation. + +Effects: pure. Drop the last item of list (errors if empty). Use last first when you need the removed value. -**`n` = > len `list`** +We retain **`n` = [Len](len(`list`))**. 1. `n` > 0 - *> host_list_remove_at list=`list` index=`n` - 1* + Return *[Drop the last item of list (errors if empty)](> host_list_remove_at list=`list` index=`n` - 1)*. 2. * - *> host_list_remove_at list=`list` index=0* + Return *[Drop the last item of list (errors if empty)](> host_list_remove_at list=`list` index=0)*. ## first - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | First item of list | + +Use `list` as the inputs for this operation. + +Effects: pure. First item of list. -*> host_list_first list=`list`* +Return *[First item of list](> host_list_first list=`list`)*. ## last - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Last item of list | + +Use `list` as the inputs for this operation. + +Effects: pure. Last item of list. -*> host_list_last list=`list`* +Return *[Last item of list](> host_list_last list=`list`)*. ## slice - + `list` - + `start` - + `end`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| start | number | required | Inclusive zero-based slice start | +| end | any | None | Exclusive zero-based slice end; None selects through the end | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Zero-based half-open slice of list from start to end | + +Use `list`, `start`, `end`=None as the inputs for this operation. + +Effects: pure. Zero-based half-open slice of list from start to end. -*> host_list_slice list=`list` start=`start` end=`end`* +Return *[Zero-based half-open slice of list from start to end](> host_list_slice list=`list` start=`start` end=`end`)*. ## contains - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether list contains item | + +Use `list`, `item` as the inputs for this operation. + +Effects: pure. Whether list contains item. -*> host_list_contains list=`list` item=`item`* +Return *[Whether list contains item](> host_list_contains list=`list` item=`item`)*. ## index_of - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| item | any | required | Element to insert, replace or compare | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Zero-based index of item in list, or None | + +Use `list`, `item` as the inputs for this operation. + +Effects: pure. Zero-based index of item in list, or None. -*> host_list_index_of list=`list` item=`item`* +Return *[Zero-based index of item in list, or None](> host_list_index_of list=`list` item=`item`)*. ## reverse - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Reverse list | + +Use `list` as the inputs for this operation. + +Effects: pure. Reverse list. -*> host_list_reverse list=`list`* +Return *[Reverse list](> host_list_reverse list=`list`)*. ## sort - + `list` -Ascending sort of list (int/num/text preferred). +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | -*> host_list_sort list=`list`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Stable ascending sort: numbers, text, bool, None, then structured values by type/display | + +Use `list` as the inputs for this operation. + +Effects: pure. + +Stable ascending sort: numbers, text, bool, None, then structured values by type/display. Numeric cross-type comparison preserves large integer order. + +Return *[Stable ascending sort: numbers, text, bool, None, then structured values by type/display](> host_list_sort list=`list`)*. ## sort_by - + `list` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| key | text | required | Field name or key required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Sort a list of maps by field key | + +Use `list`, `key` as the inputs for this operation. + +Effects: pure. Sort a list of maps by field key. -*> host_list_sort_by list=`list` key=`key`* +Return *[Sort a list of maps by field key](> host_list_sort_by list=`list` key=`key`)*. ## unique - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Stable unique of list (first wins) | + +Use `list` as the inputs for this operation. + +Effects: pure. Stable unique of list (first wins). -*> host_list_unique list=`list`* +Return *[Stable unique of list (first wins)](> host_list_unique list=`list`)*. ## chunk - + `list` - + `size` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | +| size | number | required | Positive number of elements per chunk | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Split list into chunks of size | + +Use `list`, `size` as the inputs for this operation. + +Effects: pure. Split list into chunks of size. -*> host_list_chunk list=`list` size=`size`* +Return *[Split list into chunks of size](> host_list_chunk list=`list` size=`size`)*. ## zip - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | First list of each pair | +| b | any | required | Second list of each pair | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Pair lists a and b until the shorter ends | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. Pair lists a and b until the shorter ends. -*> host_list_zip a=`a` b=`b`* +Return *[Pair lists a and b until the shorter ends](> host_list_zip a=`a` b=`b`)*. ## flatten - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | required | Input list; updates return a new list | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | One-level flatten of list | + +Use `list` as the inputs for this operation. + +Effects: pure. One-level flatten of list. -*> host_list_flatten list=`list`* +Return *[One-level flatten of list](> host_list_flatten list=`list`)*. ## clear - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Empty list or empty map for value (by type) | + +Use `value` as the inputs for this operation. + +Effects: pure. Empty list or empty map for value (by type). -*> host_collection_clear value=`value`* +Return *[Empty list or empty map for value (by type)](> host_collection_clear value=`value`)*. ## get - + `map` - + `key` -Shallow get from map at key. Missing → None. Prefer link-index get in author code. +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | +| key | text | required | Field name or key required by this operation | -*> host_map_get map=`map` key=`key`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Shallow get from map at key | + +Use `map`, `key` as the inputs for this operation. + +Effects: pure. + +Shallow get from map at key. Missing → None. Prefer access reads in author code. + +Return *[Shallow get from map at key](> host_map_get map=`map` key=`key`)*. ## set - + `map` - + `key` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | +| key | text | required | Field name or key required by this operation | +| value | any | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Shallow map update | + +Use `map`, `key`, `value` as the inputs for this operation. + +Effects: pure. Shallow map update. Prefer put for nested paths. -*> host_map_set map=`map` key=`key` value=`value`* +Return *[Shallow map update](> host_map_set map=`map` key=`key` value=`value`)*. ## delete - + `map` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | +| key | text | required | Field name or key required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Delete key from map | + +Use `map`, `key` as the inputs for this operation. + +Effects: pure. Delete key from map. -*> host_map_delete map=`map` key=`key`* +Return *[Delete key from map](> host_map_delete map=`map` key=`key`)*. ## has - + `map` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | +| key | text | required | Field name or key required by this operation | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether map has key | + +Use `map`, `key` as the inputs for this operation. + +Effects: pure. Whether map has key. -*> host_map_has map=`map` key=`key`* +Return *[Whether map has key](> host_map_has map=`map` key=`key`)*. ## keys - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Keys of map | + +Use `map` as the inputs for this operation. + +Effects: pure. Keys of map. -*> host_map_keys map=`map`* +Return *[Keys of map](> host_map_keys map=`map`)*. ## values - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Values of map | + +Use `map` as the inputs for this operation. + +Effects: pure. Values of map. -*> host_map_values map=`map`* +Return *[Values of map](> host_map_values map=`map`)*. ## items - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Key/value rows from map | + +Use `map` as the inputs for this operation. + +Effects: pure. Key/value rows from map. -*> host_map_items map=`map`* +Return *[Key/value rows from map](> host_map_items map=`map`)*. ## merge - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | required | Base record; None seeds an empty record | +| b | any | required | Record merged over a; later values win | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Merge maps a and b (right-hand keys win) | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. Merge maps a and b (right-hand keys win). -*> host_map_merge a=`a` b=`b`* +Return *[Merge maps a and b (right-hand keys win)](> host_map_merge a=`a` b=`b`)*. ## size - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | required | Input string-keyed map | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Key count of map | + +Use `map` as the inputs for this operation. + +Effects: pure. Key count of map. -*> host_map_size map=`map`* +Return *[Key count of map](> host_map_size map=`map`)*. ## empty_list +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Empty list | + +Effects: pure. + Empty list. -*> host_list_concat a=None b=None* +Return *[Empty list](> host_list_concat a=None b=None)*. ## empty_map +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Return a new empty map as a seed for immutable updates; this is not an empty list | + +Effects: pure. + Empty map. -*> host_map_merge a=None b=None* +Return a new empty map as a seed for immutable updates; this is not an empty list. + +Return *[Return a new empty map as a seed for immutable updates; this is not an empty list](> host_map_merge a=None b=None)*. + +## range + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| start | number | required | First numeric value of the sequence | +| end | number | required | Exclusive bound of the sequence | +| step | number | 1 | Nonzero range increment; sign must point toward the end | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items | + +Use `start`, `end`, `step`=1 as the inputs for this operation. + +Effects: pure. + +Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items. + +Return *[Generate a half-open integer sequence; negative steps are allowed, zero is rejected, at most 1000000 items](> host_table_range start=`start` end=`end` step=`step`)*. + +## enumerate + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| start | number | 0 | Index value assigned to the first record; default is one | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Return index/value records without modifying the input; index starts at start | + +Use `list`, `start`=0 as the inputs for this operation. + +Effects: pure. + +Return index/value records without modifying the input; index starts at start. + +Return *[Return index/value records without modifying the input; index starts at start](> host_table_enumerate list=`list` start=`start`)*. + +## pluck + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | text | required | Field name or storage key to read, compare or update | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Extract one field from every record; a missing field is an error instead of silently becoming None | + +Use `list`, `key` as the inputs for this operation. + +Effects: pure. + +Extract one field from every record; a missing field is an error instead of silently becoming None. + +Return *[Extract one field from every record; a missing field is an error instead of silently becoming None](> host_table_pluck list=`list` key=`key`)*. + +## project + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| keys | list | required | Ordered field-name list | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Keep the requested fields, in keys order; every requested field must exist | + +Use `list`, `keys` as the inputs for this operation. + +Effects: pure. + +Keep the requested fields, in keys order; every requested field must exist. + +Return *[Keep the requested fields, in keys order; every requested field must exist](> host_table_project list=`list` keys=`keys`)*. + +## where + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | text | required | Field name or storage key to read, compare or update | +| value | any | required | Value to transform or store, without mutating the input | +| op | text | "eq" | Operation name understood by this helper | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Keep matching records | + +Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. + +Effects: pure. + +Keep matching records. Operators: eq/ne/gt/ge/lt/le/contains/in; these are fixed operations, never code to evaluate. + +Return *[Keep matching records](> host_table_where list=`list` key=`key` value=`value` op=`op`)*. + +## group_by + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | text | required | Field name or storage key to read, compare or update | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Return first-seen ordered key/count/rows records; group keys keep their original value types | + +Use `list`, `key` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/table.mq.md group_by 'list=[{"team":"a","n":3},{"team":"b","n":1},{"team":"a","n":2}]' 'key="team"' --effects none --json +``` + +Return first-seen ordered key/count/rows records; group keys keep their original value types. + +Return *[Return first-seen ordered key/count/rows records; group keys keep their original value types](> host_table_group_by list=`list` key=`key`)*. + +## unique_by + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | text | required | Field name or storage key to read, compare or update | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Keep the first record per field value; input order is preserved | + +Use `list`, `key` as the inputs for this operation. + +Effects: pure. + +Keep the first record per field value; input order is preserved. + +Return *[Keep the first record per field value; input order is preserved](> host_table_unique_by list=`list` key=`key`)*. + +## aggregate + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | any | None | Field name or storage key to read, compare or update | +| op | text | "sum" | Operation name understood by this helper | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Aggregate scalar values or one record field: sum/count/min/max/mean | + +Use `list`, `key`=None, `op`="sum" as the inputs for this operation. + +Effects: pure. + +Aggregate scalar values or one record field: sum/count/min/max/mean. Empty sum/count is zero; empty min/max/mean fails; integer sum checks overflow. + +Return *[Aggregate scalar values or one record field: sum/count/min/max/mean](> host_table_aggregate list=`list` key=`key` op=`op`)*. + +## sort_keys + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| keys | list | required | Ordered field-name list | +| descending | bool | False | Whether the multi-key sort is descending | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order | + +Use `list`, `keys`, `descending`=False as the inputs for this operation. + +Effects: pure. + +Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order. + +Return *[Stable lexicographic sort by fields in keys order; descending reverses the comparison, keeping equal-key order](> host_table_sort_keys list=`list` keys=`keys` descending=`descending`)*. + +## rename + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| fields | map | required | Structured field/value record attached to the log event | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Rename fields using an old-name/new-name map; duplicate output names fail | + +Use `list`, `fields` as the inputs for this operation. + +Effects: pure. + +Rename fields using an old-name/new-name map; duplicate output names fail. + +Return *[Rename fields using an old-name/new-name map; duplicate output names fail](> host_table_rename list=`list` fields=`fields`)*. + +## from_columns + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| columns | map | required | Column-name/list record; all columns must have equal length | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Convert a column map to row records | + +Use `columns` as the inputs for this operation. + +Effects: pure. + +Convert a column map to row records. Every column must be a list of equal length; scalar object fields are not inferred as columns. + +Return *[Convert a column map to row records](> host_table_from_columns columns=`columns`)*. + +## to_columns + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | list | required | List of row records, rather than an implicit column map | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Convert records with identical field sets into a column map; empty input yields an empty map | + +Use `rows` as the inputs for this operation. + +Effects: pure. + +Convert records with identical field sets into a column map; empty input yields an empty map. + +Return *[Convert records with identical field sets into a column map; empty input yields an empty map](> host_table_to_columns rows=`rows`)*. + +## join + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First operand; its domain is described by this operation | +| b | list | required | Second operand; its domain is described by this operation | +| key | text | required | Field name or storage key to read, compare or update | +| right_key | text | required | Matching field in right-hand records | +| mode | text | "inner" | Join mode: inner or left | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Join records by field equality, preserving left and matching-right order | + +Use `a`, `b`, `key`, `right_key`, `mode`="inner" as the inputs for this operation. + +Effects: pure. + +Join records by field equality, preserving left and matching-right order. mode is inner/left; colliding right fields use right_ prefix; unresolved name collisions fail. + +Return *[Join records by field equality, preserving left and matching-right order](> host_table_join a=`a` b=`b` key=`key` right_key=`right_key` mode=`mode`)*. + +## cast + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | list | required | List of row records, rather than an implicit column map | +| schema | map | required | Field/type record using the standard contract type vocabulary | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field | + +Use `rows`, `schema` as the inputs for this operation. + +Effects: pure. + +Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field. Other fields survive. + +Return *[Convert schema fields to text/int/number/bool/any; missing or invalid cells report row and field](> host_table_cast rows=`rows` schema=`schema`)*. + +## union + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First operand; its domain is described by this operation | +| b | list | required | Second operand; its domain is described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Stable set union; first occurrences win, using the same type-sensitive equality as unique | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Stable set union; first occurrences win, using the same type-sensitive equality as unique. + +Return *[Stable set union; first occurrences win, using the same type-sensitive equality as unique](> host_table_union a=`a` b=`b`)*. + +## intersection + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First operand; its domain is described by this operation | +| b | list | required | Second operand; its domain is described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Stable set intersection; duplicates are removed | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Stable set intersection; duplicates are removed. + +Return *[Stable set intersection; duplicates are removed](> host_table_intersection a=`a` b=`b`)*. + +## difference + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | list | required | First operand; its domain is described by this operation | +| b | list | required | Second operand; its domain is described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Stable values in a but not b; duplicates are removed | + +Use `a`, `b` as the inputs for this operation. + +Effects: pure. + +Stable values in a but not b; duplicates are removed. + +Return *[Stable values in a but not b; duplicates are removed](> host_table_difference a=`a` b=`b`)*. + +## try_cast + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | list | required | List of row records, rather than an implicit column map | +| schema | map | required | Field/type record using the standard contract type vocabulary | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Recoverable cast; invalid fields return Result instead of aborting the caller | + +Use `rows`, `schema` as the inputs for this operation. + +Effects: pure. + +Recoverable cast; invalid fields return Result instead of aborting the caller. + +Return *[Recoverable cast; invalid fields return Result instead of aborting the caller](> host_table_try_cast rows=`rows` schema=`schema`)*. + +## validate + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| rows | list | required | List of row records, rather than an implicit column map | +| schema | map | required | Field/type record using the standard contract type vocabulary | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Validate required fields using core gradual types, returning Result with error | + +Use `rows`, `schema` as the inputs for this operation. + +Effects: pure. + +Validate required fields using core gradual types, returning Result with error.details row/field diagnostics. int is the core number alias; use cast for strict integer conversion. + +Return *[Validate required fields using core gradual types, returning Result with error.details row/field diagnostics](> host_table_validate rows=`rows` schema=`schema`)*. + +## find + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Ordered row records to test without changing their order | +| key | text | required | Field name whose value is compared in each row | +| value | any | required | Comparison operand; in tests membership in this supplied collection | +| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | First matching row, or None when no row matches | + +Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. + +Effects: pure. + +Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. + +We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. +Return *[First](first(list=`selected`))*. + +## any + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Ordered row records to test without changing their order | +| key | text | required | Field name whose value is compared in each row | +| value | any | required | Comparison operand; in tests membership in this supplied collection | +| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether at least one row matches; false on an empty list | + +Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. + +Effects: pure. + +Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. + +We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. +We retain **`matched` = [Len](len(`selected`))**. +Return *matched > 0*. + +## all + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Ordered row records to test without changing their order | +| key | text | required | Field name whose value is compared in each row | +| value | any | required | Comparison operand; in tests membership in this supplied collection | +| op | text | "eq" | Comparison: eq, ne, gt, ge, lt, le, contains or in; invalid operators fail | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether every row matches; true on an empty list | + +Use `list`, `key`, `value`, `op`="eq" as the inputs for this operation. + +Effects: pure. + +Use the same comparison as where. Missing fields and invalid operators still produce a diagnostic; the input rows remain unchanged. + +We retain **`selected` = [Where](where(list=`list`, key=`key`, value=`value`, op=`op`))**. +We retain **`matched` = [Len](len(`selected`))**. +We retain **`total` = [Len](len(`list`))**. +Return *matched == total*. + +## summarize + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | list | required | Input list; immutable updates return a new list | +| key | text | required | Field name or storage key to read, compare or update | +| field | text | required | Numeric field to aggregate within each group | +| op | text | "sum" | Operation name understood by this helper | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | Group by key and aggregate one field in a batch, returning first-seen key/count/value records | + +Use `list`, `key`, `field`, `op`="sum" as the inputs for this operation. + +Effects: pure. + +Group by key and aggregate one field in a batch, returning first-seen key/count/value records. Uses aggregate semantics and avoids repeatedly copying a growing output list in author loops. + +Return *[Group by key and aggregate one field in a batch, returning first-seen key/count/value records](> host_table_summarize list=`list` key=`key` field=`field` op=`op`)*. + +## from_pairs + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| pairs | list | required | Ordered row records with text key and arbitrary value fields; extra fields are ignored | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | New record in first-key insertion order; later entries replace an existing key's value | + +Effects: pure. + +The input `pairs` makes a long named record readable as an @ table with key/value columns. +Use this when a horizontal record would become too wide to inspect, such as prompt sections or +configuration fragments. It uses the same ordinary row records and immutable map update as the +rest of this library; no JSON text or alternate schema language is parsed. An empty list returns +an empty record. Invalid keys are rejected by put, rather than silently creating a dummy column. + +We begin with **record = [Create a new record](empty_map())**. Each row contributes one explicit +field; repeated keys update that field while keeping the position of its first occurrence. + +- [Copy each named field into the new record](遍历 pairs 为 pair) + Read **key = [Read this row's field name](access(pair, "key"))** + and **value = [Read this row's field value](access(pair, "value"))**. + We retain **record = [Set this field without changing the input rows](put(in=`record`, at=`key`, value=`value`))**. + +After processing the ordered rows, return *record*. The original pairs remain available to the +caller; this function performs no filesystem, network or plugin operation. diff --git a/lib/text.mq.md b/lib/text.mq.md index 32c211e..f77a971 100644 --- a/lib/text.mq.md +++ b/lib/text.mq.md @@ -6,93 +6,230 @@ description: Text helpers (Mid M4). Literal replace — use lib/re for regex. Small text helpers. Prefer these over hand-rolled splits; regex belongs in lib/re. +Clean and combine Unicode text. + +Behavior and limits: Use re for patterns and bytes for arbitrary binary. split and join use exact separators; no implicit document parsing. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/text_ops.rs](../src/host/text_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## str_trim - + `s` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| s | text | required | Input text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Trim ends of string s | + +Use `s` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/text.mq.md str_trim 's=" readable text "' --effects none --json +``` Trim ends of string s. -*> trim `s`* +Return *[Trim](trim(`s`))*. ## str_split - + `s` - + `sep` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| s | text | required | Input text | +| sep | text | required | Text separator used for splitting or joining | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | Split string s on separator sep | + +Use `s`, `sep` as the inputs for this operation. + +Effects: pure. Split string s on separator sep. -*> split value=`s` sep=`sep`* +Return *[Split](split(value=`s`, sep=`sep`))*. ## str_join - + `xs` - + `sep` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | required | Input list or collection, as required by this operation | +| sep | text | required | Text separator used for splitting or joining | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Join list xs with separator sep | + +Use `xs`, `sep` as the inputs for this operation. + +Effects: pure. Join list xs with separator sep. -*> join value=`xs` sep=`sep`* +Return *[Join](join(value=`xs`, sep=`sep`))*. ## contains - + `text` - + `sub` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| sub | any | required | Substring to search for | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether text contains substring sub | + +Use `text`, `sub` as the inputs for this operation. + +Effects: pure. Whether text contains substring sub. Caller: [text.contains] text="hello" sub="ell" -*> host_text_contains text=`text` sub=`sub`* +Return *[Whether text contains substring sub](> host_text_contains text=`text` sub=`sub`)*. ## starts_with - + `text` - + `prefix` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| prefix | text | required | Prefix added to the generated name or tested against text | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether text starts with prefix | + +Use `text`, `prefix` as the inputs for this operation. + +Effects: pure. Whether text starts with prefix. -*> host_text_starts_with text=`text` prefix=`prefix`* +Return *[Whether text starts with prefix](> host_text_starts_with text=`text` prefix=`prefix`)*. ## ends_with - + `text` - + `suffix` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| suffix | any | required | Text suffix to test | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | Whether text ends with suffix | + +Use `text`, `suffix` as the inputs for this operation. + +Effects: pure. Whether text ends with suffix. -*> host_text_ends_with text=`text` suffix=`suffix`* +Return *[Whether text ends with suffix](> host_text_ends_with text=`text` suffix=`suffix`)*. ## replace - + `text` - + `old` - + `new` - + `count`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| old | any | required | Exact substring to replace | +| new | any | required | Replacement text | +| count | any | None | Maximum replacement count; None uses the documented default | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Literal replace in text: replace old with new, optional count | + +Use `text`, `old`, `new`, `count`=None as the inputs for this operation. + +Effects: pure. Literal replace in text: replace old with new, optional count. -*> host_text_replace text=`text` old=`old` new=`new` count=`count`* +Return *[Literal replace in text: replace old with new, optional count](> host_text_replace text=`text` old=`old` new=`new` count=`count`)*. ## to_upper - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Uppercase text | + +Use `text` as the inputs for this operation. + +Effects: pure. Uppercase text. -*> host_text_to_upper text=`text`* +Return *[Uppercase text](> host_text_to_upper text=`text`)*. ## to_lower - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Lowercase text | + +Use `text` as the inputs for this operation. + +Effects: pure. Lowercase text. -*> host_text_to_lower text=`text`* +Return *[Lowercase text](> host_text_to_lower text=`text`)*. ## repeat - + `text` - + `n` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| n | number | required | Number of repetitions | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Repeat text n times | + +Use `text`, `n` as the inputs for this operation. + +Effects: pure. Repeat text n times. -*> host_text_repeat text=`text` n=`n`* +Return *[Repeat text n times](> host_text_repeat text=`text` n=`n`)*. ## pad - + `text` - + `width` - + `fill`=None - + `align`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| width | number | required | Target padded character width | +| fill | any | None | Single padding character | +| align | any | None | Padding alignment: left, right or center | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Pad text to width with fill and align (left / right / center) | + +Use `text`, `width`, `fill`=None, `align`=None as the inputs for this operation. + +Effects: pure. Pad text to width with fill and align (left / right / center). -*> host_text_pad text=`text` width=`width` fill=`fill` align=`align`* +Return *[Pad text to width with fill and align (left / right / center)](> host_text_pad text=`text` width=`width` fill=`fill` align=`align`)*. diff --git a/lib/time.mq.md b/lib/time.mq.md index 0fd6fe5..5df4608 100644 --- a/lib/time.mq.md +++ b/lib/time.mq.md @@ -6,39 +6,100 @@ description: English time wrappers Unix time, format, parse, and sleep helpers. +Format Unix time and control elapsed waits. + +Behavior and limits: now reads the clock; sleep controls execution and is clamped in capture. Calendar arithmetic and IANA rules live in datetime. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/time.rs](../src/host/time.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## now_unix +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Current Unix time in seconds | + +Effects: time.read. + Current Unix time in seconds. Caller: [time.now_unix] -*> host_now_unix* +Return *[Current Unix time in seconds](host_now_unix())*. ## now_ms +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Current Unix time in milliseconds | + +Effects: time.read. + Current Unix time in milliseconds. -*> host_now_ms* +Return *[Current Unix time in milliseconds](host_now_ms())*. ## format - + `unix` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| unix | number | required | Unix timestamp in seconds | +| pattern | text | required | strftime date/time format string | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Format unix seconds with pattern | + +Use `unix`, `pattern` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/time.mq.md format unix=0 'pattern="%Y-%m-%d"' --effects none --json +``` Format unix seconds with pattern. -*> host_format_time unix=`unix` pattern=`pattern`* +Return *[Format unix seconds with pattern](> host_format_time unix=`unix` pattern=`pattern`)*. ## sleep_ms - + `ms` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| ms | any | required | Duration or delay in milliseconds | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Sleep for ms milliseconds | + +Use `ms` as the inputs for this operation. + +Effects: process.control. Sleep for ms milliseconds. -*> host_sleep_ms ms=`ms`* +Return *[Sleep for ms milliseconds](> host_sleep_ms ms=`ms`)*. ## parse - + `text` - + `pattern` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | +| pattern | text | required | strftime date/time format string | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | Parse text as time with pattern; returns unix seconds | + +Use `text`, `pattern` as the inputs for this operation. + +Effects: pure. Parse text as time with pattern; returns unix seconds. -*> host_parse_time text=`text` pattern=`pattern`* +Return *[Parse text as time with pattern; returns unix seconds](> host_parse_time text=`text` pattern=`pattern`)*. diff --git a/lib/toml.mq.md b/lib/toml.mq.md index b5ba000..9f7dcf1 100644 --- a/lib/toml.mq.md +++ b/lib/toml.mq.md @@ -1,16 +1,79 @@ --- markup: occlusion title: lib/toml -description: Read-only TOML subset parse (Mid2 M8). Tables, scalars, arrays; no array-of-tables. +description: TOML parse/stringify with inline tables, multiline strings and arrays-of-tables. Dates become ISO text. --- -Read-only TOML subset. Prefer for config files; not a full TOML writer. +Read and write standard TOML configurations. Datetime scalars become ISO text; serialization does not preserve comments. + +Read and write standard TOML configuration data. + +Behavior and limits: Supports inline tables, multiline strings and arrays-of-tables. TOML dates become ISO text. Serialization rejects None and does not preserve original comments. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/toml_ops.rs](../src/host/toml_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. ## parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Parse TOML text into maps/lists/scalars | + +Use `text` as the inputs for this operation. + +Effects: pure. Parse TOML text into maps/lists/scalars. Caller: [toml.parse] text=`cfg` -*> host_toml_parse text=`text`* +Return *[Parse TOML text into maps/lists/scalars](> host_toml_parse text=`text`)*. + +## stringify + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | map | required | Value to transform or store, without mutating the input | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments | + +Use `value` as the inputs for this operation. + +Effects: pure. + +Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments. + +Return *[Serialize a map as TOML, rejecting None and unsupported value kinds; does not preserve source comments](> host_toml_stringify value=`value`)*. + +## try_parse + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text to read, transform or emit as described by this operation | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/toml.mq.md try_parse 'text="name="Marqdo""' --effects none --json +``` + +Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text. + +Return *[Recoverable TOML parsing supports inline tables, multiline strings and arrays-of-tables; datetime scalars become ISO text](> host_toml_try_parse text=`text`)*. diff --git a/lib/url.mq.md b/lib/url.mq.md index 79b4a05..b4cac87 100644 --- a/lib/url.mq.md +++ b/lib/url.mq.md @@ -6,25 +6,74 @@ description: Parse URLs and query strings (Mid2 M7). Segment encoding stays in n Parse URLs and query strings. Segment encoding stays in net.url_encode. +Parse addresses and repeated query parameters. + +Behavior and limits: Repeated query keys become lists; do not assume every map value is scalar. URL encoding is distinct from HTML escaping. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/url_ops.rs](../src/host/url_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Parse URL text into scheme, userinfo, host, port, path, query, fragment | + +Use `text` as the inputs for this operation. + +Effects: pure. Parse URL text into scheme, userinfo, host, port, path, query, fragment. Caller: [url.parse] text=`u` -*> host_url_parse text=`text`* +Return *[Parse URL text into scheme, userinfo, host, port, path, query, fragment](> host_url_parse text=`text`)*. ## query_parse - + `text` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | required | Text supplied by the caller | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Parse a=1&b=2 into a map; repeated keys become a list | + +Use `text` as the inputs for this operation. + +Effects: pure. + +Call this function directly: + +```sh +marqdo call lib/url.mq.md query_parse 'text="tag=a&tag=b&name=Marqdo"' --effects none --json +``` Parse a=1&b=2 into a map; repeated keys become a list. -*> host_url_query_parse text=`text`* +Return *[Parse a=1&b=2 into a map; repeated keys become a list](> host_url_query_parse text=`text`)*. ## query_stringify - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | map | required | Input string-keyed map | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | Build a query string from map | + +Use `map` as the inputs for this operation. + +Effects: pure. Build a query string from map. -*> host_url_query_stringify map=`map`* +Return *[Build a query string from map](> host_url_query_stringify map=`map`)*. diff --git a/lib/uuid.mq.md b/lib/uuid.mq.md index 58b0797..3c508fa 100644 --- a/lib/uuid.mq.md +++ b/lib/uuid.mq.md @@ -6,10 +6,32 @@ description: UUID v4 (Mid M6). Cryptographic random via getrandom. Random UUID helpers. Prefer this over rolling your own ids. +Create UUID v4 identifiers. + +Behavior and limits: Identifiers use system entropy and are not reproducible constants. Do not treat UUID strings as authorization tokens. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Implementation: [src/host/uuid_ops.rs](../src/host/uuid_ops.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## v4 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | New UUID version 4 string | + +Effects: random.read. + +Call this function directly: + +```sh +marqdo call lib/uuid.mq.md v4 --effects random.read --json +``` + New UUID version 4 string. Caller: [uuid.v4] -*> host_uuid_v4* +Return *[New UUID version 4 string](host_uuid_v4())*. diff --git a/lib/writeback.mq.md b/lib/writeback.mq.md index 118b4b6..4bea4a8 100644 --- a/lib/writeback.mq.md +++ b/lib/writeback.mq.md @@ -6,52 +6,133 @@ description: Persist run output in .mq.md (Jupyter-style writeback) Persist run output in .mq.md (Jupyter-style writeback) +Read and maintain persisted execution-output slots. + +Behavior and limits: record/get default to the current entry call site. Named slots isolate outputs. This API does not edit arbitrary document sections; use document for structural transforms. + +This single source file is the usage and development manual. Import it directly, or use marqdo call with a function heading below. Parameter tables give types and defaults; required parameters must be supplied. Return tables are progressive contracts; prose describes failure and limits. + +Relative IO paths use --fs-root, or the called file directory when omitted. Writes require explicit fs.write grants, subprocesses require process.exec, and pure transforms require no IO grant. + +Implementation: [src/host/writeback.rs](../src/host/writeback.rs) + +For development, keep EN/ZH behavior aligned and compose public libraries first. Add host primitives only at OS or algorithm boundaries and declare their effects. Run marqdo check --narrative-ratio on this file and the real workflows in tests/stdlib_tasks.rs after edits. + ## record - + `value` - + `at_end`=False - + `key`=None - + `line`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | required | Value to transform or store, without mutating the input | +| at_end | bool | False | Whether to append to the end of the target block | +| key | any | None | Field name or key required by this operation | +| line | any | None | Text line to add to the managed writeback block | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Write `value` into the entry file | + +Use `value`, `at_end`=False, `key`=None, `line`=None as the inputs for this operation. + +Effects: fs.write. Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `![marqdo-out](…)` (or `![marqdo-out key](…)`); other values use ``. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask). -*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`* +Return *[Write value into the entry file](> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`)*. ## get - + `at_end`=False - + `key`=None - + `line`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| at_end | bool | False | Whether to append to the end of the target block | +| key | any | None | Field name or key required by this operation | +| line | any | None | Text line to add to the managed writeback block | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when `at_end=true`, or a named slot when `key=` is set | + +Use `at_end`=False, `key`=None, `line`=None as the inputs for this operation. + +Effects: fs.read. Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when `at_end=true`, or a named slot when `key=` is set. -*> host_writeback_get at_end=`at_end` key=`key` line=`line`* +Return *[Read persisted output for the current call site (adjacent unkeyed block), the unkeyed EOF block when at_end=true, or a named slot when key= is set](> host_writeback_get at_end=`at_end` key=`key` line=`line`)*. ## clear - + `at_end`=False - + `key`=None - + `line`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| at_end | bool | False | Whether to append to the end of the target block | +| key | any | None | Field name or key required by this operation | +| line | any | None | Text line to add to the managed writeback block | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Remove the adjacent, EOF, or named output block | + +Use `at_end`=False, `key`=None, `line`=None as the inputs for this operation. + +Effects: fs.write. Remove the adjacent, EOF, or named output block. -*> host_writeback_clear at_end=`at_end` key=`key` line=`line`* +Return *[Remove the adjacent, EOF, or named output block](> host_writeback_clear at_end=`at_end` key=`key` line=`line`)*. ## ensure - + `key` - + `placeholder`=pending - + `line`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| key | text | required | Field name or key required by this operation | +| placeholder | any | "pending" | Placeholder used when creating the managed block | +| line | any | None | Text line to add to the managed writeback block | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | Create a named slot with `placeholder` if missing | + +Use `key`, `placeholder`="pending", `line`=None as the inputs for this operation. + +Effects: fs.write. Create a named slot with `placeholder` if missing. Never overwrites an existing slot body. -*> host_writeback_ensure key=`key` placeholder=`placeholder` line=`line`* +Return *[Create a named slot with placeholder if missing](> host_writeback_ensure key=`key` placeholder=`placeholder` line=`line`)*. ## list +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | List managed output slots from the current entry source without writing or reading another file | + +Effects: fs.read. + List all output blocks in the entry file (includes `key` when named). -*> host_writeback_list* +List managed output slots from the current entry source without writing or reading another file. + +Return *[List managed output slots from the current entry source without writing or reading another file](host_writeback_list())*. ## scan_path - + `path` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | required | Path relative to the granted filesystem root | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection) | + +Use `path` as the inputs for this operation. + +Effects: fs.read. + +Call this function directly: + +```sh +marqdo call lib/writeback.mq.md scan_path 'path="lib/writeback.mq.md"' --effects fs.read --fs-root . --json +``` List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection). -*> host_writeback_scan_path path=`path`* +Return *[List writeback slots in any file (HTML comment and !marqdo-out(…) image forms; workbook inspection)](> host_writeback_scan_path path=`path`)*. diff --git a/lib/命令行.mq.md b/lib/命令行.mq.md index 4dbd947..14b848b 100644 --- a/lib/命令行.mq.md +++ b/lib/命令行.mq.md @@ -6,11 +6,38 @@ description: 解析命令行参数(中层 M5)。--键 值 / --键=值 / -- 把进程参数解析成映射。开关与位置参(落在 _)。 +把命令行词元转换为标志和位置参数。 + +能力与边界:参数值保持文本,裸标志变为布尔值,位置参数位于下划线键。省略输入时使用宿主参数;不提供完整的参数约束模式系统。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/cli.rs](../src/host/cli.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 解析 - + `参数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 参数 | any | None | 命令行 token 列表;None 读取当前宿主 argv | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 解析 --键 值 / --键=值 / --开关 | + +这里使用`参数`=None。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/命令行.mq.md 解析 '参数=["report","--count=3","--quiet"]' --effects none --json +``` 解析 --键 值 / --键=值 / --开关。裸 --开关 若当布尔,后面不要紧跟非选项词(开关放最后,或写 --开关=true)。位置参进 _。省略参数时用进程 argv(系统.参数表)。 调用例:[命令行.解析] -*> host_cli_parse args=`参数`* +完成后返回*[解析 --键 值 / --键=值 / --开关](> host_cli_parse args=`参数`)*。 diff --git a/lib/哈希.mq.md b/lib/哈希.mq.md index 24b168e..25a9a40 100644 --- a/lib/哈希.mq.md +++ b/lib/哈希.mq.md @@ -6,33 +6,93 @@ description: 摘要与 HMAC(中层 M3)。完整性 / 缓存键 — 非密码 摘要与 HMAC。用于完整性与缓存键 — 不是密码存储。 +计算内容摘要与消息认证。 + +能力与边界:MD5 和 SHA1 用于兼容性校验,不用于保存密码。密码使用安全扩展;大文件和二进制摘要使用文件库的文件摘要。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/hash.rs](../src/host/hash.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 哈希256 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 内容的 SHA-256 十六进制摘要 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/哈希.mq.md 哈希256 '内容="abc"' --effects none --json +``` 内容的 SHA-256 十六进制摘要。 调用例:[哈希.哈希256] 内容=`s` -*> host_hash_sha256 text=`内容`* +完成后返回*[内容的 SHA-256 十六进制摘要](> host_hash_sha256 text=`内容`)*。 ## 哈希1 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 内容的 SHA-1 十六进制摘要 | + +这里使用`内容`。 + +调用效应:pure。 内容的 SHA-1 十六进制摘要。 -*> host_hash_sha1 text=`内容`* +完成后返回*[内容的 SHA-1 十六进制摘要](> host_hash_sha1 text=`内容`)*。 ## md5 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 内容的 MD5 十六进制摘要 | + +这里使用`内容`。 + +调用效应:pure。 内容的 MD5 十六进制摘要。 -*> host_hash_md5 text=`内容`* +完成后返回*[内容的 MD5 十六进制摘要](> host_hash_md5 text=`内容`)*。 ## 密钥哈希256 - + `密钥` - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 密钥 | any | 必填 | 要读取、比较或更新的字段名或存储键 | +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 用密钥对内容做 HMAC-SHA256 | + +这里使用`密钥`、`内容`。 + +调用效应:pure。 用密钥对内容做 HMAC-SHA256。 -*> host_hash_hmac_sha256 key=`密钥` text=`内容`* +完成后返回*[用密钥对内容做 HMAC-SHA256](> host_hash_hmac_sha256 key=`密钥` text=`内容`)*。 diff --git a/lib/地址.mq.md b/lib/地址.mq.md index e839f39..6f39124 100644 --- a/lib/地址.mq.md +++ b/lib/地址.mq.md @@ -6,25 +6,74 @@ description: 解析 URL 与查询串(中层 Mid2 M7)。单段编码仍用网 解析 URL 与查询串。单段编码仍用网络.网址编码。 +解析地址与重复查询参数。 + +能力与边界:重复查询键返回列表,不应假设所有值都是标量。地址编码和 HTML 转义是不同操作。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/url_ops.rs](../src/host/url_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 解析 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把 URL 解析成 scheme / userinfo / host / port / path / query / fragment | + +这里使用`内容`。 + +调用效应:pure。 把 URL 解析成 scheme / userinfo / host / port / path / query / fragment。 调用例:[地址.解析] 内容=`u` -*> host_url_parse text=`内容`* +完成后返回*[把 URL 解析成 scheme / userinfo / host / port / path / query / fragment](> host_url_parse text=`内容`)*。 ## 查询解析 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把 a=1&b=2 解析成映射;重复键变成列表 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/地址.mq.md 查询解析 '内容="tag=a&tag=b&name=Marqdo"' --effects none --json +``` 把 a=1&b=2 解析成映射;重复键变成列表。 -*> host_url_query_parse text=`内容`* +完成后返回*[把 a=1&b=2 解析成映射;重复键变成列表](> host_url_query_parse text=`内容`)*。 ## 查询串化 - + `表` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 表 | any | 必填 | 输入记录;操作说明允许时 None 可用作空记录种子 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 把映射编成查询串 | + +这里使用`表`。 + +调用效应:pure。 把映射编成查询串。 -*> host_url_query_stringify map=`表`* +完成后返回*[把映射编成查询串](> host_url_query_stringify map=`表`)*。 diff --git a/lib/外联.mq.md b/lib/外联.mq.md index c0787f5..f01ffb3 100644 --- a/lib/外联.mq.md +++ b/lib/外联.mq.md @@ -8,59 +8,113 @@ import: 通过本机解释器运行绑定的代码围栏与内联源码。 +向外部语言进程与会话明确传递数据。 + +能力与边界:语言已配置不代表解释器已安装。执行接口提供退出码、超时和输出限额,需要 process.exec;持久会话由创建者负责关闭,不透明句柄不能伪造或 JSON 序列化。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/foreign.rs](../src/host/foreign.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 设置命令 - + `语言` - + `命令` - + `参数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python | +| 命令 | any | 必填 | 可执行命令或解释器覆盖配置 | +| 参数 | any | None | 传给命令或函数的实参列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 为语言绑定解释器命令;可选附加参数 | + +这里使用`语言`、`命令`、`参数`=None。 + +调用效应:pure。 为语言绑定解释器命令;可选附加参数。 -*> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`* +完成后返回*[为语言绑定解释器命令;可选附加参数](> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`)*。 ## 运行 - + `代码` - + `标准输入`=None - + `环境`=None - + `工作目录`=None - + `超时`=None - + `参数`=None - + `最大输出`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 代码 | any | 必填 | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | +| 标准输入 | any | None | 写入子进程标准输入的文本 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 附加参数与输出上限 | + +这里使用`代码`、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None。 + +调用效应:process.exec。 运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 附加参数与输出上限。返回 stdout 文本;非 0 退出即报错。 调用例:[外联.运行] 代码=`块` -*> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`* +完成后返回*[运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、 附加参数与输出上限](> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`)*。 ## 按语言运行 - + `语言` - + `源码` - + `标准输入`=None - + `环境`=None - + `工作目录`=None - + `超时`=None - + `参数`=None - + `最大输出`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python | +| 源码 | any | 必填 | 交给指定解释器执行的源文本 | +| 标准输入 | any | None | 写入子进程标准输入的文本 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 用语言运行源码文本;选项同“运行” | + +这里使用`语言`、`源码`、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None。 + +调用效应:process.exec。 用语言运行源码文本;选项同“运行”。 -*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`* +完成后返回*[用语言运行源码文本;选项同“运行”](> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`)*。 ## 执行 - + `代码`=None - + `语言`=None - + `源码`=None - + `标准输入`=None - + `输入`=None - + `环境`=None - + `工作目录`=None - + `超时`=None - + `参数`=None - + `输出`=auto - + `最大输出`=None - + `命令`=None - + `保留`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | +| 语言 | any | None | 已注册的解释器语言标识,例如 python | +| 源码 | any | None | 交给指定解释器执行的源文本 | +| 标准输入 | any | None | 写入子进程标准输入的文本 | +| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 输出 | any | "auto" | 结果解码方式:auto、text、json 或 lines | +| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | +| 命令 | any | None | 可执行命令或解释器覆盖配置 | +| 保留 | any | False | 是否保留生成的脚本以便检查 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错 | + +这里使用`代码`=None、`语言`=None、`源码`=None、`标准输入`=None、`输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`输出`="auto"、`最大输出`=None、`命令`=None、`保留`=False。 + +调用效应:process.exec。 运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错。 字段:ok、code、stdout、stderr、ms、lang、cmd、timed_out、truncated、 @@ -69,173 +123,389 @@ result、result_error、error、script、cached。 `输入` 会编码为 JSON 写入 stdin(与 `标准输入` 互斥)。`输出` 可取 auto | text | json | lines。`命令` 仅本次覆盖解释器。 -*> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`* +完成后返回*[运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错](> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`)*。 ## 探测 - + `语言`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | None | 已注册的解释器语言标识,例如 python | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 探测一个语言;省略语言时探测所有已知语言 | + +这里使用`语言`=None。 + +调用效应:process.exec。 探测一个语言;省略语言时探测所有已知语言。返回 {lang, cmd, path, ok, version, error}(省略语言时是列表)。 -*> host_foreign_probe lang=`语言`* +完成后返回*[探测一个语言;省略语言时探测所有已知语言](> host_foreign_probe lang=`语言`)*。 ## 注册 - + `语言` - + `命令`=None - + `参数`=None - + `模板`=None - + `扩展名`=None - + `环境`=None - + `版本参数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python | +| 命令 | any | None | 可执行命令或解释器覆盖配置 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 模板 | any | None | 解释器启动模板 | +| 扩展名 | any | None | 临时脚本的文件扩展名 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 版本参数 | any | None | 查询解释器版本时使用的参数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 注册语言调用 | + +这里使用`语言`、`命令`=None、`参数`=None、`模板`=None、`扩展名`=None、`环境`=None、`版本参数`=None。 + +调用效应:pure。 注册语言调用。提供命令(+参数)或模板(占位符 {file}、{dir}、{base}、{inline}、{lang}、{cwd});二者互斥。 -*> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`* +完成后返回*[注册语言调用](> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`)*。 ## 注销 - + `语言` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 移除进程内注册;预设 / 配置 / 环境变量仍然生效 | + +这里使用`语言`。 + +调用效应:pure。 移除进程内注册;预设 / 配置 / 环境变量仍然生效。 -*> host_foreign_unset lang=`语言`* +完成后返回*[移除进程内注册;预设 / 配置 / 环境变量仍然生效](> host_foreign_unset lang=`语言`)*。 ## 加载配置 - + `路径`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量 | + +这里使用`路径`=None。 + +调用效应:fs.read。 加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量。 -*> host_foreign_load_config path=`路径`* +完成后返回*[加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量](> host_foreign_load_config path=`路径`)*。 ## 调用 - + `代码`=None - + `语言`=None - + `源码`=None - + `输入`=None - + `标准输入`=None - + `环境`=None - + `工作目录`=None - + `超时`=None - + `参数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | +| 语言 | any | None | 已注册的解释器语言标识,例如 python | +| 源码 | any | None | 交给指定解释器执行的源文本 | +| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | +| 标准输入 | any | None | 写入子进程标准输入的文本 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | +| 参数 | any | None | 传给命令或函数的实参列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回值 (stdout 为空 → None) | + +这里使用`代码`=None、`语言`=None、`源码`=None、`输入`=None、`标准输入`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None。 + +调用效应:process.exec。 JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回值 (stdout 为空 → None)。进程失败或 JSON 非法时报错。 -*> host_foreign_call code=`代码` lang=`语言` source=`源码` input=`输入` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数`* +完成后返回*[JSON 进 / JSON 出:把 输入 编码到 stdin,解析 stdout JSON 返回值 (stdout 为空 → None)](> host_foreign_call code=`代码` lang=`语言` source=`源码` input=`输入` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数`)*。 ## 批量运行 - + `任务表` - + `并发`=4 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务表 | any | 必填 | 按顺序排列的代码或语言与源码运行记录 | +| 并发 | any | 4 | 最大并发操作数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录 | + +这里使用`任务表`、`并发`=4。 + +调用效应:process.exec。 并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录。单项失败不影响其它项。 -*> host_foreign_run_many runs=`任务表` concurrency=`并发`* +完成后返回*[并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录](> host_foreign_run_many runs=`任务表` concurrency=`并发`)*。 ## 批量调用 - + `输入表` - + `代码`=None - + `语言`=None - + `源码`=None - + `命令`=None - + `环境`=None - + `工作目录`=None - + `超时`=None - + `参数`=None - + `最大输出`=None - + `并发`=4 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 输入表 | any | 必填 | 批量调用所用的输入值 | +| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | +| 语言 | any | None | 已注册的解释器语言标识,例如 python | +| 源码 | any | None | 交给指定解释器执行的源文本 | +| 命令 | any | None | 可执行命令或解释器覆盖配置 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 最大输出 | any | None | 捕获输出的字节上限;None 使用宿主默认值 | +| 并发 | any | 4 | 最大并发操作数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果 | + +这里使用`输入表`、`代码`=None、`语言`=None、`源码`=None、`命令`=None、`环境`=None、`工作目录`=None、`超时`=None、`参数`=None、`最大输出`=None、`并发`=4。 + +调用效应:process.exec。 把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果。 全部结束后若任一项失败,报错并指出下标。 -*> host_foreign_call_many inputs=`输入表` code=`代码` lang=`语言` source=`源码` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出` concurrency=`并发`* +完成后返回*[把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果](> host_foreign_call_many inputs=`输入表` code=`代码` lang=`语言` source=`源码` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出` concurrency=`并发`)*。 ## 会话 - + `内核表`=None - + `单元表`=None - + `值表`=None - + `输入表`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内核表 | any | None | 持久解释器的内核或会话规格 | +| 单元表 | any | None | 在持久解释器中求值的代码单元 | +| 值表 | any | None | 注入会话的变量与值记录 | +| 输入表 | any | None | 批量调用所用的输入值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 声明文档视图会话 | + +这里使用`内核表`=None、`单元表`=None、`值表`=None、`输入表`=None。 + +调用效应:pure。 声明文档视图会话。内核表和单元表都是普通表格;返回一个 foreign 会话句柄, 供 view 消费。没有这个句柄时,view 的 cells 是无状态的。 -**p = > table.empty_map** -**p = > table.put in=`p` at="kind" value="foreign-session"** -**p = > table.put in=`p` at="kernels" value=`内核表`** -**p = > table.put in=`p` at="cells" value=`单元表`** -**p = > table.put in=`p` at="values" value=`值表`** -**p = > table.put in=`p` at="inputs" value=`输入表`** -*p* +得到**`p` = [调用 empty map](table.empty_map())**。 +得到**`p` = [在新记录中设置 kind 字段](table.put(in=`p`, at="kind", value="foreign-session"))**。 +得到**`p` = [在新记录中设置 kernels 字段](table.put(in=`p`, at="kernels", value=`内核表`))**。 +得到**`p` = [在新记录中设置 cells 字段](table.put(in=`p`, at="cells", value=`单元表`))**。 +得到**`p` = [在新记录中设置 values 字段](table.put(in=`p`, at="values", value=`值表`))**。 +得到**`p` = [在新记录中设置 inputs 字段](table.put(in=`p`, at="inputs", value=`输入表`))**。 +完成后返回*p*。 ## 会话开启 - + `语言` - + `命令`=None - + `环境`=None - + `工作目录`=None - + `超时`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 语言 | any | 必填 | 已注册的解释器语言标识,例如 python | +| 命令 | any | None | 可执行命令或解释器覆盖配置 | +| 环境 | any | None | 传给子进程的环境变量与值记录 | +| 工作目录 | any | None | 子进程工作目录 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 启动一个持久的 Python / Node 内核;返回会话 id | + +这里使用`语言`、`命令`=None、`环境`=None、`工作目录`=None、`超时`=None。 + +调用效应:process.exec。 启动一个持久的 Python / Node 内核;返回会话 id。`超时` 是每次求值的默认超时。 -*> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`* +完成后返回*[启动一个持久的 Python / Node 内核;返回会话 id](> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`)*。 ## 会话求值 - + `标识` - + `代码`=None - + `源码`=None - + `输入`=None - + `标准输入`=None - + `超时`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | +| 代码 | any | None | 已绑定的代码围栏值;内联文本请使用语言与源码参数 | +| 源码 | any | None | 交给指定解释器执行的源文本 | +| 输入 | any | None | 编码为 JSON 后写入标准输入的结构化值;不能与标准输入文本同时使用 | +| 标准输入 | any | None | 写入子进程标准输入的文本 | +| 超时 | any | None | 执行超时秒数;None 使用宿主默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录 | + +这里使用`标识`、`代码`=None、`源码`=None、`输入`=None、`标准输入`=None、`超时`=None。 + +调用效应:process.exec。 在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录。 `输入` 会编码为 JSON 交给内核。 -*> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` stdin=`标准输入` timeout=`超时`* +完成后返回*[在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录](> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` stdin=`标准输入` timeout=`超时`)*。 ## 会话设值 - + `标识` - + `名称` - + `值` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | +| 名称 | any | 必填 | 要解析、注册或查找的名称 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 把一个 Marqdo 值写入内核变量(JSON 拷贝) | + +这里使用`标识`、`名称`、`值`。 + +调用效应:process.exec。 把一个 Marqdo 值写入内核变量(JSON 拷贝)。 -*> host_foreign_session_set id=`标识` name=`名称` value=`值`* +完成后返回*[把一个 Marqdo 值写入内核变量(JSON 拷贝)](> host_foreign_session_set id=`标识` name=`名称` value=`值`)*。 ## 会话取值 - + `标识` - + `名称` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | +| 名称 | any | 必填 | 要解析、注册或查找的名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 把一个内核变量读成 Marqdo 值 | + +这里使用`标识`、`名称`。 + +调用效应:process.exec。 把一个内核变量读成 Marqdo 值。 -*> host_foreign_session_get id=`标识` name=`名称`* +完成后返回*[把一个内核变量读成 Marqdo 值](> host_foreign_session_get id=`标识` name=`名称`)*。 ## 会话中断 - + `标识` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值 | + +这里使用`标识`。 + +调用效应:process.exec。 中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值。 -*> host_foreign_session_interrupt id=`标识`* +完成后返回*[中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值](> host_foreign_session_interrupt id=`标识`)*。 ## 会话变量 - + `标识` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 列出内核变量名 | + +这里使用`标识`。 + +调用效应:process.exec。 列出内核变量名。 -*> host_foreign_session_names id=`标识`* +完成后返回*[列出内核变量名](> host_foreign_session_names id=`标识`)*。 ## 会话关闭 - + `标识` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 标识 | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 终止并移除会话;返回是否存在 | + +这里使用`标识`。 + +调用效应:process.exec。 终止并移除会话;返回是否存在。 -*> host_foreign_session_close id=`标识`* +完成后返回*[终止并移除会话;返回是否存在](> host_foreign_session_close id=`标识`)*。 ## 会话表 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 列出活动会话的 id/lang/cmd/evals/alive/started_ms | + +调用效应:process.exec。 + 列出活动会话的 id/lang/cmd/evals/alive/started_ms。 -*> host_foreign_session_list* +完成后返回*[列出活动会话的 id/lang/cmd/evals/alive/started_ms](host_foreign_session_list())*。 ## 语言表 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 列出已配置的外联语言 | + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/外联.mq.md 语言表 --effects none --json +``` + 列出已配置的外联语言。 -*> host_foreign_langs* +返回当前外联注册表里的语言配置,不会启动解释器;是否安装可执行程序应另用探测接口确认。 + +完成后返回*[列出已配置的外联语言](host_foreign_langs())*。 + +## 观测日志 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测。 | + +调用效应:pure。 + +返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测。 + +完成后返回*[返回本次文档执行中已接纳的 eval/get/decode 观测记录,包含 index、channel、value;开启、赋值和关闭不新增观测](> host_oracle_journal )*。 + +## 重放检查 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 预期 | list | 必填 | 重放比较所用的预期观测记录 | +| 实际 | list | 必填 | 重放比较所用的实际观测记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录。 | + +这里使用`预期`、`实际`。 + +调用效应:pure。 + +不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录。 + +完成后返回*[不执行外部代码地比较两份观测日志;返回是否一致、最早差异位置和对应记录](> host_oracle_replay_check expected=`预期` observed=`实际`)*。 diff --git a/lib/子任务.mq.md b/lib/子任务.mq.md index d794183..69bb190 100644 --- a/lib/子任务.mq.md +++ b/lib/子任务.mq.md @@ -6,45 +6,165 @@ description: 并发子任务 — 文件、函数或外联代码 并发子任务:文件、函数或外联代码。 +以明确所有权管理并发任务。 + +能力与边界:文件批处理继承父权限与根目录。每项 Result.ok 表示等待协议完成,子进程业务成败还须检查 value.code。限时等待默认保留句柄,取消需要明确选择。进程可以终止并回收;函数线程只能逻辑取消。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 + +实现入口:[src/host/subtask.rs](../src/host/subtask.rs)、[src/host/task_ops.rs](../src/host/task_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 启动 - + `路径`=None - + `函数`=None - + `参数`=None - + `代码`=None - + `语言`=None - + `源码`=None - + `输入`=None - + `静默`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权根目录内的文件路径 | +| 函数 | any | None | 调用方提供的函数 | +| 参数 | any | None | 调用方提供的参数 | +| 代码 | any | None | 调用方提供的代码 | +| 语言 | any | None | 调用方提供的语言 | +| 源码 | any | None | 本次检查或试跑的源码文本 | +| 输入 | any | None | 调用方提供的输入 | +| 静默 | any | True | 调用方提供的静默 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 启动子任务 | + +这里使用`路径`=None、`函数`=None、`参数`=None、`代码`=None、`语言`=None、`源码`=None、`输入`=None、`静默`=True。 + +调用效应:process.exec。 启动子任务。文件子任务默认静默(静默=真:管道捕获)。静默=假 时继承父终端。文件等待返回 {code, value},静默捕获时另含截断的 stdout/stderr;value 为子 main 返回值。 调用例:[子任务.启动] 路径="child.mq.md" -*> host_subtask_spawn path=`路径` fn=`函数` args=`参数` code=`代码` lang=`语言` source=`源码` stdin=`输入` quiet=`静默`* +完成后返回*[启动子任务](> host_subtask_spawn path=`路径` fn=`函数` args=`参数` code=`代码` lang=`语言` source=`源码` stdin=`输入` quiet=`静默`)*。 ## 探测 - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 非阻塞查看子任务 id 状态 | + +这里使用`id`。 + +调用效应:process.exec。 非阻塞查看子任务 id 状态。 -*> host_subtask_poll id=`id`* +完成后返回*[非阻塞查看子任务 id 状态](> host_subtask_poll id=`id`)*。 ## 等待 - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 阻塞直到子任务 id 结束 | + +这里使用`id`。 + +调用效应:process.exec。 阻塞直到子任务 id 结束。 -*> host_subtask_join id=`id`* +完成后返回*[阻塞直到子任务 id 结束](> host_subtask_join id=`id`)*。 ## 终止 - + `id` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | 必填 | 对应创建或启动操作返回的标识 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 终止子任务 id | + +这里使用`id`。 + +调用效应:process.exec。 终止子任务 id。 -*> host_subtask_kill id=`id`* +完成后返回*[终止子任务 id](> host_subtask_kill id=`id`)*。 ## 等待全部 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 等待全部已启动子任务结束 | + +调用效应:process.exec。 + 等待全部已启动子任务结束。 -*> host_subtask_wait_all* +完成后返回*[等待全部已启动子任务结束](host_subtask_wait_all())*。 + +## 限时等待 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 编号 | number | 必填 | 对应创建或启动操作返回的标识 | +| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | +| 取消 | bool | False | 超时后是否同时取消尚未结束的任务 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 限时等待并返回结果记录;默认超时保留句柄。cancel=True 会终止并回收进程;函数线程只进行逻辑取消。 | + +这里使用`编号`、`超时毫秒`=30000、`取消`=False。 + +调用效应:process.exec。 + +限时等待并返回结果记录;默认超时保留句柄。cancel=True 会终止并回收进程;函数线程只进行逻辑取消。 + +完成后返回*[限时等待并返回结果记录;默认超时保留句柄](> host_subtask_wait_timeout id=`编号` timeout_ms=`超时毫秒` cancel=`取消`)*。 + +## 全部取消 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消。 | + +调用效应:process.exec。 + +取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消。 + +完成后返回*[取消所有子任务并回收子进程,返回数量;函数线程只能逻辑取消](> host_subtask_cancel_all )*。 + +## 批量执行 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 任务 | list | 必填 | 有序文件任务记录,包含 path 及可选 args | +| 并发上限 | number | 4 | 同时运行的文件任务上限,范围 1 到 64 | +| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录。超时终止回收对应进程;最多一万任务、六十四并发,继承父权限和文件根目录。 | + +这里使用`任务`、`并发上限`=4、`超时毫秒`=30000。 + +调用效应:process.exec。 + +直接调用此函数: + +```sh +marqdo call lib/子任务.mq.md 批量执行 '任务=[{"path":"examples/stdlib-handbook/worker.mq.md"}]' '并发上限=2' --effects process.exec --fs-root . --json +``` + +按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录。超时终止回收对应进程;最多一万任务、六十四并发,继承父权限和文件根目录。 + +完成后返回*[按并发上限执行 path/args 文件任务,结果按输入排序,每项是结果记录](> host_subtask_run_many tasks=`任务` limit=`并发上限` timeout_ms=`超时毫秒`)*。 diff --git a/lib/字节.mq.md b/lib/字节.mq.md new file mode 100644 index 0000000..d17fa23 --- /dev/null +++ b/lib/字节.mq.md @@ -0,0 +1,132 @@ +--- +markup: occlusion +title: 字节 +--- + +字节是 `_type: bytes` 与 `base64` 字段组成的普通记录,可跨 CLI、JSON、插件和会话保存;不新增语言类型。 + +通过普通可移植记录传递任意二进制数据。 + +能力与边界:字节记录包含 _type=bytes 和标准 Base64。字节偏移从零起;UTF-8 解码明确且严格。读块不会留下跨会话文件句柄。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/encoding.rs](../src/host/encoding.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + +## 从文本 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 把文本编码为 UTF-8 字节。 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/字节.mq.md 从文本 '内容="Marqdo"' --effects none --json +``` + +把文本编码为 UTF-8 字节。 + +完成后返回*[把文本编码为 UTF-8 字节](> host_bytes_from_text text=`内容`)*。 + +## 从编码 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 把 Base64 解码为任意字节,不假设 UTF-8。 | + +这里使用`内容`。 + +调用效应:pure。 + +把 Base64 解码为任意字节,不假设 UTF-8。 + +完成后返回*[把 Base64 解码为任意字节,不假设 UTF-8](> host_bytes_from_base64 text=`内容`)*。 + +## 转文本 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 严格解码 UTF-8;无效字节序列失败。 | + +这里使用`数据`。 + +调用效应:pure。 + +严格解码 UTF-8;无效字节序列失败。 + +完成后返回*[严格解码 UTF-8;无效字节序列失败](> host_bytes_to_text data=`数据`)*。 + +## 转编码 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 返回带填充的标准 Base64。 | + +这里使用`数据`。 + +调用效应:pure。 + +返回带填充的标准 Base64。 + +完成后返回*[返回带填充的标准 Base64](> host_bytes_to_base64 data=`数据`)*。 + +## 长度 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 计算字节数,不是字符数。 | + +这里使用`数据`。 + +调用效应:pure。 + +计算字节数,不是字符数。 + +完成后返回*[计算字节数,不是字符数](> host_bytes_len data=`数据`)*。 + +## 切片 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | +| 起 | number | 必填 | 切片起点,从零开始且包含端点 | +| 止 | number | 必填 | 切片终点,从零开始且不包含端点;None 表示到末尾 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 返回从零起、左闭右开的字节切片;端点截到长度。 | + +这里使用`数据`、`起`、`止`。 + +调用效应:pure。 + +返回从零起、左闭右开的字节切片;端点截到长度。 + +完成后返回*[返回从零起、左闭右开的字节切片;端点截到长度](> host_bytes_slice data=`数据` start=`起` end=`止`)*。 diff --git a/lib/归档.mq.md b/lib/归档.mq.md new file mode 100644 index 0000000..276a871 --- /dev/null +++ b/lib/归档.mq.md @@ -0,0 +1,65 @@ +--- +markup: occlusion +--- + +可选 ZIP 任务;原生默认构建支持,精简与浏览器构建不支持。返回统一结果记录。 + +归档是可选原生能力。本文件的打包与解包就是生产接口; +两者需要 fs.write,返回统一结果记录,目标必须不存在。解包先预检路径、 +重复条目、符号链接与总展开字节上限;失败只清理本次新建的目标目录。 +不复制权限、符号链接和空目录;精简或浏览器构建明确返回不支持。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 + +实现入口:[src/host/archive.rs](../src/host/archive.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + +## 打包 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | +| 字节上限 | number | 1073741824 | 读取或展开的字节上限;超限则失败 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 成功结果的 value 是已归档普通文件数;失败时包含结构化错误 | + +这里使用`来源`、`目标`、`字节上限`=1073741824。 + +调用效应:fs.write。 + +示例先准备可丢弃的目录 MQ_WORK,其中 input 子目录放待归档普通文件;目标 bundle.zip 和 output 必须不存在。解包后自行保留产物或清理目录。 + +```sh +marqdo call lib/归档.mq.md 打包 '来源="input"' '目标="bundle.zip"' --fs-root "$MQ_WORK" --effects fs.write --json +marqdo call lib/归档.mq.md 解包 '来源="bundle.zip"' '目标="output"' --fs-root "$MQ_WORK" --effects fs.write --json +``` + +目标必须不存在;限制总展开字节数和十万条目,拒绝符号链接和越界路径。打包只收集普通文件;解包失败清理新建目标目录。 + +完成后返回*[把普通文件打包为 ZIP,拒绝覆盖已有目标](> host_zip_pack src=`来源` dest=`目标` max_bytes=`字节上限`)*。 + +## 解包 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | +| 字节上限 | number | 1073741824 | 读取或展开的字节上限;超限则失败 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 成功结果的 value 是解包条目数;失败时包含结构化错误 | + +这里使用`来源`、`目标`、`字节上限`=1073741824。 + +调用效应:fs.write。 + +目标必须不存在;限制总展开字节数和十万条目,拒绝符号链接和越界路径。打包只收集普通文件;解包失败清理新建目标目录。 + +完成后返回*[校验 ZIP 条目后解包,拒绝越界路径及已有目标](> host_zip_unpack src=`来源` dest=`目标` max_bytes=`字节上限`)*。 diff --git a/lib/插件.mq.md b/lib/插件.mq.md index d68a9d8..50f70da 100644 --- a/lib/插件.mq.md +++ b/lib/插件.mq.md @@ -6,30 +6,82 @@ description: 加载可选原生 ABI 插件(.dll / .so / .dylib) 加载可选原生 ABI 插件(.dll / .so / .dylib)。 +定位并加载原生能力。 + +能力与边界:空列表表示本进程尚未加载插件。插件发现与加载需要 plugin.call;普通使用先读对应领域扩展的入口。原生插件不支持浏览器构建。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/plugin.rs](../src/host/plugin.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 加载 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 从路径加载原生插件 | + +这里使用`路径`。 + +调用效应:plugin.call。 从路径加载原生插件。 调用例:[插件.加载] 路径=`so` -*> host_plugin_load path=`路径`* +完成后返回*[从路径加载原生插件](> host_plugin_load path=`路径`)*。 ## 卸载 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 卸载当前原生插件 | + +调用效应:plugin.call。 + 卸载当前原生插件。 -*> host_plugin_unload* +完成后返回*[卸载当前原生插件](host_plugin_unload())*。 ## 列出 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 列出已加载的原生插件 | + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/插件.mq.md 列出 --effects none --json +``` + 列出已加载的原生插件。 -*> host_plugin_list* +返回当前宿主进程已加载插件的名称列表;本函数不会加载插件,新进程的列表可能为空。 + +完成后返回*[列出已加载的原生插件](host_plugin_list())*。 ## 原生路径 - + `名` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | 必填 | 已安装拓展库标识,例如 agent | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 解析已安装或本地原生插件路径(如 agent) | + +这里使用`名`。 + +调用效应:plugin.call。 解析已安装或本地原生插件路径(如 agent)。 -*> host_ext_native_path name=`名`* +完成后返回*[解析已安装或本地原生插件路径(如 agent)](> host_ext_native_path name=`名`)*。 diff --git a/lib/数学.mq.md b/lib/数学.mq.md index 719caa9..8e590f5 100644 --- a/lib/数学.mq.md +++ b/lib/数学.mq.md @@ -6,283 +6,680 @@ description: 高中数学 — 数值、随机、公式、作图 高中数学 — 数值、随机、公式、作图 +计算数字、符号表达式和绘图。 + +能力与边界:number 契约包括符号公式;三角函数使用弧度。随机数需要 random.read,绘图具有输出效应。矩阵和量子计算保留在扩展库。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/math.rs](../src/host/math.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 圆周率 -圆周率。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回数学常数圆周率 | -*> host_pi* +调用效应:pure。 + +返回数学常数圆周率。 + +完成后返回*[返回数学常数圆周率](host_pi())*。 ## 自然底数 -自然底数。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回自然常数 e | -*> host_e* +调用效应:pure。 + +返回自然常数 e。 + +完成后返回*[返回自然常数 e](host_e())*。 ## 数 - + `value` -数。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_num value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 把数字或数字文本转换为数值 | + +这里使用`value`。 + +调用效应:pure。 + +把数字或数字文本转换为数值。 + +完成后返回*[把数字或数字文本转换为数值](> host_num value=`value`)*。 ## 加 - + `a` - + `b` -加。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_add a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 将两个数字或符号表达式相加 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +将两个数字或符号表达式相加。 + +完成后返回*[将两个数字或符号表达式相加](> host_math_add a=`a` b=`b`)*。 ## 减 - + `a` - + `b` -减。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_sub a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 从 a 减去 b | + +这里使用`a`、`b`。 + +调用效应:pure。 + +从 a 减去 b。 + +完成后返回*[从 a 减去 b](> host_math_sub a=`a` b=`b`)*。 ## 乘 - + `a` - + `b` -乘。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_mul a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算 a 与 b 的乘积 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +计算 a 与 b 的乘积。 + +完成后返回*[计算 a 与 b 的乘积](> host_math_mul a=`a` b=`b`)*。 ## 除 - + `a` - + `b` -除。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_div a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算 a 除以 b;除数为零时报错 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +计算 a 除以 b;除数为零时报错。 + +完成后返回*[计算 a 除以 b;除数为零时报错](> host_math_div a=`a` b=`b`)*。 ## 幂 - + `a` - + `b` -幂。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_pow a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算 a 的 b 次幂 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +计算 a 的 b 次幂。 + +完成后返回*[计算 a 的 b 次幂](> host_math_pow a=`a` b=`b`)*。 ## 负 - + `value` -负。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_neg value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 对数字或符号值取负 | + +这里使用`value`。 + +调用效应:pure。 + +对数字或符号值取负。 + +完成后返回*[对数字或符号值取负](> host_math_neg value=`value`)*。 ## 正弦 - + `value` -正弦。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_sin value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算正弦;数值角度使用弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算正弦;数值角度使用弧度。 + +完成后返回*[计算正弦;数值角度使用弧度](> host_math_sin value=`value`)*。 ## 余弦 - + `value` -余弦。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_cos value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算余弦;数值角度使用弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算余弦;数值角度使用弧度。 + +完成后返回*[计算余弦;数值角度使用弧度](> host_math_cos value=`value`)*。 ## 正切 - + `value` -正切。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_tan value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算正切;数值角度使用弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算正切;数值角度使用弧度。 + +完成后返回*[计算正切;数值角度使用弧度](> host_math_tan value=`value`)*。 ## 反正弦 - + `value` -反正弦。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_asin value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算反正弦,结果为弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算反正弦,结果为弧度。 + +完成后返回*[计算反正弦,结果为弧度](> host_math_asin value=`value`)*。 ## 反余弦 - + `value` -反余弦。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_acos value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算反余弦,结果为弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算反余弦,结果为弧度。 + +完成后返回*[计算反余弦,结果为弧度](> host_math_acos value=`value`)*。 ## 反正切 - + `value` -反正切。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_atan value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算反正切,结果为弧度 | + +这里使用`value`。 + +调用效应:pure。 + +计算反正切,结果为弧度。 + +完成后返回*[计算反正切,结果为弧度](> host_math_atan value=`value`)*。 ## 平方根 - + `value` -平方根。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_sqrt value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算 value 的平方根 | + +这里使用`value`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/数学.mq.md 平方根 value=9 --effects none --json +``` + +计算 value 的平方根。 + +完成后返回*[计算 value 的平方根](> host_math_sqrt value=`value`)*。 ## 绝对值 - + `value` -绝对值。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_abs value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回绝对值 | + +这里使用`value`。 + +调用效应:pure。 + +返回绝对值。 + +完成后返回*[返回绝对值](> host_math_abs value=`value`)*。 ## 对数 - + `value` -对数。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_ln value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算自然对数 | + +这里使用`value`。 + +调用效应:pure。 + +计算自然对数。 + +完成后返回*[计算自然对数](> host_math_ln value=`value`)*。 ## 指数 - + `value` -指数。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_exp value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 计算自然指数函数 | + +这里使用`value`。 + +调用效应:pure。 + +计算自然指数函数。 + +完成后返回*[计算自然指数函数](> host_math_exp value=`value`)*。 ## 向下取整 - + `value` -向下取整。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_floor value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 向负无穷取整 | + +这里使用`value`。 + +调用效应:pure。 + +向负无穷取整。 + +完成后返回*[向负无穷取整](> host_math_floor value=`value`)*。 ## 向上取整 - + `value` -向上取整。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_math_ceil value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 向正无穷取整 | + +这里使用`value`。 + +调用效应:pure。 + +向正无穷取整。 + +完成后返回*[向正无穷取整](> host_math_ceil value=`value`)*。 ## 最小 - + `a` - + `b` -最小。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_min a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回较小的操作数 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +返回较小的操作数。 + +完成后返回*[返回较小的操作数](> host_math_min a=`a` b=`b`)*。 ## 最大 - + `a` - + `b` -最大。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | 必填 | 第二个操作数;适用范围见本操作说明 | -*> host_math_max a=`a` b=`b`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回较大的操作数 | + +这里使用`a`、`b`。 + +调用效应:pure。 + +返回较大的操作数。 + +完成后返回*[返回较大的操作数](> host_math_max a=`a` b=`b`)*。 ## 随机 -随机。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回伪随机数;可用种子控制复现 | -*> host_random* +调用效应:random.read。 + +返回伪随机数;可用种子控制复现。 + +完成后返回*[返回伪随机数;可用种子控制复现](host_random())*。 ## 随机整数 - + `min` - + `max` -随机整数。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| min | any | 必填 | 下界,或搜索与绘图区间的起点 | +| max | any | 必填 | 上界,或搜索与绘图区间的终点 | -*> host_random_int min=`min` max=`max`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 在约定区间内返回伪随机整数 | + +这里使用`min`、`max`。 + +调用效应:random.read。 + +在约定区间内返回伪随机整数。 + +完成后返回*[在约定区间内返回伪随机整数](> host_random_int min=`min` max=`max`)*。 ## 设种子 - + `value` -设种子。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_seed value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 设置本次运行的伪随机种子;不用于机密值 | + +这里使用`value`。 + +调用效应:pure。 + +设置本次运行的伪随机种子;不用于机密值。 + +完成后返回*[设置本次运行的伪随机种子;不用于机密值](> host_seed value=`value`)*。 ## 公式 - + `text` -公式。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| text | text | 必填 | 调用方提供的文本 | -*> host_formula value=`text`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断 | + +这里使用`text`。 + +调用效应:pure。 + +把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断。 + +完成后返回*[把表达式文本解析为符号公式,供后续代数运算或求值使用;语法无效时返回诊断](> host_formula value=`text`)*。 ## 化简 - + `formula` -化简。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -*> host_simplify value=`formula`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 返回化简后的公式并保留输入;这是符号代数运算,不是数值求值 | + +这里使用`formula`。 + +调用效应:pure。 + +返回化简后的公式并保留输入;这是符号代数运算,不是数值求值。 + +完成后返回*[返回化简后的公式并保留输入;这是符号代数运算,不是数值求值](> host_simplify value=`formula`)*。 ## 展开 - + `formula` -展开。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | -*> host_expand value=`formula`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 展开代数乘积与幂,返回新的符号公式 | + +这里使用`formula`。 + +调用效应:pure。 + +展开代数乘积与幂,返回新的符号公式。 + +完成后返回*[展开代数乘积与幂,返回新的符号公式](> host_expand value=`formula`)*。 ## 求导 - + `formula` - + `var` -求导。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | +| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | -*> host_diff formula=`formula` var=`var`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 对指定符号求导并返回符号导函数 | + +这里使用`formula`、`var`。 + +调用效应:pure。 + +对指定符号求导并返回符号导函数。 + +完成后返回*[对指定符号求导并返回符号导函数](> host_diff formula=`formula` var=`var`)*。 ## 代入 - + `formula` - + `var` - + `value` -代入。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | +| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_subs formula=`formula` var=`var` value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 用指定值替换公式中的符号;完全化简时返回数字,否则保留公式 | + +这里使用`formula`、`var`、`value`。 + +调用效应:pure。 + +用指定值替换公式中的符号;完全化简时返回数字,否则保留公式。 + +完成后返回*[用指定值替换公式中的符号;完全化简时返回数字,否则保留公式](> host_subs formula=`formula` var=`var` value=`value`)*。 ## 求值 - + `formula` - + `var` - + `value` -求值。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | +| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | -*> host_eval formula=`formula` var=`var` value=`value`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断 | + +这里使用`formula`、`var`、`value`。 + +调用效应:pure。 + +在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断。 + +完成后返回*[在一个变量取指定数值时计算公式;仍有未绑定符号时返回诊断](> host_eval formula=`formula` var=`var` value=`value`)*。 ## 求解 - + `formula` - + `var` - + `min`=None - + `max`=None -求解。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | +| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | +| min | any | None | 下界,或搜索与绘图区间的起点 | +| max | any | None | 上界,或搜索与绘图区间的终点 | -*> host_solve formula=`formula` var=`var` min=`min` max=`max`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100 | + +这里使用`formula`、`var`、`min`=None、`max`=None。 + +调用效应:pure。 + +返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100。 + +完成后返回*[返回指定符号在上下界内的根列表;省略边界时使用 -100 到 100](> host_solve formula=`formula` var=`var` min=`min` max=`max`)*。 ## 绘图 - + `formula` - + `var` - + `min` - + `max` - + `steps`=None - + `path`=None - + `derivative`=None - + `grid`=None -绘图。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| formula | any | 必填 | 公式函数或前序符号运算返回的符号公式 | +| var | any | 必填 | 求导、代入、求值或求根所针对的符号名 | +| min | any | 必填 | 下界,或搜索与绘图区间的起点 | +| max | any | 必填 | 上界,或搜索与绘图区间的终点 | +| steps | any | None | 绘图区间内的采样数量 | +| path | any | None | 相对已授权文件根目录的路径 | +| derivative | any | None | 是否在图中包含导函数 | +| grid | any | None | 是否绘制坐标网格 | -*> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG | + +这里使用`formula`、`var`、`min`、`max`、`steps`=None、`path`=None、`derivative`=None、`grid`=None。 + +调用效应:output.write。 + +在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG。 + +完成后返回*[在区间内采样公式并返回 SVG 文本;指定路径时还会在授权根目录内写出 SVG](> host_plot formula=`formula` var=`var` min=`min` max=`max` steps=`steps` path=`path` derivative=`derivative` grid=`grid`)*。 ## 绘点列 - + `xs` - + `ys` - + `path`=None - + `grid`=None -绘点列。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | +| ys | any | 必填 | 与 xs 一一对应的 Y 坐标列表 | +| path | any | None | 相对已授权文件根目录的路径 | +| grid | any | None | 是否绘制坐标网格 | -*> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制 | + +这里使用`xs`、`ys`、`path`=None、`grid`=None。 + +调用效应:output.write。 + +将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制。 + +完成后返回*[将一一对应的横纵坐标列表绘成 SVG 文本;两列长度不等时拒绝绘制](> host_plot_points xs=`xs` ys=`ys` path=`path` grid=`grid`)*。 ## 绘圆锥 - + `kind` - + `a` - + `b`=None - + `h`=None - + `k`=None - + `path`=None - + `grid`=None -绘圆锥。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| kind | any | 必填 | 圆锥曲线绘制函数接受的曲线类型 | +| a | any | 必填 | 第一个操作数;适用范围见本操作说明 | +| b | any | None | 第二个操作数;适用范围见本操作说明 | +| h | any | None | 圆锥曲线中心的水平偏移 | +| k | any | None | 圆锥曲线中心的垂直偏移 | +| path | any | None | 相对已授权文件根目录的路径 | +| grid | any | None | 是否绘制坐标网格 | -*> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本 | + +这里使用`kind`、`a`、`b`=None、`h`=None、`k`=None、`path`=None、`grid`=None。 + +调用效应:output.write。 + +按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本。 + +完成后返回*[按曲线类型、尺寸和中心偏移绘制圆锥曲线,返回 SVG 文本](> host_plot_conic kind=`kind` a=`a` b=`b` h=`h` k=`k` path=`path` grid=`grid`)*。 diff --git a/lib/文件.mq.md b/lib/文件.mq.md index d295653..7f4758b 100644 --- a/lib/文件.mq.md +++ b/lib/文件.mq.md @@ -1,127 +1,771 @@ --- markup: occlusion +import: + json: lib/json.mq.md + csv: lib/csv.mq.md title: lib/文件 description: 中文文件系统包装 --- 中文文件系统包装 +在明确文件根目录内读写、筛选和整理文件。 + +能力与边界:旧删除会递归删除目录;窄操作请用只删文件或只删空目录。原子操作只替换一个文件,批量目录操作不是事务。字节和文本支持 CoW;目录状态操作的限制见能力矩阵。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 + +实现入口:[src/host/fs.rs](../src/host/fs.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs)、[src/host/sandbox_fs.rs](../src/host/sandbox_fs.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 读文本 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 从路径读取 UTF-8 文本 | + +这里使用`路径`。 + +调用效应:fs.read。 从路径读取 UTF-8 文本。 -*> host_read_text path=`路径`* +完成后返回*[从路径读取 UTF-8 文本](> host_read_text path=`路径`)*。 ## 写文本 - + `路径` - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`内容`。 + +调用效应:fs.write。 把文本写入路径(覆盖)。 -*> host_write_text path=`路径` text=`内容`* +完成后返回*[把文本写入路径(覆盖)](> host_write_text path=`路径` text=`内容`)*。 ## 追加文本 - + `路径` - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`内容`。 + +调用效应:fs.write。 向路径追加文本。 -*> host_append_text path=`路径` text=`内容`* +完成后返回*[向路径追加文本](> host_append_text path=`路径` text=`内容`)*。 ## 存在 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 路径是否存在 | + +这里使用`路径`。 + +调用效应:fs.read。 路径是否存在。 -*> host_exists path=`路径`* +完成后返回*[路径是否存在](> host_exists path=`路径`)*。 ## 列目录 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 列出路径下的目录项 | + +这里使用`路径`。 + +调用效应:fs.read。 列出路径下的目录项。 -*> host_list_dir path=`路径`* +完成后返回*[列出路径下的目录项](> host_list_dir path=`路径`)*。 ## 建目录 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 创建目录。 -*> host_make_dir path=`路径`* +完成后返回*[创建目录](> host_make_dir path=`路径`)*。 ## 建目录树 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 递归创建目录(等同 `mkdir -p`)。 -*> host_make_dirs path=`路径`* +完成后返回*[递归创建目录(等同 mkdir -p)](> host_make_dirs path=`路径`)*。 ## 删除 - + `路径` -删除路径上的文件或空目录。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | -*> host_remove path=`路径`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 + +删除指定文件或递归删除目录;旧行为保持兼容,不能用于只允许删除空目录的场景。 + +删除指定文件或递归删除目录。仅删文件请用只删文件,仅删空目录请用只删空目录。 + +完成后返回*[删除指定文件或递归删除目录](> host_remove path=`路径`)*。 ## 删目录树 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 递归删除目录;若路径是文件则报错。 -*> host_remove_tree path=`路径`* +完成后返回*[递归删除目录;若路径是文件则报错](> host_remove_tree path=`路径`)*。 ## 状态 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 返回 `{size, mtime_unix, is_file, is_dir}` | + +这里使用`路径`。 + +调用效应:fs.read。 返回 `{size, mtime_unix, is_file, is_dir}`。 -*> host_stat path=`路径`* +完成后返回*[返回 {size, mtime_unix, is_file, is_dir}](> host_stat path=`路径`)*。 ## 遍历 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 深度优先列出相对路径(正斜杠) | + +这里使用`路径`。 + +调用效应:fs.read。 深度优先列出相对路径(正斜杠)。 -*> host_walk path=`路径`* +完成后返回*[深度优先列出相对路径(正斜杠)](> host_walk path=`路径`)*。 ## 复制文件 - + `源` - + `目标` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 源 | any | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | any | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`源`、`目标`。 + +调用效应:fs.write。 复制文件(目标已存在则覆盖)。路径沙箱同其他文件操作。 -*> host_copy_file src=`源` dest=`目标`* +完成后返回*[复制文件(目标已存在则覆盖)](> host_copy_file src=`源` dest=`目标`)*。 ## 移动 - + `源` - + `目标` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 源 | any | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | any | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`源`、`目标`。 + +调用效应:fs.write。 在沙箱内重命名 / 移动。 -*> host_move src=`源` dest=`目标`* +完成后返回*[在沙箱内重命名 / 移动](> host_move src=`源` dest=`目标`)*。 ## 建临时 - + `前缀`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 前缀 | any | None | 生成名称的前缀,或需要匹配的文本前缀 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 在程序目录下创建空临时文件,返回相对路径 | + +这里使用`前缀`=None。 + +调用效应:fs.write。 在程序目录下创建空临时文件,返回相对路径。 -*> host_make_temp prefix=`前缀`* +完成后返回*[在程序目录下创建空临时文件,返回相对路径](> host_make_temp prefix=`前缀`)*。 ## 文本补丁 - + `路径` - + `查找` - + `替换` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | +| 查找 | any | 必填 | 替换前需要精确查找的文本 | +| 替换 | any | 必填 | 每个精确匹配项的替换文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 对 UTF-8 文本文件做精确 FIND→REPLACE(`查找` 必须唯一匹配一次) | + +这里使用`路径`、`查找`、`替换`。 + +调用效应:fs.write。 对 UTF-8 文本文件做精确 FIND→REPLACE(`查找` 必须唯一匹配一次)。 -*> host_text_patch path=`路径` find=`查找` replace=`替换`* +完成后返回*[对 UTF-8 文本文件做精确 FIND→REPLACE(查找 必须唯一匹配一次)](> host_text_patch path=`路径` find=`查找` replace=`替换`)*。 ## 应用补丁块 - + `路径` - + `文本` - + `软失败`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | +| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | +| 软失败 | any | False | 补丁未匹配时是否软失败 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 解析规划回复中的 FIND/REPLACE 块并应用到 `路径` | + +这里使用`路径`、`文本`、`软失败`=False。 + +调用效应:fs.write。 解析规划回复中的 FIND/REPLACE 块并应用到 `路径`。`软失败=真` 时仅「找不到 FIND」返回 0;空 FIND、多匹配、整文件重写仍报错。 -*> host_apply_patch_blocks path=`路径` text=`文本` soft=`软失败`* +完成后返回*[解析规划回复中的 FIND/REPLACE 块并应用到 路径](> host_apply_patch_blocks path=`路径` text=`文本` soft=`软失败`)*。 + +## 尝试读文本 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 以 {ok,value,error} 返回文本或错误;仍需 fs | + +这里使用`路径`。 + +调用效应:fs.read。 + +直接调用此函数: + +```sh +marqdo call lib/文件.mq.md 尝试读文本 '路径="lib/fs.mq.md"' --effects fs.read --fs-root . --json +``` + +以 {ok,value,error} 返回至多 8 MiB 的 UTF-8 文本或错误;仍需 fs.read 授权。 + +完成后返回*[以 {ok,value,error} 返回至多 8 MiB 的 UTF-8 文本或错误;仍需 fs.read 授权](> host_fs_try_read_text path=`路径`)*。 + +## 尝试写文本 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs | + +这里使用`路径`、`内容`。 + +调用效应:fs.write。 + +覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs.write。 + +完成后返回*[覆盖写入 UTF-8 文本,返回 {ok,value,error};需要 fs.write](> host_fs_try_write_text path=`路径` text=`内容`)*。 + +## 读字节 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库。 | + +这里使用`路径`、`字节上限`=8388608。 + +调用效应:fs.read。 + +读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库。 + +完成后返回*[读取 bytes 记录;默认上限 8 MiB,最大 64 MiB;解码须明确使用字节库](> host_fs_read_bytes path=`路径` max_bytes=`字节上限`)*。 + +## 写字节 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`数据`。 + +调用效应:fs.write。 + +用字节原子替换文件,不进行 UTF-8 转换;需要 fs.write。 + +完成后返回*[用字节原子替换文件,不进行 UTF-8 转换;需要 fs.write](> host_fs_write_bytes path=`路径` data=`数据`)*。 + +## 读块 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 偏移 | number | 0 | 下一块的字节偏移,从零开始 | +| 大小 | number | 65536 | 本次块读取的字节数 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄。 | + +这里使用`路径`、`偏移`=0、`大小`=65536。 + +调用效应:fs.read。 + +从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄。 + +完成后返回*[从零起字节偏移 offset 读取至多 size 字节,返回 data/next_offset/eof;每次调用关闭文件,不跨会话持有句柄](> host_fs_read_chunk path=`路径` offset=`偏移` size=`大小`)*。 + +## 追加字节 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 数据 | map | 必填 | 含 _type=bytes 与 base64 的可移植字节记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`数据`。 + +调用效应:fs.write。 + +追加字节,不存在则创建文件;父目录必须存在。 + +完成后返回*[追加字节,不存在则创建文件;父目录必须存在](> host_fs_append_bytes path=`路径` data=`数据`)*。 + +## 原子写文本 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`内容`。 + +调用效应:fs.write。 + +经同目录独占临时文件和重命名替换文本;失败清理临时文件。这是单文件替换,不是多文件事务。 + +完成后返回*[经同目录独占临时文件和重命名替换文本;失败清理临时文件](> host_fs_atomic_write path=`路径` text=`内容`)*。 + +## 变化才写 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | 仅内容变化时原子写入;返回是否发生写入。 | + +这里使用`路径`、`内容`。 + +调用效应:fs.write。 + +仅内容变化时原子写入;返回是否发生写入。 + +完成后返回*[仅内容变化时原子写入;返回是否发生写入](> host_fs_write_changed path=`路径` text=`内容`)*。 + +## 校验后写 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | +| 预期摘要 | text | 必填 | 前次精确文本的摘要;操作允许时 None 表示不检查 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调。 | + +这里使用`路径`、`内容`、`预期摘要`。 + +调用效应:fs.write。 + +核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调。 + +完成后返回*[核对当前 SHA-256 后原子替换,返回结果记录;可发现过期内容,并发写者仍需外部协调](> host_fs_write_checked path=`路径` text=`内容` expected_sha256=`预期摘要`)*。 + +## 读行 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行。 | + +这里使用`路径`、`字节上限`=8388608。 + +调用效应:fs.read。 + +有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行。 + +完成后返回*[有界读取 UTF-8 行,去除行尾;接受 CRLF,末尾换行不产生额外行](> host_fs_read_lines path=`路径` max_bytes=`字节上限`)*。 + +## 写行 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 行表 | list | 必填 | 待写入的文本行列表 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`行表`。 + +调用效应:fs.write。 + +按 LF 原子写入文本行;非空输入追加一个末尾换行。 + +完成后返回*[按 LF 原子写入文本行;非空输入追加一个末尾换行](> host_fs_write_lines path=`路径` lines=`行表`)*。 + +## 只删文件 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 + +删除文件,拒绝目录;不存在则失败。旧删除接口保持递归兼容行为。 + +完成后返回*[删除文件,拒绝目录;不存在则失败](> host_fs_remove_file path=`路径`)*。 + +## 只删空目录 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`。 + +调用效应:fs.write。 + +只删除空目录;非空目录失败。仅原生文件系统支持。 + +完成后返回*[只删除空目录;非空目录失败](> host_fs_remove_empty_dir path=`路径`)*。 + +## 临时目录 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 前缀 | text | "mqtmp" | 生成名称的前缀,或需要匹配的文本前缀 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录。 | + +这里使用`前缀`="mqtmp"。 + +调用效应:fs.write。 + +在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录。 + +完成后返回*[在文件根目录内创建临时目录,返回相对名称;调用方负责删目录树清理,不使用系统全局临时目录](> host_fs_temp_dir prefix=`前缀`)*。 + +## 文件摘要 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存。 | + +这里使用`路径`。 + +调用效应:fs.read。 + +以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存。 + +完成后返回*[以 64 KiB 缓冲区计算 SHA-256;支持二进制大文件,不整文件载入内存](> host_fs_file_hash path=`路径`)*。 + +## 查找文件 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 模式 | text | "**" | 相对路径 glob,支持 *、** 与 ? | +| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | +| 深度上限 | number | 64 | 最大遍历深度 | +| 类型 | text | "file" | 条目类型过滤:file、dir 或 any | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项。读取原生文件系统快照。 | + +这里使用`路径`、`模式`="**"、`排除`=None、`深度上限`=64、`类型`="file"。 + +调用效应:fs.read。 + +按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项。读取原生文件系统快照。 + +完成后返回*[按 单星号、双星号与问号 模式查找有序相对路径;exclude 可剪除目录,kind 为 file/dir/all;不跟随符号链接,最多十万项](> host_fs_find path=`路径` pattern=`模式` exclude=`排除` max_depth=`深度上限` kind=`类型`)*。 + +## 复制目录树 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | +| 覆盖 | bool | False | 是否允许替换已存在的目标文件 | +| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | +| 预演 | bool | False | 是否仅返回计划而不修改文件 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 在不相交目录树间复制文件;先检查冲突,覆盖须明确开启。返回相对文件列表;dry_run 仅计划。不复制权限、链接和空目录。 | + +这里使用`来源`、`目标`、`覆盖`=False、`排除`=None、`预演`=False。 + +调用效应:fs.write。 + +在不相交目录树间复制文件;先检查冲突,覆盖须明确开启。返回相对文件列表;dry_run 仅计划。不复制权限、链接和空目录。 + +完成后返回*[在不相交目录树间复制文件;先检查冲突,覆盖须明确开启](> host_fs_copy_tree src=`来源` dest=`目标` overwrite=`覆盖` exclude=`排除` dry_run=`预演`)*。 + +## 同步目录树 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 来源 | text | 必填 | 来源路径;归档打包时必须是目录 | +| 目标 | text | 必填 | 目标路径;仅在操作明确允许时才能覆盖 | +| 覆盖 | bool | False | 是否允许替换已存在的目标文件 | +| 排除 | any | None | 遍历时剪枝的 glob 模式列表;None 表示不排除 | +| 预演 | bool | False | 是否仅返回计划而不修改文件 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务。 | + +这里使用`来源`、`目标`、`覆盖`=False、`排除`=None、`预演`=False。 + +调用效应:fs.write。 + +按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务。 + +完成后返回*[按复制目录树的冲突规则复制新增或变化文件;不删除目标独有文件,执行不是事务](> host_fs_sync_tree src=`来源` dest=`目标` overwrite=`覆盖` exclude=`排除` dry_run=`预演`)*。 + +## 批量改名 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 改名表 | list | 必填 | 来源与目标路径组成的改名记录列表 | +| 预演 | bool | False | 是否仅返回计划而不修改文件 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名。不支持环路或回滚;dry_run 返回计划数量。 | + +这里使用`改名表`、`预演`=False。 + +调用效应:fs.write。 + +预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名。不支持环路或回滚;dry_run 返回计划数量。 + +完成后返回*[预检 src/dest 文件记录,拒绝已有或重复目标,然后按输入顺序改名](> host_fs_rename_many moves=`改名表` dry_run=`预演`)*。 + +## 读JSON + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 相对文件根目录的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 解析后的数据 | + +这里使用`路径`。 + +调用效应:fs.read。 + +读取 UTF-8 文本后使用同一标准解析器;错误会终止,批处理请先尝试读文本。 + +得到**`body` = [读取指定文件的 UTF-8 正文](读文本(路径=`路径`))**。 +完成后返回*[解析 JSON 传输文本](json.parse(text=`body`))*。 + +## 写JSON + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 相对文件根目录的路径 | +| 数据 | any | 必填 | 待序列化的数据 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`数据`。 + +调用效应:fs.write。 + +序列化后以原子写入替换文件;不保留旧格式与注释。 + +得到**`body` = [将结构化值编码为 JSON 文本](json.stringify(value=`数据`))**。 +完成后返回*[将准备好的文本写入指定文件](原子写文本(路径=`路径`, 内容=`body`))*。 + +## 读CSV + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 相对文件根目录的路径 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 解析后的数据 | + +这里使用`路径`。 + +调用效应:fs.read。 + +读取 UTF-8 文本后使用同一标准解析器;错误会终止,批处理请先尝试读文本。 + +得到**`body` = [读取指定文件的 UTF-8 正文](读文本(路径=`路径`))**。 +完成后返回*[调用 parse](csv.parse(text=`body`))*。 + +## 写CSV + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 相对文件根目录的路径 | +| 数据 | list | 必填 | 待序列化的数据 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 完成后返回 None;文件操作失败时返回诊断 | + +这里使用`路径`、`数据`。 + +调用效应:fs.write。 + +序列化后以原子写入替换文件;不保留旧格式与注释。 + +得到**`body` = [调用 stringify](csv.stringify(rows=`数据`))**。 +完成后返回*[将准备好的文本写入指定文件](原子写文本(路径=`路径`, 内容=`body`))*。 diff --git a/lib/文本.mq.md b/lib/文本.mq.md index 07ea9b3..d6a0cf3 100644 --- a/lib/文本.mq.md +++ b/lib/文本.mq.md @@ -6,93 +6,230 @@ description: 文本库加厚(中层 M4)。字面替换 — 正则请用 lib/ 常用文本助手。手写拆分不如走这里;正则请用 lib/正则。 +清理与组合 Unicode 文本。 + +能力与边界:字面替换使用本库,模式匹配使用正则库,任意二进制使用字节库。拆分和拼接使用明确分隔符,不隐式解析文档。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/text_ops.rs](../src/host/text_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 去空白 - + `s` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| s | text | 必填 | 输入文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 去掉字符串 s 两端空白 | + +这里使用`s`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/文本.mq.md 去空白 's=" readable text "' --effects none --json +``` 去掉字符串 s 两端空白。 -*> trim `s`* +完成后返回*[调用 trim](trim(`s`))*。 ## 拆分 - + `s` - + `sep` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| s | text | 必填 | 输入文本 | +| sep | text | 必填 | 拆分或连接文本所用的分隔符 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 按分隔符 sep 拆分字符串 s | + +这里使用`s`、`sep`。 + +调用效应:pure。 按分隔符 sep 拆分字符串 s。 -*> split value=`s` sep=`sep`* +完成后返回*[调用 split](split(value=`s`, sep=`sep`))*。 ## 拼接 - + `xs` - + `sep` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | +| sep | text | 必填 | 拆分或连接文本所用的分隔符 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 用分隔符 sep 拼接列表 xs | + +这里使用`xs`、`sep`。 + +调用效应:pure。 用分隔符 sep 拼接列表 xs。 -*> join value=`xs` sep=`sep`* +完成后返回*[调用 join](join(value=`xs`, sep=`sep`))*。 ## 包含 - + `内容` - + `子串` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 子串 | any | 必填 | 需要查找的子串 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 内容是否包含子串 | + +这里使用`内容`、`子串`。 + +调用效应:pure。 内容是否包含子串。 调用例:[文本.包含] 内容="你好" 子串="好" -*> host_text_contains text=`内容` sub=`子串`* +完成后返回*[内容是否包含子串](> host_text_contains text=`内容` sub=`子串`)*。 ## 开头是 - + `内容` - + `前缀` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 前缀 | any | 必填 | 生成名称的前缀,或需要匹配的文本前缀 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 内容是否以前缀开头 | + +这里使用`内容`、`前缀`。 + +调用效应:pure。 内容是否以前缀开头。 -*> host_text_starts_with text=`内容` prefix=`前缀`* +完成后返回*[内容是否以前缀开头](> host_text_starts_with text=`内容` prefix=`前缀`)*。 ## 结尾是 - + `内容` - + `后缀` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 后缀 | any | 必填 | 需要匹配的文本后缀 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 内容是否以后缀结尾 | + +这里使用`内容`、`后缀`。 + +调用效应:pure。 内容是否以后缀结尾。 -*> host_text_ends_with text=`内容` suffix=`后缀`* +完成后返回*[内容是否以后缀结尾](> host_text_ends_with text=`内容` suffix=`后缀`)*。 ## 替换 - + `内容` - + `旧` - + `新` - + `次数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 旧 | any | 必填 | 需要替换的精确子串 | +| 新 | any | 必填 | 替换后使用的文本 | +| 次数 | any | None | 最大替换次数;None 使用操作说明中的默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 在内容里把字面旧换成新,可选次数 | + +这里使用`内容`、`旧`、`新`、`次数`=None。 + +调用效应:pure。 在内容里把字面旧换成新,可选次数。 -*> host_text_replace text=`内容` old=`旧` new=`新` count=`次数`* +完成后返回*[在内容里把字面旧换成新,可选次数](> host_text_replace text=`内容` old=`旧` new=`新` count=`次数`)*。 ## 大写 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 内容转大写 | + +这里使用`内容`。 + +调用效应:pure。 内容转大写。 -*> host_text_to_upper text=`内容`* +完成后返回*[内容转大写](> host_text_to_upper text=`内容`)*。 ## 小写 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 内容转小写 | + +这里使用`内容`。 + +调用效应:pure。 内容转小写。 -*> host_text_to_lower text=`内容`* +完成后返回*[内容转小写](> host_text_to_lower text=`内容`)*。 ## 重复 - + `内容` - + `次数` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 次数 | any | 必填 | 重复次数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 把内容重复次数遍 | + +这里使用`内容`、`次数`。 + +调用效应:pure。 把内容重复次数遍。 -*> host_text_repeat text=`内容` n=`次数`* +完成后返回*[把内容重复次数遍](> host_text_repeat text=`内容` n=`次数`)*。 ## 填充 - + `内容` - + `宽度` - + `填充符`=None - + `对齐`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 宽度 | any | 必填 | 填充后的目标字符宽度 | +| 填充符 | any | None | 单个填充字符 | +| 对齐 | any | None | 填充对齐方式:left、right 或 center | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 把内容填充到宽度,可选填充符与对齐(left / right / center) | + +这里使用`内容`、`宽度`、`填充符`=None、`对齐`=None。 + +调用效应:pure。 把内容填充到宽度,可选填充符与对齐(left / right / center)。 -*> host_text_pad text=`内容` width=`宽度` fill=`填充符` align=`对齐`* +完成后返回*[把内容填充到宽度,可选填充符与对齐(left / right / center)](> host_text_pad text=`内容` width=`宽度` fill=`填充符` align=`对齐`)*。 diff --git a/lib/文档.mq.md b/lib/文档.mq.md new file mode 100644 index 0000000..b963d81 --- /dev/null +++ b/lib/文档.mq.md @@ -0,0 +1,155 @@ +--- +markup: occlusion +--- + +通过渲染器共用的 Markdown 解析器读取文档结构。全部接口均为纯函数。 + +不执行内容地读取与变换 Markdown 结构。 + +能力与边界:复用 Markdown 解析器并识别 YAML 前置信息;区间是原始 UTF-8 字节偏移。不执行文档。重复章节名失败;替换保留周围源码,持久化使用校验后写。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/document.rs](../src/host/document.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + +## 章节列表 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题。不执行文档。 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/文档.mq.md 章节列表 '内容="# Notes"' --effects none --json +``` + +列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题。不执行文档。 + +完成后返回*[列出标题、原始 UTF-8 字节区间和正文;章节结束于下一个同级或更高级标题](> host_document_sections text=`内容`)*。 + +## 读取章节 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | +| 标题 | text | 必填 | 精确且唯一的 Markdown 标题文字 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 按完整标题读取正文;缺失或重复标题失败。 | + +这里使用`内容`、`标题`。 + +调用效应:pure。 + +按完整标题读取正文;缺失或重复标题失败。 + +完成后返回*[按完整标题读取正文;缺失或重复标题失败](> host_document_section text=`内容` title=`标题`)*。 + +## 替换章节 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | +| 标题 | text | 必填 | 精确且唯一的 Markdown 标题文字 | +| 正文 | text | 必填 | 请求正文;文档操作中为替换正文 | +| 预期摘要 | any | None | 前次精确文本的摘要;操作允许时 None 表示不检查 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要。这是纯转换,持久化使用文件库校验后写。 | + +这里使用`内容`、`标题`、`正文`、`预期摘要`=None。 + +调用效应:pure。 + +返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要。这是纯转换,持久化使用文件库校验后写。 + +完成后返回*[返回替换章节正文的结果记录,保留标题和周围源码;可校验整份来源摘要](> host_document_replace_section text=`内容` title=`标题` body=`正文` expected_sha256=`预期摘要`)*。 + +## 表格列表 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格。 | + +这里使用`内容`。 + +调用效应:pure。 + +提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格。 + +完成后返回*[提取惰性的 GFM 表头、单元格文本和原始字节区间;不求值单元格](> host_document_tables text=`内容`)*。 + +## 替换表格 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | +| 序号 | number | 必填 | 按源码顺序排列的表格下标,从零开始 | +| 表头 | list | 必填 | 按列顺序排列的表头文本列表 | +| 行 | list | 必填 | 单元格文本列表组成的行列表;每行宽度必须与表头一致 | +| 预期摘要 | any | None | 前次精确文本的摘要;操作允许时 None 表示不检查 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录。 | + +这里使用`内容`、`序号`、`表头`、`行`、`预期摘要`=None。 + +调用效应:pure。 + +按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录。 + +完成后返回*[按从零起的表序号,用文本表头和行替换表格,保留周围源码;返回结果记录](> host_document_replace_table text=`内容` index=`序号` headers=`表头` rows=`行` expected_sha256=`预期摘要`)*。 + +## 链接列表 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 列出 Markdown 链接描述、目标和字节区间;不访问或执行链接。 | + +这里使用`内容`。 + +调用效应:pure。 + +列出 Markdown 链接描述、目标和字节区间;不访问或执行链接。 + +完成后返回*[列出 Markdown 链接描述、目标和字节区间;不访问或执行链接](> host_document_links text=`内容`)*。 + +## 代码块列表 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码。 | + +这里使用`内容`。 + +调用效应:pure。 + +列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码。 + +完成后返回*[列出代码块语言、字面源码和字节区间;不运行其中的外联或 Marqdo 代码](> host_document_code_blocks text=`内容`)*。 diff --git a/lib/日志.mq.md b/lib/日志.mq.md index 23168cf..4354514 100644 --- a/lib/日志.mq.md +++ b/lib/日志.mq.md @@ -6,57 +6,128 @@ description: 按级别过滤的一行日志(中层 M6 + Mid2 M10 字段)。 按级别过滤的一行日志(中层 M6 + Mid2 M10 字段)。默认级别 info。 +输出按等级过滤的诊断日志。 + +能力与边界:日志等级只影响本次运行;日志是输出效应,不是返回值。call 将捕获输出与 JSON 结果分开。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/log.rs](../src/host/log.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 设级别 - + `级别` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 级别 | any | 必填 | 日志阈值:debug、info、warn 或 error | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 级别:debug / info / warn / error(或 调试/信息/警告/错误) | + +这里使用`级别`。 + +调用效应:pure。 级别:debug / info / warn / error(或 调试/信息/警告/错误)。 -*> host_log_set_level level=`级别`* +完成后返回*[级别:debug / info / warn / error(或 调试/信息/警告/错误)](> host_log_set_level level=`级别`)*。 ## 调试 - + `内容` - + `字段`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 写出调试日志行;可选字段映射 | + +这里使用`内容`、`字段`=None。 + +调用效应:output.write。 写出调试日志行;可选字段映射。 -**line = > host_log_line level="debug" text=`内容` fields=`字段`** +得到**`line` = [调用 log line]([写出调试日志行;可选字段映射](host_log_line(level="debug", text=`内容`, fields=`字段`)))**。 1. `line` - > 打印 内容=`line` + 这里**[输出本步已准备的消息](打印(内容=`line`))**。 2. * - **** + 完成后返回*None*。 ## 信息 - + `内容` - + `字段`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 写出信息日志行;可选字段映射 | + +这里使用`内容`、`字段`=None。 + +调用效应:output.write。 + +直接调用此函数: + +```sh +marqdo call lib/日志.mq.md 信息 '内容="handbook example"' '字段={"task":"sample"}' --effects output.write --json +``` 写出信息日志行;可选字段映射。 -**line = > host_log_line level="info" text=`内容` fields=`字段`** +得到**`line` = [调用 log line]([写出信息日志行;可选字段映射](host_log_line(level="info", text=`内容`, fields=`字段`)))**。 1. `line` - > 打印 内容=`line` + 这里**[输出本步已准备的消息](打印(内容=`line`))**。 2. * - **** + 完成后返回*None*。 ## 警告 - + `内容` - + `字段`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 写出警告日志行;可选字段映射 | + +这里使用`内容`、`字段`=None。 + +调用效应:output.write。 写出警告日志行;可选字段映射。 -**line = > host_log_line level="warn" text=`内容` fields=`字段`** +得到**`line` = [调用 log line]([写出警告日志行;可选字段映射](host_log_line(level="warn", text=`内容`, fields=`字段`)))**。 1. `line` - > 打印 内容=`line` + 这里**[输出本步已准备的消息](打印(内容=`line`))**。 2. * - **** + 完成后返回*None*。 ## 错误 - + `内容` - + `字段`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 字段 | any | None | 附加到日志事件的结构化字段与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 写出错误日志行;可选字段映射 | + +这里使用`内容`、`字段`=None。 + +调用效应:output.write。 写出错误日志行;可选字段映射。 -**line = > host_log_line level="error" text=`内容` fields=`字段`** +得到**`line` = [调用 log line]([写出错误日志行;可选字段映射](host_log_line(level="error", text=`内容`, fields=`字段`)))**。 1. `line` - > 打印 内容=`line` + 这里**[输出本步已准备的消息](打印(内容=`line`))**。 2. * - **** + 完成后返回*None*。 diff --git a/lib/日期时间.mq.md b/lib/日期时间.mq.md index 7530c47..5a71023 100644 --- a/lib/日期时间.mq.md +++ b/lib/日期时间.mq.md @@ -1,63 +1,191 @@ --- markup: occlusion title: lib/日期时间 -description: 日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移与少量 IANA 别名。 +description: 日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移和内嵌 IANA 时区与夏令时规则。 --- -日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移与少量 IANA 别名。 +日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移和内嵌 IANA 时区与夏令时规则。 + +处理时间戳、IANA 时区和当地日历。 + +能力与边界:zone 保留数值偏移,timezone 保留 IANA 身份。加按经过的秒数计算;加日历日保持当地钟点。夏令时缺口失败,重叠时间须明确选择策略。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/datetime.rs](../src/host/datetime.rs)、[src/host/data_ops.rs](../src/host/data_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 ## 现在 -现在。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 读取时钟并返回当前 UTC 日期时间记录 | -*> host_datetime_now* +调用效应:time.read。 + +读取时钟并返回当前 UTC 日期时间记录。 + +完成后返回*[读取时钟并返回当前 UTC 日期时间记录](host_datetime_now())*。 ## 自戳 - + `秒` - + `区`=None -自戳。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 秒 | any | 必填 | 以秒为单位的 Unix 时间戳 | +| 区 | any | None | 本操作接受的固定偏移或命名时区 | -*> host_datetime_from_unix unix=`秒` zone=`区`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC | + +这里使用`秒`、`区`=None。 + +调用效应:pure。 + +把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC。 + +完成后返回*[把 Unix 秒数转换为指定时区的日期时间记录;未指定时区时使用 UTC](> host_datetime_from_unix unix=`秒` zone=`区`)*。 ## 成戳 - + `时刻` -成戳。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | -*> host_datetime_to_unix dt=`时刻`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻 | + +这里使用`时刻`。 + +调用效应:pure。 + +从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻。 + +完成后返回*[从日期时间记录读取 Unix 秒数;格式与时区表示不改变同一时刻](> host_datetime_to_unix dt=`时刻`)*。 ## 解析 - + `内容` - + `格式`=None -解析。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 格式 | any | None | None 使用默认解析,或指定 rfc3339、strftime 格式 | -*> host_datetime_parse text=`内容` pattern=`格式`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339 | + +这里使用`内容`、`格式`=None。 + +调用效应:pure。 + +解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339。 + +完成后返回*[解析 RFC3339 或带可选时分秒的 YYYY-MM-DD 文本;显式格式使用 strftime 或 rfc3339](> host_datetime_parse text=`内容` pattern=`格式`)*。 ## 格式化 - + `时刻` - + `样式`=None -格式化。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | +| 样式 | any | None | 宿主日期格式化接口接受的格式样式 | -*> host_datetime_format dt=`时刻` style=`样式`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本 | + +这里使用`时刻`、`样式`=None。 + +调用效应:pure。 + +把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本。 + +完成后返回*[把日期时间记录格式化为 rfc3339、date、time,或显式 strftime 格式的文本](> host_datetime_format dt=`时刻` style=`样式`)*。 ## 加 - + `时刻` - + `天`=None - + `小时`=None - + `分钟`=None - + `秒数`=None -加。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | +| 天 | any | None | 增加的完整 24 小时时段数量 | +| 小时 | any | None | 增加的小时数 | +| 分钟 | any | None | 增加的分钟数 | +| 秒数 | any | None | 增加的秒数 | -*> host_datetime_add dt=`时刻` days=`天` hours=`小时` minutes=`分钟` seconds=`秒数`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移 | + +这里使用`时刻`、`天`=None、`小时`=None、`分钟`=None、`秒数`=None。 + +调用效应:pure。 + +增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移。 + +完成后返回*[增加经过的天、小时、分钟与秒;这里一天固定为 24 小时,命名时区在移动后重新计算偏移](> host_datetime_add dt=`时刻` days=`天` hours=`小时` minutes=`分钟` seconds=`秒数`)*。 ## 时区 - + `时刻` - + `区` -时区。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 时刻 | any | 必填 | 本库返回的日期时间记录,不是格式化文本 | +| 区 | any | 必填 | 本操作接受的固定偏移或命名时区 | -*> host_datetime_in_zone dt=`时刻` zone=`区`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳 | + +这里使用`时刻`、`区`。 + +调用效应:pure。 + +用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳。 + +完成后返回*[用固定偏移或 IANA 时区重新表示同一时刻,保留其 Unix 时间戳](> host_datetime_in_zone dt=`时刻` zone=`区`)*。 + +## 解析当地时间 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | +| 时区 | text | 必填 | 本操作接受的固定偏移或命名时区 | +| 歧义处理 | text | "reject" | 夏令时重叠处理:reject、earliest 或 latest | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest。格式为年-月-日 时:分:秒。 | + +这里使用`内容`、`时区`、`歧义处理`="reject"。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/日期时间.mq.md 解析当地时间 '内容="2024-11-03 01:30:00"' '时区="America/New_York"' '歧义处理="earliest"' --effects none --json +``` + +解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest。格式为年-月-日 时:分:秒。 + +完成后返回*[解析 IANA 时区的当地时间并返回结果记录;夏令时缺口失败,重叠须选择 reject/earliest/latest](> host_datetime_local text=`内容` zone=`时区` ambiguity=`歧义处理`)*。 + +## 加日历日 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 时刻 | map | 必填 | 本库返回的日期时间记录,不是格式化文本 | +| 天数 | number | 必填 | 增加的当地日历天数;跨夏令时保持墙钟时间 | +| 歧义处理 | text | "reject" | 夏令时重叠处理:reject、earliest 或 latest | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点。旧 add 按持续秒数计算,一天为二十四小时。 | + +这里使用`时刻`、`天数`、`歧义处理`="reject"。 + +调用效应:pure。 + +按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点。旧 add 按持续秒数计算,一天为二十四小时。 + +完成后返回*[按当地日历增加日期并返回结果记录,跨夏令时保持当地钟点](> host_datetime_calendar_add dt=`时刻` days=`天数` ambiguity=`歧义处理`)*。 diff --git a/lib/时间.mq.md b/lib/时间.mq.md index a570190..716b8b2 100644 --- a/lib/时间.mq.md +++ b/lib/时间.mq.md @@ -6,39 +6,100 @@ description: 中文时间包装 Unix 时间、格式化、解析与睡眠。 +格式化时间戳并控制等待。 + +能力与边界:读取当前时间需要时钟效应;等待具有控制效应,在捕获模式下会被限制。日历和 IANA 时区规则由日期时间库负责。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/time.rs](../src/host/time.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 此刻秒 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 当前 Unix 秒 | + +调用效应:time.read。 + 当前 Unix 秒。 调用例:[时间.此刻秒] -*> host_now_unix* +完成后返回*[当前 Unix 秒](host_now_unix())*。 ## 此刻毫秒 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 当前 Unix 毫秒 | + +调用效应:time.read。 + 当前 Unix 毫秒。 -*> host_now_ms* +完成后返回*[当前 Unix 毫秒](host_now_ms())*。 ## 格式化 - + `秒` - + `格式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 秒 | any | 必填 | 以秒为单位的 Unix 时间戳 | +| 格式 | any | 必填 | strftime 日期时间格式文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 用格式把秒格式化成文本 | + +这里使用`秒`、`格式`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/时间.mq.md 格式化 '秒=0' '格式="%Y-%m-%d"' --effects none --json +``` 用格式把秒格式化成文本。 -*> host_format_time unix=`秒` pattern=`格式`* +完成后返回*[用格式把秒格式化成文本](> host_format_time unix=`秒` pattern=`格式`)*。 ## 睡眠毫秒 - + `毫秒` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 睡眠指定的毫秒数 | + +这里使用`毫秒`。 + +调用效应:process.control。 睡眠指定的毫秒数。 -*> host_sleep_ms ms=`毫秒`* +完成后返回*[睡眠指定的毫秒数](> host_sleep_ms ms=`毫秒`)*。 ## 解析时间 - + `内容` - + `格式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 格式 | any | 必填 | strftime 日期时间格式文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 按格式解析内容,得到 Unix 秒 | + +这里使用`内容`、`格式`。 + +调用效应:pure。 按格式解析内容,得到 Unix 秒。 -*> host_parse_time text=`内容` pattern=`格式`* +完成后返回*[按格式解析内容,得到 Unix 秒](> host_parse_time text=`内容` pattern=`格式`)*。 diff --git a/lib/机密.mq.md b/lib/机密.mq.md index 792790c..361e17a 100644 --- a/lib/机密.mq.md +++ b/lib/机密.mq.md @@ -6,18 +6,56 @@ description: 安全随机令牌(中层 M3)。勿用 math.random 生成令牌 安全随机令牌。勿用 math.random 生成令牌。 +生成密码学随机令牌。 + +能力与边界:字节数是输入字节长度,不是输出文本长度。不能用数学伪随机数生成凭证;浏览器熵源依赖运行时桥接,不可悄悄替换为伪随机。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/secrets.rs](../src/host/secrets.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 十六进制令牌 - + `字节数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 字节数 | any | None | 请求的字节数;None 使用接口默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 字节长度(默认 16),返回长度为 2*字节数 的小写 hex | + +这里使用`字节数`=None。 + +调用效应:random.read。 + +直接调用此函数: + +```sh +marqdo call lib/机密.mq.md 十六进制令牌 '字节数=16' --effects random.read --json +``` 字节长度(默认 16),返回长度为 2*字节数 的小写 hex。 调用例:[机密.十六进制令牌] 字节数=16 -*> host_secrets_token_hex n=`字节数`* +完成后返回*[字节长度(默认 16),返回长度为 2*字节数 的小写 hex](> host_secrets_token_hex n=`字节数`)*。 ## 网址安全令牌 - + `字节数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 字节数 | any | None | 请求的字节数;None 使用接口默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 字节长度(默认 16),URL-safe Base64(无填充) | + +这里使用`字节数`=None。 + +调用效应:random.read。 字节长度(默认 16),URL-safe Base64(无填充)。 -*> host_secrets_token_urlsafe n=`字节数`* +完成后返回*[字节长度(默认 16),URL-safe Base64(无填充)](> host_secrets_token_urlsafe n=`字节数`)*。 diff --git a/lib/标识.mq.md b/lib/标识.mq.md index 344f766..99738af 100644 --- a/lib/标识.mq.md +++ b/lib/标识.mq.md @@ -6,10 +6,34 @@ description: UUID 版本 4(中层 M6)。经 getrandom 安全随机。 随机 UUID。不要自己拼不可靠的标识。 +生成 UUID v4 标识。 + +能力与边界:使用系统熵生成 UUID v4,不是可复现常量;不能把普通标识当作授权令牌。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口: + +实现入口:[src/host/uuid_ops.rs](../src/host/uuid_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 版本4 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 生成 UUID 版本 4 字符串 | + +调用效应:random.read。 + +直接调用此函数: + +```sh +marqdo call lib/标识.mq.md 版本4 --effects random.read --json +``` + 生成 UUID 版本 4 字符串。 调用例:[标识.版本4] -*> host_uuid_v4* +完成后返回*[生成 UUID 版本 4 字符串](host_uuid_v4())*。 diff --git a/lib/正则.mq.md b/lib/正则.mq.md index 94ee4c4..4a99bd9 100644 --- a/lib/正则.mq.md +++ b/lib/正则.mq.md @@ -6,46 +6,117 @@ description: 正则表达式(中层 M1)。Unicode;无回溯引用。 正则表达式。Unicode;无回溯引用。字面替换请用 lib/文本。 +进行 Unicode 正则匹配。 + +能力与边界:不支持反向引用;当前查找返回完整匹配,不承诺捕获组对象或替换回调。字面字符串替换使用文本库。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/re.rs](../src/host/re.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 匹配 - + `内容` - + `模式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 内容是否匹配模式 | + +这里使用`内容`、`模式`。 + +调用效应:pure。 内容是否匹配模式。 调用例:[正则.匹配] 内容=`s` 模式="a+" -*> host_re_is_match text=`内容` pattern=`模式`* +完成后返回*[内容是否匹配模式](> host_re_is_match text=`内容` pattern=`模式`)*。 ## 查找 - + `内容` - + `模式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 在内容中查找模式的首个匹配;没有 → None | + +这里使用`内容`、`模式`。 + +调用效应:pure。 在内容中查找模式的首个匹配;没有 → None。 -*> host_re_find text=`内容` pattern=`模式`* +完成后返回*[在内容中查找模式的首个匹配;没有 → None](> host_re_find text=`内容` pattern=`模式`)*。 ## 查找全部 - + `内容` - + `模式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 在内容中查找模式的全部匹配 | + +这里使用`内容`、`模式`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/正则.mq.md 查找全部 '内容="a12 b34"' '模式="[0-9]+"' --effects none --json +``` 在内容中查找模式的全部匹配。 -*> host_re_find_all text=`内容` pattern=`模式`* +完成后返回*[在内容中查找模式的全部匹配](> host_re_find_all text=`内容` pattern=`模式`)*。 ## 替换 - + `内容` - + `模式` - + `为` - + `次数`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | +| 为 | any | 必填 | 替换匹配片段所用的文本 | +| 次数 | any | None | 最大替换次数;None 使用操作说明中的默认值 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部) | + +这里使用`内容`、`模式`、`为`、`次数`=None。 + +调用效应:pure。 用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部)。 -*> host_re_replace text=`内容` pattern=`模式` with=`为` count=`次数`* +完成后返回*[用为替换内容中匹配模式的部分;可选次数限制(缺省 = 全部)](> host_re_replace text=`内容` pattern=`模式` with=`为` count=`次数`)*。 ## 拆分 - + `内容` - + `模式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 模式 | any | 必填 | 宿主 regex 实现支持的正则表达式 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 按模式拆分内容 | + +这里使用`内容`、`模式`。 + +调用效应:pure。 按模式拆分内容。 -*> host_re_split text=`内容` pattern=`模式`* +完成后返回*[按模式拆分内容](> host_re_split text=`内容` pattern=`模式`)*。 diff --git a/lib/浏览器.mq.md b/lib/浏览器.mq.md index 9dabfc2..9747b7d 100644 --- a/lib/浏览器.mq.md +++ b/lib/浏览器.mq.md @@ -9,107 +9,255 @@ import: 浏览器效应助手(WASM 客户端)。优先 GFM 表格 + 本库;勿用 json.set 链拼效应。 +使用普通结构化值构造浏览器效果。 + +能力与边界:构造效果是纯数据变换,由官方 WASM 桥接在浏览器中执行。原生进程生成效果记录不表示 DOM 已更新;业务逻辑仍写在 Marqdo 中。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[crates/marqdo-wasm/js/marqdo-bridge.js](../crates/marqdo-wasm/js/marqdo-bridge.js) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 设文本 - + `选择器` - + `文本` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_text 效应 | + +这里使用`选择器`、`文本`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/浏览器.mq.md 设文本 '选择器="#status"' '文本="Ready"' --effects none --json +``` 构造 set_text 效应。 -**`m` = > table.put in=None at=选择器 value=文本** -*> table.put in=None at="set_text" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`文本`))**。 +完成后返回*[在新记录中设置 set_text 字段](table.put(in=None, at="set_text", value=`m`))*。 ## 设HTML - + `选择器` - + `html` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| html | any | 必填 | HTML 片段;普通不可信文本应使用设文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_html 效应 | + +这里使用`选择器`、`html`。 + +调用效应:pure。 构造 set_html 效应。 -**`m` = > table.put in=None at=选择器 value=html** -*> table.put in=None at="set_html" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`html`))**。 +完成后返回*[在新记录中设置 set_html 字段](table.put(in=None, at="set_html", value=`m`))*。 ## 设值 - + `选择器` - + `值` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_value 效应 | + +这里使用`选择器`、`值`。 + +调用效应:pure。 构造 set_value 效应。 -**`m` = > table.put in=None at=选择器 value=值** -*> table.put in=None at="set_value" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`值`))**。 +完成后返回*[在新记录中设置 set_value 字段](table.put(in=None, at="set_value", value=`m`))*。 ## 设类 - + `选择器` - + `类` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 类 | any | 必填 | 以空格分隔的 CSS 类名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_class 效应 | + +这里使用`选择器`、`类`。 + +调用效应:pure。 构造 set_class 效应。 -**`m` = > table.put in=None at=选择器 value=类** -*> table.put in=None at="set_class" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 +完成后返回*[在新记录中设置 set_class 字段](table.put(in=None, at="set_class", value=`m`))*。 ## 加类 - + `选择器` - + `类` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 类 | any | 必填 | 以空格分隔的 CSS 类名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 add_class 效应(classList.add;可用空格分隔多个类名) | + +这里使用`选择器`、`类`。 + +调用效应:pure。 构造 add_class 效应(classList.add;可用空格分隔多个类名)。 -**`m` = > table.put in=None at=选择器 value=类** -*> table.put in=None at="add_class" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 +完成后返回*[在新记录中设置 add_class 字段](table.put(in=None, at="add_class", value=`m`))*。 ## 去类 - + `选择器` - + `类` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 类 | any | 必填 | 以空格分隔的 CSS 类名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 remove_class 效应 | + +这里使用`选择器`、`类`。 + +调用效应:pure。 构造 remove_class 效应。 -**`m` = > table.put in=None at=选择器 value=类** -*> table.put in=None at="remove_class" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 +完成后返回*[在新记录中设置 remove_class 字段](table.put(in=None, at="remove_class", value=`m`))*。 ## 切类 - + `选择器` - + `类` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 类 | any | 必填 | 以空格分隔的 CSS 类名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 toggle_class 效应 | + +这里使用`选择器`、`类`。 + +调用效应:pure。 构造 toggle_class 效应。 -**`m` = > table.put in=None at=选择器 value=类** -*> table.put in=None at="toggle_class" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`类`))**。 +完成后返回*[在新记录中设置 toggle_class 字段](table.put(in=None, at="toggle_class", value=`m`))*。 ## 设样式 - + `选择器` - + `样式` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 样式 | any | 必填 | 目标元素的 CSS 属性与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_style 效应;样式为属性表或 cssText 字符串 | + +这里使用`选择器`、`样式`。 + +调用效应:pure。 构造 set_style 效应;样式为属性表或 cssText 字符串。 -**`m` = > table.put in=None at=选择器 value=样式** -*> table.put in=None at="set_style" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`样式`))**。 +完成后返回*[在新记录中设置 set_style 字段](table.put(in=None, at="set_style", value=`m`))*。 ## 设属性 - + `选择器` - + `属性` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 属性 | any | 必填 | 目标元素的 HTML 属性与值记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 set_attr 效应 | + +这里使用`选择器`、`属性`。 + +调用效应:pure。 构造 set_attr 效应。 -**`m` = > table.put in=None at=选择器 value=属性** -*> table.put in=None at="set_attr" value=m* +得到**`m` = [返回更新后的结构化值](table.put(in=None, at=`选择器`, value=`属性`))**。 +完成后返回*[在新记录中设置 set_attr 字段](table.put(in=None, at="set_attr", value=`m`))*。 ## 包装 - + `键` - + `值` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 单键效应包装 | + +这里使用`键`、`值`。 + +调用效应:pure。 单键效应包装。 -*> table.put in=None at=键 value=值* +完成后返回*[返回更新后的结构化值](table.put(in=None, at=`键`, value=`值`))*。 ## 合并 - + `甲` - + `乙` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 甲 | any | 必填 | 第一个浏览器效果记录 | +| 乙 | any | 必填 | 合入第一个记录的浏览器效果记录 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 合并两张效应表,右侧优先 | + +这里使用`甲`、`乙`。 + +调用效应:pure。 合并两张效应表,右侧优先。 -*> table.merge a=`甲` b=`乙`* +完成后返回*[调用 merge](table.merge(a=`甲`, b=`乙`))*。 ## 画布 - + `选择器` - + `命令` - + `清空`=True + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 命令 | any | 必填 | 按执行顺序排列的画布绘制命令列表 | +| 清空 | any | True | 绘制命令前是否清空画布 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 canvas 效应;命令一般为 @ 行表 | + +这里使用`选择器`、`命令`、`清空`=True。 + +调用效应:pure。 构造 canvas 效应;命令一般为 @ 行表。 @@ -119,34 +267,58 @@ import: |-----|-------|----------| | `选择器` | `清空` | `命令` | -*> table.put in=None at="canvas" value=spec* +完成后返回*[在新记录中设置 canvas 字段](table.put(in=None, at="canvas", value=`spec`))*。 ## 音频 - + `操作`="play" - + `id`="default" - + `源`="" - + `频率`=None - + `毫秒`=None - + `选择器`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 操作 | any | "play" | 音频命令:play、pause 或 stop | +| id | any | "default" | 音频通道标识 | +| 源 | any | "" | 音频 URL;beep 表示合成提示音 | +| 频率 | any | None | 振荡器频率,单位 Hz | +| 毫秒 | any | None | 时长或延迟,单位毫秒 | +| 选择器 | any | "" | 目标浏览器元素的 CSS 选择器 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 audio 效应 | + +这里使用`操作`="play"、`id`="default"、`源`=""、`频率`=None、`毫秒`=None、`选择器`=""。 + +调用效应:pure。 构造 audio 效应。 -**`spec` = > table.put in=None at="op" value=操作** -**`spec` = > table.put in=`spec` at="id" value=id** +本函数只返回效果记录,不会立刻播放声音。播放源、合成频率与音频元素按桥接规则选择;浏览器可能要求用户先交互。 + +得到**`spec` = [在新记录中设置 op 字段](table.put(in=None, at="op", value=`操作`))**。 +得到**`spec` = [在新记录中设置 id 字段](table.put(in=`spec`, at="id", value=`id`))**。 1. `源` != "" - **`spec` = > table.put in=`spec` at="src" value=源** + 得到**`spec` = [在新记录中设置 src 字段](table.put(in=`spec`, at="src", value=`源`))**。 1. `频率` != None - **`spec` = > table.put in=`spec` at="freq" value=频率** + 得到**`spec` = [在新记录中设置 freq 字段](table.put(in=`spec`, at="freq", value=`频率`))**。 1. `毫秒` != None - **`spec` = > table.put in=`spec` at="ms" value=毫秒** + 得到**`spec` = [在新记录中设置 ms 字段](table.put(in=`spec`, at="ms", value=`毫秒`))**。 1. `选择器` != "" - **`spec` = > table.put in=`spec` at="sel" value=选择器** -*> table.put in=None at="audio" value=spec* + 得到**`spec` = [在新记录中设置 sel 字段](table.put(in=`spec`, at="sel", value=`选择器`))**。 +完成后返回*[在新记录中设置 audio 字段](table.put(in=None, at="audio", value=`spec`))*。 ## 读文件 - + `选择器` - + `然后` - + `格式`="text" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | +| 格式 | any | "text" | 浏览器桥接读取文件所用的内容表示 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 read_file 效应 | + +这里使用`选择器`、`然后`、`格式`="text"。 + +调用效应:pure。 构造 read_file 效应。 @@ -156,32 +328,78 @@ import: |-----|----|------| | `选择器` | `格式` | `然后` | -*> table.put in=None at="read_file" value=spec* +完成后返回*[在新记录中设置 read_file 字段](table.put(in=None, at="read_file", value=`spec`))*。 ## 观察 - + `规格` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 规格 | any | 必填 | 效果规格;使用单条记录或 @ 行记录列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 observe 效应 | + +这里使用`规格`。 + +调用效应:pure。 构造 observe 效应。 -*> table.put in=None at="observe" value=规格* +完成后返回*[在新记录中设置 observe 字段](table.put(in=None, at="observe", value=`规格`))*。 ## 取消观察 - + `规格` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 规格 | any | 必填 | 效果规格;使用单条记录或 @ 行记录列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 unobserve 效应 | + +这里使用`规格`。 + +调用效应:pure。 构造 unobserve 效应。 -*> table.put in=None at="unobserve" value=规格* +完成后返回*[在新记录中设置 unobserve 字段](table.put(in=None, at="unobserve", value=`规格`))*。 ## 聚焦 - + `选择器` -聚焦。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 选择器 | any | 必填 | 目标浏览器元素的 CSS 选择器 | -*> table.put in=None at="focus" value=选择器* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造目标元素的聚焦效果;浏览器桥接在处理函数返回后执行 | + +这里使用`选择器`。 + +调用效应:pure。 + +构造目标元素的聚焦效果;浏览器桥接在处理函数返回后执行。 + +完成后返回*[在新记录中设置 focus 字段](table.put(in=None, at="focus", value=`选择器`))*。 ## 导航 - + `url` - + `替换`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 替换 | any | False | 导航时是否替换当前历史项 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 navigate 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`url`、`替换`=False。 + +调用效应:pure。 + +构造 navigate 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -189,13 +407,24 @@ import: |-----|---------| | `url` | `替换` | -*> table.put in=None at="navigate" value=spec* +完成后返回*[在新记录中设置 navigate 字段](table.put(in=None, at="navigate", value=`spec`))*。 ## 存设 - + `键` - + `值` - + `作用域`="memory" - + `然后`="" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | +| 作用域 | any | "memory" | 存储范围:memory、local 或 session | +| 然后 | any | "" | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | SPA 客户端状态写入 | + +这里使用`键`、`值`、`作用域`="memory"、`然后`=""。 + +调用效应:pure。 SPA 客户端状态写入。优先 `作用域=memory`(页内内存)。 可选 `然后`:写入后回调,参数含 `{ok, op, key, scope}`。 @@ -203,31 +432,53 @@ SPA 客户端状态写入。优先 `作用域=memory`(页内内存)。 `spec` = | op | key | value | scope | -|----|-----|-------|-------| +| ---- | ----- | ------- | ------- | | set | `键` | `值` | `作用域` | 1. `然后` != "" - **`spec` = > table.put in=spec at="then" value=然后** -*> table.put in=None at="storage" value=spec* + 得到**`spec` = [在新记录中设置 then 字段](table.put(in=`spec`, at="then", value=`然后`))**。 +完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`spec`))*。 ## 存取 - + `键` - + `然后` - + `作用域`="memory" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | +| 作用域 | any | "memory" | 存储范围:memory、local 或 session | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 读取键并回调 `然后`,参数含 `{ok, value, found, key, scope}` | + +这里使用`键`、`然后`、`作用域`="memory"。 + +调用效应:pure。 读取键并回调 `然后`,参数含 `{ok, value, found, key, scope}`。 `spec` = | op | key | then | scope | -|----|-----|------|-------| +| ---- | ----- | ------ | ------- | | get | `键` | `然后` | `作用域` | -*> table.put in=None at="storage" value=spec* +完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`spec`))*。 ## 页跳 - + `url` - + `替换`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 替换 | any | False | 导航时是否替换当前历史项 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | SPA 导航(bridge `navigate`) | + +这里使用`url`、`替换`=False。 + +调用效应:pure。 SPA 导航(bridge `navigate`)。 @@ -237,19 +488,43 @@ SPA 导航(bridge `navigate`)。 |-----|---------| | `url` | `替换` | -*> table.put in=None at="navigate" value=spec* +完成后返回*[在新记录中设置 navigate 字段](table.put(in=None, at="navigate", value=`spec`))*。 ## 存储 - + `规格` -存储。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 规格 | any | 必填 | 存储操作记录:op、key、scope,以及可选 value 和 then | -*> table.put in=None at="storage" value=规格* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把存储规格包装为浏览器效果;桥接处理 op、key、value、scope 和 then | + +这里使用`规格`。 + +调用效应:pure。 + +把存储规格包装为浏览器效果;桥接处理 op、key、value、scope 和 then。 + +完成后返回*[在新记录中设置 storage 字段](table.put(in=None, at="storage", value=`规格`))*。 ## 定时 - + `毫秒` - + `然后` - + `id`="default" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | +| id | any | "default" | 定时器标识,之后传给清除定时器 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 interval 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`毫秒`、`然后`、`id`="default"。 + +调用效应:pure。 + +构造 interval 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -257,20 +532,44 @@ SPA 导航(bridge `navigate`)。 |----|------|----| | `毫秒` | `然后` | `id` | -*> table.put in=None at="interval" value=spec* +完成后返回*[在新记录中设置 interval 字段](table.put(in=None, at="interval", value=`spec`))*。 ## 清定时 - + `id`="default" -清定时。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| id | any | "default" | 对应创建或启动操作返回的标识 | -**`spec` = > table.put in=None at="id" value=id** -*> table.put in=None at="clear_interval" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 使用创建定时器时相同的标识,构造取消定时器效果 | + +这里使用`id`="default"。 + +调用效应:pure。 + +使用创建定时器时相同的标识,构造取消定时器效果。 + +得到**`spec` = [在新记录中设置 id 字段](table.put(in=None, at="id", value=`id`))**。 +完成后返回*[在新记录中设置 clear_interval 字段](table.put(in=None, at="clear_interval", value=`spec`))*。 ## 拉取 - + `url` - + `然后` - + `方法`="GET" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| url | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | +| 方法 | any | "GET" | HTTP 方法,例如 GET 或 POST | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 fetch 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`url`、`然后`、`方法`="GET"。 + +调用效应:pure。 + +构造 fetch 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -278,11 +577,24 @@ SPA 导航(bridge `navigate`)。 |-----|------|--------| | `url` | `然后` | `方法` | -*> table.put in=None at="fetch" value=spec* +完成后返回*[在新记录中设置 fetch 字段](table.put(in=None, at="fetch", value=`spec`))*。 ## 拉取全部 - + `请求` - + `然后` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 请求 | any | 必填 | 按顺序排列的浏览器请求规格记录列表 | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 fetch_all 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`请求`、`然后`。 + +调用效应:pure。 + +构造 fetch_all 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -290,11 +602,24 @@ SPA 导航(bridge `navigate`)。 |----------|------| | `请求` | `然后` | -*> table.put in=None at="fetch_all" value=spec* +完成后返回*[在新记录中设置 fetch_all 字段](table.put(in=None, at="fetch_all", value=`spec`))*。 ## 延后 - + `毫秒` - + `然后` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 毫秒 | any | 必填 | 时长或延迟,单位毫秒 | +| 然后 | any | 必填 | 桥接结果回调的 Marqdo 函数名;空文本表示无回调 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 after 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`毫秒`、`然后`。 + +调用效应:pure。 + +构造 after 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -302,27 +627,62 @@ SPA 导航(bridge `navigate`)。 |----|------| | `毫秒` | `然后` | -*> table.put in=None at="after" value=spec* +完成后返回*[在新记录中设置 after 字段](table.put(in=None, at="after", value=`spec`))*。 ## 套接字 - + `规格` -套接字。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 规格 | any | 必填 | 一条桥接效果规格记录 | -*> table.put in=None at="ws" value=规格* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把 WebSocket 操作规格包装为浏览器桥接效果;本函数不会打开原生套接字 | + +这里使用`规格`。 + +调用效应:pure。 + +把 WebSocket 操作规格包装为浏览器桥接效果;本函数不会打开原生套接字。 + +完成后返回*[在新记录中设置 ws 字段](table.put(in=None, at="ws", value=`规格`))*。 ## 剪贴板 - + `文本` -剪贴板。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | -**`spec` = > table.put in=None at="text" value=文本** -*> table.put in=None at="clipboard" value=spec* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 按文本构造剪贴板效果;消费效果时仍受浏览器权限和用户手势要求约束 | + +这里使用`文本`。 + +调用效应:pure。 + +按文本构造剪贴板效果;消费效果时仍受浏览器权限和用户手势要求约束。 + +得到**`spec` = [在新记录中设置 text 字段](table.put(in=None, at="text", value=`文本`))**。 +完成后返回*[在新记录中设置 clipboard 字段](table.put(in=None, at="clipboard", value=`spec`))*。 ## 下载 - + `正文` - + `文件名`="download.txt" - + `mime`="text/plain;charset=utf-8" + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 正文 | any | 必填 | 请求正文;文档操作中为替换正文 | +| 文件名 | any | "download.txt" | 建议的下载文件名 | +| mime | any | "text/plain;charset=utf-8" | 内容的 MIME 类型 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 构造 download 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面 | + +这里使用`正文`、`文件名`="download.txt"、`mime`="text/plain;charset=utf-8"。 + +调用效应:pure。 + +构造 download 效果记录,由浏览器桥接消费后执行;调用本函数本身不修改页面。 `spec` = @@ -330,4 +690,4 @@ SPA 导航(bridge `navigate`)。 |------|----------|------| | `正文` | `文件名` | `mime` | -*> table.put in=None at="download" value=spec* +完成后返回*[在新记录中设置 download 字段](table.put(in=None, at="download", value=`spec`))*。 diff --git a/lib/系统.mq.md b/lib/系统.mq.md index e2039cd..3fa49ad 100644 --- a/lib/系统.mq.md +++ b/lib/系统.mq.md @@ -6,76 +6,188 @@ description: 中文系统包装(加载环境 可选 路径=) 中文系统包装(加载环境 可选 路径=) +读取执行元数据并与宿主系统交互。 + +能力与边界:元信息与模块源码来自入口文档,不是被导入库。执行进程需要 process.exec;读写环境和读取配置具有独立效应。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/sys.rs](../src/host/sys.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 取环境 - + `名` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | 必填 | 环境变量名 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 读取环境变量名 | + +这里使用`名`。 + +调用效应:environment.read。 读取环境变量名。 -*> host_env_get name=`名`* +完成后返回*[读取环境变量名](> host_env_get name=`名`)*。 ## 设环境 - + `名` - + `值` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 名 | any | 必填 | 环境变量名 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 设置环境变量名的值 | + +这里使用`名`、`值`。 + +调用效应:environment.write。 设置环境变量名的值。 -*> host_env_set name=`名` value=`值`* +完成后返回*[设置环境变量名的值](> host_env_set name=`名` value=`值`)*。 ## 加载环境 - + `路径`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | None | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 加载 `.env`(可选具名实参 `路径=`) | + +这里使用`路径`=None。 + +调用效应:environment.write,fs.read。 加载 `.env`(可选具名实参 `路径=`)。不覆盖已有进程环境变量。 -*> host_dotenv_load path=`路径`* +完成后返回*[加载 .env(可选具名实参 路径=)](> host_dotenv_load path=`路径`)*。 ## 参数表 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 进程参数表 | + +调用效应:pure。 + 进程参数表。 -*> host_args* +完成后返回*[进程参数表](host_args())*。 ## 工作目录 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 当前工作目录 | + +调用效应:pure。 + 当前工作目录。 -*> host_cwd* +完成后返回*[当前工作目录](host_cwd())*。 ## 元信息 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 入口 `.mq.md` 已绑定的 Artifact Metadata(映射) | + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/系统.mq.md 元信息 --effects none --json +``` + 入口 `.mq.md` 已绑定的 Artifact Metadata(映射)。见 `doc/design/binding.md`。 -*> host_meta* +完成后返回*[入口 .mq.md 已绑定的 Artifact Metadata(映射)](host_meta())*。 ## 取元信息 - + `键` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 按键取一条元信息;缺失 → None | + +这里使用`键`。 + +调用效应:pure。 按键取一条元信息;缺失 → None。 -*> host_meta_get key=`键`* +完成后返回*[按键取一条元信息;缺失 → None](> host_meta_get key=`键`)*。 ## 工件种类 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 入口 Artifact 分类:`web` / `endpoint` / `prompt` / `other`;无 `type`/`类型` → None | + +调用效应:pure。 + 入口 Artifact 分类:`web` / `endpoint` / `prompt` / `other`;无 `type`/`类型` → None。ADR 0007。 -*> host_artifact_kind* +完成后返回*[入口 Artifact 分类:web / endpoint / prompt / other;无 type/类型 → None](host_artifact_kind())*。 ## 模块源码 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 入口 `.mq.md` 全文(供 document-as-prompt) | + +调用效应:pure。 + 入口 `.mq.md` 全文(供 document-as-prompt)。未设置时为空文本。 -*> host_module_source* +完成后返回*[入口 .mq.md 全文(供 document-as-prompt)](host_module_source())*。 ## 退出 - + `码` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 码 | any | 必填 | 进程退出码;零表示成功 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 以代码退出进程 | + +这里使用`码`。 + +调用效应:process.control。 以代码退出进程。 -*> host_exit code=`码`* +完成后返回*[以代码退出进程](> host_exit code=`码`)*。 ## 执行 - + `命令` - + `参数`=None - + `捕获`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 命令 | any | 必填 | 可执行命令或解释器覆盖配置 | +| 参数 | any | None | 传给命令或函数的实参列表 | +| 捕获 | any | False | 是否返回命令输出而非直接转发 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 运行子进程 | + +这里使用`命令`、`参数`=None、`捕获`=False。 + +调用效应:process.exec。 运行子进程。默认返回退出码(整数)。 @@ -83,11 +195,22 @@ description: 中文系统包装(加载环境 可选 路径=) 在 `**…**` 内优先写裸变量 `参数=参数`;`` 参数=`参数` `` 亦可。 -*> host_exec cmd=`命令` args=`参数` capture=`捕获`* +完成后返回*[运行子进程](> host_exec cmd=`命令` args=`参数` capture=`捕获`)*。 ## 发布流事件 - + `事件` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 事件 | any | 必填 | 发布到当前流的结构化事件 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 向进程内 EventBus 发布流事件(供 `marqdo view` SSE) | + +这里使用`事件`。 + +调用效应:output.write。 向进程内 EventBus 发布流事件(供 `marqdo view` SSE)。无订阅者时为空操作。 -*> host_stream_publish event=`事件`* +完成后返回*[向进程内 EventBus 发布流事件(供 marqdo view SSE)](> host_stream_publish event=`事件`)*。 diff --git a/lib/结果.mq.md b/lib/结果.mq.md new file mode 100644 index 0000000..068e21f --- /dev/null +++ b/lib/结果.mq.md @@ -0,0 +1,100 @@ +--- +markup: occlusion +--- + +可恢复结果使用普通记录 ok/value/error;error 内含 code/message/operation。 +先判断 ok 再使用 value;结果包装不会绕过宿主权限检查。 + +以统一数据契约组合可恢复结果。 + +能力与边界:先检查 ok,再使用 value;HTTP 状态和子进程退出码仍需按领域规则判断;错误含 code/message/operation。尝试接口处理已定义的可恢复失败,不是捕获任意运行时错误的异常系统,也不会授予权限。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/result.rs](../src/host/result.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + +## 成功 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 值 | any | 必填 | 成功操作的值,包括 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| 结果 | map | Successful Result | + +这里使用`值`。 + +将当前输入交给 成功,保留同源能力的返回值和失败语义。 + +调用效应:pure。 + +`out` = + +| ok | value | error | +|----|-------|-------| +| True | `值` | None | + +完成后返回*out*。 + +## 失败 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 错误码 | text | 必填 | 供程序判断的稳定错误类别 | +| 消息 | text | 必填 | 供人阅读的错误解释 | +| 操作 | text | "application" | 发生失败的操作名 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| 结果 | map | Failed Result | + +这里使用`错误码`、`消息`、`操作`="application"。 + +将当前输入交给 失败,保留同源能力的返回值和失败语义。 + +调用效应:pure。 + +`failure` = + +| code | message | operation | +|------|---------|-----------| +| `错误码` | `消息` | `操作` | + +`out` = + +| ok | value | error | +|----|-------|-------| +| False | None | `failure` | + +完成后返回*out*。 + +## 值或默认 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 结果 | map | 必填 | 可恢复操作返回的结果记录 | +| 默认值 | any | None | 操作失败时明确采用的替代值 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| 结果 | any | Successful value or fallback | + +这里使用`结果`、`默认值`=None。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/结果.mq.md 值或默认 '结果={"ok":false,"value":null,"error":{"code":"missing","message":"absent","operation":"example"}}' '默认值="fallback"' --effects none --json +``` + +只在 ok 为真时读取 value;成功且值为 None 时仍保留 None。仅在操作失败时使用默认值,不按真假性吞掉零或空文本。 + +1. [operation succeeded](access(`结果`, "ok")) + 完成后返回*[successful value](access(结果, "value"))*。 +2. * + 完成后返回*默认值*。 diff --git a/lib/统计.mq.md b/lib/统计.mq.md index 82f19fa..48b20bc 100644 --- a/lib/统计.mq.md +++ b/lib/统计.mq.md @@ -6,25 +6,74 @@ description: 薄均值 / 中位数 / 样本标准差(中层 Mid2 M10)。非 薄数值摘要。不是数据框库。 +计算基础描述统计。 + +能力与边界:均值和中位数要求非空数字列表;这不是数据帧或数值数组运行时。矩阵计算由线性代数扩展负责。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/stats.rs](../src/host/stats.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 均值 - + `列表` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 列表的算术均值 | + +这里使用`列表`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/统计.mq.md 均值 '列表=[1,2,3]' --effects none --json +``` 列表的算术均值。 调用例:[统计.均值] 列表=`xs` -*> host_stats_mean list=`列表`* +完成后返回*[列表的算术均值](> host_stats_mean list=`列表`)*。 ## 中位数 - + `列表` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 列表的中位数 | + +这里使用`列表`。 + +调用效应:pure。 列表的中位数。 -*> host_stats_median list=`列表`* +完成后返回*[列表的中位数](> host_stats_median list=`列表`)*。 ## 标准差 - + `列表` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | any | 必填 | 输入列表;不可变更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 样本标准差;至少两个值 | + +这里使用`列表`。 + +调用效应:pure。 样本标准差;至少两个值。 -*> host_stats_stdev list=`列表`* +完成后返回*[样本标准差;至少两个值](> host_stats_stdev list=`列表`)*。 diff --git a/lib/编码.mq.md b/lib/编码.mq.md index 2ac61dc..4750d43 100644 --- a/lib/编码.mq.md +++ b/lib/编码.mq.md @@ -6,46 +6,128 @@ description: Base64、十六进制与基32编解码(中层 M1 + Mid2 M8)。U Base64、十六进制与基32编解码。UTF-8 文本往返。 +在 UTF-8 文本与 Base64、十六进制、Base32 之间转换。 + +能力与边界:这些历史接口用于文本往返。任意二进制应使用字节库的从编码;把无效 UTF-8 解码为文本会失败。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/encoding.rs](../src/host/encoding.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 基64编码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做 Base64 编码 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/编码.mq.md 基64编码 '内容="Marqdo"' --effects none --json +``` 对内容做 Base64 编码。 调用例:[编码.基64编码] 内容=`s` -*> host_encoding_base64_encode text=`内容`* +完成后返回*[对内容做 Base64 编码](> host_encoding_base64_encode text=`内容`)*。 ## 基64解码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做 Base64 解码 | + +这里使用`内容`。 + +调用效应:pure。 对内容做 Base64 解码。 -*> host_encoding_base64_decode text=`内容`* +完成后返回*[对内容做 Base64 解码](> host_encoding_base64_decode text=`内容`)*。 ## 十六进制编码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做十六进制编码 | + +这里使用`内容`。 + +调用效应:pure。 对内容做十六进制编码。 -*> host_encoding_hex_encode text=`内容`* +完成后返回*[对内容做十六进制编码](> host_encoding_hex_encode text=`内容`)*。 ## 十六进制解码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做十六进制解码 | + +这里使用`内容`。 + +调用效应:pure。 对内容做十六进制解码。 -*> host_encoding_hex_decode text=`内容`* +完成后返回*[对内容做十六进制解码](> host_encoding_hex_decode text=`内容`)*。 ## 基32编码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做基32编码(RFC 4648;= 填充) | + +这里使用`内容`。 + +调用效应:pure。 对内容做基32编码(RFC 4648;= 填充)。 -*> host_encoding_base32_encode text=`内容`* +完成后返回*[对内容做基32编码(RFC 4648;= 填充)](> host_encoding_base32_encode text=`内容`)*。 ## 基32解码 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做基32解码 | + +这里使用`内容`。 + +调用效应:pure。 对内容做基32解码。 -*> host_encoding_base32_decode text=`内容`* +完成后返回*[对内容做基32解码](> host_encoding_base32_decode text=`内容`)*。 diff --git a/lib/网络.mq.md b/lib/网络.mq.md index 8589255..c3985c0 100644 --- a/lib/网络.mq.md +++ b/lib/网络.mq.md @@ -1,85 +1,295 @@ --- markup: occlusion +import: + table: lib/table.mq.md + text: lib/text.mq.md title: lib/网络 description: 中文 HTTP(S) 包装。可选 headers / content_type 经宿主别名绑定。 --- 中文 HTTP(S) 包装。可选 headers / content_type 经宿主别名绑定。 +处理 HTTP、响应数据和有界下载。 + +能力与边界:读取只需 network.read;可恢复请求的方法可动态变化,因此保守要求 network.write。响应头是 name/values 行记录,可用响应头值取值。下载还需 fs.write;旧接口保留原契约。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/net.rs](../src/host/net.rs)、[src/host/net_ops.rs](../src/host/net_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 获取 - + `地址` - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 支持 HTTPS | + +这里使用`地址`、`headers`=None。 + +调用效应:network.read。 支持 HTTPS。可选具名实参 `headers=`(映射)。 -*> host_http_get url=`地址` headers=`headers`* +完成后返回*[支持 HTTPS](> host_http_get url=`地址` headers=`headers`)*。 ## 提交 - + `地址` - + `内容` - + `content_type`=None - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 内容 | any | 必填 | 请求正文;文档操作中为替换正文 | +| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | +| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 默认 Content-Type 为 JSON | + +这里使用`地址`、`内容`、`content_type`=None、`headers`=None。 + +调用效应:network.write。 默认 Content-Type 为 JSON。可选 `content_type=` / `headers=`。 -*> host_http_post url=`地址` body=`内容` content_type=`content_type` headers=`headers`* +完成后返回*[默认 Content-Type 为 JSON](> host_http_post url=`地址` body=`内容` content_type=`content_type` headers=`headers`)*。 ## 提交流式 - + `地址` - + `内容` - + `content_type`=None - + `headers`=None - + `打印增量`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 内容 | any | 必填 | 请求正文;文档操作中为替换正文 | +| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | +| headers | any | None | HTTP 头名称与值记录;None 不附加额外头 | +| 打印增量 | any | False | 是否在接收 SSE 时打印增量文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | POST 并消费 OpenAI 兼容 SSE | + +这里使用`地址`、`内容`、`content_type`=None、`headers`=None、`打印增量`=False。 + +调用效应:network.write。 POST 并消费 OpenAI 兼容 SSE。返回 `{status, events}`(`delta` / `done` / `error`)。`打印增量=真` 时边读边打印增量文本。 -*> host_http_post_sse url=`地址` body=`内容` content_type=`content_type` headers=`headers` echo=`打印增量`* +完成后返回*[POST 并消费 OpenAI 兼容 SSE](> host_http_post_sse url=`地址` body=`内容` content_type=`content_type` headers=`headers` echo=`打印增量`)*。 ## 解析流式 - + `内容` - + `打印增量`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 打印增量 | any | False | 是否在接收 SSE 时打印增量文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网) | + +这里使用`内容`、`打印增量`=False。 + +调用效应:pure。 离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网)。 -*> host_openai_sse_parse text=`内容` echo=`打印增量`* +完成后返回*[离线解析 OpenAI 聊天 SSE 正文为事件列表(不联网)](> host_openai_sse_parse text=`内容` echo=`打印增量`)*。 ## 请求 - + `方法` - + `地址` - + `body`=None - + `content_type`=None - + `headers`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 方法 | any | 必填 | HTTP 方法,例如 GET 或 POST | +| 地址 | any | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 正文 | any | None | 请求正文;文档操作中为替换正文 | +| content_type | any | None | HTTP 内容类型覆盖;None 使用接口默认值 | +| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 可选 `body=` / `content_type=` / `headers=` | + +这里使用`方法`、`地址`、`正文`=None、`content_type`=None、`表头`=None。 + +调用效应:network.write。 可选 `body=` / `content_type=` / `headers=`。 -*> host_http_request method=`方法` url=`地址` body=`body` content_type=`content_type` headers=`headers`* +完成后返回*[可选 body= / content_type= / headers=](> host_http_request method=`方法` url=`地址` body=`正文` content_type=`content_type` headers=`表头`)*。 ## 编码地址 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对 URL 段做百分号编码 | + +这里使用`内容`。 + +调用效应:pure。 对 URL 段做百分号编码。 -*> host_url_encode text=`内容`* +完成后返回*[对 URL 段做百分号编码](> host_url_encode text=`内容`)*。 ## 解析Cookie - + `内容` - + `是响应头`=False + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | +| 是响应头 | any | False | 是否按响应头而非请求头解析 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 解析 `Cookie` 请求头(默认)或一个/多个 `Set-Cookie` 响应头(`是响应头=真`)为 `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` 列表 | + +这里使用`内容`、`是响应头`=False。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/网络.mq.md 解析Cookie '内容="a=1; b=2"' --effects none --json +``` 解析 `Cookie` 请求头(默认)或一个/多个 `Set-Cookie` 响应头(`是响应头=真`)为 `{name, value, path, domain, expires, max_age, secure, http_only, same_site}` 列表。 -*> host_cookie_parse text=`内容` is_response=`是响应头`* +完成后返回*[解析 Cookie 请求头(默认)或一个/多个 Set-Cookie 响应头(是响应头=真)为 {name, value, path, domain, expires, max_age, secure, http_only, same_site} 列表](> host_cookie_parse text=`内容` is_response=`是响应头`)*。 ## 解析多部分 - + `正文` - + `边界` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 正文 | any | 必填 | 请求正文;文档操作中为替换正文 | +| 边界 | any | 必填 | Content-Type 头中的 multipart 分隔标记 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 解析 `multipart/form-data` 请求体(给定 `boundary`)为 `{name, filename?, content_type?, value}` 部件列表 | + +这里使用`正文`、`边界`。 + +调用效应:pure。 解析 `multipart/form-data` 请求体(给定 `boundary`)为 `{name, filename?, content_type?, value}` 部件列表。 -*> host_multipart_parse body=`正文` boundary=`边界`* +完成后返回*[解析 multipart/form-data 请求体(给定 boundary)为 {name, filename?, content_type?, value} 部件列表](> host_multipart_parse body=`正文` boundary=`边界`)*。 ## 解析Markdown - + `文本` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 文本 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O) | + +这里使用`文本`。 + +调用效应:pure。 将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O)。 -*> host_markdown_parse text=`文本`* +完成后返回*[将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O)](> host_markdown_parse text=`文本`)*。 + +## 可恢复请求 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 方法 | text | 必填 | HTTP 方法,例如 GET 或 POST | +| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 正文 | any | None | 请求正文;文档操作中为替换正文 | +| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | +| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | +| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | +| 响应类型 | text | "text" | 响应正文表示:text 或 bytes | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 返回统一结果记录;value 含 status、headers、body。响应头为 name/values 行记录。动态方法需要 network | + +这里使用`方法`、`地址`、`正文`=None、`表头`=None、`超时毫秒`=30000、`字节上限`=8388608、`响应类型`="text"。 + +调用效应:network.write。 + +正文可为文本、字节记录或空值;发送 JSON 前使用 json.stringify。请求头使用字典,响应头使用 name/values 行记录。输出参数和目标路径在联网前预检。 + +返回统一结果记录;value 含 status、headers、body。响应头为 name/values 行记录。动态方法需要 network.write;只读请求使用读取。HTTP 错误状态仍是响应,传输失败是错误。 + +完成后返回*[正文可为文本、字节记录或空值;发送 JSON 前使用 json.stringify](> host_http_request_result method=`方法` url=`地址` body=`正文` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限` response=`响应类型`)*。 + +## 下载 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | +| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | +| 字节上限 | number | 67108864 | 读取或展开的字节上限;超限则失败 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 有界流式下载至文件;成功后原子替换,失败保留原文件。返回结果记录,value 含 status、headers、size、path;需要 network | + +这里使用`地址`、`路径`、`表头`=None、`超时毫秒`=30000、`字节上限`=67108864。 + +调用效应:fs.write,network.read。 + +有界流式下载至文件;成功后原子替换,失败保留原文件。返回结果记录,value 含 status、headers、size、path;需要 network.read 与 fs.write。 + +完成后返回*[有界流式下载至文件;成功后原子替换,失败保留原文件](> host_http_download url=`地址` path=`路径` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限`)*。 + +## 读取 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 地址 | text | 必填 | 目标 URL;HTTP 接口接受 http 或 https | +| 表头 | any | None | HTTP 头名称与值记录;None 不附加额外头 | +| 超时毫秒 | number | 30000 | 超时毫秒数;等待后检查操作结果 | +| 字节上限 | number | 8388608 | 读取或展开的字节上限;超限则失败 | +| 响应类型 | text | "text" | 响应正文表示:text 或 bytes | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 只读 GET 请求,返回统一结果记录;只需 network | + +这里使用`地址`、`表头`=None、`超时毫秒`=30000、`字节上限`=8388608、`响应类型`="text"。 + +调用效应:network.read。 + +只读 GET 请求,返回统一结果记录;只需 network.read。响应头为 name/values 行记录,响应类型可选 text/bytes。 + +完成后返回*[只读 GET 请求,返回统一结果记录;只需 network.read](> host_http_get_result url=`地址` headers=`表头` timeout_ms=`超时毫秒` max_bytes=`字节上限` response=`响应类型`)*。 + +## 响应头值 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 响应头 | list | 必填 | 响应中的 headers 行记录 | +| 名称 | text | 必填 | 头部名称 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 同名头部的全部值 | + +这里使用`响应头`、`名称`。 + +调用效应:pure。 + +从响应头行记录中按不区分大小写的名称取全部值;不存在返回空列表。请求的 headers 参数仍使用字典,响应 headers 使用行记录以保留任意名称和重复值。 + +得到**`lower` = [调用 to lower](text.to_lower(text=`名称`))**。 +得到**`matches` = [调用 where](table.where(list=`响应头`, key="name", value=`lower`))**。 +得到**`values` = [调用 pluck](table.pluck(list=`matches`, key="values"))**。 +完成后返回*[调用 flatten](table.flatten(list=`values`))*。 diff --git a/lib/自写回.mq.md b/lib/自写回.mq.md index 4dc749c..d881488 100644 --- a/lib/自写回.mq.md +++ b/lib/自写回.mq.md @@ -6,52 +6,131 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回) 将运行结果写回 .mq.md(Jupyter 式自写回) +读取并维护持久化执行输出槽位。 + +能力与边界:记录与读取默认锚定入口的当前调用点;命名槽互相隔离。结构化章节修改使用文档库,而不是把自写回当作任意文档编辑器。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +相对文件路径以 --fs-root 为准,省略时以被调用文件所在目录为准。写入需要显式 fs.write 授权,子进程需要 process.exec;纯计算无需 IO 权限。 + +实现入口:[src/host/writeback.rs](../src/host/writeback.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 写回 - + `值` - + `末尾`=False - + `键`=None - + `行`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | +| 末尾 | any | False | 是否追加到目标区块末尾 | +| 键 | any | None | 要读取、比较或更新的字段名或存储键 | +| 行 | any | None | 加入受管理写回区块的文本行 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 `` | + +这里使用`值`、`末尾`=False、`键`=None、`行`=None。 + +调用效应:fs.write。 在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 ``。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。 -*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`* +完成后返回*[在入口文件中写入自写回块:若 值 像图片路径/URL(.png / .svg / … 或 data:image/…)则写成 !marqdo-out(…),否则写成 ](> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`)*。 ## 取 - + `末尾`=False - + `键`=None - + `行`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 末尾 | any | False | 是否追加到目标区块末尾 | +| 键 | any | None | 要读取、比较或更新的字段名或存储键 | +| 行 | any | None | 加入受管理写回区块的文本行 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 读取当前调用处紧邻无键块、无键末尾块,或命名槽 | + +这里使用`末尾`=False、`键`=None、`行`=None。 + +调用效应:fs.read。 读取当前调用处紧邻无键块、无键末尾块,或命名槽。 -*> host_writeback_get at_end=`末尾` key=`键` line=`行`* +完成后返回*[读取当前调用处紧邻无键块、无键末尾块,或命名槽](> host_writeback_get at_end=`末尾` key=`键` line=`行`)*。 ## 清除 - + `末尾`=False - + `键`=None - + `行`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 末尾 | any | False | 是否追加到目标区块末尾 | +| 键 | any | None | 要读取、比较或更新的字段名或存储键 | +| 行 | any | None | 加入受管理写回区块的文本行 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 删除紧邻块、末尾块或命名槽 | + +这里使用`末尾`=False、`键`=None、`行`=None。 + +调用效应:fs.write。 删除紧邻块、末尾块或命名槽。 -*> host_writeback_clear at_end=`末尾` key=`键` line=`行`* +完成后返回*[删除紧邻块、末尾块或命名槽](> host_writeback_clear at_end=`末尾` key=`键` line=`行`)*。 ## 确保 - + `键` - + `占位`=pending - + `行`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键 | any | 必填 | 要读取、比较或更新的字段名或存储键 | +| 占位 | any | "pending" | 创建受管理区块时使用的占位文本 | +| 行 | any | None | 加入受管理写回区块的文本行 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 若命名槽不存在则创建并写入占位;已存在则不改动 | + +这里使用`键`、`占位`="pending"、`行`=None。 + +调用效应:fs.write。 若命名槽不存在则创建并写入占位;已存在则不改动。 -*> host_writeback_ensure key=`键` placeholder=`占位` line=`行`* +完成后返回*[若命名槽不存在则创建并写入占位;已存在则不改动](> host_writeback_ensure key=`键` placeholder=`占位` line=`行`)*。 ## 列出 -列出。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件 | -*> host_writeback_list* +调用效应:fs.read。 + +列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件。 + +完成后返回*[列出当前入口源码中的受管理输出槽位;不写入,也不读取其他文件](host_writeback_list())*。 ## 扫描路径 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察) | + +这里使用`路径`。 + +调用效应:fs.read。 + +直接调用此函数: + +```sh +marqdo call lib/自写回.mq.md 扫描路径 '路径="lib/writeback.mq.md"' --effects fs.read --fs-root . --json +``` 扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察)。 -*> host_writeback_scan_path path=`路径`* +完成后返回*[扫描任意文件中的自写回槽(注释块与 !marqdo-out(…) 图片;工作簿观察)](> host_writeback_scan_path path=`路径`)*。 diff --git a/lib/表.mq.md b/lib/表.mq.md index 6ffd73c..63e9d53 100644 --- a/lib/表.mq.md +++ b/lib/表.mq.md @@ -2,291 +2,1177 @@ markup: occlusion title: lib/表 description: >- - 列表与字典。优先用「改」(路径 1-based,与链接取元同构);取/改位/切片为 0-based。 + 列表与字典。优先用「改」(路径 1-based,与access 取元同构);取/改位/切片为 0-based。 json 只管解析/序列化。 --- -列表与字典。嵌套写入优先「改」;作者程序里读元用链接取元,不要新写脚注取元。 +列表与字典。嵌套写入优先「改」;作者程序里读元用access 取元,不要新写脚注取元。 + +用明确的数据形态变换列表、字典和行记录。 + +能力与边界:access 与改的整数路径从一开始;取、切片、插入、删位等旧接口从零开始。更新返回新值,必须保存。行数只是长度别名;列转行、行转列明确转换形态。相等比较沿用运行时的类型和字典顺序规则。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/collection.rs](../src/host/collection.rs)、[src/host/collection_ops.rs](../src/host/collection_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 ## 改 - + `入` - + `于` - + `值` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 入 | any | 必填 | 输入集合;None 用于创建新记录 | +| 于 | any | 必填 | 文本键、从一开始的下标,或由键与下标组成的嵌套路径 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 把集合入在路径于上的那一元改成值 | + +这里使用`入`、`于`、`值`。 + +调用效应:pure。 把集合入在路径于上的那一元改成值。 -于可以是文本键、1-based 下标,或键/下标组成的路径列表(与链接取元嵌套同构)。 +于可以是文本键、1-based 下标,或键/下标组成的路径列表(与access 取元嵌套同构)。 调用例:[表.改] 入=None 于="Authorization" 值="Bearer-x" -*> host_collection_put in=`入` at=`于` value=`值`* +完成后返回*[把集合入在路径于上的那一元改成值](> host_collection_put in=`入` at=`于` value=`值`)*。 ## 长度 - + `xs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 列表或字典 xs 的长度 | + +这里使用`xs`。 + +调用效应:pure。 列表或字典 xs 的长度。 -*> len `xs`* +完成后返回*[调用 len](len(`xs`))*。 ## 行数 - + `xs` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | 列表 xs 的行数(同长度) | + +这里使用`xs`。 + +调用效应:pure。 列表 xs 的行数(同长度)。 -*> len `xs`* +完成后返回*[调用 len](len(`xs`))*。 ## 取 - + `xs` - + `i` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | +| i | number | 必填 | 从零开始的元素或行下标 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 从零起取 xs 的第 i 项(与内置 at 相同) | + +这里使用`xs`、`i`。 + +调用效应:pure。 从零起取 xs 的第 i 项(与内置 at 相同)。越界 → None。 -*> at value=`xs` index=`i`* +完成后返回*[调用 at](at(value=`xs`, index=`i`))*。 ## 取行 - + `xs` - + `i` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| xs | any | 必填 | 本操作要求的输入列表或集合 | +| i | number | 必填 | 从零开始的元素或行下标 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 从零起取 xs 的第 i 行 | + +这里使用`xs`、`i`。 + +调用效应:pure。 从零起取 xs 的第 i 行。 -*> at value=`xs` index=`i`* +完成后返回*[调用 at](at(value=`xs`, index=`i`))*。 ## 追加 - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 在 list 末尾追加 item | + +这里使用`list`、`item`。 + +调用效应:pure。 在 list 末尾追加 item。 -*> host_list_append list=`list` item=`item`* +完成后返回*[在 list 末尾追加 item](> host_list_append list=`list` item=`item`)*。 ## 前插 - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 在 list 开头插入 item | + +这里使用`list`、`item`。 + +调用效应:pure。 在 list 开头插入 item。 -*> host_list_prepend list=`list` item=`item`* +完成后返回*[在 list 开头插入 item](> host_list_prepend list=`list` item=`item`)*。 ## 拼接 - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 第一个列表;None 用作空列表种子 | +| b | any | 必填 | 追加到 a 后面的列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 拼接列表 a 与 b | + +这里使用`a`、`b`。 + +调用效应:pure。 拼接列表 a 与 b。 -*> host_list_concat a=`a` b=`b`* +完成后返回*[拼接列表 a 与 b](> host_list_concat a=`a` b=`b`)*。 ## 插入 - + `list` - + `index` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| index | number | 必填 | 插入、替换或删除的位置,从零开始 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 在 list 的从零起 index 处插入 item | + +这里使用`list`、`index`、`item`。 + +调用效应:pure。 在 list 的从零起 index 处插入 item。 -*> host_list_insert list=`list` index=`index` item=`item`* +完成后返回*[在 list 的从零起 index 处插入 item](> host_list_insert list=`list` index=`index` item=`item`)*。 ## 改位 - + `list` - + `index` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| index | number | 必填 | 插入、替换或删除的位置,从零开始 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 从零起替换 list 的 index 为 item;日常嵌套改写请用「改」 | + +这里使用`list`、`index`、`item`。 + +调用效应:pure。 从零起替换 list 的 index 为 item;日常嵌套改写请用「改」。 -*> host_list_set_at list=`list` index=`index` item=`item`* +完成后返回*[从零起替换 list 的 index 为 item;日常嵌套改写请用「改」](> host_list_set_at list=`list` index=`index` item=`item`)*。 ## 删位 - + `list` - + `index` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| index | number | 必填 | 插入、替换或删除的位置,从零开始 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 删去 list 从零起的 index | + +这里使用`list`、`index`。 + +调用效应:pure。 删去 list 从零起的 index。 -*> host_list_remove_at list=`list` index=`index`* +完成后返回*[删去 list 从零起的 index](> host_list_remove_at list=`list` index=`index`)*。 ## 弹出 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 去掉 list 末项(空表报错) | + +这里使用`list`。 + +调用效应:pure。 去掉 list 末项(空表报错)。需要末值时先「末」。 -**`n` = > len `list`** +得到**`n` = [调用 len](len(`list`))**。 1. `n` > 0 - *> host_list_remove_at list=`list` index=`n` - 1* + 完成后返回*[去掉 list 末项(空表报错)](> host_list_remove_at list=`list` index=`n` - 1)*。 2. * - *> host_list_remove_at list=`list` index=0* + 完成后返回*[去掉 list 末项(空表报错)](> host_list_remove_at list=`list` index=0)*。 ## 首 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | list 的首项 | + +这里使用`list`。 + +调用效应:pure。 list 的首项。 -*> host_list_first list=`list`* +完成后返回*[list 的首项](> host_list_first list=`list`)*。 ## 末 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | list 的末项 | + +这里使用`list`。 + +调用效应:pure。 list 的末项。 -*> host_list_last list=`list`* +完成后返回*[list 的末项](> host_list_last list=`list`)*。 ## 切片 - + `list` - + `start` - + `end`=None + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| start | number | 必填 | 切片起点,从零开始且包含端点 | +| end | any | None | 切片终点,从零开始且不包含端点;None 表示到末尾 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 对 list 做从零起的半开切片,从 start 到 end | + +这里使用`list`、`start`、`end`=None。 + +调用效应:pure。 对 list 做从零起的半开切片,从 start 到 end。 -*> host_list_slice list=`list` start=`start` end=`end`* +完成后返回*[对 list 做从零起的半开切片,从 start 到 end](> host_list_slice list=`list` start=`start` end=`end`)*。 ## 含有 - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | list 是否含有 item | + +这里使用`list`、`item`。 + +调用效应:pure。 list 是否含有 item。 -*> host_list_contains list=`list` item=`item`* +完成后返回*[list 是否含有 item](> host_list_contains list=`list` item=`item`)*。 ## 下标 - + `list` - + `item` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| item | any | 必填 | 要插入、替换或比较的元素 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | item 在 list 中从零起的下标;没有 → None | + +这里使用`list`、`item`。 + +调用效应:pure。 item 在 list 中从零起的下标;没有 → None。 -*> host_list_index_of list=`list` item=`item`* +完成后返回*[item 在 list 中从零起的下标;没有 → None](> host_list_index_of list=`list` item=`item`)*。 ## 反转 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 反转 list | + +这里使用`list`。 + +调用效应:pure。 反转 list。 -*> host_list_reverse list=`list`* +完成后返回*[反转 list](> host_list_reverse list=`list`)*。 ## 排序 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 对 list 升序排序(优先 int/num/text) | + +这里使用`list`。 + +调用效应:pure。 对 list 升序排序(优先 int/num/text)。 -*> host_list_sort list=`list`* +完成后返回*[对 list 升序排序(优先 int/num/text)](> host_list_sort list=`list`)*。 ## 按键排序 - + `list` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| key | text | 必填 | 本操作需要的字段名或键 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 对 map 列表 list 按字段 key 排序 | + +这里使用`list`、`key`。 + +调用效应:pure。 对 map 列表 list 按字段 key 排序。 -*> host_list_sort_by list=`list` key=`key`* +完成后返回*[对 map 列表 list 按字段 key 排序](> host_list_sort_by list=`list` key=`key`)*。 ## 去重 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 对 list 保序去重(保留首次) | + +这里使用`list`。 + +调用效应:pure。 对 list 保序去重(保留首次)。 -*> host_list_unique list=`list`* +完成后返回*[对 list 保序去重(保留首次)](> host_list_unique list=`list`)*。 ## 分块 - + `list` - + `size` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | +| size | number | 必填 | 每块包含的元素数,必须为正数 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 把 list 按 size 分块 | + +这里使用`list`、`size`。 + +调用效应:pure。 把 list 按 size 分块。 -*> host_list_chunk list=`list` size=`size`* +完成后返回*[把 list 按 size 分块](> host_list_chunk list=`list` size=`size`)*。 ## 拉链 - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 各配对中第一项来自的列表 | +| b | any | 必填 | 各配对中第二项来自的列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 将 a 与 b 配对,取较短长度 | + +这里使用`a`、`b`。 + +调用效应:pure。 将 a 与 b 配对,取较短长度。 -*> host_list_zip a=`a` b=`b`* +完成后返回*[将 a 与 b 配对,取较短长度](> host_list_zip a=`a` b=`b`)*。 ## 展平 - + `list` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| list | any | 必填 | 输入列表;更新返回新列表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 对 list 做一层展平 | + +这里使用`list`。 + +调用效应:pure。 对 list 做一层展平。 -*> host_list_flatten list=`list`* +完成后返回*[对 list 做一层展平](> host_list_flatten list=`list`)*。 ## 清空 - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 按类型清空 value(空列表或空字典) | + +这里使用`value`。 + +调用效应:pure。 按类型清空 value(空列表或空字典)。 -*> host_collection_clear value=`value`* +完成后返回*[按类型清空 value(空列表或空字典)](> host_collection_clear value=`value`)*。 ## 取键 - + `map` - + `key` -浅取 map 的 key;缺键 → None。作者侧优先链接取元。 +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | +| key | text | 必填 | 本操作需要的字段名或键 | -*> host_map_get map=`map` key=`key`* +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 浅取 map 的 key;缺键 → None | + +这里使用`map`、`key`。 + +调用效应:pure。 + +浅取 map 的 key;缺键 → None。作者侧优先access 取元。 + +完成后返回*[浅取 map 的 key;缺键 → None](> host_map_get map=`map` key=`key`)*。 ## 设 - + `map` - + `key` - + `value` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | +| key | text | 必填 | 本操作需要的字段名或键 | +| value | any | 必填 | 运行时值;具体规则见下方操作说明 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 浅设 map 的 key 为 value;嵌套请用「改」 | + +这里使用`map`、`key`、`value`。 + +调用效应:pure。 浅设 map 的 key 为 value;嵌套请用「改」。 -*> host_map_set map=`map` key=`key` value=`value`* +完成后返回*[浅设 map 的 key 为 value;嵌套请用「改」](> host_map_set map=`map` key=`key` value=`value`)*。 ## 删键 - + `map` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | +| key | text | 必填 | 本操作需要的字段名或键 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 从 map 删除 key | + +这里使用`map`、`key`。 + +调用效应:pure。 从 map 删除 key。 -*> host_map_delete map=`map` key=`key`* +完成后返回*[从 map 删除 key](> host_map_delete map=`map` key=`key`)*。 ## 有键 - + `map` - + `key` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | +| key | text | 必填 | 本操作需要的字段名或键 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | map 是否有 key | + +这里使用`map`、`key`。 + +调用效应:pure。 map 是否有 key。 -*> host_map_has map=`map` key=`key`* +完成后返回*[map 是否有 key](> host_map_has map=`map` key=`key`)*。 ## 键表 - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | map 的键表 | + +这里使用`map`。 + +调用效应:pure。 map 的键表。 -*> host_map_keys map=`map`* +完成后返回*[map 的键表](> host_map_keys map=`map`)*。 ## 值表 - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | map 的值表 | + +这里使用`map`。 + +调用效应:pure。 map 的值表。 -*> host_map_values map=`map`* +完成后返回*[map 的值表](> host_map_values map=`map`)*。 ## 项表 - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | map 的键值对行表 | + +这里使用`map`。 + +调用效应:pure。 map 的键值对行表。 -*> host_map_items map=`map`* +完成后返回*[map 的键值对行表](> host_map_items map=`map`)*。 ## 合并 - + `a` - + `b` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| a | any | 必填 | 基础记录;None 用作空记录种子 | +| b | any | 必填 | 合入 a 的记录;后面的值覆盖同名键 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 合并 a 与 b(右侧覆盖左侧) | + +这里使用`a`、`b`。 + +调用效应:pure。 合并 a 与 b(右侧覆盖左侧)。 -*> host_map_merge a=`a` b=`b`* +完成后返回*[合并 a 与 b(右侧覆盖左侧)](> host_map_merge a=`a` b=`b`)*。 ## 键数 - + `map` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| map | any | 必填 | 输入文本键字典 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | number | map 的键数 | + +这里使用`map`。 + +调用效应:pure。 map 的键数。 -*> host_map_size map=`map`* +完成后返回*[map 的键数](> host_map_size map=`map`)*。 ## 空表 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 空列表 | + +调用效应:pure。 + 空列表。 -*> host_list_concat a=None b=None* +完成后返回*[空列表](> host_list_concat a=None b=None)*。 ## 空字典 -空字典。 +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 返回新的空字典,作为不可变更新的种子;它与空列表不同 | -*> host_map_merge a=None b=None* +调用效应:pure。 + +返回新的空字典,作为不可变更新的种子;它与空列表不同。 + +完成后返回*[返回新的空字典,作为不可变更新的种子;它与空列表不同](> host_map_merge a=None b=None)*。 + +## 序列 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 起 | number | 必填 | 序列的第一个数值 | +| 止 | number | 必填 | 序列不包含的终止边界 | +| 步长 | number | 1 | 非零序列步长;符号必须朝向终点 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项。 | + +这里使用`起`、`止`、`步长`=1。 + +调用效应:pure。 + +生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项。 + +完成后返回*[生成左闭右开的整数序列;允许负步长,拒绝零步长,最多一百万项](> host_table_range start=`起` end=`止` step=`步长`)*。 + +## 编号 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 起 | number | 0 | 第一条记录所用的索引值;默认从一开始 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 返回 index/value 记录列表;编号从 start 开始,输入不变。 | + +这里使用`列表`、`起`=0。 + +调用效应:pure。 + +返回 index/value 记录列表;编号从 start 开始,输入不变。 + +完成后返回*[返回 index/value 记录列表;编号从 start 开始,输入不变](> host_table_enumerate list=`列表` start=`起`)*。 + +## 提列 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 逐行提取一个字段;缺少字段时报错,不悄悄变为空。 | + +这里使用`列表`、`键`。 + +调用效应:pure。 + +逐行提取一个字段;缺少字段时报错,不悄悄变为空。 + +完成后返回*[逐行提取一个字段;缺少字段时报错,不悄悄变为空](> host_table_pluck list=`列表` key=`键`)*。 + +## 投影 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键表 | list | 必填 | 按顺序排列的字段名列表 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按 keys 顺序保留字段;每个字段必须存在。 | + +这里使用`列表`、`键表`。 + +调用效应:pure。 + +按 keys 顺序保留字段;每个字段必须存在。 + +完成后返回*[按 keys 顺序保留字段;每个字段必须存在](> host_table_project list=`列表` keys=`键表`)*。 + +## 筛选 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | +| 值 | any | 必填 | 待转换或保存的值;不会就地修改输入 | +| 操作 | text | "eq" | 本接口支持的操作名 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 筛选匹配记录。op 为 eq/ne/gt/ge/lt/le/contains/in;这是固定操作名,不执行文本代码。 | + +这里使用`列表`、`键`、`值`、`操作`="eq"。 + +调用效应:pure。 + +筛选匹配记录。op 为 eq/ne/gt/ge/lt/le/contains/in;这是固定操作名,不执行文本代码。 + +完成后返回*[筛选匹配记录](> host_table_where list=`列表` key=`键` value=`值` op=`操作`)*。 + +## 分组 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按首次出现顺序返回 key/count/rows 记录;分组键保留原类型。 | + +这里使用`列表`、`键`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/表.mq.md 分组 '列表=[{"team":"a","n":3},{"team":"b","n":1},{"team":"a","n":2}]' '键="team"' --effects none --json +``` + +按首次出现顺序返回 key/count/rows 记录;分组键保留原类型。 + +完成后返回*[按首次出现顺序返回 key/count/rows 记录;分组键保留原类型](> host_table_group_by list=`列表` key=`键`)*。 + +## 按键去重 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 每个字段值保留第一条记录,维持输入顺序。 | + +这里使用`列表`、`键`。 + +调用效应:pure。 + +每个字段值保留第一条记录,维持输入顺序。 + +完成后返回*[每个字段值保留第一条记录,维持输入顺序](> host_table_unique_by list=`列表` key=`键`)*。 + +## 聚合 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键 | any | None | 要读取、比较或更新的字段名或存储键 | +| 操作 | text | "sum" | 本接口支持的操作名 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 聚合标量列表或一个字段:sum/count/min/max/mean。空表求和与计数为零;空表最值与均值失败;整数求和检查溢出。 | + +这里使用`列表`、`键`=None、`操作`="sum"。 + +调用效应:pure。 + +聚合标量列表或一个字段:sum/count/min/max/mean。空表求和与计数为零;空表最值与均值失败;整数求和检查溢出。 + +完成后返回*[聚合标量列表或一个字段:sum/count/min/max/mean](> host_table_aggregate list=`列表` key=`键` op=`操作`)*。 + +## 多键排序 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 键表 | list | 必填 | 按顺序排列的字段名列表 | +| 降序 | bool | False | 是否按多键降序排列 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序。 | + +这里使用`列表`、`键表`、`降序`=False。 + +调用效应:pure。 + +按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序。 + +完成后返回*[按 keys 的字段顺序稳定排序;descending 改变比较方向,相同键保持顺序](> host_table_sort_keys list=`列表` keys=`键表` descending=`降序`)*。 + +## 改字段名 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 字段 | map | 必填 | 附加到日志事件的结构化字段与值记录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 用旧名到新名的字典改字段名;输出字段重名时报错。 | + +这里使用`列表`、`字段`。 + +调用效应:pure。 + +用旧名到新名的字典改字段名;输出字段重名时报错。 + +完成后返回*[用旧名到新名的字典改字段名;输出字段重名时报错](> host_table_rename list=`列表` fields=`字段`)*。 + +## 列转行 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列 | map | 必填 | 列名与列表记录;各列长度必须一致 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段。 | + +这里使用`列`。 + +调用效应:pure。 + +把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段。 + +完成后返回*[把列式字典转为行记录;各列必须是等长列表,不猜测普通对象字段](> host_table_from_columns columns=`列`)*。 + +## 行转列 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | list | 必填 | 行记录列表,不是隐式列式表 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 把字段集合相同的行记录转为列式字典;空输入返回空字典。 | + +这里使用`行`。 + +调用效应:pure。 + +把字段集合相同的行记录转为列式字典;空输入返回空字典。 + +完成后返回*[把字段集合相同的行记录转为列式字典;空输入返回空字典](> host_table_to_columns rows=`行`)*。 + +## 连接 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | +| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | +| 键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | +| 右键 | text | 必填 | 右侧记录中用于匹配的字段 | +| 模式 | text | "inner" | 连接方式:inner 或 left | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按字段相等连接;保持左表和右表匹配顺序。mode 为 inner/left;右侧重名字段加 right_ 前缀,仍冲突则失败。 | + +这里使用`左`、`右`、`键`、`右键`、`模式`="inner"。 + +调用效应:pure。 + +按字段相等连接;保持左表和右表匹配顺序。mode 为 inner/left;右侧重名字段加 right_ 前缀,仍冲突则失败。 + +完成后返回*[按字段相等连接;保持左表和右表匹配顺序](> host_table_join a=`左` b=`右` key=`键` right_key=`右键` mode=`模式`)*。 + +## 转字段类型 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | list | 必填 | 行记录列表,不是隐式列式表 | +| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段。 | + +这里使用`行`、`规则`。 + +调用效应:pure。 + +按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段。 + +完成后返回*[按 schema 转换 text/int/number/bool/any 字段;缺失或无效值报告行号和字段,保留其他字段](> host_table_cast rows=`行` schema=`规则`)*。 + +## 并集 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | +| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 保持首次出现顺序的并集;值相等规则与去重一致,区分类型。 | + +这里使用`左`、`右`。 + +调用效应:pure。 + +保持首次出现顺序的并集;值相等规则与去重一致,区分类型。 + +完成后返回*[保持首次出现顺序的并集;值相等规则与去重一致,区分类型](> host_table_union a=`左` b=`右`)*。 + +## 交集 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | +| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 保持输入顺序的交集,去除重复值。 | + +这里使用`左`、`右`。 + +调用效应:pure。 + +保持输入顺序的交集,去除重复值。 + +完成后返回*[保持输入顺序的交集,去除重复值](> host_table_intersection a=`左` b=`右`)*。 + +## 差集 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 左 | list | 必填 | 第一个操作数;适用范围见本操作说明 | +| 右 | list | 必填 | 第二个操作数;适用范围见本操作说明 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 保留左表中不在右表的值,维持顺序并去重。 | + +这里使用`左`、`右`。 + +调用效应:pure。 + +保留左表中不在右表的值,维持顺序并去重。 + +完成后返回*[保留左表中不在右表的值,维持顺序并去重](> host_table_difference a=`左` b=`右`)*。 + +## 尝试转类型 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | list | 必填 | 行记录列表,不是隐式列式表 | +| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 可恢复地转换字段;无效字段返回结果记录,不中断调用方。 | + +这里使用`行`、`规则`。 + +调用效应:pure。 + +可恢复地转换字段;无效字段返回结果记录,不中断调用方。 + +完成后返回*[可恢复地转换字段;无效字段返回结果记录,不中断调用方](> host_table_try_cast rows=`行` schema=`规则`)*。 + +## 校验记录 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行 | list | 必填 | 行记录列表,不是隐式列式表 | +| 规则 | map | 必填 | 字段与类型记录,采用标准契约类型词汇 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型。 | + +这里使用`行`、`规则`。 + +调用效应:pure。 + +按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型。 + +完成后返回*[按核心渐进式类型校验必需字段,结果错误含 details 行号与字段诊断;int 是核心 number 别名,严格整数转换使用转字段类型](> host_table_validate rows=`行` schema=`规则`)*。 + +## 查找首项 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | +| 键 | text | 必填 | 每行需要读取并比较的字段名 | +| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | +| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | 首个匹配行;没有匹配时为空值 | + +这里使用`列表`、`键`、`值`、`操作`="eq"。 + +调用效应:pure。 + +复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 + +得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 +完成后返回*[调用 首](首(list=`selected`))*。 + +## 任一满足 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | +| 键 | text | 必填 | 每行需要读取并比较的字段名 | +| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | +| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 是否至少一行匹配;空列表为假 | + +这里使用`列表`、`键`、`值`、`操作`="eq"。 + +调用效应:pure。 + +复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 + +得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 +得到**`matched` = [调用 len](len(`selected`))**。 +完成后返回*matched > 0*。 + +## 全部满足 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 按原有顺序检查的行记录列表,不会就地修改 | +| 键 | text | 必填 | 每行需要读取并比较的字段名 | +| 值 | any | 必填 | 比较右值;in 操作在此集合中测试成员关系 | +| 操作 | text | "eq" | eq、ne、gt、ge、lt、le、contains 或 in;无效操作会失败 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 是否每行都匹配;空列表为真 | + +这里使用`列表`、`键`、`值`、`操作`="eq"。 + +调用效应:pure。 + +复用同一筛选规则,保持原行顺序且不修改输入;缺失字段或无效操作仍会产生诊断。 + +得到**`selected` = [调用 筛选](筛选(列表=`列表`, 键=`键`, 值=`值`, 操作=`操作`))**。 +得到**`matched` = [调用 len](len(`selected`))**。 +得到**`total` = [调用 len](len(`列表`))**。 +完成后返回*matched == total*。 + +## 分组汇总 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 列表 | list | 必填 | 输入列表;不可变更新返回新列表 | +| 分组键 | text | 必填 | 要读取、比较或更新的字段名或存储键 | +| 字段 | text | 必填 | 各分组内需要聚合的数值字段 | +| 操作 | text | "sum" | 本接口支持的操作名 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | list | 批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表。 | + +这里使用`列表`、`分组键`、`字段`、`操作`="sum"。 + +调用效应:pure。 + +批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表。 + +完成后返回*[批量按键分组并聚合一个字段,返回 key/count/value 行记录,保持首次分组顺序;操作规则同聚合,避免在作者循环中反复复制增长的结果列表](> host_table_summarize list=`列表` key=`分组键` field=`字段` op=`操作`)*。 + +## 键值转记录 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 键值对 | list | 必填 | 有序行记录,每行含文本 key 与任意 value 字段;其他字段不参与构造 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| 结果 | map | 新记录;首次出现的键决定顺序,后续同名键替换其值 | + +调用效应:pure。 + +输入`键值对`采用普通 @ 行记录表,把过宽的横向记录改写成可逐行阅读的 key/value 数据。 +适合提示章节、配置片段和具名字段较多的记录;这里复用本库既有的不可变更新, +不解析 JSON 文本,也不另造表格方言。空列表得到空记录,缺少或无效的键交给改操作报告, +不会为了制造字典而添加一个无意义的占位列。 + +先准备**记录 = [创建新的空记录](空字典())**,再按行读取字段,使每一项的来源都保持可见。 + +- [把每条具名字段写入新记录](遍历 键值对 为 键值行) + 读取**键 = [取出本行的字段名](access(键值行, "key"))**, + 以及**值 = [取出本行的字段值](access(键值行, "value"))**。 + 然后保留**记录 = [设置字段而不修改输入行](改(入=`记录`, 于=`键`, 值=`值`))**。 + +处理完有序行后,返回*记录*。同名字段保留第一次出现的位置并更新其值; +原来的键值对仍可继续使用,本操作没有文件、网络或插件副作用。 diff --git a/lib/超文本.mq.md b/lib/超文本.mq.md index 3ca9078..4d4484d 100644 --- a/lib/超文本.mq.md +++ b/lib/超文本.mq.md @@ -6,18 +6,56 @@ description: HTML 转义 / 还原(中层 Mid2 M8)。拼装字符串时的 XS HTML 转义助手。把不可信文本拼进标记前先转义。 +转义或还原 HTML 文本。 + +能力与边界:文本转义不等于清洗任意 HTML 文档。站点内容优先采用 Markdown 叶子和结构化视图节点。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/html_ops.rs](../src/host/html_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 转义 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 对内容做 HTML 转义 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/超文本.mq.md 转义 '内容="&"' --effects none --json +``` 对内容做 HTML 转义。 调用例:[超文本.转义] 内容=`段` -*> host_html_escape text=`内容`* +完成后返回*[对内容做 HTML 转义](> host_html_escape text=`内容`)*。 ## 还原 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 还原内容里的 HTML 实体 | + +这里使用`内容`。 + +调用效应:pure。 还原内容里的 HTML 实体。 -*> host_html_unescape text=`内容`* +完成后返回*[还原内容里的 HTML 实体](> host_html_unescape text=`内容`)*。 diff --git a/lib/路径.mq.md b/lib/路径.mq.md index b404c10..5becc1c 100644 --- a/lib/路径.mq.md +++ b/lib/路径.mq.md @@ -6,54 +6,185 @@ description: 路径代数(中层 M2)。无 I/O;分隔符随宿主 OS。 只做路径代数。无 I/O;分隔符随宿主 OS。 +不访问磁盘的路径运算。 + +能力与边界:归一化是词法运算,不代表已获得文件访问权限。真正的 IO 路径由宿主按文件根目录检查。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/path.rs](../src/host/path.rs)、[src/host/fs_ops.rs](../src/host/fs_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 拼接 - + `甲` - + `乙` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 甲 | any | 必填 | 基础路径 | +| 乙 | any | 必填 | 追加到基础路径的路径片段 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 拼接路径段甲与乙 | + +这里使用`甲`、`乙`。 + +调用效应:pure。 拼接路径段甲与乙。 调用例:[路径.拼接] 甲="a" 乙="b" -*> host_path_join a=`甲` b=`乙`* +完成后返回*[拼接路径段甲与乙](> host_path_join a=`甲` b=`乙`)*。 ## 拆分 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 把路径拆成各段 | + +这里使用`路径`。 + +调用效应:pure。 把路径拆成各段。 -*> host_path_split path=`路径`* +完成后返回*[把路径拆成各段](> host_path_split path=`路径`)*。 ## 文件名 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 路径的末段文件名 | + +这里使用`路径`。 + +调用效应:pure。 路径的末段文件名。 -*> host_path_file_name path=`路径`* +完成后返回*[路径的末段文件名](> host_path_file_name path=`路径`)*。 ## 父目录 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 路径的父目录 | + +这里使用`路径`。 + +调用效应:pure。 路径的父目录。 -*> host_path_parent path=`路径`* +完成后返回*[路径的父目录](> host_path_parent path=`路径`)*。 ## 扩展名 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 路径的扩展名 | + +这里使用`路径`。 + +调用效应:pure。 路径的扩展名。 -*> host_path_extension path=`路径`* +完成后返回*[路径的扩展名](> host_path_extension path=`路径`)*。 ## 规范化 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 规范化路径(处理点段) | + +这里使用`路径`。 + +调用效应:pure。 规范化路径(处理点段)。 -*> host_path_normalize path=`路径`* +完成后返回*[规范化路径(处理点段)](> host_path_normalize path=`路径`)*。 ## 是绝对 - + `路径` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | any | 必填 | 授权文件根目录内的路径 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | bool | 路径是否为绝对路径 | + +这里使用`路径`。 + +调用效应:pure。 路径是否为绝对路径。 -*> host_path_is_absolute path=`路径`* +完成后返回*[路径是否为绝对路径](> host_path_is_absolute path=`路径`)*。 + +## 相对路径 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 基准 | text | 必填 | 计算相对路径所用的基础目录 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘。 | + +这里使用`路径`、`基准`。 + +调用效应:pure。 + +计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘。 + +完成后返回*[计算相对 base 的词法路径;两个参数须同为绝对或相对路径,不访问磁盘](> host_path_relative path=`路径` base=`基准`)*。 + +## 换扩展名 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 路径 | text | 必填 | 授权文件根目录内的路径 | +| 扩展名 | text | 必填 | 新扩展名,可带或不带开头的点 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 替换最后的扩展名;空扩展名表示去除。 | + +这里使用`路径`、`扩展名`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/路径.mq.md 换扩展名 '路径="notes/draft.txt"' '扩展名="md"' --effects none --json +``` + +替换最后的扩展名;空扩展名表示去除。 + +完成后返回*[替换最后的扩展名;空扩展名表示去除](> host_path_with_extension path=`路径` extension=`扩展名`)*。 diff --git a/lib/逗号表.mq.md b/lib/逗号表.mq.md index 313b994..d00e7da 100644 --- a/lib/逗号表.mq.md +++ b/lib/逗号表.mq.md @@ -6,18 +6,74 @@ description: CSV 解析/序列化(中层 M4)。首行为表头 → 映射列 CSV 解析与序列化。首行为表头;各行变成映射列表。 +解析并序列化带表头的 CSV 行记录。 + +能力与边界:解析后单元格是文本,使用表库明确转换类型;序列化依第一行字段顺序。输入应为行记录,不是列式字典。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口: + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 + ## 解析 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | list | 把 CSV 文本解析成映射列表 | + +这里使用`内容`。 + +调用效应:pure。 把 CSV 文本解析成映射列表。 调用例:[逗号表.解析] 内容=`原文` -*> host_csv_parse text=`内容`* +完成后返回*[把 CSV 文本解析成映射列表](> host_csv_parse text=`内容`)*。 ## 序列化 - + `行集` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 行集 | any | 必填 | 行记录列表,不是隐式列式表 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | text | 把映射列表序列化成 CSV 文本 | + +这里使用`行集`。 + +调用效应:pure。 把映射列表序列化成 CSV 文本。 -*> host_csv_stringify rows=`行集`* +完成后返回*[把映射列表序列化成 CSV 文本](> host_csv_stringify rows=`行集`)*。 + +## 尝试解析 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 返回 {ok,value,error};解析失败是可恢复的数据。 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/逗号表.mq.md 尝试解析 '内容="name,n"' --effects none --json +``` + +返回 {ok,value,error};解析失败是可恢复的数据。 + +完成后返回*[返回 {ok,value,error};解析失败是可恢复的数据](> host_try_csv_parse text=`内容`)*。 diff --git a/lib/配置表.mq.md b/lib/配置表.mq.md index c84b8e4..89cd416 100644 --- a/lib/配置表.mq.md +++ b/lib/配置表.mq.md @@ -1,16 +1,79 @@ --- markup: occlusion title: lib/配置表 -description: 只读 TOML 子集解析(中层 Mid2 M8)。表 / 标量 / 数组;无数组表。 +description: 标准 TOML 配置读写,支持数组表、多行文本和内联表;日期转为 ISO 文本。 --- -只读 TOML 子集。适合配置;不做完整 TOML 写出。 +标准 TOML 配置读写;日期转为 ISO 文本,序列化不保留原注释。 + +读写标准 TOML 配置。 + +能力与边界:支持内联表、多行文本和数组表。TOML 日期转换成 ISO 文本;序列化不支持空值,也不保留原注释。 + +本文件就是调用和开发手册:直接导入此文件,或用 marqdo call 按下面的函数标题调用。参数表说明类型和默认值;未填默认值的参数必须提供。返回表是渐进契约,后文说明失败与边界。 + +实现入口:[src/host/toml_ops.rs](../src/host/toml_ops.rs) + +开发时保持中英文语义一致,先组合公开库;仅在 OS 或算法边界添加宿主原语并声明效应。修改后运行 marqdo check --narrative-ratio 本文件,并执行 tests/stdlib_tasks.rs 的真实任务。 ## 解析 - + `内容` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | any | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | 把 TOML 文本解析成映射/列表/标量 | + +这里使用`内容`。 + +调用效应:pure。 把 TOML 文本解析成映射/列表/标量。 调用例:[配置表.解析] 内容=`配置` -*> host_toml_parse text=`内容`* +完成后返回*[把 TOML 文本解析成映射/列表/标量](> host_toml_parse text=`内容`)*。 + +## 序列化 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 值 | map | 必填 | 待转换或保存的值;不会就地修改输入 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | text | 序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释。 | + +这里使用`值`。 + +调用效应:pure。 + +序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释。 + +完成后返回*[序列化字典为 TOML,拒绝空值及不支持的数据类型;不保留原注释](> host_toml_stringify value=`值`)*。 + +## 尝试解析 + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| 内容 | text | 必填 | 本操作读取、转换或输出的文本 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | map | 以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本。 | + +这里使用`内容`。 + +调用效应:pure。 + +直接调用此函数: + +```sh +marqdo call lib/配置表.mq.md 尝试解析 '内容="name="Marqdo""' --effects none --json +``` + +以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本。 + +完成后返回*[以结果记录返回 TOML 解析;支持内联表、多行文本、数组表,日期转换为 ISO 文本](> host_toml_try_parse text=`内容`)*。 diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index a652b7d..9f837c8 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -26,7 +26,7 @@ These rules are the **current default**. Do **not** teach Classic `[key](map)` i 4. **Read collections with `access(coll, key)`** (aliases `取` / `取值`). **Never** use `[key](map)` as index under default Occlusion. 5. **Foreach:** `- [描述](遍历 coll 为 item)` (`遍历`/`for`, `为`/`as`/`in`). Prefer explicit traversal when generating new code. 6. **Import / call:** frontmatter `import:` / `导入:`; call `lib.member`. One language (EN or ZH) per file. -7. **Control flow:** `#` object/type, `##`+ function, `+` params, `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. +7. **Control flow:** `#` object/type, `##`+ function, prose params (legacy `+` remains parseable), `1.`/`2.` branches, `-` loops, `N. *` else. No invented `if`/`for`/`def`/`return` keywords. 8. **Prose vs code:** blank line separates comment paragraphs from executable lines. 9. **GFM tables** for data; prefer `table.put` over `json.set` chains. `ext/**` never calls `host_*`. 10. Body narrative `[描述](target)` is lazy (NarrativeRef) — reading does not execute side effects. @@ -48,7 +48,7 @@ Executable-knowledge gate: [`tests/executable_knowledge/`](../../tests/executabl ## Hard rules (do not violate) 1. Obey **CORE SYNTAX** above — Occlusion is default; do not emit Classic index links. -2. **Identifiers:** params `` + `name` ``; inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. +2. **Identifiers:** declare library parameters in prose as `` input `name` `` (defaults follow `=`); inside `*…*` / `**…**` bare ids are variables. Quote text literals. Standalone `>` calls: backticks where bare would be text. 3. **Structure lines** (`#` `>` `+` `-` `|`) are not wrapped in italics. 4. **Paths:** bare `/` in expressions is division; in call args / table cells unspaced `a/b` is path text. Ratios as text need quotes (`"1/5"`). 5. End side-effect-only helpers with `*None*` / `*空*` / `**` / `****` when the outer function continues. Lone `---` is a thematic break, not function end. @@ -136,6 +136,9 @@ Chinese builtins (same functions, no import): ## Frontmatter imports + stdlib +A standard library is normally one `lib/*.mq.md` file: read/import/call that file directly. It is its own manual and skill; no `index.mq.md` or module handbook directory is required. Each function puts parameter/default and return tables directly below its heading, explains purpose, failures and limits, and keeps narrative above 50%. Use prose parameters, not legacy `+` declarations. Describe opaque instructions with `[what it does](actual code)` inside statement/return markers; labels do not execute. Multi-file extensions use an index to organize their files. File tools require explicit `--effects fs.read` or `--effects fs.write` with `--fs-root`; real workflows live in `examples/stdlib-handbook`. Read the [executable authoring guide](../../doc/library-development.mq.md) for inline prose and complete runnable examples. + + Imports use nested YAML `import:` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: ```markdown diff --git a/src/builtin.rs b/src/builtin.rs index e30f07e..0a19c51 100644 --- a/src/builtin.rs +++ b/src/builtin.rs @@ -138,7 +138,7 @@ pub fn builtin_at(value: &Value, index: &Value) -> Result { Value::Int(n) => *n, _ => return Err("at needs int index".into()), }; - if i < 0 || (i as usize) >= xs.len() { + if i < 0 || i >= xs.len() as i64 { return Ok(Value::None); } Ok(xs[i as usize].clone()) diff --git a/src/call.rs b/src/call.rs index 5d3dc19..7704e65 100644 --- a/src/call.rs +++ b/src/call.rs @@ -19,62 +19,94 @@ use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject}; use crate::value::Value; use crate::Backend; -/// Which host side effects `marqdo call` may perform. +/// Explicit effect grants. Writes imply reads; unrelated effects stay denied. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CallEffects { - /// Refuse any non-pure artifact (historical default). - #[default] - None, - /// Allow `plugin.call` (and accompanying `output.write` from load helpers). - Plugin, -} +pub struct CallEffects(u32); impl CallEffects { + #[allow(non_upper_case_globals)] + pub const None: Self = Self(0); + #[allow(non_upper_case_globals)] + pub const Plugin: Self = Self((1 << 2) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 11)); + const NAMES: &'static [&'static str] = &[ + "fs.read", + "fs.write", + "plugin.call", + "network.read", + "network.write", + "process.exec", + "output.write", + "time.read", + "random.read", + "environment.read", + "environment.write", + "process.control", + "user.input", + ]; pub fn parse(s: &str) -> Result { - match s.trim().to_ascii_lowercase().as_str() { - "none" | "" => Ok(Self::None), - "plugin" => Ok(Self::Plugin), - other => Err(call_diag( - None, - 0, - "call.bad_effects", - format!("unknown --effects `{other}` (expected none|plugin)"), - )), + let mut out = Self::None; + for name in s.split(',').map(str::trim) { + match name { + "none" | "" => {} + "plugin" => out.0 |= Self::Plugin.0, + "read" => out.0 |= 1, + "write" => out.0 |= 3, + _ => { + let index = Self::NAMES.iter().position(|v| *v == name) + .ok_or_else(|| call_diag(None, 0, "call.bad_effects", + format!("unknown effect `{name}`; use none, plugin or comma-separated effect names")))?; + out.0 |= 1 << index; + } + } } - } - - pub fn as_str(self) -> &'static str { - match self { - Self::None => "none", - Self::Plugin => "plugin", + if out.0 & (1 << 1) != 0 { + out.0 |= 1; } + if out.0 & (1 << 4) != 0 { + out.0 |= 1 << 3; + } + Ok(out) + } + pub fn as_str(self) -> String { + if self == Self::None { + return "none".into(); + } + if self == Self::Plugin { + return "plugin".into(); + } + Self::NAMES + .iter() + .enumerate() + .filter(|(i, _)| self.0 & (1 << i) != 0) + .map(|(_, name)| *name) + .collect::>() + .join(",") + } + /// File/network/process writes must never be repeated to rebuild a handle. + pub(crate) fn needs_snapshot(self) -> bool { + [ + "fs.write", + "network.write", + "process.exec", + "environment.write", + ] + .iter() + .any(|effect| self.allows(effect)) } - fn host_caps(self) -> HostCaps { - match self { - Self::None => HostCaps { - fs_write: false, - exec: false, - net: false, - plugin: false, - }, - Self::Plugin => HostCaps { - fs_write: false, - exec: false, - net: false, - plugin: true, - }, + HostCaps { + fs_write: self.allows("fs.write"), + exec: self.allows("process.exec"), + net: self.allows("network.read") || self.allows("network.write"), + plugin: self.allows("plugin.call"), } } - fn allows(self, effect: &str) -> bool { - match self { - Self::None => effect == "pure", - Self::Plugin => matches!( - effect, - "pure" | "plugin.call" | "output.write" | "time.read" | "random.read" - ), - } + effect == "pure" + || Self::NAMES + .iter() + .position(|v| *v == effect) + .is_some_and(|i| self.0 & (1 << i) != 0) } } @@ -82,6 +114,7 @@ impl CallEffects { #[derive(Debug, Clone, Default)] pub struct CallOptions { pub effects: CallEffects, + pub fs_root: Option, pub session: Option, pub toget: Option, } @@ -104,19 +137,16 @@ pub fn call_file_with( backend: Backend, opts: CallOptions, ) -> Result { - let path = path - .canonicalize() - .map_err(|e| { - call_diag( - None, - 1, - "call.compile", - format!("failed to read {}: {e}", path.display()), - ) - })?; + let path = path.canonicalize().map_err(|e| { + call_diag( + None, + 1, + "call.compile", + format!("failed to read {}: {e}", path.display()), + ) + })?; - let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) - { + let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) { let id = opts .session .clone() @@ -135,7 +165,14 @@ pub fn call_file_with( // Record uses original arg texts (with $refs) so replay can re-resolve. let record_args = args.to_vec(); - let value = call_file_raw(&path, function, &resolved, opts.effects, backend)?; + let value = call_file_raw_with_root( + &path, + function, + &resolved, + opts.effects, + backend, + opts.fs_root.as_deref(), + )?; if let Some(ref mut sess) = session { crate::call_session::record_step( @@ -144,6 +181,7 @@ pub fn call_file_with( function, &record_args, opts.effects, + opts.fs_root.as_deref(), opts.toget.as_deref(), &value, )?; @@ -160,6 +198,17 @@ pub fn call_file_raw( args: &[(String, Value)], effects: CallEffects, backend: Backend, +) -> Result { + call_file_raw_with_root(path, function, args, effects, backend, None) +} + +pub(crate) fn call_file_raw_with_root( + path: &Path, + function: &str, + args: &[(String, Value)], + effects: CallEffects, + backend: Backend, + fs_root: Option<&Path>, ) -> Result { let path = if path.is_absolute() { path.to_path_buf() @@ -176,7 +225,7 @@ pub fn call_file_raw( let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?; let artifact = locate_artifact(&compilation.semantics, &path, function)?; deny_unsafe(&path, artifact, effects)?; - execute_source_function( + execute_source_function_with_root( &path, artifact.source.line, &artifact.display_name, @@ -184,14 +233,14 @@ pub fn call_file_raw( effects.host_caps(), backend, true, + fs_root, ) .map(|(value, _stdout)| value) } fn args_need_session(args: &[(String, Value)]) -> bool { - args.iter().any(|(_, v)| { - matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) - }) + args.iter() + .any(|(_, v)| matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@'))) } /// Run the function declared at `line` in `path`. @@ -203,6 +252,28 @@ pub(crate) fn execute_source_function( caps: HostCaps, backend: Backend, strict_args: bool, +) -> Result<(Value, String)> { + execute_source_function_with_root( + path, + line, + display_name, + args, + caps, + backend, + strict_args, + None, + ) +} + +fn execute_source_function_with_root( + path: &Path, + line: u32, + display_name: &str, + args: &[(String, Value)], + caps: HostCaps, + backend: Backend, + strict_args: bool, + fs_root: Option<&Path>, ) -> Result<(Value, String)> { let module = load_module(path)?; let fun = find_function_at_line(&module.functions, line).ok_or_else(|| { @@ -225,8 +296,16 @@ pub(crate) fn execute_source_function( ), )); } - let mut interp = Interpreter::with_capture(Some(path), false) - .with_host(HostContext::for_capture(Some(path), caps)); + let mut host = HostContext::for_capture(Some(path), caps); + if let Some(root) = fs_root { + let root = root.canonicalize()?; + if !root.is_dir() { + anyhow::bail!("call.fs_root: root must be a directory"); + } + host.cwd = root.clone(); + host.fs_root = Some(root); + } + let mut interp = Interpreter::with_capture(Some(path), false).with_host(host); let bound; let invoke_args: &[(String, Value)] = if strict_args { bound = interp.bind_external_args(&module, fun, args)?; @@ -258,8 +337,13 @@ pub(crate) fn execute_source_function( format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"), ) })?; - let mut vm = - Vm::with_capture(Some(path)).with_host(HostContext::for_capture(Some(path), caps)); + let mut host = HostContext::for_capture(Some(path), caps); + if let Some(root) = fs_root { + let root = root.canonicalize()?; + host.cwd = root.clone(); + host.fs_root = Some(root); + } + let mut vm = Vm::with_capture(Some(path)).with_host(host); let value = vm.call_function(&program, idx, invoke_args)?; Ok((value, vm.captured_stdout)) } @@ -308,7 +392,12 @@ pub fn parse_call_args(tokens: &[String]) -> Result> { )); } let value = parse_literal(raw).map_err(|message| { - call_diag(None, 0, "call.bad_value", format!("参数 `{name}`: {message}")) + call_diag( + None, + 0, + "call.bad_value", + format!("参数 `{name}`: {message}"), + ) })?; out.push((name.to_string(), value)); } @@ -356,8 +445,7 @@ fn locate_artifact<'a>( .copied() .filter(|artifact| { artifact.kind == "function" - && (artifact.display_name.ends_with(&suffix) - || artifact.display_name == query) + && (artifact.display_name.ends_with(&suffix) || artifact.display_name == query) }) .collect() }; diff --git a/src/call_session.rs b/src/call_session.rs index 7e0f193..fd060e4 100644 --- a/src/call_session.rs +++ b/src/call_session.rs @@ -35,6 +35,10 @@ pub struct CallStep { pub function: String, pub args: BTreeMap, pub effects: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fs_root: Option, #[serde(skip_serializing_if = "Option::is_none")] pub toget: Option, } @@ -97,18 +101,22 @@ pub fn resolve_args( live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?); } let needs_replay = args.iter().any(|(_, v)| { - matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) - && { - let name = v_text_ref(v); - session.journal_bindings.contains_key(name) - || (!session.bindings.contains_key(name) - && session.steps.iter().any(|s| s.toget.as_deref() == Some(name))) - } + matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) && { + let name = v_text_ref(v); + session.journal_bindings.contains_key(name) + || (!session.bindings.contains_key(name) + && session + .steps + .iter() + .any(|s| s.toget.as_deref() == Some(name))) + } }); - if needs_replay || args.iter().any(|(_, v)| { - matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@')) + if needs_replay + || args.iter().any(|(_, v)| { + matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@')) && session.journal_bindings.contains_key(&t[1..])) - }) { + }) + { live = replay_live(session, backend)?; } let mut out = Vec::with_capacity(args.len()); @@ -150,9 +158,12 @@ fn resolve_one( } // Last resort: full replay let live = replay_live(session, backend)?; - live.get(key) - .cloned() - .ok_or_else(|| anyhow::anyhow!("call.session_unbound: `${key}` not in session {}", session.session)) + live.get(key).cloned().ok_or_else(|| { + anyhow::anyhow!( + "call.session_unbound: `${key}` not in session {}", + session.session + ) + }) } fn replay_live(session: &CallSession, backend: Backend) -> Result> { @@ -179,13 +190,20 @@ fn replay_live(session: &CallSession, backend: Backend) -> Result, toget: Option<&str>, result: &Value, ) -> Result<()> { @@ -229,7 +248,13 @@ pub fn record_step( file: file_s, function: function.to_string(), args: arg_map, - effects: effects.as_str().to_string(), + effects: effects.as_str(), + result: if is_json_friendly(result) { + value_to_json(result).ok() + } else { + None + }, + fs_root: fs_root.map(|p| p.canonicalize()).transpose()?, toget: toget.map(|s| s.to_string()), }; session.steps.push(step); @@ -267,7 +292,8 @@ fn is_json_friendly(v: &Value) -> bool { /// Dump journal steps as a minimal Marqdo script for later `marqdo run`. pub fn dump_replay_script(session: &CallSession) -> String { - let mut out = String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n"); + let mut out = + String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n"); for (i, step) in session.steps.iter().enumerate() { out.push_str(&format!( "> print text=\"step {i}: call {} {} effects={}\"\n", @@ -284,3 +310,46 @@ pub fn dump_replay_script(session: &CallSession) -> String { pub fn default_session_id() -> String { std::env::var("MARQDO_CALL_SESSION").unwrap_or_else(|_| "default".into()) } + +#[cfg(test)] +mod write_snapshot_tests { + use super::*; + #[test] + fn replay_uses_durable_write_results_instead_of_repeating_io() { + let dir = std::env::temp_dir().join(format!("mq-write-replay-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("log.txt"), "once").unwrap(); + for backend in [Backend::Tree, Backend::Bytecode] { + let step = CallStep { + file: Path::new(env!("CARGO_MANIFEST_DIR")) + .join("lib/fs.mq.md") + .to_string_lossy() + .into(), + function: "append_text".into(), + args: BTreeMap::from([ + ("path".into(), serde_json::json!("log.txt")), + ("text".into(), serde_json::json!("once")), + ]), + effects: "fs.write".into(), + result: Some(serde_json::Value::Null), + fs_root: Some(dir.clone()), + toget: Some("written".into()), + }; + let mut session = CallSession { + steps: vec![step], + ..Default::default() + }; + assert_eq!( + replay_live(&session, backend).unwrap()["written"], + Value::None + ); + assert_eq!(fs::read_to_string(dir.join("log.txt")).unwrap(), "once"); + session.steps[0].result = None; + assert!(replay_live(&session, backend) + .unwrap_err() + .to_string() + .contains("refusing to repeat")); + } + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/ext_cli.rs b/src/ext_cli.rs index b62577c..e15f6ad 100644 --- a/src/ext_cli.rs +++ b/src/ext_cli.rs @@ -22,6 +22,9 @@ pub const CATALOG: &[ExtPackage] = &[ id: "llm", description: "OpenAI-compatible chat object (ext/ai/llm)", mq_files: &[ + "ai/index.mq.md", + "ai/索引.mq.md", + "ai/llm/index.mq.md", "ai/llm.mq.md", "ai/大模型.mq.md", "ai/llm/openai.mq.md", @@ -32,13 +35,32 @@ pub const CATALOG: &[ExtPackage] = &[ ExtPackage { id: "agent", description: "Agent development framework (ext/ai/agent)", - mq_files: &["ai/agent.mq.md", "ai/智能体.mq.md"], + mq_files: &[ + "ai/agent.mq.md", + "ai/智能体.mq.md", + "ai/sandbox.mq.md", + "ai/沙盒.mq.md", + "ai/policies/step-route.mq.md", + ], native_crate: Some("marqdo_plugin_agent"), }, ExtPackage { id: "web", description: "Dynamic website toolkit (ext/web) — Document/Endpoint + layout skill", mq_files: &[ + "data/index.mq.md", + "data/cache.mq.md", + "data/db.mq.md", + "data/form.mq.md", + "data/storage.mq.md", + "security/index.mq.md", + "security/auth.mq.md", + "security/rbac.mq.md", + "security/oidc.mq.md", + "net/index.mq.md", + "net/http.mq.md", + "net/url.mq.md", + "net/websocket.mq.md", "web/index.mq.md", "web/web.mq.md", "web/网页.mq.md", @@ -86,7 +108,12 @@ pub const CATALOG: &[ExtPackage] = &[ ExtPackage { id: "linalg", description: "Formula-first linear algebra (ext/linalg) — MatExpr simplify/display", - mq_files: &["linalg/linalg.mq.md", "linalg/线性代数.mq.md"], + mq_files: &[ + "linalg/index.mq.md", + "linalg/索引.mq.md", + "linalg/linalg.mq.md", + "linalg/线性代数.mq.md", + ], native_crate: Some("marqdo_plugin_linalg"), }, ]; diff --git a/src/host/archive.rs b/src/host/archive.rs new file mode 100644 index 0000000..2a224e4 --- /dev/null +++ b/src/host/archive.rs @@ -0,0 +1,199 @@ +//! Optional ZIP tasks with preflight, expansion limits and no path traversal. +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use std::collections::HashMap; +#[cfg(feature = "net-host")] +use std::{ + collections::HashSet, + fs, + io::{Read, Write}, + path::Path, +}; +type Args = HashMap; +#[cfg(feature = "net-host")] +fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + #[cfg(feature = "net-host")] + let answer = operate(ctx, id, b); + #[cfg(not(feature = "net-host"))] + let answer = { + let _ = (ctx, id, b); + Err("ZIP unavailable: build with net-host (native default)".into()) + }; + Ok(super::result::capture( + if id == HostFn::ZipPack { + "archive.pack" + } else { + "archive.unpack" + }, + answer, + )) +} +#[cfg(feature = "net-host")] +fn operate(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + if !ctx.allow_fs_write() { + return Err("filesystem write denied by host policy".into()); + } + if ctx.sandbox_session.is_some() { + return Err("ZIP unavailable in CoW sandbox".into()); + } + let src = ctx.resolve_path(super::as_text(arg(b, "src")?, "src")?)?; + let dest = ctx.resolve_path(super::as_text(arg(b, "dest")?, "dest")?)?; + let max = match arg(b, "max_bytes")? { + Value::Int(n) if *n > 0 && *n <= 1024 * 1024 * 1024 => *n as u64, + _ => return Err("max_bytes must be 1..1073741824".into()), + }; + if dest.exists() { + return Err("destination conflict: ZIP output must not exist".into()); + } + if id == HostFn::ZipPack { + if !src.is_dir() || dest.starts_with(&src) { + return Err("pack src must be directory and dest outside src".into()); + } + let mut args = HashMap::new(); + args.insert("path".into(), Value::Text(src.to_string_lossy().into())); + args.insert("pattern".into(), Value::Text("**".into())); + args.insert("exclude".into(), Value::None); + args.insert("max_depth".into(), Value::Int(256)); + args.insert("kind".into(), Value::Text("file".into())); + let Value::List(files) = super::fs_ops::call(ctx, HostFn::FsFind, &args)? else { + unreachable!() + }; + let total = files.iter().try_fold(0u64, |n, name| { + let p = src.join(super::as_text(name, "name")?); + let size = fs::metadata(p).map_err(|e| e.to_string())?.len(); + n.checked_add(size) + .ok_or_else(|| "archive size overflow".to_string()) + })?; + if total > max { + return Err("archive source exceeds max_bytes".into()); + } + let parent = dest.parent().ok_or("archive needs parent")?; + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let temp = parent.join(format!(".mq-zip-{}", random_name()?)); + let file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp) + .map_err(|e| e.to_string())?; + let written = (|| { + let mut writer = zip::ZipWriter::new(file); + let mut buffer = [0u8; 65536]; + let mut seen = 0u64; + for name in &files { + let name = super::as_text(name, "name")?; + writer + .start_file( + name, + zip::write::FileOptions::default() + .compression_method(zip::CompressionMethod::Deflated), + ) + .map_err(|e| e.to_string())?; + let p = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?; + let mut file = fs::File::open(p).map_err(|e| e.to_string())?; + loop { + let n = file.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + seen += n as u64; + if seen > max { + return Err("archive source grew past max_bytes".into()); + } + writer.write_all(&buffer[..n]).map_err(|e| e.to_string())?; + } + } + writer + .finish() + .map_err(|e| e.to_string())? + .sync_all() + .map_err(|e| e.to_string())?; + // hard_link is an atomic no-clobber publish on the same filesystem. + fs::hard_link(&temp, &dest).map_err(|e| e.to_string())?; + Ok(Value::Int(files.len() as i64)) + })(); + let _ = fs::remove_file(&temp); + return written; + } + let file = fs::File::open(src).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; + if zip.len() > 100000 { + return Err("archive exceeds 100000 entries".into()); + } + let mut names = HashSet::new(); + let mut total = 0u64; + for i in 0..zip.len() { + let entry = zip.by_index(i).map_err(|e| e.to_string())?; + let name = entry + .enclosed_name() + .ok_or("archive path escapes destination")?; + if entry.name().contains('\\') || name == Path::new("") || !names.insert(name.to_path_buf()) + { + return Err("invalid or duplicate archive path".into()); + } + if entry + .unix_mode() + .is_some_and(|mode| mode & 0o170000 == 0o120000) + { + return Err("archive symlinks unsupported".into()); + } + total = total + .checked_add(entry.size()) + .ok_or("archive size overflow")?; + if total > max { + return Err("archive expansion exceeds max_bytes".into()); + } + } + fs::create_dir_all(dest.parent().ok_or("destination needs parent")?) + .map_err(|e| e.to_string())?; + fs::create_dir(&dest).map_err(|e| e.to_string())?; + let extracted = (|| { + let mut total = 0u64; + let mut buffer = [0u8; 65536]; + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + let path = ctx.resolve_path( + dest.join(entry.enclosed_name().ok_or("invalid archive path")?) + .to_str() + .ok_or("non UTF-8 path")?, + )?; + if entry.is_dir() { + fs::create_dir_all(path).map_err(|e| e.to_string())?; + continue; + } + fs::create_dir_all(path.parent().ok_or("entry needs parent")?) + .map_err(|e| e.to_string())?; + let mut file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(path) + .map_err(|e| e.to_string())?; + loop { + let n = entry.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + total += n as u64; + if total > max { + return Err("archive expansion exceeds max_bytes".into()); + } + file.write_all(&buffer[..n]).map_err(|e| e.to_string())?; + } + } + Ok(Value::Int(zip.len() as i64)) + })(); + if extracted.is_err() { + let _ = fs::remove_dir_all(&dest); + } + extracted +} +#[cfg(feature = "net-host")] +fn random_name() -> Result { + let mut bytes = [0u8; 16]; + getrandom::getrandom(&mut bytes).map_err(|e| e.to_string())?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} diff --git a/src/host/collection.rs b/src/host/collection.rs index 360bb93..9f02c89 100644 --- a/src/host/collection.rs +++ b/src/host/collection.rs @@ -16,7 +16,7 @@ fn path_segments(at: &Value) -> Result, String> { if *n < 1 { return Err("put path index must be >= 1 (1-based)".into()); } - Ok(vec![PathSeg::Index1(*n as usize)]) + Ok(vec![PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)]) } Value::List(xs) => { if xs.is_empty() { @@ -32,7 +32,7 @@ fn path_segments(at: &Value) -> Result, String> { "put path segment {i}: index must be >= 1 (1-based)" )); } - out.push(PathSeg::Index1(*n as usize)); + out.push(PathSeg::Index1(usize::try_from(*n).map_err(|_| "put path index exceeds target size")?)); } _ => { return Err(format!( @@ -284,7 +284,7 @@ pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result vec![], _ => return Err("list_insert needs list".into()), }; - if index < 0 || index as usize > xs.len() { + if index < 0 || index > xs.len() as i64 { return Err(format!( "list_insert index {index} out of range (len {})", xs.len() @@ -298,7 +298,7 @@ pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result= xs.len() { + if index < 0 || index >= xs.len() as i64 { return Err(format!( "list_set_at index {index} out of range (len {})", xs.len() @@ -313,7 +313,7 @@ pub fn list_remove_at(list: &Value, index: i64) -> Result { let Value::List(xs) = list else { return Err("list_remove_at needs list".into()); }; - if index < 0 || index as usize >= xs.len() { + if index < 0 || index >= xs.len() as i64 { return Err(format!( "list_remove_at index {index} out of range (len {})", xs.len() @@ -385,16 +385,33 @@ pub fn list_last(list: &Value) -> Result { } } -fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering { +/// Total type order avoids cyclic comparisons between numeric and text keys. +pub(super) fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering { use std::cmp::Ordering; - match (a, b) { - (Value::Int(x), Value::Int(y)) => x.cmp(y), - (Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal), - (Value::Int(x), Value::Num(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal), - (Value::Num(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal), - (Value::Text(x), Value::Text(y)) => x.cmp(y), - (Value::Bool(x), Value::Bool(y)) => x.cmp(y), - _ => a.as_display().cmp(&b.as_display()), + fn rank(v:&Value)->u8{match v{ + Value::Int(_)|Value::Num(_)=>0,Value::Text(_)=>1,Value::Bool(_)=>2, + Value::None=>3,Value::List(_)=>4,Value::Map(_)=>5,Value::Formula(_)=>6, + Value::Code(_)=>7,Value::Secret(_)=>8,Value::Handle(_)=>9, + }} + fn int_float(integer:i64,number:f64)->Ordering{ + if number.is_nan(){return Ordering::Less} + if number >= -(i64::MIN as f64){return Ordering::Less} + if number < i64::MIN as f64{return Ordering::Greater} + let truncated=number as i64; + match integer.cmp(&truncated){Ordering::Equal=>0.0f64.partial_cmp(&number.fract()).unwrap_or(Ordering::Equal),other=>other} + } + let order=rank(a).cmp(&rank(b));if !order.is_eq(){return order} + match (a,b){ + (Value::Int(a),Value::Int(b))=>a.cmp(b), + (Value::Num(a),Value::Num(b))=>match(a.is_nan(),b.is_nan()){ + (true,false)=>Ordering::Greater,(false,true)=>Ordering::Less, + _=>a.partial_cmp(b).unwrap_or_else(||a.total_cmp(b)), + }, + (Value::Int(a),Value::Num(b))=>int_float(*a,*b), + (Value::Num(a),Value::Int(b))=>int_float(*b,*a).reverse(), + (Value::Text(a),Value::Text(b))=>a.cmp(b), + (Value::Bool(a),Value::Bool(b))=>a.cmp(b), + _=>a.as_display().cmp(&b.as_display()), } } @@ -447,9 +464,12 @@ pub fn list_sort_by(list: &Value, key: &Value) -> Result { pub fn list_unique(list: &Value) -> Result { match list { Value::List(xs) => { - let mut out = Vec::new(); + let mut out: Vec = Vec::new(); + let mut seen: std::collections::HashMap> = std::collections::HashMap::new(); for x in xs { - if !out.iter().any(|y| y == x) { + let bucket = seen.entry(super::collection_ops::fingerprint(x)).or_default(); + if !bucket.iter().any(|i| out[*i] == *x) { + bucket.push(out.len()); out.push(x.clone()); } } @@ -462,7 +482,7 @@ pub fn list_unique(list: &Value) -> Result { pub fn list_chunk(list: &Value, size: &Value) -> Result { let n = match size { - Value::Int(i) if *i > 0 => *i as usize, + Value::Int(i) if *i > 0 => usize::try_from(*i).unwrap_or(usize::MAX), Value::Int(_) => return Err("chunk size must be positive".into()), _ => return Err("chunk size needs int".into()), }; @@ -570,3 +590,27 @@ mod tests { assert!(matches!(m, Value::Map(_))); } } + +#[cfg(test)] +mod task_scale_tests { + use super::*; + #[test] + fn unique_preserves_signed_zero_nan_and_nested_equality(){ + let xs=Value::List(vec![Value::Num(-0.0),Value::Num(0.0),Value::Num(f64::NAN),Value::Num(f64::NAN),Value::Int(0),Value::List(vec![Value::Num(-0.0)]),Value::List(vec![Value::Num(0.0)])]); + let Value::List(out)=list_unique(&xs).unwrap()else{panic!()}; + assert_eq!(out.len(),5);assert_eq!(out[0],Value::Num(-0.0));assert_eq!(out[3],Value::Int(0)); + } + #[test] + fn mixed_order_is_transitive_and_exact_at_integer_float_boundary(){ + let values=[Value::Int(2),Value::Int(10),Value::Text("11".into()),Value::Int(i64::MAX),Value::Num(i64::MAX as f64),Value::Num(f64::NAN),Value::Num(-0.0),Value::Bool(false),Value::None]; + for a in &values{for b in &values{for c in &values{ + if cmp_value(a,b).is_le()&&cmp_value(b,c).is_le(){assert!(cmp_value(a,c).is_le(),"{a:?} {b:?} {c:?}");} + }}} + assert!(cmp_value(&Value::Int(i64::MAX),&Value::Num(i64::MAX as f64)).is_lt()); + } + #[test] + fn bulk_unique_handles_one_hundred_thousand_values(){ + let xs=Value::List((0..100_000).map(|n|Value::Int(n%50_000)).collect()); + let Value::List(out)=list_unique(&xs).unwrap()else{panic!()};assert_eq!(out.len(),50_000); + } +} diff --git a/src/host/collection_ops.rs b/src/host/collection_ops.rs new file mode 100644 index 0000000..1f7ad9d --- /dev/null +++ b/src/host/collection_ops.rs @@ -0,0 +1,584 @@ +//! Field-driven collection transforms. No string evaluation or callback language. +use super::{as_text, collection::cmp_value}; +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use std::collections::{HashMap, HashSet}; + +type Args = HashMap; +fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { + as_text(arg(b, k)?, k) +} +fn list(v: &Value) -> Result<&[Value], String> { + match v { + Value::List(xs) => Ok(xs), + _ => Err("expected list".into()), + } +} +fn record(v: &Value) -> Result<&[(String, Value)], String> { + match v { + Value::Map(m) => Ok(m), + _ => Err("expected record map".into()), + } +} +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> { + record(v)? + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v) + .ok_or_else(|| format!("missing field {key}")) +} +fn strings(v: &Value) -> Result, String> { + list(v)? + .iter() + .map(|v| as_text(v, "key").map(str::to_owned)) + .collect() +} +fn integer(v: &Value) -> Result { + match v { + Value::Int(n) => Ok(*n), + _ => Err("expected integer".into()), + } +} +fn number(v: &Value) -> Result { + match v { + Value::Int(n) => Ok(*n as f64), + Value::Num(n) if n.is_finite() => Ok(*n), + _ => Err("expected finite number".into()), + } +} +fn row(fields: Vec<(&str, Value)>) -> Value { + Value::Map(fields.into_iter().map(|(k, v)| (k.into(), v)).collect()) +} +// Structural equality is type-sensitive and map-order-sensitive, like Value::eq. +// Fingerprints accelerate buckets; equality is still checked inside each bucket. +pub(super) fn fingerprint(v: &Value) -> String { + match v { + Value::Num(n) if *n == 0.0 => "Num(0)".into(), + Value::List(xs) => format!("List{:?}", xs.iter().map(fingerprint).collect::>()), + Value::Map(xs) => format!( + "Map{:?}", + xs.iter() + .map(|(k, v)| (k, fingerprint(v))) + .collect::>() + ), + Value::Formula(formula) => format!("Formula{}", formula.as_display()), + _ => format!("{v:?}"), + } +} + +pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + match id { + HostFn::ListRange => { + let start = integer(arg(b, "start")?)?; + let end = integer(arg(b, "end")?)?; + let step = integer(arg(b, "step")?)?; + if step == 0 { + return Err("range step cannot be zero".into()); + } + let mut out = Vec::new(); + let mut n = start; + while if step > 0 { n < end } else { n > end } { + if out.len() >= 1_000_000 { + return Err("range exceeds 1000000 items".into()); + } + out.push(Value::Int(n)); + match n.checked_add(step) { + Some(next) => n = next, + None => break, + } + } + Ok(Value::List(out)) + } + HostFn::ListEnumerate => { + let start = integer(arg(b, "start")?)?; + let out = list(arg(b, "list")?)? + .iter() + .enumerate() + .map(|(i, v)| { + let index = start + .checked_add(i as i64) + .ok_or("enumerate index overflow")?; + Ok(row(vec![ + ("index", Value::Int(index)), + ("value", v.clone()), + ])) + }) + .collect::, String>>()?; + Ok(Value::List(out)) + } + HostFn::ListPluck => { + let key = text(b, "key")?; + Ok(Value::List( + list(arg(b, "list")?)? + .iter() + .map(|v| field(v, key).cloned()) + .collect::>()?, + )) + } + HostFn::ListProject => { + let keys = strings(arg(b, "keys")?)?; + if keys.iter().collect::>().len() != keys.len() { + return Err("project keys must be unique".into()); + } + let out = list(arg(b, "list")?)? + .iter() + .map(|v| { + keys.iter() + .map(|k| Ok((k.clone(), field(v, k)?.clone()))) + .collect::, String>>() + .map(Value::Map) + }) + .collect::>()?; + Ok(Value::List(out)) + } + HostFn::ListWhere => { + let key = text(b, "key")?; + let op = text(b, "op")?; + let wanted = arg(b, "value")?; + if !matches!( + op, + "eq" | "ne" | "gt" | "ge" | "lt" | "le" | "contains" | "in" + ) { + return Err(format!("unknown where operator {op}")); + } + let mut out = Vec::new(); + for v in list(arg(b, "list")?)? { + let got = field(v, key)?; + let yes = match op { + "eq" => got == wanted, + "ne" => got != wanted, + "gt" | "ge" | "lt" | "le" => { + let order = match (got, wanted) { + (Value::Text(a), Value::Text(b)) => a.cmp(b), + _ => number(got)? + .partial_cmp(&number(wanted)?) + .ok_or("unordered comparison")?, + }; + match op { + "gt" => order.is_gt(), + "ge" => order.is_ge(), + "lt" => order.is_lt(), + _ => order.is_le(), + } + } + "contains" => match got { + Value::List(xs) => xs.contains(wanted), + Value::Text(s) => s.contains(as_text(wanted, "value")?), + _ => return Err("contains needs text or list".into()), + }, + "in" => list(wanted)?.contains(got), + _ => return Err(format!("unknown where operator {op}")), + }; + if yes { + out.push(v.clone()) + } + } + Ok(Value::List(out)) + } + HostFn::ListGroupBy | HostFn::ListUniqueBy => { + let key = text(b, "key")?; + let mut groups: Vec<(Value, Vec)> = Vec::new(); + let mut index: HashMap> = HashMap::new(); + for v in list(arg(b, "list")?)? { + let k = field(v, key)?; + let fp = fingerprint(k); + let bucket = index.entry(fp).or_default(); + if let Some(i) = bucket.iter().find(|i| groups[**i].0 == *k) { + groups[*i].1.push(v.clone()); + } else { + bucket.push(groups.len()); + groups.push((k.clone(), vec![v.clone()])); + } + } + Ok(Value::List( + groups + .into_iter() + .map(|(key, rows)| { + if id == HostFn::ListUniqueBy { + rows.into_iter().next().unwrap() + } else { + row(vec![ + ("key", key), + ("count", Value::Int(rows.len() as i64)), + ("rows", Value::List(rows)), + ]) + } + }) + .collect(), + )) + } + HostFn::ListAggregate => { + let xs = list(arg(b, "list")?)?; + let op = text(b, "op")?; + if op == "count" { + return Ok(Value::Int(xs.len() as i64)); + } + let key = arg(b, "key")?; + let values = xs + .iter() + .map(|v| { + if matches!(key, Value::None) { + Ok(v) + } else { + field(v, as_text(key, "key")?) + } + }) + .collect::, String>>()?; + if op == "sum" && values.iter().all(|v| matches!(v, Value::Int(_))) { + let sum = values.into_iter().try_fold(0i64, |sum, v| { + sum.checked_add(integer(v)?) + .ok_or_else(|| "sum integer overflow".to_string()) + })?; + return Ok(Value::Int(sum)); + } + let nums = values + .into_iter() + .map(number) + .collect::, _>>()?; + let n = match op { + "sum" => nums.iter().sum(), + "mean" if !nums.is_empty() => nums.iter().sum::() / nums.len() as f64, + "min" if !nums.is_empty() => nums.iter().copied().fold(f64::INFINITY, f64::min), + "max" if !nums.is_empty() => nums.iter().copied().fold(f64::NEG_INFINITY, f64::max), + _ => { + return Err( + "aggregate needs sum/count/min/max/mean; empty min/max/mean is invalid" + .into(), + ) + } + }; + if !n.is_finite() { + return Err("aggregate overflow".into()); + } + Ok(Value::Num(n)) + } + HostFn::ListSortKeys => { + let keys = strings(arg(b, "keys")?)?; + let descending = matches!(arg(b, "descending")?, Value::Bool(true)); + let mut xs = list(arg(b, "list")?)?.to_vec(); + for v in &xs { + for k in &keys { + field(v, k)?; + } + } + xs.sort_by(|a, b| { + let mut order = std::cmp::Ordering::Equal; + for k in &keys { + order = cmp_value(field(a, k).unwrap(), field(b, k).unwrap()); + if !order.is_eq() { + break; + } + } + if descending { + order.reverse() + } else { + order + } + }); + Ok(Value::List(xs)) + } + HostFn::ListRename => { + let names = record(arg(b, "fields")?)?; + for (_, v) in names { + as_text(v, "new field name")?; + } + let mut out = Vec::new(); + for v in list(arg(b, "list")?)? { + let mut seen = HashSet::new(); + let mut fields = Vec::new(); + for (k, v) in record(v)? { + let name = names + .iter() + .find(|(old, _)| old == k) + .map(|(_, v)| as_text(v, "name").unwrap()) + .unwrap_or(k); + if !seen.insert(name) { + return Err(format!("rename conflict: {name}")); + } + fields.push((name.into(), v.clone())); + } + out.push(Value::Map(fields)); + } + Ok(Value::List(out)) + } + HostFn::TableFromColumns => { + let columns = record(arg(b, "columns")?)?; + let n = columns + .first() + .map(|(_, v)| list(v).map(|xs| xs.len())) + .transpose()? + .unwrap_or(0); + for (_, v) in columns { + if list(v)?.len() != n { + return Err("column lengths differ".into()); + } + } + Ok(Value::List( + (0..n) + .map(|i| { + Value::Map( + columns + .iter() + .map(|(k, v)| (k.clone(), list(v).unwrap()[i].clone())) + .collect(), + ) + }) + .collect(), + )) + } + HostFn::TableToColumns => { + let rows = list(arg(b, "rows")?)?; + if rows.is_empty() { + return Ok(Value::Map(vec![])); + } + let keys: Vec<_> = record(&rows[0])?.iter().map(|(k, _)| k.clone()).collect(); + for v in rows { + let fields = record(v)?; + if fields.len() != keys.len() + || keys.iter().any(|k| !fields.iter().any(|(f, _)| f == k)) + { + return Err("rows have different fields".into()); + } + } + Ok(Value::Map( + keys.into_iter() + .map(|k| { + let values = rows.iter().map(|v| field(v, &k).unwrap().clone()).collect(); + (k, Value::List(values)) + }) + .collect(), + )) + } + HostFn::ListJoin => { + let a = list(arg(b, "a")?)?; + let b_rows = list(arg(b, "b")?)?; + let key = text(b, "key")?; + let right_key = text(b, "right_key")?; + let mode = text(b, "mode")?; + if !matches!(mode, "inner" | "left") { + return Err("join mode must be inner or left".into()); + } + let mut index: HashMap> = HashMap::new(); + for v in b_rows { + index + .entry(fingerprint(field(v, right_key)?)) + .or_default() + .push(v); + } + let right_fields: Vec<_> = b_rows + .first() + .map(|v| record(v).map(|m| m.iter().map(|(k, _)| k.clone()).collect())) + .transpose()? + .unwrap_or_default(); + for right in b_rows { + let fields = record(right)?; + if fields.len() != right_fields.len() + || right_fields + .iter() + .any(|key| !fields.iter().any(|(k, _)| k == key)) + { + return Err("join right rows have different fields".into()); + } + } + let mut out = Vec::new(); + for left in a { + let left_key = field(left, key)?; + let hits = index.get(&fingerprint(left_key)); + let matches: Vec> = match hits { + Some(h) => { + let values: Vec<_> = h + .iter() + .filter(|v| field(v, right_key).is_ok_and(|key| key == left_key)) + .map(|v| Some(*v)) + .collect(); + if values.is_empty() && mode == "left" { + vec![None] + } else { + values + } + } + None if mode == "left" => vec![None], + _ => vec![], + }; + for hit in matches { + let mut fields = record(left)?.to_vec(); + let source = hit.map(record).transpose()?; + for k in &right_fields { + if k == right_key && key == right_key { + continue; + } + let name = if fields.iter().any(|(f, _)| f == k) { + format!("right_{k}") + } else { + k.clone() + }; + if fields.iter().any(|(f, _)| f == &name) { + return Err(format!("join field conflict: {name}")); + } + let value = source + .and_then(|m| m.iter().find(|(f, _)| f == k)) + .map(|(_, v)| v.clone()) + .unwrap_or(Value::None); + fields.push((name, value)); + } + if out.len() >= 1_000_000 { + return Err("join exceeds 1000000 rows".into()); + } + out.push(Value::Map(fields)); + } + } + Ok(Value::List(out)) + } + HostFn::TableCast => { + let schema = record(arg(b, "schema")?)?; + let mut out = Vec::new(); + for (i, v) in list(arg(b, "rows")?)?.iter().enumerate() { + let mut fields = record(v)?.to_vec(); + for (k, ty) in schema { + let value = field(v, k)?; + let ty = as_text(ty, "type")?; + let cast = cast(value, ty).map_err(|e| format!("row {i} field {k}: {e}"))?; + fields.iter_mut().find(|(name, _)| name == k).unwrap().1 = cast; + } + out.push(Value::Map(fields)); + } + Ok(Value::List(out)) + } + HostFn::TableSummarize => { + let groups = call(_ctx, HostFn::ListGroupBy, b)?; + let field_name = text(b, "field")?; + let op = text(b, "op")?; + let mut out = Vec::new(); + for group in list(&groups)? { + let rows = field(group, "rows")?; + let mut args = HashMap::new(); + args.insert("list".into(), rows.clone()); + args.insert("key".into(), Value::Text(field_name.into())); + args.insert("op".into(), Value::Text(op.into())); + let value = call(_ctx, HostFn::ListAggregate, &args)?; + out.push(row(vec![ + ("key", field(group, "key")?.clone()), + ("count", field(group, "count")?.clone()), + ("value", value), + ])); + } + Ok(Value::List(out)) + } + HostFn::TableTryCast => { + let answer = + call(_ctx, HostFn::TableCast, b).map_err(|e| format!("validation_failed: {e}")); + Ok(super::result::capture("table.cast", answer)) + } + HostFn::TableValidate => { + let rows = list(arg(b, "rows")?)?; + let schema = record(arg(b, "schema")?)?; + let mut errors = Vec::new(); + for (index, value) in rows.iter().enumerate() { + let fields = record(value)?; + for (key, ty) in schema { + let name = as_text(ty, "type")?; + let ty = crate::contract::Ty::parse(name); + let got = fields.iter().find(|(k, _)| k == key).map(|(_, v)| v); + if !got.is_some_and(|v| ty.matches_value(v)) { + errors.push(row(vec![ + ("row", Value::Int(index as i64)), + ("field", Value::Text(key.clone())), + ("expected", Value::Text(name.into())), + ( + "actual", + Value::Text( + got.map(crate::contract::type_of) + .unwrap_or("missing") + .into(), + ), + ), + ])); + } + } + } + if errors.is_empty() { + Ok(super::result::capture( + "table.validate", + Ok(arg(b, "rows")?.clone()), + )) + } else { + let mut result = super::result::capture( + "table.validate", + Err("validation_failed: records do not match schema".into()), + ); + if let Value::Map(fields) = &mut result { + if let Some((_, Value::Map(error))) = + fields.iter_mut().find(|(k, _)| k == "error") + { + error.push(("details".into(), Value::List(errors))); + } + } + Ok(result) + } + } + HostFn::ListUnion | HostFn::ListIntersection | HostFn::ListDifference => { + let left = list(arg(b, "a")?)?; + let right = list(arg(b, "b")?)?; + let mut index: HashMap> = HashMap::new(); + for v in right { + index.entry(fingerprint(v)).or_default().push(v) + } + let mut values = Vec::new(); + for v in left { + let contains = index + .get(&fingerprint(v)) + .is_some_and(|bucket| bucket.iter().any(|r| *r == v)); + if id == HostFn::ListUnion + || (id == HostFn::ListIntersection && contains) + || (id == HostFn::ListDifference && !contains) + { + values.push(v.clone()) + } + } + if id == HostFn::ListUnion { + values.extend_from_slice(right) + } + super::collection::list_unique(&Value::List(values)) + } + _ => Err("not a collection transform".into()), + } +} +fn cast(v: &Value, ty: &str) -> Result { + match ty { + "text" => Ok(Value::Text(v.as_display())), + "int" => match v { + Value::Int(_) => Ok(v.clone()), + Value::Text(s) => s + .parse::() + .map(Value::Int) + .map_err(|_| "invalid integer".into()), + _ => Err("int expects integer or text".into()), + }, + "number" => { + let n = match v { + Value::Text(s) => s.parse::().map_err(|_| "invalid number")?, + _ => number(v)?, + }; + if !n.is_finite() { + return Err("non-finite number".into()); + } + Ok(Value::Num(n)) + } + "bool" => match v { + Value::Bool(_) => Ok(v.clone()), + Value::Text(s) => match s.as_str() { + "true" | "True" => Ok(Value::Bool(true)), + "false" | "False" => Ok(Value::Bool(false)), + _ => Err("invalid bool".into()), + }, + _ => Err("bool expects bool or text".into()), + }, + "any" => Ok(v.clone()), + _ => Err(format!("unknown cast type {ty}")), + } +} diff --git a/src/host/data_ops.rs b/src/host/data_ops.rs new file mode 100644 index 0000000..30c17bd --- /dev/null +++ b/src/host/data_ops.rs @@ -0,0 +1,31 @@ +//! Recoverable parsing and timezone operations at the public data boundary. +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use std::collections::HashMap; +fn arg<'a>(b: &'a HashMap, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +pub(super) fn call( + _ctx: &mut HostContext, + id: HostFn, + b: &HashMap, +) -> Result { + match id { + HostFn::TomlStringify => super::toml_ops::stringify(arg(b, "value")?), + HostFn::TomlTryParse => Ok(super::result::capture( + "toml.parse", + super::toml_ops::parse(arg(b, "text")?).map_err(|e| format!("invalid_toml: {e}")), + )), + HostFn::DatetimeLocal => Ok(super::result::capture( + "datetime.parse_local", + super::datetime::local(arg(b, "text")?, arg(b, "zone")?, arg(b, "ambiguity")?), + )), + HostFn::DatetimeCalendarAdd => Ok(super::result::capture( + "datetime.add_calendar", + super::datetime::calendar_add(arg(b, "dt")?, arg(b, "days")?, arg(b, "ambiguity")?), + )), + _ => Err("not a data operation".into()), + } +} diff --git a/src/host/datetime.rs b/src/host/datetime.rs index 4a14996..b74f310 100644 --- a/src/host/datetime.rs +++ b/src/host/datetime.rs @@ -1,10 +1,11 @@ -//! Calendar / timezone subset for Mid2 M7 (`lib/datetime`). +//! Calendar moments with fixed offsets or embedded IANA timezone rules. //! -//! Moments are plain maps: `{unix, zone, iso}`. Zone is a fixed offset (`+08:00`) -//! or alias (`UTC`); a few fixed-offset IANA names are accepted. Full tzdb is out of scope. +//! Moments retain `{unix, zone, iso}`; `zone` is the numeric offset. +//! Named zones additionally retain `timezone`, so future instants and calendar +//! arithmetic recompute offsets using embedded IANA/DST rules. use crate::host::as_text; -use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc}; +use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc, Offset, LocalResult}; use crate::value::Value; @@ -126,7 +127,11 @@ fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> { } } let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?; - Ok((unix, zone_of_moment(entries)?)) + let offset = if let Some((_, Value::Text(zone))) = entries.iter().find(|(k,_)|k=="timezone") { + let zone: chrono_tz::Tz = zone.parse().map_err(|_| format!("unknown IANA timezone {zone}"))?; + zone.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.offset().fix() + } else { zone_of_moment(entries)? }; + Ok((unix, offset)) } Value::Text(s) => { // Treat bare ISO/RFC3339 text as a moment. @@ -151,11 +156,10 @@ pub fn now() -> Result { pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result { let secs = as_i64(unix, "unix")?; - let off = match zone { - None | Some(Value::None) => FixedOffset::east_opt(0).unwrap(), - Some(z) => parse_zone(as_text(z, "zone")?)?, - }; - moment(secs, off) + match zone { + None | Some(Value::None) => moment(secs, FixedOffset::east_opt(0).unwrap()), + Some(zone) => moment_in_zone(secs, as_text(zone,"zone")?), + } } pub fn to_unix(dt: &Value) -> Result { @@ -241,20 +245,56 @@ pub fn add( let hours = optional_i64(hours, "hours")?; let minutes = optional_i64(minutes, "minutes")?; let seconds = optional_i64(seconds, "seconds")?; - let delta = Duration::days(days) - + Duration::hours(hours) - + Duration::minutes(minutes) - + Duration::seconds(seconds); - let new_secs = secs - .checked_add(delta.num_seconds()) - .ok_or_else(|| "datetime.add overflow".to_string())?; - moment(new_secs, zone) + let delta = days.checked_mul(86400).and_then(|n|hours.checked_mul(3600).and_then(|h|n.checked_add(h))) + .and_then(|n|minutes.checked_mul(60).and_then(|m|n.checked_add(m))).and_then(|n|n.checked_add(seconds)) + .ok_or("datetime.add overflow")?; + let new_secs = secs.checked_add(delta).ok_or("datetime.add overflow")?; + if let Some(zone) = named_zone(dt) { moment_in_zone(new_secs,zone) } else { moment(new_secs,zone) } } pub fn in_zone(dt: &Value, zone: &Value) -> Result { let (secs, _) = unix_of_value(dt)?; - let off = parse_zone(as_text(zone, "zone")?)?; - moment(secs, off) + moment_in_zone(secs, as_text(zone,"zone")?) +} + +fn named_zone(dt:&Value)->Option<&str>{ + let Value::Map(fields)=dt else{return None}; + fields.iter().find_map(|(k,v)|if k=="timezone"{if let Value::Text(zone)=v{Some(zone.as_str())}else{None}}else{None}) +} +fn moment_in_zone(unix:i64,zone:&str)->Result{ + if let Ok(tz)=zone.parse::(){ + let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?; + let mut value=moment(unix,local.offset().fix())?; + if let Value::Map(fields)=&mut value{fields.push(("timezone".into(),Value::Text(zone.into())));} + Ok(value) + }else{moment(unix,parse_zone(zone)?)} +} +fn choose_local(tz:chrono_tz::Tz,local:NaiveDateTime,ambiguity:&str)->Result{ + if !matches!(ambiguity,"reject"|"earliest"|"latest"){return Err("ambiguity must be reject/earliest/latest".into())} + match tz.from_local_datetime(&local){ + LocalResult::Single(dt)=>Ok(dt.timestamp()), + LocalResult::None=>Err("nonexistent_time: local time is in a DST gap".into()), + LocalResult::Ambiguous(a,b)=>match ambiguity{ + "earliest"=>Ok(a.timestamp().min(b.timestamp())), + "latest"=>Ok(a.timestamp().max(b.timestamp())), + _=>Err("ambiguous_time: DST fold; select earliest or latest".into()), + } + } +} +pub(super) fn local(text:&Value,zone:&Value,ambiguity:&Value)->Result{ + let source=as_text(text,"text")?.replace('T'," "); + let local=NaiveDateTime::parse_from_str(&source,"%Y-%m-%d %H:%M:%S").map_err(|e|format!("datetime.parse_local: {e}"))?; + let zone=as_text(zone,"zone")?;let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?; + moment_in_zone(choose_local(tz,local,as_text(ambiguity,"ambiguity")?)?,zone) +} +pub(super) fn calendar_add(dt:&Value,days:&Value,ambiguity:&Value)->Result{ + let (unix,_)=unix_of_value(dt)?;let days=as_i64(days,"days")?; + let Some(zone)=named_zone(dt) else{return add(dt,Some(&Value::Int(days)),None,None,None)}; + let tz:chrono_tz::Tz=zone.parse().map_err(|_|"unknown IANA timezone")?; + let local=tz.timestamp_opt(unix,0).single().ok_or("invalid timestamp")?.naive_local(); + let duration=Duration::try_days(days).ok_or("calendar day overflow")?; + let next=local.checked_add_signed(duration).ok_or("calendar date overflow")?; + moment_in_zone(choose_local(tz,next,as_text(ambiguity,"ambiguity")?)?,zone) } #[cfg(test)] diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index 3740de0..8a18bff 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -222,6 +222,74 @@ pub enum HostFn { Access = 212, OracleJournal = 213, OracleReplayCheck = 214, + ListRange = 215, + ListEnumerate = 216, + ListPluck = 217, + ListProject = 218, + ListWhere = 219, + ListGroupBy = 220, + ListUniqueBy = 221, + ListAggregate = 222, + ListSortKeys = 223, + ListRename = 224, + TableFromColumns = 225, + TableToColumns = 226, + ListJoin = 227, + TableCast = 228, + FsTryReadText = 229, + FsTryWriteText = 230, + TryJsonParse = 231, + TryCsvParse = 232, + BytesFromText = 233, + BytesFromBase64 = 234, + BytesToText = 235, + BytesToBase64 = 236, + BytesLen = 237, + BytesSlice = 238, + FsReadBytes = 239, + FsWriteBytes = 240, + FsReadChunk = 241, + FsAppendBytes = 242, + FsAtomicWrite = 243, + FsWriteChanged = 244, + FsWriteChecked = 245, + FsReadLines = 246, + FsWriteLines = 247, + FsRemoveFile = 248, + FsRemoveEmptyDir = 249, + FsTempDir = 250, + FsFileHash = 251, + FsFind = 252, + FsCopyTree = 253, + FsSyncTree = 254, + FsRenameMany = 255, + PathRelative = 256, + PathWithExtension = 257, + DocumentSections = 258, + DocumentSection = 259, + DocumentReplaceSection = 260, + DocumentTables = 261, + DocumentReplaceTable = 262, + DocumentLinks = 263, + DocumentCodeBlocks = 264, + HttpRequestResult = 265, + HttpDownload = 266, + TomlStringify = 267, + TomlTryParse = 268, + DatetimeLocal = 269, + DatetimeCalendarAdd = 270, + SubtaskWaitTimeout = 271, + SubtaskCancelAll = 272, + SubtaskRunMany = 273, + HttpGetResult = 274, + ZipPack = 275, + ZipUnpack = 276, + TableTryCast = 277, + TableValidate = 278, + ListUnion = 279, + ListIntersection = 280, + ListDifference = 281, + TableSummarize = 282, } /// Single source of truth for every host function. `` slimming @@ -442,6 +510,74 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[ HostFnDef { id: 212, f: HostFn::Access, name: "host_access", required: &["value", "key"], optional: &[] }, HostFnDef { id: 213, f: HostFn::OracleJournal, name: "host_oracle_journal", required: &[], optional: &[] }, HostFnDef { id: 214, f: HostFn::OracleReplayCheck, name: "host_oracle_replay_check", required: &["expected", "observed"], optional: &[] }, + HostFnDef { id: 215, f: HostFn::ListRange, name: "host_table_range", required: &["start", "end"], optional: &["step"] }, + HostFnDef { id: 216, f: HostFn::ListEnumerate, name: "host_table_enumerate", required: &["list"], optional: &["start"] }, + HostFnDef { id: 217, f: HostFn::ListPluck, name: "host_table_pluck", required: &["list", "key"], optional: &[] }, + HostFnDef { id: 218, f: HostFn::ListProject, name: "host_table_project", required: &["list", "keys"], optional: &[] }, + HostFnDef { id: 219, f: HostFn::ListWhere, name: "host_table_where", required: &["list", "key", "value"], optional: &["op"] }, + HostFnDef { id: 220, f: HostFn::ListGroupBy, name: "host_table_group_by", required: &["list", "key"], optional: &[] }, + HostFnDef { id: 221, f: HostFn::ListUniqueBy, name: "host_table_unique_by", required: &["list", "key"], optional: &[] }, + HostFnDef { id: 222, f: HostFn::ListAggregate, name: "host_table_aggregate", required: &["list"], optional: &["key", "op"] }, + HostFnDef { id: 223, f: HostFn::ListSortKeys, name: "host_table_sort_keys", required: &["list", "keys"], optional: &["descending"] }, + HostFnDef { id: 224, f: HostFn::ListRename, name: "host_table_rename", required: &["list", "fields"], optional: &[] }, + HostFnDef { id: 225, f: HostFn::TableFromColumns, name: "host_table_from_columns", required: &["columns"], optional: &[] }, + HostFnDef { id: 226, f: HostFn::TableToColumns, name: "host_table_to_columns", required: &["rows"], optional: &[] }, + HostFnDef { id: 227, f: HostFn::ListJoin, name: "host_table_join", required: &["a", "b", "key", "right_key"], optional: &["mode"] }, + HostFnDef { id: 228, f: HostFn::TableCast, name: "host_table_cast", required: &["rows", "schema"], optional: &[] }, + HostFnDef { id: 229, f: HostFn::FsTryReadText, name: "host_fs_try_read_text", required: &["path"], optional: &[] }, + HostFnDef { id: 230, f: HostFn::FsTryWriteText, name: "host_fs_try_write_text", required: &["path", "text"], optional: &[] }, + HostFnDef { id: 231, f: HostFn::TryJsonParse, name: "host_try_json_parse", required: &["text"], optional: &[] }, + HostFnDef { id: 232, f: HostFn::TryCsvParse, name: "host_try_csv_parse", required: &["text"], optional: &[] }, + HostFnDef { id: 233, f: HostFn::BytesFromText, name: "host_bytes_from_text", required: &["text"], optional: &[] }, + HostFnDef { id: 234, f: HostFn::BytesFromBase64, name: "host_bytes_from_base64", required: &["text"], optional: &[] }, + HostFnDef { id: 235, f: HostFn::BytesToText, name: "host_bytes_to_text", required: &["data"], optional: &[] }, + HostFnDef { id: 236, f: HostFn::BytesToBase64, name: "host_bytes_to_base64", required: &["data"], optional: &[] }, + HostFnDef { id: 237, f: HostFn::BytesLen, name: "host_bytes_len", required: &["data"], optional: &[] }, + HostFnDef { id: 238, f: HostFn::BytesSlice, name: "host_bytes_slice", required: &["data", "start", "end"], optional: &[] }, + HostFnDef { id: 239, f: HostFn::FsReadBytes, name: "host_fs_read_bytes", required: &["path"], optional: &["max_bytes"] }, + HostFnDef { id: 240, f: HostFn::FsWriteBytes, name: "host_fs_write_bytes", required: &["path", "data"], optional: &[] }, + HostFnDef { id: 241, f: HostFn::FsReadChunk, name: "host_fs_read_chunk", required: &["path"], optional: &["offset", "size"] }, + HostFnDef { id: 242, f: HostFn::FsAppendBytes, name: "host_fs_append_bytes", required: &["path", "data"], optional: &[] }, + HostFnDef { id: 243, f: HostFn::FsAtomicWrite, name: "host_fs_atomic_write", required: &["path", "text"], optional: &[] }, + HostFnDef { id: 244, f: HostFn::FsWriteChanged, name: "host_fs_write_changed", required: &["path", "text"], optional: &[] }, + HostFnDef { id: 245, f: HostFn::FsWriteChecked, name: "host_fs_write_checked", required: &["path", "text", "expected_sha256"], optional: &[] }, + HostFnDef { id: 246, f: HostFn::FsReadLines, name: "host_fs_read_lines", required: &["path"], optional: &["max_bytes"] }, + HostFnDef { id: 247, f: HostFn::FsWriteLines, name: "host_fs_write_lines", required: &["path", "lines"], optional: &[] }, + HostFnDef { id: 248, f: HostFn::FsRemoveFile, name: "host_fs_remove_file", required: &["path"], optional: &[] }, + HostFnDef { id: 249, f: HostFn::FsRemoveEmptyDir, name: "host_fs_remove_empty_dir", required: &["path"], optional: &[] }, + HostFnDef { id: 250, f: HostFn::FsTempDir, name: "host_fs_temp_dir", required: &[], optional: &["prefix"] }, + HostFnDef { id: 251, f: HostFn::FsFileHash, name: "host_fs_file_hash", required: &["path"], optional: &[] }, + HostFnDef { id: 252, f: HostFn::FsFind, name: "host_fs_find", required: &["path"], optional: &["pattern", "exclude", "max_depth", "kind"] }, + HostFnDef { id: 253, f: HostFn::FsCopyTree, name: "host_fs_copy_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] }, + HostFnDef { id: 254, f: HostFn::FsSyncTree, name: "host_fs_sync_tree", required: &["src", "dest"], optional: &["overwrite", "exclude", "dry_run"] }, + HostFnDef { id: 255, f: HostFn::FsRenameMany, name: "host_fs_rename_many", required: &["moves"], optional: &["dry_run"] }, + HostFnDef { id: 256, f: HostFn::PathRelative, name: "host_path_relative", required: &["path", "base"], optional: &[] }, + HostFnDef { id: 257, f: HostFn::PathWithExtension, name: "host_path_with_extension", required: &["path", "extension"], optional: &[] }, + HostFnDef { id: 258, f: HostFn::DocumentSections, name: "host_document_sections", required: &["text"], optional: &[] }, + HostFnDef { id: 259, f: HostFn::DocumentSection, name: "host_document_section", required: &["text", "title"], optional: &[] }, + HostFnDef { id: 260, f: HostFn::DocumentReplaceSection, name: "host_document_replace_section", required: &["text", "title", "body"], optional: &["expected_sha256"] }, + HostFnDef { id: 261, f: HostFn::DocumentTables, name: "host_document_tables", required: &["text"], optional: &[] }, + HostFnDef { id: 262, f: HostFn::DocumentReplaceTable, name: "host_document_replace_table", required: &["text", "index", "headers", "rows"], optional: &["expected_sha256"] }, + HostFnDef { id: 263, f: HostFn::DocumentLinks, name: "host_document_links", required: &["text"], optional: &[] }, + HostFnDef { id: 264, f: HostFn::DocumentCodeBlocks, name: "host_document_code_blocks", required: &["text"], optional: &[] }, + HostFnDef { id: 265, f: HostFn::HttpRequestResult, name: "host_http_request_result", required: &["method", "url"], optional: &["body", "headers", "timeout_ms", "max_bytes", "response"] }, + HostFnDef { id: 266, f: HostFn::HttpDownload, name: "host_http_download", required: &["url", "path"], optional: &["headers", "timeout_ms", "max_bytes"] }, + HostFnDef { id: 267, f: HostFn::TomlStringify, name: "host_toml_stringify", required: &["value"], optional: &[] }, + HostFnDef { id: 268, f: HostFn::TomlTryParse, name: "host_toml_try_parse", required: &["text"], optional: &[] }, + HostFnDef { id: 269, f: HostFn::DatetimeLocal, name: "host_datetime_local", required: &["text", "zone"], optional: &["ambiguity"] }, + HostFnDef { id: 270, f: HostFn::DatetimeCalendarAdd, name: "host_datetime_calendar_add", required: &["dt", "days"], optional: &["ambiguity"] }, + HostFnDef { id: 271, f: HostFn::SubtaskWaitTimeout, name: "host_subtask_wait_timeout", required: &["id"], optional: &["timeout_ms", "cancel"] }, + HostFnDef { id: 272, f: HostFn::SubtaskCancelAll, name: "host_subtask_cancel_all", required: &[], optional: &[] }, + HostFnDef { id: 273, f: HostFn::SubtaskRunMany, name: "host_subtask_run_many", required: &["tasks"], optional: &["limit", "timeout_ms"] }, + HostFnDef { id: 274, f: HostFn::HttpGetResult, name: "host_http_get_result", required: &["url"], optional: &["headers", "timeout_ms", "max_bytes", "response"] }, + HostFnDef { id: 275, f: HostFn::ZipPack, name: "host_zip_pack", required: &["src", "dest"], optional: &["max_bytes"] }, + HostFnDef { id: 276, f: HostFn::ZipUnpack, name: "host_zip_unpack", required: &["src", "dest"], optional: &["max_bytes"] }, + HostFnDef { id: 277, f: HostFn::TableTryCast, name: "host_table_try_cast", required: &["rows", "schema"], optional: &[] }, + HostFnDef { id: 278, f: HostFn::TableValidate, name: "host_table_validate", required: &["rows", "schema"], optional: &[] }, + HostFnDef { id: 279, f: HostFn::ListUnion, name: "host_table_union", required: &["a", "b"], optional: &[] }, + HostFnDef { id: 280, f: HostFn::ListIntersection, name: "host_table_intersection", required: &["a", "b"], optional: &[] }, + HostFnDef { id: 281, f: HostFn::ListDifference, name: "host_table_difference", required: &["a", "b"], optional: &[] }, + HostFnDef { id: 282, f: HostFn::TableSummarize, name: "host_table_summarize", required: &["list", "key", "field"], optional: &["op"] }, ]; @@ -452,6 +588,74 @@ impl HostFn { pub fn from_name(name: &str) -> Option { Some(match name { + "host_table_summarize" => Self::TableSummarize, + "host_table_difference" => Self::ListDifference, + "host_table_intersection" => Self::ListIntersection, + "host_table_union" => Self::ListUnion, + "host_table_validate" => Self::TableValidate, + "host_table_try_cast" => Self::TableTryCast, + "host_zip_unpack" => Self::ZipUnpack, + "host_zip_pack" => Self::ZipPack, + "host_http_get_result" => Self::HttpGetResult, + "host_subtask_run_many" => Self::SubtaskRunMany, + "host_subtask_cancel_all" => Self::SubtaskCancelAll, + "host_subtask_wait_timeout" => Self::SubtaskWaitTimeout, + "host_datetime_calendar_add" => Self::DatetimeCalendarAdd, + "host_datetime_local" => Self::DatetimeLocal, + "host_toml_try_parse" => Self::TomlTryParse, + "host_toml_stringify" => Self::TomlStringify, + "host_http_download" => Self::HttpDownload, + "host_http_request_result" => Self::HttpRequestResult, + "host_document_code_blocks" => Self::DocumentCodeBlocks, + "host_document_links" => Self::DocumentLinks, + "host_document_replace_table" => Self::DocumentReplaceTable, + "host_document_tables" => Self::DocumentTables, + "host_document_replace_section" => Self::DocumentReplaceSection, + "host_document_section" => Self::DocumentSection, + "host_document_sections" => Self::DocumentSections, + "host_path_with_extension" => Self::PathWithExtension, + "host_path_relative" => Self::PathRelative, + "host_fs_rename_many" => Self::FsRenameMany, + "host_fs_sync_tree" => Self::FsSyncTree, + "host_fs_copy_tree" => Self::FsCopyTree, + "host_fs_find" => Self::FsFind, + "host_fs_file_hash" => Self::FsFileHash, + "host_fs_temp_dir" => Self::FsTempDir, + "host_fs_remove_empty_dir" => Self::FsRemoveEmptyDir, + "host_fs_remove_file" => Self::FsRemoveFile, + "host_fs_write_lines" => Self::FsWriteLines, + "host_fs_read_lines" => Self::FsReadLines, + "host_fs_write_checked" => Self::FsWriteChecked, + "host_fs_write_changed" => Self::FsWriteChanged, + "host_fs_atomic_write" => Self::FsAtomicWrite, + "host_fs_append_bytes" => Self::FsAppendBytes, + "host_fs_read_chunk" => Self::FsReadChunk, + "host_fs_write_bytes" => Self::FsWriteBytes, + "host_fs_read_bytes" => Self::FsReadBytes, + "host_bytes_slice" => Self::BytesSlice, + "host_bytes_len" => Self::BytesLen, + "host_bytes_to_base64" => Self::BytesToBase64, + "host_bytes_to_text" => Self::BytesToText, + "host_bytes_from_base64" => Self::BytesFromBase64, + "host_bytes_from_text" => Self::BytesFromText, + "host_try_csv_parse" => Self::TryCsvParse, + "host_try_json_parse" => Self::TryJsonParse, + "host_fs_try_write_text" => Self::FsTryWriteText, + "host_fs_try_read_text" => Self::FsTryReadText, + "host_table_cast" => Self::TableCast, + "host_table_join" => Self::ListJoin, + "host_table_to_columns" => Self::TableToColumns, + "host_table_from_columns" => Self::TableFromColumns, + "host_table_rename" => Self::ListRename, + "host_table_sort_keys" => Self::ListSortKeys, + "host_table_aggregate" => Self::ListAggregate, + "host_table_unique_by" => Self::ListUniqueBy, + "host_table_group_by" => Self::ListGroupBy, + "host_table_where" => Self::ListWhere, + "host_table_project" => Self::ListProject, + "host_table_pluck" => Self::ListPluck, + "host_table_enumerate" => Self::ListEnumerate, + "host_table_range" => Self::ListRange, "host_read_text" => Self::ReadText, "host_write_text" => Self::WriteText, "host_append_text" => Self::AppendText, @@ -664,6 +868,281 @@ impl HostFn { }) } + /// Effects belong to resolved host identities, never import spellings. + /// Exhaustive match forces every new primitive to declare its effects. + pub fn effects(self) -> &'static [&'static str] { + match self { + Self::TableSummarize => &["pure"], + Self::DotenvLoad => &["fs.read", "environment.write"], + Self::ForeignLoadConfig => &["fs.read"], + Self::ExtNativePath => &["plugin.call"], + Self::ListDifference => &["pure"], + Self::ListIntersection => &["pure"], + Self::ListUnion => &["pure"], + Self::TableValidate => &["pure"], + Self::TableTryCast => &["pure"], + Self::ZipUnpack => &["fs.write"], + Self::ZipPack => &["fs.write"], + Self::HttpGetResult => &["network.read"], + Self::SubtaskRunMany => &["process.exec"], + Self::SubtaskCancelAll => &["process.exec"], + Self::SubtaskWaitTimeout => &["process.exec"], + Self::DatetimeCalendarAdd => &["pure"], + Self::DatetimeLocal => &["pure"], + Self::TomlTryParse => &["pure"], + Self::TomlStringify => &["pure"], + Self::HttpDownload => &["network.read", "fs.write"], + Self::HttpRequestResult => &["network.write"], + Self::DocumentCodeBlocks => &["pure"], + Self::DocumentLinks => &["pure"], + Self::DocumentReplaceTable => &["pure"], + Self::DocumentTables => &["pure"], + Self::DocumentReplaceSection => &["pure"], + Self::DocumentSection => &["pure"], + Self::DocumentSections => &["pure"], + Self::PathWithExtension => &["pure"], + Self::PathRelative => &["pure"], + Self::FsRenameMany => &["fs.write"], + Self::FsSyncTree => &["fs.write"], + Self::FsCopyTree => &["fs.write"], + Self::FsFind => &["fs.read"], + Self::FsFileHash => &["fs.read"], + Self::FsTempDir => &["fs.write"], + Self::FsRemoveEmptyDir => &["fs.write"], + Self::FsRemoveFile => &["fs.write"], + Self::FsWriteLines => &["fs.write"], + Self::FsReadLines => &["fs.read"], + Self::FsWriteChecked => &["fs.write"], + Self::FsWriteChanged => &["fs.write"], + Self::FsAtomicWrite => &["fs.write"], + Self::FsAppendBytes => &["fs.write"], + Self::FsReadChunk => &["fs.read"], + Self::FsWriteBytes => &["fs.write"], + Self::FsReadBytes => &["fs.read"], + Self::BytesSlice => &["pure"], + Self::BytesLen => &["pure"], + Self::BytesToBase64 => &["pure"], + Self::BytesToText => &["pure"], + Self::BytesFromBase64 => &["pure"], + Self::BytesFromText => &["pure"], + Self::TryCsvParse => &["pure"], + Self::TryJsonParse => &["pure"], + Self::FsTryWriteText => &["fs.write"], + Self::FsTryReadText => &["fs.read"], + Self::TableCast => &["pure"], + Self::ListJoin => &["pure"], + Self::TableToColumns => &["pure"], + Self::TableFromColumns => &["pure"], + Self::ListRename => &["pure"], + Self::ListSortKeys => &["pure"], + Self::ListAggregate => &["pure"], + Self::ListUniqueBy => &["pure"], + Self::ListGroupBy => &["pure"], + Self::ListWhere => &["pure"], + Self::ListProject => &["pure"], + Self::ListPluck => &["pure"], + Self::ListEnumerate => &["pure"], + Self::ListRange => &["pure"], + Self::ReadText + | Self::Exists + | Self::ListDir + | Self::FsStat + | Self::FsWalk + | Self::WritebackGet + | Self::WritebackList + | Self::WritebackScanPath => &["fs.read"], + Self::WriteText + | Self::AppendText + | Self::MakeDir + | Self::Remove + | Self::FsCopyFile + | Self::FsMove + | Self::FsMakeTemp + | Self::FsMakeDirs + | Self::FsRemoveTree + | Self::TextPatch + | Self::ApplyPatchBlocks + | Self::WritebackRecord + | Self::WritebackClear + | Self::WritebackEnsure => &["fs.write"], + Self::HttpGet => &["network.read"], + Self::HttpRequest => &["network.write"], + Self::HttpPost | Self::HttpPostSse => &["network.write"], + Self::Exec + | Self::SubtaskSpawn + | Self::SubtaskPoll + | Self::SubtaskJoin + | Self::SubtaskKill + | Self::SubtaskWaitAll + | Self::ForeignRun + | Self::ForeignRunLang + | Self::ForeignInvoke + | Self::ForeignProbe + | Self::ForeignCall + | Self::ForeignRunMany + | Self::ForeignCallMany + | Self::ForeignSessionOpen + | Self::ForeignSessionEval + | Self::ForeignSessionSet + | Self::ForeignSessionGet + | Self::ForeignSessionNames + | Self::ForeignSessionClose + | Self::ForeignSessionList + | Self::ForeignSessionInterrupt => &["process.exec"], + Self::PluginLoad | Self::PluginUnload => &["plugin.call"], + Self::LogLine + | Self::StreamPublish + | Self::Plot + | Self::PlotPoints + | Self::PlotConic => &["output.write"], + Self::NowUnix | Self::NowMs | Self::DatetimeNow => &["time.read"], + Self::Random + | Self::RandomInt + | Self::SecretsTokenHex + | Self::SecretsTokenUrlsafe + | Self::UuidV4 => &["random.read"], + Self::EnvGet => &["environment.read"], + Self::EnvSet => &["environment.write"], + Self::Exit | Self::SleepMs => &["process.control"], + Self::FormatTime + | Self::ParseTime + | Self::Args + | Self::Cwd + | Self::JsonParse + | Self::JsonStringify + | Self::JsonGet + | Self::JsonKeys + | Self::UrlEncode + | Self::Pi + | Self::EConst + | Self::Num + | Self::MathAdd + | Self::MathSub + | Self::MathMul + | Self::MathDiv + | Self::MathPow + | Self::MathNeg + | Self::MathSin + | Self::MathCos + | Self::MathTan + | Self::MathAsin + | Self::MathAcos + | Self::MathAtan + | Self::MathSqrt + | Self::MathAbs + | Self::MathLn + | Self::MathExp + | Self::MathFloor + | Self::MathCeil + | Self::MathMin + | Self::MathMax + | Self::Seed + | Self::Formula + | Self::Simplify + | Self::Expand + | Self::Diff + | Self::Subs + | Self::Eval + | Self::Solve + | Self::ForeignSetCmd + | Self::ForeignLangs + | Self::JsonQuote + | Self::PluginList + | Self::MapSet + | Self::ListAppend + | Self::OuterCallLine + | Self::OpenAiSseParse + | Self::CollectionPut + | Self::ListPrepend + | Self::ListConcat + | Self::ListInsert + | Self::ListSetAt + | Self::ListRemoveAt + | Self::ListSlice + | Self::ListContains + | Self::ListIndexOf + | Self::ListReverse + | Self::ListFirst + | Self::ListLast + | Self::MapGet + | Self::MapDelete + | Self::MapHas + | Self::MapKeys + | Self::MapValues + | Self::MapItems + | Self::MapMerge + | Self::MapSize + | Self::CollectionClear + | Self::CookieParse + | Self::MultipartParse + | Self::MarkdownParse + | Self::ReIsMatch + | Self::ReFind + | Self::ReFindAll + | Self::ReReplace + | Self::ReSplit + | Self::EncodingBase64Encode + | Self::EncodingBase64Decode + | Self::EncodingHexEncode + | Self::EncodingHexDecode + | Self::PathJoin + | Self::PathSplit + | Self::PathFileName + | Self::PathParent + | Self::PathExtension + | Self::PathNormalize + | Self::PathIsAbsolute + | Self::HashSha256 + | Self::HashSha1 + | Self::HashMd5 + | Self::HashHmacSha256 + | Self::TextContains + | Self::TextStartsWith + | Self::TextEndsWith + | Self::TextReplace + | Self::TextToUpper + | Self::TextToLower + | Self::TextRepeat + | Self::TextPad + | Self::CsvParse + | Self::CsvStringify + | Self::ListSort + | Self::ListSortBy + | Self::ListUnique + | Self::ListChunk + | Self::ListZip + | Self::ListFlatten + | Self::CliParse + | Self::LogSetLevel + | Self::DatetimeFromUnix + | Self::DatetimeToUnix + | Self::DatetimeParse + | Self::DatetimeFormat + | Self::DatetimeAdd + | Self::DatetimeInZone + | Self::UrlParse + | Self::UrlQueryParse + | Self::UrlQueryStringify + | Self::TomlParse + | Self::HtmlEscape + | Self::HtmlUnescape + | Self::EncodingBase32Encode + | Self::EncodingBase32Decode + | Self::StatsMean + | Self::StatsMedian + | Self::StatsStdev + | Self::Meta + | Self::MetaGet + | Self::ModuleSource + | Self::ArtifactKind + | Self::ForeignRegister + | Self::ForeignUnset + | Self::Access + | Self::OracleJournal + | Self::OracleReplayCheck => &["pure"], + } + } + pub fn as_u16(self) -> u16 { self as u16 } @@ -705,6 +1184,74 @@ pub fn call_host( bound: &HashMap, ) -> Result { match fn_id { + HostFn::TableSummarize => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListDifference => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListIntersection => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListUnion => super::collection_ops::call(ctx, fn_id, bound), + HostFn::TableValidate => super::collection_ops::call(ctx, fn_id, bound), + HostFn::TableTryCast => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ZipUnpack => super::archive::call(ctx, fn_id, bound), + HostFn::ZipPack => super::archive::call(ctx, fn_id, bound), + HostFn::HttpGetResult => super::net_ops::call(ctx, fn_id, bound), + HostFn::SubtaskRunMany => super::task_ops::call(ctx, fn_id, bound), + HostFn::SubtaskCancelAll => super::task_ops::call(ctx, fn_id, bound), + HostFn::SubtaskWaitTimeout => super::task_ops::call(ctx, fn_id, bound), + HostFn::DatetimeCalendarAdd => super::data_ops::call(ctx, fn_id, bound), + HostFn::DatetimeLocal => super::data_ops::call(ctx, fn_id, bound), + HostFn::TomlTryParse => super::data_ops::call(ctx, fn_id, bound), + HostFn::TomlStringify => super::data_ops::call(ctx, fn_id, bound), + HostFn::HttpDownload => super::net_ops::call(ctx, fn_id, bound), + HostFn::HttpRequestResult => super::net_ops::call(ctx, fn_id, bound), + HostFn::DocumentCodeBlocks => super::document::call(ctx, fn_id, bound), + HostFn::DocumentLinks => super::document::call(ctx, fn_id, bound), + HostFn::DocumentReplaceTable => super::document::call(ctx, fn_id, bound), + HostFn::DocumentTables => super::document::call(ctx, fn_id, bound), + HostFn::DocumentReplaceSection => super::document::call(ctx, fn_id, bound), + HostFn::DocumentSection => super::document::call(ctx, fn_id, bound), + HostFn::DocumentSections => super::document::call(ctx, fn_id, bound), + HostFn::PathWithExtension => super::fs_ops::call(ctx, fn_id, bound), + HostFn::PathRelative => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsRenameMany => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsSyncTree => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsCopyTree => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsFind => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsFileHash => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsTempDir => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsRemoveEmptyDir => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsRemoveFile => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsWriteLines => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsReadLines => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsWriteChecked => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsWriteChanged => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsAtomicWrite => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsAppendBytes => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsReadChunk => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsWriteBytes => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsReadBytes => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesSlice => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesLen => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesToBase64 => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesToText => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesFromBase64 => super::fs_ops::call(ctx, fn_id, bound), + HostFn::BytesFromText => super::fs_ops::call(ctx, fn_id, bound), + HostFn::TryCsvParse => super::fs_ops::call(ctx, fn_id, bound), + HostFn::TryJsonParse => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsTryWriteText => super::fs_ops::call(ctx, fn_id, bound), + HostFn::FsTryReadText => super::fs_ops::call(ctx, fn_id, bound), + HostFn::TableCast => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListJoin => super::collection_ops::call(ctx, fn_id, bound), + HostFn::TableToColumns => super::collection_ops::call(ctx, fn_id, bound), + HostFn::TableFromColumns => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListRename => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListSortKeys => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListAggregate => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListUniqueBy => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListGroupBy => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListWhere => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListProject => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListPluck => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListEnumerate => super::collection_ops::call(ctx, fn_id, bound), + HostFn::ListRange => super::collection_ops::call(ctx, fn_id, bound), HostFn::Access => { let base = require(bound, "value")?; let key = match require(bound, "key")? { diff --git a/src/host/document.rs b/src/host/document.rs new file mode 100644 index 0000000..3da5ff1 --- /dev/null +++ b/src/host/document.rs @@ -0,0 +1,358 @@ +//! Inert Markdown structure using the same pulldown-cmark parser as rendering. +//! Byte ranges always refer to the original UTF-8 source; nothing is executed. +use super::{as_text, result}; +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +type Args = HashMap; +fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { + as_text(arg(b, k)?, k) +} +fn map(values: Vec<(&str, Value)>) -> Value { + Value::Map(values.into_iter().map(|(k, v)| (k.into(), v)).collect()) +} +fn string(v: impl Into) -> Value { + Value::Text(v.into()) +} +fn num(v: usize) -> Value { + Value::Int(v as i64) +} +#[derive(Debug)] +struct Section { + title: String, + level: usize, + start: usize, + body: usize, + end: usize, +} +fn sections(text: &str) -> Vec
{ + let mut out: Vec
= Vec::new(); + let mut active = None; + for (event, range) in Parser::new_ext( + text, + Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, + ) + .into_offset_iter() + { + match event { + Event::Start(Tag::Heading { level, .. }) => { + let n = level as usize; + for section in &mut out { + if section.end == text.len() && section.level >= n { + section.end = range.start + } + } + out.push(Section { + title: String::new(), + level: n, + start: range.start, + body: range.end, + end: text.len(), + }); + active = Some(out.len() - 1); + } + Event::End(TagEnd::Heading(_)) => { + if let Some(i) = active.take() { + out[i].body = range.end + } + } + Event::Text(t) | Event::Code(t) => { + if let Some(i) = active { + out[i].title.push_str(&t) + } + } + Event::SoftBreak | Event::HardBreak => { + if let Some(i) = active { + out[i].title.push(' ') + } + } + _ => {} + } + } + out +} +fn unique_section<'a>(sections: &'a [Section], title: &str) -> Result<&'a Section, String> { + let hits: Vec<_> = sections.iter().filter(|s| s.title == title).collect(); + match hits.as_slice() { + [s] => Ok(s), + [] => Err(format!("section not found: {title}")), + _ => Err(format!("ambiguous section: {title}")), + } +} +#[derive(Default)] +struct Table { + start: usize, + end: usize, + headers: Vec, + rows: Vec>, +} +fn tables(text: &str) -> Vec { + let mut out = Vec::new(); + let mut table: Option
= None; + let mut header = false; + let mut row = Vec::new(); + let mut cell: Option = None; + for (event, range) in Parser::new_ext( + text, + Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, + ) + .into_offset_iter() + { + match event { + Event::Start(Tag::Table(_)) => { + table = Some(Table { + start: range.start, + ..Default::default() + }) + } + Event::Start(Tag::TableHead) => { + header = true; + row.clear() + } + Event::End(TagEnd::TableHead) => { + if let Some(t) = table.as_mut() { + t.headers = std::mem::take(&mut row) + } + header = false + } + Event::Start(Tag::TableRow) => row.clear(), + Event::End(TagEnd::TableRow) => { + if !header { + if let Some(t) = table.as_mut() { + t.rows.push(std::mem::take(&mut row)); + } + } + } + Event::Start(Tag::TableCell) => cell = Some(String::new()), + Event::End(TagEnd::TableCell) => { + if let Some(c) = cell.take() { + row.push(c) + } + } + Event::Text(t) | Event::Code(t) => { + if let Some(c) = cell.as_mut() { + c.push_str(&t) + } + } + Event::SoftBreak | Event::HardBreak => { + if let Some(c) = cell.as_mut() { + c.push('\n') + } + } + Event::End(TagEnd::Table) => { + if let Some(mut t) = table.take() { + t.end = range.end; + out.push(t) + } + } + _ => {} + } + } + out +} +fn check_digest(b: &Args, text: &str) -> Result<(), String> { + if let Some(Value::Text(expected)) = b.get("expected_sha256") { + if format!("{:x}", Sha256::digest(text.as_bytes())) != *expected { + return Err("conflict: document content changed".into()); + } + } + Ok(()) +} +pub(super) fn call(_ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + let source = text(b, "text")?; + match id { + HostFn::DocumentSections => Ok(Value::List( + sections(source) + .into_iter() + .map(|s| { + map(vec![ + ("title", string(s.title)), + ("level", num(s.level)), + ("start", num(s.start)), + ("body_start", num(s.body)), + ("end", num(s.end)), + ("text", string(&source[s.body..s.end])), + ]) + }) + .collect(), + )), + HostFn::DocumentSection => { + let sections = sections(source); + let section = unique_section(§ions, text(b, "title")?)?; + Ok(string(&source[section.body..section.end])) + } + HostFn::DocumentReplaceSection => { + let change = (|| { + check_digest(b, source)?; + let sections = sections(source); + let section = unique_section(§ions, text(b, "title")?)?; + let mut out = source[..section.body].to_string(); + let body = text(b, "body")?; + if !out.ends_with('\n') { + out.push('\n') + } + out.push('\n'); + out.push_str(body); + if !body.ends_with('\n') { + out.push('\n') + } + out.push_str(&source[section.end..]); + Ok(string(out)) + })(); + Ok(result::capture("document.replace_section", change)) + } + HostFn::DocumentTables => Ok(Value::List( + tables(source) + .into_iter() + .map(|t| { + map(vec![ + ("start", num(t.start)), + ("end", num(t.end)), + ( + "headers", + Value::List(t.headers.into_iter().map(string).collect()), + ), + ( + "rows", + Value::List( + t.rows + .into_iter() + .map(|r| Value::List(r.into_iter().map(string).collect())) + .collect(), + ), + ), + ]) + }) + .collect(), + )), + HostFn::DocumentReplaceTable => { + let change = (|| { + check_digest(b, source)?; + let index = match arg(b, "index")? { + Value::Int(n) if *n >= 0 => *n as usize, + _ => return Err("table index is zero-based nonnegative integer".into()), + }; + let tables = tables(source); + let table = tables.get(index).ok_or("table index out of range")?; + fn cells(v: &Value) -> Result, String> { + let Value::List(xs) = v else { + return Err("cells must be list of text".into()); + }; + xs.iter() + .map(|v| { + as_text(v, "cell").map(|s| { + s.replace('\\', "\\\\") + .replace('|', "\\|") + .replace('\n', "
") + }) + }) + .collect() + } + let headers = cells(arg(b, "headers")?)?; + if headers.is_empty() { + return Err("table needs headers".into()); + } + let Value::List(rows) = arg(b, "rows")? else { + return Err("rows must be list".into()); + }; + let mut rendered = format!( + "| {} |\n| {} |\n", + headers.join(" | "), + vec!["---"; headers.len()].join(" | ") + ); + for row in rows { + let row = cells(row)?; + if row.len() != headers.len() { + return Err("table row length differs from header".into()); + } + rendered.push_str(&format!("| {} |\n", row.join(" | "))) + } + Ok(string(format!( + "{}{}{}", + &source[..table.start], + rendered, + &source[table.end..] + ))) + })(); + Ok(result::capture("document.replace_table", change)) + } + HostFn::DocumentLinks => { + let mut out = Vec::new(); + let mut active: Vec<(String, String, usize)> = Vec::new(); + for (event, range) in Parser::new_ext( + source, + Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, + ) + .into_offset_iter() + { + match event { + Event::Start(Tag::Link { dest_url, .. }) => { + active.push((dest_url.into_string(), String::new(), range.start)) + } + Event::Text(s) | Event::Code(s) => { + if let Some((_, text, _)) = active.last_mut() { + text.push_str(&s) + } + } + Event::End(TagEnd::Link) => { + if let Some((url, text, start)) = active.pop() { + out.push(map(vec![ + ("label", string(text)), + ("target", string(url)), + ("start", num(start)), + ("end", num(range.end)), + ])) + } + } + _ => {} + } + } + Ok(Value::List(out)) + } + HostFn::DocumentCodeBlocks => { + let mut out = Vec::new(); + let mut active = None; + for (event, range) in Parser::new_ext( + source, + Options::ENABLE_TABLES | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS, + ) + .into_offset_iter() + { + match event { + Event::Start(Tag::CodeBlock(kind)) => { + let lang = match kind { + CodeBlockKind::Fenced(s) => s.into_string(), + CodeBlockKind::Indented => String::new(), + }; + active = Some((lang, String::new(), range.start)); + } + Event::Text(s) => { + if let Some((_, body, _)) = active.as_mut() { + body.push_str(&s) + } + } + Event::End(TagEnd::CodeBlock) => { + if let Some((lang, body, start)) = active.take() { + out.push(map(vec![ + ("language", string(lang)), + ("text", string(body)), + ("start", num(start)), + ("end", num(range.end)), + ])) + } + } + _ => {} + } + } + Ok(Value::List(out)) + } + _ => Err("not a document operation".into()), + } +} diff --git a/src/host/encoding.rs b/src/host/encoding.rs index 9a635d6..d503de2 100644 --- a/src/host/encoding.rs +++ b/src/host/encoding.rs @@ -125,7 +125,7 @@ fn from_hex(b: u8) -> Result { } } -fn encode_base64(input: &[u8]) -> String { +pub(super) fn encode_base64(input: &[u8]) -> String { let mut out = String::with_capacity((input.len() + 2) / 3 * 4); let mut i = 0; while i + 3 <= input.len() { @@ -153,7 +153,7 @@ fn encode_base64(input: &[u8]) -> String { out } -fn decode_base64(input: &str) -> Result, String> { +pub(super) fn decode_base64(input: &str) -> Result, String> { let raw = input.as_bytes(); if raw.len() % 4 != 0 { return Err("base64_decode: length must be multiple of 4".into()); diff --git a/src/host/fs.rs b/src/host/fs.rs index dad8bee..1fcf828 100644 --- a/src/host/fs.rs +++ b/src/host/fs.rs @@ -62,6 +62,17 @@ pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result text, + Err(_) if !matches!(exists(ctx,path),Ok(Value::Bool(true))) => String::new(), + Err(e) => return Err(e), + _ => return Err("append_text needs UTF-8".into()), + }; + current.push_str(text_body(text)?); + crate::host::sandbox_fs::cow_write_text(ctx,&p,¤t)?; + return Ok(Value::None); + } use std::io::Write; let mut f = fs::OpenOptions::new() .create(true) @@ -99,6 +110,7 @@ pub fn make_dir(ctx: &HostContext, path: &Value) -> Result { if !ctx.allow_fs_write() { return Err("make_dir denied by host policy".into()); } + if ctx.sandbox_session.is_some() { return Err("unsupported: make_dir directory state in CoW sandbox".into()); } let p = ctx.resolve_path(text_path(path)?)?; fs::create_dir_all(&p).map_err(|e| format!("make_dir {}: {e}", p.display()))?; Ok(Value::None) @@ -109,6 +121,7 @@ pub fn make_dirs(ctx: &HostContext, path: &Value) -> Result { if !ctx.allow_fs_write() { return Err("make_dirs denied by host policy".into()); } + if ctx.sandbox_session.is_some() { return Err("unsupported: make_dirs directory state in CoW sandbox".into()); } let p = ctx.resolve_path(text_path(path)?)?; fs::create_dir_all(&p).map_err(|e| format!("make_dirs {}: {e}", p.display()))?; Ok(Value::None) @@ -119,6 +132,9 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result { return Err("remove denied by host policy".into()); } let p = ctx.resolve_path(text_path(path)?)?; + if ctx.sandbox_session.is_some() && p.is_dir() { + return Err("unsupported: recursive directory removal in CoW sandbox".into()); + } if crate::host::sandbox_fs::cow_remove(ctx, &p)? { return Ok(Value::None); } @@ -135,6 +151,7 @@ pub fn remove_tree(ctx: &HostContext, path: &Value) -> Result { if !ctx.allow_fs_write() { return Err("remove_tree denied by host policy".into()); } + if ctx.sandbox_session.is_some() { return Err("unsupported: remove_tree directory state in CoW sandbox".into()); } let p = ctx.resolve_path(text_path(path)?)?; if !p.exists() { return Err(format!("remove_tree: not found: {}", p.display())); @@ -210,6 +227,18 @@ pub fn copy_file(ctx: &HostContext, src: &Value, dest: &Value) -> Result bytes, + None => { let mut bytes=Vec::new();fs::File::open(&from).map_err(|e|e.to_string())? + .take(64*1024*1024+1).read_to_end(&mut bytes).map_err(|e|e.to_string())?;bytes }, + }; + if bytes.len()>64*1024*1024 { return Err("resource_limit: CoW copy exceeds 64 MiB".into()); } + crate::host::sandbox_fs::cow_write_bytes(ctx,&to,&bytes)?; + return Ok(Value::None); + } if let Some(parent) = to.parent() { fs::create_dir_all(parent).map_err(|e| format!("copy_file mkdir: {e}"))?; } @@ -223,6 +252,12 @@ pub fn move_path(ctx: &HostContext, src: &Value, dest: &Value) -> Result) -> Result 1 { return Err(format!( "text_patch: find matched {count} times in {} (must be unique)", - p.display() + display )); } let next = src.replacen(find, replace, 1); - fs::write(&p, next).map_err(|e| format!("text_patch write {}: {e}", p.display()))?; + write_text(ctx,path,&Value::Text(next))?; Ok(Value::Int(1)) } @@ -362,8 +404,8 @@ fn apply_patch_blocks_inner( if blocks.is_empty() { return Ok(Value::Int(0)); } - let p = ctx.resolve_path(text_path(path)?)?; - let mut src = fs::read_to_string(&p).map_err(|e| format!("apply_patch_blocks {}: {e}", p.display()))?; + let display = text_path(path)?; + let Value::Text(mut src) = read_text(ctx,path)? else { return Err("apply_patch_blocks needs text".into()); }; let mut applied = 0i64; for (find, replace) in blocks { if find.is_empty() { @@ -379,19 +421,19 @@ fn apply_patch_blocks_inner( if count == 0 { return Err(format!( "apply_patch_blocks: FIND not found in {}", - p.display() + display )); } if count > 1 { return Err(format!( "apply_patch_blocks: FIND matched {count} times in {} (must be unique)", - p.display() + display )); } src = src.replacen(&find, &replace, 1); applied += 1; } - fs::write(&p, src).map_err(|e| format!("apply_patch_blocks write {}: {e}", p.display()))?; + write_text(ctx,path,&Value::Text(src))?; Ok(Value::Int(applied)) } diff --git a/src/host/fs_ops.rs b/src/host/fs_ops.rs new file mode 100644 index 0000000..714d0ef --- /dev/null +++ b/src/host/fs_ops.rs @@ -0,0 +1,681 @@ +//! Bounded filesystem tasks. Public authors use lib/fs, lib/path and lib/bytes. +use super::{as_text, encoding, fs as legacy, result, sandbox_fs}; +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashMap, + fs, + io::{Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, +}; +type Args = HashMap; +const MAX_READ: usize = 64 * 1024 * 1024; +fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +fn text<'a>(b: &'a Args, k: &str) -> Result<&'a str, String> { + as_text(arg(b, k)?, k) +} +fn number(b: &Args, k: &str) -> Result { + match arg(b, k)? { + Value::Int(n) if *n >= 0 => Ok(*n as u64), + _ => Err(format!("{k} must be nonnegative integer")), + } +} +fn flag(b: &Args, k: &str) -> bool { + matches!(b.get(k), Some(Value::Bool(true))) +} +fn native(ctx: &HostContext) -> Result<(), String> { + if ctx.sandbox_session.is_some() { + Err("operation unavailable in CoW sandbox; use write_text/remove_file".into()) + } else { + Ok(()) + } +} +fn writable(ctx: &HostContext) -> Result<(), String> { + if ctx.allow_fs_write() { + Ok(()) + } else { + Err("filesystem write denied by host policy".into()) + } +} +fn path(ctx: &HostContext, b: &Args, k: &str) -> Result { + ctx.resolve_path(text(b, k)?) +} +fn ioerr(e: std::io::Error) -> String { + let code = match e.kind() { + std::io::ErrorKind::NotFound => "not_found", + std::io::ErrorKind::PermissionDenied => "permission_denied", + std::io::ErrorKind::AlreadyExists => "conflict", + _ => "operation_failed", + }; + format!("{code}: {e}") +} +fn limit(b: &Args, k: &str) -> Result { + let n = number(b, k)?; + if n == 0 || n > MAX_READ as u64 { + return Err(format!("{k} must be 1..{MAX_READ}")); + } + Ok(n as usize) +} +pub(super) fn bytes_value(bytes: &[u8]) -> Value { + Value::Map(vec![ + ("_type".into(), Value::Text("bytes".into())), + ("base64".into(), Value::Text(encoding::encode_base64(bytes))), + ]) +} +pub(super) fn bytes(v: &Value) -> Result, String> { + let Value::Map(fields) = v else { + return Err("expected bytes record from lib/bytes or fs.read_bytes".into()); + }; + if !fields + .iter() + .any(|(k, v)| k == "_type" && v == &Value::Text("bytes".into())) + { + return Err("expected _type bytes".into()); + } + let text = fields + .iter() + .find(|(k, _)| k == "base64") + .ok_or("missing bytes.base64")?; + encoding::decode_base64(as_text(&text.1, "base64")?) +} +fn read(ctx: &HostContext, p: &Path, max: usize) -> Result, String> { + let mut out = Vec::new(); + if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, p)? { + if bytes.len() > max { + return Err("file exceeds max_bytes".into()); + } + return Ok(bytes); + } + fs::File::open(p) + .map_err(ioerr)? + .take(max as u64 + 1) + .read_to_end(&mut out) + .map_err(ioerr)?; + if out.len() > max { + return Err("file exceeds max_bytes".into()); + } + Ok(out) +} +fn atomic(ctx: &HostContext, p: &Path, body: &[u8]) -> Result<(), String> { + writable(ctx)?; + if sandbox_fs::cow_write_bytes(ctx, p, body)? { + return Ok(()); + } + let parent = p.parent().ok_or("file needs parent")?; + fs::create_dir_all(parent).map_err(ioerr)?; + // create_new reserves the sibling name. Never truncate an existing temp file. + let mut reserved = None; + for _ in 0..128 { + let mut entropy = [0u8; 16]; + getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; + let name = entropy + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let temp = parent.join(format!(".mq-{name}.tmp")); + match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp) + { + Ok(file) => { + reserved = Some((temp, file)); + break; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(ioerr(e)), + } + } + let (temp, mut file) = reserved.ok_or("cannot reserve atomic write file")?; + let result = (|| { + file.write_all(body).map_err(ioerr)?; + file.sync_all().map_err(ioerr)?; + drop(file); + fs::rename(&temp, p).map_err(ioerr) + })(); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result +} +pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + let answer = match id { + HostFn::FsTryReadText => { + let answer = (|| { + let data = read(ctx, &path(ctx, b, "path")?, 8 * 1024 * 1024)?; + String::from_utf8(data) + .map(Value::Text) + .map_err(|e| format!("invalid_encoding: {e}")) + })(); + return Ok(result::capture("fs.read_text", answer)); + } + HostFn::FsTryWriteText => { + return Ok(result::capture( + "fs.write_text", + legacy::write_text(ctx, arg(b, "path")?, arg(b, "text")?), + )) + } + HostFn::TryJsonParse => { + return Ok(result::capture( + "json.parse", + super::json::parse(arg(b, "text")?).map_err(|e| format!("invalid_json: {e}")), + )) + } + HostFn::TryCsvParse => { + return Ok(result::capture( + "csv.parse", + super::csv::parse(arg(b, "text")?).map_err(|e| format!("invalid_csv: {e}")), + )) + } + HostFn::BytesFromText => bytes_value(text(b, "text")?.as_bytes()), + HostFn::BytesFromBase64 => bytes_value(&encoding::decode_base64(text(b, "text")?)?), + HostFn::BytesToText => Value::Text( + String::from_utf8(bytes(arg(b, "data")?)?) + .map_err(|e| format!("bytes are not UTF-8: {e}"))?, + ), + HostFn::BytesToBase64 => Value::Text(encoding::encode_base64(&bytes(arg(b, "data")?)?)), + HostFn::BytesLen => Value::Int(bytes(arg(b, "data")?)?.len() as i64), + HostFn::BytesSlice => { + let data = bytes(arg(b, "data")?)?; + let start = usize::try_from(number(b, "start")?) + .unwrap_or(usize::MAX) + .min(data.len()); + let end = usize::try_from(number(b, "end")?) + .unwrap_or(usize::MAX) + .min(data.len()); + bytes_value(if start > end { &[] } else { &data[start..end] }) + } + HostFn::FsReadBytes => { + bytes_value(&read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?) + } + HostFn::FsWriteBytes => { + let p = path(ctx, b, "path")?; + atomic(ctx, &p, &bytes(arg(b, "data")?)?)?; + Value::None + } + HostFn::FsReadChunk => { + let p = path(ctx, b, "path")?; + let offset = number(b, "offset")?; + let size = limit(b, "size")?; + let mut data = vec![0u8; size]; + let (n, total) = if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? { + let start = usize::try_from(offset) + .unwrap_or(usize::MAX) + .min(bytes.len()); + let end = start.saturating_add(size).min(bytes.len()); + data[..end - start].copy_from_slice(&bytes[start..end]); + (end - start, bytes.len() as u64) + } else { + let mut file = fs::File::open(&p).map_err(ioerr)?; + let total = file.metadata().map_err(ioerr)?.len(); + file.seek(SeekFrom::Start(offset)).map_err(ioerr)?; + let n = file.take(size as u64).read(&mut data).map_err(ioerr)?; + (n, total) + }; + data.truncate(n); + let next = offset.checked_add(n as u64).ok_or("offset overflow")?; + Value::Map(vec![ + ("data".into(), bytes_value(&data)), + ("next_offset".into(), Value::Int(next as i64)), + ("eof".into(), Value::Bool(next >= total)), + ]) + } + HostFn::FsAppendBytes => { + writable(ctx)?; + let p = path(ctx, b, "path")?; + let data = bytes(arg(b, "data")?)?; + if ctx.sandbox_session.is_some() { + let mut body = read(ctx, &p, MAX_READ).or_else(|e| { + if matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(false))) { + Ok(vec![]) + } else { + Err(e) + } + })?; + body.extend_from_slice(&data); + sandbox_fs::cow_write_bytes(ctx, &p, &body)?; + } else { + let mut f = fs::OpenOptions::new() + .create(true) + .append(true) + .open(&p) + .map_err(ioerr)?; + f.write_all(&data).map_err(ioerr)?; + } + Value::None + } + HostFn::FsAtomicWrite | HostFn::FsWriteChanged => { + let p = path(ctx, b, "path")?; + let body = text(b, "text")?.as_bytes(); + if id == HostFn::FsWriteChanged && read(ctx, &p, MAX_READ).ok().as_deref() == Some(body) + { + return Ok(Value::Bool(false)); + } + atomic(ctx, &p, body)?; + if id == HostFn::FsWriteChanged { + Value::Bool(true) + } else { + Value::None + } + } + HostFn::FsWriteChecked => { + let change = (|| { + let p = path(ctx, b, "path")?; + let expected = text(b, "expected_sha256")?; + let current = read(ctx, &p, MAX_READ)?; + let actual = format!("{:x}", Sha256::digest(¤t)); + if actual != expected { + return Err("conflict: file content changed".into()); + } + atomic(ctx, &p, text(b, "text")?.as_bytes()).map(|_| Value::None) + })(); + return Ok(result::capture("fs.write_checked", change)); + } + HostFn::FsReadLines => { + let data = read(ctx, &path(ctx, b, "path")?, limit(b, "max_bytes")?)?; + let text = String::from_utf8(data).map_err(|e| format!("file is not UTF-8: {e}"))?; + Value::List(text.lines().map(|s| Value::Text(s.into())).collect()) + } + HostFn::FsWriteLines => { + let Value::List(lines) = arg(b, "lines")? else { + return Err("lines must be list of text".into()); + }; + let lines = lines + .iter() + .map(|v| as_text(v, "line")) + .collect::, _>>()?; + let mut body = lines.join("\n"); + if !lines.is_empty() { + body.push('\n') + }; + atomic(ctx, &path(ctx, b, "path")?, body.as_bytes())?; + Value::None + } + HostFn::FsRemoveFile => { + writable(ctx)?; + let p = path(ctx, b, "path")?; + if p.is_dir() { + return Err("remove_file refuses directory".into()); + } + if !matches!(legacy::exists(ctx, arg(b, "path")?), Ok(Value::Bool(true))) { + return Err("not_found: remove_file target absent".into()); + } + if !sandbox_fs::cow_remove(ctx, &p)? { + fs::remove_file(p).map_err(ioerr)?; + } + Value::None + } + HostFn::FsRemoveEmptyDir => { + writable(ctx)?; + native(ctx)?; + fs::remove_dir(path(ctx, b, "path")?).map_err(ioerr)?; + Value::None + } + HostFn::FsTempDir => { + writable(ctx)?; + native(ctx)?; + let prefix = text(b, "prefix")?; + if prefix.contains('/') || prefix.contains('\\') || prefix.contains("..") { + return Err("temp prefix must be simple name".into()); + } + let mut created = None; + for _ in 0..128 { + let mut entropy = [0u8; 16]; + getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; + let name = format!( + "{prefix}-{}", + entropy + .iter() + .map(|n| format!("{n:02x}")) + .collect::() + ); + let p = ctx.resolve_path(&name)?; + match fs::create_dir(p) { + Ok(()) => { + created = Some(Value::Text(name)); + break; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(ioerr(e)), + } + } + created.ok_or("unable to reserve temporary directory")? + } + HostFn::FsFileHash => { + let p = path(ctx, b, "path")?; + let mut hasher = Sha256::new(); + if let Some(bytes) = sandbox_fs::cow_read_bytes(ctx, &p)? { + hasher.update(bytes) + } else { + let mut f = fs::File::open(p).map_err(ioerr)?; + let mut buffer = [0u8; 65536]; + loop { + let n = f.read(&mut buffer).map_err(ioerr)?; + if n == 0 { + break; + } + hasher.update(&buffer[..n]); + } + } + Value::Text(format!("{:x}", hasher.finalize())) + } + HostFn::FsFind => { + let root = path(ctx, b, "path")?; + let pattern = glob(text(b, "pattern")?)?; + let excluded = patterns(arg(b, "exclude")?)?; + let max_depth = number(b, "max_depth")? as usize; + let kind = text(b, "kind")?; + if !matches!(kind, "file" | "dir" | "all") { + return Err("find kind must be file/dir/all".into()); + } + let mut files = Vec::new(); + find( + ctx, + &root, + Path::new(""), + &pattern, + &excluded, + max_depth, + kind, + &mut files, + )?; + Value::List(files) + } + HostFn::FsCopyTree | HostFn::FsSyncTree => { + writable(ctx)?; + native(ctx)?; + let src = path(ctx, b, "src")?; + let dest = path(ctx, b, "dest")?; + if dest.starts_with(&src) || src.starts_with(&dest) { + return Err("copy/sync trees must be disjoint".into()); + } + if !src.is_dir() { + return Err("src must be directory".into()); + } + let excluded = patterns(arg(b, "exclude")?)?; + let mut files = Vec::new(); + find( + ctx, + &src, + Path::new(""), + &glob("**")?, + &excluded, + 256, + "file", + &mut files, + )?; + let mut jobs = Vec::new(); + for name in files { + let name = as_text(&name, "name")?; + let from = ctx.resolve_path(src.join(name).to_str().ok_or("non UTF-8 path")?)?; + let to = ctx.resolve_path(dest.join(name).to_str().ok_or("non UTF-8 path")?)?; + if to.exists() { + if id == HostFn::FsSyncTree && files_equal(&from, &to)? { + continue; + } + if !flag(b, "overwrite") { + return Err(format!("destination conflict: {}", to.display())); + } + } + jobs.push((from, to, name.to_string())); + } + let dry = flag(b, "dry_run"); + let mut changed = Vec::new(); + for (from, to, name) in jobs { + if !dry { + if let Some(parent) = to.parent() { + fs::create_dir_all(parent).map_err(ioerr)?; + } + fs::copy(from, to).map_err(ioerr)?; + } + changed.push(Value::Text(name)); + } + Value::List(changed) + } + HostFn::FsRenameMany => { + writable(ctx)?; + native(ctx)?; + let Value::List(rows) = arg(b, "moves")? else { + return Err("moves must be record list".into()); + }; + let mut jobs = Vec::new(); + let mut destinations = std::collections::HashSet::new(); + let mut sources = std::collections::HashSet::new(); + for row in rows { + let Value::Map(fields) = row else { + return Err("move needs src,dest".into()); + }; + let mut paths = Vec::new(); + for key in ["src", "dest"] { + let value = fields + .iter() + .find(|(k, _)| k == key) + .ok_or("move needs src,dest")?; + paths.push(ctx.resolve_path(as_text(&value.1, key)?)?); + } + if !paths[0].is_file() { + return Err("rename_many source must be file".into()); + } + if !sources.insert(paths[0].clone()) { + return Err("conflict: repeated rename source".into()); + } + if paths[1].exists() || !destinations.insert(paths[1].clone()) { + return Err("rename_many destination conflict".into()); + } + jobs.push((paths.remove(0), paths.remove(0))); + } + // Preflight all paths. Execution is ordered and deliberately not transactional. + if !flag(b, "dry_run") { + for (from, to) in &jobs { + if let Some(parent) = to.parent() { + fs::create_dir_all(parent).map_err(ioerr)?; + } + fs::rename(from, to).map_err(ioerr)?; + } + } + Value::Int(jobs.len() as i64) + } + HostFn::PathRelative => { + let normalized = super::path::normalize(arg(b, "path")?)?; + let normalized_base = super::path::normalize(arg(b, "base")?)?; + let path = PathBuf::from(as_text(&normalized, "path")?); + let base = PathBuf::from(as_text(&normalized_base, "base")?); + if path.is_absolute() != base.is_absolute() { + return Err("relative paths must share absolute/relative form".into()); + } + let a: Vec<_> = path.components().collect(); + let b: Vec<_> = base.components().collect(); + if path.is_absolute() && a.first() != b.first() { + return Err("relative paths have different roots".into()); + } + let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count(); + let mut out = PathBuf::new(); + for _ in common..b.len() { + out.push("..") + } + for c in &a[common..] { + out.push(c.as_os_str()) + } + Value::Text(if out.as_os_str().is_empty() { + ".".into() + } else { + out.to_string_lossy().replace('\\', "/") + }) + } + HostFn::PathWithExtension => { + let mut p = PathBuf::from(text(b, "path")?); + let ext = text(b, "extension")?; + if ext.contains('/') || ext.contains('\\') { + return Err("extension cannot contain path separator".into()); + } + p.set_extension(ext.trim_start_matches('.')); + Value::Text(p.to_string_lossy().replace('\\', "/")) + } + _ => return Err("not a filesystem task".into()), + }; + Ok(answer) +} +fn patterns(v: &Value) -> Result, String> { + if matches!(v, Value::None) { + return Ok(vec![]); + } + let Value::List(xs) = v else { + return Err("exclude must be list of patterns".into()); + }; + xs.iter().map(|v| glob(as_text(v, "pattern")?)).collect() +} +fn glob(pattern: &str) -> Result { + let mut out = String::from("^"); + let mut cs = pattern.chars().peekable(); + while let Some(c) = cs.next() { + match c { + '*' => { + if cs.peek() == Some(&'*') { + cs.next(); + if cs.peek() == Some(&'/') { + cs.next(); + out.push_str("(?:.*/)?") + } else { + out.push_str(".*") + } + } else { + out.push_str("[^/]*") + } + } + '?' => out.push_str("[^/]"), + _ => out.push_str(®ex::escape(&c.to_string())), + } + } + out.push('$'); + regex::Regex::new(&out).map_err(|e| e.to_string()) +} +fn find( + ctx: &HostContext, + root: &Path, + rel: &Path, + pattern: ®ex::Regex, + exclude: &[regex::Regex], + depth: usize, + kind: &str, + out: &mut Vec, +) -> Result<(), String> { + if depth == 0 { + return Ok(()); + } + let mut entries = fs::read_dir(root.join(rel)) + .map_err(ioerr)? + .collect::, _>>() + .map_err(ioerr)?; + entries.sort_by_key(|e| e.file_name()); + for entry in entries { + let child = rel.join(entry.file_name()); + let name = child.to_string_lossy().replace('\\', "/"); + let ty = entry.file_type().map_err(ioerr)?; + if exclude + .iter() + .any(|r| r.is_match(&name) || r.is_match(&format!("{name}/"))) + { + continue; + } + // No symlink traversal. Reads returned by this finder still use resolve_path. + if ty.is_symlink() { + continue; + } + ctx.resolve_path(entry.path().to_str().ok_or("non UTF-8 path")?)?; + if pattern.is_match(&name) + && ((ty.is_file() && kind != "dir") || (ty.is_dir() && kind != "file")) + { + if out.len() >= 100_000 { + return Err("find exceeds 100000 entries".into()); + } + out.push(Value::Text(name)) + } + if ty.is_dir() { + find(ctx, root, &child, pattern, exclude, depth - 1, kind, out)? + } + } + Ok(()) +} + +fn files_equal(a: &Path, b: &Path) -> Result { + if fs::metadata(a).map_err(ioerr)?.len() != fs::metadata(b).map_err(ioerr)?.len() { + return Ok(false); + } + let mut a = std::io::BufReader::new(fs::File::open(a).map_err(ioerr)?); + let mut b = std::io::BufReader::new(fs::File::open(b).map_err(ioerr)?); + use std::io::BufRead; + loop { + let left = a.fill_buf().map_err(ioerr)?; + let right = b.fill_buf().map_err(ioerr)?; + if left.is_empty() || right.is_empty() { + return Ok(left.is_empty() && right.is_empty()); + } + let n = left.len().min(right.len()); + if left[..n] != right[..n] { + return Ok(false); + } + a.consume(n); + b.consume(n); + } +} + +#[cfg(test)] +mod overlay_tests { + use super::*; + #[test] + fn byte_append_copy_and_patch_stay_in_the_overlay_until_commit() { + let root = std::env::temp_dir().join(format!("mq-byte-overlay-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + fs::write(root.join("note.md"), "old text").unwrap(); + let mut ctx = + HostContext::for_run(Some(&root.join("main.mq.md")), Default::default(), vec![]); + let session = sandbox_fs::open(Some(root.to_str().unwrap()), &ctx).unwrap(); + let id = session["id"].as_str().unwrap().to_string(); + ctx.sandbox_session = Some(id.clone()); + legacy::text_patch( + &ctx, + &Value::Text("note.md".into()), + &Value::Text("old".into()), + &Value::Text("new".into()), + ) + .unwrap(); + assert_eq!( + fs::read_to_string(root.join("note.md")).unwrap(), + "old text" + ); + assert_eq!( + legacy::read_text(&ctx, &Value::Text("note.md".into())).unwrap(), + Value::Text("new text".into()) + ); + let mut args = Args::from([ + ("path".into(), Value::Text("data.bin".into())), + ("data".into(), bytes_value(&[0, 255])), + ]); + call(&mut ctx, HostFn::FsWriteBytes, &args).unwrap(); + args.insert("data".into(), bytes_value(&[128])); + call(&mut ctx, HostFn::FsAppendBytes, &args).unwrap(); + legacy::copy_file( + &ctx, + &Value::Text("data.bin".into()), + &Value::Text("copied.bin".into()), + ) + .unwrap(); + assert_eq!( + sandbox_fs::cow_read_bytes(&ctx, &root.join("copied.bin")) + .unwrap() + .unwrap(), + [0, 255, 128] + ); + assert!(!root.join("data.bin").exists()); + assert!(!root.join("copied.bin").exists()); + assert!(legacy::make_dirs(&ctx, &Value::Text("unsupported".into())).is_err()); + assert!(!root.join("unsupported").exists()); + sandbox_fs::discard(&id).unwrap(); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/src/host/mod.rs b/src/host/mod.rs index ef041cf..34feb78 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -276,21 +276,46 @@ impl HostContext { self.cwd.join(p) }; if let Some(root) = &self.fs_root { - let root_canon = root.canonicalize().unwrap_or_else(|_| root.clone()); - let check = abs.canonicalize().unwrap_or_else(|_| abs.clone()); - if !path_under_root(&check, &root_canon) && !path_under_root(&abs, root) { - if let Some(parent) = abs.parent() { - let parent_ok = parent - .canonicalize() - .map(|p| path_under_root(&p, &root_canon)) - .unwrap_or_else(|_| path_under_root(parent, root)); - if !parent_ok { - return Err(format!("path escapes sandbox root: {}", abs.display())); - } - } else { - return Err(format!("path escapes sandbox root: {}", abs.display())); + let abs = if abs.is_absolute() { abs } else { + std::env::current_dir().map_err(|e|e.to_string())?.join(abs) + }; + let root = root.canonicalize().map_err(|e| format!("filesystem root: {e}"))?; + // Normalize before checking, including destinations that do not exist yet. + let mut lexical = PathBuf::new(); + for component in abs.components() { + match component { + std::path::Component::CurDir => {}, + std::path::Component::ParentDir => { lexical.pop(); }, + component => lexical.push(component.as_os_str()), } } + if !lexical.is_absolute() { + lexical = std::env::current_dir().map_err(|e| e.to_string())?.join(lexical); + } + if !lexical.starts_with(&root) { + return Err(format!("path escapes sandbox root: {}", abs.display())); + } + // The nearest existing ancestor must also be inside root: a symlink + // cannot authorize writes through a not-yet-existing descendant. + let mut ancestor = lexical.as_path(); + loop { + match ancestor.canonicalize() { + Ok(real) => { + if !real.starts_with(&root) { + return Err(format!("path escapes sandbox root: {}", abs.display())); + } + break; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if ancestor.symlink_metadata().is_ok() { + return Err(format!("unresolvable symlink: {}", ancestor.display())); + } + ancestor = ancestor.parent().ok_or_else(|| "invalid file path".to_string())?; + } + Err(e) => return Err(format!("resolve path {}: {e}", abs.display())), + } + } + return Ok(lexical); } Ok(abs) } @@ -320,3 +345,19 @@ pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> R } Ok(()) } + +mod collection_ops; + +mod result; + +mod fs_ops; + +mod document; + +mod net_ops; + +mod data_ops; + +mod task_ops; + +mod archive; diff --git a/src/host/net_ops.rs b/src/host/net_ops.rs new file mode 100644 index 0000000..da95b3f --- /dev/null +++ b/src/host/net_ops.rs @@ -0,0 +1,201 @@ +//! Configurable bounded HTTP with one recoverable Result envelope. +#[cfg(feature = "net-host")] +use super::as_text; +use super::result; +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use std::collections::HashMap; +#[cfg(feature = "net-host")] +use std::{ + io::{Read, Write}, + time::Duration, +}; +type Args = HashMap; +#[cfg(feature = "net-host")] +fn arg<'a>(b: &'a Args, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +pub(super) fn call(ctx: &mut HostContext, id: HostFn, b: &Args) -> Result { + #[cfg(feature = "net-host")] + let answer = request(ctx, id, b); + #[cfg(not(feature = "net-host"))] + let answer = { + let _ = (ctx, id, b); + Err("HTTP unavailable in this build".into()) + }; + Ok(result::capture( + if id == HostFn::HttpDownload { + "net.download" + } else { + "net.request" + }, + answer, + )) +} +#[cfg(feature = "net-host")] +fn integer(b: &Args, k: &str, max: u64) -> Result { + match arg(b, k)? { + Value::Int(n) if *n > 0 && (*n as u64) <= max => Ok(*n as u64), + _ => Err(format!("{k} must be 1..{max}")), + } +} +#[cfg(feature = "net-host")] +fn request(ctx: &HostContext, id: HostFn, b: &Args) -> Result { + if !ctx.allow_net() { + return Err("network denied by host policy".into()); + } + let url = as_text(arg(b, "url")?, "url")?; + if !(url.starts_with("https://") || url.starts_with("http://")) { + return Err("url must use http/https".into()); + } + let timeout = Duration::from_millis(integer(b, "timeout_ms", 600000)?); + let max = integer(b, "max_bytes", 1024 * 1024 * 1024)?; + let method = if matches!(id, HostFn::HttpDownload | HostFn::HttpGetResult) { + "GET" + } else { + as_text(arg(b, "method")?, "method")? + }; + if !matches!( + method, + "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" + ) { + return Err("unsupported method".into()); + } + // Reject invalid output settings and destinations before any HTTP exchange. + let destination = if id == HostFn::HttpDownload { + if !ctx.allow_fs_write() { + return Err("filesystem write denied by host policy".into()); + } + if ctx.sandbox_session.is_some() { + return Err("unsupported: stream download in CoW sandbox".into()); + } + let path = ctx.resolve_path(as_text(arg(b, "path")?, "path")?)?; + if path.is_dir() { + return Err("invalid_argument: download destination is a directory".into()); + } + Some(path) + } else { + if max > 64 * 1024 * 1024 { + return Err( + "resource_limit: in-memory response limit exceeds 64 MiB; use download".into(), + ); + } + if !matches!(as_text(arg(b, "response")?, "response")?, "text" | "bytes") { + return Err("invalid_argument: response must be text or bytes".into()); + } + None + }; + let agent = ureq::AgentBuilder::new() + .timeout(timeout) + .timeout_connect(timeout) + .timeout_read(timeout) + .timeout_write(timeout) + .build(); + let mut request = agent.request(method, url).set("User-Agent", "marqdo"); + if let Some(Value::Map(headers)) = b.get("headers") { + for (k, v) in headers { + request = request.set(k, as_text(v, "header value")?) + } + } else if !matches!(b.get("headers"), None | Some(Value::None)) { + return Err("headers must be map or None".into()); + } + let exchange = match b.get("body") { + None | Some(Value::None) => request.call(), + Some(Value::Text(text)) => request.send_bytes(text.as_bytes()), + Some(v) => request.send_bytes(&super::fs_ops::bytes(v)?), + }; + let response = match exchange { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(e) => return Err(format!("transport_error: {e}")), + }; + let status = response.status(); + let mut headers = Vec::new(); + for name in response.headers_names() { + let values = response + .all(&name) + .into_iter() + .map(|v| Value::Text(v.into())) + .collect(); + headers.push(Value::Map(vec![ + ("name".into(), Value::Text(name.to_ascii_lowercase())), + ("values".into(), Value::List(values)), + ])); + } + let mut reader = response.into_reader(); + if id == HostFn::HttpDownload { + if !(200..300).contains(&status) { + return Err(format!("http_status: {status}; destination unchanged")); + } + let path = destination.ok_or("missing validated download destination")?; + let parent = path.parent().ok_or("destination needs parent")?; + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let mut entropy = [0u8; 16]; + getrandom::getrandom(&mut entropy).map_err(|e| e.to_string())?; + let token = entropy + .iter() + .map(|n| format!("{n:02x}")) + .collect::(); + let temp = parent.join(format!(".mq-download-{token}")); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp) + .map_err(|e| e.to_string())?; + let downloaded = (|| { + let mut total = 0u64; + let mut buffer = [0u8; 65536]; + loop { + let n = reader.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + total += n as u64; + if total > max { + return Err("resource_limit: HTTP response exceeds max_bytes".into()); + } + file.write_all(&buffer[..n]).map_err(|e| e.to_string())?; + } + file.sync_all().map_err(|e| e.to_string())?; + drop(file); + std::fs::rename(&temp, &path).map_err(|e| e.to_string())?; + Ok(total) + })(); + let total = match downloaded { + Ok(n) => n, + Err(e) => { + let _ = std::fs::remove_file(temp); + return Err(e); + } + }; + return Ok(Value::Map(vec![ + ("status".into(), Value::Int(status as i64)), + ("headers".into(), Value::List(headers)), + ("size".into(), Value::Int(total as i64)), + ("path".into(), arg(b, "path")?.clone()), + ])); + } + let mut bytes = Vec::new(); + reader + .take(max + 1) + .read_to_end(&mut bytes) + .map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err("resource_limit: HTTP response exceeds max_bytes".into()); + } + let mode = as_text(arg(b, "response")?, "response")?; + let body = match mode { + "text" => Value::Text(String::from_utf8(bytes).map_err(|e| { + format!("invalid_encoding: response is not UTF-8; request bytes instead: {e}") + })?), + "bytes" => super::fs_ops::bytes_value(&bytes), + _ => return Err("response must be text or bytes".into()), + }; + Ok(Value::Map(vec![ + ("status".into(), Value::Int(status as i64)), + ("headers".into(), Value::List(headers)), + ("body".into(), body), + ])) +} diff --git a/src/host/result.rs b/src/host/result.rs new file mode 100644 index 0000000..3045d27 --- /dev/null +++ b/src/host/result.rs @@ -0,0 +1,40 @@ +//! A recoverable failure is data; permission errors remain explicit failures. +use crate::value::Value; + +pub(super) fn capture(operation: &str, result: Result) -> Value { + let (ok, value, error) = match result { + Ok(value) => (true, value, Value::None), + Err(message) => { + let tagged = message.split_once(':').map(|(code, _)| code); + let code = match tagged { + Some( + code @ ("validation_failed" | "timed_out" | "permission_denied" | "not_found" + | "conflict" | "invalid_encoding" | "invalid_json" | "invalid_csv" + | "invalid_toml" | "transport_error" | "http_status" | "resource_limit" + | "unsupported" | "invalid_argument" | "nonexistent_time" + | "ambiguous_time"), + ) => code, + _ if message.starts_with("path escapes sandbox root:") + || message.ends_with("denied by host policy") => + { + "permission_denied" + } + _ => "operation_failed", + }; + ( + false, + Value::None, + Value::Map(vec![ + ("code".into(), Value::Text(code.into())), + ("message".into(), Value::Text(message)), + ("operation".into(), Value::Text(operation.into())), + ]), + ) + } + }; + Value::Map(vec![ + ("ok".into(), Value::Bool(ok)), + ("value".into(), value), + ("error".into(), error), + ]) +} diff --git a/src/host/sandbox_fs.rs b/src/host/sandbox_fs.rs index 16ffe3d..0872a5d 100644 --- a/src/host/sandbox_fs.rs +++ b/src/host/sandbox_fs.rs @@ -277,6 +277,25 @@ pub fn inspect(id: &str) -> Result { }) } +/// Byte-preserving overlay access shared by text and byte APIs. +pub(super) fn cow_read_bytes(ctx: &HostContext, abs: &Path) -> Result>, String> { + let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(None); }; + with_session(id, |session| { + let rel = rel_from_root(&session.root, abs)?; + if session.whiteout.contains(&rel) { return Err(format!("not found (sandbox whiteout): {rel}")); } + Ok(session.upper.get(&rel).cloned()) + }) +} +pub(super) fn cow_write_bytes(ctx: &HostContext, abs: &Path, bytes: &[u8]) -> Result { + let Some(id) = ctx.sandbox_session.as_deref() else { return Ok(false); }; + with_session_mut(id, |session| { + let rel = rel_from_root(&session.root, abs)?; + session.whiteout.remove(&rel); + session.upper.insert(rel, bytes.to_vec()); + Ok(true) + }) +} + /// Read file bytes through CoW for an active host sandbox session (lib/fs). pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result, String> { let Some(id) = ctx.sandbox_session.as_deref() else { diff --git a/src/host/subtask.rs b/src/host/subtask.rs index 2abf8fd..0dea516 100644 --- a/src/host/subtask.rs +++ b/src/host/subtask.rs @@ -302,6 +302,11 @@ fn spawn_file( )); let mut cmd = Command::new(&exe); cmd.arg("run").arg(&file); + if !ctx.caps.fs_write { cmd.arg("--deny-fs-write"); } + if !ctx.caps.exec { cmd.arg("--deny-exec"); } + if !ctx.caps.net { cmd.arg("--deny-net"); } + if !ctx.caps.plugin { cmd.arg("--deny-plugin"); } + if let Some(root) = &ctx.fs_root { cmd.arg("--fs-root").arg(root); } cmd.arg("--emit-result").arg(&result_path); cmd.current_dir(&ctx.cwd); cmd.stdin(Stdio::null()); @@ -340,18 +345,10 @@ fn spawn_file( let mut stdout_pipe = child.stdout.take(); let mut stderr_pipe = child.stderr.take(); let stdout = thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(ref mut r) = stdout_pipe { - let _ = r.read_to_end(&mut buf); - } - String::from_utf8_lossy(&buf).into_owned() + stdout_pipe.as_mut().map(capture_file_io).unwrap_or_default() }); let stderr = thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(ref mut r) = stderr_pipe { - let _ = r.read_to_end(&mut buf); - } - String::from_utf8_lossy(&buf).into_owned() + stderr_pipe.as_mut().map(capture_file_io).unwrap_or_default() }); (Some(stdout), Some(stderr)) } else { @@ -679,6 +676,54 @@ pub fn wait_all(ctx: &mut HostContext) -> Result { Ok(Value::List(results)) } +fn capture_file_io(reader:&mut impl Read)->String { + let mut kept=Vec::new(); let mut buffer=[0u8;8192]; + loop { match reader.read(&mut buffer) { + Ok(0)|Err(_)=>break, + Ok(n)=>{ let take=(FILE_IO_CAP+4-kept.len()).min(n);kept.extend_from_slice(&buffer[..take]); } + }} + clip_io(&String::from_utf8_lossy(&kept)) +} + +/// Timeout leaves the handle available unless cancel=True. Process cancellation +/// reaps the OS child; function-thread cancellation is logical, as in kill(). +pub(super) fn wait_timeout(ctx:&mut HostContext,id:&Value,timeout_ms:u64,cancel:bool)->Result{ + let start=std::time::Instant::now(); + loop{ + let status=poll(ctx,id)?; + let running=matches!(&status,Value::Map(fields) if fields.iter().any(|(k,v)|k=="status"&&v==&Value::Text("running".into()))); + if !running{return join(ctx,id)} + if start.elapsed()>=Duration::from_millis(timeout_ms){if cancel{kill(ctx,id)?;}return Err("timed_out: subtask wait deadline exceeded".into())} + thread::sleep(Duration::from_millis(5)); + } +} +pub(super) fn run_many(ctx:&mut HostContext,tasks:&Value,limit:usize,timeout_ms:u64)->Result{ + let Value::List(tasks)=tasks else{return Err("tasks must be record list".into())}; + if !(1..=64).contains(&limit){return Err("limit must be 1..64".into())} + if tasks.len()>10000{return Err("batch exceeds 10000 tasks".into())} + // Validate the entire batch before starting any process. + let jobs=tasks.iter().map(|task|{let Value::Map(fields)=task else{return Err("task must contain path and optional args".to_string())}; + let mut job=HashMap::new();for (key,value) in fields{if !matches!(key.as_str(),"path"|"args"){return Err(format!("unsupported batch field {key}"))}job.insert(key.clone(),value.clone());} + let path=job.get("path").ok_or("task missing path")?;ctx.resolve_path(as_text(path,"path")?)?;Ok(job) + }).collect::,String>>()?; + let mut active:Vec<(usize,Value,std::time::Instant)>=Vec::new();let mut next=0;let mut out=vec![Value::None;jobs.len()]; + while nextactive.push((next,id,std::time::Instant::now())),Err(error)=>out[next]=super::result::capture("subtask.run_many",Err(error))};next+=1; + } + let mut i=0; + while i=Duration::from_millis(timeout_ms){let(index,id,_)=active.remove(i);let _=kill(ctx,&id);out[index]=super::result::capture("subtask.run_many",Err("timed_out: batch task deadline exceeded".into()));} + else{i+=1;} + } + if !active.is_empty(){thread::sleep(Duration::from_millis(5));} + } + Ok(Value::List(out)) +} + fn clip_io(s: &str) -> String { let mut it = s.chars(); let head: String = it.by_ref().take(FILE_IO_CAP).collect(); diff --git a/src/host/task_ops.rs b/src/host/task_ops.rs new file mode 100644 index 0000000..b9cbe36 --- /dev/null +++ b/src/host/task_ops.rs @@ -0,0 +1,53 @@ +//! Bounded orchestration over existing subtask resources. +use crate::{ + host::{HostContext, HostFn}, + value::Value, +}; +use std::collections::HashMap; +#[cfg(feature = "exec-host")] +fn arg<'a>(b: &'a HashMap, k: &str) -> Result<&'a Value, String> { + b.get(k).ok_or_else(|| format!("missing {k}")) +} +pub(super) fn call( + ctx: &mut HostContext, + id: HostFn, + b: &HashMap, +) -> Result { + #[cfg(feature = "exec-host")] + { + fn integer(b: &HashMap, key: &str) -> Result { + match arg(b, key)? { + Value::Int(n) if *n >= 0 => Ok(*n as u64), + _ => Err(format!("{key} must be nonnegative integer")), + } + } + match id { + HostFn::SubtaskWaitTimeout => { + let answer = super::subtask::wait_timeout( + ctx, + arg(b, "id")?, + integer(b, "timeout_ms")?, + matches!(b.get("cancel"), Some(Value::Bool(true))), + ); + Ok(super::result::capture("subtask.wait_timeout", answer)) + } + HostFn::SubtaskCancelAll => { + let count = ctx.subtasks.len(); + super::subtask::kill_all(ctx); + Ok(Value::Int(count as i64)) + } + HostFn::SubtaskRunMany => super::subtask::run_many( + ctx, + arg(b, "tasks")?, + integer(b, "limit")? as usize, + integer(b, "timeout_ms")?, + ), + _ => Err("not a task operation".into()), + } + } + #[cfg(not(feature = "exec-host"))] + { + let _ = (ctx, id, b); + Err("subtask unavailable in this build".into()) + } +} diff --git a/src/host/toml_ops.rs b/src/host/toml_ops.rs index 1ca8384..75d0887 100644 --- a/src/host/toml_ops.rs +++ b/src/host/toml_ops.rs @@ -1,305 +1,38 @@ -//! Minimal TOML → Marqdo Value for Mid2 M8 (`lib/toml`). -//! Subset: comments, keys, strings, ints, floats, bools, arrays of scalars, -//! `[table]` / dotted tables. No datetime, inline tables, or array-of-tables. +//! Standards-based TOML; datetime scalars become explicit ISO text at Value boundary. +use crate::{host::as_text,value::Value}; -use crate::host::as_text; -use crate::host::json::json_to_value; -use crate::value::Value; - - -pub fn parse(text: &Value) -> Result { - let raw = as_text(text, "text")?; - let json = toml_to_json(raw)?; - json_to_value(&json) +pub fn parse(text: &Value) -> Result { + let parsed: toml::Value = toml::from_str(as_text(text,"text")?).map_err(|e|format!("toml.parse: {e}"))?; + fn convert(v: toml::Value) -> Result { + Ok(match v { + toml::Value::String(s) => Value::Text(s), + toml::Value::Integer(n) => Value::Int(n), + toml::Value::Float(n) if n.is_finite() => Value::Num(n), + toml::Value::Float(_) => return Err("toml: non-finite numbers unsupported".into()), + toml::Value::Boolean(b) => Value::Bool(b), + toml::Value::Datetime(dt) => Value::Text(dt.to_string()), + toml::Value::Array(xs) => Value::List(xs.into_iter().map(convert).collect::>()?), + toml::Value::Table(fields) => Value::Map(fields.into_iter().map(|(k,v)|convert(v).map(|v|(k,v))).collect::>()?), + }) + } + convert(parsed) } -fn toml_to_json(src: &str) -> Result { - let mut root = serde_json::Map::new(); - let mut current_path: Vec = Vec::new(); - for (lineno, line) in src.lines().enumerate() { - let line_no = lineno + 1; - let stripped = strip_comment(line); - let t = stripped.trim(); - if t.is_empty() { - continue; - } - if t.starts_with('[') { - if !t.ends_with(']') { - return Err(format!("toml.parse:{line_no}: bad table header")); - } - if t.starts_with("[[") { - return Err(format!( - "toml.parse:{line_no}: array-of-tables [[...]] not supported" - )); - } - let inner = t[1..t.len() - 1].trim(); - current_path = split_dotted_keys(inner, line_no)?; - ensure_table_path(&mut root, ¤t_path, line_no)?; - continue; - } - let (key, val) = t - .split_once('=') - .ok_or_else(|| format!("toml.parse:{line_no}: expected key = value"))?; - let key = key.trim(); - if key.is_empty() { - return Err(format!("toml.parse:{line_no}: empty key")); - } - let key_parts = split_dotted_keys(key, line_no)?; - let value = parse_value(val.trim(), line_no)?; - let parent = table_at_path(&mut root, ¤t_path, line_no)?; - insert_dotted(parent, &key_parts, value, line_no)?; +pub fn stringify(value:&Value)->Result{ + fn convert(v:&Value)->Result{ + Ok(match v { + Value::Text(s)=>toml::Value::String(s.clone()), + Value::Int(n)=>toml::Value::Integer(*n), + Value::Num(n) if n.is_finite()=>toml::Value::Float(*n), + Value::Bool(b)=>toml::Value::Boolean(*b), + Value::List(xs)=>toml::Value::Array(xs.iter().map(convert).collect::>()?), + Value::Map(fields)=>toml::Value::Table(fields.iter().map(|(k,v)|convert(v).map(|v|(k.clone(),v))).collect::>()?), + _=>return Err("toml.stringify supports text/finite numbers/bool/list/map; None has no TOML representation".into()), + }) } - Ok(serde_json::Value::Object(root)) + if !matches!(value,Value::Map(_)){return Err("toml root must be map".into())} + toml::to_string_pretty(&convert(value)?).map(Value::Text).map_err(|e|format!("toml.stringify: {e}")) } - -fn strip_comment(line: &str) -> String { - // Strip unquoted `#` comments. - let mut out = String::new(); - let mut in_str = false; - let mut chars = line.chars().peekable(); - while let Some(c) = chars.next() { - if !in_str && c == '#' { - break; - } - if c == '"' { - out.push(c); - in_str = !in_str; - continue; - } - if in_str && c == '\\' { - out.push(c); - if let Some(n) = chars.next() { - out.push(n); - } - continue; - } - out.push(c); - } - out -} - -fn split_dotted_keys(s: &str, line_no: usize) -> Result, String> { - let mut parts = Vec::new(); - let mut cur = String::new(); - let mut in_quote = false; - let mut chars = s.chars().peekable(); - while let Some(c) = chars.next() { - if c == '"' { - in_quote = !in_quote; - continue; - } - if c == '.' && !in_quote { - if cur.is_empty() { - return Err(format!("toml.parse:{line_no}: empty key segment")); - } - parts.push(std::mem::take(&mut cur)); - continue; - } - cur.push(c); - } - if in_quote { - return Err(format!("toml.parse:{line_no}: unclosed quoted key")); - } - if !cur.is_empty() { - parts.push(cur); - } - if parts.is_empty() { - return Err(format!("toml.parse:{line_no}: empty path")); - } - Ok(parts) -} - -fn ensure_table_path( - root: &mut serde_json::Map, - path: &[String], - line_no: usize, -) -> Result<(), String> { - let mut cur = root; - for seg in path { - if !cur.contains_key(seg) { - cur.insert(seg.clone(), serde_json::Value::Object(serde_json::Map::new())); - } - cur = match cur.get_mut(seg) { - Some(serde_json::Value::Object(m)) => m, - Some(_) => { - return Err(format!("toml.parse:{line_no}: {seg} is not a table")); - } - None => unreachable!(), - }; - } - Ok(()) -} - -fn table_at_path<'a>( - root: &'a mut serde_json::Map, - path: &[String], - line_no: usize, -) -> Result<&'a mut serde_json::Map, String> { - let mut cur = root; - for seg in path { - cur = match cur.get_mut(seg) { - Some(serde_json::Value::Object(m)) => m, - Some(_) => { - return Err(format!("toml.parse:{line_no}: {seg} is not a table")); - } - None => { - return Err(format!("toml.parse:{line_no}: missing table {seg}")); - } - }; - } - Ok(cur) -} - -fn insert_dotted( - parent: &mut serde_json::Map, - parts: &[String], - value: serde_json::Value, - line_no: usize, -) -> Result<(), String> { - if parts.len() == 1 { - if parent.contains_key(&parts[0]) { - return Err(format!( - "toml.parse:{line_no}: duplicate key {}", - parts[0] - )); - } - parent.insert(parts[0].clone(), value); - return Ok(()); - } - let head = &parts[0]; - let entry = parent - .entry(head.clone()) - .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())); - let obj = match entry { - serde_json::Value::Object(m) => m, - _ => { - return Err(format!("toml.parse:{line_no}: {head} is not a table")); - } - }; - insert_dotted(obj, &parts[1..], value, line_no) -} - -fn parse_value(s: &str, line_no: usize) -> Result { - if s.is_empty() { - return Err(format!("toml.parse:{line_no}: empty value")); - } - if s == "true" { - return Ok(serde_json::Value::Bool(true)); - } - if s == "false" { - return Ok(serde_json::Value::Bool(false)); - } - if s.starts_with('"') { - return Ok(serde_json::Value::String(parse_basic_string(s, line_no)?)); - } - if s.starts_with('\'') { - return Ok(serde_json::Value::String(parse_literal_string(s, line_no)?)); - } - if s.starts_with('[') { - return parse_array(s, line_no); - } - if let Ok(i) = s.replace('_', "").parse::() { - return Ok(serde_json::Value::Number(i.into())); - } - if let Ok(f) = s.replace('_', "").parse::() { - if let Some(n) = serde_json::Number::from_f64(f) { - return Ok(serde_json::Value::Number(n)); - } - } - Err(format!("toml.parse:{line_no}: unsupported value {s:?}")) -} - -fn parse_basic_string(s: &str, line_no: usize) -> Result { - if !s.ends_with('"') || s.len() < 2 { - return Err(format!("toml.parse:{line_no}: bad string")); - } - let inner = &s[1..s.len() - 1]; - let mut out = String::new(); - let mut chars = inner.chars(); - while let Some(c) = chars.next() { - if c == '\\' { - match chars.next() { - Some('n') => out.push('\n'), - Some('t') => out.push('\t'), - Some('r') => out.push('\r'), - Some('\\') => out.push('\\'), - Some('"') => out.push('"'), - Some(other) => { - return Err(format!( - "toml.parse:{line_no}: bad escape \\{other}" - )); - } - None => return Err(format!("toml.parse:{line_no}: trailing escape")), - } - } else { - out.push(c); - } - } - Ok(out) -} - -fn parse_literal_string(s: &str, line_no: usize) -> Result { - if !s.ends_with('\'') || s.len() < 2 { - return Err(format!("toml.parse:{line_no}: bad literal string")); - } - Ok(s[1..s.len() - 1].to_string()) -} - -fn parse_array(s: &str, line_no: usize) -> Result { - if !s.ends_with(']') { - return Err(format!("toml.parse:{line_no}: bad array")); - } - let inner = s[1..s.len() - 1].trim(); - if inner.is_empty() { - return Ok(serde_json::Value::Array(vec![])); - } - let mut items = Vec::new(); - let mut cur = String::new(); - let mut depth = 0i32; - let mut in_str = false; - let mut str_ch = '"'; - let mut chars = inner.chars().peekable(); - while let Some(c) = chars.next() { - if in_str { - cur.push(c); - if c == '\\' { - if let Some(n) = chars.next() { - cur.push(n); - } - continue; - } - if c == str_ch { - in_str = false; - } - continue; - } - match c { - '"' | '\'' => { - in_str = true; - str_ch = c; - cur.push(c); - } - '[' => { - depth += 1; - cur.push(c); - } - ']' => { - depth -= 1; - cur.push(c); - } - ',' if depth == 0 => { - items.push(parse_value(cur.trim(), line_no)?); - cur.clear(); - } - _ => cur.push(c), - } - } - if !cur.trim().is_empty() { - items.push(parse_value(cur.trim(), line_no)?); - } - Ok(serde_json::Value::Array(items)) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 104ac30..2e499d5 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -188,6 +188,24 @@ pub fn matching_bold_close_inline(trimmed: &str) -> Option { matching_bold_close_opts(trimmed, false) } +// An occlusion label is prose: stars, quotes and backticks inside it are not +// statement/return delimiters. Payload nesting is tracked by the callers. +fn occlusion_payload_start(bytes: &[u8], start: usize) -> Option { + if bytes.get(start) != Some(&b'[') { + return None; + } + let mut i = start + 1; + while i < bytes.len() { + match bytes[i] { + b'\\' => i += 2, + b']' => return (bytes.get(i + 1) == Some(&b'(')).then_some(i + 1), + b'\n' | b'\r' => return None, + _ => i += 1, + } + } + None +} + fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option { let Some(rest) = trimmed.strip_prefix("**") else { return None; @@ -196,6 +214,7 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option { let mut i = 0usize; let mut in_bt = false; let mut in_str = false; + let mut nesting = Vec::new(); while i + 1 < bytes.len() { let c = bytes[i]; if in_str { @@ -216,7 +235,27 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option { i += 1; continue; } + if c == b'[' { + if let Some(payload) = occlusion_payload_start(bytes, i) { + i = payload; + continue; + } + } match c { + b'(' | b'[' | b'{' => { + nesting.push(match c { + b'(' => b')', + b'[' => b']', + _ => b'}', + }); + i += 1; + } + b')' | b']' | b'}' => { + if nesting.last() == Some(&c) { + nesting.pop(); + } + i += 1; + } b'`' => { in_bt = true; i += 1; @@ -225,7 +264,7 @@ fn matching_bold_close_opts(trimmed: &str, require_eol: bool) -> Option { in_str = true; i += 1; } - b'*' if bytes[i + 1] == b'*' => { + b'*' if bytes[i + 1] == b'*' && nesting.is_empty() => { let after = i + 2; if !require_eol || rest[after..].trim().is_empty() { return Some(2 + i); @@ -260,6 +299,7 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option let mut i = 1usize; // skip opening * let mut in_bt = false; let mut in_str = false; + let mut nesting = Vec::new(); while i < bytes.len() { let c = bytes[i]; if in_str { @@ -280,7 +320,27 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option i += 1; continue; } + if c == b'[' { + if let Some(payload) = occlusion_payload_start(bytes, i) { + i = payload; + continue; + } + } match c { + b'(' | b'[' | b'{' => { + nesting.push(match c { + b'(' => b')', + b'[' => b']', + _ => b'}', + }); + i += 1; + } + b')' | b']' | b'}' => { + if nesting.last() == Some(&c) { + nesting.pop(); + } + i += 1; + } b'`' => { in_bt = true; i += 1; @@ -289,7 +349,7 @@ fn matching_italic_close_opts(trimmed: &str, require_eol: bool) -> Option in_str = true; i += 1; } - b'*' => { + b'*' if nesting.is_empty() => { if !require_eol || trimmed[i + 1..].trim().is_empty() { return Some(i); } @@ -723,3 +783,15 @@ mod tests { assert_eq!(lines[4].kind, LineKind::Code, "assign recovers after bad line"); } } + +#[cfg(test)] +mod inline_occlusion_boundaries { + use super::*; + #[test] + fn prose_stars_and_payload_products_keep_the_real_return_boundary() { + let source = r#"*[multiply x*y and keep "raw" text](2 * (3 + 1))* after the result"#; + assert_eq!(matching_italic_close_inline(source), source.find("* after")); + let source = r#"**answer = [render **literal** marker](helper(text="**", value=(2 * 3)))** then continue"#; + assert_eq!(matching_bold_close_inline(source), source.find("** then")); + } +} diff --git a/src/main.rs b/src/main.rs index 82efaaa..23299b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -120,6 +120,19 @@ enum Commands { #[arg(long = "fs-root", value_name = "DIR")] fs_root: Option, + /// Deny filesystem writes in this run and its file subtasks. + #[arg(long)] + deny_fs_write: bool, + /// Deny process execution. + #[arg(long)] + deny_exec: bool, + /// Deny network access. + #[arg(long)] + deny_net: bool, + /// Deny native plugin loading. + #[arg(long)] + deny_plugin: bool, + /// Isolated worker: call `lib.member` on the site entry instead of `# main`. #[arg(long = "call-lib-path", value_name = "LIB.MEMBER")] call_lib_path: Option, @@ -158,10 +171,14 @@ enum Commands { #[arg(long, value_enum, default_value_t = BackendCli::Tree)] backend: BackendCli, - /// Side effects this call may perform (`none` = pure only; `plugin` allows ABI plugins). + /// Comma-separated effect grants: none, plugin, fs.read, fs.write, output.write, etc. #[arg(long, default_value = "none")] effects: String, + /// Directory available to file tools; defaults to the called file directory. + #[arg(long)] + fs_root: Option, + /// Call-session id for `toget` / `$name` (default: env `MARQDO_CALL_SESSION` or `default`). #[arg(long)] session: Option, @@ -769,6 +786,10 @@ fn try_main(cli: Cli) -> Result { args_json, json: _, legacy_markup, + deny_fs_write, + deny_exec, + deny_net, + deny_plugin, } => { let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); let stdin_lines = match stdin_file { @@ -809,6 +830,10 @@ fn try_main(cli: Cli) -> Result { ..RunOptions::default() } }; + opts.allow_fs_write = !deny_fs_write; + opts.allow_exec = !deny_exec; + opts.allow_net = !deny_net; + opts.allow_plugin = !deny_plugin; if dump_all { opts.backend = backend.into(); } @@ -828,6 +853,7 @@ fn try_main(cli: Cli) -> Result { json, backend, effects, + fs_root, session, toget, } => { @@ -858,6 +884,7 @@ fn try_main(cli: Cli) -> Result { backend.into(), marqdo::call::CallOptions { effects, + fs_root, session, toget, }, diff --git a/src/narrative_ratio.rs b/src/narrative_ratio.rs index cdab534..71442ef 100644 --- a/src/narrative_ratio.rs +++ b/src/narrative_ratio.rs @@ -94,44 +94,86 @@ fn collect_starts(fns: &[Function], out: &mut Vec<(String, u32, usize)>) { /// Split a function unit's source into narrative vs code character counts. /// -/// Code: lines that are primarily executable markers (`>`, `**`, `*…*`, `+`, tables with `|`, -/// fences, `#`/`##` headings themselves). Narrative: remaining prose (including formula fences -/// content is counted as narrative — formulas are documentation). +/// Count executable inline payloads separately from the sentences containing them. +/// Occlusion labels and unbound contract/documentation tables are narration; +/// bound data tables, expression payloads, code fences and structure markers are code. +/// Display formulas retain the existing documentation treatment. pub fn split_narrative_code(chunk: &str) -> (usize, usize) { + use crate::parse::{scan_md_links_in_line, scan_prose_line, ProseBit}; let mut narrative = 0usize; let mut code = 0usize; let mut in_fence = false; let mut fence_is_formula = false; + let mut pending_table = false; + let mut data_table = false; for line in chunk.lines() { let trimmed = line.trim(); + let count = line.chars().count(); if trimmed.starts_with("```") || trimmed.starts_with("~~~") { in_fence = !in_fence; fence_is_formula = trimmed.contains("$$") || trimmed == "$$"; - // Fence markers themselves are markup/code budget. - code += line.chars().count(); + code += count; continue; } if in_fence { - // Math/display fences count as narration; language fences as code. if fence_is_formula { - narrative += line.chars().count(); + narrative += count; } else { - code += line.chars().count(); + code += count; } continue; } if trimmed.is_empty() { + data_table = false; continue; } - // Standalone $$ formula blocks (Marqdo formula assignment bodies). - if trimmed == "$$" || trimmed.starts_with("$$") { - narrative += line.chars().count(); + if trimmed.starts_with('|') { + if pending_table { + data_table = true; + pending_table = false; + } + if data_table { + code += count; + } else { + narrative += count; + } continue; } - if is_code_line(trimmed) { - code += line.chars().count(); + data_table = false; + pending_table = (trimmed.starts_with('`') && trimmed.ends_with('=')) + || (trimmed.starts_with("**") + && trimmed.ends_with("**") + && trimmed[2..trimmed.len() - 2].trim_end().ends_with('=')); + if trimmed.starts_with("$$") { + narrative += count; + continue; + } + let mut inline_code = 0; + for bit in scan_prose_line(line) { + let (inner, markers) = match bit { + ProseBit::BoldCode { inner, .. } => (inner, 4), + ProseBit::ItalicReturn { inner, .. } => (inner, 2), + ProseBit::Decl { .. } => continue, + }; + let labels: usize = scan_md_links_in_line(&inner, 0) + .iter() + .map(|link| link.label.chars().count()) + .sum(); + inline_code += (inner.chars().count() + markers).saturating_sub(labels); + } + if inline_code > 0 { + let actual = inline_code.min(count); + code += actual; + narrative += count - actual; + } else if is_code_line(trimmed) || pending_table { + let labels: usize = scan_md_links_in_line(line, 0) + .iter() + .map(|link| link.label.chars().count()) + .sum(); + narrative += labels.min(count); + code += count.saturating_sub(labels); } else { - narrative += line.chars().count(); + narrative += count; } } (narrative, code) @@ -200,10 +242,7 @@ This paragraph keeps narration above half even with a small table. *None* "#; let (n, c) = split_narrative_code(chunk); - assert!( - (n as f64) / ((n + c) as f64) >= 0.5, - "n={n} c={c}" - ); + assert!((n as f64) / ((n + c) as f64) >= 0.5, "n={n} c={c}"); } #[test] @@ -214,9 +253,30 @@ This paragraph keeps narration above half even with a small table. *> quantum_h circuit=`self` qubit=`qubit`* "#; let (n, c) = split_narrative_code(chunk); - assert!( - (n as f64) / ((n + c) as f64) < 0.5, - "n={n} c={c}" + assert!((n as f64) / ((n + c) as f64) < 0.5, "n={n} c={c}"); + } +} + +#[cfg(test)] +mod inline_measurement_tests { + use super::*; + #[test] + fn inline_expressions_are_not_all_prose() { + let (n, c) = + split_narrative_code("Now **out = [Read the value](lookup(key=\"selected\"))**."); + assert_eq!( + n, + "Now .".chars().count() + "Read the value".chars().count() ); + assert!(c > n); + } + #[test] + fn bound_data_is_code_but_contracts_are_narration() { + let table = "| field | value |\n|---|---|\n| example | item |"; + let (n, c) = split_narrative_code(table); + assert!(n > 0 && c == 0); + let (n, c) = split_narrative_code(&format!("`record` =\n\n{table}")); + assert_eq!(n, 0); + assert!(c > 0); } } diff --git a/src/parse/mod.rs b/src/parse/mod.rs index bc28e8f..e12f06d 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -2470,7 +2470,34 @@ fn split_table_row(line: &str) -> Vec { let t = line.trim(); let t = t.strip_prefix('|').unwrap_or(t); let t = t.strip_suffix('|').unwrap_or(t); - t.split('|').map(|c| c.trim().to_string()).collect() + // GFM escaped pipes belong to a cell, including inside a quoted value. + // Preserve other escapes for the expression parser (e.g. \n in text). + let mut cells = Vec::new(); + let mut cell = String::new(); + let mut chars = t.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '\\' { + match chars.peek().copied() { + Some('|') => { + chars.next(); + cell.push('|'); + } + Some('\\') => { + chars.next(); + cell.push('\\'); + cell.push('\\'); + } + _ => cell.push(ch), + } + } else if ch == '|' { + cells.push(cell.trim().to_string()); + cell.clear(); + } else { + cell.push(ch); + } + } + cells.push(cell.trim().to_string()); + cells } #[cfg(test)] @@ -2886,3 +2913,21 @@ pub const CORE_CONSTRUCTS: &[(&str, &str)] = &[ ("footnote-index", "集合[^键]"), ("soft-emphasis", "*仅* / **说明**"), ]; + +#[cfg(test)] +mod escaped_gfm_cell_tests { + use super::*; + #[test] + fn escaped_pipes_do_not_create_columns() { + assert_eq!( + split_table_row(r#"| "source\|skill" | "line\n" |"#), + [r#""source|skill""#, r#""line\n""#] + ); + assert_eq!(split_table_row(r"| a\\| b |"), [r"a\\", "b"]); + let module = parse_source( + "## value\n\n`items` =\n\n| line |\n|---|\n| \"source\\|skill\" |\n\n*items*\n", + ) + .unwrap(); + assert!(format!("{:?}", module.functions[0].body).contains("source|skill")); + } +} diff --git a/src/parse/prose.rs b/src/parse/prose.rs index 6c4e078..672b6da 100644 --- a/src/parse/prose.rs +++ b/src/parse/prose.rs @@ -290,12 +290,32 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> { let after_tick = start + 1 + end + 1; let after = line.get(after_tick..)?; if let Some(stripped) = after.strip_prefix('=') { - let def_end = stripped - .find(|c: char| { - c.is_whitespace() - || matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`') - }) - .unwrap_or(stripped.len()); + // Quoted defaults may contain prose delimiters, glob stars or spaces. + // Keep the same quoted literal accepted by explicit parameter defaults. + let def_end = if let Some(quote @ ('"' | '\'')) = stripped.chars().next() { + let mut escaped = false; + stripped + .char_indices() + .skip(1) + .find_map(|(i, ch)| { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == quote { + return Some(i + ch.len_utf8()); + } + None + }) + .unwrap_or(stripped.len()) + } else { + stripped + .find(|c: char| { + c.is_whitespace() + || matches!(c, ',' | '。' | ';' | '、' | ',' | ';' | '*' | '`') + }) + .unwrap_or(stripped.len()) + }; let default = stripped[..def_end].to_string(); let next = after_tick + 1 + def_end; return Some(( @@ -369,6 +389,27 @@ mod tests { } } + #[test] + fn quoted_defaults_keep_delimiters_and_escaped_quotes() { + let line = r#"输入 `pattern`="**";`mime`="text/plain;charset=utf-8";`label`="a, b \"quoted\""。"#; + let bits = scan_prose_line(line); + let defaults: Vec<_> = bits + .iter() + .filter_map(|bit| match bit { + ProseBit::Decl { name, default, .. } => Some((name.as_str(), default.as_deref())), + _ => None, + }) + .collect(); + assert_eq!( + defaults, + vec![ + ("pattern", Some(r#""**""#)), + ("mime", Some(r#""text/plain;charset=utf-8""#)), + ("label", Some(r#""a, b \"quoted\"""#)) + ] + ); + } + #[test] fn soft_bold_emphasis_skipped() { let bits = scan_prose_line("本文件既是**说明**也是**程序**。"); diff --git a/src/sema/bind.rs b/src/sema/bind.rs index b8ce769..024d824 100644 --- a/src/sema/bind.rs +++ b/src/sema/bind.rs @@ -41,7 +41,10 @@ pub fn lookup_local<'a>(module: &'a Module, current: &'a Function, name: &str) - super::resolution::lookup(&super::resolution::AstView::default(), &module, current, name) } pub fn resolve_for_exec<'a>(module: &'a Module, current: &'a Function, call: &CallExpr) -> ExecTarget<'a> { - super::resolution::resolve(&super::resolution::AstView::default(), &module, current, call) + match call.for_evaluation() { + Ok(normalized) => super::resolution::resolve(&super::resolution::AstView::default(), &module, current, &normalized), + Err(message) => ExecTarget::Unresolved { message, span_hint: None }, + } } pub fn is_static_bound(target: &ExecTarget<'_>) -> bool { diff --git a/src/sema/ir.rs b/src/sema/ir.rs index ccf6c73..ce23d14 100644 --- a/src/sema/ir.rs +++ b/src/sema/ir.rs @@ -323,6 +323,24 @@ fn compile_index(index: ProjectIndex) -> Result { } } close_effect_dependencies(&mut artifacts); + let resolved_effects: BTreeMap<_,_> = artifacts.iter() + .map(|artifact|(artifact.artifact_id.clone(),artifact.effects.clone())).collect(); + for bound in &mut bound_calls { + if let Some(effects) = resolved_effects.get(&ArtifactId(bound.target.as_str().into())) { + bound.required_effects = effects.clone(); + } + } + let mut callsite_effects: BTreeMap<(String,u32),EffectSet> = BTreeMap::new(); + for bound in &bound_calls { + callsite_effects.entry((bound.source.file.clone(),bound.source.line)) + .or_default().extend(&bound.required_effects); + } + for step in &mut steps { + if let Some(effects) = callsite_effects.get(&(step.source.file.clone(),step.source.line)) { + step.effects.extend(effects); + } + if step.effects.0.is_empty() { step.effects = EffectSet::pure(); } + } close_closure_digests(&mut artifacts); artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0)); refs.sort_by(|a, b| a.id.cmp(&b.id)); @@ -455,6 +473,10 @@ fn attach_project_imports(files: &mut BTreeMap, ) { let calls = collect_call_sites(function); - let mut effects = direct_effects(&calls); + let mut effects = direct_effects(index, ast_module, function, &calls); let mut dependencies = Vec::new(); let mut bound_calls = Vec::new(); let mut dynamic_calls = Vec::new(); @@ -561,11 +583,10 @@ fn artifact_for_function( .unwrap_or_else(|| named.resolution.clone()), target: target.clone(), }); - let step_effects = named - .call - .as_ref() - .map(effects_for_call) - .unwrap_or_else(EffectSet::pure); + let mut step_effects = EffectSet::default(); + for (_, call, line) in &calls { + if *line == named.line { step_effects.extend(&effects_for_call(ast_module,function,call,Some(index))); } + } steps.push(KnowledgeStep { id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)), reference: ref_id, @@ -719,7 +740,7 @@ fn classify_call( }; CallClass::Bound { target, - effects: effects_for_call(call), + effects: EffectSet::default(), } } ExecTarget::Import { bind, lib, fun, path } => { @@ -754,7 +775,7 @@ fn classify_call( }; CallClass::Bound { target, - effects: effects_for_call(call), + effects: EffectSet::default(), } } ExecTarget::Builtin(_) | ExecTarget::Host(_) => CallClass::Other, @@ -1037,35 +1058,50 @@ fn call_name(call: &CallExpr) -> String { call_display(call) } -fn effects_for_call(call: &CallExpr) -> EffectSet { - let name = call_name(call).to_ascii_lowercase(); +fn effects_for_call(module: &Module, current: &Function, call: &CallExpr, index: Option<&ProjectIndex>) -> EffectSet { let mut effects = EffectSet::default(); - let effect = if name.starts_with("fs.") || name.contains("writeback") { if name.contains("write") || name.contains("remove") || name.contains("move") || name.contains("mkdir") { "fs.write" } else { "fs.read" } } - else if name.starts_with("http.") || name.starts_with("net.") { if name.contains("post") || name.contains("put") || name.contains("delete") { "network.write" } else { "network.read" } } - else if name.starts_with("foreign.") || name.starts_with("subtask.") || name == "exec" { "process.exec" } - else if name.starts_with("plugin.") { "plugin.call" } - else if name.starts_with("llm.") || name.starts_with("openai.") { "llm.call" } - else if name.starts_with("time.") || name.starts_with("datetime.") { "time.read" } - else if name.starts_with("random.") || name.starts_with("uuid.") { "random.read" } - else if name.starts_with("input") { "user.input" } - else if name.starts_with("print") || name.starts_with("log.") { "output.write" } - else if is_observe_call(call) { - return EffectSet::pure(); - } else if call.path.is_some() || (call.path.is_none() && call.receiver.is_none()) { - // Local bare name or import path: effects filled by BoundCall dependency - // closure. Do not guess pure / unknown here. - return EffectSet::default(); - } else { - // Receiver / unresolved dynamic — unknown (G06). - return EffectSet::unknown(); - }; - effects.add(effect); + match resolve_for_exec(module, current, call) { + ExecTarget::Host(host) => { + for effect in host.effects() { effects.add(*effect); } + } + ExecTarget::Builtin("print") => effects.add("output.write"), + ExecTarget::Builtin("input") => effects.add("user.input"), + ExecTarget::Builtin(_) => return EffectSet::pure(), + ExecTarget::Local(_) => {}, + ExecTarget::Import { lib, fun, .. } => { + if index.is_some_and(|index| lib.source.path.as_ref().is_some_and(|path| index.module_id_for_path(path).is_some())) { + // Project-indexed dependencies close by edges, not shallow AST clones. + return EffectSet::default(); + } + return imported_effects(lib, fun, &mut std::collections::HashSet::new()); + }, + ExecTarget::Dynamic { reason: DynamicReason::Plugin, .. } => effects.add("plugin.call"), + ExecTarget::Dynamic { .. } | ExecTarget::Unresolved { .. } => return EffectSet::unknown(), + } effects } -fn direct_effects(calls: &[(usize, CallExpr, u32)]) -> EffectSet { +fn imported_effects( + module: &Module, function: &Function, + visiting: &mut std::collections::HashSet<(Option, u32)>, +) -> EffectSet { + let identity = (module.source.path.clone(), function.span.line); + if !visiting.insert(identity.clone()) { return EffectSet::default(); } let mut effects = EffectSet::default(); - for (_, call, _) in calls { effects.extend(&effects_for_call(call)); } + for (_, call, _) in collect_call_sites(function) { + match resolve_for_exec(module, function, &call) { + ExecTarget::Local(fun) => effects.extend(&imported_effects(module, fun, visiting)), + ExecTarget::Import { lib, fun, .. } => effects.extend(&imported_effects(lib, fun, visiting)), + _ => effects.extend(&effects_for_call(module, function, &call, None)), + } + } + visiting.remove(&identity); + effects +} + +fn direct_effects(index: &ProjectIndex, module: &Module, current: &Function, calls: &[(usize, CallExpr, u32)]) -> EffectSet { + let mut effects = EffectSet::default(); + for (_, call, _) in calls { effects.extend(&effects_for_call(module, current, call, Some(index))); } effects } @@ -1516,7 +1552,7 @@ mod tests { #[test] fn compilation_is_deterministic_and_preserves_contract_effects() { let root = root(); - fs::write(root.join("main.mq.md"), "# main\n\n| 参数 | 类型 |\n| --- | --- |\n| path | text |\n\n## save\n\n> fs.write_text `path` ok\n\n*1*").unwrap(); + fs::write(root.join("main.mq.md"), "---\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n| 参数 | 类型 |\n| --- | --- |\n| path | text |\n\n## save\n\n> fs.write_text `path` ok\n\n*1*").unwrap(); let options = CompileOptions::for_path(&root).unwrap(); let first = compile_project(&options).unwrap(); let second = compile_project(&options).unwrap(); @@ -1545,6 +1581,8 @@ mod tests { root.join("main.mq.md"), r#"--- markup: occlusion +import: + fs: lib/fs.mq.md --- ## save diff --git a/src/sema/symbols.rs b/src/sema/symbols.rs index ef34431..75857fa 100644 --- a/src/sema/symbols.rs +++ b/src/sema/symbols.rs @@ -143,8 +143,9 @@ impl ProjectIndex { ); } path_to_module.insert(file.clone(), module_id.clone()); - let module = crate::load::parse_source_auto(&source) + let mut module = crate::load::parse_source_auto(&source) .with_context(|| format!("parse source {}", file.display()))?; + module.source.path = Some(file.clone()); for function in &module.functions { collect_symbols( &project_id, diff --git a/src/view/document.rs b/src/view/document.rs index 5e110eb..9d0e366 100644 --- a/src/view/document.rs +++ b/src/view/document.rs @@ -26,10 +26,12 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot let special = index_special_assigns(module, source); let skip_body = special_body_lines(&special); let stmt_lines = index_stmt_lines(module); + let occluded_lines = index_occluded_lines(module); let writebacks = writeback::writeback_map(source); let taken_arms = taken_arms_by_branch_line(annots); let mut out = String::from(r#"
"#); + out.push_str(&render_syntax_guide()); if !module.imports.is_empty() || !module.uses.is_empty() { out.push_str(r#"
"#); @@ -62,10 +64,11 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot .map(|(_, t)| t.as_str()) .collect::>() .join(" "); + let source_anchors=para.iter().skip(1).map(|(line,_)|format!(r#""#)).collect::(); para.clear(); let md = comment_markdown_to_html(&text); out.push_str(&format!( - r#"
{md}
"#, + r#"
{source_anchors}
{md}
"#, line = first_line, md = md )); @@ -157,6 +160,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot special.get(&l.line_no), writebacks.get(&l.line_no), None, + &occluded_lines, )); } else if !trimmed.is_empty() { para.push((l.line_no, trimmed.to_string())); @@ -190,6 +194,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot &writebacks, &taken_arms, annots, + &occluded_lines, ); out.push_str(&html); i = next; @@ -205,6 +210,7 @@ pub fn render_module_document(module: &Module, source: &str, annots: &[ViewAnnot special.get(&l.line_no), writebacks.get(&l.line_no), None, + &occluded_lines, )); i += 1; } @@ -295,7 +301,7 @@ fn render_table_block( } let first_line = rows[0].0; let mut html = format!( - r#"
"#, + r#"
"#, line = first_line ); let mut header_done = false; @@ -370,6 +376,7 @@ fn render_list_block( writebacks: &HashMap, taken_arms: &HashMap, all_annots: &[ViewAnnot], + occluded_lines: &HashSet, ) -> (String, usize) { let base_indent = indent_level(&lines[start].text); let tag = match kind { @@ -407,8 +414,7 @@ fn render_list_block( let frames: Vec<&ViewAnnot> = all_annots .iter() .filter(|a| { - a.kind == crate::view::annot::AnnotKind::LoopFrame - && a.anchor_line == branch_line + a.kind == crate::view::annot::AnnotKind::LoopFrame && a.anchor_line == branch_line }) .collect(); if frames.len() >= 2 { @@ -483,7 +489,7 @@ fn render_list_block( _ => "", }; html.push_str(&format!( - r#"
  • "#, + r#"
  • "#, arm_cls = arm_cls, line = lines[i].line_no, arm_idx = arm_index, @@ -491,7 +497,12 @@ fn render_list_block( )); html.push_str(&format!( r#"
    {}
    "#, - render_surface_line(lines[i].line_no, head, by_line) + render_surface_line( + lines[i].line_no, + head, + by_line, + occluded_lines.contains(&lines[i].line_no) + ) )); // Annots for this line; Branch chips on the arm they refer to (filtered by call frame in JS). let mut head_annots: Vec = Vec::new(); @@ -515,9 +526,12 @@ fn render_list_block( } } } - if !head_annots.is_empty() { - html.push_str(&render_annot_band(&head_annots, MAX_VISIBLE_ANNOTS)); - } + let notes = if occluded_lines.contains(&lines[i].line_no) { + render_logic_notes(lines[i].line_no, head, &[]) + } else { + String::new() + }; + html.push_str(&render_document_band(&head_annots, ¬es)); // Body: following lines with greater indent until next sibling. i += 1; html.push_str(r#"
    "#); @@ -525,9 +539,7 @@ fn render_list_block( let t2 = lines[i].text.trim_end_matches(['\r', '\n']); if t2.trim().is_empty() { // allow blank inside body - if i + 1 < lines.len() - && indent_level(&lines[i + 1].text) > base_indent - { + if i + 1 < lines.len() && indent_level(&lines[i + 1].text) > base_indent { i += 1; continue; } @@ -550,6 +562,7 @@ fn render_list_block( writebacks, taken_arms, all_annots, + occluded_lines, ); html.push_str(&inner); i = next; @@ -573,6 +586,7 @@ fn render_list_block( special.get(&lines[i].line_no), writebacks.get(&lines[i].line_no), Some(ind2), + occluded_lines, )); i += 1; } @@ -593,23 +607,25 @@ fn render_surface_line( line_no: u32, head: &str, by_line: &HashMap>, + occluded: bool, ) -> String { + if occluded && !occlusion_spans(head).is_empty() { + return format!( + r#"{}"#, + head.len(), + render_occlusion_text(line_no, head, 0) + ); + } let bits = scan_prose_line(head); if bits.is_empty() { // Else arm "*" or plain condition text. if head.trim() == "*" { return r#"else"#.into(); } - format!( - r#"{}"#, - escape(head) - ) + format!(r#"{}"#, escape(head)) } else { - let annots = by_line - .get(&line_no) - .map(|v| v.as_slice()) - .unwrap_or(&[]); - render_prose_with_marks(line_no, head, &bits, annots) + let annots = by_line.get(&line_no).map(|v| v.as_slice()).unwrap_or(&[]); + render_prose_with_marks(line_no, head, &bits, annots, false) } } @@ -635,7 +651,7 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String { r##"

    {name}

    -说明"##, +说明"##, line = fun.span.line, name = escape(&fun.name), ); @@ -645,7 +661,9 @@ fn render_fun_heading(fun: &Function, annots: &[ViewAnnot]) -> String { .filter(|a| a.kind == crate::view::annot::AnnotKind::CallFrame && a.label == fun.name) .collect(); if call_labels.len() >= 2 { - s.push_str(r#"
  • "#, + ); + for (id, surface) in crate::parse::CORE_CONSTRUCTS { + let meaning=match *id { + "narrative"=>"作者的解释,按普通 Markdown 阅读。", "blank"=>"分隔叙述与结构,不是计算步骤。", + "heading-unit"=>"一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。", + "call-line"=>"调用函数;实际执行结果另有标注。", "branch-list"=>"按条件选择分支,不是普通编号说明。", + "loop-list"=>"重复或遍历结构;迭代选择器只切换已有运行记录。", "param"=>"兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。", + "table"=>"未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。", "fence"=>"代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。", + "hr"=>"分隔内容,不能把分隔线当作函数返回。", "writeback"=>"程序写回的结果,区别于作者原始正文。", + "ident"=>"叙述中的参数或变量;默认值跟在名称之后。", "bold-code"=>"执行语句:赋值、调用或计算;不是打印,也不是返回。", + "italic-return"=>"返回表达式;句中以返回、Return 等明确引出。", "empty-return"=>"显式返回空值或结束当前函数。", + "link-index"=>"默认模式是 [动作](实现) 遮蔽,正文只显示动作;空括号表示待补充实际逻辑。classic 模式才解释为旧链接取元。", + "bracket-call"=>"兼容的带修饰调用;不能把任意普通链接当作执行授权。", "footnote-index"=>"兼容的脚注取元;当前库优先用 access 读取集合。", + "soft-emphasis"=>"普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。", _=>"按源码中的真实结构阅读。" + }; + html.push_str(&format!( + r#""#, + escape(id), + escape(surface), + escape(meaning) + )); + } + html.push_str("
    标记阅读含义
    {}{}
    "); + html +} + #[cfg(test)] -mod occl_split_tests { - use super::split_occlusion; - - #[test] - fn splits_bare_assignment_occlusion() { - let (head, label, payload, rest) = - split_occlusion("`留存` = [客户留存率,模拟数据](0.42)").unwrap(); - assert_eq!(head, "`留存` ="); - assert_eq!(label, "客户留存率,模拟数据"); - assert_eq!(payload, "0.42"); - assert_eq!(rest, ""); +mod readable_occlusion_tests { + use super::*; + fn render(source: &str) -> String { + let module = crate::load::parse_source_auto(source).unwrap(); + render_module_document(&module, source, &[]) } - #[test] - fn splits_bold_assignment_occlusion_without_markers() { - let (head, label, payload, _) = - split_occlusion("**留存 = [客户留存率,模拟数据](0.42)**").unwrap(); - assert_eq!(head, "留存 ="); - assert_eq!(label, "客户留存率,模拟数据"); - assert_eq!(payload, "0.42"); + fn prose_keeps_multiple_actions_and_returns_without_exposing_payloads() { + let html=render("# main\n\n先**a = [读取甲](1 + 2)**,接着**b = [读取乙](3 + 4)**,最后返回*[合计](a + b)*。\n"); + let line = html + .split("doc-line doc-prose-line\"") + .nth(1) + .unwrap() + .split("") + .next() + .unwrap(); + for text in ["先", "读取甲", "接着", "读取乙", "最后返回", "合计"] { + assert!(line.contains(text), "{line}"); + } + for code in ["1 + 2", "3 + 4", "a + b", "[读取甲]"] { + assert!(!line.contains(code), "payload leaked into prose: {line}"); + } + assert_eq!( + html.matches("class=\"annot-chip annot-implementation\"") + .count(), + 3 + ); + assert!(html.contains("data-syntax=\"return\"")); + assert!(html.contains(">1 + 2") && html.contains(">a + b")); } - #[test] - fn splits_stub_and_nested_payload() { - let (_, label, payload, _) = - split_occlusion("`待接` = [搜索接入,待开发]()").unwrap(); - assert_eq!(label, "搜索接入,待开发"); - assert!(payload.is_empty()); - - let (_, label, payload, _) = - split_occlusion("`取第一` = [第一颗](access(`篮子`, \"1\"))").unwrap(); - assert_eq!(label, "第一颗"); - assert_eq!(payload, "access(`篮子`, \"1\")"); + fn empty_logic_quotes_nested_parentheses_and_html_are_safe() { + let html = + render("# main\n\n得到**a = [括号](str(value=\") \"))**,再**b = [待接]()**。\n"); + assert!(html.contains("待补充实际逻辑")); + assert!(html.contains("<tag>") && !html.contains("")); + assert!(html.contains("str(value=") <tag>")")); + assert!(html.contains("当前空遮蔽返回 None")); } - #[test] - fn ignores_index_and_plain_lines() { - // Link-index (classic) and ordinary statements are not occlusions. - assert!(split_occlusion("**v = [键](`表`)**").is_some()); // shape matches; parser decides meaning - assert!(split_occlusion("**甲 = 加(1 2)**").is_none()); - assert!(split_occlusion("> print text=x").is_none()); + fn navigation_and_quoted_links_are_not_executable_occlusions() { + let html=render("# main\n\n参阅 [普通链接](https://example.com/guide)。\n\n得到**literal = \"[数据链接](should_stay_text)\"**,以及**value = [真实动作](5)**,参阅 [混合链接](https://example.com/mixed)。\n"); + assert!(html.contains("href=\"https://example.com/guide\"")); + assert!(html.contains("href=\"https://example.com/mixed\"")); + assert_eq!( + html.matches("class=\"annot-chip annot-implementation\"") + .count(), + 1 + ); + assert!(html.contains("[数据链接](should_stay_text)")); + let classic = render("---\nmarkup: classic\n---\n# main\n\n**value = [key](`record`)**\n"); + assert!(!classic.contains("class=\"annot-chip annot-implementation\"")); + } + #[test] + fn semantic_loop_labels_and_every_core_construct_are_explained() { + let html=render("# main\n\n`items` =\n\n| n |\n|---|\n| 1 |\n| 2 |\n\n- [逐项处理](遍历 items 为 item)\n **out = item + 1**\n"); + assert!(html.contains("逐项处理")); + assert!(html.contains("遍历 items 为 item")); + for (id, _) in crate::parse::CORE_CONSTRUCTS { + assert!( + html.contains(&format!("data-construct-id=\"{id}\"")), + "missing {id}" + ); + } } } diff --git a/src/view/html.rs b/src/view/html.rs index b7585dd..3b722bc 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -2504,7 +2504,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { var root = scope || document.getElementById("structure") || document; root.querySelectorAll("[data-annot-band]").forEach(function (band) {{ band.classList.remove("is-expanded"); - var chips = band.querySelectorAll(".annot-chip"); + var chips = band.querySelectorAll(".annot-chip:not(.annot-implementation)"); var visible = []; chips.forEach(function (chip) {{ chip.classList.remove("annot-chip-overflow"); @@ -4210,7 +4210,7 @@ window.MARQDO_VIEW_PAGE_TOKEN = {page_token_js}; String::new() } else { format!( - "
    可执行知识(辅助){}
    ", + "
    可执行知识 · 输入、返回与依据{}
    ", vm.knowledge_html ) } diff --git a/src/view/knowledge_reading.rs b/src/view/knowledge_reading.rs new file mode 100644 index 0000000..6676f38 --- /dev/null +++ b/src/view/knowledge_reading.rs @@ -0,0 +1,266 @@ +//! Reader-facing projection of compiler facts; no evaluation or invented evidence. +use crate::ast::{Function, Module}; +use crate::sema::{SemanticArtifact, SemanticProject}; +use crate::view::{html::escape, render::expr_display}; + +fn find_function(functions: &[Function], line: u32) -> Option<&Function> { + functions.iter().find_map(|f| { + if f.span.line == line { + Some(f) + } else { + find_function(&f.children, line) + } + }) +} +fn state(value: &str) -> String { + match value { + "passed" => "检查通过".into(), + "failed" => "检查失败".into(), + "unchecked" => "尚未检查".into(), + "not_run" => "分析未运行程序".into(), + "unknown" => "没有可用记录".into(), + "sourced" => "已关联来源,内容尚未核验".into(), + "verified" => "证据已核验".into(), + "unverified" => "尚无已核验证据".into(), + "unreviewed" => "尚未进行领域审阅".into(), + other => format!("原始状态:{other}"), + } +} +fn effect(value: &str) -> &str { + match value { + "pure" => "无已知宿主副作用", + "fs.read" => "读取文件", + "fs.write" => "写入文件", + "net.http" | "network" => "网络请求", + "process.exec" => "启动进程", + "plugin" => "加载原生插件", + "environment.read" => "读取环境配置", + "output.write" => "输出文本", + "input.read" => "读取输入", + "unknown" => "调用效应尚不能确定", + _ => value, + } +} +fn kind(value: &str) -> &str { + match value { + "type" => "对象", + "function" => "函数", + "constant" => "常量", + _ => value, + } +} +fn step_kind(value: &str) -> &str { + match value { + "derive" => "计算", + "observe" => "观察", + "iterate" => "遍历", + "call" => "调用", + "return" => "返回", + "branch" => "条件", + "narrate" | "reference" => "正文引用", + _ => value, + } +} +fn render_steps( + project: &SemanticProject, + steps: &[&crate::sema::ir::KnowledgeStep], + title: &str, +) -> String { + if steps.is_empty() { + return String::new(); + } + let mut out=format!("
    {}

    这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。

      ",escape(title)); + for step in steps { + let label = project + .refs + .iter() + .find(|r| r.id == step.reference) + .map(|r| r.label.as_str()) + .unwrap_or("未命名步骤"); + out.push_str(&format!(r##"
    1. {meaning}{label}
    2. "##,kind=escape(&step.kind),line=step.source.line,meaning=escape(step_kind(&step.kind)),label=escape(label))); + } + out.push_str("
    "); + out +} +fn technical(artifact: &SemanticArtifact) -> String { + let v = &artifact.verification; + format!( + r##"
    技术详情:身份、摘要与原始状态
    目标标识
    {target}
    制品摘要(未检查锁定状态)
    {digest}
    依赖标识
    {deps}
    原始验证状态
    parse: {parse}; resolve: {resolve}; contract: {contract}; execution: {execution}; tests: {tests}; evidence: {evidence}; domain: {domain}
    "##, + target = escape( + artifact + .symbol_id + .as_ref() + .map(|id| id.as_str()) + .unwrap_or(&artifact.artifact_id.0) + ), + digest = escape(&artifact.hashes.artifact.0), + deps = escape( + &artifact + .dependencies + .iter() + .map(|id| id.0.as_str()) + .collect::>() + .join("\n") + ), + parse = escape(&v.parse), + resolve = escape(&v.resolve), + contract = escape(&v.contract), + execution = escape(&v.execution), + tests = escape(&v.tests), + evidence = escape(&v.evidence), + domain = escape(&v.domain) + ) +} +/// Facts are grouped by exact source unit, with machine identities behind disclosure. +pub(super) fn render(project: &SemanticProject, rel: &str, module: Option<&Module>) -> String { + let mut artifacts: Vec<_> = project + .artifacts + .iter() + .filter(|a| a.source.file == rel && a.kind != "module") + .collect(); + artifacts.sort_by_key(|a| a.source.line); + let steps: Vec<_> = project + .steps + .iter() + .filter(|s| s.source.file == rel) + .collect(); + if artifacts.is_empty() && steps.is_empty() { + return String::new(); + } + let mut out = format!( + r##"

    这份文档怎样成为可调用的知识

    {} 个知识单元 · {} 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。

    以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。

    "##, + artifacts.len(), + steps.len() + ); + let first = artifacts.first().map(|a| a.source.line).unwrap_or(u32::MAX); + let introductory: Vec<_> = steps + .iter() + .copied() + .filter(|s| s.source.line < first) + .collect(); + out.push_str(&render_steps(project, &introductory, "正文中的引用与步骤")); + for (index, a) in artifacts.iter().enumerate() { + let line = a.source.line; + let function = module.and_then(|m| find_function(&m.functions, line)); + let end = artifacts + .get(index + 1) + .map(|a| a.source.line) + .unwrap_or(u32::MAX); + out.push_str(&format!(r##"
    {name}{kind}
    回到正文 · 第 {line} 行"##,name=escape(&a.display_name),kind=escape(if function.is_some_and(|f|f.name=="main"&&f.level==1){"程序入口"}else{kind(&a.kind)}))); + if let Some(signature) = &a.signature { + if signature.receiver == "instance" { + out.push_str("

    实例方法:先创建所属对象,再通过同一实例调用。

    "); + } + out.push_str("

    需要什么输入

    "); + if signature.params.is_empty() { + out.push_str("

    无需提供输入参数。

    "); + } else { + out.push_str("
    "); + for param in &signature.params { + let authored = function + .and_then(|f| f.contract.as_ref()) + .and_then(|c| c.params.iter().find(|p| p.name == param.name)); + let default = function + .and_then(|f| f.params.iter().find(|p| p.name == param.name)) + .and_then(|p| p.default.as_ref()) + .map(expr_display); + let supply = if param.required { + "必填".into() + } else { + default + .map(|v| format!("默认 {v}")) + .unwrap_or("可省略;默认值见源码".into()) + }; + out.push_str(&format!( + "", + escape(¶m.name), + escape(¶m.ty), + escape(&supply), + escape( + authored + .map(|p| p.desc.as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("源码未提供参数说明") + ) + )); + } + out.push_str("
    参数类型提供方式含义
    {}{}{}{}
    "); + } + let returns = function + .and_then(|f| f.contract.as_ref()) + .and_then(|c| c.returns.as_ref()); + out.push_str(&format!( + "

    返回什么

    {} · {}

    ", + escape(&signature.returns), + escape( + returns + .map(|r| r.desc.as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("源码未提供返回值说明;请结合正文实现阅读。") + ) + )); + } else { + out.push_str("

    这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。

    "); + if let Some(returns) = function + .and_then(|f| f.contract.as_ref()) + .and_then(|c| c.returns.as_ref()) + { + out.push_str(&format!( + "

    源码中的返回契约

    {} · {}

    ", + escape(&returns.ty.name()), + escape(&returns.desc) + )); + } + } + out.push_str(&format!( + "

    调用边界

    {}。权限由实际运行入口授予;静态副作用信息不等于运行许可。

    ", + escape( + &a.effects + .values() + .iter() + .map(|s| effect(s)) + .collect::>() + .join("、") + ) + )); + if !a.dependencies.is_empty() { + out.push_str("

    依赖哪些知识

      "); + for dependency in &a.dependencies { + if let Some(target) = project + .artifacts + .iter() + .find(|other| other.artifact_id == *dependency) + { + if target.source.file == rel && target.kind != "module" { + out.push_str(&format!( + r##"
    • {}
    • "##, + target.source.line, + escape(&target.display_name) + )); + } else { + out.push_str(&format!( + "
    • {} {}
    • ", + escape(&target.display_name), + escape(&target.source.file) + )); + } + } else { + out.push_str("
    • 依赖尚未解析;完整标识见技术详情。
    • "); + } + } + out.push_str("
    "); + } + let v = &a.verification; + out.push_str(&format!("

    当前有哪些依据

    语法与引用
    {};{}
    契约检查
    {}
    测试记录
    {}
    内容来源
    {}
    领域审阅
    {}
    ",escape(&state(&v.parse)),escape(&state(&v.resolve)),escape(&state(&v.contract)),escape(&state(&v.tests)),escape(&state(&v.evidence)),escape(&state(&v.domain)))); + let owned: Vec<_> = steps + .iter() + .copied() + .filter(|s| s.source.line >= line && s.source.line < end) + .collect(); + out.push_str(&render_steps(project, &owned, "查看本单元的结构步骤")); + out.push_str(&technical(a)); + out.push_str("
    "); + } + out.push_str("
    "); + out +} diff --git a/src/view/mod.rs b/src/view/mod.rs index 5c4aba4..fbe4431 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -7,6 +7,7 @@ mod debug_page; mod document; mod html; mod knowledge_present; +mod knowledge_reading; mod notebook_api; mod output; mod render; @@ -410,30 +411,28 @@ pub(crate) fn build_file_view_with_exec( ) -> Result { let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?; // Structure shows this file only — do not merge imported lib bodies into the tree. - let (mut structure, mut module_opt, input_prompts) = match crate::load::parse_source_auto(&source) { - Ok(module) => { - let prompts = collect_input_prompts(&module); - ( - render_module_structure(&module, &source), - Some(module), - prompts, - ) - } - Err(e) => ( - format!( - "
    parse/load error: {}
    ", - escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) + let (mut structure, mut module_opt, input_prompts) = + match crate::load::parse_source_auto(&source) { + Ok(module) => { + let prompts = collect_input_prompts(&module); + ( + render_module_structure(&module, &source), + Some(module), + prompts, + ) + } + Err(e) => ( + format!( + "
    parse/load error: {}
    ", + escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) + ), + None, + Vec::new(), ), - None, - Vec::new(), - ), - }; + }; let effective = effective_stdin(&source, stdin_lines); let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source); - let show_stream = module_opt - .as_ref() - .map(uses_stream_panel) - .unwrap_or(false); + let show_stream = module_opt.as_ref().map(uses_stream_panel).unwrap_or(false); // Live + LLM/agent import + has `input` + stdin ready → stream via client `/api/run`. let auto_stream = live && show_stream @@ -447,41 +446,40 @@ pub(crate) fn build_file_view_with_exec( // Optional: sandbox to the whole view tree so sibling folders are reachable. opts.fs_root = Some(root.root.clone()); let mut captured: Option = None; - let (stdout, stderr, ok, plots, mut bindings_html) = - if !execute { - ( - String::new(), - "execution skipped (--no-exec)".into(), - true, - Vec::new(), - String::from(r#"

    skipped

    "#), - ) - } else if awaiting_input || auto_stream { - ( - String::new(), - String::new(), - true, - Vec::new(), - String::new(), - ) - } else { - match run_file_capture(abs, &opts) { - Ok(cap) => { - let stdout = cap.stdout.clone(); - let plots = cap.plots.iter().map(|p| p.svg.clone()).collect(); - let bindings_html = render_bindings_html(&cap.bindings); - captured = Some(cap); - (stdout, String::new(), true, plots, bindings_html) - } - Err(e) => ( - String::new(), - tidy_user_error(&format!("{e:#}"), abs, rel), - false, - Vec::new(), - String::new(), - ), + let (stdout, stderr, ok, plots, mut bindings_html) = if !execute { + ( + String::new(), + "execution skipped (--no-exec)".into(), + true, + Vec::new(), + String::from(r#"

    skipped

    "#), + ) + } else if awaiting_input || auto_stream { + ( + String::new(), + String::new(), + true, + Vec::new(), + String::new(), + ) + } else { + match run_file_capture(abs, &opts) { + Ok(cap) => { + let stdout = cap.stdout.clone(); + let plots = cap.plots.iter().map(|p| p.svg.clone()).collect(); + let bindings_html = render_bindings_html(&cap.bindings); + captured = Some(cap); + (stdout, String::new(), true, plots, bindings_html) } - }; + Err(e) => ( + String::new(), + tidy_user_error(&format!("{e:#}"), abs, rel), + false, + Vec::new(), + String::new(), + ), + } + }; // Re-read after run so writeback slots / workbook edits show in Structure. if execute && !awaiting_input && !auto_stream { if let Ok(next) = fs::read_to_string(abs) { @@ -514,46 +512,60 @@ pub(crate) fn build_file_view_with_exec( // Analysis is intentionally independent from capture/run. If a document // has side effects, its facts remain visible while its values stay absent. let title_guess = crate::view::title_from_source(&source, rel); - let (knowledge_html, knowledge_error, page_token) = - match crate::sema::compile_project(&crate::sema::CompileOptions { + let analysis = if root.only_file.is_some() { + crate::sema::compile_file_closure(abs) + } else { + crate::sema::compile_project(&crate::sema::CompileOptions { project_root: root.root.clone(), entry: Some(abs.to_path_buf()), lock_mode: crate::sema::LockMode::Off, - }) { - Ok(compilation) => { - let html = render_knowledge_html(&compilation.semantics, rel); - // V1: also materialize structured presentation (JSON available to page scripts). - let mut presentation = crate::view::KnowledgePresentation::from_project( - &compilation.semantics, - rel, - &title_guess, - ); - presentation.page_token = crate::view::page_token_from_source(rel, &source); - let json = presentation.to_json().to_string(); - let with_model = if html.is_empty() { - format!( - r#""#, - json = json.replace("{json}"#, - html = html, - json = json.replace(" { + // Dependency closures may have a wider root than the reader's file directory. + let semantic_rel = abs + .strip_prefix(&compilation.semantics.root) + .unwrap_or(abs) + .to_string_lossy() + .replace('\\', "/"); + let html = crate::view::knowledge_reading::render( + &compilation.semantics, + &semantic_rel, + module_opt.as_ref(), + ); + // V1: also materialize structured presentation (JSON available to page scripts). + let mut presentation = crate::view::KnowledgePresentation::from_project( + &compilation.semantics, + &semantic_rel, + &title_guess, + ); + presentation.document_id = rel.to_string(); + presentation.page_token = crate::view::page_token_from_source(rel, &source); + let json = presentation.to_json().to_string(); + let with_model = if html.is_empty() { + format!( + r#""#, + json = json.replace(" ( - String::new(), - format!("知识关系暂不可用:{}", tidy_user_error(&format!("{e:#}"), abs, rel)), - crate::view::page_token_from_source(rel, &source), + } else { + format!( + r#"{html}"#, + html = html, + json = json.replace(" ( + String::new(), + format!( + "知识关系暂不可用:{}", + tidy_user_error(&format!("{e:#}"), abs, rel) ), - }; + crate::view::page_token_from_source(rel, &source), + ), + }; let page_token = if page_token.is_empty() { crate::view::page_token_from_source(rel, &source) } else { diff --git a/src/view/reader.css b/src/view/reader.css index 6bc5258..f12ae2f 100644 --- a/src/view/reader.css +++ b/src/view/reader.css @@ -169,3 +169,46 @@ body.reader-page .nav { visibility:hidden; } body.reader-page #nav-toggle:checked ~ .shell .nav { visibility:visible; } @media print { body.reader-page .document-surface { padding-bottom:0; } } + +/* Action text belongs to the sentence; its implementation belongs to a note. */ +body.reader-page .doc-line { font:19px/1.8 var(--serif); overflow-wrap:anywhere; } +body.reader-page .mq-anchor:has(.occl-label) { background:transparent; border:0; padding:0; } +body.reader-page button.occl-label { display:inline; appearance:none; font:inherit; color:var(--olive); background:transparent; border:0; border-bottom:1px dotted var(--gold); border-radius:0; padding:0 1px; cursor:pointer; text-align:inherit; } +body.reader-page button.occl-label:hover { background:var(--fill); } +body.reader-page .occl-stub { display:inline; font:11px/1.5 var(--sans); border:1px solid var(--gold); border-radius:5px; padding:2px 5px; margin-left:6px; color:var(--focus); white-space:normal; } +body.reader-page details.annot-implementation { display:block; padding:8px 12px; border-radius:7px; border:1px solid var(--line); margin:5px 0; } +body.reader-page .annot-implementation > summary { cursor:pointer; font:12px/1.6 var(--sans); color:var(--olive); } +body.reader-page .annot-implementation .occl-code { display:block; text-align:left; white-space:pre-wrap; overflow-wrap:anywhere; font:12px/1.7 var(--mono); padding:6px 0; border:0; border-radius:0; background:transparent; } +body.reader-page details.annot-implementation.is-margin-note { padding:5px 0; border:0; margin:0; } +body.reader-page .is-margin-note.annot-implementation > summary { font:15px/1.5 var(--serif); } +.logic-hint { display:block; color:var(--muted); font:10px/1.6 var(--sans); margin-top:5px; } +.reader-syntax-guide { font:13px/1.7 var(--sans); border:1px solid var(--line); padding:12px 16px; border-radius:9px; margin:0 0 28px; color:var(--muted); } +.reader-syntax-guide > summary { cursor:pointer; color:var(--olive); } +.reader-syntax-guide p { margin:12px 0; } +.knowledge-table-wrap { max-width:100%; overflow-x:auto; } +.reader-syntax-guide table,.knowledge-panel table { width:100%; border-collapse:collapse; font:12px/1.65 var(--sans); } +.reader-syntax-guide th,.reader-syntax-guide td,.knowledge-panel th,.knowledge-panel td { padding:9px 10px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; } +.reader-syntax-guide td:first-child { min-width:115px; } +.reader-page .knowledge-block { border-top:1px solid var(--line); padding-top:22px; font:14px/1.7 var(--sans); } +.reader-page .knowledge-block > summary { color:var(--olive); font:18px/1.6 var(--serif); } +.knowledge-intro { margin:20px 0; }.knowledge-intro h3 { font:22px/1.5 var(--serif); margin:0 0 8px; } +.knowledge-intro p { margin:7px 0; } +.knowledge-card { margin:12px 0; border:1px solid var(--line); border-radius:10px; overflow:hidden; font:13px/1.75 var(--sans); } +.knowledge-card > summary { display:flex; align-items:baseline; flex-wrap:wrap; gap:10px; padding:14px 18px; cursor:pointer; background:var(--fill); } +.knowledge-card > summary::before { content:'›'; color:var(--gold); }.knowledge-card[open] > summary::before { content:'⌄'; } +.knowledge-unit-name { font:18px/1.6 var(--serif); overflow-wrap:anywhere; }.knowledge-unit-kind { font:11px/1.5 var(--sans); color:var(--muted); } +.knowledge-unit-body { padding:16px 18px; }.knowledge-unit-body h4 { margin:20px 0 8px; font:600 13px/1.6 var(--sans); color:var(--olive); } +.knowledge-unit-body p { margin:6px 0; }.knowledge-source-link { color:var(--olive); border-bottom:1px dotted var(--gold); font-size:12px; } +.knowledge-status { display:grid; grid-template-columns:100px minmax(0,1fr); gap:7px 12px; margin:8px 0; }.knowledge-status dt { color:var(--muted); }.knowledge-status dd { margin:0; } +.knowledge-panel code { white-space:pre-wrap; overflow-wrap:anywhere; font:11px/1.65 var(--mono); } +.knowledge-dependencies { padding-left:20px; }.knowledge-dependencies a { border-bottom:1px dotted var(--gold); } +.knowledge-steps,.knowledge-technical { border-top:1px solid var(--line); margin-top:18px; padding-top:12px; } +.knowledge-steps > summary,.knowledge-technical > summary { font:12px/1.7 var(--sans); cursor:pointer; color:var(--muted); } +.knowledge-step { padding:5px 0; overflow-wrap:anywhere; }.knowledge-step-kind { display:inline-block; color:var(--olive); min-width:4em; margin-right:8px; } +.knowledge-technical dl { font-size:11px; }.knowledge-technical dd { margin:4px 0 14px; overflow-wrap:anywhere; } +.reader-dialog:has(.knowledge-panel) { width:min(850px,calc(100vw - 32px)); } +@media(max-width:600px) { body.reader-page .doc-line { font-size:17px; }.knowledge-unit-body { padding:12px; }.knowledge-status { grid-template-columns:80px minmax(0,1fr); }.knowledge-card > summary { padding:12px; }.knowledge-table-wrap th,.knowledge-table-wrap td { min-width:65px; }.reader-syntax-guide { padding:10px; } } +@media print { .annot-implementation { break-inside:avoid; }.reader-syntax-guide { display:none; }.knowledge-technical { overflow-wrap:anywhere; } } +.reader-dialog .knowledge-table-wrap table { width:100%; border-collapse:collapse; font:12px/1.7 var(--sans); } +.reader-dialog .knowledge-table-wrap th,.reader-dialog .knowledge-table-wrap td { text-align:left; padding:8px 10px; border-bottom:1px solid var(--line); vertical-align:top; overflow-wrap:anywhere; } +.reader-run-summary { color:var(--olive); }.reader-dialog > details { margin:16px 0; } diff --git a/src/view/reader.js b/src/view/reader.js index ff86501..367d6ad 100644 --- a/src/view/reader.js +++ b/src/view/reader.js @@ -72,6 +72,8 @@ if (name === 'close-dialog') { dialog.close(); return; } if (name === 'document') { if (dialog.open) dialog.close(); scrollTo(document.getElementById('document-section') || document.querySelector('main')); return; } if (name === 'search') { showSearch(); return; } + if (name === 'knowledge') { openDialog('可执行知识', name); movePanel(document.querySelector('.knowledge-panel')); return; } + if (name === 'syntax') { var guide=document.getElementById('reader-syntax-guide'); if(guide) {guide.open=true;scrollTo(guide);} return; } if (name === 'functions' || name === 'variables') { var panel = document.getElementById(name === 'functions' ? 'fn-outline' : 'vars-panel'); openDialog(name === 'functions' ? '函数目录' : '文档变量', name); movePanel(panel); return; @@ -79,10 +81,27 @@ if (name === 'memory') { openDialog('执行内存与调用轨迹', name); var hint = document.createElement('p'); hint.textContent = window.MARQDO_VIEW_LIVE ? '当前文档已捕获的绑定与调用轨迹;会话状态可在高级工具中查看。' : '以下为导出时保存的执行快照。'; content.appendChild(hint); - var pre = document.createElement('pre'); - try { pre.textContent = JSON.stringify(JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'), null, 2); } - catch (_) { pre.textContent = '当前没有可用执行快照。'; } - content.appendChild(pre); return; + var report; + try { report=JSON.parse((document.getElementById('mq-view-trace') || {}).textContent || '{}'); } + catch (_) { report={}; } + if(typeof report.ok!=='boolean') { + var empty=document.createElement('p');empty.textContent='本页没有捕获执行记录;静态知识分析不会自动产生运行结果。';content.appendChild(empty);return; + } + var status=document.createElement('p');status.className='reader-run-summary'; + status.textContent=(report.ok?'这次运行成功':'这次运行失败')+' · '+(report.calls||[]).length+' 次调用 · '+(report.loops||[]).length+' 个循环记录';content.appendChild(status); + function reportTable(title,headers,rows) { + var heading=document.createElement('h3');heading.textContent=title;content.appendChild(heading); + var wrap=document.createElement('div');wrap.className='knowledge-table-wrap'; + var table=document.createElement('table'),head=document.createElement('tr'); + headers.forEach(function(text){var cell=document.createElement('th');cell.textContent=text;head.appendChild(cell);});table.appendChild(head); + rows.forEach(function(row){var tr=document.createElement('tr');row.forEach(function(text){var cell=document.createElement('td');cell.textContent=text;tr.appendChild(cell);});table.appendChild(tr);}); + wrap.appendChild(table);content.appendChild(wrap); + } + var bindings=report.bindings_final||{}; + reportTable('最终绑定',['名称','值'],Object.keys(bindings).map(function(key){return [key,String(bindings[key])];})); + reportTable('调用记录',['函数','源码位置','输入'],(report.calls||[]).map(function(call){return [call.fn,'第 '+call.fn_line+' 行',call.args_brief||'无实参'];})); + var details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='完整执行报告(技术详情)';details.appendChild(summary); + var pre=document.createElement('pre');pre.textContent=JSON.stringify(report,null,2);details.appendChild(pre);content.appendChild(details);return; } if (name === 'execution') { scrollTo(document.getElementById('exec-block')); return; } if (name === 'run') { @@ -104,6 +123,8 @@ } if (name === 'more') { openDialog('文档工具', name); + option('可执行知识', function () { action('knowledge'); }); + option('语法与阅读说明', function () { dialog.close(); action('syntax'); }); option('文件目录', function () { dialog.close(); action('files'); }); option('查看完整源码', function () { var source = document.querySelector('.source-block'); if (source) { source.open = true; scrollTo(source); } }); option('高级运行工具', function () { document.body.classList.toggle('reader-tools'); dialog.close(); scrollTo(document.getElementById('notebook-bar')); }); @@ -170,6 +191,7 @@ band.classList.remove('is-keyed'); band.querySelectorAll('.annot-chip').forEach(function (chip) { chip.classList.remove('is-margin-note'); + if(chip.classList.contains('annot-implementation')) chip.open=false; ['left', 'top', 'width'].forEach(function (key) { chip.style.removeProperty(key); }); delete chip.dataset.readerAnchor; delete chip.dataset.readerSide; }); @@ -379,6 +401,7 @@ var fragments = anchorFragments(item.anchor); var width = Math.max(140, Math.min(190, Math.min.apply(Math, space) * .58)); item.chip.classList.add('is-margin-note'); item.chip.style.width = width + 'px'; + if(item.chip.classList.contains('annot-implementation')) item.chip.open=true; var height = item.chip.offsetHeight, stagger = [-58, 44, -34, 68][index % 4]; var choices = nextY.map(function (y, side) { var fragment = side === 0 ? fragments[0] : fragments[fragments.length - 1]; @@ -439,14 +462,32 @@ dialog = document.getElementById('reader-dialog'); content = document.getElementById('reader-dialog-content'); dialog.addEventListener('close', function () { restorePanels(); refreshAnnotations(); }); document.addEventListener('click', function (ev) { + var logic=ev.target.closest('[data-logic-id]'); + if(logic) { + ev.preventDefault(); + var note=document.getElementById(logic.dataset.logicId+'-note'); + openDialog('实际逻辑 · '+logic.textContent,'logic'); + var hint=document.createElement('p');hint.className='knowledge-hint';hint.textContent='这里展示源码实现,阅读不会执行;运行结果另有标注。';content.appendChild(hint); + var code=document.createElement('pre');code.textContent=note ? note.querySelector('.annot-value').textContent : '此片段的逻辑详情暂不可用。';content.appendChild(code);return; + } + var knowledge=ev.target.closest('.knowledge-explain, [data-knowledge-link]'); + if(knowledge) { + var target=document.getElementById((knowledge.getAttribute('href')||'').slice(1)); + if(target){ev.preventDefault();if(dialog.open)dialog.close();var parent=target;while(parent){if(parent.tagName==='DETAILS')parent.open=true;parent=parent.parentElement;}scrollTo(target);}return; + } + var sourceLink=ev.target.closest('.knowledge-source-link,.knowledge-step a'); + if(sourceLink && dialog.open) dialog.close(); var button = ev.target.closest('[data-reader-action]'); if (button) action(button.dataset.readerAction); var chip = ev.target.closest('.annot-chip'); - if (chip) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); } + if (chip && !chip.classList.contains('annot-implementation')) { openDialog(chip.querySelector('.annot-label').textContent, 'annotation'); var pre = document.createElement('pre'); pre.textContent = chip.title || chip.textContent; content.appendChild(pre); } if (ev.target.closest('.reader-brand')) { ev.preventDefault(); window.scrollTo({top:0,behavior:'auto'}); } if (dialog.open && ev.target.closest('.outline-panel a')) { dialog.close(); } }); function focusNote(ev, focus) { - var chip = ev.target.closest('.annot-chip'); if (!chip || ev.relatedTarget && chip.contains(ev.relatedTarget)) return; + var trigger=ev.target.closest('.annot-chip,[data-logic-id]'); + if(!trigger || ev.relatedTarget && trigger.contains(ev.relatedTarget)) return; + var chip=trigger.matches('.annot-chip') ? trigger : document.getElementById(trigger.dataset.logicId+'-note'); + if(!chip) return; var owner = noteOwner(chip.closest('[data-annot-band]')); var anchor = findAnchor(owner,chip); if (anchor) anchor.classList.toggle('is-focus', focus); chip.classList.toggle('is-focus',focus); diff --git a/src/view/render.rs b/src/view/render.rs index 5630f36..2aaf0fd 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -60,90 +60,9 @@ pub struct FileViewModel { /// View deliberately compiles semantics without running the target, so a page /// can show binding/effect/verification facts even in `--no-exec` exports. /// -/// V0: skip module/type container cards by default; rename lock digest accurately. +/// The reader groups facts by source unit and folds raw identifiers into technical detail. pub fn render_knowledge_html(project: &crate::sema::SemanticProject, rel: &str) -> String { - let artifacts: Vec<_> = project - .artifacts - .iter() - .filter(|artifact| { - artifact.source.file == rel && artifact.kind != "module" && artifact.kind != "type" - }) - .collect(); - let steps: Vec<_> = project.steps.iter().filter(|step| step.source.file == rel).collect(); - if artifacts.is_empty() && steps.is_empty() { - return String::new(); - } - let mut out = String::from(r#"
    "#); - if !steps.is_empty() { - out.push_str(r#"

    文档中的步骤

    结构步骤(非实际执行时序)

      "#); - for step in &steps { - let label = project - .refs - .iter() - .find(|r| r.id == step.reference) - .map(|r| r.label.as_str()) - .unwrap_or(step.reference.as_str()); - let line = step.source.line; - let target_ids = if step.calls.is_empty() { - String::new() - } else { - format!( - r#" → {}"#, - escape(&step.calls.iter().map(|id| id.as_str()).collect::>().join(", ")) - ) - }; - // Structure pane uses #stmt-{line}; jump there for source navigation. - out.push_str(&format!( - "
    1. {0} {2}{3}
    2. ", - escape(&step.kind), - line, - escape(label), - target_ids, - )); - } - out.push_str("
    "); - } - for artifact in artifacts { - let target = artifact.symbol_id.as_ref().map(|id| id.as_str()).unwrap_or(artifact.artifact_id.0.as_str()); - let signature = artifact.signature.as_ref().map(|sig| { - let params = sig.params.iter().map(|param| format!("{}: {}{}", param.name, param.ty, if param.required { "" } else { "?" })).collect::>().join(", "); - format!("({params}) → {}", sig.returns) - }).unwrap_or_else(|| "declaration".into()); - let effects = artifact.effects.values().join(", "); - let deps = if artifact.dependencies.is_empty() { "none".to_string() } else { artifact.dependencies.iter().map(|id| id.0.as_str()).collect::>().join(", ") }; - // Short digest for display; full value in title for copy. - let digest = &artifact.hashes.artifact.0; - let digest_short = if digest.len() > 20 { - format!("{}…", &digest[..20]) - } else { - digest.clone() - }; - let evidence_note = match artifact.verification.evidence.as_str() { - "sourced" => "已关联来源,内容尚未核验", - "verified" => "证据已核验", - "unverified" => "尚无来源记录", - other => other, - }; - out.push_str(&format!( - r#"

    {name} {kind}

    Target
    {target}
    Signature
    {sig}
    Effects
    {effects}
    Verification
    parse: {parse}; resolve: {resolve}; contract: {contract}; tests: {tests}; evidence: {evidence}({evidence_note})
    制品摘要
    {digest_short} (未检查锁定状态)
    Depends on
    {deps}
    Execution
    尚无该知识的运行记录(知识预览不执行)。
    "#, - name = escape(&artifact.display_name), - kind = escape(&artifact.kind), - target = escape(target), - sig = escape(&signature), - effects = escape(&effects), - parse = escape(&artifact.verification.parse), - resolve = escape(&artifact.verification.resolve), - contract = escape(&artifact.verification.contract), - tests = escape(&artifact.verification.tests), - evidence = escape(&artifact.verification.evidence), - evidence_note = escape(evidence_note), - digest = escape(digest), - digest_short = escape(&digest_short), - deps = escape(&deps), - )); - } - out.push_str("
    "); - out + crate::view::knowledge_reading::render(project, rel, None) } /// Collect prompt strings from every `input` / `输入` call in the module (pre-order). @@ -1336,7 +1255,7 @@ fn occl_card(name: Option<&str>, label: &str, payload: Option<&Expr>) -> String escape(&expr_display(e)) ), None => String::from( - "桩", + "待补充实际逻辑", ), }; format!( diff --git a/tests/executable_knowledge/baseline/09-effects/main.mq.md b/tests/executable_knowledge/baseline/09-effects/main.mq.md index 57382a8..a5f6374 100644 --- a/tests/executable_knowledge/baseline/09-effects/main.mq.md +++ b/tests/executable_knowledge/baseline/09-effects/main.mq.md @@ -2,6 +2,8 @@ markup: occlusion title: S2 G06 效应传递与未知不纯 status: implemented +import: + fs: lib/fs.mq.md --- ## save diff --git a/tests/gold.rs b/tests/gold.rs index 160f4d8..8edbd4d 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -198,7 +198,24 @@ fn assert_import_err(path: &str, library: &str, origin: &str, caller: &str, subs for backend in ["tree", "bytecode"] { let (code, stdout, stderr) = run(&["run", path, "--backend", backend]); assert_ne!(code, 0, "{path} backend={backend} unexpectedly succeeded stdout={stdout}"); - let origin = format!("{library}:{origin}:"); + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(library); + let module = marqdo::load::load_module(&source).expect("load actual library origin"); + let mut lines = Vec::new(); + for function in &module.functions { + marqdo::ast::walk_stmts(function, &mut |statement| { + if let marqdo::ast::Stmt::Return { value, span } = statement { + let mut payload = value; + while let marqdo::ast::Expr::Occluded { payload: Some(inner), .. } = payload { + payload = inner; + } + if let marqdo::ast::Expr::Call(call) = payload { + if call.callee == origin { lines.push(span.line); } + } + } + }); + } + assert_eq!(lines.len(), 1, "expected one instruction {origin} in {library}"); + let origin = format!("{library}:{}:1:", lines[0]); assert!(stderr.lines().next().unwrap_or("").contains(&origin), "{path} backend={backend} missing actual library origin {origin:?}: {stderr}"); let caller = format!(" from {path}:{caller}"); @@ -1575,16 +1592,21 @@ fn ext_mq_md_never_calls_host() { #[test] fn catalog_includes_agent_kb_concepts() { let dir = tempfile_dir("mq-cat-kb"); - // Ensure a concept exists under tests/ext agent-kb (offline reuse test leaves one). - let (code, _, stderr) = run(&[ - "run", - "tests/ext/agent-kb-reuse.mq.md", - ]); + // Own the seed and scan root: other agent tests may create/delete their + // private .marqdo files concurrently under tests/ext. + ensure_agent_plugin_built(); + let scan = tempfile_dir("mq-cat-kb-source"); + let seed = scan.join("seed.mq.md"); + std::fs::copy( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/ext/agent-kb-reuse.mq.md"), + &seed, + ).unwrap(); + let (code, _, stderr) = run(&["run", seed.to_str().unwrap()]); assert_eq!(code, 0, "seed kb via reuse test: {stderr}"); let (code, _, stderr) = run(&[ "catalog", - "tests/ext", + scan.to_str().unwrap(), "-o", dir.to_str().unwrap(), "--no-knowledge", @@ -1922,7 +1944,7 @@ fn lib_json_vsafe_refuse() { assert_import_err( "tests/lib/json-vsafe-refuse.mq.md", "lib/json.mq.md", - "16:1", + "host_json_parse", "10:1", "json: integer outside V_safe", ); @@ -1933,7 +1955,7 @@ fn lib_json_vsafe_stringify_refuse() { assert_import_err( "tests/lib/json-vsafe-stringify-refuse.mq.md", "lib/json.mq.md", - "24:1", + "host_json_stringify", "11:1", "json: integer outside V_safe", ); @@ -3671,7 +3693,7 @@ fn lib_foreign_session_vsafe_refuse() { assert_import_err( "tests/lib/foreign-session-vsafe-refuse.mq.md", "lib/foreign.mq.md", - "207:1", + "host_foreign_session_set", "12:1", "json: integer outside V_safe", ); @@ -3686,7 +3708,7 @@ fn lib_foreign_session_use_after_close() { assert_import_err( "tests/lib/foreign-session-use-after-close.mq.md", "lib/foreign.mq.md", - "198:1", + "host_foreign_session_eval", "12:1", "foreign session", ); @@ -3701,7 +3723,7 @@ fn lib_foreign_session_double_close() { assert_import_err( "tests/lib/foreign-session-double-close.mq.md", "lib/foreign.mq.md", - "231:1", + "host_foreign_session_close", "12:1", "foreign session", ); @@ -3713,7 +3735,7 @@ fn lib_foreign_session_use_before_open() { assert_import_err( "tests/lib/foreign-session-use-before-open.mq.md", "lib/foreign.mq.md", - "198:1", + "host_foreign_session_eval", "10:1", "session id must be a handle", ); @@ -3728,7 +3750,7 @@ fn lib_foreign_session_handle_no_serialize() { assert_import_err( "tests/lib/foreign-session-handle-no-serialize.mq.md", "lib/json.mq.md", - "24:1", + "host_json_stringify", "12:1", "session handle cannot be serialized", ); @@ -3743,7 +3765,7 @@ fn lib_foreign_session_result_vsafe_refuse() { assert_import_err( "tests/lib/foreign-session-result-vsafe-refuse.mq.md", "lib/foreign.mq.md", - "198:1", + "host_foreign_session_eval", "11:1", "json: integer outside V_safe", ); @@ -3767,7 +3789,7 @@ fn lib_foreign_session_cold_replay_empty() { assert_import_err( "tests/lib/foreign-session-cold-replay-empty.mq.md", "lib/foreign.mq.md", - "198:1", + "host_foreign_session_eval", "13:1", "foreign session", ); @@ -3782,7 +3804,7 @@ fn lib_foreign_vsafe_refuse() { assert_import_err( "tests/lib/foreign-vsafe-refuse.mq.md", "lib/json.mq.md", - "16:1", + "host_json_parse", "21:1", "json: integer outside V_safe", ); @@ -3797,7 +3819,7 @@ fn lib_foreign_vsafe_postarith_refuse() { assert_import_err( "tests/lib/foreign-vsafe-postarith-refuse.mq.md", "lib/json.mq.md", - "16:1", + "host_json_parse", "22:1", "json: integer outside V_safe", ); diff --git a/tests/library_authoring.rs b/tests/library_authoring.rs new file mode 100644 index 0000000..1128144 --- /dev/null +++ b/tests/library_authoring.rs @@ -0,0 +1,461 @@ +//! Exercise the authoring rules and actual package workflows, including repaired old paths. +use serde_json::Value; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, + sync::OnceLock, +}; +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} +fn sources(dir: &Path, out: &mut Vec) { + for e in fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + sources(&p, out) + } else if p.to_string_lossy().ends_with(".mq.md") { + out.push(p) + } + } +} +fn native() { + static READY: OnceLock<()> = OnceLock::new(); + READY.get_or_init(|| { + let out = Command::new("cargo") + .current_dir(root()) + .args([ + "build", + "--offline", + "-p", + "marqdo_plugin_agent", + "-p", + "marqdo_plugin_linalg", + ]) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let out = Command::new("bash") + .current_dir(root()) + .arg("scripts/build-web-plugin.sh") + .env("GOFLAGS", "-buildvcs=false") + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + }); +} +fn command() -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_marqdo")); + c.current_dir(root()) + .env("MARQDO_EXT", root().join("ext")) + .env("MARQDO_LIB", root().join("lib")); + for (name, file) in [ + ("WEB", "plugins/web/build/libweb.so"), + ("AGENT", "target/debug/libagent.so"), + ("LINALG", "target/debug/liblinalg.so"), + ] { + c.env(format!("MARQDO_{name}_PLUGIN"), root().join(file)); + } + c +} +fn call(backend: &str, file: &str, function: &str, args: &[&str], effects: &str) -> Value { + let mut cmd = command(); + let mut root_arg = None; + if effects.contains("fs.write") { + let work = std::env::temp_dir().join(format!("mq-authoring-data-{}", std::process::id())); + fs::create_dir_all(&work).unwrap(); + root_arg = Some(format!("root=\"{}\"", work.display())); + cmd.arg("call").arg("--fs-root").arg(work); + } else { + cmd.arg("call"); + } + let out = cmd + .args([ + "--backend", + backend, + "--json", + "--effects", + effects, + file, + function, + ]) + .args(args) + .args(root_arg) + .output() + .unwrap(); + let v: Value = serde_json::from_slice(&out.stdout).unwrap_or_else(|_| { + panic!( + "{file} {function}: {} {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }); + assert!(out.status.success(), "{backend} {file} {function}: {v}"); + assert_eq!(v["ok"], true, "{v}"); + v["result"].clone() +} +#[test] +fn all_library_units_follow_the_single_source_guide() { + let mut paths = Vec::new(); + sources(&root().join("lib"), &mut paths); + sources(&root().join("ext"), &mut paths); + assert!(paths.len() >= 125); + let mut gaps = Vec::new(); + for path in paths { + let source = fs::read_to_string(&path).unwrap(); + let module = marqdo::load::load_module(&path) + .unwrap_or_else(|e| panic!("{}: {e:#}", path.display())); + let diagnostics = marqdo::check::check_path(&path).unwrap(); + if !diagnostics.is_empty() { + gaps.push(format!("{}: {diagnostics:?}", path.display())) + } + for report in marqdo::narrative_ratio::measure_source_units(&source, &module.functions) { + if report.ratio <= 0.5 { + gaps.push(format!( + "{} {} narrative {:.1}%", + path.display(), + report.name, + report.ratio * 100.0 + )) + } + } + fn units( + functions: &[marqdo::ast::Function], + source: &str, + path: &Path, + gaps: &mut Vec, + ) { + for f in functions { + let c = f + .contract + .as_ref() + .unwrap_or_else(|| panic!("{} {} missing contract", path.display(), f.name)); + assert!( + c.returns.is_some(), + "{} {} no return contract", + path.display(), + f.name + ); + assert_eq!( + c.params.len(), + f.params.len(), + "{} {} parameter mismatch", + path.display(), + f.name + ); + assert!( + f.params.iter().all(|p| p.inferred), + "{} {} legacy parameter", + path.display(), + f.name + ); + let first = source + .lines() + .skip(f.span.line as usize) + .find(|l| !l.trim().is_empty()) + .unwrap(); + if !first.starts_with(if f.params.is_empty() { + "| 返回 |" + } else { + "| 参数 |" + }) { + gaps.push(format!( + "{} {} contracts are not directly below heading", + path.display(), + f.name + )) + } + units(&f.children, source, path, gaps); + } + } + units(&module.functions, &source, &path, &mut gaps); + let mut fence = false; + for (line, text) in source.lines().enumerate() { + let t = text.trim(); + if t.starts_with("```") { + fence = !fence; + continue; + } + if fence { + continue; + } + if t.starts_with("+ `") { + gaps.push(format!("{}:{} legacy parameters", path.display(), line + 1)) + } + if t.starts_with('>') { + gaps.push(format!("{}:{} isolated call", path.display(), line + 1)) + } + if t.starts_with('*') + && t.ends_with('*') + && !t.starts_with("**_ =") + && !t.trim_matches('*').trim_end().ends_with('=') + { + gaps.push(format!( + "{}:{} isolated statement/return", + path.display(), + line + 1 + )) + } + } + } + assert!( + gaps.is_empty(), + "{} authoring gaps:\n{}", + gaps.len(), + gaps.join("\n") + ); +} +#[test] +fn new_package_workflows_return_real_results_on_both_backends() { + native(); + for backend in ["tree", "bytecode"] { + let cached = call( + backend, + "ext/data/index.mq.md", + "memory_cache", + &["key=\"manual-test\"", "value=\"retained\""], + "plugin", + ); + assert_eq!(cached["value"], "retained"); + let tx = call( + backend, + "ext/data/index.mq.md", + "transaction_roundtrip", + &[], + "plugin,fs.write", + ); + assert_eq!(tx["rows"].as_array().unwrap().len(), 1); + assert_eq!(tx["rows"][0]["title"], "committed"); + fs::remove_dir_all(tx["work_dir"].as_str().unwrap()).unwrap(); + for (held, allowed) in [("notes:read", true), ("notes:write", false)] { + let arg = format!("held=\"{held}\""); + let result = call( + backend, + "ext/security/index.mq.md", + "check_permission", + &[&arg, "needed=\"notes:read\""], + "plugin", + ); + assert_eq!(result["ok"], true); + assert_eq!(result["allowed"], allowed); + } + assert_eq!( + call( + backend, + "ext/net/index.mq.md", + "encode", + &["text=\"Marqdo notes/one\""], + "none" + ), + "Marqdo%20notes%2Fone" + ); + for (file, entry) in [ + ("ext/linalg/index.mq.md", "solve_example"), + ("ext/linalg/索引.mq.md", "求解示例"), + ] { + let result = call(backend, file, entry, &[], "plugin"); + let rows = &result["x"]["data"]; + assert!( + (rows[0][0].as_f64().unwrap() - 2.0).abs() < 1e-9, + "{result}" + ); + assert!( + (rows[1][0].as_f64().unwrap() - 1.0).abs() < 1e-9, + "{result}" + ); + } + for (file, entry) in [ + ("ext/ai/index.mq.md", "offline_example"), + ("ext/ai/索引.mq.md", "离线示例"), + ] { + assert_eq!(call(backend, file, entry, &[], "none"), "Hello world"); + } + let usage = call( + backend, + "ext/ai/llm/index.mq.md", + "usage", + &["data={\"usage\":{\"prompt_tokens\":2,\"completion_tokens\":3,\"total_tokens\":5}}"], + "none", + ); + assert_eq!(usage["total_tokens"], 5); + let policy = call( + backend, + "ext/ai/policies/step-route.mq.md", + "routes", + &[], + "none", + ); + assert_eq!(policy["kind"][0], "lookup"); + assert_eq!(policy["backend"][4], "auto"); + } +} +#[test] +fn chinese_step_runs_its_body_instead_of_returning_a_prose_word() { + native(); + let path = std::env::temp_dir().join(format!( + "mq-authoring-chinese-step-{}.mq.md", + std::process::id() + )); + fs::write( + &path, + r#"--- +markup: occlusion +import: + 智能: ext/ai/智能体.mq.md + 表: lib/表.mq.md + json: lib/json.mq.md +--- +# 回复器 + +*None* + +## 运行 + +根据上下文`提示`生成离线固定回答;本例不连接模型服务。 + +**字符数 = len value=`提示`** +*"deterministic answer"* + +# main + +**模型 = 回复器()** +**工具 = 表.空表()** +**执行器 = 智能.智能体(大模型=`模型`, 工具=`工具`, 站立提示="")** +**结果 = > `执行器`.单步 任务="offline step" 写回=False** +**wire = json.stringify value=`结果`** +> print text=`wire` +"#, + ) + .unwrap(); + for backend in ["tree", "bytecode"] { + let output = command() + .args(["run", path.to_str().unwrap(), "--backend", backend]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let v: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(v["status"], "ok"); + assert_eq!(v["task"], "offline step"); + assert_eq!(v["result"], "deterministic answer"); + } + fs::remove_file(path).unwrap(); +} + +#[test] +fn pair_records_preserve_nulls_last_value_and_source_rows() { + for backend in ["tree", "bytecode"] { + for (file, entry, argument) in [ + ("lib/table.mq.md", "from_pairs", "pairs"), + ("lib/表.mq.md", "键值转记录", "键值对"), + ] { + assert_eq!( + call(backend, file, entry, &[&format!("{argument}=[]")], "none"), + serde_json::json!({}) + ); + let rows = format!("{argument}=[{{\"key\":\"first\",\"value\":1}},{{\"key\":\"null\",\"value\":null}},{{\"key\":\"first\",\"value\":3,\"ignored\":true}}]"); + assert_eq!( + call(backend, file, entry, &[&rows], "none"), + serde_json::json!({"first":3,"null":null}) + ); + } + let path = + std::env::temp_dir().join(format!("mq-pair-records-{}.mq.md", std::process::id())); + fs::write( + &path, + r#"--- +import: + table: lib/table.mq.md + json: lib/json.mq.md +--- +# main + +`rows` = + +| @ | key | value | +|---|---|---| +| 1 | first | 1 | +| 2 | second | None | +| 3 | first | 3 | + +**original = json.stringify(value=`rows`)** +**record = table.from_pairs(pairs=`rows`)** +**after = json.stringify(value=`rows`)** +**keys = table.keys(map=`record`)** + +`out` = + +| original | after | keys | +|---|---|---| +| `original` | `after` | `keys` | + +**wire = json.stringify(value=`out`)** +> print text=`wire` +"#, + ) + .unwrap(); + let output = command() + .args(["run", path.to_str().unwrap(), "--backend", backend]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value["original"], value["after"]); + assert_eq!(value["keys"], serde_json::json!(["first", "second"])); + fs::remove_file(path).unwrap(); + } +} + +#[test] +fn shipped_package_sources_include_their_runtime_imports_and_entries() { + use std::collections::BTreeSet; + let catalog = marqdo::ext_cli::CATALOG; + let files: BTreeSet<_> = catalog + .iter() + .flat_map(|p| p.mq_files.iter().copied()) + .collect(); + for package in catalog { + for file in package.mq_files { + let path = root().join("ext").join(file); + let module = marqdo::load::load_module(&path).unwrap(); + for import in &module.imports { + if let Some(dependency) = import.path.strip_prefix("ext/") { + assert!( + files.contains(dependency), + "{} imports an unshipped source {}", + path.display(), + import.path + ); + } + } + } + } + for entry in [ + "ai/index.mq.md", + "ai/索引.mq.md", + "ai/llm/index.mq.md", + "ai/policies/step-route.mq.md", + "data/index.mq.md", + "net/index.mq.md", + "security/index.mq.md", + "linalg/index.mq.md", + "linalg/索引.mq.md", + ] { + assert!(files.contains(entry), "unshipped entry {entry}"); + } +} diff --git a/tests/stdlib_tasks.rs b/tests/stdlib_tasks.rs new file mode 100644 index 0000000..0b9291d --- /dev/null +++ b/tests/stdlib_tasks.rs @@ -0,0 +1,1275 @@ +//! Exercise public documents on both runtimes; no private host-only shortcuts. +use serde_json::{json, Value}; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, + sync::atomic::{AtomicU64, Ordering}, +}; +static SEQ: AtomicU64 = AtomicU64::new(0); +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} +struct Scratch(PathBuf); +impl Scratch { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "mq-stdlib-{}-{}", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&p).unwrap(); + Self(p) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn call( + backend: &str, + module: &str, + function: &str, + args: &[&str], + effects: &str, + dir: Option<&Path>, +) -> Value { + let mut c = Command::new(env!("CARGO_BIN_EXE_marqdo")); + c.current_dir(root()) + .args(["call", "--json", "--backend", backend, "--effects", effects]); + if let Some(dir) = dir { + c.arg("--fs-root").arg(dir); + } + let out = c.arg(module).arg(function).args(args).output().unwrap(); + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "{module} {function}: {e}: {} {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }) +} +fn ok(v: Value) -> Value { + assert_eq!(v["ok"], true, "{v}"); + v["result"].clone() +} +#[test] +fn field_transforms_and_table_shapes_are_real_public_tools() { + for backend in ["tree", "bytecode"] { + let m = "lib/table.mq.md"; + assert_eq!( + ok(call( + backend, + m, + "range", + &["start=5", "end=0", "step=-2"], + "none", + None + )), + json!([5, 3, 1]) + ); + let rows = + "list=[{\"team\":\"a\",\"n\":3},{\"team\":\"b\",\"n\":1},{\"team\":\"a\",\"n\":2}]"; + assert_eq!( + ok(call( + backend, + m, + "pluck", + &[rows, "key=\"n\""], + "none", + None + )), + json!([3, 1, 2]) + ); + let groups = ok(call( + backend, + m, + "group_by", + &[rows, "key=\"team\""], + "none", + None, + )); + assert_eq!(groups[0]["count"], 2); + assert_eq!(groups[1]["key"], "b"); + assert_eq!( + ok(call( + backend, + m, + "aggregate", + &[rows, "key=\"n\""], + "none", + None + )), + 6 + ); + assert_eq!( + ok(call( + backend, + m, + "where", + &[rows, "key=\"n\"", "value=2", "op=\"ge\""], + "none", + None + )) + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!( + ok(call( + backend, + m, + "from_columns", + &["columns={\"a\":[1,2],\"b\":[3,4]}"], + "none", + None + )), + json!([{"a":1,"b":3},{"a":2,"b":4}]) + ); + assert_eq!( + call( + backend, + m, + "from_columns", + &["columns={\"a\":[1],\"b\":[3,4]}"], + "none", + None + )["ok"], + false + ); + let joined = ok(call( + backend, + m, + "join", + &[ + "a=[{\"id\":1,\"name\":\"left\"},{\"id\":2,\"name\":\"only\"}]", + "b=[{\"id\":1,\"name\":\"right\"}]", + "key=\"id\"", + "right_key=\"id\"", + "mode=\"left\"", + ], + "none", + None, + )); + assert_eq!(joined[0]["right_name"], "right"); + assert_eq!(joined[1]["right_name"], Value::Null); + assert_eq!( + ok(call( + backend, + m, + "cast", + &[ + "rows=[{\"n\":\"42\",\"yes\":\"true\"}]", + "schema={\"n\":\"int\",\"yes\":\"bool\"}" + ], + "none", + None + )), + json!([{"n":42,"yes":true}]) + ); + assert_eq!( + ok(call( + backend, + "lib/表.mq.md", + "分组", + &[&rows.replace("list=", "列表="), "键=\"team\""], + "none", + None + )), + groups + ); + assert_eq!( + ok(call( + backend, + "lib/path.mq.md", + "with_extension", + &["path=\"a/b.txt\"", "extension=\"md\""], + "none", + None + )), + "a/b.md" + ); + } +} +#[test] +fn file_tasks_cover_binary_chunks_atomicity_and_conflicts() { + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + let dir = Some(scratch.0.as_path()); + let m = "lib/fs.mq.md"; + fs::write(scratch.0.join("binary"), [0u8, 255, 128]).unwrap(); + let bytes = ok(call( + backend, + m, + "read_bytes", + &["path=\"binary\""], + "fs.read", + dir, + )); + assert_eq!(bytes, json!({"_type":"bytes","base64":"AP+A"})); + let chunk = ok(call( + backend, + m, + "read_chunk", + &["path=\"binary\"", "offset=1", "size=1"], + "fs.read", + dir, + )); + assert_eq!(chunk["data"]["base64"], "/w=="); + assert_eq!(chunk["next_offset"], 2); + assert_eq!(chunk["eof"], false); + ok(call( + backend, + m, + "write_bytes", + &[ + "path=\"copy\"", + "data={\"_type\":\"bytes\",\"base64\":\"AP+A\"}", + ], + "fs.write", + dir, + )); + assert_eq!(fs::read(scratch.0.join("copy")).unwrap(), [0, 255, 128]); + assert_eq!( + call(backend, m, "exists", &["path=\"copy\""], "none", dir)["error"]["code"], + "artifact.effect_denied" + ); + ok(call( + backend, + m, + "atomic_write", + &["path=\"nested/a.txt\"", "text=\"old\""], + "fs.write", + dir, + )); + assert_eq!( + ok(call( + backend, + m, + "write_changed", + &["path=\"nested/a.txt\"", "text=\"old\""], + "fs.write", + dir + )), + false + ); + let conflict = ok(call( + backend, + m, + "write_checked", + &[ + "path=\"nested/a.txt\"", + "text=\"new\"", + "expected_sha256=\"wrong\"", + ], + "fs.write", + dir, + )); + assert_eq!(conflict["error"]["code"], "conflict"); + assert_eq!( + fs::read_to_string(scratch.0.join("nested/a.txt")).unwrap(), + "old" + ); + let result = ok(call( + backend, + m, + "try_read_text", + &["path=\"missing\""], + "fs.read", + dir, + )); + assert_eq!(result["ok"], false); + assert_eq!(result["error"]["code"], "not_found"); + let found = ok(call( + backend, + m, + "find", + &["path=\".\"", "pattern=\"**/*.txt\""], + "fs.read", + dir, + )); + assert_eq!(found, json!(["nested/a.txt"])); + assert_eq!( + call( + backend, + m, + "remove_file", + &["path=\"nested\""], + "fs.write", + dir + )["ok"], + false + ); + assert!(scratch.0.join("nested/a.txt").exists()); + let planned = ok(call( + backend, + m, + "copy_tree", + &["src=\"nested\"", "dest=\"backup\"", "dry_run=True"], + "fs.write", + dir, + )); + assert_eq!(planned, json!(["a.txt"])); + assert!(!scratch.0.join("backup").exists()); + ok(call( + backend, + m, + "copy_tree", + &["src=\"nested\"", "dest=\"backup\""], + "fs.write", + dir, + )); + assert_eq!( + fs::read_to_string(scratch.0.join("backup/a.txt")).unwrap(), + "old" + ); + assert_eq!( + ok(call( + backend, + m, + "sync_tree", + &["src=\"nested\"", "dest=\"backup\""], + "fs.write", + dir + )), + json!([]) + ); + assert_eq!( + call( + backend, + m, + "read_text", + &["path=\"../outside\""], + "fs.read", + dir + )["ok"], + false + ); + } +} +#[test] +fn effects_follow_host_identity_through_aliases_and_chinese() { + let scratch = Scratch::new(); + let library = root().join("lib/文件.mq.md"); + let source=format!("---\nmarkup: occlusion\nimport:\n disk: {}\n---\n\n## query\n\n*> disk.存在 路径=\"a.txt\"*\n",library.display()); + let file = scratch.0.join("caller.mq.md"); + fs::write(&file, source).unwrap(); + fs::write(scratch.0.join("a.txt"), "a").unwrap(); + for backend in ["tree", "bytecode"] { + let file = file.to_str().unwrap(); + assert_eq!( + call(backend, file, "query", &[], "none", None)["error"]["code"], + "artifact.effect_denied" + ); + assert_eq!(ok(call(backend, file, "query", &[], "fs.read", None)), true); + assert_eq!( + call( + backend, + "lib/文件.mq.md", + "存在", + &["路径=\"a.txt\""], + "none", + Some(&scratch.0) + )["error"]["code"], + "artifact.effect_denied" + ); + } +} +#[cfg(unix)] +#[test] +fn sandbox_rejects_symlink_escapes_even_for_new_descendants() { + use std::os::unix::fs::symlink; + let inside = Scratch::new(); + let outside = Scratch::new(); + symlink(&outside.0, inside.0.join("escape")).unwrap(); + for backend in ["tree", "bytecode"] { + assert_eq!( + call( + backend, + "lib/fs.mq.md", + "write_text", + &["path=\"escape/new/a.txt\"", "text=\"no\""], + "fs.write", + Some(&inside.0) + )["ok"], + false + ); + assert!(!outside.0.join("new").exists()); + } +} + +#[test] +fn inert_documents_preserve_surrounding_source_and_reject_ambiguity() { + let source="---\ntitle: sample\n---\n\n# Intro\n\nkeep\n\n## Data\n\n| item | n |\n|---|---|\n| a | 2 |\n\n```mq\n> fs.remove_tree path=\".\"\n# not a heading\n```\n\n# End\n\nleave me\n"; + for backend in ["tree", "bytecode"] { + let text = format!("text=\"{source}\""); + let sections = ok(call( + backend, + "lib/document.mq.md", + "sections", + &[&text], + "none", + None, + )); + assert_eq!(sections.as_array().unwrap().len(), 3); + let tables = ok(call( + backend, + "lib/document.mq.md", + "tables", + &[&text], + "none", + None, + )); + assert_eq!(tables[0]["headers"], json!(["item", "n"])); + assert_eq!(tables[0]["rows"], json!([["a", "2"]])); + let code = ok(call( + backend, + "lib/document.mq.md", + "code_blocks", + &[&text], + "none", + None, + )); + assert!(code[0]["text"].as_str().unwrap().contains("remove_tree")); + let result = ok(call( + backend, + "lib/document.mq.md", + "replace_section", + &[&text, "title=\"Data\"", "body=\"replacement\""], + "none", + None, + )); + assert_eq!(result["ok"], true); + let changed = result["value"].as_str().unwrap(); + assert!(changed.starts_with("---\ntitle: sample\n---\n\n# Intro\n\nkeep")); + assert!(changed.ends_with("# End\n\nleave me\n")); + assert!(changed.contains("## Data\n\nreplacement\n")); + let replaced = ok(call( + backend, + "lib/document.mq.md", + "replace_table", + &[ + &text, + "index=0", + "headers=[\"item\",\"n\"]", + "rows=[[\"b\",\"3\"]]", + ], + "none", + None, + )); + assert_eq!(replaced["ok"], true); + assert!(replaced["value"] + .as_str() + .unwrap() + .contains("# not a heading")); + let conflict = ok(call( + backend, + "lib/document.mq.md", + "replace_section", + &[ + &text, + "title=\"Data\"", + "body=\"x\"", + "expected_sha256=\"stale\"", + ], + "none", + None, + )); + assert_eq!(conflict["error"]["code"], "conflict"); + } +} +#[test] +fn timezone_dst_and_full_toml_have_explicit_data_boundaries() { + for backend in ["tree", "bytecode"] { + let gap = ok(call( + backend, + "lib/datetime.mq.md", + "parse_local", + &["text=\"2024-03-10 02:30:00\"", "zone=\"America/New_York\""], + "none", + None, + )); + assert_eq!(gap["ok"], false); + let args = [ + "text=\"2024-11-03 01:30:00\"", + "zone=\"America/New_York\"", + "ambiguity=\"earliest\"", + ]; + let early = ok(call( + backend, + "lib/datetime.mq.md", + "parse_local", + &args, + "none", + None, + )); + let late = ok(call( + backend, + "lib/datetime.mq.md", + "parse_local", + &[args[0], args[1], "ambiguity=\"latest\""], + "none", + None, + )); + assert_eq!( + late["value"]["unix"].as_i64().unwrap() - early["value"]["unix"].as_i64().unwrap(), + 3600 + ); + let before = ok(call( + backend, + "lib/datetime.mq.md", + "parse_local", + &["text=\"2024-03-09 12:00:00\"", args[1]], + "none", + None, + )); + let dt = format!("dt={}", before["value"]); + let after = ok(call( + backend, + "lib/datetime.mq.md", + "add_calendar", + &[&dt, "days=1"], + "none", + None, + )); + assert_eq!( + after["value"]["unix"].as_i64().unwrap() - before["value"]["unix"].as_i64().unwrap(), + 23 * 3600 + ); + let elapsed = ok(call( + backend, + "lib/datetime.mq.md", + "add", + &[&dt, "days=1"], + "none", + None, + )); + assert!(elapsed["iso"].as_str().unwrap().contains("13:00:00-04:00")); + let toml="text=\"[app]\ninline = { ok = true }\n[[workers]]\nname = 'one'\n[[workers]]\nname = 'two'\n\""; + let parsed = ok(call( + backend, + "lib/toml.mq.md", + "parse", + &[toml], + "none", + None, + )); + assert_eq!(parsed["workers"].as_array().unwrap().len(), 2); + assert_eq!(parsed["app"]["inline"]["ok"], true); + let value = format!("value={parsed}"); + let rendered = ok(call( + backend, + "lib/toml.mq.md", + "stringify", + &[&value], + "none", + None, + )); + let text = format!("text=\"{}\"", rendered.as_str().unwrap()); + assert_eq!( + ok(call( + backend, + "lib/toml.mq.md", + "parse", + &[&text], + "none", + None + )), + parsed + ); + } +} +#[test] +fn bounded_file_batch_inherits_parent_permissions_and_returns_ordered_results() { + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + fs::write(scratch.0.join("one.mq.md"), "# main\n\n*1*\n").unwrap(); + fs::write(scratch.0.join("two.mq.md"), "# main\n\n*2*\n").unwrap(); + fs::write(scratch.0.join("write.mq.md"),format!("---\nimport:\n fs: {}\n---\n# main\n\n> fs.write_text path=forbidden text=no\n*3*\n",root().join("lib/fs.mq.md").display())).unwrap(); + let results=ok(call(backend,"lib/subtask.mq.md","run_many",&["tasks=[{\"path\":\"one.mq.md\"},{\"path\":\"two.mq.md\"},{\"path\":\"write.mq.md\"}]","limit=2"],"process.exec",Some(&scratch.0))); + assert_eq!(results[0]["value"]["value"], 1); + assert_eq!(results[1]["value"]["value"], 2); + assert_ne!(results[2]["value"]["code"], 0); + assert!(!scratch.0.join("forbidden").exists()); + } +} + +fn public_standard_libraries() -> Vec { + let mut files: Vec<_> = fs::read_dir(root().join("lib")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.is_file() && path.to_string_lossy().ends_with(".mq.md")) + .collect(); + files.sort(); + files +} + +#[test] +fn single_file_source_examples_execute_on_both_backends() { + let guides = public_standard_libraries(); + assert!(guides.len() >= 60, "missing standard library sources"); + for path in guides { + let source = fs::read_to_string(&path).unwrap(); + let mut shell = false; + let mut commands = Vec::new(); + for line in source.lines() { + if line == "```sh" { + shell = true + } else if line == "```" { + shell = false + } else if shell && !line.trim().is_empty() { + commands.push(line.to_string()); + } + } + assert!( + !commands.is_empty(), + "{} lacks an executable recipe", + path.display() + ); + let errors = marqdo::check::check_path(&path).unwrap(); + assert!(errors.is_empty(), "{}: {errors:?}", path.display()); + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + fs::create_dir(scratch.0.join("input")).unwrap(); + fs::write(scratch.0.join("input/note.txt"), "Archive example").unwrap(); + for command in &commands { + assert!(command.starts_with("marqdo call "), "{command}"); + let command = command.replacen( + "marqdo call ", + &format!( + "\"{}\" call --backend {backend} ", + env!("CARGO_BIN_EXE_marqdo") + ), + 1, + ); + let out = Command::new("bash") + .args(["--noprofile", "--norc", "-ec", &command]) + .env_remove("BASH_ENV") + .env("MQ_WORK", &scratch.0) + .current_dir(root()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{} [{backend}] {command}: {} {}", + path.display(), + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + let body: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(body["ok"], true, "{body}"); + if body["result"]["ok"].is_boolean() { + assert_eq!( + body["result"]["ok"], true, + "example returned failure: {body}" + ); + } + } + } + } +} + +#[test] +fn complete_engineering_example_runs_in_a_disposable_root() { + for backend in ["tree", "bytecode"] { + for (file, function) in [ + ("examples/stdlib-handbook/index.mq.md", "demo"), + ("examples/stdlib-handbook/索引.mq.md", "演示"), + ] { + let scratch = Scratch::new(); + let result = ok(call( + backend, + file, + function, + &[], + "fs.write", + Some(&scratch.0), + )); + let files = result["inventory"].as_array().unwrap(); + assert_eq!(files.len(), 2); + assert_eq!(files.iter().filter(|row| row["ok"] == true).count(), 1); + assert_eq!(files.iter().filter(|row| row["ok"] == false).count(), 1); + assert!(result["csv"].as_str().unwrap().contains("a,30,2")); + assert_eq!(result["update"]["ok"], true); + let document = result["document"].as_str().unwrap(); + assert!(document.contains("Updated through public")); + assert!(document.contains("# Appendix\n\nKeep this paragraph.")); + assert_eq!( + fs::read_dir(&scratch.0).unwrap().count(), + 0, + "demo leaked its temporary tree" + ); + } + } +} +#[test] +fn optional_zip_roundtrip_and_expansion_preflight() { + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + let dir = Some(scratch.0.as_path()); + fs::create_dir(scratch.0.join("input")).unwrap(); + fs::write(scratch.0.join("input/data.bin"), [0u8, 255]).unwrap(); + let packed = ok(call( + backend, + "lib/archive.mq.md", + "pack", + &["src=\"input\"", "dest=\"bundle.zip\""], + "fs.write", + dir, + )); + assert_eq!(packed["ok"], true); + let limited = ok(call( + backend, + "lib/archive.mq.md", + "unpack", + &["src=\"bundle.zip\"", "dest=\"too-large\"", "max_bytes=1"], + "fs.write", + dir, + )); + assert_eq!(limited["ok"], false); + assert!(!scratch.0.join("too-large").exists()); + let unpacked = ok(call( + backend, + "lib/archive.mq.md", + "unpack", + &["src=\"bundle.zip\"", "dest=\"output\""], + "fs.write", + dir, + )); + assert_eq!(unpacked["ok"], true); + assert_eq!( + fs::read(scratch.0.join("output/data.bin")).unwrap(), + [0, 255] + ); + } +} +#[test] +fn http_results_keep_status_headers_and_binary_downloads() { + use std::{ + io::{Read, Write}, + net::TcpListener, + thread, + time::Duration, + }; + for backend in ["tree", "bytecode"] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = thread::spawn(move || { + for i in 0..4 { + let (mut socket, _) = listener.accept().unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buffer = [0u8; 4096]; + let _ = socket.read(&mut buffer); + let body = if i == 2 || i == 3 { + vec![0u8, 255, 128] + } else { + b"ready".to_vec() + }; + let status = if i == 1 { "404 Not Found" } else { "200 OK" }; + let header=format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nX-Example: yes\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\nConnection: close\r\n\r\n",body.len()); + socket.write_all(header.as_bytes()).unwrap(); + socket.write_all(&body).unwrap(); + } + }); + let url = format!("url=\"http://{addr}/sample\""); + let response = ok(call( + backend, + "lib/net.mq.md", + "get", + &[&url], + "network.read", + None, + )); + assert_eq!(response["ok"], true); + assert_eq!(response["value"]["status"], 200); + assert_eq!(response["value"]["body"], "ready"); + assert_eq!( + response["value"]["headers"] + .as_array() + .unwrap() + .iter() + .find(|row| row["name"] == "set-cookie") + .unwrap()["values"] + .as_array() + .unwrap() + .len(), + 2 + ); + let response = ok(call( + backend, + "lib/net.mq.md", + "get", + &[&url], + "network.read", + None, + )); + assert_eq!(response["ok"], true); + assert_eq!(response["value"]["status"], 404); + let response = ok(call( + backend, + "lib/net.mq.md", + "get", + &[&url, "response=\"bytes\""], + "network.read", + None, + )); + assert_eq!(response["value"]["body"]["base64"], "AP+A"); + let scratch = Scratch::new(); + let download = ok(call( + backend, + "lib/net.mq.md", + "download", + &[&url, "path=\"download.bin\""], + "network.read,fs.write", + Some(&scratch.0), + )); + assert_eq!(download["ok"], true); + assert_eq!( + fs::read(scratch.0.join("download.bin")).unwrap(), + [0, 255, 128] + ); + server.join().unwrap(); + } +} + +#[test] +fn timeout_retains_a_handle_until_the_caller_chooses_to_join() { + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + fs::write( + scratch.0.join("child.mq.md"), + format!( + "---\nimport:\n time: {}\n---\n# main\n\n> time.sleep_ms ms=100\n*17*\n", + root().join("lib/time.mq.md").display() + ), + ) + .unwrap(); + let source=format!("---\nmarkup: occlusion\nimport:\n task: {}\n---\n\n## example\n\n**id = task.spawn path=\"child.mq.md\"**\n**early = task.wait_timeout id=`id` timeout_ms=1**\n**late = task.wait_timeout id=`id` timeout_ms=2000 cancel=True**\n`out` =\n\n| early | late |\n|---|---|\n| `early` | `late` |\n\n*out*\n",root().join("lib/subtask.mq.md").display()); + let parent = scratch.0.join("parent.mq.md"); + fs::write(&parent, source).unwrap(); + let value = ok(call( + backend, + parent.to_str().unwrap(), + "example", + &[], + "process.exec", + None, + )); + assert_eq!(value["early"]["error"]["code"], "timed_out"); + assert_eq!(value["late"]["ok"], true); + assert_eq!(value["late"]["value"]["value"], 17); + } +} +#[test] +fn validation_set_operations_and_batch_aggregation_share_collection_semantics() { + for backend in ["tree", "bytecode"] { + let m = "lib/table.mq.md"; + assert_eq!( + ok(call( + backend, + m, + "union", + &["a=[1,2,1]", "b=[2,3]"], + "none", + None + )), + json!([1, 2, 3]) + ); + let validation = ok(call( + backend, + m, + "validate", + &[ + "rows=[{\"n\":1},{\"n\":\"bad\"},{}]", + "schema={\"n\":\"number\"}", + ], + "none", + None, + )); + assert_eq!(validation["error"]["code"], "validation_failed"); + assert_eq!(validation["error"]["details"].as_array().unwrap().len(), 2); + let cast = ok(call( + backend, + m, + "try_cast", + &["rows=[{\"n\":\"bad\"}]", "schema={\"n\":\"int\"}"], + "none", + None, + )); + assert_eq!(cast["ok"], false); + let summary = ok(call( + backend, + m, + "summarize", + &[ + "list=[{\"team\":\"a\",\"n\":1},{\"team\":\"a\",\"n\":2},{\"team\":\"b\",\"n\":4}]", + "key=\"team\"", + "field=\"n\"", + ], + "none", + None, + )); + assert_eq!( + summary, + json!([{"key":"a","count":2,"value":3},{"key":"b","count":1,"value":4}]) + ); + } +} + +#[test] +fn invalid_http_options_send_nothing_and_failed_download_keeps_original() { + use std::{ + io::{Read, Write}, + net::TcpListener, + thread, + time::Duration, + }; + for backend in ["tree", "bytecode"] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let url = format!("url=\"http://{}/\"", listener.local_addr().unwrap()); + let result = ok(call( + backend, + "lib/net.mq.md", + "request", + &[ + &url, + "method=\"POST\"", + "body=\"must not send\"", + "response=\"invalid\"", + ], + "network.write", + None, + )); + assert_eq!(result["error"]["code"], "invalid_argument"); + assert!( + matches!(listener.accept(),Err(error) if error.kind()==std::io::ErrorKind::WouldBlock) + ); + let scratch = Scratch::new(); + let result = ok(call( + backend, + "lib/net.mq.md", + "download", + &[&url, "path=\"../escape.bin\""], + "network.read,fs.write", + Some(&scratch.0), + )); + assert_eq!(result["error"]["code"], "permission_denied"); + assert!( + matches!(listener.accept(),Err(error) if error.kind()==std::io::ErrorKind::WouldBlock) + ); + listener.set_nonblocking(false).unwrap(); + let server = thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = [0u8; 2048]; + let _ = socket.read(&mut request); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\n12345678", + ) + .unwrap(); + }); + fs::write(scratch.0.join("saved.bin"), "keep").unwrap(); + let result = ok(call( + backend, + "lib/net.mq.md", + "download", + &[&url, "path=\"saved.bin\"", "max_bytes=3"], + "network.read,fs.write", + Some(&scratch.0), + )); + assert_eq!(result["error"]["code"], "resource_limit"); + assert_eq!(fs::read(scratch.0.join("saved.bin")).unwrap(), b"keep"); + assert_eq!(fs::read_dir(&scratch.0).unwrap().count(), 1); + server.join().unwrap(); + } +} +#[test] +fn zip_preflight_rejects_escaping_and_symlink_entries() { + use std::io::Write; + for backend in ["tree", "bytecode"] { + let scratch = Scratch::new(); + let file = fs::File::create(scratch.0.join("escaping.zip")).unwrap(); + let mut zip = zip::ZipWriter::new(file); + zip.start_file("../outside.txt", zip::write::FileOptions::default()) + .unwrap(); + zip.write_all(b"no").unwrap(); + zip.finish().unwrap(); + let failed = ok(call( + backend, + "lib/archive.mq.md", + "unpack", + &["src=\"escaping.zip\"", "dest=\"escaped\""], + "fs.write", + Some(&scratch.0), + )); + assert_eq!(failed["ok"], false); + assert!(!scratch.0.join("escaped").exists()); + let file = fs::File::create(scratch.0.join("symlink.zip")).unwrap(); + let mut zip = zip::ZipWriter::new(file); + zip.add_symlink("link", "../../target", zip::write::FileOptions::default()) + .unwrap(); + zip.finish().unwrap(); + let failed = ok(call( + backend, + "lib/archive.mq.md", + "unpack", + &["src=\"symlink.zip\"", "dest=\"links\""], + "fs.write", + Some(&scratch.0), + )); + assert_eq!(failed["ok"], false); + assert!(!scratch.0.join("links").exists()); + } +} + +#[test] +fn every_standard_library_is_its_own_readable_handbook() { + let files = public_standard_libraries(); + assert!(files.len() >= 60); + for path in files { + let text = fs::read_to_string(&path).unwrap(); + assert!( + !text + .lines() + .any(|line| line.trim_start().starts_with("+ `")), + "{} retains legacy parameters", + path.display() + ); + for line in text + .lines() + .filter(|line| line.contains("host_") && line.trim_start().starts_with('*')) + { + assert!( + line.contains("]("), + "{} has an opaque unlabeled instruction: {line}", + path.display() + ); + } + let module = marqdo::load::load_module(&path).unwrap(); + assert!( + !module.functions.is_empty(), + "empty library: {}", + path.display() + ); + let diagnostics = marqdo::check::check_path(&path).unwrap(); + assert!( + diagnostics.is_empty(), + "{}: {diagnostics:?}", + path.display() + ); + let reports = marqdo::narrative_ratio::measure_source_units(&text, &module.functions); + for report in &reports { + assert!( + report.ratio > 0.5, + "{} {} has {:.1}% narrative", + path.display(), + report.name, + report.ratio * 100.0 + ); + } + for function in &module.functions { + assert!( + function.params.iter().all(|p| p.inferred), + "{} {} retains explicit parameters", + path.display(), + function.name + ); + let contract = function + .contract + .as_ref() + .unwrap_or_else(|| panic!("{} {} lacks a contract", path.display(), function.name)); + assert!( + contract.returns.is_some(), + "{} {} lacks a return contract", + path.display(), + function.name + ); + assert_eq!( + contract.params.len(), + function.params.len(), + "{} {} incomplete parameter table", + path.display(), + function.name + ); + let first = text + .lines() + .skip(function.span.line as usize) + .find(|line| !line.trim().is_empty()) + .unwrap(); + assert!( + first.starts_with(if function.params.is_empty() { + "| 返回 |" + } else { + "| 参数 |" + }), + "{} {} must put its contract table directly below the heading", + path.display(), + function.name + ); + } + } +} + +#[test] +fn large_indices_and_chunk_sizes_have_portable_meaning() { + for backend in ["tree", "bytecode"] { + let table = "lib/table.mq.md"; + assert_eq!( + ok(call( + backend, + table, + "at", + &["xs=[1,2]", "i=4294967296"], + "none", + None + )), + Value::Null + ); + assert_eq!( + ok(call( + backend, + table, + "chunk", + &["list=[1,2]", "size=4294967296"], + "none", + None + )), + json!([[1, 2]]) + ); + assert_eq!( + call( + backend, + table, + "put", + &["in=[1,2]", "at=[4294967296,1]", "value=9"], + "none", + None + )["ok"], + false + ); + for operation in ["insert", "set_at"] { + assert_eq!( + call( + backend, + table, + operation, + &["list=[1,2]", "index=4294967296", "item=9"], + "none", + None + )["ok"], + false + ); + } + let bytes = ok(call( + backend, + "lib/bytes.mq.md", + "slice", + &[ + "data={\"_type\":\"bytes\",\"base64\":\"AP+A\"}", + "start=4294967296", + "end=4294967298", + ], + "none", + None, + )); + assert_eq!(bytes["base64"], ""); + } +} + +#[test] +fn library_development_guide_examples_match_their_contracts() { + let file = "doc/library-development.mq.md"; + let source = fs::read_to_string(root().join(file)).unwrap(); + let module = marqdo::load::load_module(&root().join(file)).unwrap(); + assert_eq!( + module + .functions + .iter() + .map(|f| f.name.as_str()) + .collect::>(), + ["计算金额", "形成订单摘要", "尝试读取正文"] + ); + assert!(marqdo::check::check_path(&root().join(file)) + .unwrap() + .is_empty()); + for report in marqdo::narrative_ratio::measure_source_units(&source, &module.functions) { + assert!( + report.ratio > 0.5, + "{} has {:.1}% narrative", + report.name, + report.ratio * 100.0 + ); + } + let recipe = source + .split("```sh\n") + .nth(1) + .unwrap() + .split("\n```") + .next() + .unwrap(); + let commands: Vec<_> = recipe.lines().collect(); + assert_eq!(commands.len(), 3); + for backend in ["tree", "bytecode"] { + let mut results = Vec::new(); + for command in &commands { + let command = command.replacen( + "marqdo call ", + &format!( + "\"{}\" call --backend {backend} ", + env!("CARGO_BIN_EXE_marqdo") + ), + 1, + ); + let output = Command::new("bash") + .args(["--noprofile", "--norc", "-ec", &command]) + .env_remove("BASH_ENV") + .current_dir(root()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{backend}: {command}: {}", + String::from_utf8_lossy(&output.stderr) + ); + results.push(ok(serde_json::from_slice(&output.stdout).unwrap())); + } + assert_eq!(results[0], 36); + assert_eq!(results[1], json!({"商品":"笔记本","数量":3,"金额":36})); + assert_eq!(results[2]["ok"], true); + assert_eq!(results[2]["value"], source); + assert_eq!( + ok(call(backend, file, "计算金额", &["单价=12"], "none", None)), + 12 + ); + let scratch = Scratch::new(); + let missing = ok(call( + backend, + file, + "尝试读取正文", + &["路径=\"missing.md\""], + "fs.read", + Some(&scratch.0), + )); + assert_eq!(missing["ok"], false); + assert_eq!(missing["error"]["code"], "not_found"); + assert_eq!( + call( + backend, + file, + "尝试读取正文", + &["路径=\"missing.md\""], + "none", + Some(&scratch.0) + )["ok"], + false + ); + } +} diff --git a/tests/view/readability.browser.cjs b/tests/view/readability.browser.cjs new file mode 100644 index 0000000..642b8f9 --- /dev/null +++ b/tests/view/readability.browser.cjs @@ -0,0 +1,79 @@ +// Exercise actual reader DOM, side-note geometry, accessibility and offline export. +const assert = require('node:assert/strict'); +const { chromium } = require(process.env.MARQDO_PLAYWRIGHT_MODULE || 'playwright'); +let browser; +(async()=>{ + browser=await chromium.launch({headless:true,executablePath:process.env.MARQDO_CHROMIUM||undefined,args:['--no-sandbox']}); + const page=await browser.newPage({viewport:{width:1440,height:1000}}), errors=[]; + page.on('pageerror',e=>errors.push(e.message)); + await page.route('https://**/*',route=>route.abort()); + await page.goto(process.argv[2]);await page.waitForTimeout(300); + const surface=page.locator('#structure'); + assert.deepEqual(await surface.locator('.occl-label').allTextContents(),['按件数计算金额','由作者补充具体业务','购买两件商品','使用默认件数','依次累计数量','输出累计值','说明输入为空']); + assert.equal(await surface.locator('.occl-stub').count(),1); + assert.match(await surface.locator('.occl-stub').textContent(),/待补充实际逻辑/); + const sentence=surface.locator('.doc-prose-line').filter({hasText:'先第一笔'}); + const text=await sentence.innerText(); + assert(text.includes('购买两件商品')&&text.includes('使用默认件数')); + assert(!text.includes('计算小计(')&&!text.includes('单价=12')); + const actions=await surface.locator('.occl-label').evaluateAll(nodes=>nodes.map(n=>({id:n.dataset.logicId,label:n.textContent}))); + for(const a of actions){ + assert.equal(await page.locator('#'+a.id+'-note').count(),1,'one note for '+a.label); + assert.equal(await page.locator('#'+a.id+'-source').count(),1,'unique source '+a.label); + } + for(const width of [1920,1440,1100,1024,1000,800,390]){ + await page.setViewportSize({width,height:1000});await page.waitForTimeout(120); + assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'horizontal overflow '+width); + const notes=await surface.locator('.annot-implementation.is-margin-note').count(); + if(width>=1440) assert(notes>0,'wide logic notes'); + if(width<=1000) assert.equal(notes,0,'mobile must use native disclosures'); + assert.deepEqual(await page.locator('.is-margin-note').evaluateAll(nodes=>{ + const rects=nodes.map(n=>n.getBoundingClientRect()),issues=[]; + for(let i=0;iinnerWidth)issues.push('offscreen'); + for(let j=i+1;jn.classList.contains('is-focus')),'source highlights actual implementation'); + await source.click(); + assert(await page.locator('#reader-dialog').evaluate(n=>n.open)); + assert((await page.locator('#reader-dialog-content pre').textContent()).includes('计算小计(单价=12, 数量=2)')); + await page.keyboard.press('Escape'); + await surface.locator('.knowledge-explain').first().click(); + assert(await page.locator('.knowledge-block').evaluate(n=>n.open)); + assert((await page.locator('.knowledge-card[open]').first().innerText()).includes('每件商品的价格')); + const technical=page.locator('.knowledge-card[open] .knowledge-technical').first(); + assert.equal(await technical.evaluate(n=>n.open),false,'identities folded initially'); + for(const href of await page.locator('.knowledge-step a,.knowledge-source-link,.knowledge-explain').evaluateAll(nodes=>nodes.map(n=>n.getAttribute('href')))){ + assert(await page.evaluate(href=>!!document.getElementById(href.slice(1)),href),'broken source link '+href); + } + assert.equal(await page.locator('.knowledge-error').count(),0,'knowledge must load for one example'); + await page.locator('[data-reader-action="more"]').click(); + await page.getByRole('button',{name:'可执行知识',exact:true}).click(); + assert.equal(await page.locator('#reader-dialog-content .knowledge-panel').count(),1); + await page.keyboard.press('Escape'); + await page.waitForFunction(()=>!!document.querySelector('.knowledge-block .knowledge-panel')); + assert.equal(await page.locator('.knowledge-block .knowledge-panel').count(),1,'restore actual panel'); + await page.locator('#reader-syntax-guide summary').click(); + assert.equal(await page.locator('[data-construct-id]').count(),19); + // Read-only no-script fallback still exposes native details and real source text. + const context=await browser.newContext({javaScriptEnabled:false,viewport:{width:390,height:900}}); + const plain=await context.newPage();await plain.goto(process.argv[2]); + const note=plain.locator('.annot-implementation').first();await note.locator('summary').click(); + assert(await note.locator('.annot-value').isVisible()); + assert.equal(await plain.locator('.occl-stub').count(),1); + await context.close(); + if(process.env.MARQDO_SCREENSHOT_DIR){ + const fs=require('node:fs');fs.mkdirSync(process.env.MARQDO_SCREENSHOT_DIR,{recursive:true}); + await page.locator('#reader-syntax-guide').evaluate(n=>n.open=false); + await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/reading-desktop.png',fullPage:true}); + await page.setViewportSize({width:390,height:900});await page.screenshot({path:process.env.MARQDO_SCREENSHOT_DIR+'/reading-mobile.png',fullPage:true}); + } + assert.deepEqual(errors,[]); + await browser.close();console.log('reader readability: actions, logic notes, knowledge, source links, responsive and no-JS passed'); +})().catch(async error=>{console.error(error);if(browser)await browser.close();process.exitCode=1;}); diff --git a/tests/view_readability.rs b/tests/view_readability.rs new file mode 100644 index 0000000..6f44765 --- /dev/null +++ b/tests/view_readability.rs @@ -0,0 +1,127 @@ +//! Reader exports must remain faithful to source facts without evaluating them. +use std::{ + fs, + path::PathBuf, + process::Command, + sync::atomic::{AtomicU64, Ordering}, +}; +static SEQUENCE: AtomicU64 = AtomicU64::new(0); +struct Scratch(PathBuf); +impl Scratch { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "mq-view-reading-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn html_files(path: &std::path::Path, files: &mut Vec) { + for entry in fs::read_dir(path).unwrap() { + let p = entry.unwrap().path(); + if p.is_dir() { + html_files(&p, files) + } else if p.extension().is_some_and(|e| e == "html") { + files.push(p) + } + } +} +fn export(source: &std::path::Path, out: &std::path::Path) -> String { + let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .args(["view", "output", "--no-exec", "--out"]) + .arg(out) + .arg(source) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let mut files = Vec::new(); + html_files(out, &mut files); + files + .iter() + .map(|p| fs::read_to_string(p).unwrap()) + .find(|s| s.contains("id=\"structure\"")) + .unwrap() +} +#[test] +fn single_file_reading_ignores_unrelated_name_collisions_and_never_runs_logic() { + let temp = Scratch::new(); + for dir in ["one", "two"] { + let dir = temp.0.join(dir); + fs::create_dir(&dir).unwrap(); + fs::write(dir.join("same.mq.md"), "# main\n\n*1*\n").unwrap(); + } + let marker = temp.0.join("must-not-exist"); + let source = temp.0.join("entry.mq.md"); + let text=format!("---\nimport:\n fs: lib/fs.mq.md\n---\n# main\n\n**[写入标记](fs.write_text(path={}, text=\"read must not execute\"))**\n",serde_json::to_string(&marker.to_string_lossy()).unwrap()); + fs::write(&source, &text).unwrap(); + let html = export(&source, &temp.0.join("out")); + assert!(!marker.exists(), "--no-exec performed the occluded write"); + assert!( + html.contains("class=\"knowledge-panel\""), + "knowledge failed: {html}" + ); + assert!(!html.contains("knowledge-error\"")); + let structure = html + .split("
    ") + .nth(1) + .unwrap() + .split("class=\"knowledge-panel\"") + .next() + .unwrap(); + assert!(structure.contains("写入标记")); + assert!(structure.contains("class=\"annot-chip annot-implementation\"")); + assert!( + !structure.contains("class=\"annot-chip annot-bind"), + "unrun source acquired a runtime result" + ); +} +#[test] +fn knowledge_cards_use_real_contracts_and_keep_verification_states_separate() { + let temp = Scratch::new(); + let source = temp.0.join("reading.mq.md"); + fs::write(&source, include_str!("../examples/view-reading.mq.md")).unwrap(); + let html = export(&source, &temp.0.join("out")); + let panel = html + .split("aria-label=\"可执行知识\"") + .nth(1) + .unwrap() + .split("id=\"mq-knowledge-presentation\"") + .next() + .unwrap(); + for label in [ + "需要什么输入", + "返回什么", + "调用边界", + "当前有哪些依据", + "测试记录", + "内容来源", + "领域审阅", + "技术详情", + ] { + assert!(panel.contains(label), "missing {label}"); + } + assert!(panel.contains("每件商品的价格")); + assert!(panel.contains("不包含额外税费或优惠")); + assert!(panel.contains("没有可用记录") && panel.contains("尚未进行领域审阅")); + assert!(!panel.contains("Signature") && !panel.contains("Verification")); + assert!(panel.contains("未检查锁定状态")); + let structure = html + .split("
    ") + .nth(1) + .unwrap(); + assert!( + structure.contains("由作者补充具体业务待补充实际逻辑") + ); +} diff --git a/tests/wasm/stdlib.mjs b/tests/wasm/stdlib.mjs new file mode 100644 index 0000000..79962dd --- /dev/null +++ b/tests/wasm/stdlib.mjs @@ -0,0 +1,154 @@ +#!/usr/bin/env node +// Exercise current embedded libraries through the public browser ABI. +import fs from 'node:fs'; +import assert from 'node:assert/strict'; +const {instance}=await WebAssembly.instantiate(fs.readFileSync(process.argv[2]),{}); +const e=instance.exports, enc=new TextEncoder(),dec=new TextDecoder(); +function boot(source,expectedOk=true){ + const bytes=enc.encode(source),p=e.mq_alloc(bytes.length); + new Uint8Array(e.memory.buffer,p,bytes.length).set(bytes); + const out=e.mq_boot(p,bytes.length);e.mq_dealloc(p,bytes.length); + const length=new DataView(e.memory.buffer).getUint32(out,true); + const value=JSON.parse(dec.decode(new Uint8Array(e.memory.buffer,out+4,length))); + e.mq_dealloc(out,length+4);assert.equal(value.ok,expectedOk,JSON.stringify(value));return expectedOk?value.value:value; +} +const summary=boot(`--- +markup: occlusion +import: + table: lib/table.mq.md +--- +# main + +\`rows\` = + +| @ | team | n | +|---|---|---| +| 1 | a | 1 | +| 2 | b | 4 | +| 3 | a | 2 | + +*> table.summarize list=\`rows\` key="team" field="n"* +`); +assert.deepEqual(summary,[{key:'a',count:2,value:3},{key:'b',count:1,value:4}]); +const bytes=boot(`--- +markup: occlusion +import: + bytes: lib/bytes.mq.md +--- +# main + +*> bytes.from_base64 text="AP+A"* +`); +assert.deepEqual(bytes,{_type:'bytes',base64:'AP+A'}); +const doc=boot(`--- +markup: occlusion +import: + document: lib/document.mq.md +--- +# main + +*> document.sections text="# Notes"* +`); +assert.equal(doc.length,1);assert.equal(doc[0].title,'Notes'); +const config=boot(`--- +markup: occlusion +import: + toml: lib/toml.mq.md +--- +# main + +*> toml.parse text="name='Marqdo'"* +`); +assert.equal(config.name,'Marqdo'); +const moment=boot(`--- +markup: occlusion +import: + dt: lib/datetime.mq.md +--- +# main + +*> dt.parse_local text="2024-11-03 01:30:00" zone="America/New_York" ambiguity="earliest"* +`); +assert.equal(moment.ok,true);assert.equal(moment.value.iso,'2024-11-03T01:30:00-04:00'); +console.log('wasm stdlib ok: collection, bytes, document, TOML, IANA/DST'); +const chunk=boot(`--- +markup: occlusion +import: + table: lib/table.mq.md +--- +# main + +\`values\` = + +| n | +|---| +| 1 | +| 2 | + +*> table.chunk list=\`values\` size=4294967296* +`); +assert.deepEqual(chunk,[[1,2]]); +const sliced=boot(`--- +markup: occlusion +import: + bytes: lib/bytes.mq.md +--- +# main + +**data = bytes.from_base64 text="AP+A"** +*> bytes.slice data=\`data\` start=4294967296 end=4294967298* +`); +assert.equal(sliced.base64,''); +console.log('wasm 32-bit large-index semantics ok'); + +const badPut=boot(`--- +markup: occlusion +import: + table: lib/table.mq.md +--- +# main + +\`values\` = + +| n | +|---| +| 1 | +| 2 | + +\`indices\` = + +| index | +|---| +| 4294967296 | +| 1 | + +*> table.put in=\`values\` at=\`indices\` value=9* +`,false); +assert.equal(badPut.ok,false); +console.log('wasm nested index overflow is a diagnostic, not a trap'); + +for (const [module, entry, parameter] of [ + ['lib/table.mq.md', 'from_pairs', 'pairs'], + ['lib/表.mq.md', '键值转记录', '键值对'], +]) { + const result = boot(`--- +markup: occlusion +import: + records: ${module} +--- +# main + +\`fields\` = + +| @ | key | value | +|---|---|---| +| 1 | channel | old | +| 2 | empty | None | +| 3 | channel | "source\\|skill" | + +The ordered fields retain real nulls. Return *[Build the record from the visible rows](records.${entry}(${parameter}=\`fields\`))*. +`); + assert.deepEqual(result, {channel: 'source|skill', empty: null}); +} +assert.equal(boot(`# main\n\nReturn *[multiply x*y and retain the product](2 * (3 + 1))* after calculation.\n`), 8); +console.log('wasm narrative libraries ok: bilingual pair records, escaped GFM pipe, inline occlusion product');