diff --git a/.cursor/rules/web-artifact-no-degrade.mdc b/.cursor/rules/web-artifact-no-degrade.mdc old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo-dev/SKILL.md b/.cursor/skills/marqdo-dev/SKILL.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo-release/SKILL.md b/.cursor/skills/marqdo-release/SKILL.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo-release/reference.md b/.cursor/skills/marqdo-release/reference.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo/migration-classic.md b/.cursor/skills/marqdo/migration-classic.md old mode 100644 new mode 100755 diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md old mode 100644 new mode 100755 diff --git a/.env.example b/.env.example old mode 100644 new mode 100755 diff --git a/.env.r2.example b/.env.r2.example old mode 100644 new mode 100755 diff --git a/.gitattributes b/.gitattributes old mode 100644 new mode 100755 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md old mode 100644 new mode 100755 diff --git a/.github/workflows/executable-knowledge.yml b/.github/workflows/executable-knowledge.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/extension-release.yml b/.github/workflows/extension-release.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml new file mode 100755 index 0000000..a119553 --- /dev/null +++ b/.github/workflows/proof.yml @@ -0,0 +1,115 @@ +# 判定流水线(marqdo prove) +# +# 验证「SKILL 编排文档 → Lean 4 → 自动证明」全链路: +# 1. 构建内置 Lean 底座(MarqdoProof.lean)。 +# 2. 跑判定矩阵(tests/prove_lean.rs):真定理 proved、假定理 unproved、 +# 证书缓存命中跳判定、--require-lean 退出码。 +# 3. CI 硬性要求(MARQDO_PROOF_REQUIRE_LEAN=1):没有工具链即失败, +# 不允许悄悄降级成 unverified。 +# +# 说明:仓库不强制贡献者装 Lean——本工作流在装有 elan 的 runner 上运行; +# 本地无 Lean 时判定状态为 unverified(advisory,不阻塞)。 +name: proof + +on: + push: + branches: [main] + paths: + - "src/prove/**" + - "doc/verification/skill-proof/**" + - "lib/**" + - "tests/prove*.rs" + - ".github/workflows/proof.yml" + pull_request: + paths: + - "src/prove/**" + - "doc/verification/skill-proof/**" + - "lib/**" + - "tests/prove*.rs" + - ".github/workflows/proof.yml" + workflow_dispatch: + +jobs: + proof: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Rust (1.81) + run: | + rustup toolchain install 1.81.0 --profile minimal + rustup default 1.81.0 + + # leanprover/lean-action@v1 已移除 lean4-version;本仓库运行时只需 lean 二进制 + # (底座内嵌、不经 lake)。用 elan 钉 v4.35.0,与 doc/verification/skill-proof/lean-toolchain 一致。 + - name: Install Lean 4.35.0 (elan) + run: | + curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0 + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + "$HOME/.elan/bin/lean" --version + + - name: Verify embedded proof library + run: | + chmod +x scripts/check-proof-library.sh + scripts/check-proof-library.sh + + - name: Build + run: cargo build --locked + + - name: Judgment matrix (real Lean; CI requires toolchain) + env: + MARQDO_PROOF_REQUIRE_LEAN: "1" + run: cargo test --locked --test prove_lean + + - name: Rest of prove suite (no toolchain assumptions) + run: cargo test --locked --test prove + + - name: Corpus monotonicity — offline_checked ⊆ lean_proved (40 fixtures) + env: + MARQDO_PROOF_REQUIRE_LEAN: "1" + run: cargo test --locked --test prove_corpus + + - name: T4 differential consistency — interpreter == Lean + env: + MARQDO_PROOF_REQUIRE_LEAN: "1" + run: cargo test --locked --test conformance + + - name: Full sweep — divergence guard bites on injected fault + env: + MARQDO_PROOF_REQUIRE_LEAN: "1" + run: | + # A3:注入分歧必须显式失败(error[proof.divergence],退 1)—— + # 护栏失灵(静默落绿)比单点失败严重得多。 + set -e + tmp=$(mktemp -d) + cat > "$tmp/审批.mq.md" <<'FIXTURE' + --- + markup: occlusion + --- + + # 台账 + + ## 记录 + + `金额` + + | 定理 | 结论 | 策略 | + |---|---|---| + | 记过即记 | 长度(轨迹) = 1 | auto | + + **结果 = [登记](result.ok(value=`金额`))** + + *结果* + FIXTURE + set +e + out=$(cargo run --locked -- prove "$tmp/审批.mq.md" --fault-inject offline-claim --json 2>/dev/null) + code=$? + echo "$out" | head -c 400 + if [ "$code" -ne 1 ]; then + echo "::error::注入分歧未被拦截(exit=$code)——单调性护栏失灵" + exit 1 + fi + echo "$out" | grep -q "proof.divergence" || { + echo "::error::未出现 proof.divergence 诊断" + exit 1 + } + echo "divergence guard OK" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f3f859..7676640 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,21 @@ - CI builds the agent cdylib and runs offline integration without the removed `run --effects` flag, using `MARQDO_AGENT_PLUGIN` instead. +### Changed + +- 分支已合并 v2.8.0:`Cargo.toml`/`Cargo.lock`、发布工作流与全部拓展包 + 统一到 2.8.0 依赖锁,后续发版不再从 2.7.1 基线分叉。 +- The branch now includes v2.8.0, so its crate versions, lockfile and release + workflows match the current release line instead of the 2.7.1 baseline. + +## v2.8.0 — 2026-11-17 + +`marqdo prove` 正式发布:定理表 → Lean 4 证明 → 自动判定。离线符号执行(F1–F5)无工具链可用,`checked` 永远弱于 `proved`;单调性护栏让判定器缺陷显式失败;假定理给出反例见证;证书缓存与目录模式面向智能体批量出证。 + +`marqdo prove` ships: theorem tables compile to Lean 4 and are judged automatically. Offline symbolic execution works without a toolchain, monotonicity guardrails fail loudly on judger defects, fake theorems get counterexample witnesses, and certificate caching plus directory mode support agent-scale proving. + +详见 [双语发布说明](doc/releases/v2.8.0.md)。 + ## v2.7.1 — 2026-11-11 CLI 修复发布:View 实际逻辑的手动开合不再被布局重排或运行结果刷新覆盖;函数、链接、列表和记录按内容排版,手机详情整行展示。核心仍为 19 个构造;拓展库保留 2.7.0。 diff --git a/Cargo.lock b/Cargo.lock old mode 100644 new mode 100755 index 8c8fce1..62a9995 --- 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 = 4 +version = 3 [[package]] name = "adler2" @@ -143,9 +143,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "byteorder" @@ -582,9 +582,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -615,7 +615,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" [[package]] name = "marqdo" -version = "2.7.1" +version = "2.8.0" dependencies = [ "anyhow", "assert_cmd", @@ -656,7 +656,7 @@ dependencies = [ [[package]] name = "marqdo-wasm" -version = "2.7.1" +version = "2.8.0" dependencies = [ "marqdo", "serde_json", @@ -1457,12 +1457,11 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -1470,9 +1469,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1480,9 +1479,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", @@ -1493,9 +1492,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] diff --git a/Cargo.toml b/Cargo.toml old mode 100644 new mode 100755 index 7bcd33d..ebb81c3 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo" -version = "2.7.1" +version = "2.8.0" edition = "2021" license = "Apache-2.0" description = "Marqdo — Markdown markers as an interpreted programming language" @@ -12,6 +12,12 @@ name = "marqdo" path = "src/main.rs" required-features = ["cli"] +# Lean 判定集成测试(独立目标:缓存/判定/退出码矩阵,见 tests/prove_lean.rs)。 +[[test]] +name = "prove_lean" +path = "tests/prove_lean.rs" +required-features = ["cli"] + [features] default = ["native"] native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"] diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 4715db1..09a02bd --- a/README.md +++ b/README.md @@ -117,12 +117,19 @@ marqdo view examples/procurement --no-open Agent Skills already support scripts; Marqdo's claim is **one document-native language surface** for authoring, inspecting, executing and reusing functions. This is **not** a claim of full formal verification, zero-delay execution, or OS-level isolation of all plugin/process behavior. -**Resources:** [Release v2.7.1](https://github.com/cflmy/marqdo/releases/tag/v2.7.1) · [Procurement example](examples/procurement/index.mq.md) · [Executable library authoring](doc/library-development.mq.md) · [Function calling](public/features/22-函数调用.mq.md) · [Link syntax](doc/design/link-syntax.md) · [Website](https://www.marqdo.com/) +**Resources:** [Release v2.8.0](https://github.com/cflmy/marqdo/releases/tag/v2.8.0) · [Procurement example](examples/procurement/index.mq.md) · [Executable library authoring](doc/library-development.mq.md) · [Function calling](public/features/22-函数调用.mq.md) · [Link syntax](doc/design/link-syntax.md) · [Website](https://www.marqdo.com/) --- ## Deep dive · 语言、设计与执行系统 +标准库单文件本身就是手册:直接阅读[文件库](lib/文件.mq.md)、[集合库](lib/表.mq.md)等源码,按函数标题下的参数表、返回契约和动作说明调用;[工程实践](examples/stdlib-handbook/索引.mq.md)演示文件整理、CSV 汇总与文档维护。 +开发标准库和拓展库请直接阅读[可执行库开发指南](doc/library-development.mq.md):契约表、叙述式实现、遮蔽调用与多文件工程组织均有可运行示范。 + +当前 CLI **2.8.0** 新增 `marqdo prove`:知识文件的定理表编译为 Lean 4 并自动判定真假——没有 Lean 工具链也能离线符号执行(诚实降级,绝不冒充证明),有 Lean 时全链路证明并给出反例见证。参见[发布说明](doc/releases/v2.8.0.md)。 + +CLI **2.8.0** adds `marqdo prove`: theorem tables in knowledge files compile to Lean 4 and are judged automatically — offline symbolic execution without a toolchain (honest degradation, never impersonating a proof), full proofs with counterexample witnesses when Lean is available. + ## 核心优势:可执行知识(Executable Knowledge) > **Knowledge That Can Run —— 知识即可执行。** @@ -242,6 +249,7 @@ Agent Skills already support scripts; Marqdo's claim is **one document-native la 3. **程序即 AI 长期记忆**:`.mq.md` 工程 = 可执行知识库 = AI 的世界模型(Executable Knowledge Representation)。 4. **链接即调用 / 可执行知识图**:`[描述](类.函数)` 既是文档链接,也是类/函数调用;编译器解析目标、校验签名、返回 LinkInfo;`view` 显示调用点;`.mq.md` 之间的链接长成文档图 + 知识图 + 程序图(Executable Knowledge Graph)。 5. **知识可测试**:文档中的示例表自动执行;知识与执行结果不一致会被机器报告——Knowledge-Code Coherence 从理念变为日常。 +6. **知识可证明**:知识文件内的定理表 → Lean 4 定理 → 自动判定(`marqdo prove`);离线符号执行与 Lean 单调一致,分歧显式报错——Trusted Knowledge,判定器缺陷优先于任何绿灯。 6. **可靠性基准**:让同一个 AI 分别用 Python / TypeScript / Marqdo 完成真实任务,测量生成长度、语法 / 语义错误率、修复轮次、token 消耗与人类阅读 / 修改成本——用实验数据证明「文档型语法降低 LLM 生成熵」。 --- diff --git a/crates/marqdo-plugin-sdk/Cargo.toml b/crates/marqdo-plugin-sdk/Cargo.toml old mode 100644 new mode 100755 diff --git a/crates/marqdo-plugin-sdk/src/lib.rs b/crates/marqdo-plugin-sdk/src/lib.rs old mode 100644 new mode 100755 diff --git a/crates/marqdo-wasm/Cargo.toml b/crates/marqdo-wasm/Cargo.toml old mode 100644 new mode 100755 index 2be80c0..76ccc34 --- a/crates/marqdo-wasm/Cargo.toml +++ b/crates/marqdo-wasm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "marqdo-wasm" -version = "2.7.1" +version = "2.8.0" edition = "2021" license = "Apache-2.0" description = "Marqdo interpreter as WebAssembly (browser host bridge)" diff --git a/crates/marqdo-wasm/README.md b/crates/marqdo-wasm/README.md old mode 100644 new mode 100755 diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js old mode 100644 new mode 100755 diff --git a/crates/marqdo-wasm/js/package.json b/crates/marqdo-wasm/js/package.json old mode 100644 new mode 100755 diff --git a/crates/marqdo-wasm/src/lib.rs b/crates/marqdo-wasm/src/lib.rs old mode 100644 new mode 100755 diff --git a/debian/README.Debian b/debian/README.Debian old mode 100644 new mode 100755 diff --git a/debian/changelog b/debian/changelog index 0e157d0..a6b7f9e 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +marqdo (2.8.0-1ppa1) noble; urgency=medium + + * Release 2.8.0; see the reviewed upstream CHANGELOG. + + -- Marqdo Maintainers Wed, 18 Nov 2026 10:24:08 +0800 + marqdo (2.7.1-1ppa2) noble; urgency=medium * Release 2.7.1; see the reviewed upstream CHANGELOG. diff --git a/debian/control b/debian/control old mode 100644 new mode 100755 diff --git a/debian/copyright b/debian/copyright old mode 100644 new mode 100755 diff --git a/debian/patches/engineering-stable-option.patch b/debian/patches/engineering-stable-option.patch old mode 100644 new mode 100755 diff --git a/debian/patches/series b/debian/patches/series old mode 100644 new mode 100755 diff --git a/debian/source/format b/debian/source/format old mode 100644 new mode 100755 diff --git a/debian/source/options b/debian/source/options old mode 100644 new mode 100755 diff --git a/doc/README.md b/doc/README.md old mode 100644 new mode 100755 index 9dfcacb..4d81fda --- a/doc/README.md +++ b/doc/README.md @@ -19,6 +19,9 @@ | 文档 | 摘要 | |------|------| +| [design/prove-cli.md](design/prove-cli.md) | **Proposed:`marqdo prove` 设计**;SKILL 控制平面 → Lean 4、函数级定理表与语言习惯审查、离线判定片段、`proved`/`checked` 诚实性契约、无公理 TCB | +| [roadmap/prove.md](roadmap/prove.md) | **Proposed:`marqdo prove` 实施路线**;P0–P3 周计划、8 类测试矩阵(单调性/一致性/不执行/子集/定理表/CLI/缓存/编码)、CI 与验收证据 | +| [adr/0010-skill-proof-boundary.md](adr/0010-skill-proof-boundary.md) | **ADR 0010**:定理表作为契约表第四角色、可证子集封闭、Lean 为唯一 `proved` 来源、顾问式不强制 | | [roadmap/agent-reliability-crossrepo-2026-10-27.md](roadmap/agent-reliability-crossrepo-2026-10-27.md) | **Proposed:跨仓 Agent 可靠性开发计划**;M-A0–M-A6 ∥ Q-A0–Q-A7 排期、依赖图、F01–F20 映射、MA-T*/QA-* 验收与第一刀切片;协议真源仍见下方设计文档 | | [design/agent-reliability-tools-resources-2026-10-27.md](design/agent-reliability-tools-resources-2026-10-27.md) | **Proposed:智能体能力补足**;基于 `16f26d7`,增量设计错误恢复、检查点/效应账本、结构化工具、输出通道、上下文与只读资源视图;含跨仓边界、阶段计划和故障验收 | | [research/agent-capabilities-2026-10-27.md](research/agent-capabilities-2026-10-27.md) | **官方能力调研与源码复核**;OpenAI/Claude/Gemini/LangGraph/Deep Agents/MCP,求道当前问题 F01–F20;区分现有能力、设计推导与待实测项 | diff --git a/doc/adr/0001-implementation-language.md b/doc/adr/0001-implementation-language.md old mode 100644 new mode 100755 diff --git a/doc/adr/0002-browser-marqdo-wasm.md b/doc/adr/0002-browser-marqdo-wasm.md old mode 100644 new mode 100755 diff --git a/doc/adr/0003-browser-async-effects.md b/doc/adr/0003-browser-async-effects.md old mode 100644 new mode 100755 diff --git a/doc/adr/0004-web-plugin-go.md b/doc/adr/0004-web-plugin-go.md old mode 100644 new mode 100755 diff --git a/doc/adr/0005-prose-unified-markup.md b/doc/adr/0005-prose-unified-markup.md old mode 100644 new mode 100755 diff --git a/doc/adr/0006-artifact-metadata-binding.md b/doc/adr/0006-artifact-metadata-binding.md old mode 100644 new mode 100755 diff --git a/doc/adr/0007-web-document-endpoint.md b/doc/adr/0007-web-document-endpoint.md old mode 100644 new mode 100755 diff --git a/doc/adr/0008-web-invoke-serialization.md b/doc/adr/0008-web-invoke-serialization.md old mode 100644 new mode 100755 diff --git a/doc/adr/0009-isolated-web-runtime.md b/doc/adr/0009-isolated-web-runtime.md old mode 100644 new mode 100755 diff --git a/doc/adr/0010-skill-proof-boundary.md b/doc/adr/0010-skill-proof-boundary.md new file mode 100755 index 0000000..ed7a93b --- /dev/null +++ b/doc/adr/0010-skill-proof-boundary.md @@ -0,0 +1,79 @@ +# ADR 0010: SKILL 证明边界:定理表、可证子集与顾问式判定 + +| 项目 | 约定 | +|---|---| +| 状态 | **Accepted(决策已定)**;实现未开始,路线见 [roadmap/prove.md](../roadmap/prove.md) | +| 日期 | 2026-11-13 | +| 设计 | [design/prove-cli.md](../design/prove-cli.md) | +| 相关 | [core-surface.md](../design/core-surface.md)(不新增标记)· [layers.md](../design/layers.md)(Language 层扩表角色)· [contract.rs](../../src/contract.rs)(既有契约表提取)· [replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定先例) | + +## 背景 + +Agent 改写 SKILL 后,人需要逐行确认"分支是否绕开审核、失败是否被吞掉"。这类**控制平面**性质适合形式化:编排是带条件的有限 DAG,没有死循环、没有指针。同时,把整个 Marqdo 当通用语言编译到 Lean 会立刻撞上字符串/JSON/浮点/IO 的语义鸿沟,收益被稀释。 + +项目已有一条 Lean 纪律:`verification/replay-policy` 用 Lean 做唯一判定,Rust 不保留第二份实现,缺伴随进程时失败关闭。本 ADR 决定把同样的纪律用于 SKILL 编排,但**降级为顾问式**:证明用于减少审核量,不作为发布门禁。 + +## 决策 + +1. **定理是契约表的第四种角色**,不是新标记。 + 函数体首条可执行语句之前可放一张「定理表」(`定理 | 结论 | 前提 | 策略`),与 `参数`/`返回`/`字段` 表同槽位;解析期提取进 `Function.claims`,从 body 移除,不参与运行。核心标记计数不变,`CORE_CONSTRUCTS` 不增行;`layers.md` 的 Language 清单补记该角色。 + +2. **可证子集显式封闭**:无 `while`、无递归、无动态派发(插件、变量函数名、`code` 值调用)。越界函数被跳过(`rejected`),不降级成不透明块。外部操作是 `Env := Op → Val` 参数,不是公理;后置条件只能来自 `假设` 表并成为定理前提。 + +3. **Lean 是唯一能产生 `proved` 的判定器**。离线判定只到 `checked`,且被限制在一个极小的片段(路径枚举、轨迹、字面结果、命题组合、单变量区间),凡是离线判定为真的定理都必须同时生成 Lean 脚本。运行期若 Lean 可用则复核;离线 `checked` 而 Lean 未关闭视为内部错误(`proof.divergence`),以 Lean 为准并退出非零。 + +4. **顾问式,不强制**。默认退出码只对"作者写下的定理未被关闭"(`unproved`)与工具错误非零;缺工具链、`rejected`、`unverified` 默认 0。需要严格覆盖的调用方显式传 `--require-lean`。规范与技能手册**推荐**在发布 SKILL 前运行,但不设为门禁。 + +5. **`prove` 不执行被证程序**。只读源码、写缓存与 `--emit` 目录;这一点由测试夹具(带 `fs.write` 的函数)守住。 + +## 备选与取舍 + +| 备选 | 否决理由 | +|---|---| +| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;多函数文件无法分派;诊断指不回具体行 | +| `# 证明` 标题 | `#` 是对象、`##` 是函数;新增"标题=命题"破坏"标题即可调用单元"的既有习惯,还会进命名空间 | +| ` ```proof ` 围栏 | 代码围栏必须跟在空赋值后,为写定理先造死变量,比表更别扭;且会被当作可执行值 | +| 普通注释承载定理 | 注释不参与语义,无法可靠区分说明与定理,拿不到行锚点 | +| 旁挂 `.proof.md` | 把真理拆成两份,违背"文档与代码同一份"的项目前提 | +| 细化类型(refinement types) | 语义增量过大,且与既有契约表形成两份作者真相 | +| 强制门禁(proved 才能发布) | 与"降低审核难度"的目标冲突;无 Lean 的团队会绕过工具 | + +## 后果 + +**正面** + +- 作者在一个地方写清"这条编排保证什么",机器可判定、行号可定位; +- 定理表与契约表同一提取路径,`check` / `view` / `catalog` 可逐步接入,不产生第二套声明; +- 外部依赖以假设形式显式化,证书是本项目一贯的"可复核证据"; +- 不新增核心标记,守卫测试与文档计数不膨胀。 + +**负面 / 代价** + +- 新增一个语言层语义角色与一个 CLI 命令,需要 ADR + 测试 + 文档(本 ADR 即准入材料); +- 离线判定器是新代码,必须长期用 Lean 语料护栏,防止"过度自信"; +- 作者可能误以为定理会在运行时生效——需要文档、`view` 与 `check` 三处反复澄清; +- `proved` 容易被读成"整份 SKILL 安全"——README 必须写死"只对陈述负责"。 + +## 语义增量清单 + +| 新增 | 是否进运行时 | 说明 | +|---|---|---| +| `Function.claims` | 否 | 与 `Function.contract` 同类的声明元数据 | +| `结果` / `轨迹` 与 `包含` / `长度` / `下标` | 否 | 仅定理作用域;与普通表达式作用域隔离 | +| `check --proof` | 否 | 静态校验,默认关 | + +不新增:求值规则、作用域规则、调用约定、核心标记、类型系统扩展。同名遮蔽(参数或局部变量叫 `结果`/`轨迹`)一律报 `proof.name_shadow`,不做隐式优先。 + +## 验收(摘要) + +- 核心表面:`cargo test --test core_surface` 不变红;`CORE_CONSTRUCTS` 计数不变。 +- 单调性:语料中每条离线 `checked` 的定理,Lean 均 `proved`;分歧为 0。 +- 不执行:带 `fs.write` 的夹具在 `prove` 后无副作用。 +- 确定性:同输入两次 `emit` 字节一致。 +- 诚实性:文本、JSON、证书三处对 `checked`/`proved` 的措辞一致。 + +## 未决(不阻塞实现) + +- `假设` 表是否需要扩展列(`来源`、`责任方`)。 +- `--all` 的聚合粒度(按文件/按函数)。 +- 证书是否需要签名,以及签名由谁持有。 diff --git a/doc/design/agent-reliability-tools-resources-2026-10-27.md b/doc/design/agent-reliability-tools-resources-2026-10-27.md old mode 100644 new mode 100755 diff --git a/doc/design/ai-skill.md b/doc/design/ai-skill.md old mode 100644 new mode 100755 diff --git a/doc/design/ambient-parameters-evaluation.md b/doc/design/ambient-parameters-evaluation.md old mode 100644 new mode 100755 diff --git a/doc/design/binding.md b/doc/design/binding.md old mode 100644 new mode 100755 diff --git a/doc/design/bracket-as-label-evaluation.md b/doc/design/bracket-as-label-evaluation.md old mode 100644 new mode 100755 diff --git a/doc/design/bracket-call-modifiers.md b/doc/design/bracket-call-modifiers.md old mode 100644 new mode 100755 diff --git a/doc/design/browser-marqdo-wasm.md b/doc/design/browser-marqdo-wasm.md old mode 100644 new mode 100755 diff --git a/doc/design/bytecode.md b/doc/design/bytecode.md old mode 100644 new mode 100755 diff --git a/doc/design/call-arguments.md b/doc/design/call-arguments.md old mode 100644 new mode 100755 diff --git a/doc/design/call-syntax-from-marks.md b/doc/design/call-syntax-from-marks.md old mode 100644 new mode 100755 diff --git a/doc/design/catalog-cli.md b/doc/design/catalog-cli.md old mode 100644 new mode 100755 diff --git a/doc/design/change-d9-unterminated-string.md b/doc/design/change-d9-unterminated-string.md old mode 100644 new mode 100755 diff --git a/doc/design/change-hostfn-table.md b/doc/design/change-hostfn-table.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m1-paren-call.md b/doc/design/change-m1-paren-call.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m10-engineering-habits.md b/doc/design/change-m10-engineering-habits.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m2-occlusion.md b/doc/design/change-m2-occlusion.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m25-label-diagnostics.md b/doc/design/change-m25-label-diagnostics.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m3-access-and-loop.md b/doc/design/change-m3-access-and-loop.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m4-label-refs.md b/doc/design/change-m4-label-refs.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m5-implicit-occlusion.md b/doc/design/change-m5-implicit-occlusion.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m6-t1-session.md b/doc/design/change-m6-t1-session.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m7-migration.md b/doc/design/change-m7-migration.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m8-ratchet.md b/doc/design/change-m8-ratchet.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m8-view-occlusion.md b/doc/design/change-m8-view-occlusion.md old mode 100644 new mode 100755 diff --git a/doc/design/change-m9-label-search.md b/doc/design/change-m9-label-search.md old mode 100644 new mode 100755 diff --git a/doc/design/change-plugin-sdk.md b/doc/design/change-plugin-sdk.md old mode 100644 new mode 100755 diff --git a/doc/design/code-as-docs-gaps.md b/doc/design/code-as-docs-gaps.md old mode 100644 new mode 100755 diff --git a/doc/design/code-volume-audit.md b/doc/design/code-volume-audit.md old mode 100644 new mode 100755 diff --git a/doc/design/code-vs-comment.md b/doc/design/code-vs-comment.md old mode 100644 new mode 100755 diff --git a/doc/design/collection-access-link.md b/doc/design/collection-access-link.md old mode 100644 new mode 100755 diff --git a/doc/design/core-surface.md b/doc/design/core-surface.md old mode 100644 new mode 100755 diff --git a/doc/design/dependencies.md b/doc/design/dependencies.md old mode 100644 new mode 100755 diff --git a/doc/design/document-native-development-guide.md b/doc/design/document-native-development-guide.md old mode 100644 new mode 100755 diff --git a/doc/design/engineering-knowledge.md b/doc/design/engineering-knowledge.md old mode 100644 new mode 100755 diff --git a/doc/design/examples-and-tests.md b/doc/design/examples-and-tests.md old mode 100644 new mode 100755 diff --git a/doc/design/executable-knowledge-system.md b/doc/design/executable-knowledge-system.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-abi.md b/doc/design/ext-abi.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-agent-parent.md b/doc/design/ext-agent-parent.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-agent-plan.md b/doc/design/ext-agent-plan.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-agent.md b/doc/design/ext-agent.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-ai-optimize.md b/doc/design/ext-ai-optimize.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-ai-sandbox.md b/doc/design/ext-ai-sandbox.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-cdn.md b/doc/design/ext-cdn.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-cli.md b/doc/design/ext-cli.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-hosting-fill.md b/doc/design/ext-hosting-fill.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-index-skill-tools.md b/doc/design/ext-index-skill-tools.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-linalg-formula-doc.md b/doc/design/ext-linalg-formula-doc.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-linalg.md b/doc/design/ext-linalg.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-llm.md b/doc/design/ext-llm.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-custom-gate.md b/doc/design/ext-quantum-custom-gate.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-handbook.md b/doc/design/ext-quantum-handbook.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-q5.5.md b/doc/design/ext-quantum-q5.5.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-q5.md b/doc/design/ext-quantum-q5.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-q7.md b/doc/design/ext-quantum-q7.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum-viz-style.md b/doc/design/ext-quantum-viz-style.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-skill-tools-paradigm.md b/doc/design/ext-skill-tools-paradigm.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-artifact.md b/doc/design/ext-web-artifact.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-collab.md b/doc/design/ext-web-collab.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/01-routes-and-admin-prefix.md b/doc/design/ext-web-customization/01-routes-and-admin-prefix.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/02-shell-css.md b/doc/design/ext-web-customization/02-shell-css.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/03-auth-gates.md b/doc/design/ext-web-customization/03-auth-gates.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/04-stylesheet-authoring.md b/doc/design/ext-web-customization/04-stylesheet-authoring.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/05-page-shell-slots.md b/doc/design/ext-web-customization/05-page-shell-slots.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/06-admin-crud-forms.md b/doc/design/ext-web-customization/06-admin-crud-forms.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/07-assets-script-lifecycle.md b/doc/design/ext-web-customization/07-assets-script-lifecycle.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/08-ext-deploy-coupling.md b/doc/design/ext-web-customization/08-ext-deploy-coupling.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-customization/README.md b/doc/design/ext-web-customization/README.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-drivers.md b/doc/design/ext-web-drivers.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-go-rewrite.md b/doc/design/ext-web-go-rewrite.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-handbook.md b/doc/design/ext-web-handbook.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-layout-paradigm.md b/doc/design/ext-web-layout-paradigm.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-net.md b/doc/design/ext-web-net.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-rbac.md b/doc/design/ext-web-rbac.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-request-context.md b/doc/design/ext-web-request-context.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-spa.md b/doc/design/ext-web-spa.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web-tenant.md b/doc/design/ext-web-tenant.md old mode 100644 new mode 100755 diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md old mode 100644 new mode 100755 diff --git a/doc/design/fence-meta-and-control-prose.md b/doc/design/fence-meta-and-control-prose.md old mode 100644 new mode 100755 diff --git a/doc/design/foreign-kernel.md b/doc/design/foreign-kernel.md old mode 100644 new mode 100755 diff --git a/doc/design/foreign-library-paper-direction-2026-11-05.md b/doc/design/foreign-library-paper-direction-2026-11-05.md old mode 100644 new mode 100755 diff --git a/doc/design/foreign-strong-correspondence.md b/doc/design/foreign-strong-correspondence.md old mode 100644 new mode 100755 diff --git a/doc/design/foreign-v3.md b/doc/design/foreign-v3.md old mode 100644 new mode 100755 diff --git a/doc/design/frontend-call-semantics-2026-11-03.md b/doc/design/frontend-call-semantics-2026-11-03.md old mode 100644 new mode 100755 diff --git a/doc/design/function-as-naming-philosophy.md b/doc/design/function-as-naming-philosophy.md old mode 100644 new mode 100755 diff --git a/doc/design/function-as-table-semantics.md b/doc/design/function-as-table-semantics.md old mode 100644 new mode 100755 diff --git a/doc/design/functions-as-values-evaluation.md b/doc/design/functions-as-values-evaluation.md old mode 100644 new mode 100755 diff --git a/doc/design/generated-yaml-manifest.md b/doc/design/generated-yaml-manifest.md old mode 100644 new mode 100755 diff --git a/doc/design/isolated-web-runtime-development-2026-10-26.md b/doc/design/isolated-web-runtime-development-2026-10-26.md old mode 100644 new mode 100755 diff --git a/doc/design/keywords-i18n.md b/doc/design/keywords-i18n.md old mode 100644 new mode 100755 diff --git a/doc/design/keywords.md b/doc/design/keywords.md old mode 100644 new mode 100755 diff --git a/doc/design/knowledge-layers.md b/doc/design/knowledge-layers.md old mode 100644 new mode 100755 diff --git a/doc/design/label-freshness-and-repair.md b/doc/design/label-freshness-and-repair.md old mode 100644 new mode 100755 diff --git a/doc/design/layers.md b/doc/design/layers.md old mode 100644 new mode 100755 diff --git a/doc/design/lib-code-as-docs.md b/doc/design/lib-code-as-docs.md old mode 100644 new mode 100755 diff --git a/doc/design/link-style-call-evaluation.md b/doc/design/link-style-call-evaluation.md old mode 100644 new mode 100755 diff --git a/doc/design/link-syntax.md b/doc/design/link-syntax.md old mode 100644 new mode 100755 diff --git a/doc/design/markdown-mapping-v0.3.md b/doc/design/markdown-mapping-v0.3.md old mode 100644 new mode 100755 diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md old mode 100644 new mode 100755 diff --git a/doc/design/module-namespace.md b/doc/design/module-namespace.md old mode 100644 new mode 100755 diff --git a/doc/design/notebook-session.md b/doc/design/notebook-session.md old mode 100644 new mode 100755 diff --git a/doc/design/notebook-syntax.md b/doc/design/notebook-syntax.md old mode 100644 new mode 100755 diff --git a/doc/design/objects.md b/doc/design/objects.md old mode 100644 new mode 100755 diff --git a/doc/design/occlusion-description-and-search.md b/doc/design/occlusion-description-and-search.md old mode 100644 new mode 100755 diff --git a/doc/design/occlusion-syntax.md b/doc/design/occlusion-syntax.md old mode 100644 new mode 100755 diff --git a/doc/design/okf.md b/doc/design/okf.md old mode 100644 new mode 100755 diff --git a/doc/design/oracle-journal-values.md b/doc/design/oracle-journal-values.md old mode 100644 new mode 100755 diff --git a/doc/design/paren-call-and-readable-invocation.md b/doc/design/paren-call-and-readable-invocation.md old mode 100644 new mode 100755 diff --git a/doc/design/parser-diagnostics-d8-d9.md b/doc/design/parser-diagnostics-d8-d9.md old mode 100644 new mode 100755 diff --git a/doc/design/pipeline-debug.md b/doc/design/pipeline-debug.md old mode 100644 new mode 100755 diff --git a/doc/design/prove-cli.md b/doc/design/prove-cli.md new file mode 100755 index 0000000..ff5450c --- /dev/null +++ b/doc/design/prove-cli.md @@ -0,0 +1,925 @@ +# `marqdo prove`:SKILL 编排的 Lean 编译与顾问式证明 + +| | | +|---|---| +| 状态 | **已实施(Implemented · 2.8.0)**:P0–P3 落地记录见 §12;遗留项(foreach、跨模块 assume-guarantee、假设表 T3)显式延期至 2.9,理由见 §12.4。路线图:[roadmap/prove.md](../roadmap/prove.md) | +| 日期 | 2026-11-13 | +| 层归属 | **Language**:定理表角色 + `check --proof`(§7,[ADR 0010](../adr/0010-skill-proof-boundary.md))· **Runtime**:`prove` 管线(§4–§6、§8)· **Document**:`verification/skill-proof` 证据 | +| 相关 | [core-surface.md](core-surface.md)(复用 `table` 构造,不新增标记)· [layers.md](layers.md)(准入)· [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [ADR 0010](../adr/0010-skill-proof-boundary.md) · [verification/replay-policy](../../verification/replay-policy/README.md)(Lean 伴随判定的先例) | +| 目标版本 | CLI **2.8.0**(wasm / ext 不随动:`prove` 不进 wasm) | + +--- + +## 0. 一句话与三条契约 + +`prove` 把一份 `.mq.md` 的**控制平面**(参数 → 分支 → 外部操作 → 返回值)降级成 Lean 4 定义,把作者声明的**定理**变成 Lean 定理,并尽最大努力自动关闭它们;同时输出一份可供人复核的证据(证书、假设、被拒清单)。它**不**是发布门禁,也**不**声称"过了 Lean 就绝对正确"。 + +三条契约,按优先级排列: + +1. **诚实**:`proved` 只表示"Lean 内核接受了这条形式化陈述"。它不表示陈述写对了意图、不表示外部 API 会守约、更不表示整份 SKILL 安全。反过来,`unproved` 只表示"这次没有关闭它"——可能是定理不成立,也可能只是策略不够。 +2. **单调**:离线判定(没有 Lean 时)**只能**给出 Lean 也能给出的结论。若两者分歧,以 Lean 为准并报内部错误,绝不放绿。`checked` 永远弱于 `proved`。 +3. **不执行**:`prove` 从头到尾不运行被证程序,不产生任何效应;它只读源码、写缓存与 `--emit` 目录。 + +> 一句话给论文:*给编排文档配一张可复核的证明收据*,而不是给整个语言发一张正确性证书。 + +--- + +## 1. 定位:降低审核量,不取代审核 + +### 1.1 为什么是顾问而不是门禁 + +Agent 改写 SKILL 后,人要看的是"这一步会不会绕开审核""失败分支会不会吞掉错误"。这些恰好是控制平面命题,Lean 能帮我们把"逐行读代码"压缩成"读几条定理 + 看一眼反例"。但: + +- 真实 SKILL 里有字符串、JSON、外部服务;把这些都形式化,成本远高于收益; +- 形式化陈述与业务意图之间永远隔着"作者写得对不对"; +- 大多数团队没有 Lean,强制门禁只会让人绕过工具。 + +所以 `prove` 的默认行为是**报告**,不是**拦截**。规范与手册**推荐**在发布 SKILL 前跑一次,但不强求;要不要把某个状态当失败,由调用方用 `--require-lean` / `--report-only` 自己决定。 + +### 1.2 三种"绿"和两种"红" + +| 状态 | 含义 | 由谁产生 | 能不能当"已证明" | +|---|---|---|---| +| `proved` | 全部定理被 Lean 内核接受 | Lean | **能**(且仅限陈述本身) | +| `checked` | 全部定理在离线片段(§5)内判定为真,已生成对应 Lean 脚本但未运行 | 离线判定 | **不能**,只能说"离线判定通过" | +| `unverified` | 有定理超出离线片段,且没有跑 Lean | 离线判定 | 不能 | +| `unproved` | 至少一条定理未被关闭;若能给出反例则附见证 | Lean / 离线 | 不能;这是红灯 | +| `rejected` | 有函数不在可证子集(`while`/递归/动态派发),已跳过 | 降级器 | 不能;这是"未覆盖",不是"错误" | + +`rejected` 与 `unproved` 的区别很重要:前者是**工具够不着**,后者是**命题没过**。把它们混成一个红,会让"文件里有个循环"看起来像"业务逻辑错了"。 + +此外还有 `error`(编码/类型/效应/IO/超时):它不是判定结果,而是**工具或程序本身出错**,退出 1。五种判定(proved/checked/unverified/unproved/rejected)与 `error` 在 JSON 里共用 `status` 字段,但语义分组不同,报告会分开统计。 + +### 1.3 诚实性词汇表(写进 README 与 `--json`) + +- `proved` ≠ 正确:它只对**写下来的陈述**负责,且假设 `Env` 的返回值任意、`假设` 表成立。 +- `unproved` ≠ 错误:策略失败、超时、片段外都可能;只有带 `counterexample` 字段时才是"确实不成立"。 +- `rejected` ≠ 不安全:只表示这部分没被形式化覆盖。 +- 证书不替代代码评审:它是**缩小**评审范围的工具,`audit` 会明确列出"哪些外部操作完全未知"。 + +### 1.4 非目标 + +- 不形式化解释器、字符串库、JSON、浮点、`formula`。 +- 不证明外部服务与网络;这些由 `假设` 表显式承担。 +- 不在 Agent 每次运行时跑 Lean;运行期只读证书。 +- 不自动安装 Lean;只探测并给出可执行提示。 +- 不追求"零人工":目标是让人从"读 200 行"变成"读 5 条定理 + 1 张假设表"。 + +--- + +## 2. 证明范围 + +### 2.1 义务分级 + +| 级别 | 义务 | 作者要写什么 | 谁保证 | 离线可做 | +|---|---|---|---|---| +| **T0 类型** | 生成的 Lean 通过内核;字段、元数、分支同型 | 无 | Lean | 部分(Rust 类型检查) | +| **T1 结构** | 终止(无 `while`/递归 ⇒ 结构递归)、分支出口完整、返回类型符合 `返回` 契约、效应不越权(给了 `--effects` 时) | 无 | 降级器 + Lean | 是 | +| **T2 声明** | 定理表里的业务命题 | 定理表 | Lean / 离线片段 | 是(F1–F5) | +| **T3 契约** | 外部操作前置/后置假设下的组合推理 | `假设` 表 | Lean | 部分 | +| **T4 一致性** | 生成语义与解释器在纯片段上同值 | 测试语料 | 差分测试 | 是 | + +### 2.2 三条硬边界(拒绝,不降级) + +| 构造 | 处理 | 诊断码 | +|---|---|---| +| `while`(`-` + 条件行) | 跳过该函数 | `proof.while` | +| 直接/间接递归(调用图有环) | 跳过该环 | `proof.recursion` | +| 动态派发(插件调用、变量函数名、`code` 值调用) | 跳过该调用点 | `proof.dynamic_call` | + +被跳过的函数不参与定理,其余函数照常出证。整体状态按固定优先级合成(差者胜):`error` > `unproved` > `rejected` > `unverified` > `checked` > `proved`。`--allow-opaque ` 可把某个被跳过的函数**整体**降级为不透明操作,让调用它的编排仍可证——此时它的行为完全未知,`audit` 必须列出来。 + +--- + +## 3. 命令面 + +### 3.1 命令与别名 + +```bash +marqdo prove [PATH] # 降级 → 生成 → 离线判定 →(有 Lean 时)Lean 判定 +marqdo prove emit [PATH] -o DIR # 只生成 Lean,不判定(离线/论文/AI 取用) +marqdo prove audit [PATH] # 只报降级结论:内联了什么、不透明了什么、拒了什么、假设了什么 +marqdo prove clean # 清 .marqdo/prove 缓存 +``` + +`prove` 带 `visible_alias = "lean"`;文档与 CI 统一写 `prove`。它与既有 `verify` 不重叠:`verify` 查知识一致性,`prove` 查控制平面命题。 + +### 3.2 参数 + +| 参数 | 默认 | 含义 | +|---|---|---| +| `PATH` | `index.mq.md` | 单个 `.mq.md`;目录需 `--all` | +| `--all` | off | 目录递归(跳过 `target`/`dist`/`node_modules`/`.git`/`.marqdo`);`--max-files ` 默认 200 | +| `--entry ` | `main` | 入口与报告分组;不限制文件内全量证明 | +| `--only ` | — | 只证这些函数(可重复),用于增量 | +| `--emit ` | `.marqdo/prove//Generated` | 保留生成的 Lean | +| `--json` | off | stdout 一个 JSON 对象(§3.5);诊断走 stderr | +| `--lean ` / `--lake ` | 探测 | 显式工具链 | +| `--library ` | 探测 | `MarqdoProof` 库目录 | +| `--timeout ` | 120 | 单次 Lean 调用上限 | +| `--heartbeats ` | 400000 | `maxHeartbeats` | +| `--no-cache` | off | 绕过证书与 olean 缓存 | +| `--no-offline` | off | 跳过离线判定,只用 Lean(CI 复现/调试用) | +| `--require-lean` | off | 严格模式:`checked`/`unverified`/`rejected` 一律返回 2 | +| `--report-only` | off | 除工具错误外恒返回 0 | +| `--allow-opaque ` | — | 把被跳过的函数降级为不透明操作 | +| `--effects ` | — | 与 `marqdo call --effects` 同格式;给出时检查实际调用是否越权 | +| `--strict-types` | on | 类型无法推断即报错;`--no-strict-types` 落 `Val`(证明力下降,报告标注) | +| `--tactic ` | `auto` | 定理表未写 `策略` 时的默认策略 | + +### 3.3 状态与退出码 + +| 状态 | 退出码 | `--require-lean` | `--report-only` | +|---|---|---|---| +| `proved` | 0 | 0 | 0 | +| `checked` | 0 | **2** | 0 | +| `unverified` | 0 | **2** | 0 | +| `rejected` | 0 | **2** | 0 | +| `unproved` | 1 | 1 | 0 | +| `error` / `timeout` | 1 | 1 | 1 | + +设计理由: + +- 缺工具链、有循环、定理在片段外,都**不是**程序的错,默认不返回非零——否则没装 Lean 的机器上 `prove` 等于不可用。 +- 默认情况下只有两种非零来源:**你写下的定理未被关闭**(1),或**工具出错**(1)。不写定理就不会有第一类失败。 +- 想要严格覆盖的团队用 `--require-lean`,把"未判定"升级成 2;CI 里加这一个参数即可。 +- 全局开关 `--report-only` 让 Agent 在探索期只看报告。 + +### 3.4 文本输出 + +```text +$ marqdo prove skills/marqdo-release/index.mq.md +审批 2/2 定理 proved Lean 0.8s +plan 1/1 定理 checked 离线判定 12ms(附 Lean 脚本,未运行) +预检 — rejected 离线 3ms proof.while L88 +prove: proved 1 · checked 1 · rejected 1 + 说明: checked 不代表 Lean 已验证;安装 Lean 或传 --lean 可交由 Lean 判定。 + 提示: `marqdo prove audit …` 查看降级细节与假设清单。 +``` + +失败时: + +```text +error[proof.claim_failed]: 定理「不该自动放行」未被关闭 + --> examples/approval.mq.md:31:3 + = 目标: (run env p).1.ok = false + = 上下文: h : p.amount > 10000 + = 反例: 金额 = 10001 时走「人工审核」分支,结果 ok = true + = 说明: 可能是命题不成立,也可能是策略不够;补 `策略` 或改判据后重跑。 +``` + +### 3.5 JSON(面向智能体的稳定契约) + +一个对象,`schema` 版本化;永不交互、stdout 只有结果、诊断在 stderr、路径为相对工作目录: + +```json +{ + "schema": 1, + "status": "checked", + "file": "skills/example/index.mq.md", + "source_sha256": "…", + "artifact_id": "mq://…", + "functions": [{ + "name": "审批", + "status": "checked", + "tier": "offline", + "claims": [ + {"id": "大额必经人工", "status": "checked", "decided_by": "trace", "ms": 3}, + {"id": "退款必须留痕", "status": "unverified", "reason": "out_of_fragment"} + ], + "obligations": [{"id": "terminates", "status": "passed"}, + {"id": "effects_subset", "status": "skipped", "reason": "no --effects"}] + }], + "lean": null, + "assumptions": [], + "diagnostics": [], + "emitted": [".marqdo/prove/ab12…/Generated/Approval.lean"], + "duration_ms": 15 +} +``` + +`lean` 为 `null` 表示没跑;跑了则是 `{"toolchain": "...", "library_sha256": "...", "module_sha256": "...", "cache": "hit|miss"}`。`tier` ∈ `{lean, offline, none}`,标明该函数的结论来自哪一层。`status` 的取值集合固定(§1.2),Agent 可按它分支,不需要解析自然语言。 + +### 3.6 面向智能体的使用契约 + +`prove` 的主要调用者不是人,是 Agent 的循环。因此: + +- **一次调用一个结论**:不做交互式提问,不读 TTY,不依赖环境变量之外的隐藏状态。 +- **只解析 JSON**:`--json` 的键与状态词是稳定契约(`schema` 升级才变);stdout 不混入程序输出或进度条。 +- **失败即数据**:每条诊断都有 `code` / `file` / `line` / `column` / `message`,能定位的还带 `goal`、`context`、`counterexample`、`hint`。Agent 不需要从自然语言里猜。 +- **可增量**:`--only ` 只证受影响函数;证书命中让第二轮降到毫秒级。 +- **先审计再证明**:Agent 应先 `prove audit --json` 看"有多少内联、多少不透明、多少被跳过",再决定是否值得为该文件写定理。 +- **推荐循环**:写 SKILL → `check` → `prove --json` → 读 `claims[].status` → 改代码/定理/策略 → 重跑 → 把证书附进交付说明。 + +### 3.7 选择规则 + +- **文件**:显式路径;目录必须 `--all`(否则 `proof.need_all`)。 +- **函数**:文件内全部 `##` 函数默认参与;`# main` 只作分组。 +- **导入**:默认内联可判定的纯函数(§4.5),其余成为不透明操作;不递归证明被导入文件。 +- **`--all` 聚合**:逐文件出状态,整体取最差;`--json` 输出 `files: [...]`。 + +--- + +## 4. 管线 + +### 4.1 六段 + +```text +.mq.md + ① 装载 load_module(只读,不执行) + ② 降级 AST → Plan IR:子集验收、拒绝码、span + ③ 定型 contract::Ty 驱动;未定 ⇒ 报错或 Val + ④ 生成 IR → Lean(确定性:稳定排序、无时间戳、相对路径) + ⑤ 离线判定 符号执行 + 片段判定(§5),产出 checked / 反例 / unverified + ⑥ Lean 判定 有工具链时运行;以它为准,与 ⑤ 分歧即 error +``` + +⑤ 永远在 ⑥ 之前:离线先给快速反馈,Lean 随后确认。`--no-offline` 可只跑 ⑥。 + +### 4.2 Plan IR + +`src/prove/ir.rs`,`serde` 序列化为 `plan.json`(版本化,缓存键的一部分,论文工具可直接消费): + +```jsonc +{ + "schema": 1, + "module": "skills/example/index.mq.md", + "source_sha256": "…", + "functions": [{ + "name": "审批", + "params": [{"name": "金额", "ty": {"kind": "int"}}], + "result_ty": {"kind": "map", "fields": [["ok","bool"],["value","any"],["error","any"]]}, + "ops": [{"id": "人工审核", "effect": "network.read", "params": [["金额","int"]]}], + "steps": [ + {"kind": "if", "cond": {"op": "gt", "args": [{"var": "金额"}, {"int": 10000}]}, + "then": [{"kind": "bind", "var": "审核", "expr": {"call": "人工审核", "args": [{"var": "金额"}]}}, + {"kind": "return", "expr": {"ctor": "result.ok", "args": [{"var": "审核"}]}}], + "else": [{"kind": "return", "expr": {"ctor": "result.ok", "args": [{"text": "auto"}]}}], + "span": {"line": 21, "col": 1}}], + "claims": [{"id": "大额必经人工", "premise": null, "conclusion": "…", "tactic": null}], + "effects": ["network.read"], + "assumptions": [] + }] +} +``` + +表达式分两层:`PureExpr`(字面量、变量、算术/比较/布尔、字符串拼接与插值、列表/映射字面量、`access`、`len`、类型转换)可翻译成 Lean 项;其余一律 `Call`(不透明操作),或按 §4.3 拒绝。**没有"猜"的回退。** + +### 4.3 接受 / 拒绝矩阵 + +| Marqdo | 处理 | 备注 | +|---|---|---| +| `**x = 纯表达式**` | `bind` | 类型由右值推断 | +| `**x = [标签](调用)**` | `bind` + `Op` + `trace` | 效应来自 sema | +| `**x**`(粗体无赋值) | `return` | 纯表达式或已内联构造器 | +| `*语句*` / `> 调用` | 语句形式,值丢弃 | 丢弃的调用仍进 trace | +| `1. 条件 / 2. *` | `if/else` | 条件必须是纯布尔表达式 | +| `- [项](遍历 列表 为 项)` | `foreach`(P3) | 只接受有限列表;此前 `proof.foreach_pending` | +| `-` + 条件 | **跳过** `proof.while` | | +| 递归 | **跳过** `proof.recursion` | 调用图环检测 | +| 方法调用 `` `recv`.方法 `` | 不透明操作 | 接收者不展开 | +| `code` 值 / 插件调用 | **跳过** `proof.dynamic_call` | 不在纯片段 | +| GFM 表绑定 | `list`/`map` 字面量 | 列长不一致已在解析期拒绝 | +| `$$` 公式 | 不透明值(`Formula`) | 不翻译 TeX,不做推理 | + +### 4.4 类型推断 + +起点:`参数` 表 + `返回` 表(`contract::Ty`)。合一规则: + +- 字面量给最具体类型;`+ - * /` 要求两侧 `int`;`and/or/not` 要求 `bool`。 +- 分支合流:两臂同名变量类型必须相容,否则 `proof.type_mismatch`(带两处行号)。 +- 映射字段:返回表达式是映射字面量时得到 `structure`;是内联的 `result.ok/error`(lib/result 真实 API)时沿用 Result 形状;否则落 `Val`,此时 `结果.ok` 报 `proof.result_untyped`(提示:返回映射字面量或包成 Result)。 +- `--no-strict-types` 时未知类型落 `Val`;定理里只能做等式/成员判断,报告标注"弱类型"。 + +### 4.5 内联与不透明化 + +1. 建调用图(本文件 + 导入文件);有环即跳过该环。 +2. **内联**:被调函数(含 `lib/result` 一类纯库)满足 ①契约 `Effects: pure` ②语句数 ≤ 24 ③不含被跳过构造 ④非递归 → 展开函数体。这样 `result.ok(...)` 在 Lean 里就是 Val 映射构造(`mqResultOk`),`结果.ok` 变成可判定字段。 +3. **不透明化**:其余调用生成 `Op` 构造器 + 效应,由 `Env` 参数处理;`--allow-opaque` 可强制。 +4. `audit` 逐条列出:内联 / 不透明 / 跳过,以及每个不透明操作的效应与参数类型。 + +--- + +## 5. 离线判定(没有 Lean 也能给结论) + +### 5.1 为什么需要 + +- 大多数开发机与 CI 没有 Lean;没有离线路径,`prove` 就只是"生成器"。 +- Agent 迭代需要毫秒级反馈,Lean 一次数百毫秒到数十秒。 +- 反例("金额 = 10001 时轨迹里没有人工审核")比 tactic 失败更有用。 + +但离线**绝不能**比 Lean 强。做法不是"相信我们的判定器",而是把它关进一个**极小的片段**,并让每条离线结论都附带 Lean 脚本。 + +### 5.2 片段 F1–F5(保守,超出即 `unverified`) + +| 片段 | 能判定什么 | 为什么安全 | +|---|---|---| +| **F1 路径枚举** | 控制流是有限树(无循环/递归)⇒ 返回路径有限 | 由 §2.2 的拒绝保证 | +| **F2 轨迹** | 每条路径的 `Op` 序列由分支决定;`包含/长度/下标` 逐路径求值 | 轨迹是语法产物,不依赖 `env` 返回值 | +| **F3 字面结果** | 返回表达式只由字面量、参数、内联构造器组成时按结构求值 | 与 Lean 的 `mqResultOk` 形状一一对应 | +| **F4 命题** | `and/or/not`、`=/≠` 作用于 F2/F3 的布尔结果;外部返回值上的**布尔判定**(如 `access(回执,"ok") == False`)视为自由原子,可分叉 | 自由原子只做二分、不假设原子间关系;两条分支都关闭才 `checked`,因此证明是对任意 `env` 成立的 | +| **F5 单变量区间** | 原子 `x ⋈ c`(`c` 为整数字面量,`⋈ ∈ {<,≤,>,≥,=,≠}`);用路径条件 + 前提的上下界判定蕴含 | 单变量区间推理是线性整数算术的子集,`omega` 必然也能证 | + +明确**不**离线判定(直接 `unverified`,不猜):多变量线性组合、非线性算术、字符串比较、外部返回值的非布尔字段(`.value` 之类)、任何需要归纳的命题。 + +### 5.3 判定过程 + +1. 符号执行函数体:状态 `Var → SymVal`(`Const` / `Param` / `OpResult` / `Unknown`),路径条件为原子列表,轨迹为 `Op` 列表。 +2. 每个 `if` 分叉两支(条件 / 其否定);每个 `Op` 调用产生一个 `OpResult` 符号(值未知,但**出现**已知)。 +3. 每个 `return` 收集 `(路径条件, 结果 SymVal, 轨迹)`。 +4. 对每条路径检查 `前提 ∧ 路径条件 ⊢ 结论`:把 `结果/轨迹` 代入后按 F2–F5 求值或判定。 +5. 全部路径关闭 ⇒ 该定理 `checked`;任一原子超出片段 ⇒ `unverified`;某条路径可满足且结论为假 ⇒ `unproved` + 反例。 + +### 5.4 证书与"单调性" + +每条 `checked` 定理同时产出: + +- **情形证书**:`(路径 id, 路径条件, 规范化目标, 关闭理由 ∈ {literal, hypothesis, interval, atom})`,写进 `certificate.json`; +- **Lean 脚本**:`unfold run` 后按同一棵 `if` 树 `split_ifs`,每个叶子 `simp_all <;> omega`。离线情形树与 Lean 的 `if` 树来自同一份 IR,叶子一一对应;某个叶子离线关闭而 Lean 关不掉,就是 `proof.divergence`。 + +因此"离线判定 ⊂ Lean 判定"不是口头承诺,而是三件事: + +1. **构造上**:F5 的推理是 `omega` 的子集,F1–F4 是 `simp`/`decide` 的子集; +2. **运行期**:只要有 Lean,就在 ⑥ 复核;`checked` 但 Lean 未关闭 ⇒ `error[proof.divergence]`,退出 1,永不落绿; +3. **测试上**:语料库强制 `offline_checked ⊆ lean_proved`(roadmap 测试矩阵 A1)。 + +**不夸大**:我们不说"离线判定器已被证明正确"。我们说它片段极小、保守、每条结论都带 Lean 脚本,且有运行期复核与 CI 语料强制。 + +### 5.5 反例 + +当某条路径可满足、且结论在该路径上求值为假时,从区间端点取一组参数值作为见证: + +```text +反例: 金额 = 10001 +路径: 金额 > 10000 → 人工审核 +结论: 结果.ok = False +实际: 结果.ok = True(人工审核的返回值被包进 result.ok) +``` + +反例只承认**确定性否定**:结论必须是字面 `false`,路径必须由区间证明可满足,且路径条件里**不含自由布尔原子**(否则可能凑出真实语义下不存在的组合)。任何一条不满足就退回 `unproved`(无见证)或 `unverified`,不编故事。 + +--- + +## 6. Lean 编码 + +### 6.1 产物布局 + +```text +verification/skill-proof/ # 入仓:语义库 + 论文样例(人工评审) + lean-toolchain # 与 replay-policy 同钉(v4.35.0) + lakefile.lean + MarqdoProof.lean + MarqdoProof/{Basic,Result,Tactic}.lean + examples/{approval,false-claim}.lean + README.md # TCB 与"证了什么"的边界声明 + LIBRARY-SHA256 # 由构建脚本写入 + +.marqdo/prove/ # 生成物(.marqdo/ 已 gitignore) + pkg/ # 一次性 Lake 包(库副本 + Generated/) + /plan.json module.lean certificate.json lean.log + index.json # key → 指纹/状态/耗时 +``` + +### 6.2 无公理:操作是参数,假设是前提 + +```lean +-- 库提供(MarqdoProof/Basic.lean,节选) +inductive Val | none | int : Int → Val | str : String → Val | bool : Bool → Val + | list : List Val → Val | map : List (String × Val) → Val + +structure Err where code : String; message : String; operation : String +structure Result where ok : Bool; value : Val := .none; error : Option Err := none + +-- lib/result 的真实构造器(ok/error/value_or)映射: +def Result.success (v : Val) : Result := { ok := true, value := v } +def Result.failure (e : Err) : Result := { ok := false, error := some e } +``` + +生成文件里**不出现 `axiom`,也不出现 `opaque`**:外部操作是 `Env := Op → Val` 参数,后置条件是定理的假设 `h_post`。于是 `#print axioms` 为空,定理陈述本身就把"信任了什么"写清楚。 + +### 6.3 直接风格降级(无 monad、无 `do`) + +`StateM`/`do` 在证明里要额外展开 monad 定律,早返回的语义也容易踩坑。改用**续延式直接风格**:`compile_stmts(stmts, k)` 在 Rust 里把后续语句当续延,早返回就是"把 `k` 换成函数出口"。产出的 Lean 是纯 `let`/`if`/`pair`,`simp`/`split`/`omega` 直接可用。 + +输入(`verification/skill-proof/examples/approval.mq.md` 节选): + +```markdown +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留人工审核结论](result.ok(value=`审核`))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +**结果** +``` + +输出: + +```lean +import MarqdoProof +open MarqdoProof + +namespace Generated.Approval + +structure Params where + 金额 : Int + deriving Repr, DecidableEq + +inductive Op where + | 人工审核 (金额 : Int) + deriving Repr, BEq + +def Op.name : Op → String + | .人工审核 _ => "人工审核" + +abbrev Env := Op → Val + +def run (env : Env) (p : Params) : Result × List Op := + if p.金额 > 10000 then + let v := env (.人工审核 p.金额) + (Result.success v, [.人工审核 p.金额]) + else + (Result.success (.str "auto"), []) + +theorem 大额必经人工 (env : Env) (p : Params) (h : p.金额 > 10000) : + (run env p).2.any (fun o => o.name == "人工审核") = true := by + unfold run + split_ifs <;> simp_all <;> omega + +end Generated.Approval +``` + +要点:每步带 `-- mq: line:col` 注释;中文标识符直接可用,含点/空格的用 `«…»`;命名冲突在生成前消解。 + +### 6.4 义务与定理 + +| 项 | 形状 | 来源 | +|---|---|---| +| 类型检查(T0) | 文件通过内核:字段、元数、分支同型 | Lean,编译结果即证据 | +| 终止(T1) | 无 `while`/递归 ⇒ Lean 接受为 `def` | 同上;需要 `partial` 的一律已跳过 | +| `effects_subset` | 实际 `Op` 集合 ⊆ `--effects` 授权 | Rust 判定,写证书 `obligations` | +| 作者定理(T2) | `∀ p, pre p → post p (run env p)` | 定理表 | +| 假设(T3) | `h_* : ∀ …, Post …` 作为定理前提 | 假设表 | + +违反 `effects_subset` 不是 `rejected` 而是 `error[proof.effects_exceeded]`:前者是"够不着",后者是"够得着且越权",必须区分。未给 `--effects` 时该义务记为 `skipped`,不假装通过。 + +### 6.5 策略 + +```lean +macro "mq_auto" : tactic => + `(tactic| first + | decide + | omega + | simp_all + | (split <;> simp_all) + | (split_ifs <;> simp_all <;> omega) + | aesop) +``` + +定理表 `策略` 列可写 `auto` / `omega` / `simp [run]` / 任意 tactic 片段;写 `none` 表示只生成不证(论文留人工证明钩子),状态记 `unverified` 而不是失败。 + +### 6.6 源码映射 + +每个语句前放 `-- mq: :`;`module.lean` 与 `plan.json` 同缓存。Lean 报 `Generated/X.lean:41:7: error: …` 时,驱动把 41 映射回 `.mq.md` 行,诊断指回源码,`lean_line` 放在 JSON 细节里。映射表进证书。 + +--- + +## 7. 作者面:定理表与语言习惯 + +### 7.1 语法与位置 + +表格构造**已有**(不新增核心标记),这里只给它一个新的**语义角色**: + +```markdown +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | +``` + +规则(与 `参数/返回/字段` 契约表同构): + +1. 表头别名:`定理/证明/claim/theorem`;列名 `结论/conclusion`、`前提/premise`(可缺省)、`策略/tactic`(可缺省)。 +2. 位置:函数体**首条可执行语句之前**,与契约表同一槽位;提取后从 body 移除,**不参与运行**。出现在别处仍是普通表,`check --proof` 报 `proof.claim_misplaced`。 +3. 一行一条;`定理` 列是函数内唯一 id,重复即 `proof.claim_duplicate`。 +4. 结论/前提是**受限表达式**:参数、`结果`、`轨迹`、`包含/contains`、`长度/length`、`下标/index`,以及算术/比较/布尔。其他名字 → `proof.claim_unknown_symbol`(带最近建议)。 +5. 一张表如果既像契约表(有 `类型` 列)又像定理表(有 `结论` 列)→ `proof.claim_ambiguous`,不猜。 + +### 7.2 语义 + +一条定理展开为: + +```lean +theorem (env : Env) (p : Params) (h : <前提>[p]) : + <结论>[p, (run env p)] := by … +``` + +- 前提在**入口状态**求值(参数),结论可引用参数、`结果`、`轨迹`。 +- 没有前提就是全称命题;`结果.ok = True` 天然表示"所有成功终止都满足"。 +- `轨迹` 有序;`包含/长度/下标` 三个谓词够表达"存在/顺序/计数",不再长大。 +- 定理是**声明**,不是代码:没有求值顺序、没有副作用、不能调用任意函数。 + +### 7.3 语言习惯审查(是否引入了多余语义) + +这是这次设计最需要交代清楚的一节。逐条回答"会不会破坏语言习惯"。 + +#### 7.3.1 实际新增了什么 + +| 新增项 | 性质 | 是否影响运行 | +|---|---|---| +| `Function.claims` 元数据 | 声明(与 `Function.contract` 同类) | **否**,提取后从 body 移除 | +| 定理作用域的两个保留名(`结果/轨迹`)与三个谓词 | 只在定理内可见的绑定 | **否**,不在普通表达式作用域 | +| 假设表作用域的 `返回` | 只在假设表内可见的绑定 | **否** | +| `check --proof` | 静态校验开关,默认关 | 否 | + +除此之外没有新语法、没有新标记、没有新求值规则、没有新类型系统。 + +#### 7.3.2 没有新增什么(逐项对照) + +| 风险项 | 结论 | 依据 | +|---|---|---| +| 新核心标记? | 否 | 用的是既有 GFM 表(`core-surface.md` 的 `table`);`CORE_CONSTRUCTS` 计数不变 | +| 新求值顺序/作用域? | 否 | 定理表与契约表一样,在解析期提取,不进 AST body | +| 新调用约定/形参? | 否 | 不要求调用者传证明参数,不给函数加隐藏形参 | +| 新类型系统(refinement/依赖类型)? | 否 | 只在表里写命题;不做类型层扩展 | +| 影响叙述比例/可读性? | 否 | 表是 code 构造;GitHub 渲染正常;`labels`/`narrative_ratio` 行为不变 | +| 影响 `check` 既有诊断? | 否 | 新表头不命中 `参数/返回/字段`,`parse_contract_table` 不认领;新增校验默认关 | + +#### 7.3.3 为什么不是别的写法 + +| 备选 | 为什么不用 | +|---|---| +| frontmatter `proof:` 块 | 丢函数作用域与行级锚点;一个函数一条定理时锚点落在文件头,诊断无法指回具体行;多函数文件无法分派 | +| `# 证明` 标题 | `#` 是对象、`##` 是函数,标题即单元——新增"标题=命题"会破坏"标题即可调用单元"这条既有习惯,且会进命名空间 | +| 围栏块(` ```proof ` 语言标签) | 代码围栏必须跟在空赋值后(`x =` + fence),否则解析器直接报错;为了写定理先造一个死变量,比表更别扭,且该值会被当作可执行值 | +| 注释里写定理(``) | 注释不参与语义,也拿不到行锚点;工具无法可靠区分"说明"与"定理" | +| 单独 `.proof.md` 旁挂文件 | 真理被拆成两份,正是这个项目一直在避免的事("代码与文档同一份") | +| 类型即契约(refinement) | 语义增量太大,且现有契约表已经承担类型声明;再来一套会形成"两份作者真相" | + +函数级表格是最符合本项目习惯的:**声明与函数同址、可定位、可校验、不可执行**——这正是 `参数/返回/字段` 表已经建立的模式。 + +#### 7.3.4 命名冲突与遮蔽 + +- 定理作用域里 `结果`/`轨迹`、假设作用域里 `返回` 是保留名。若函数有形参或局部变量同名,`check --proof` 报 `proof.name_shadow`(错误),要求改名——**不**做隐式优先,避免"同名不同义"。 +- 谓词名 `包含/长度/下标` 若与用户函数同名,同样报 `proof.name_shadow`,不做静默覆盖。 + +#### 7.3.5 仍然存在的风险与护栏 + +| 风险 | 说明 | 护栏 | +|---|---|---| +| "定理像代码"的错觉 | 作者可能以为 `结果.ok = False` 会在运行时求值 | 文档措辞统一为"声明";`view` 渲染成定理卡片;`check` 提示不可运行位置 | +| 定理表长出第二门语言 | 有人想写量词、自定义谓词、调用函数 | 谓词集合封闭(3 个);超出即 `proof.claim_unsupported`;ADR 改集合需重新评审 | +| 定理与代码漂移 | 改了分支但没改定理 | 定理锚定行号;`check --proof` 校验引用的变量仍存在;`prove` 每次重证 | +| 定理变成装饰 | 写了 `策略 none` 或永远 `unverified` | `audit` 统计"声明/已判定/未判定";证书只记录实际判定结果 | +| 表被误当数据表 | 普通文档表恰好叫 `定理` | 只有表头命中且列形正确才认领;两列的"定理/说明"表仍是普通表 | + +结论:**语义增量被压到三条声明级绑定,且不进入运行时**。它没有引入新的编程习惯,只是把"契约表"这一既有习惯扩展到"命题"。 + +### 7.4 假设表(T3) + +外部操作默认完全未知。要让"只要银行返回失败,我们就不会记账"这类推理成立,把假设写成表: + +```markdown +| 假设 | 前置 | 后置 | +|---|---|---| +| 银行.转账 | 金额 > 0 | 返回.ok = True | +``` + +- 表头 `假设/assumption`;`操作` 列是调用显示名(`库.成员`)。 +- 前置在实参上求值;后置在 `返回`(操作返回值)上求值;支持 `=/≠/包含/长度` 与 `返回.ok`(映射字段读取的语法糖)。 +- 生成 Lean 时不是公理,而是**定理前提**:`h_转账 : ∀ a, a > 0 → (env (.转账 a)).field? "ok" = some (.bool true)`。 +- 无法定型的后置 → `proof.assumption_untyped`(提示改成等式或补返回契约)。 +- `audit` 与证书 `assumptions` 一一对应。 + +### 7.5 与 `check` / `view` / `catalog` + +- `check`:新增 `--proof`(**默认关**,保持既有性能),校验表形、名字、片段;不跑 Lean。 +- `view`:定理表渲染成"已声明定理"卡片;有证书时附状态徽标(`proved`/`checked`/`unverified`)。不触发证明。 +- `catalog`/`knowledge`:`Artifact` 增可选 `proof:` 摘要(证书哈希 + 状态 + 定理数),供 EKM 与 `reuse` 过滤;不改变现有 schema 必填项。 + +--- + +## 8. 工程落点 + +### 8.1 新增 / 修改文件 + +| 文件 | 变更 | +|---|---| +| `src/prove/mod.rs` | API、状态机、报告聚合 | +| `src/prove/ir.rs` | Plan IR + 规范化 JSON + 指纹 | +| `src/prove/lower.rs` | AST → IR、子集验收、拒绝码、内联 | +| `src/prove/types.rs` | 类型推断与合一 | +| `src/prove/emit.rs` | IR → Lean(确定性、命名消解、span 注释、脚本生成) | +| `src/prove/offline.rs` | 符号执行、F1–F5 判定、反例 | +| `src/prove/driver.rs` | 工具链探测、Lake 包、`lean` 调用、超时、诊断映射 | +| `src/prove/cache.rs` | 证书、`index.json`、失效判定 | +| `src/prove/report.rs` | 文本 / `--json` 渲染 | +| `src/ast.rs` | `Function.claims: Vec` | +| `src/claim.rs`(或并入 `contract.rs`) | 定理表提取与校验 | +| `src/parse/mod.rs` | 定理表提取入口(首条可执行语句前) | +| `src/check.rs` | `--proof` | +| `src/main.rs` | `Commands::Prove`、`ProveAction`、json_errors | +| `src/lib.rs` | `pub mod prove;` | +| `verification/skill-proof/**` | Lean 库、样例、`LIBRARY-SHA256`、README | +| `tests/prove.rs` + `tests/prove/**` + `tests/prove_lean.rs` | 集成测试、夹具、Lean 语料(独立目标) | +| `.github/workflows/proof.yml` | elan + `lake build` + 语料门禁 | + +不新增 crate 依赖(`serde_json`、`sha2`、`anyhow` 已在);Lean 侧零依赖(只用 Std)。 + +### 8.2 API + +```rust +pub struct ProveOptions { + pub entry: Option, + pub only: Vec, + pub allow_opaque: Vec, + pub emit_dir: Option, + pub effects: Option, + pub strict_types: bool, + pub offline: bool, + pub timeout: Duration, + pub heartbeat: u64, + pub require_lean: bool, + pub report_only: bool, + pub no_cache: bool, + pub lean: Option, + pub library: Option, +} + +pub enum Verdict { Proved, Checked, Unverified, Unproved, Rejected, Error } + +pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result; +pub fn emit_path(path: &Path, out: &Path) -> Result; // 不判定 +pub fn audit_path(path: &Path) -> Result; // 不判定 +``` + +`main.rs` 只做参数搬运与退出码映射(与 `Commands::Verify` 同风格)。 + +### 8.3 缓存与证书 + +缓存键:`sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)`。证书: + +```jsonc +{ + "schema": 1, + "key": "…", + "status": "proved", + "tier": "lean", + "source": {"path": "skills/…", "sha256": "…", "artifact_id": "mq://…"}, + "lean": {"toolchain": "…", "library_sha256": "…", "module_sha256": "…", "axioms": []}, + "claims": [{"id": "…", "status": "proved", "decided_by": "omega"}], + "offline": {"claims": [{"id": "…", "status": "checked", "cases": 3}]}, + "obligations": [{"id": "effects_subset", "status": "passed"}], + "assumptions": ["银行.转账: 前置 金额 > 0;后置 返回.ok = True"], + "span_map": {"41": "21:1"}, + "created": "2026-11-13T09:00:00Z", + "marqdo": "2.8.0" +} +``` + +- 命中即跳过判定(报告标 `cache: hit`)。 +- 源文件、库、工具链任一变化即失效;暂不做部分重证。 +- 证书是**复核收据**,不是发布许可:推荐附在发布说明里,不强制。 +- `prove clean` 删 `.marqdo/prove`(`--emit` 目录不动)。 + +### 8.4 工具链与库发现 + +1. `--lean`/`--lake`;2. `MARQDO_PROOF_LEAN`/`MARQDO_PROOF_LAKE`;3. `PATH` 上的 `lake`,再 `lean`;4. 都没有 → 只跑离线,`lean: null`。 + +显式给出(flag 或环境变量)但路径不存在/不可执行 → `error[proof.lean_missing]`,**不**回退到离线:避免"我以为在跑 Lean,其实没有"。 + +库发现:`--library` → `MARQDO_PROOF_LIB` → 仓库内 `verification/skill-proof` → 安装根 `share/marqdo/proof/` → 相邻 `marqdo-proof/`。首次使用按 `LIBRARY-SHA256` 复制进 `.marqdo/prove/pkg` 并 `lake build` 一次(缓存);库哈希进证书。 + +### 8.5 环境变量 + +| 变量 | 作用 | +|---|---| +| `MARQDO_PROOF_LEAN` / `MARQDO_PROOF_LAKE` | 工具链路径 | +| `MARQDO_PROOF_LIB` | 语义库目录 | +| `MARQDO_PROOF_TIMEOUT` | 默认超时(秒) | +| `MARQDO_PROOF_CACHE` | 缓存根(默认 `.marqdo/prove`) | +| `MARQDO_PROOF_NO_CACHE` | 等价 `--no-cache` | +| `MARQDO_PROOF_REQUIRE_LEAN` | 等价 `--require-lean`(CI/测试用) | + +--- + +## 9. 测试与证据(摘要) + +完整矩阵见 [roadmap/prove.md](../roadmap/prove.md) §6。四类必须守住的证据: + +1. **单调性**(用户硬要求):语料库里每条离线 `checked` 的定理,Lean 都必须证出来;任何分歧 → `error[proof.divergence]`。 +2. **不执行**:带 `fs.write`/`exec` 的夹具在 `prove` 后不产生任何副作用。 +3. **确定性**:同输入两次运行,`module.lean` / `plan.json` / 证书键全等。 +4. **诚实性文案**:`checked` 与 `proved` 在文本、JSON、证书三处措辞一致,不允许出现"已验证"字样描述离线结果。 + +--- + +## 10. 已定事项 + +| # | 事项 | 结论 | 备注 | +|---|---|---|---| +| 1 | 命令名 | `marqdo prove` | 别名 `lean` | +| 2 | 是否强制 | **不强制**;规范与手册推荐 | 无 `--require-lean` 时缺工具链不失败 | +| 3 | 离线能否给结论 | 能,但只到 `checked` | 严格弱于 Lean(§5) | +| 4 | 定理写法 | 函数级 `定理` 表 | [ADR 0010](../adr/0010-skill-proof-boundary.md) | +| 5 | `check --proof` | 加,默认关 | | +| 6 | 首版 `foreach` | 不做,P3 再加 | 之前 `proof.foreach_pending` | +| 7 | 状态词 | `proved` / `checked` / `unverified` / `unproved` / `rejected` | 只有 `proved` 能说"已证明" | + +遗留(不阻塞开工,P2 前定):`假设` 表是否也认领 `前置/后置` 之外的列(如 `来源`);`--all` 的聚合粒度(按文件还是按函数);证书是否需要签名。 + +--- + +## 11. 文档与发布清单 + +- [ ] 本文件转 `Implemented`(分阶段勾) +- [ ] `doc/roadmap/prove.md`:里程碑、周计划、测试矩阵 +- [ ] `doc/adr/0010-skill-proof-boundary.md`:定理表角色 + 子集边界 + 顾问式定位 +- [ ] `doc/design/skill-proof-theory.md`:语义映射、定理形态、TCB 表 +- [ ] `verification/skill-proof/README.md`:构建、身份哈希、与 replay-policy 的关系 +- [ ] `README.md`:CLI 三行示例 + 状态表 + "推荐但不强制" +- [ ] `doc/tutorial/13-命令行工具.md`:先 `emit`,再 `prove` +- [ ] `skills/marqdo-dev/index.mq.md`:新增 `prove` 任务(推荐在发布前跑) +- [ ] `skills/marqdo/reference.md`:定理表语法速查 +- [ ] `CHANGELOG.md`:2.8.0;「核心表面 Δ:无(表格新增语义角色:定理)」 +- [ ] `.github/workflows/proof.yml`;`.gitignore` 已含 `.marqdo/` +- [ ] 发版手册:推荐附证书哈希,不设为硬门禁 + +--- + +## 12. 实现状态与偏差记录(P0/P1 落地时修订) + +| 状态 | 内容 | +|---|---| +| **P0 已落地** | `src/prove/`:`ir.rs`(Plan IR + 稳定 JSON)、`lower.rs`(子集验收/内联/不透明化/效应标签)、`types.rs`(字面量推断 + 分支合流 + `proof.type_mismatch`)、`emit.rs`(确定性 Lean 生成)、`mod.rs`(Report/Verdict/ProveOptions + `prove/emit/audit/clean`)。测试:`tests/prove.rs` 12 例 + 模块单元测试,全部不依赖 Lean。 | +| **P1(Rust 侧)已落地** | 定理表提取(`ast::Function.claims` + `contract::parse_claim_table`,首条可执行语句之前,提取后移出 body);`check --proof`(默认关):`proof.claim_malformed` / `claim_ambiguous` / `claim_misplaced` / `claim_duplicate` / `claim_unknown_symbol` / `claim_unsupported` / `name_shadow`;定理脚手架生成(受限文法 → Lean `theorem` 陈述 + §7.2 策略脚本)。Lean 判定(lake/driver/cache/CI)按 roadmap P1 第 2 周继续。 | + +### 与本文前面章节的偏差(以本表为准) + +1. **`result.ok/error/value_or`,不是 `result.success/failure`**:设计起草时假设的库名与 `lib/result.mq.md` 真实 API 不一致,实现以真实库为准(§4.5/§6.2 示例已同步修正)。Lean 侧库提供 `Result.success/failure` 作为映射目标。 +2. **P0/P1 的 `run` 返回 `Val × List Op`**:`result.ok(...)` 内联为 Val 字面映射构造(`mqResultOk`),而非单独的 `Result` 结构。P2 起按返回契约提升为类型化 `structure Params`/`Result`(§6.2 的形态),届时定理表可直接做字段级推理。 +3. **Op 构造器带元数**:`inductive Op` 的每个构造器按首现实参个数声明 `参数1..参数N : Val`(§6.2 示例省略了这一点)。 +4. **`--allow-opaque` 的效应标签恒为 `opaque`**:即便函数声明了契约效应也不沿用——行为完全未知时引用其声明只会误导 `audit` 读者(§2.2)。 + +### 审查修复(同日代码审查发现,均有回归测试) + +| 缺陷 | 后果 | 修复 | +|---|---|---| +| 表格单元格里的调用被静默丢弃 | 含副作用调用的函数在 Lean 里伪装成"无操作"——违反诚实性契约 | `lower_expr` 回退分支检测容器内的调用 → `proof.unsupported` 拒绝整个函数 | +| 同名不同元数的调用点共享一个 Op | 构造器按首现声明元数,另一调用点生成非法 Lean(无法编译) | `register_op` 对不同元数加 `/N` 后缀,各自独立声明(轨迹名诚实区分) | +| `name_shadow` 每层遍历重复报告 | 模块有 N 个函数就报 N 次,噪声淹没真实问题 | 谓词名检查只跑一次(模块级事实);形参检查只看自带定理表的函数 | +| `长度(轨迹) = 2` 生成 `mqEq (Nat) (Val)` | Nat 与 Val 类型不匹配,Lean 无法编译 | Nat 语境检测:轨迹长度与整数字面量的比较走原生 Nat 运算;不可译形状 → 注释占位 | + +另有防护加固:`lean_ident` 保留 `轨迹₀`/`h_前提`(定理 binder 撞名防御);emit 对重复定理 id 去重(`check --proof` 未跑时也不产出重复声明)。 + +### 审查时的业务级验证(/tmp/biz,电商大额订单审批流) + +- `审批.mq.md`(审批单 + 人工审核)+ `风控.mq.md`(风险分级)+ `lib/工单.mq.md`(建单):三条定理(大额必经人工 / 恰两步轨迹 / 必有回执)提取成功 +- 真实解释器三场景交叉验证:5000 元 → `auto`(1 步轨迹);20000/60000 元 → 人工建单 `T-20000`/`T-60000`(`需人工 → 创建` 恰两步)——与定理表逐条吻合 +- 负例:破坏定理表(未知符号 + 重复 id + 谓词元数错)→ `check --proof` 各报一码且默认关静默;emit 仍 advisory 可用;双次 emit 字节一致 + +### Lean 环境实装与真机证明(2026-11-16,Lean 4.35.0 / lake 5.0.0) + +工具链:`lean-4.35.0-linux.tar.zst` 解包至 `target/toolchain/lean-4.35.0-linux/`(无 elan, +直接 PATH);语义底座 `MarqdoProof`(`Val` + `mq*` 辅助 + 矛盾引理,无 `axiom`/`opaque`) +经 lake 构建于 `target/proof/skill-proof/`(库源同步在 `doc/verification/skill-proof/`, +发布时装入 `verification/skill-proof/`——checkout 中该目录属 root)。 + +实测发现并修正的发射器缺陷(均有测试覆盖): + +| 缺陷 | Lean 行为 | 修复 | +|---|---|---| +| `namespace Generated.审批_mq` | `namespace` 命令只接受 ASCII 名(`namespace 审批` 直接语法错误) | 非 ASCII 字符确定性编码 `uXXXX`:`Generated.u5BA1u6279_mq` | +| 裸中文标识符 `def 审批单`、`(h_前提 : …)`、`v_结果` | Lean 标识符仅 ASCII,全部语法错误 | 非 ASCII 一律 guillemet `«…»`;改名形式走同一编码(`v_u7ED3u679C`) | +| Op 构造器 `«调用:人工审核»` | guillemet 记号内 `:` 截断记号 | 标识符内 `:` → `_`;`Op.name` 字符串显示保持原 id | +| 多参构造器模式 `.«调用:x» =>` | 模式未绑定实参,类型不匹配 | `Op.name` 臂补 `_ _` | +| 占位构造器裸中文 `无操作` | 语法错误 | 占位构造器也走 `op_ctor` | +| `h_run : … = (结果, 轨迹)` 反向等式 | simp_all 不做反向替换,输出值进不了目标 | 定理陈述翻转:`((结果, 轨迹) = run env [] …)` | +| 分支互斥假设(`mqGt=true ∧ mqLe=true`) | simp_all 不链式应用蕴含引理 | 库中矛盾引理 + 脚本显式 `.elim`(`exact (mqGt_mqLe_false ‹…› ‹…›).elim`) | +| 无分支函数上 `split at h_run` | 硬报错(无 if/match 可拆),挡住本可证明的平凡断言 | `try split at h_run` | + +驱动脚本 `target/proof/run-lean-check.sh`(P1 第 2 周 `--require-lean` 集成雏形): +prove 生成 → `lake env lean` → `proved / unproved / lean-error` 三态分类。 + +真机证明结果: + +| 目标 | 结果 | +|---|---| +| 业务样例 `审批.mq.md`(3 定理:大额必经人工 / 恰两步轨迹 / 必有回执) | `lake env lean` 0 error,全部 **proved** | +| 6 个带定理的测试夹具 + 业务样例 | **7/7 全部 proved**(`p2_len` 夹具的断言已修正:纯函数轨迹恒空,`长度(轨迹) = 2` 是作者笔误,改为 `长度(轨迹) = 0`——Nat 比较路径覆盖不变) | +| 全量 Rust 测试 | 499 通过;仅剩 2 个已记录的环境受限失败(python3 缺失 / playwright root 属主),与 prove 改动无关 | + +诚实性核对(首轮实测发现后修正):`p2_len` 曾因断言写错(纯函数却断言两步轨迹) +被 Lean 如实拒绝——生成侧把语义为假的断言原样交给 Lean、判定侧不虚报 proved, +正是"绝不 lean 无法证明的 marqdo 可以证明"的落实;修复方向是改对断言,不是放宽判定。 + +生成文件头部带 `set_option linter.unusedVariables false` / +`set_option linter.unusedSimpArgs false`:机器生成产物不应被人写代码的 linter +刷屏( simp 参数是固定词汇表,个别文件用不到属正常)。 + +### P1 Lean 判定落地(2026-11-17,commit 见 git log) + +新增 `src/prove/driver.rs` + `src/prove/cache.rs`,判定接进 `prove` 默认动作: + +| 组件 | 实现 | 与设计的偏差 | +|---|---|---| +| 工具链发现(§8.4) | `--lean` → `MARQDO_PROOF_LEAN` → `PATH`;显式给路径但不可执行 → `error[proof.lean_missing]` **不回退**;都找不到 → 状态保持 `unverified`(`--require-lean` 时退 2) | 一致 | +| 底座构建 | `MarqdoProof.lean` **内嵌**进 marqdo 二进制(`include_str!`),按内容 sha256 前 8 位落盘缓存,`lean -o MarqdoProof.olean` 直接构建 + `LEAN_PATH` 指给被检模块 | **不经 lake**:运行时只依赖 `lean` 一个二进制(无 elan/lake 也判定);lakefile 保留给人/CI 用。`scripts/check-proof-library.sh` 校验内嵌源与 `doc/verification/skill-proof/` 逐字节一致并输出库 sha256 | +| 判定调用 | `lean <模块>` + 超时(默认 120s,`--timeout`;try_wait 轮询,超时杀进程判 `error`);`--heartbeats` 透传 `-DmaxHeartbeats` | 一致 | +| 结果解析 | `unsolved goals` → `unproved`;其它 `error` → `error`;干净编译 → `proved`;`sorry`(策略 `none`)→ `unverified` | 一致(§4.4 E4) | +| 证据映射 | 生成文件 `-- mq: LINE:COL` + 定理头 `-- 定理 (策略 …;mq: N)` → 证书 `span_map`;unproved 定理的诊断指回定理表行,附 Lean 原始目标上下文 | 一致(§8.5) | +| 证书缓存(§8.3) | 键 = sha256(源码 ⊕ plan ⊕ 库 sha256 ⊕ lean 版本 ⊕ marqdo 版本);命中 → 跳过判定,`lean.cache: "hit"`;`--no-cache` / `MARQDO_PROOF_NO_CACHE` 绕过 | plan.json schema 即结构化 plan(无独立 schema 文件) | +| 状态/退出码(§3.3) | E1 假定理 unproved 退 1;F2 `--report-only` 恒 0 不判定;F3 `--require-lean` 无工具链退 2;`prove emit` 子命令只生成不判定 | 一致 | + +**实测抓出的判定层缺陷**(均有回归测试,tests/prove_lean.rs + driver 单元测试): + +| 缺陷 | 后果 | 修复 | +|---|---|---| +| 错误头 `:47:62: error` 解析取了**列号** 62 | unsolved 目标错配到下一个定理(相邻 61–76 区间),甲定理的失败记到乙定理头上 | 取倒数第二个数字段为行号 | +| 干净编译时 driver 不产出逐定理记录 | 所有定理停留在 `unverified`,证书 `claims: []` | 无错定理一律补 `proved`(或 sorry → `unverified`) | +| 函数全名含点(`台账.记录.记过即记`)按第一个点切分 | claim id 拼错(`记录.记过即记`),匹配不上报告 | 从定理头注释直接取 claim id,函数名 = 定理名剥掉 claim 后缀 | +| 无定理函数把文件状态拖成 unverified | 没有义务的函数(纯编排胶水)使整体永远到不了 proved | 文件状态只聚合**有定理**与**被拒绝**的函数;无定理函数自身行仍如实 `unverified` | +| 测试夹具 `长度(轨迹) = 0` 断言写错(函数体有一次调用) | Lean 如实拒绝——生成侧诚实、判定侧不虚报 | 修正夹具断言为 `= 1`(不是放宽判定) | + +测试矩阵(`tests/prove_lean.rs`,独立测试目标,`required-features = ["cli"]`): +A1 真定理 proved · E1 假定理 unproved 退 1 · E4 策略 none → unverified 退 0 · +F2 report-only 恒 0 · F3 require-lean 无工具链退 2 · F4 emit 子命令不判定 · +G1 假 lean 计数器证"命中跳判定"(含 `--no-cache` 复判) · G2 真证书命中 · +G2b `--no-cache` 强制 miss。无工具链时自动 SKIP,`MARQDO_PROOF_REQUIRE_LEAN=1` +(CI)则缺失即失败。 + +CI:`.github/workflows/proof.yml` —— 装 Lean 4.35.0 → 底座校验 → +`MARQDO_PROOF_REQUIRE_LEAN=1` 跑判定矩阵(CI 不许静默降级)→ prove 主套件。 + +### P2 离线判定落地(2026-11-17) + +新增 `src/prove/offline.rs`(片段 F1–F5 的符号执行)+ `tests/prove_corpus.rs` +(40 夹具单调性语料库): + +| 组件 | 实现 | +|---|---| +| 符号执行(§5.3) | 状态 `Var → SymVal`(Const/Struct/OpResult/Param/Unknown);If 逐分支克隆状态并**接续 If 之后的语句**(Return 常在外层);每个 Return 收集 (路径条件, 结果, 轨迹, 变量快照) | +| 可行性 | 前提区间 ∩ 路径条件为空 → 路径不可行,空真关闭(Lean 侧对应假设矛盾,simp 可消) | +| F2 轨迹 | 包含/长度逐路径求值(Op.name 显示名与 Lean 一致) | +| F3 字面 | `result.ok/error/value_or` 结构求值(与 mqResultOk/mqError/mqValueOr 语义一致) | +| F4 自由原子 | 外部返回值布尔判定只二分;路径条件里出现同键原子才可关闭(hypothesis);反例路径含自由原子 → 保守放弃见证 | +| F5 区间 | **收紧后的诚实范围**:字面重述(同原子)→ hypothesis 关闭;区间违反 → 确定性否定 + 区间端点见证(反例);区间**蕴含**(10000 ⊢ 9999)数学上真,但当前 Lean 脚本无 Val 比较传递引理,simp+omega 关不掉——离线同样保守 unverified(等库补引理再放开),否则必触发 divergence | +| 状态 | 离线 closed → `checked`(decided_by=trace,**不是 proved**);反例 → `unproved` + `proof.claim_failed` 诊断(指回定理表行 + 见证如 `金额 = 10001`) | +| 单调性护栏(§5.4) | 有 Lean 时逐定理复核:离线 checked 但 Lean unproved,或离线反例被 Lean 证出 → `error[proof.divergence]` 退 1,永不落绿;`MARQDO_PROOF_INJECT_DIVERGENCE=1` 测试注入验证护栏咬人 | +| 语料库 | `tests/prove/fixtures/` 8 类 × 5 = 40 夹具(literal/trace/interval/free-bool/branches/composition/counterexample/beyond);`corpus_monotonicity_offline_subset_of_lean` 强制 offline ⊆ lean;`corpus_offline_never_claims_proved` 无 Lean 时禁 proved | + +**实测抓出并修复的缺陷**(均有测试): + +| 缺陷 | 修复 | +|---|---| +| If 分支后丢弃剩余步骤(Return 在 If 外层的常见编排全部丢结果) | 两支克隆状态并接续后续语句 | +| `negated` 字段与 op 翻转双重否定,取反原子被收集函数丢弃 | 移除字段,否定一律折进 op/expected | +| 嵌套分支(else 里再嵌 if)Lean 只拆一层 | `try split at h_run` 按最大 if 深度重复发射 | +| simp 清单缺 `mqResultError`/`mqValueOr`/`mqAnd/mqOr/mqNot` | 全部补入(l2/l5/f1 由分歧护栏暴露) | + +**已记录的文法限制**:分支条件尚不支持字段访问(`access(审核, "ok")` 作条件 +解析失败)——F4 的"路径条件含自由原子"场景目前由单元测试覆盖,语料库中以 +分支后的结构化结论代替;文法放开后 prove 侧无需改动(offline.cond_atom 已支持)。 + +### P3 组合与产品化(2026-11-17) + +| 任务 | 状态 | 实现 | +|---|---|---| +| `--all` 目录模式 + `--max-files` | ✅ | 递归收集(跳过 target/dist/node_modules/.git/.marqdo,上限 200);目录不带 --all → 拒绝;聚合 JSON `{"kind":"prove-all","status":…,"files":[…]}`;整体状态差者胜(A6 测试:假 lean 分歧在目录模式同样触发护栏、整体退 1) | +| 差分一致性 T4(B 组) | ✅ | `tests/conformance.rs`:5 个纯函数语料(算术/中文标识符/分支比较/字符串拼接/i64 边界)解释器求值 == Lean `example … = Val.… := by simp`;B4 result.ok 结构字段读取两侧一致。B2(除零/模零)保持已记录偏差:解释器为运行时错误,P1 库模型返回 `.int 0`(MarqdoProof.lean 注释) | +| 调试注入 `--fault-inject offline-claim` | ✅ | 等价于 `MARQDO_PROOF_INJECT_DIVERGENCE=1`(A3 分歧护栏验证入口) | +| 跨函数组合 | 部分 | 同模块直线纯函数**内联**(≤24 语句、无分支、effect=pure)已落地;跨模块调用=不透明操作(效应未知,护栏兜底);**assume-guarantee 后置条件复用 → 2.9**(依赖假设表 T3) | +| `foreach` | 延期 | 维持 `proof.foreach_pending` 拒绝;有限列表 fold 编码需要库级归纳引理,冒进会先于 Lean 关闭路径、破坏单调性护栏可信度(§12.4) | +| 文档 | ✅ | 教程 §13.8(prove 章节)、skills/marqdo/reference.md(定理表)、本设计文档状态行、roadmap 落地记录;README/CHANGELOG/doc/releases 因仓库权限(root 属主)待人工合入,内容已在 §12.5 | + +#### §12.4 延期理由(2.9) + +1. **foreach**:可证子集刻意无循环(返回路径有限性是反例枚举与 Lean 分支 + 拆解的共同根基)。fold 编码需 `List.length` 归纳引理入 MarqdoProof.lean, + 且离线判定器需要"有限列表"的证据语法——两件事都没有通过 40 夹具语料库 + 的单调性验证,不该在发布版里冒险。 +2. **跨模块 assume-guarantee**:需要假设表(T3)承载被调者后置条件,并把 + 假设作为 `hypothesis` 关闭理由暴露给证书。当前跨模块调用是不透明操作, + 诚实且护栏可兜底;半吊子假设复用会制造"看起来证了其实靠假设"的绿灯。 +3. **分支条件字段访问**(`access(审核, "ok")` 作条件):解析器文法限制, + prove 侧已就绪(offline cond_atom 支持任意键),放开即生效。 + +#### §12.5 待仓库权限合入的内容(已于 2026-11-18 合入) + +`CHANGELOG.md`(v2.8.0 条目)、`README.md`(版本行 + 愿景第 6 条)、 +`doc/releases/v2.8.0.md`(双语发版说明)、`skills/marqdo-dev/index.mq.md` +(`prove` 任务)——权限放开后已全部合入原文,见各自文件。 diff --git a/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md b/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md old mode 100644 new mode 100755 diff --git a/doc/design/return-hr-and-code-surface.md b/doc/design/return-hr-and-code-surface.md old mode 100644 new mode 100755 diff --git a/doc/design/spaced-function-names-d8.md b/doc/design/spaced-function-names-d8.md old mode 100644 new mode 100755 diff --git a/doc/design/staleness-providers.md b/doc/design/staleness-providers.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-csv.md b/doc/design/stdlib-csv.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-datetime.md b/doc/design/stdlib-datetime.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-encoding.md b/doc/design/stdlib-encoding.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-foreign.md b/doc/design/stdlib-foreign.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-fs-mid.md b/doc/design/stdlib-fs-mid.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-fs-mid2.md b/doc/design/stdlib-fs-mid2.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-handbook.md b/doc/design/stdlib-handbook.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-hash.md b/doc/design/stdlib-hash.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-html.md b/doc/design/stdlib-html.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-i18n.md b/doc/design/stdlib-i18n.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-list-cli.md b/doc/design/stdlib-list-cli.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-log-uuid.md b/doc/design/stdlib-log-uuid.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-math.md b/doc/design/stdlib-math.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-mid.md b/doc/design/stdlib-mid.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-mid2.md b/doc/design/stdlib-mid2.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-path.md b/doc/design/stdlib-path.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-re.md b/doc/design/stdlib-re.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-secrets.md b/doc/design/stdlib-secrets.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-stats-log.md b/doc/design/stdlib-stats-log.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-subtask.md b/doc/design/stdlib-subtask.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-table.md b/doc/design/stdlib-table.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-text-mid.md b/doc/design/stdlib-text-mid.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-toml.md b/doc/design/stdlib-toml.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-url.md b/doc/design/stdlib-url.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib-writeback.md b/doc/design/stdlib-writeback.md old mode 100644 new mode 100755 diff --git a/doc/design/stdlib.md b/doc/design/stdlib.md old mode 100644 new mode 100755 diff --git a/doc/design/t1-session-staleness.md b/doc/design/t1-session-staleness.md old mode 100644 new mode 100755 diff --git a/doc/design/table-cell-expressions.md b/doc/design/table-cell-expressions.md old mode 100644 new mode 100755 diff --git a/doc/design/tech-stack.md b/doc/design/tech-stack.md old mode 100644 new mode 100755 diff --git a/doc/design/ubuntu-ppa.md b/doc/design/ubuntu-ppa.md old mode 100644 new mode 100755 diff --git a/doc/design/user-site.md b/doc/design/user-site.md old mode 100644 new mode 100755 diff --git a/doc/design/v-safe-json.md b/doc/design/v-safe-json.md old mode 100644 new mode 100755 diff --git a/doc/design/view-debug.md b/doc/design/view-debug.md old mode 100644 new mode 100755 diff --git a/doc/design/view-document-annotations.md b/doc/design/view-document-annotations.md old mode 100644 new mode 100755 diff --git a/doc/design/view-execution-trace.md b/doc/design/view-execution-trace.md old mode 100644 new mode 100755 diff --git a/doc/design/view-frame-selection.md b/doc/design/view-frame-selection.md old mode 100644 new mode 100755 diff --git a/doc/design/view-knowledge-reading-experience-2026-10-24.md b/doc/design/view-knowledge-reading-experience-2026-10-24.md old mode 100644 new mode 100755 diff --git a/doc/design/view-markup-surface.md b/doc/design/view-markup-surface.md old mode 100644 new mode 100755 diff --git a/doc/design/view-prose-annot-gaps.md b/doc/design/view-prose-annot-gaps.md old mode 100644 new mode 100755 diff --git a/doc/design/view-readable-actions.md b/doc/design/view-readable-actions.md old mode 100644 new mode 100755 diff --git a/doc/design/view-reader-botanical.md b/doc/design/view-reader-botanical.md old mode 100644 new mode 100755 diff --git a/doc/design/view-static-interactive.md b/doc/design/view-static-interactive.md old mode 100644 new mode 100755 diff --git a/doc/design/view.md b/doc/design/view.md old mode 100644 new mode 100755 diff --git a/doc/design/vscode-extension-commit.md b/doc/design/vscode-extension-commit.md old mode 100644 new mode 100755 diff --git a/doc/design/vscode-extension.md b/doc/design/vscode-extension.md old mode 100644 new mode 100755 diff --git a/doc/design/warning-fatigue-control.md b/doc/design/warning-fatigue-control.md old mode 100644 new mode 100755 diff --git a/doc/design/web-asgi-servers-and-marqdo.md b/doc/design/web-asgi-servers-and-marqdo.md old mode 100644 new mode 100755 diff --git a/doc/design/web-assets-and-images.md b/doc/design/web-assets-and-images.md old mode 100644 new mode 100755 diff --git a/doc/design/web-invoke-serialization.md b/doc/design/web-invoke-serialization.md old mode 100644 new mode 100755 diff --git a/doc/design/web-net-capabilities.md b/doc/design/web-net-capabilities.md old mode 100644 new mode 100755 diff --git a/doc/design/web-view-resources.md b/doc/design/web-view-resources.md old mode 100644 new mode 100755 diff --git a/doc/dev-setup.md b/doc/dev-setup.md old mode 100644 new mode 100755 diff --git a/doc/library-development.mq.md b/doc/library-development.mq.md old mode 100644 new mode 100755 diff --git a/doc/next/001.md b/doc/next/001.md old mode 100644 new mode 100755 diff --git a/doc/next/002.md b/doc/next/002.md old mode 100644 new mode 100755 diff --git a/doc/next/003.md b/doc/next/003.md old mode 100644 new mode 100755 diff --git a/doc/next/004.md b/doc/next/004.md old mode 100644 new mode 100755 diff --git a/doc/next/005.md b/doc/next/005.md old mode 100644 new mode 100755 diff --git a/doc/next/006.md b/doc/next/006.md old mode 100644 new mode 100755 diff --git a/doc/next/007.md b/doc/next/007.md old mode 100644 new mode 100755 diff --git a/doc/next/008.md b/doc/next/008.md old mode 100644 new mode 100755 diff --git a/doc/next/009.md b/doc/next/009.md old mode 100644 new mode 100755 diff --git a/doc/next/010.md b/doc/next/010.md old mode 100644 new mode 100755 diff --git a/doc/next/011.md b/doc/next/011.md old mode 100644 new mode 100755 diff --git a/doc/next/012.md b/doc/next/012.md old mode 100644 new mode 100755 diff --git a/doc/next/013.md b/doc/next/013.md new file mode 100755 index 0000000..c17a3db --- /dev/null +++ b/doc/next/013.md @@ -0,0 +1,702 @@ +我实际开发了一下,觉得借助外部框架反而会拖累marqdo的特性发挥,应该将marqdo的智能体框架优化一下,方便实际的开发工作。我觉得重点在于以下几个方面: +上下文操作,允许用户方便的进行用户输入和marqdo文件级、类级、函数级的提示词拼接和注入。 +能够等待模型输入进行便捷的模型控制执行流 +能够控制模型开启并发操作,进行多智能体并发执行 +能够便捷的解析模型的输出,对于不是很稳定的模型也能实现交互 +易于拓展 + +我认为这次应该对 Marqdo 的智能体框架进行一次**面向文档原生执行的架构升级**,而不是继续给 qdagent 增加包装层。 + +结合你此前对小模型、极短 SKILL 和递归调用的要求,我认为新的设计目标应该是: + +> **Marqdo 文档负责描述任务,模型负责作出选择,Marqdo Runtime 负责控制执行。** +> +> 模型不必理解整个智能体框架,只需要完成当前函数要求的一个小决策。 + +这与传统 Agent Framework 的区别在于:我们不应让模型不断生成复杂的工具调用协议,也不应要求它理解隐藏的框架状态机。它只需要返回简短结果,后续的判断、等待、路由、并发以及恢复都可以交给 Marqdo。 + +## **一、从现有代码看,真正缺少的是什么** + +我查看了目前 `marqdo/main` 的 `ext/ai/agent.mq.md`、`ext/ai/llm.mq.md`、`lib/subtask.mq.md`,以及相关设计文件。 + +Marqdo 并不是缺少智能体基础设施,而是**已有能力尚未形成面向普通 Marqdo 作者的简洁统一接口**。 + +| 目标能力 | 当前基础 | 需要补充 | +| ------- | ------------------------------------------------- | ------------------- | +| 上下文操作 | `build_step_context`、`ContextPackV2`、`llm.prompt` | 文件/类/函数级的精确提取和组合 | +| 模型控制执行流 | `agent.step`、`model_turn`、`resume` | 简短模型结果驱动的条件分支、等待和恢复 | +| 多智能体并发 | `subtask.spawn`、`wait`、`run_many` | 模型任务级的派发、并发配额、结果汇合 | +| 不稳定输出解析 | `LLMResult`、`CALL:`/`DECISION:` 解析 | 枚举选择、宽容解析、类型验证和有限修复 | +| 易于扩展 | `.mq.md` 函数、插件、MCP、SKILL 编译 | 一套简单、稳定的开发者门面 | + +尤其值得注意的是,当前 `ext/ai/agent.mq.md` 已经增长为约 256 KB 的大型文件,包含大量内部编排函数。这不意味着它一定会被完整送入模型,但说明开发接口和内部机制已经有明显的分离价值。 + +我建议此次重构的原则是: + +**不新增第二种编程语言,不重写 Agent Runtime,不破坏现有 SKILL。只给 Marqdo 增加几个真正必要、可以自然组合的智能体操作。** + +## **二、我建议提供的五项原生能力** + +### **1. 上下文:让函数所在的文档自动成为提示词** + +这是我认为最有 Marqdo 特色、也最应该优先实现的部分。 + +当前已有 `source_brief` 和 `skill_brief`,但开发者仍需要理解智能体的上下文组装机制。我希望把它进一步转化为**编译器可寻址的上下文投影**。 + +**当前用户输入** + +始终保留本轮最新消息 + +文件级 + +全局职责 + +类级 + +当前领域 + +函数级 + +当前动作 + +**ContextPack** + +按需拼接、去重、裁剪,然后交给模型 + +建议默认只注入当前函数和必要的祖先说明,不注入全部兄弟函数。 + +| 范围 | 读取内容 | 典型用途 | +| ---------- | ----------------- | -------- | +| `file` | 文件级说明、约束与能力概述 | 根 SKILL | +| `class` | 当前 `#` 类的说明和继承的约束 | 子领域 | +| `function` | 当前 `##` 函数的说明与契约 | 单次模型决策 | +| `full` | 指定范围的完整源码 | 显式请求深入理解 | + +这里必须使用 Marqdo 的 AST、模块身份和函数作用域来提取内容,不能简单用正则截取标题。 + +进一步建议增加一个可直接调用的 `ai.context`,支持 `scope="function"` 等选择,并允许 `user=` 提供显式输入。普通交互可以从当前调用会话获取最新用户消息;独立的 `marqdo call` 则能够明确传入该消息,便于复现和单元测试。 + +**一个重要细节:文档片段是提示上下文,不代表执行这些片段。** `import` 也不应默认把依赖模块的完整内容注入模型。 + +### **2. 等待模型:让模型返回值直接控制 Marqdo 分支** + +现阶段 Marqdo 已经支持条件分支,真正需要的是一个足够简单、能够阻塞等待模型结果的函数。 + +例如拟增加: + +`ai.choose(options=...)` + +模型只需要从提供的选项中选择一个,Marqdo 负责等待结果、解析结果、验证选项,然后把结果交给原有分支语句。 + +在此基础上保留: + +| 接口(拟议) | 职责 | +| ----------- | ---------------- | +| `ai.ask` | 等待模型生成文本或指定类型的结果 | +| `ai.choose` | 等待模型从给定选项中选择 | +| `ai.start` | 发起非阻塞模型任务 | +| `ai.wait` | 等待任务完成并获取结果 | + +`ask` 和 `choose` 默认是同步的。只有真正需要同时处理多个任务时,作者才使用 `start` 和 `wait`。 + +这意味着控制流无需新增 `if AI`、`await AI` 等语言关键字,也不必为了执行一步模型决策创建完整的工作簿。 + +对于需要用户回答的场景,还应区分 `waiting_model` 和 `waiting_user`。后者必须能持久化当前执行位置,并由会话输入恢复,不能在函数内部长期阻塞一个模型或 HTTP 请求。 + +### **3. 并发:直接并发执行 **`.mq.md`**,而不是另造 Agent 类型** + +当前 `lib/subtask` 的实现已经相当接近目标。 + +它支持创建子任务、等待、轮询,以及 `run_many` 的受限并发执行。因此不需要再做一套独立的 Multi-Agent Framework。 + +我建议新增薄封装: + +`ai.parallel(tasks=..., limit=2)` + +其中每个任务都引用一个实际存在的 `.mq.md` 文件、可调用函数和输入。 + +**父 Marqdo 函数** + +子 SKILL A + +资料检索 + +子 SKILL B + +方案评估 + +子 SKILL C + +风险分析 + +**结果汇合** + +父函数获取三个独立返回值 + +每个子任务是独立的执行上下文,不继承父模型完整历史,只接收明确传入的任务、允许使用的能力与必要文档。 + +还需要统一限制并发数、模型请求配额、超时与取消。尤其在单张 GPU 上运行多个小模型任务时,任务并发不意味着推理一定能并行;Runtime 应允许共享模型服务进行排队,而不是为每个子智能体重复加载模型权重。 + +### **4. 输出解析:优先理解短文本,不强迫小模型生成复杂 JSON** + +这项能力对小模型尤其重要。 + +例如,模型本来只需要回答 `chat`,但实际可能生成以下任意一种结果: + +chat + +chat + +我选择 chat + +chat + +选择:chat,因为用户希望对话 + +chat + +\`\`\`text\ +chat\ +\`\`\` + +chat + +这些结果都可以被确定性地规范化为相同选项;无需再调用一个模型来解释前一个模型。 + +我建议采用递进式解析: + +| 层级 | 行为 | +| ---- | ------------------------ | +| 精确 | 完整匹配合法选项 | +| 规范化 | 处理空白、代码围栏、常见选择前缀 | +| 受限提取 | 从明确的选择字段中提取唯一合法选项 | +| 有界修复 | 无法确定时,只让模型重新输出选项标识 | +| 失败返回 | 仍不确定、多个选项冲突时返回 `invalid` | + +**不能为了追求成功率而随意猜测。** 模型同时提到 `chat` 和 `office`,不意味着可以选择其中第一个。工具执行、文件写入等高风险动作更不能依赖模糊匹配。 + +可以支持模型服务的 constrained decoding,但不应强制所有小模型使用复杂 JSON Schema。2026 年针对小模型的结构化输出研究也指出,格式合法性提高不一定意味着语义决策更正确。 + +[image](https://www.google.com/s2/favicons?domain=https://ijcai.org\&sz=32) + +ijcai.org+1 + + + +### **5. 扩展:把能力沉到 Marqdo 库,而不是产品框架** + +建议新增的接口仍保持 Marqdo 的现有组织习惯: + +``` +ext/ai/ + index.mq.md # 简短导航 + flow.mq.md # 模型控制流 + context.mq.md # 文档上下文 + parse.mq.md # 模型结果解析 + parallel.mq.md # 智能体并发 + agent.mq.md # 现有高级编排,保留兼容 + llm.mq.md # 现有模型抽象 +``` + +这些是拟议的新文件划分,不代表当前仓库已经实现。 + +每份 `.mq.md` 自身仍是一份可以阅读的 SKILL,公开 `##` 函数即工具,不需要再维护独立的 Tool Schema。真正需要操作系统、异步调度或模型推理后端的部分,复用 Rust Runtime 与现有插件。 + +特别是 `flow.mq.md`,我建议它成为日常智能体开发的**极薄门面**,而不是把现有大型 `agent.mq.md` 再复制一遍。 + +## **三、理想中的开发体验:两个函数就能完成根 SKILL** + +这是最重要的验收标准:**经过框架升级,原先的 qdagent 根入口不应该变复杂,反而应该更短。** + +下面展示我希望实现的最终作者体验。注意,这是**拟议的新接口示例**,当前 Marqdo 2.7.1 还不能直接运行这些新函数。 + +``` + +--- +markup: occlusion +title: 求道智能体入口 +import: + ai: ext/ai/flow.mq.md +--- + +# main + +你是求道智能体。 + +每次收到非空用户输入,先提供简短选项, +等待用户确认,再进入对应的 SKILL。 +这里只负责意图确认和路由,不执行具体任务。 + +## 分解意图 + +根据`用户输入`生成两个简短方向, +每个方向说明好处和代价。 + +**选项 = [让模型生成意图选项](ai.ask(input=`用户输入`, output="options", count=2))** + +**确认 = [展示选项并等待用户回复](ai.input(options=`选项`))** + +返回*确认*。 + +## 路由函数 + +根据确认后的`用户意图`选择下一层 SKILL。 + +**目标 = [让模型选择已有的技能](ai.choose(input=`用户意图`, options=["chat", "office"]))** + +返回*[进入对应的 SKILL](ai.enter(skill=`目标`))*。 + +``` + +这份入口只保留两个业务函数。运行时自动提供函数级上下文,模型不需要认识 `ai.input` 的暂停实现,也不需要理解 `ai.enter` 的模块加载机制。 + +其中 `ai.input` 应该由 Marqdo Runtime 原生支持持久化暂停:展示选项后释放执行资源,收到用户回复时从原执行位置恢复。qdagent 只需要实现用户消息和选项卡的传输、展示。 + +`ai.enter` 只能接受已登记的 SKILL 标识,运行时解析为实际文档,并校验权限与函数入口。不能直接执行模型任意返回的文件路径。 + +这样,真正复杂的东西存在于 Marqdo Runtime,而不是每份 SKILL 的正文中。 + +## **四、开发顺序:先做最小闭环,再扩展并发** + +我建议按下面的依赖顺序推进,避免一开始就大规模重构 `agent.mq.md`。 + +**P0 — 文档上下文与模型选择** + +在 `src/frontend` 的 AST/符号定位基础上,建立文档作用域提取;给 `ext/ai` 增加 `context`、`ask`、`choose` 的轻量接口。 + +验收:一个函数能够使用自己的说明与用户输入,完成一次模型选择,不依赖 `agent.plan`。 + +**P1 — 用户等待与跨 SKILL 续执行** + +在现有 Runtime checkpoint、会话和事件基础上增加可持久化的 `input`、`enter`。恢复时检查文档版本、用户回复和调用权限。 + +验收:qdagent 从意图选择卡暂停,用户回复后继续进入聊天 SKILL;服务中断后也可以安全恢复。 + +**P2 — 并发模型与多智能体** + +将 `subtask.run_many` 包装为可接收模型与 SKILL 任务的 `ai.parallel`,加入每个子任务独立上下文、模型选择、取消、超时和结果汇合。 + +验收:三个独立 SKILL 可以同时运行,父函数获得全部成功或失败结果,且不会重复提交有副作用的操作。 + +**P3 — 小模型可靠性与开发工具** + +整合输出解析、自动修复和轻量上下文预算;增加实际调用测试、trace 与 `marqdo view` 中的模型决策展示。 + +验收:测试格式正确率、真实意图命中率、工具执行正确率和 Token 消耗,而不是只检查输出是否符合 JSON 格式。 + +这里还有一个建议:先挑选约 100~200 条实际意图、路由、人格切换、函数调用用例,使用目标 1B 小模型测试,再与当前的 `agent.step` 方式比较。重点测量每次决策输入 Token、输出 Token、有效选择率、修复轮数和最终任务成功率。并发部分还要独立测量吞吐量、等待时延和取消后的资源回收。 + +## **五、这次升级最关键的架构决定** + +我不建议立即修改 Marqdo 的 19 个核心语法构造。现有的 `#`、`##`、`###`、GFM 表格、描述链接、返回值和条件分支,已经足够表达智能体编排。 + +真正值得修改的是 Marqdo 的**执行能力与开发体验**: + +| 层次 | 应承担的职责 | +| ------------------- | ------------------- | +| Marqdo Language | 函数、参数、分支、文档作用域 | +| Marqdo AI Extension | 上下文、模型推理、选择、解析 | +| Marqdo Runtime | 任务等待、恢复、并发、权限 | +| `.mq.md` SKILL | 当前任务的自然语言规则与少量可执行操作 | +| qdagent | 人格、交互界面、模型配置、用户数据 | + +这也直接呼应了 Marqdo 仓库中 [doc/next/012.md](https://github.com/cflmy/marqdo/blob/main/doc/next/012.md?utm_source=chatgpt.com) 提出的构想:*code as document, document as skill, skill is tools*。 + +我的核心建议是将此次升级首先锁定在 **“函数级上下文投影 + 等待模型选择 + 原生用户暂停恢复”** 这个最小闭环。 + +只要这三个能力完成,qdagent 的根 SKILL 就能够独立驱动一次真实的意图确认和递归路由。后续聊天、Office、代码开发、科研等 SKILL 都可以基于同样的简单函数组合构建。 + +**这次改进的价值不在于 Marqdo 能支持多少种 Agent,而在于让一个很小的模型,只阅读几十行文档、输出几个字,就能够可靠地控制一个复杂的可执行系统。** + +一个智能体框架很重要的一点是错误处理和恢复上面展示的内容看上去确实不错但是错误处理和恢复这些写的不够好,我希望达成的目标是减少错误,这依靠框架本身,但是一旦出现无法避免的错误,请你给出框架应该怎么应对这些问题 + +我认为,Marqdo 的智能体框架应该把**错误预防与自动恢复提升为 Runtime 的原生能力**,而不是依靠每份 SKILL 自己编写重试逻辑,更不能依靠大模型不断阅读错误日志、重新思考和重新执行。 + +对于你希望使用的 1B 左右小模型,这一点尤其重要。 + +我建议确立一个核心原则: + +> **能由编译器和运行时避免的错误,不交给模型;能由确定性程序恢复的错误,不重新调用模型;只有必须重新作出语义判断时,才让模型介入。** + +而且恢复必须满足三个条件: + +- **不重复做**:已经成功的步骤不得因为后续失败而无故重新执行。 +- **不丢失结果**:即使最终任务失败,也保留已经完成的工作与验证证据。 +- **不假装成功**:无法确定执行结果时,明确标记为未知,而不是猜测成功或失败。 + +## **一、Marqdo 现有基础与真正的问题** + +我重新检查了 [ext/ai/agent.mq.md](https://github.com/cflmy/marqdo/blob/main/ext/ai/agent.mq.md?utm_source=chatgpt.com)。当前代码已经具备相当一部分可靠性基础: + +| 现有能力 | 当前作用 | 仍需加强 | +| ----------------------------- | ---------- | ----------------------- | +| `error_make` | 构造结构化错误 | 统一所有 AI 调用与 SKILL 的错误出口 | +| `error_decide_retry` | 有界重试判断 | 自动选择具体恢复策略 | +| `resume_save/load` | 保存、恢复检查点 | 与函数执行位置、用户等待和子任务统一 | +| `effects_prepare/transition` | 记录副作用执行状态 | 在所有可能写入的操作前强制应用 | +| `effects_reconcile` | 对账不确定的执行结果 | 自动检测、恢复和阻断不安全的重复执行 | +| `subtask.spawn/wait/run_many` | 子任务和并发 | 失败隔离、部分成功与子任务恢复 | + +此外,源码已经提供 `checkpoint_v2` 选项,但 `resume_save` 的默认值还是 `False`。而 `run_tool` 在缺失原生 Agent 插件时存在能力较弱的兼容执行路径。 + +这些说明 Marqdo **不需要再造一个恢复框架**,但需要把分散的能力统一为可靠的默认执行语义,特别是消除容易绕过严格校验的路径。 + +### **我建议的总体执行模型** + +**Marqdo SKILL 函数调用** + +**执行前预检** + +类型 · 上下文 · 权限 · 预算 · 依赖版本 + +**受控执行** + +模型调用 / 普通函数 / 子 SKILL / 并发 + +**结果验证** + +格式、类型、业务条件、执行证据 + +**成功提交** + +记录结果并继续 + +**恢复控制器** + +分类、恢复或安全中止 + +这里的“恢复控制器”应是 Rust Runtime 的确定性机制,不是另一个依赖 LLM 的智能体。 + +它可以在必要时请求模型作出局部判断,但错误处理本身不能依赖模型是否足够聪明。 + +## **二、先预防:让错误尽可能无法进入执行阶段** + +对于 Marqdo,我建议设置四道防线,但全部由框架自动完成,不要求 SKILL 作者编写额外逻辑。 + +| 防线 | 框架自动完成 | 可以阻止的问题 | +| --- | --------------------- | -------------- | +| 编译前 | 检查函数签名、依赖、参数、类型 | 调用不存在的函数、参数错误 | +| 推理前 | 检查上下文范围、模型能力、Token 预算 | 上下文溢出、错误模型配置 | +| 执行前 | 校验模型输出、工具权限、资源版本 | 幻觉工具、非法路径、过期文件 | +| 提交前 | 验证返回值、操作结果和执行证据 | 错误结果被当作成功、重复写入 | + +这里有两个关键设计。 + +首先,**模型只产生候选值,不直接决定程序是否成功**。例如要求模型选择 `chat` 或 `office`,框架在验证之后才允许结果进入路由函数。模型说“已执行成功”,也不能代替真实的执行回执。 + +其次,**要把模型的不确定性限制在最小的函数范围内**。一次 `ai.choose` 只需要理解当前函数及两个选项,不应该携带整个 qdagent 的执行历史。上下文不够时读取相关内容,而不是无条件扩充系统提示词。 + +这种设计降低的是错误发生概率,不保证模型的语义判断必然正确。语义正确性仍需要任务相关的验证或用户确认。 + +## **三、错误发生后,框架必须先分类,再采取不同动作** + +我不建议把所有错误交给一个通用 `retry()`。 + +因为“模型选项格式错误”和“文件写入后进程崩溃”,虽然都叫失败,但适合的处理方式完全不同。 + +下面是我建议的默认恢复策略。 + +| 错误情况 | 框架应该怎么做 | 是否重新调用模型 | +| -------------- | ------------------- | -------- | +| 模型输出格式不正确 | 规范化、匹配合法值,必要时要求重新输出 | 最多一次 | +| 模型选择不在选项内 | 拒绝非法值,重新请求明确选择 | 必要时一次 | +| 上下文超过限制 | 删除冗余、提取相关函数、重新计算预算 | 通常不需要 | +| 模型请求超时、429 | 检查超时与限流,退避后重试 | 可以 | +| 模型返回错误事实 | 通过验证器识别问题,提供局部修正依据 | 可能需要 | +| Marqdo 函数参数错误 | 根据已知契约检查并修正可确定的问题 | 通常不需要 | +| SKILL 文件或函数不存在 | 重新解析注册目录;不存在则终止 | 不应盲目重试 | +| 权限不足、凭证失效 | 保存现场,要求用户或管理员处理 | 不需要 | +| 文件版本冲突 | 重新读取最新版本,重新计算变更 | 可能需要 | +| 子智能体执行失败 | 保留其他成功结果,仅处理失败子任务 | 视情况 | +| 写入结果不确定 | 查询外部结果和效应账本,不得直接重做 | 不应重新决策 | +| 运行时崩溃 | 恢复检查点,检查未完成操作后继续 | 通常不需要 | + +默认恢复应该有预算,例如传输请求总共最多三次尝试、输出修复一次、代码局部修复一至两次。这些属于初始策略参数,不应该变成语言硬编码的限制。 + +同时必须识别**重复失败循环**:如果同一个输入、同一个错误、同一个版本连续失败两次,且没有新证据,自动终止该恢复路径,避免小模型陷入无限生成。 + +### **恢复策略应当分层** + +**L0 · Runtime 自行修复** + +无需 LLM + +清理格式、重新获取连接、读取检查点、重建缓存、解析已知选项 + +**L1 · 确定性替代路径** + +已注册的备用工具、已有知识命中、只读降级、可验证的本地计算 + +**L2 · 小模型局部修复** + +只给模型失败字段、允许选项和必要证据,不再发送全部上下文 + +**L3 · 安全停止与交接** + +保存成功进度,报告错误、未决操作和能够安全继续的入口 + +L0 到 L2 只在恢复动作被验证为安全、且仍有预算时继续;不可逆写入、权限拒绝等错误可能直接进入 L3。不能把这套层级理解为所有错误都要逐层尝试。 + +**这是最适合小模型的重要改进之一:大部分错误不应该消耗额外的推理 Token。** + +## **四、真正困难的部分:如何做到失败后继续,而不是重新运行** + +这是我认为整个框架最值得投入研发资源的部分。 + +假设一份 Marqdo 文档依次完成: + +读取用户输入 + +已完成 + +分析与确认意图 + +已完成 + +进入 Office SKILL + +已完成 + +生成演示文稿 + +执行中断 + +交付结果 + +尚未执行 + +此时的正确恢复方式,不是重新运行 `# main`,更不是重新询问用户意图。 + +而是从“生成演示文稿”的可恢复边界继续执行,并复用之前的意图确认结果。 + +### **关键机制:函数级 Checkpoint + 执行日志** + +现有 CheckpointV2 已经提供良好的基础,但建议将它从 Agent 的可选机制进一步发展为**支持暂停的 Marqdo 执行会话的默认机制**。 + +每个可恢复边界记录这些信息: + +| 信息 | 作用 | +| ------------------ | ----------------- | +| `run_id / step_id` | 明确是哪次执行、哪一步 | +| 文档与函数 digest | 确保恢复的还是原始逻辑 | +| 参数、局部变量或结果引用 | 保留后续执行需要的数据 | +| 已完成步骤记录 | 跳过已经成功的操作 | +| 当前等待原因 | 等用户、等模型、等子任务或需要对账 | +| 副作用账本位置 | 判断写入是否发生 | +| 权限、资源版本和剩余预算 | 防止旧状态绕过新限制 | + +在实现上,我倾向**优先采用语句/函数边界的持久化续体(continuation)**,而不是一开始就尝试保存任意 Rust 调用栈。 + +如果当前解释器无法序列化整个运行帧,可以先从已提交的步骤边界恢复,再通过执行日志复用此前的结果。这要求可重放部分具有确定性,所有外部效应都由账本管理。 + +特别注意:`ai.input` 等待用户时,应提交暂停状态、释放执行资源。用户恢复时必须匹配原来的 `run_id`、输入请求 ID 和文档版本,不能把回复当作新的根任务重复执行。 + +类似的恢复问题在其他框架中也存在。例如 LangGraph 的部分中断机制会在恢复时重新执行节点,所以特别要求中断前的副作用具备幂等性。Marqdo 可以争取在语句/函数粒度提供更直观的恢复语义。 + +[image](https://www.google.com/s2/favicons?domain=https://github.com\&sz=32) + +GitHub+1 + + + +## **五、最不能出错的地方:副作用执行后崩溃** + +考虑这样一个场景: + +智能体调用“发送邮件”,邮件已经成功发出,但进程在收到确认结果之前崩溃。 + +如果框架简单重试,就可能把同一封邮件发送两次。 + +这个问题无法只靠模型解决。 + +我建议将 Marqdo 已有的 EffectLedger 变成所有带副作用工具的强制执行路径: + +`prepared` · 记录执行意图与幂等标识 + +`started` · 开始真实操作 + +**committed** + +有成功回执,允许复用结果 + +**unknown** + +先对账,不自动重做 + +其处理应当遵循: + +| 状态 | 恢复行为 | +| ------------------ | -------------------- | +| `prepared` | 尚未开始真实效应且有可信证据时,可以开始 | +| `started` | 如果执行中断,先调查,不能推断未生效 | +| `committed` | 直接复用已保存的成功结果 | +| `failed_no_effect` | 确认无效应后,才根据策略决定重试 | +| `unknown` | 查询外部资源、回执、版本;无法确认就阻断 | +| `reconciled_*` | 使用对账后的事实决定是否继续 | + +对接外部工具时,应提供可选的 `reconcile` 查询能力。外部系统支持幂等键就使用稳定幂等键,不支持则尽可能使用状态查询与版本校验。 + +对于已执行的动作,如果存在业务上明确、安全的逆操作,可以进行补偿;但不能把补偿等同于数据库事务回滚。 + +这一点与 Temporal 的可靠任务设计原则一致:外部操作可能在完成后、记录结果前失去连接,所以必须单独处理幂等性和不确定状态。 + +[image](https://www.google.com/s2/favicons?domain=https://github.com\&sz=32) + +GitHub+1 + + + +**Marqdo 不能承诺所有外部操作都严格只执行一次;它应承诺绝不在结果未知时盲目重试不可逆操作。** + +## **六、多智能体错误:允许局部失败,不让整个任务雪崩** + +将来支持 `ai.parallel` 后,可能出现三个子智能体同时工作,其中一个失败。 + +我建议父智能体按照任务依赖与结果完整性决定下一步,而不是默认重新启动全部子任务。 + +| 子任务状态 | 父级处理 | +| ------ | ------------- | +| 成功 | 缓存结果和验证状态 | +| 暂时性错误 | 仅安全重试该子任务 | +| 无法恢复 | 标记失败并保留错误证据 | +| 需要用户输入 | 保存该分支的等待状态 | +| 已取消 | 不再自动重启 | +| 写入状态未知 | 阻断依赖这一写入的后续动作 | + +例如三个子 SKILL 分别负责资料检索、方案分析和风险评估。当资料检索失败时,已经完成的风险评估不应该无条件被抛弃。 + +如果任务要求三份结果必须齐全,父函数进入 `partial` 或 `blocked`;如果允许部分交付,则可以返回两份成功结果,但必须标注缺失项。 + +并发管理还要处理取消传播:父级取消时停止新任务,通知运行中的子任务,并等待它们清理;已经发生的外部副作用不能假定被撤销。 + +## **七、让恢复不破坏极短 SKILL 范式** + +你的根 SKILL 仍然只应有两个函数。 + +例如未来可以继续这样编写(下面的 `ai.choose` 是拟议接口): + +``` + +## 路由函数 + +根据`用户意图`选择下一层 SKILL。 + +**目标 = [选择合适的技能](ai.choose(input=`用户意图`, options=["chat", "office"]))** + +返回*目标*。 + +``` + +注意,这段函数完全没有重试逻辑、异常捕获或状态维护。 + +模型正常时,`ai.choose` 返回一个短字符串;框架校验成功后,`路由函数` 正常返回。 + +模型异常时,由 Runtime 根据错误类别处理。必要时暂停整个可恢复执行会话。对调用方暴露统一的执行结果,而不是要求模型理解复杂的恢复协议。 + +建议的结果结构可以简化为: + +``` + +{ + "status": "waiting_input", + "value": null, + "error": { + "code": "model.invalid_choice", + "stage": "路由函数" + }, + "resume_id": "run-42", + "recovery": "ask_user" +} + +``` + +这是运行时的结果信封,**不是让小模型生成的 JSON**。正常成功时作者仍然得到原本的 Marqdo 返回值。 + +状态建议至少区分 `succeeded`、`partial`、`waiting_input`、`blocked`、`uncertain`、`failed` 和 `cancelled`。 + +这里 `uncertain` 特别重要:它表示外部执行结果尚未确认,不能简单归类为失败。 + +如果错误被框架自动恢复,SKILL 不需要知道细节。只有恢复耗尽、需要外部输入,或者作者显式要求检查错误时,才将结构化诊断提供给上层。 + +同时保留原始错误、每次尝试、模型用量和恢复动作的执行记录,供 `marqdo view` 和 `debug` 检查。 + +## **八、具体应该修改哪些代码** + +我建议在现有能力上进行增量重构。 + +| 优先级 | 修改位置 | 主要工作 | +| --- | ------------------------------ | ------------------------------------------ | +| P0 | `plugins/agent/src/error.rs` | 建立统一错误分类、恢复动作和策略预算 | +| P0 | `plugins/agent/src/tools.rs` | 强制校验和授权,不允许插件缺失时静默降低安全保证 | +| P0 | `ext/ai/llm.mq.md` | 统一模型超时、格式错误与结果验证出口 | +| P1 | `plugins/agent/src/resume.rs` | 让 CheckpointV2 成为可恢复会话默认格式 | +| P1 | `src/runtime/` | 实现等待输入、步骤恢复、取消与恢复调度 | +| P1 | `plugins/agent/src/effects.rs` | 将效应账本强制接入受控写工具 | +| P2 | `lib/subtask.mq.md` | 增强子任务部分成功、取消和结果恢复 | +| P2 | `ext/ai/flow.mq.md`(新) | 提供简洁的 `ask/choose/input/enter/parallel` 门面 | + +我特别建议先检查 `error.rs` 中当前根据错误代码字符串推断类别的路径。作为兼容机制可以保留,但核心调用应该直接从 LLM Adapter、工具执行器、解释器获得结构化错误码,而不是靠字符串包含 `timeout`、`connect` 等词来识别。 + +另外,生产模式下不能让缺失原生 Agent 插件的情况退化成一个不具备同等效应和权限保证的执行路径。只读实验可以降级,涉及写入的生产调用必须显式拒绝。 + +### **最重要的验收测试** + +**可靠性验收清单** + +0/8 已确认 + +模型输出错误 + +只在允许范围内修复,不路由到错误 SKILL + +429 / 网络中断 + +有界退避,正确计算模型调用和成本 + +意图确认后崩溃 + +恢复后不再次询问同一轮意图 + +外部写入后崩溃 + +不重复执行,先查询真实效应 + +三个子智能体中一个失败 + +保留另外两个成功结果 + +SKILL 源码被修改 + +检测版本变化,不静默恢复旧步骤 + +权限被撤销 + +立即阻断,不利用旧检查点继续 + +恢复失败或预算耗尽 + +返回部分结果和可操作的失败信息 + +重置检查 + +这些测试应使用确定性假模型、假工具和故障注入完成,不能只依赖线上模型的偶然成功。特别要测试进程在每一个关键提交点前后崩溃的情况。 + +## **九、最终我希望 Marqdo 达到的标准** + +我认为这次优化的成功,不应该用“重试后最终完成的任务数量”来单独衡量。 + +还应该关注首次执行成功率、自动恢复成功率、恢复额外 Token、重复副作用次数、恢复时延和人工介入率。 + +其中最重要的是: + +**可自动避免的错误越来越少发生;发生错误时只重做必要的部分;无法安全恢复时保留全部可用成果,并明确告诉用户原因。** + +更进一步,我认为 Marqdo 可以把经过验证的失败恢复方案沉淀成可执行知识。比如某个 SKILL 遇到特定格式错误后成功使用了一个确定性修复函数,系统可以将这一规则作为候选知识,在验证和批准后复用。下次遇到相同情况,甚至不需要再次调用模型。 + +这将形成一个很有价值的闭环: + +**执行 → 错误 → 恢复 → 验证 → 知识沉淀 → 下次预防。** + +它与传统框架只强调容错重试的方向相比,更符合 Marqdo 的核心理念:文档不仅描述智能体该怎么做,还能逐渐沉淀成经过验证、可直接执行的处理能力。 + +我建议把这次框架升级的第一阶段明确收敛为 **“统一错误信封 + 自动恢复策略 + CheckpointV2 默认化 + 安全副作用账本”**。这四项比立即增加更多模型控制函数更优先,因为它们决定了后续所有简短 SKILL 能否真正可靠地运行。 \ No newline at end of file diff --git a/doc/next/Marqdo_Executable_Knowledge_Design.md b/doc/next/Marqdo_Executable_Knowledge_Design.md old mode 100644 new mode 100755 diff --git a/doc/next/Marqdo_Executable_Knowledge_Development.md b/doc/next/Marqdo_Executable_Knowledge_Development.md old mode 100644 new mode 100755 diff --git a/doc/next/Marqdo_Executable_Knowledge_Example.md b/doc/next/Marqdo_Executable_Knowledge_Example.md old mode 100644 new mode 100755 diff --git a/doc/next/Marqdo_Executable_Knowledge_Testing.md b/doc/next/Marqdo_Executable_Knowledge_Testing.md old mode 100644 new mode 100755 diff --git a/doc/releases/v2.7.0.md b/doc/releases/v2.7.0.md old mode 100644 new mode 100755 diff --git a/doc/releases/v2.7.1.md b/doc/releases/v2.7.1.md old mode 100644 new mode 100755 diff --git a/doc/releases/v2.8.0.md b/doc/releases/v2.8.0.md new file mode 100644 index 0000000..ad17fc7 --- /dev/null +++ b/doc/releases/v2.8.0.md @@ -0,0 +1,51 @@ +# v2.8.0 发布说明 · Release Notes(prove) + +## 1. 一句话 + +`marqdo prove` 正式发布:知识文件的定理表 → Lean 4 证明 → 自动判定。 +没有 Lean 工具链也能跑(离线符号执行,诚实降级);有 Lean 时全链路证明, +假定理给出路径见证反例,离线与 Lean 分歧时显式报错永不落绿。 + +`marqdo prove` ships: theorem tables in knowledge files compile to Lean 4 +and are judged automatically. It runs without a Lean toolchain (offline +symbolic execution, honest degradation); with Lean, fake theorems get +counterexamples and any offline/Lean divergence fails loudly. + +## 2. 亮点(Highlights) + +| | | +|---|---| +| 定理表 | `| 定理 | 结论 | 前提 | 策略 |`,结论文法:`结果.ok`、`包含(轨迹,…)`、`长度(轨迹)`、参数比较,且/或/非组合 | +| 六段管线 | 装载 → 降级 → 定型 → 生成(Lean 4.35)→ 判定(离线先行 + Lean 复核)→ 证书 | +| 离线判定 | F1–F5 片段符号执行:路径枚举、轨迹形状、构造器结构、自由原子二分、区间字面重述与反例见证(毫秒级) | +| 单调性护栏 | 离线 `checked` 但 Lean 证不出(或反例被证出)→ `error[proof.divergence]` 退 1——绝不让离线判定比 Lean 更乐观 | +| 诚实状态 | `proved > checked > unverified > rejected > unproved > error`;`checked ≠ proved`;无 Lean 时状态如实降级(咨询性退 0),`--require-lean` CI 严格模式退 2 | +| 反例 | 假定理给出区间端点见证(如 `金额 = 10001`)并指回定理表行号 | +| 证书缓存 | 复合键(源码⊕计划⊕库⊕Lean 版本⊕CLI 版本),`.marqdo/prove/`,命中跳过判定;`--no-cache` 绕过 | +| 目录模式 | `prove --all 目录`(`--max-files` 默认 200):逐文件出证,整体取最差,聚合 JSON | +| 差分一致性 | T4 语料:解释器求值 == Lean 语义(算术/中文标识符/分支/拼接/i64 边界/结构字段) | +| 工具链 | `--lean` 显式指定 → `MARQDO_PROOF_LEAN` → PATH;内嵌判定库按内容哈希缓存构建,无需 lake/elan | + +## 3. 使用(Usage) + +```bash +marqdo prove 审批.mq.md --json # 判定 + 单个 JSON 报告 +marqdo prove emit 审批.mq.md # 只生成 Lean 模块 + plan.json +marqdo prove audit 审批.mq.md # 只审查可证子集(不写盘) +marqdo prove --all skills/ --json # 目录聚合(整体取最差) +marqdo prove clean # 清空 .marqdo/prove +``` + +测试:`cargo test --test prove`(无 Lean 全绿)· +`MARQDO_PROOF_LEAN= cargo test --test prove_lean --test prove_corpus --test conformance`(有 Lean 全链路 + 40 夹具单调性 + T4 一致性)。 + +详见 [design/prove-cli.md](../design/prove-cli.md)(命令面、可证子集与判定管线)与 +[skill-proof-theory.md](../verification/skill-proof-theory.md)(库形式化说明)。 + +## 4. 已知限制(Known limitations) + +- `foreach` 维持 `proof.foreach_pending`(可证子集无循环;fold 编码 → 2.9)。 +- 跨模块调用 = 不透明操作;assume-guarantee 后置条件复用 → 2.9(依赖假设表 T3)。 +- 除零/模零:解释器为运行时错误,判定库模型返回 `.int 0`(已记录偏差)。 +- 分支条件暂不支持字段访问(解析器文法限制;prove 侧已就绪,放开即生效)。 +- i64 溢出:解释器报运行时错误;判定库 `Int` 无界(语料只测界内值)。 diff --git a/doc/research/agent-capabilities-2026-10-27.md b/doc/research/agent-capabilities-2026-10-27.md old mode 100644 new mode 100755 diff --git a/doc/research/agent-framework-2026-09.md b/doc/research/agent-framework-2026-09.md old mode 100644 new mode 100755 diff --git a/doc/research/agent-framework-gaps-after-a4.md b/doc/research/agent-framework-gaps-after-a4.md old mode 100644 new mode 100755 diff --git a/doc/research/agent-frameworks-and-marqdo.md b/doc/research/agent-frameworks-and-marqdo.md old mode 100644 new mode 100755 diff --git a/doc/research/agent-llm-transport-soft-2026-10.md b/doc/research/agent-llm-transport-soft-2026-10.md old mode 100644 new mode 100755 diff --git a/doc/research/agent-run-efi-resolve-bugs-2026-10.md b/doc/research/agent-run-efi-resolve-bugs-2026-10.md old mode 100644 new mode 100755 diff --git a/doc/research/ai-agent-llm-optimize-2026-10.md b/doc/research/ai-agent-llm-optimize-2026-10.md old mode 100644 new mode 100755 diff --git a/doc/research/ai-agent-sandbox.md b/doc/research/ai-agent-sandbox.md old mode 100644 new mode 100755 diff --git a/doc/research/ext-hosting-gaps.md b/doc/research/ext-hosting-gaps.md old mode 100644 new mode 100755 diff --git a/doc/research/ext-linalg-formula.md b/doc/research/ext-linalg-formula.md old mode 100644 new mode 100755 diff --git a/doc/research/ext-web-customization-limits.md b/doc/research/ext-web-customization-limits.md old mode 100644 new mode 100755 diff --git a/doc/research/foreign-notebook-decisions.md b/doc/research/foreign-notebook-decisions.md old mode 100644 new mode 100755 diff --git a/doc/research/occlusion-vs-executable-knowledge-2026-10.md b/doc/research/occlusion-vs-executable-knowledge-2026-10.md old mode 100644 new mode 100755 diff --git a/doc/research/okf-and-marqdo.md b/doc/research/okf-and-marqdo.md old mode 100644 new mode 100755 diff --git a/doc/research/qdagent-refactor-defects-2026-10.md b/doc/research/qdagent-refactor-defects-2026-10.md old mode 100644 new mode 100755 diff --git a/doc/research/stdlib-gaps-after-mid.md b/doc/research/stdlib-gaps-after-mid.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/agent-reliability-crossrepo-2026-10-27.md b/doc/roadmap/agent-reliability-crossrepo-2026-10-27.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/agent-streaming.md b/doc/roadmap/agent-streaming.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ai-stack.md b/doc/roadmap/ai-stack.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/blind-experiment-2026-09-23-deepseek-flash.md b/doc/roadmap/blind-experiment-2026-09-23-deepseek-flash.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/blind-experiment-2026-09-23-mimo-v2.6-pro.md b/doc/roadmap/blind-experiment-2026-09-23-mimo-v2.6-pro.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/browser-wasm-d.md b/doc/roadmap/browser-wasm-d.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/browser-wasm-e.md b/doc/roadmap/browser-wasm-e.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/browser-wasm-f.md b/doc/roadmap/browser-wasm-f.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/browser-wasm.md b/doc/roadmap/browser-wasm.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/code-as-docs-gaps.md b/doc/roadmap/code-as-docs-gaps.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/executable-knowledge-gaps-2026-10-23.md b/doc/roadmap/executable-knowledge-gaps-2026-10-23.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-agent-optimize.md b/doc/roadmap/ext-agent-optimize.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-ai-optimize.md b/doc/roadmap/ext-ai-optimize.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-ai-sandbox.md b/doc/roadmap/ext-ai-sandbox.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-hosting.md b/doc/roadmap/ext-hosting.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-linalg.md b/doc/roadmap/ext-linalg.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/foreign-v2.md b/doc/roadmap/foreign-v2.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/interpreter.md b/doc/roadmap/interpreter.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/lib-ext-code-as-docs.md b/doc/roadmap/lib-ext-code-as-docs.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/library-authoring-refactor.md b/doc/roadmap/library-authoring-refactor.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/library-authoring-reviewed-fixes.json b/doc/roadmap/library-authoring-reviewed-fixes.json old mode 100644 new mode 100755 diff --git a/doc/roadmap/markup-v0.3.md b/doc/roadmap/markup-v0.3.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/next-phase.md b/doc/roadmap/next-phase.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/notebook-session.md b/doc/roadmap/notebook-session.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/object-inheritance.md b/doc/roadmap/object-inheritance.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/okf-near-match.md b/doc/roadmap/okf-near-match.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/perf-validation-report-2026-09-23.md b/doc/roadmap/perf-validation-report-2026-09-23.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/perf-validation.md b/doc/roadmap/perf-validation.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/prove-release-2.8.0.md b/doc/roadmap/prove-release-2.8.0.md new file mode 100755 index 0000000..7f2fd73 --- /dev/null +++ b/doc/roadmap/prove-release-2.8.0.md @@ -0,0 +1,133 @@ +# v2.8.0 发布说明 · Release Notes(prove) + +> 仓库权限说明:本文件由 2.8.0 收口时的自动化会话写入 `doc/roadmap/` +> (`CHANGELOG.md`、`README.md`、`doc/releases/`、`skills/marqdo-dev/` 为 +> root 属主、运行账号不可写)。内容已定稿,合入即可;§4 为待合入原文。 + +## 1. 一句话 + +`marqdo prove` 正式发布:知识文件的定理表 → Lean 4 证明 → 自动判定。 +没有 Lean 工具链也能跑(离线符号执行,诚实降级);有 Lean 时全链路证明, +假定理给出路径见证反例,离线与 Lean 分歧时显式报错永不落绿。 + +`marqdo prove` ships: theorem tables in knowledge files compile to Lean 4 +and are judged automatically. It runs without a Lean toolchain (offline +symbolic execution, honest degradation); with Lean, fake theorems get +counterexamples and any offline/Lean divergence fails loudly. + +## 2. 亮点(Highlights) + +| | | +|---|---| +| 定理表 | `| 定理 | 结论 | 前提 | 策略 |`,结论文法:`结果.ok`、`包含(轨迹,…)`、`长度(轨迹)`、参数比较,且/或/非组合 | +| 六段管线 | 装载 → 降级 → 定型 → 生成(Lean 4.35)→ 判定(离线先行 + Lean 复核)→ 证书 | +| 离线判定 | F1–F5 片段符号执行:路径枚举、轨迹形状、构造器结构、自由原子二分、区间字面重述与反例见证(毫秒级) | +| 单调性护栏 | 离线 `checked` 但 Lean 证不出(或反例被证出)→ `error[proof.divergence]` 退 1——绝不让离线判定比 Lean 更乐观 | +| 诚实状态 | `proved > checked > unverified > rejected > unproved > error`;`checked ≠ proved`;无 Lean 时状态如实降级(咨询性退 0),`--require-lean` CI 严格模式退 2 | +| 反例 | 假定理给出区间端点见证(如 `金额 = 10001`)并指回定理表行号 | +| 证书缓存 | 复合键(源码⊕计划⊕库⊕Lean 版本⊕CLI 版本),`.marqdo/prove/`,命中跳过判定;`--no-cache` 绕过 | +| 目录模式 | `prove --all 目录`(`--max-files` 默认 200):逐文件出证,整体取最差,聚合 JSON | +| 差分一致性 | T4 语料:解释器求值 == Lean 语义(算术/中文标识符/分支/拼接/i64 边界/结构字段) | +| 工具链 | `--lean` 显式指定 → `MARQDO_PROOF_LEAN` → PATH;内嵌判定库按内容哈希缓存构建,无需 lake/elan | + +## 3. 使用(Usage) + +```bash +marqdo prove 审批.mq.md --json # 判定 + 单个 JSON 报告 +marqdo prove emit 审批.mq.md # 只生成 Lean 模块 + plan.json +marqdo prove audit 审批.mq.md # 只审查可证子集(不写盘) +marqdo prove --all skills/ --json # 目录聚合(整体取最差) +marqdo prove clean # 清空 .marqdo/prove +``` + +测试:`cargo test --test prove`(无 Lean 全绿)· +`MARQDO_PROOF_LEAN= cargo test --test prove_lean --test prove_corpus --test conformance`(有 Lean 全链路 + 40 夹具单调性 + T4 一致性)。 + +## 4. 待合入原文(需 root 属主文件权限) + +### 4.1 `CHANGELOG.md` 追加 + +```markdown +## v2.8.0 — 2026-11-17 + +`marqdo prove` 正式发布:定理表 → Lean 4 证明 → 自动判定。离线符号执行 +(F1–F5)无工具链可用,`checked` 永远弱于 `proved`;单调性护栏让判定器 +缺陷显式失败;假定理给出反例见证;证书缓存与目录模式面向智能体批量出证。 + +`marqdo prove` ships: theorem tables compile to Lean 4 and are judged +automatically. Offline symbolic execution works without a toolchain, +monotonicity guardrails fail loudly on judger defects, fake theorems get +counterexample witnesses, and certificate caching plus directory mode +support agent-scale proving. + +详见 [双语发布说明](../releases/v2.8.0.md)。 +``` + +### 4.2 `README.md` 修改 + +版本行(第 19–21 行)替换为: + +```markdown +当前 CLI **2.8.0** 新增 `marqdo prove`:知识文件的定理表编译为 Lean 4 并自动 +判定真假——没有 Lean 工具链也能离线符号执行(诚实降级,绝不冒充证明), +有 Lean 时全链路证明并给出反例见证。参见[发布说明](../releases/v2.8.0.md)。 + +CLI **2.8.0** adds `marqdo prove`: theorem tables in knowledge files compile +to Lean 4 and are judged automatically — offline symbolic execution without +a toolchain (honest degradation, never impersonating a proof), full proofs +with counterexample witnesses when Lean is available. +``` + +「愿景与期许」清单追加第 7 条: + +```markdown +7. **知识可证明**:知识文件内的定理表 → Lean 4 定理 → 自动判定 + (`marqdo prove`);离线符号执行与 Lean 单调一致,分歧显式报错。 +``` + +### 4.3 `skills/marqdo-dev/index.mq.md` 追加 `prove` 任务 + +```markdown +## prove + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | "." | 单个 `.mq.md` 或目录(目录需要 all=True) | +| all | bool | False | 目录模式:递归收集 .mq.md 逐文件出证,整体取最差状态 | +| max_files | num | 200 | 目录收集上限 | +| require_lean | bool | False | CI 严格模式:未判定状态退 2 | +| json | bool | False | 单个 JSON 对象输出(智能体可读契约) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:真实 `marqdo prove` 退出状态、标准输出与错误输出 | + +证明知识文件的定理表:先离线符号执行(毫秒级 checked,不是 proved), +有 Lean 工具链时由 Lean 复核升级 proved;假定理给出路径见证反例; +离线与 Lean 分歧触发 proof.divergence 错误并退 1,永不落绿。 +不带 Lean 时状态如实停留在 unverified/checked(咨询性退 0), +require_lean=True 才把未判定当作阻塞。 + +通过只说明所选文件判定完成,不能替代 test 任务的运行时验收; +两者结合才是完整验收。 + +1. len(text.trim(`path`)) == 0 + Return *[要求明确的证明范围](result.error(code="dev.prove_path", message="path is required", operation="prove"))*. +1. `all` + We **argv = ["prove", "--all", `path`, "--max-files", text.num_text(`max_files`)]**. +1. not `all` + We **argv = ["prove", `path`]**. +1. `require_lean` + We **argv = [追加严格模式](table.append(list=`argv`, item="--require-lean"))**. +1. `json` + We **argv = [追加机器可读输出](table.append(list=`argv`, item="--json"))**. +We **checked = [执行真实证明管线](engineering.run(argv=`argv`, timeout_ms=600000, max_output=4194304))**. +验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 +``` + +## 5. 已知限制(Known limitations) + +- `foreach` 维持 `proof.foreach_pending`(可证子集无循环;fold 编码 → 2.9)。 +- 跨模块调用 = 不透明操作;assume-guarantee 后置条件复用 → 2.9(依赖假设表 T3)。 +- 除零/模零:解释器为运行时错误,P1 判定库模型返回 `.int 0`(已记录偏差)。 +- 分支条件暂不支持字段访问(解析器文法限制;prove 侧已就绪,放开即生效)。 diff --git a/doc/roadmap/prove.md b/doc/roadmap/prove.md new file mode 100755 index 0000000..929f17a --- /dev/null +++ b/doc/roadmap/prove.md @@ -0,0 +1,409 @@ +# `marqdo prove` 实施路线(P0–P3) + +| | | +|---|---| +| 状态 | **已实施(P0–P3 落地,2.8.0)**——落地记录:[design/prove-cli.md §12](../design/prove-cli.md);foreach / 跨模块 assume-guarantee / 假设表 T3 显式延期 2.9 | +| 日期 | 2026-11-13 | +| 设计 | [design/prove-cli.md](../design/prove-cli.md)(命令面、离线片段、定理表、语言习惯审查) | +| 决策 | [ADR 0010](../adr/0010-skill-proof-boundary.md)(定理表角色、子集边界、顾问式定位) | +| 目标版本 | CLI 2.8.0(已发) | +| 总工期 | 6.5 人周(单人;P0+P1 共 3 周可演示) | + +--- + +## 0. 完成定义 + +| 阶段 | 完成定义(DoD) | +|---|---| +| P0 | `prove emit` / `prove audit` 可跑;确定性生成;12 个夹具的降级结论稳定;`cargo test --test prove` 在**没有 Lean** 的机器上全绿 | +| P1 | 定理表落地;有 Lean 时 `proved`,无 Lean 时至少 `unverified`;证书与源码映射可用;CI 跑通「假定理必须红」 | +| P2 | 离线判定 `checked` 可用;语料库强制 `offline_checked ⊆ lean_proved`;反例可读;`--require-lean` 严格模式 | +| P3 | 跨函数组合、`--all`、差分一致性;文档/教程/技能手册齐;2.8.0 发布 | + +关键指标(P3 收口时复核): + +- 语料 **≥ 40** 个夹具,覆盖 8 类(§6)。 +- 控制平面类定理的**离线覆盖率 ≥ 60%**(其余 `unverified`,不算失败)。 +- 冷启动(50 函数文件)**< 30s**;证书命中 **< 50ms**。 +- **单调性分歧 0 例**(语料 + CI 每次运行)。 + +--- + +## 1. 为什么先 Lean、后离线 + +离线判定器需要一把"标尺":没有 Lean 作为判据,无法知道它会不会"过度自信"。所以顺序是: + +1. P0 先把降级与生成做确定(无判定,不会撒谎); +2. P1 接上 Lean,得到**权威判据**与失败证据格式; +3. P2 才写离线判定,并用 P1 的 Lean 结果做语料护栏(`offline ⊆ lean`)。 + +如果反过来,P2 的判定器会在没有标尺的情况下生长,最后很难证明它保守。 + +--- + +## 2. P0 · 骨架与确定性生成(1 周) + +### 任务 + +| 天 | 任务 | 产物 | +|---|---|---| +| D1 | `Commands::Prove` + `ProveAction::{Emit,Audit,Clean}`;`--json` 外壳;`src/prove/mod.rs` 状态机骨架 | `marqdo prove --help` 正确;未知参数报 clap 错误 | +| D2 | `ir.rs` + `lower.rs`:参数、赋值、返回、调用→`Op`、`if/else`;`while`/递归/动态调用的拒绝码 | 12 个夹具降级到 IR,`plan.json` 可读 | +| D3 | `types.rs`:从契约表起步的推断与合一;`proof.type_mismatch` 等错误码 | 类型错误夹具给出两处行号 | +| D4 | `emit.rs`:确定性 Lean 生成(稳定排序、无时间戳、相对路径)、中文名、`-- mq:` 注释 | 两次运行字节一致 | +| D5 | `report.rs` + `audit`:内联/不透明/跳过三类清单;快照测试;`tests/prove.rs` | `cargo test --test prove` 无 Lean 全绿 | + +### 验收 + +```bash +marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/lean +marqdo prove audit tests/prove/fixtures/approval.mq.md --json | jq '.functions[0].ops, .functions[0].rejected' +# 两次 emit 的 sha256 相同 +``` + +### 明确不做 + +判定、证书、Lean 调用、定理表。P0 的 `prove` 只有 `emit`/`audit` 两个子命令可用,默认命令直接转发到 `emit` 并提示"判定将在 P1 提供"。 + +--- + +## 3. P1 · 定理表 + Lean 判定(2 周) + +### 第 1 周:语言面与工具链 + +| 任务 | 产物 | +|---|---| +| ADR 0010 落定;`Function.claims`;定理表提取(首条可执行语句前,提取后移出 body) | 解析后 `claims` 非空,body 里没有该表 | +| `check --proof`(默认关):表形、名字、片段、遮蔽 | `check` 报 `proof.claim_malformed` / `proof.name_shadow` | +| `verification/skill-proof/`:`lean-toolchain`、`lakefile`、`Basic/Result/Tactic`、`LIBRARY-SHA256` 脚本 | `lake build` 通过 | +| `driver.rs`:工具链探测、Lake 包、`lake env lean`、超时、stderr 解析 | 手工跑通 approval 样例 | +| `cache.rs`:证书、`index.json`、失效 | 二次运行毫秒返回 | + +### 第 2 周:定理语义与失败证据 + +| 任务 | 产物 | +|---|---| +| 结论/前提求值:参数、`结果`、`轨迹`、三个谓词 | 定理编译通过 | +| 脚本生成:`intro` → `unfold run` → `split_ifs <;> simp_all <;> omega` | 正例 `proved` | +| 失败解析:`unsolved goals` → 目标 + 上下文 → 映射回 `.mq.md` 行 | 假定理给出源码行与残余目标 | +| `.github/workflows/proof.yml`:elan 钉版、`lake build`、跑 Lean 用例 | CI 绿;假定理用例必须红 | +| 文本/JSON/退出码对齐设计文档 | 状态表逐项手测 | + +### 验收 + +```bash +marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "proved" +marqdo prove tests/prove/fixtures/false-claim.mq.md; echo $? # 1 +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status +# P1 阶段没有离线判定,因此是 "unverified";P2 起升级为 "checked" +``` + +--- + +## 4. P2 · 离线判定与单调性(2 周) + +### 第 1 周:符号执行与 F1–F4 + +- `offline.rs`:符号状态(`Const/Param/OpResult/Unknown`)、路径条件、轨迹。 +- 分支分叉与返回路径收集;`if` 条件求值到符号原子。 +- F2 轨迹求值(`包含/长度/下标`)、F3 字面结果、F4 命题组合。 +- 结论:`checked` / `unverified` 两态;证书写入情形列表。 + +### 第 2 周:F5 区间、反例、护栏 + +- F5:单变量 `x ⋈ c` 的区间传播与蕴含判定(保守;不可判定即 `unverified`)。 +- 反例:路径可满足 + 结论字面假 → 端点见证值。 +- 分歧护栏:`checked` 但 Lean 未关闭 → `error[proof.divergence]`(含测试专用注入开关,见 §6 A3)。 +- 假设表(T3):前置/后置 → 定理前提;`proof.assumption_untyped`。 +- 单调性脚本:对语料逐条比对离线与 Lean 的定理状态。 + +### 验收 + +```bash +# 无 Lean 也能给出离线结论 +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq .status # "checked" +# 单调性:语料中不存在 checked 而 Lean unproved 的定理 +cargo test --test prove_lean # 需工具链 +``` + +--- + +## 5. P3 · 组合与产品化(1.5 周) + +| 任务 | 产物 | +|---|---| +| 跨函数内联 + assume-guarantee(调用者用被调者证书里的后置条件) | 多函数编排证明 | +| `foreach`(有限列表,fold 编码) | Q1 夹具 | +| `--all` 目录模式、聚合报告、`--max-files` | 仓库级报告 | +| 差分一致性(T4):`Conformance.lean` + 解释器期望值 | CI 比对 | +| `view` 徽标、`catalog` `proof:` 字段、MLSP `proof` 方法(可选) | 读侧可见 | +| 文档:README、教程、两个 skill 手册、CHANGELOG、2.8.0 | 发布 | +| 发版手册:推荐附证书(不强制) | 流程更新 | + +### 验收 + +```bash +marqdo prove --all skills/ --json | jq '.status, (.files|length)' +lake build # verification/skill-proof/examples 全部通过 +``` + +--- + +## 6. 测试矩阵(针对性) + +夹具目录 `tests/prove/fixtures/`,集成测试 `tests/prove.rs`;Lean 相关用 `tests/prove_lean.rs`(独立测试目标,不进默认 `cargo test`)。 + +### A · 单调性与诚实性(最高优先级) + +| ID | 夹具 / 操作 | 期望 | 守住什么 | +|---|---|---|---| +| A1 | `approval.mq.md`:`包含(轨迹,"人工审核")` | 离线 `checked`;Lean `proved` | 离线结论被 Lean 确认 | +| A2 | `false-claim.mq.md`:大额时断言 `结果.ok = False` | `unproved`,退出 1;P2 起附反例 `金额=10001` | 假定理不被放绿 | +| A3 | 同一夹具 + 测试注入 `--fault-inject offline-claim`(仅 debug 构建存在) | `error[proof.divergence]`,退出 1,JSON `status=="error"` | 分歧必须显式失败,不许静默以离线为准 | +| A4 | 多变量线性命题(`金额 + 手续费 > 10000`) | 离线 `unverified`;跑 Lean 后 `proved` 或 `unproved` | 片段保守,不越界断言 | +| A5 | 语料全量:`checked` 集合 ⊆ Lean `proved` 集合 | 集合包含成立,0 反例 | 长期单调性回归 | + +### B · 语义一致性(T4) + +| ID | 内容 | 期望 | +|---|---|---| +| B1 | 纯函数语料(算术、比较、布尔、字符串拼接、`access`、`len`) | 解释器输出 == Lean `example : f args = expected := by decide` | +| B2 | 除零、取模零 | 与运行时错误语义一致(生成 `mq_div`/`mq_mod` 返回 Result.failure) | +| B3 | 中文标识符 `计算器.加法`、含空格名 `多 步` | 生成 `«…»`,Lean 接受 | +| B4 | 映射/表字面量:字段顺序、`ok` 字段读取 | Lean 结构与 Marqdo 取值一致 | +| B5 | 负数、大整数(`i64` 边界) | 无溢出漂移;超界按契约拒绝 | + +### C · 不执行(安全) + +| ID | 夹具 | 期望 | +|---|---|---| +| C1 | 函数里调 `fs.write`、`fs.make_dirs` | `prove` 后目标路径不存在 | +| C2 | 函数里调 `print` | stdout **只有** `prove` 的报告;没有程序输出 | +| C3 | `--emit` 到只读目录 | 清晰 IO 错误,退出 1,不 panic | + +### D · 子集与拒绝 + +| ID | 夹具 | 期望 | +|---|---|---| +| D1 | `while` 循环 | `proof.while`,行号准确;整体 `rejected`,退出 0 | +| D2 | 自递归 + 互递归 | `proof.recursion`,列出环上函数名 | +| D3 | 插件/动态调用 | `proof.dynamic_call` | +| D4 | 未定型变量(strict) | `proof.type_mismatch`,两处行号 | +| D5 | 同上 + `--no-strict-types` | 落 `Val`,报告标"弱类型",不报错 | +| D6 | `--allow-opaque 预检` | 该函数列为不透明操作,调用者仍可证 | + +### E · 定理表 + +| ID | 夹具 | 期望 | +|---|---|---| +| E1 | 未知名字 `审批人.ok` | `proof.claim_unknown_symbol` + 最近建议 | +| E2 | 重复 id | `proof.claim_duplicate` | +| E3 | 参数名 `结果` 遮蔽保留名 | `proof.name_shadow` | +| E4 | `策略 none` | 定理生成、不证;状态 `unverified`,不是失败 | +| E5 | 非法策略片段 `策略 nonsense` | `proof.claim_failed` 带 Lean 原始错误,不 panic | +| E6 | 缺 `结论` 列 / 表在语句之后 | `proof.claim_malformed` / `proof.claim_misplaced`(`check --proof`) | +| E7 | 两列「定理 / 说明」普通表 | 不认领,`check --proof` 不报 | +| E8 | `假设` 表:`返回.ok = True` 用于分支判断 | Lean `proved`;证书 `assumptions` 有该条 | + +### F · CLI / JSON / 退出码 + +| ID | 操作 | 期望 | +|---|---|---| +| F1 | 各状态夹具 | 退出码 == 设计表(0/0/0/0/1/1) | +| F2 | `--report-only` on A2 | 退出 0,状态仍 `unproved` | +| F3 | `--require-lean` 且 `PATH` 无 lean | 退出 2,`status=="unverified"` | +| F4 | `--json` | 键集合与类型快照;`schema==1`;无绝对路径 | +| F5 | 目录不带 `--all` | `proof.need_all`,退出 1 | +| F6 | `prove clean` | `.marqdo/prove` 消失;`--emit` 目录保留 | + +### G · 缓存与确定性 + +| ID | 操作 | 期望 | +|---|---|---| +| G1 | 连续两次 `prove emit` | `module.lean`、`plan.json` 字节相同 | +| G2 | 假 `lean` 脚本写日志;连续两次 `prove` | 日志只有 1 行(第二次命中缓存) | +| G3 | 改源码一个字符 | 证书键变化,重新判定 | +| G4 | 改库文件(模拟 `LIBRARY-SHA256` 变化) | 缓存失效 | +| G5 | 手工损坏 `certificate.json` | `proof.cache_corrupt`;重算或退出 1,不读坏证书 | + +### H · 编码边角 + +| ID | 内容 | 期望 | +|---|---|---| +| H1 | 空 else、两臂都早返回 | 生成退化正确,Lean 通过 | +| H2 | 不可达分支(`1. False`) | `audit` 标 warning;不阻塞 | +| H3 | 字符串含引号/换行/中文 | 转义正确,Lean 字面量等值 | +| H4 | 0 参数、0 语句函数 | 生成 `def run := ...` 合法 | +| H5 | 参数默认值 | 与契约默认一致;Lean 用显式值代入 | + +--- + +### 关键夹具草稿(P0 落盘到 `tests/prove/fixtures/`) + +正例(轨迹命题,A1): + +```markdown +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留人工审核结论](result.ok(value=`审核`))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +**结果** +``` + +反例(A2):同构文件,只把定理换成 + +```markdown +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 不该自动放行 | 结果.ok = False | 金额 > 10000 | auto | +``` + +期望 `unproved`、退出 1;P2 起附反例 `金额 = 10001`。 + +不执行(C1): + +```markdown +## 落盘 ++ `path` + +**written = [真的写一个文件](fs.write_text(path=`path`, text="证明工具不该执行我"))** + +**written** +``` + +跑 `prove` 后指定路径必须不存在;`prove` 只做降级与生成。 + +拒绝(D1): + +```markdown +## 倒计时 ++ `n` + +- `n` > 0 + **n = n - 1** + +**n** +``` + +期望 `proof.while`,整体 `rejected`、退出 0(若没有别的未关闭定理)。 + +遮蔽(E3): + +```markdown +## 遮蔽 ++ `结果` + +| 定理 | 结论 | +|---|---| +| 读结果 | 结果.ok = True | +``` + +参数名与保留名冲突 → `proof.name_shadow`,要求改名,不做隐式优先。 + +--- + +## 7. 验收证据(可直接粘进 PR) + +```bash +# 1) 离线可用(把 PATH 收窄到没有 lean) +PATH=/usr/bin:/bin target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status +# checked + +# 2) 有 Lean 时升级为证明 +target/debug/marqdo prove tests/prove/fixtures/approval.mq.md --json | jq -r .status +# proved + +# 3) 假定理必须红,且给出行号 +target/debug/marqdo prove tests/prove/fixtures/false-claim.mq.md; echo "exit=$?" +# error[proof.claim_failed] … --> false-claim.mq.md:31:3 +# exit=1 + +# 4) 单调性(语料) +cargo test --test prove_lean -- --nocapture +# offline_checked=37 lean_proved=37 divergences=0 + +# 5) 不执行 +rm -f /tmp/mq-prove-should-not-exist +target/debug/marqdo prove tests/prove/fixtures/side-effect.mq.md +test ! -e /tmp/mq-prove-should-not-exist && echo "no side effect" + +# 6) 确定性 +a=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/a && sha256sum /tmp/a/Generated/Approval.lean) +b=$(target/debug/marqdo prove emit tests/prove/fixtures/approval.mq.md -o /tmp/b && sha256sum /tmp/b/Generated/Approval.lean) +[ "${a%% *}" = "${b%% *}" ] && echo deterministic +``` + +--- + +## 8. CI 设计 + +```yaml +# .github/workflows/proof.yml(示意;action 版本以仓库既有 workflow 为准) +jobs: + corpus: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Install elan (toolchain pinned by verification/skill-proof/lean-toolchain) + run: | + curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + - name: Build proof library (cache .lake) + working-directory: verification/skill-proof + run: lake build + - run: cargo build --locked + - run: cargo test --test prove --locked # 不需要 Lean 的部分 + - run: cargo test --test prove_lean --locked + env: { MARQDO_PROOF_REQUIRE_LEAN: "1" } + - run: bash scripts/check-proof-library.sh # LIBRARY-SHA256 与 BUILD-IDENTITY +``` + +原则: + +- `cargo test` **不依赖** Lean;Lean 用例在独立目标里,缺失工具链时打印 `SKIP: lean toolchain not found` 并在 `MARQDO_PROOF_REQUIRE_LEAN=1` 下转为失败。 +- 不使用 `#[ignore]` 作为成功证据(沿用 `executable-knowledge.yml` 的纪律)。 +- Lean 构建缓存 `.lake`,避免每次拉依赖。 + +--- + +## 9. 风险与回滚 + +| 风险 | 触发 | 应对 | +|---|---|---| +| Lean 工具链在 CI 不可用 | action 变更/网络 | 钉版本 + 缓存;`proof.yml` 失败只红该 job,不阻塞其它 | +| 离线判定"过度自信" | 片段实现 bug | 语料 A5 强制包含关系;运行期 A3 分歧即 error | +| 生成不确定 | HashMap 遍历顺序 | 全量 `BTreeMap`;两次 emit 字节比对进 CI | +| 定理表被误用成数据表 | 表头重名 | 只有表头+列形同时命中才认领;`check --proof` 可关 | +| 破坏既有 `check` 性能 | 提取逻辑 | `--proof` 默认关;提取只做一次线性扫描 | +| 范围蔓延(想把整个语言编译过去) | 需求诱惑 | ADR 0010 写死子集;新增构造需重新评审 | + +回滚:`prove` 是**纯增量**(新命令 + 新可选表角色);删除命令与 `Function.claims` 字段即可回到现状,已有 `.mq.md` 不受影响(定理表在无 `prove` 的旧版本里只是普通表格)。 + +--- + +## 10. 不做清单(本版本) + +- `while`、递归、动态派发的形式化(拒绝而非近似)。 +- 字符串/JSON/浮点/公式库的语义建模。 +- 自动修复不成立的定理。 +- 证明缓存的服务端共享。 +- IDE 内联证明状态(先走 `view` 徽标)。 +- 强制门禁:任何"必须 proved 才能发布"的默认行为。 diff --git a/doc/roadmap/qdagent-knowledge-support-gaps-2026-10-24.md b/doc/roadmap/qdagent-knowledge-support-gaps-2026-10-24.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/repair-experiment-2026-09-22-mimo-v2.6-flash.md b/doc/roadmap/repair-experiment-2026-09-22-mimo-v2.6-flash.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/repair-experiment-2026-09-22.md b/doc/roadmap/repair-experiment-2026-09-22.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/stdlib-executable-handbook.md b/doc/roadmap/stdlib-executable-handbook.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/stdlib-mid.md b/doc/roadmap/stdlib-mid.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/stdlib-mid2.md b/doc/roadmap/stdlib-mid2.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/tables-maps-footnotes.md b/doc/roadmap/tables-maps-footnotes.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/three-problems-plan.md b/doc/roadmap/three-problems-plan.md old mode 100644 new mode 100755 diff --git a/doc/roadmap/three-problems.md b/doc/roadmap/three-problems.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/01-入门.md b/doc/tutorial/01-入门.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/02-基本语法.md b/doc/tutorial/02-基本语法.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/03-变量与赋值.md b/doc/tutorial/03-变量与赋值.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/04-输出与输入.md b/doc/tutorial/04-输出与输入.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/05-运算符与比较.md b/doc/tutorial/05-运算符与比较.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/06-函数.md b/doc/tutorial/06-函数.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/07-条件分支.md b/doc/tutorial/07-条件分支.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/08-循环.md b/doc/tutorial/08-循环.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/09-集合.md b/doc/tutorial/09-集合.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/10-对象与方法.md b/doc/tutorial/10-对象与方法.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/11-模块与导入.md b/doc/tutorial/11-模块与导入.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/12-标准库.md b/doc/tutorial/12-标准库.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/13-命令行工具.md b/doc/tutorial/13-命令行工具.md old mode 100644 new mode 100755 index 5002750..6d38268 --- a/doc/tutorial/13-命令行工具.md +++ b/doc/tutorial/13-命令行工具.md @@ -98,7 +98,36 @@ marqdo ext remove llm - **标准库**:内置于二进制;磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。 - **库路径解析**:`MARQDO_LIB` → 当前目录 `lib/` → 可执行文件旁 `lib/`。 -## 13.8 下一步 +## 13.8 证明定理表:`prove` + +知识文件里带定理表(`| 定理 | 结论 | 前提 | 策略 |`)的函数,可以用 +`marqdo prove` 生成 Lean 4 证明并自动判定真假: + +```bash +marqdo prove 审批.mq.md # 生成 Lean 模块 + 判定(有 Lean 时) +marqdo prove 审批.mq.md --json # 智能体可读的单个 JSON 报告 +marqdo prove emit 审批.mq.md # 只生成不判定 +marqdo prove audit 审批.mq.md # 只审查可证子集,不写盘 +marqdo prove --all skills/ # 目录模式:逐文件出证,整体取最差 +marqdo prove clean # 清空 .marqdo/prove +``` + +状态从强到弱:`proved`(Lean 证出)> `checked`(离线符号执行关闭)> +`unverified`(超出可证子集,诚实未知)> `rejected`(子集验收拒绝)> +`unproved`(反例)> `error`(判定层错误)。关键纪律: + +- **没有 Lean 也能跑**:离线符号执行给出 `checked`,但它不是 proved—— + 只是"在受限片段里符号地关掉了"。状态如实降级,绝不冒充证明。 +- **假定理必须红**:断言与执行语义矛盾的定理会得到反例(路径见证, + 如 `金额 = 10001`),退出码 1。 +- **单调性护栏**:离线说 `checked` 但 Lean 证不出(或反过来)→ + `error[proof.divergence]`,判定器缺陷优先于任何绿灯。 +- **证书缓存**:判定结果按源码+计划+库+版本哈希缓存于 `.marqdo/prove/`, + 重复运行毫秒级命中;`--no-cache` 绕过。 + +详见 [design/prove-cli.md](../design/prove-cli.md)(命令面、可证子集与判定管线)。 + +## 13.9 下一步 恭喜!你已经完成了 Marqdo 语法教程。你现在可以: diff --git a/doc/tutorial/14-网络与Web扩展.md b/doc/tutorial/14-网络与Web扩展.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/15-常见陷阱.md b/doc/tutorial/15-常见陷阱.md old mode 100644 new mode 100755 diff --git a/doc/tutorial/README.md b/doc/tutorial/README.md old mode 100644 new mode 100755 diff --git a/doc/verification/skill-proof-theory.md b/doc/verification/skill-proof-theory.md new file mode 100755 index 0000000..6bb212c --- /dev/null +++ b/doc/verification/skill-proof-theory.md @@ -0,0 +1,78 @@ +# 判定库 `MarqdoProof.lean` 的形式化说明 + +> 本文是 [design/prove-cli.md](../design/prove-cli.md) §4–§5 的配套理论摘要: +> 生成文件依赖哪些库事实、离线判定凭什么与 Lean 单调一致、边界在哪里。 +> 库本体:[skill-proof/MarqdoProof.lean](skill-proof/MarqdoProof.lean) +> (由 `marqdo prove` 内嵌携带,`scripts/check-proof-library.sh` 校验一致性)。 + +## 1. 语义模型 + +生成文件把每个函数降级为纯 Lean 定义: + +```lean +def «模块.函数» (env : Env) («轨迹» : List Op) («参数» : Val)… : Val × List Op +``` + +- `Val`:8 形状和(none/int/num/bool/text/list/map + formula/code 边界), + 与解释器 `value::Value` 一一对应(T4 差分一致性测试锁定)。 +- `env : Env`:不透明操作的答案函数。**调用者的定理以 env 为全称量词**—— + 证出即"对任意环境实现成立",这正是 assume-guarantee 的保守形态。 +- 不透明操作 = `Op.«调用_显示名»` 构造器 + 追加轨迹;操作名用链接显示文本, + 与定理表里 `包含(轨迹, "显示名")` 的写法一致。 +- 库函数面:`mqAdd/mqSub/mqMul/mqDiv`(int 面,除零→0,已记录偏差)、 + `mqGt/mqGe/mqLt/mqLe/mqEq`(decide 编码)、`mqAccess`(映射字段读取, + 方程友好)、`mqResultOk/mqResultError/mqValueOr`(lib/result 结构)。 + +## 2. 定理形状与判定 + +每条定理表行生成: + +```lean +theorem «模块.函数.定理名» (env : Env) («参数» : Val)… : + (前提 → True) → + ((«结果», «轨迹») = «模块.函数» env [] «参数»…) → + mqTruth «结论的 Lean 编码» := by + intro … h_run + unfold «模块.函数» at h_run + try split at h_run -- 按最大 if 嵌套深度重复 + all_goals (simp_all [域引理]; try omega) +``` + +- `decided_by = "lean"`:Lean 内核接受 ⇒ `proved`;`sorry` ⇒ `unverified`; + 报错 ⇒ `unproved`(错误指回定理表行)。 +- 策略 `none`:定理生成但主体 `sorry`,状态恒 `unverified`——绝不冒充。 + +## 3. 离线判定(F1–F5)与单调性论证 + +离线判定器对同一 IR 做符号执行,路径记录 (路径条件, 结果, 轨迹, 变量)。 +它与 Lean 的对应关系是**逐构造镜像**: + +| 离线闭包理由 | Lean 侧对应 | 单调性依据 | +|---|---|---| +| F1 路径枚举穷尽 | `split at h_run` 产生的同一组目标 | 同一 IR 树,分支集合相同 | +| F2 轨迹形状(包含/长度) | `(轨迹.map Op.name).contains` / `List.length` simp | 字面轨迹的列表运算两侧同构 | +| F3 构造器结构求值 | `mqResultOk/mqResultError/mqValueOr` + `mqAccess` simp 方程 | 同一套库定义;结构字面归约是计算的 | +| F4 自由原子 | split 后假设里的同一原子(`hypothesis` 关闭) | 只承认路径条件中字面出现的原子;路径反例含自由原子时放弃见证(保守) | +| F5 区间字面重述 | split 后假设直接就是结论(`hypothesis`) | 字面匹配,无推理步 | +| F5 区间违反(反例) | 无对应(Lean 同样证不出) | 反例只产生 `unproved`,不产生绿灯;见证 = 区间端点 | +| 不可行路径跳过 | split 后假设矛盾(互斥比较引理 `.elim` + omega) | 前提 ∩ 路径条件为空 ⇒ 该分支假设集 Lean 侧同样矛盾 | + +**单调性护栏**:有 Lean 时逐定理复核。离线 `checked` 而 Lean 关不掉,或 +离线反例被 Lean 证出 ⇒ `error[proof.divergence]`,永不落绿。护栏使 +"离线比 Lean 乐观"成为运行时可见错误而非静默错误;40 夹具语料库 +(`tests/prove_corpus.rs`)在 CI 强制 `offline_checked ⊆ lean_proved`。 + +**已知保守边界**(离线能、Lean 脚本不能,因此离线也必须不做): + +- 区间**蕴含**(`金额 > 10000 ⊢ 金额 > 9999`):数学上真,但当前脚本没有 + Val 比较的传递引理,simp+omega 关不掉 ⇒ 离线同样 `unverified` + (`f5_interval_closure_scope` 单测锁定)。库补传递引理后两侧同时放开。 +- 多变量线性、非线性、文本相等:超出 F5 单变量区间 ⇒ `unverified`; + Lean 侧若能证则升级 `proved`(允许,这是"弱判定被强判定确认")。 + +## 4. 证书与缓存 + +证书记录:claim id、结论、策略、状态、`decided_by`(lean/trace/none)、 +证据(Lean 报错或离线见证)、库与模块 sha256、Lean 版本、CLI 版本。 +缓存键 = 上述全部的 sha256 ⇒ 任何一侧变化自动失效,命中即跳过判定。 +证书是**证据陈述**("这次判定是这样"),不是正确性保证——与设计 §0 契约 1 一致。 diff --git a/doc/verification/skill-proof/MarqdoProof.lean b/doc/verification/skill-proof/MarqdoProof.lean new file mode 100755 index 0000000..852b4e6 --- /dev/null +++ b/doc/verification/skill-proof/MarqdoProof.lean @@ -0,0 +1,202 @@ +/- +MarqdoProof:`marqdo prove` 生成代码的语义底座(设计 §6.2,无公理)。 + +原则: +- `Val` 是 Marqdo 值的忠实模型;每个 `mq*` 辅助函数对应 Marqdo 运行时语义的一个片段。 +- 不出现 `axiom`、不出现 `opaque`:外部操作是 `Env := Op → Val` 参数(每个生成文件 + 自带 `abbrev Env := Op → Val`,因为 `Op` 构造器集合是每文件独立的)。 +- 定理陈述把"信任了什么"写清楚:对任意 `env` 成立的命题,只依赖这里给出的方程。 +-/ + +namespace MarqdoProof + +/-- Marqdo 值模型(§6.2;`text` 是发射器的真实命名,设计文档起草时的 `str` 已修订)。 -/ +inductive Val where + | none : Val + | int : Int → Val + | num : Float → Val + | bool : Bool → Val + | text : String → Val + | list : List Val → Val + | map : List (String × Val) → Val + deriving Repr, BEq + +/-- 定理命题包装:`Bool` 语义上的"为真"。 -/ +def mqTruth (b : Bool) : Prop := b = true + +/-- 映射字段读取(`结果.ok` 等);缺失字段 → `none`(与运行时 access 一致)。 +按表项递归, simp 方程友好(`mqAccess (mqResultOk v) "ok"` 直接化到 `.bool true`)。 -/ +def mqAccess : Val → String → Val + | .map [], _ => .none + | .map ((k, v) :: rest), k' => if k == k' then v else mqAccess (.map rest) k' + | _, _ => .none + +-- ---------------------------------------------------------------- 算术 + +/-- 显示串:标量与解释器 `Value::as_display` 对齐(T4 差分一致性)。 +容器做一层显示(值经 mqDisplayScalar),嵌套容器超出 `+` 片段—— +记录为有意简化,语料不依赖嵌套容器拼接。非递归 ⇒ 无终止性负担。 -/ +def mqDisplayScalar : Val → String + | .int n => toString n + | .num x => toString x + | .bool b => if b then "True" else "False" + | .text s => s + | _ => "…" + +def mqDisplay : Val → String + | .int n => toString n + | .num x => toString x + | .bool b => if b then "True" else "False" + | .text s => s + | .list xs => "[" ++ String.intercalate ", " (xs.map mqDisplayScalar) ++ "]" + | .map ps => "{" ++ String.intercalate ", " (ps.map (fun p => p.1 ++ ": " ++ mqDisplayScalar p.2)) ++ "}" + | _ => "None" + +/-- `+`:int 算术 + 文本拼接 + num 混合,与解释器 `eval_binary(Add)` 一致。 +偏差:解释器 i64 溢出报运行时错误;Lean `Int` 无界(语料只测界内值)。 -/ +def mqAdd : Val → Val → Val + | .int a, .int b => .int (a + b) + | .num a, .num b => .num (a + b) + | .int a, .num b => .num (Float.ofInt a + b) + | .num a, .int b => .num (a + Float.ofInt b) + | .text a, .text b => .text (a ++ b) + | .text a, b => .text (a ++ mqDisplay b) + | a, .text b => .text (mqDisplay a ++ b) + | _, _ => .none + +def mqSub : Val → Val → Val + | .int a, .int b => .int (a - b) + | _, _ => .none + +def mqMul : Val → Val → Val + | .int a, .int b => .int (a * b) + | _, _ => .none + +/-- 整除;除以 0 在 Marqdo 运行时是运行时错误,此处 P1 模型按 Int 语义取 0。 -/ +def mqDiv : Val → Val → Val + | .int a, .int b => .int (a / b) + | _, _ => .none + +def mqNeg : Val → Val + | .int a => .int (-a) + | _ => .none + +-- ---------------------------------------------------------------- 比较 + +def mqLt : Val → Val → Bool + | .int a, .int b => a < b + | _, _ => false + +def mqLe : Val → Val → Bool + | .int a, .int b => a ≤ b + | _, _ => false + +def mqGt : Val → Val → Bool + | .int a, .int b => a > b + | _, _ => false + +def mqGe : Val → Val → Bool + | .int a, .int b => a ≥ b + | _, _ => false + +/-- 结构化相等(生成定理的 simp 用方程逐构造器化简)。 -/ +def mqEq : Val → Val → Bool + | .none, .none => true + | .int a, .int b => a == b + | .num a, .num b => a == b + | .bool a, .bool b => a == b + | .text a, .text b => a == b + | .list a, .list b => a == b + | .map a, .map b => a == b + | _, _ => false + +@[simp] theorem mqGt_int (a b : Int) : mqGt (Val.int a) (Val.int b) = decide (a > b) := rfl +@[simp] theorem mqGe_int (a b : Int) : mqGe (Val.int a) (Val.int b) = decide (a ≥ b) := rfl +@[simp] theorem mqLt_int (a b : Int) : mqLt (Val.int a) (Val.int b) = decide (a < b) := rfl +@[simp] theorem mqLe_int (a b : Int) : mqLe (Val.int a) (Val.int b) = decide (a ≤ b) := rfl +@[simp] theorem mqEq_int (a b : Int) : mqEq (Val.int a) (Val.int b) = decide (a = b) := rfl +@[simp] theorem mqEq_bool (a b : Bool) : mqEq (Val.bool a) (Val.bool b) = (a == b) := rfl +@[simp] theorem mqEq_text (a b : String) : mqEq (Val.text a) (Val.text b) = (a == b) := rfl + +-- ---------------------------------------------------------------- 分支矛盾 + +/-- 同一值对同一阈值既 `> n` 又 `≤ n`:分支矛盾(simp_all 消掉互斥分支)。 -/ +@[simp] theorem mqGt_mqLe_false {v : Val} {n : Int} + (h1 : mqGt v (Val.int n) = true) (h2 : mqLe v (Val.int n) = true) : False := by + cases v with + | int x => + simp only [mqGt, mqLe, decide_eq_true_eq] at h1 h2 + omega + | _ => simp [mqGt] at h1 + +@[simp] theorem mqLe_mqGt_false {v : Val} {n : Int} + (h1 : mqLe v (Val.int n) = true) (h2 : mqGt v (Val.int n) = true) : False := by + cases v with + | int x => + simp only [mqLe, mqGt, decide_eq_true_eq] at h1 h2 + omega + | _ => simp [mqGt] at h2 + +@[simp] theorem mqLt_mqGe_false {v : Val} {n : Int} + (h1 : mqLt v (Val.int n) = true) (h2 : mqGe v (Val.int n) = true) : False := by + cases v with + | int x => + simp only [mqLt, mqGe, decide_eq_true_eq] at h1 h2 + omega + | _ => simp [mqLt] at h1 + +@[simp] theorem mqGe_mqLt_false {v : Val} {n : Int} + (h1 : mqGe v (Val.int n) = true) (h2 : mqLt v (Val.int n) = true) : False := by + cases v with + | int x => + simp only [mqGe, mqLt, decide_eq_true_eq] at h1 h2 + omega + | _ => simp [mqLt] at h2 + +-- ---------------------------------------------------------------- 布尔 + +def mqAnd (a b : Bool) : Bool := a && b +def mqOr (a b : Bool) : Bool := a || b +def mqNot (b : Bool) : Bool := !b + +-- ---------------------------------------------------------------- 列表 + +/-- Val 列表的 `包含`(谓词;轨迹上的包含由生成文件按 `Op.name` 内联)。 -/ +def mqContains (xs v : Val) : Bool := + match xs with + | .list ys => ys.contains v + | _ => false + +/-- Val 列表的长度(`Val.int` 面)。 -/ +def mqLen : Val → Val + | .list ys => .int ys.length + | _ => .none + +/-- 从 `Val.int` 取 `Nat`(供 `长度` 比较等)。 -/ +def mqNatOf : Val → Nat + | .int n => n.toNat + | _ => 0 + +/-- Val 列表拼接。 -/ +def mqAppend : Val → Val → Val + | .list a, .list b => .list (a ++ b) + | _, _ => .none + +-- ---------------------------------------------------------------- lib/result + +/-- `result.ok(v)`:Val 字面映射构造(§12 偏差 2)。 -/ +def mqResultOk (v : Val) : Val := + .map [("ok", .bool true), ("value", v), ("error", .none)] + +/-- `result.error(code, message, operation)`。 -/ +def mqResultError (code message operation : Val) : Val := + .map [("ok", .bool false), ("value", .none), + ("error", .map [("code", code), ("message", message), ("operation", operation)])] + +/-- `result.value_or(r, dflt)`。 -/ +def mqValueOr (r dflt : Val) : Val := + match mqAccess r "ok" with + | .bool true => mqAccess r "value" + | _ => dflt + +end MarqdoProof diff --git a/doc/verification/skill-proof/README.md b/doc/verification/skill-proof/README.md new file mode 100755 index 0000000..d68cc3e --- /dev/null +++ b/doc/verification/skill-proof/README.md @@ -0,0 +1,58 @@ +# MarqdoProof — `marqdo prove` 生成代码的语义底座 + +`MarqdoProof.lean` 是生成 Lean 定理所依赖的全部符号(`Val`、`mq*` 辅助函数、 +矛盾引理),无公理、无 `opaque`。发布/校验环境把它作为 lake 项目 +`verification/skill-proof/` 安装(仓库 checkout 中该目录属 root,构建期 +落在 `target/proof/skill-proof/`,两者内容一致)。 + +## 构建与校验(Lean 4.35.0) + +```sh +export PATH=/bin:$PATH # lean 4.35.0 + lake 5.0.0 +cd verification/skill-proof +lake build # 产出 MarqdoProof.olean +lake env lean .lean # exit 0 且无 error ⇒ 该文件全部定理成立 +``` + +## 生成文件的形状(emit.rs 契约) + +- 命名空间强制 ASCII:`审批.mq.md` → `namespace Generated.u5BA1u6279_mq` + (Lean 的 `namespace` 命令只接受 ASCII 名字)。 +- 非 ASCII 标识符一律 guillemet:`def «审批单»`;guillemet 内 `:` 替换为 `_` + (`«调用_人工审核»`)。`Op.name` 的字符串显示保持原始 id。 +- 定理形如: + ```lean + theorem «审批单.大额必经人工» (env : Env) («金额» : Val) («等级» : Val) + («h_前提» : mqTruth (mqGt «金额» (Val.int 10000))) : + ∀ («结果» : Val) («轨迹» : List Op), + ((«结果», «轨迹») = «审批单» env [] «金额» «等级») → + mqTruth ((«轨迹».map Op.name).contains "人工审核") := by + intro «结果» «轨迹» h_run + unfold «审批单» at h_run + try split at h_run + all_goals + simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqEq] + try + first + | exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim + | … + | omega + ``` +- run 等式方向 `(结果, 轨迹) = run env [] …`:输出变量在左,simp_all 才能把 + 输出替换进目标;run 从空轨迹起跑(§2:轨迹是语法产物,函数入口为空)。 + +## 实测结论(2026-11-16,Lean 4.35.0 / lake 5.0.0) + +- 业务样例(审批.mq.md,3 条定理):`lake env lean` 0 error 0 warning,全部证明。 +- 6 个带定理的测试夹具 + 业务样例:**7/7 全部 proved**(驱动脚本三态分类: + proved / unproved / lean-error)。 +- 首轮曾发现 `p2_len` 夹具断言写错(纯函数却断言两步轨迹)被 Lean 如实拒绝—— + 修复方向是改对断言,不是放宽判定:"绝不 lean 无法证明的 marqdo 可以证明"。 + +## 驱动集成(P1,2026-11-17) + +`marqdo prove` 的判定驱动把本库**内嵌**进 marqdo 二进制(`include_str!`), +按内容哈希落盘缓存后直接 `lean -o MarqdoProof.olean` 构建,被检模块经 +`LEAN_PATH` 引用——运行时只依赖 `lean` 一个二进制,不需要 lake/elan。 +本目录的 lakefile 保留给人与 CI 使用;`scripts/check-proof-library.sh` +负责校验内嵌副本与本目录逐字节一致,并输出库 sha256(写入判定证书)。 diff --git a/doc/verification/skill-proof/lakefile.toml b/doc/verification/skill-proof/lakefile.toml new file mode 100755 index 0000000..25f4ec3 --- /dev/null +++ b/doc/verification/skill-proof/lakefile.toml @@ -0,0 +1,6 @@ +name = "skill-proof" +version = "0.1.0" +defaultTargets = ["MarqdoProof"] + +[[lean_lib]] +name = "MarqdoProof" diff --git a/doc/verification/skill-proof/lean-toolchain b/doc/verification/skill-proof/lean-toolchain new file mode 100644 index 0000000..a6aff06 --- /dev/null +++ b/doc/verification/skill-proof/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/doc/verification/skill-proof/run-lean-check.sh b/doc/verification/skill-proof/run-lean-check.sh new file mode 100755 index 0000000..19562d2 --- /dev/null +++ b/doc/verification/skill-proof/run-lean-check.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# run-lean-check.sh — 用真实 Lean 4.35.0 校验 `marqdo prove --emit` 的产物。 +# 用法: run-lean-check.sh ... +# 每个文件: prove 生成 → lake env lean 编译 → 按退出状态分类。 +set -u +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" # /workspace/marqdo +LEAN_BIN="$ROOT/target/toolchain/lean-4.35.0-linux/bin" +PROOF_DIR="$ROOT/target/proof/skill-proof" +MARQDO="$ROOT/target/node/debug/marqdo" +export PATH="$LEAN_BIN:$PATH" + +[ -x "$MARQDO" ] || { echo "marqdo binary missing: $MARQDO" >&2; exit 2; } +[ -f "$PROOF_DIR/.lake/build/lib/lean/MarqdoProof.olean" ] || \ + { (cd "$PROOF_DIR" && lake build) >&2 || exit 2; } + +declare -A RESULT +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +for src in "$@"; do + name="$(basename "$src" .mq.md)" + outdir="$work/$name" + mkdir -p "$outdir" + if ! "$MARQDO" prove "$src" --emit "$outdir" >/dev/null 2>&1; then + RESULT[$src]="emit-failed" + continue + fi + lean_file="$(find "$outdir" -name '*.lean' | head -1)" + [ -n "$lean_file" ] || { RESULT[$src]="no-lean-emitted"; continue; } + cp "$lean_file" "$PROOF_DIR/Generated/_check.lean" + log="$work/$name.leanlog" + (cd "$PROOF_DIR" && lake env lean Generated/_check.lean) >"$log" 2>&1 + rc=$? + rm -f "$PROOF_DIR/Generated/_check.lean" + if [ $rc -eq 0 ] && ! grep -q "error" "$log"; then + RESULT[$src]="proved" + elif grep -q "unsolved goals" "$log"; then + RESULT[$src]="unproved" + else + RESULT[$src]="lean-error" + fi +done + +fail=0 +for src in "$@"; do + status="${RESULT[$src]}" + printf '%-12s %s\n' "$status" "$src" + [ "$status" = "proved" ] || fail=1 +done +exit $fail diff --git a/examples/agent-okf-flywheel/README.md b/examples/agent-okf-flywheel/README.md old mode 100644 new mode 100755 diff --git a/examples/agent-okf-flywheel/index.mq.md b/examples/agent-okf-flywheel/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/agent-pong/README.md b/examples/agent-pong/README.md old mode 100644 new mode 100755 diff --git a/examples/agent-pong/index.mq.md b/examples/agent-pong/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/agent-sandbox-okf/README.md b/examples/agent-sandbox-okf/README.md old mode 100644 new mode 100755 diff --git a/examples/agent-sandbox-okf/index.mq.md b/examples/agent-sandbox-okf/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/README.md b/examples/browser-app/README.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/about.mq.md b/examples/browser-app/components/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/controls.mq.md b/examples/browser-app/components/controls.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/home/editor.mq.md b/examples/browser-app/components/home/editor.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/home/index.mq.md b/examples/browser-app/components/home/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/home/timer.mq.md b/examples/browser-app/components/home/timer.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/index.mq.md b/examples/browser-app/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/navigation.mq.md b/examples/browser-app/components/navigation.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/network/index.mq.md b/examples/browser-app/components/network/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/components/network/socket.mq.md b/examples/browser-app/components/network/socket.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/content/about.md b/examples/browser-app/content/about.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/content/intro.md b/examples/browser-app/content/intro.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/index.mq.md b/examples/browser-app/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/static/app.mq.md b/examples/browser-app/static/app.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/styles/index.mq.md b/examples/browser-app/styles/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/browser-app/styles/theme.tables.md b/examples/browser-app/styles/theme.tables.md old mode 100644 new mode 100755 diff --git a/examples/calculator.mq.md b/examples/calculator.mq.md old mode 100644 new mode 100755 diff --git a/examples/code-as-docs/README.md b/examples/code-as-docs/README.md old mode 100644 new mode 100755 diff --git a/examples/code-as-docs/index.mq.md b/examples/code-as-docs/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/engineering-knowledge/config/resolve.mq.md b/examples/engineering-knowledge/config/resolve.mq.md old mode 100644 new mode 100755 diff --git a/examples/engineering-knowledge/index.mq.md b/examples/engineering-knowledge/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/engineering-knowledge/knowledge/adr-022.md b/examples/engineering-knowledge/knowledge/adr-022.md old mode 100644 new mode 100755 diff --git a/examples/engineering-knowledge/knowledge/c-014.md b/examples/engineering-knowledge/knowledge/c-014.md old mode 100644 new mode 100755 diff --git a/examples/engineering-knowledge/knowledge/f-008.md b/examples/engineering-knowledge/knowledge/f-008.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/README.md b/examples/executable-knowledge/README.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/capabilities/order-pricing.mq.md b/examples/executable-knowledge/capabilities/order-pricing.mq.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/corpus/tax-policy-2026.md b/examples/executable-knowledge/corpus/tax-policy-2026.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/docs/invoice-answer.mq.md b/examples/executable-knowledge/docs/invoice-answer.mq.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/knowledge/negative-refund.mq.md b/examples/executable-knowledge/knowledge/negative-refund.mq.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/knowledge/tax-2026.mq.md b/examples/executable-knowledge/knowledge/tax-2026.mq.md old mode 100644 new mode 100755 diff --git a/examples/executable-knowledge/schema/order.mq.md b/examples/executable-knowledge/schema/order.mq.md old mode 100644 new mode 100755 diff --git a/examples/foreign-native-report/index.mq.md b/examples/foreign-native-report/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/README.md b/examples/knowledge-layers/README.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/corpus/libai.md b/examples/knowledge-layers/corpus/libai.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/libai.mq.md b/examples/knowledge-layers/libai.mq.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/main.compat.mq.md b/examples/knowledge-layers/main.compat.mq.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/main.mq.md b/examples/knowledge-layers/main.mq.md old mode 100644 new mode 100755 diff --git a/examples/knowledge-layers/poet.mq.md b/examples/knowledge-layers/poet.mq.md old mode 100644 new mode 100755 diff --git a/examples/library_audit.rs b/examples/library_audit.rs old mode 100644 new mode 100755 diff --git a/examples/linalg-least-squares/README.md b/examples/linalg-least-squares/README.md old mode 100644 new mode 100755 diff --git a/examples/linalg-least-squares/index.mq.md b/examples/linalg-least-squares/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/linalg-svd/README.md b/examples/linalg-svd/README.md old mode 100644 new mode 100755 diff --git a/examples/linalg-svd/index.mq.md b/examples/linalg-svd/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/linalg-transpose/README.md b/examples/linalg-transpose/README.md old mode 100644 new mode 100755 diff --git a/examples/linalg-transpose/index.mq.md b/examples/linalg-transpose/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/link-syntax/README.md b/examples/link-syntax/README.md old mode 100644 new mode 100755 diff --git a/examples/link-syntax/expected-link-info.json b/examples/link-syntax/expected-link-info.json old mode 100644 new mode 100755 diff --git a/examples/link-syntax/libai.mq.md b/examples/link-syntax/libai.mq.md old mode 100644 new mode 100755 diff --git a/examples/link-syntax/links.lock.yaml b/examples/link-syntax/links.lock.yaml old mode 100644 new mode 100755 diff --git a/examples/link-syntax/main.compat.mq.md b/examples/link-syntax/main.compat.mq.md old mode 100644 new mode 100755 diff --git a/examples/link-syntax/main.mq.md b/examples/link-syntax/main.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/README.md b/examples/marqdo-blog/README.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/api/echo.mq.md b/examples/marqdo-blog/api/echo.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/api/ping.mq.md b/examples/marqdo-blog/api/ping.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/components/foot.mq.md b/examples/marqdo-blog/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/components/nav.mq.md b/examples/marqdo-blog/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/components/side.mq.md b/examples/marqdo-blog/components/side.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/posts.mq.md b/examples/marqdo-blog/db/posts.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/posts.tables.md b/examples/marqdo-blog/db/posts.tables.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/schema.mq.md b/examples/marqdo-blog/db/schema.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/schema.tables.md b/examples/marqdo-blog/db/schema.tables.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/seed.mq.md b/examples/marqdo-blog/db/seed.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/db/seed.tables.md b/examples/marqdo-blog/db/seed.tables.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/index.mq.md b/examples/marqdo-blog/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/pages/about.mq.md b/examples/marqdo-blog/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/pages/post.mq.md b/examples/marqdo-blog/pages/post.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/public/favicon.png b/examples/marqdo-blog/public/favicon.png old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/public/favicon.svg b/examples/marqdo-blog/public/favicon.svg old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/public/live.js b/examples/marqdo-blog/public/live.js old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/public/logo.svg b/examples/marqdo-blog/public/logo.svg old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/serve.mq.md b/examples/marqdo-blog/serve.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/styles/theme.mq.md b/examples/marqdo-blog/styles/theme.mq.md old mode 100644 new mode 100755 diff --git a/examples/marqdo-blog/styles/theme.tables.md b/examples/marqdo-blog/styles/theme.tables.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/README.md b/examples/oa2026-showcase/README.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/add.mq.md b/examples/oa2026-showcase/add.mq.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/bell-circuit.svg b/examples/oa2026-showcase/bell-circuit.svg old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/bell-probs.svg b/examples/oa2026-showcase/bell-probs.svg old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/bell.mq.md b/examples/oa2026-showcase/bell.mq.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/calculus-plot.svg b/examples/oa2026-showcase/calculus-plot.svg old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/calculus.mq.md b/examples/oa2026-showcase/calculus.mq.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/foreign-node.mq.md b/examples/oa2026-showcase/foreign-node.mq.md old mode 100644 new mode 100755 diff --git a/examples/oa2026-showcase/invoice.mq.md b/examples/oa2026-showcase/invoice.mq.md old mode 100644 new mode 100755 diff --git a/examples/quantum-bell/README.md b/examples/quantum-bell/README.md old mode 100644 new mode 100755 diff --git a/examples/quantum-bell/index.mq.md b/examples/quantum-bell/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/quantum-entanglement/README.md b/examples/quantum-entanglement/README.md old mode 100644 new mode 100755 diff --git a/examples/quantum-entanglement/index.mq.md b/examples/quantum-entanglement/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/quantum-ghz/index.mq.md b/examples/quantum-ghz/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/quantum-skill-call/index.mq.md b/examples/quantum-skill-call/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/stdlib-handbook/index.mq.md b/examples/stdlib-handbook/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/stdlib-handbook/worker.mq.md b/examples/stdlib-handbook/worker.mq.md old mode 100644 new mode 100755 diff --git a/examples/stdlib-handbook/索引.mq.md b/examples/stdlib-handbook/索引.mq.md old mode 100644 new mode 100755 diff --git a/examples/stdlib_catalog.rs b/examples/stdlib_catalog.rs old mode 100644 new mode 100755 diff --git a/examples/syntax-tour/index.mq.md b/examples/syntax-tour/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/view-details.mq.md b/examples/view-details.mq.md old mode 100644 new mode 100755 diff --git a/examples/view-reading.mq.md b/examples/view-reading.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-client-site/README.md b/examples/web-client-site/README.md old mode 100644 new mode 100755 diff --git a/examples/web-client-site/index.mq.md b/examples/web-client-site/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-client-site/serve.mq.md b/examples/web-client-site/serve.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-client-site/static/client.mq.md b/examples/web-client-site/static/client.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-client-site/static/marqdo-bridge.js b/examples/web-client-site/static/marqdo-bridge.js old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/README.md b/examples/web-collab-doc/README.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/editor.mq.md b/examples/web-collab-doc/editor.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/home.mq.md b/examples/web-collab-doc/home.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/index.mq.md b/examples/web-collab-doc/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/intro.md b/examples/web-collab-doc/intro.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/static/client.mq.md b/examples/web-collab-doc/static/client.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-collab-doc/status.mq.md b/examples/web-collab-doc/status.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/README.md b/examples/web-layout-handbook-zh/README.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/api/ping.mq.md b/examples/web-layout-handbook-zh/api/ping.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/brand/content.md b/examples/web-layout-handbook-zh/components/footer/brand/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md b/examples/web-layout-handbook-zh/components/footer/brand/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/index.mq.md b/examples/web-layout-handbook-zh/components/footer/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/links/community/content.md b/examples/web-layout-handbook-zh/components/footer/links/community/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/community/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/links/docs/content.md b/examples/web-layout-handbook-zh/components/footer/links/docs/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/docs/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/footer/links/index.mq.md b/examples/web-layout-handbook-zh/components/footer/links/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/index.mq.md b/examples/web-layout-handbook-zh/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/main/content.md b/examples/web-layout-handbook-zh/components/main/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/main/index.mq.md b/examples/web-layout-handbook-zh/components/main/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/nav/content.md b/examples/web-layout-handbook-zh/components/nav/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/components/nav/index.mq.md b/examples/web-layout-handbook-zh/components/nav/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/index.mq.md b/examples/web-layout-handbook-zh/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/pages/about.mq.md b/examples/web-layout-handbook-zh/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/preview.mq.md b/examples/web-layout-handbook-zh/preview.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook-zh/serve.mq.md b/examples/web-layout-handbook-zh/serve.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/README.md b/examples/web-layout-handbook/README.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/api/ping.mq.md b/examples/web-layout-handbook/api/ping.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/brand/content.md b/examples/web-layout-handbook/components/footer/brand/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/brand/index.mq.md b/examples/web-layout-handbook/components/footer/brand/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/index.mq.md b/examples/web-layout-handbook/components/footer/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/links/community/content.md b/examples/web-layout-handbook/components/footer/links/community/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/links/community/index.mq.md b/examples/web-layout-handbook/components/footer/links/community/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/links/docs/content.md b/examples/web-layout-handbook/components/footer/links/docs/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/links/docs/index.mq.md b/examples/web-layout-handbook/components/footer/links/docs/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/footer/links/index.mq.md b/examples/web-layout-handbook/components/footer/links/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/index.mq.md b/examples/web-layout-handbook/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/main/content.md b/examples/web-layout-handbook/components/main/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/main/index.mq.md b/examples/web-layout-handbook/components/main/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/nav/content.md b/examples/web-layout-handbook/components/nav/content.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/components/nav/index.mq.md b/examples/web-layout-handbook/components/nav/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/index.mq.md b/examples/web-layout-handbook/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/pages/about.mq.md b/examples/web-layout-handbook/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/preview.mq.md b/examples/web-layout-handbook/preview.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-layout-handbook/serve.mq.md b/examples/web-layout-handbook/serve.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/README.md b/examples/web-net-site-zh/README.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/about.md b/examples/web-net-site-zh/components/content/about.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/foot.md b/examples/web-net-site-zh/components/content/foot.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/home.md b/examples/web-net-site-zh/components/content/home.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/multipart.txt b/examples/web-net-site-zh/components/content/multipart.txt old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/nav.md b/examples/web-net-site-zh/components/content/nav.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/new.md b/examples/web-net-site-zh/components/content/new.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/content/side.md b/examples/web-net-site-zh/components/content/side.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/foot.mq.md b/examples/web-net-site-zh/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/home.mq.md b/examples/web-net-site-zh/components/home.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/index.mq.md b/examples/web-net-site-zh/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/live.mq.md b/examples/web-net-site-zh/components/live.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/nav.mq.md b/examples/web-net-site-zh/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/components/side.mq.md b/examples/web-net-site-zh/components/side.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/db/articles.mq.md b/examples/web-net-site-zh/db/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/db/articles.tables.md b/examples/web-net-site-zh/db/articles.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/db/index.mq.md b/examples/web-net-site-zh/db/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/forms.mq.md b/examples/web-net-site-zh/forms.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/index.mq.md b/examples/web-net-site-zh/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/pages/about.mq.md b/examples/web-net-site-zh/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/pages/new.mq.md b/examples/web-net-site-zh/pages/new.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/pages/tools.mq.md b/examples/web-net-site-zh/pages/tools.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/public/client.mq.md b/examples/web-net-site-zh/public/client.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site-zh/styles/shell.mq.md b/examples/web-net-site-zh/styles/shell.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/README.md b/examples/web-net-site/README.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/about.md b/examples/web-net-site/components/content/about.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/foot.md b/examples/web-net-site/components/content/foot.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/home.md b/examples/web-net-site/components/content/home.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/multipart.txt b/examples/web-net-site/components/content/multipart.txt old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/nav.md b/examples/web-net-site/components/content/nav.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/new.md b/examples/web-net-site/components/content/new.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/content/side.md b/examples/web-net-site/components/content/side.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/foot.mq.md b/examples/web-net-site/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/home.mq.md b/examples/web-net-site/components/home.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/index.mq.md b/examples/web-net-site/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/live.mq.md b/examples/web-net-site/components/live.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/nav.mq.md b/examples/web-net-site/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/components/side.mq.md b/examples/web-net-site/components/side.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/db/articles.mq.md b/examples/web-net-site/db/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/db/articles.tables.md b/examples/web-net-site/db/articles.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/db/index.mq.md b/examples/web-net-site/db/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/forms.mq.md b/examples/web-net-site/forms.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/index.mq.md b/examples/web-net-site/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/pages/about.mq.md b/examples/web-net-site/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/pages/new.mq.md b/examples/web-net-site/pages/new.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/pages/tools.mq.md b/examples/web-net-site/pages/tools.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/public/client.mq.md b/examples/web-net-site/public/client.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-net-site/styles/shell.mq.md b/examples/web-net-site/styles/shell.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/README.md b/examples/web-site-zh/README.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/articles.mq.md b/examples/web-site-zh/components/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/about.md b/examples/web-site-zh/components/content/about.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/desk-footer.md b/examples/web-site-zh/components/content/desk-footer.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/desk.md b/examples/web-site-zh/components/content/desk.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/footer.md b/examples/web-site-zh/components/content/footer.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/home.md b/examples/web-site-zh/components/content/home.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/new.md b/examples/web-site-zh/components/content/new.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/content/post.md b/examples/web-site-zh/components/content/post.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/desk.mq.md b/examples/web-site-zh/components/desk.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/foot.mq.md b/examples/web-site-zh/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/head.mq.md b/examples/web-site-zh/components/head.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/index.mq.md b/examples/web-site-zh/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/intro.mq.md b/examples/web-site-zh/components/intro.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/nav.mq.md b/examples/web-site-zh/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/components/side.mq.md b/examples/web-site-zh/components/side.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/db/articles.mq.md b/examples/web-site-zh/db/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/db/articles.tables.md b/examples/web-site-zh/db/articles.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/db/index.mq.md b/examples/web-site-zh/db/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/forms.mq.md b/examples/web-site-zh/forms.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/forms.tables.md b/examples/web-site-zh/forms.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/index.mq.md b/examples/web-site-zh/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/pages/about.mq.md b/examples/web-site-zh/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/pages/desk.mq.md b/examples/web-site-zh/pages/desk.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/pages/new.mq.md b/examples/web-site-zh/pages/new.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/pages/post.mq.md b/examples/web-site-zh/pages/post.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/styles/index.mq.md b/examples/web-site-zh/styles/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/styles/shell.mq.md b/examples/web-site-zh/styles/shell.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/styles/shell.tables.md b/examples/web-site-zh/styles/shell.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/styles/view.tables.md b/examples/web-site-zh/styles/view.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site-zh/verify.mq.md b/examples/web-site-zh/verify.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/DEMO.md b/examples/web-site/DEMO.md old mode 100644 new mode 100755 diff --git a/examples/web-site/README.md b/examples/web-site/README.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/articles.mq.md b/examples/web-site/components/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/about.md b/examples/web-site/components/content/about.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/desk-footer.md b/examples/web-site/components/content/desk-footer.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/desk.md b/examples/web-site/components/content/desk.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/footer.md b/examples/web-site/components/content/footer.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/home.md b/examples/web-site/components/content/home.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/new.md b/examples/web-site/components/content/new.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/content/post.md b/examples/web-site/components/content/post.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/desk.mq.md b/examples/web-site/components/desk.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/foot.mq.md b/examples/web-site/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/head.mq.md b/examples/web-site/components/head.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/index.mq.md b/examples/web-site/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/intro.mq.md b/examples/web-site/components/intro.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/nav.mq.md b/examples/web-site/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/components/side.mq.md b/examples/web-site/components/side.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/db/articles.mq.md b/examples/web-site/db/articles.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/db/articles.tables.md b/examples/web-site/db/articles.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site/db/index.mq.md b/examples/web-site/db/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/forms.mq.md b/examples/web-site/forms.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/forms.tables.md b/examples/web-site/forms.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/pages/about.mq.md b/examples/web-site/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/pages/desk.mq.md b/examples/web-site/pages/desk.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/pages/new.mq.md b/examples/web-site/pages/new.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/pages/post.mq.md b/examples/web-site/pages/post.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/styles/index.mq.md b/examples/web-site/styles/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/styles/shell.mq.md b/examples/web-site/styles/shell.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-site/styles/shell.tables.md b/examples/web-site/styles/shell.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site/styles/view.tables.md b/examples/web-site/styles/view.tables.md old mode 100644 new mode 100755 diff --git a/examples/web-site/verify.mq.md b/examples/web-site/verify.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/README.md b/examples/web-spa-app/README.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/controls.mq.md b/examples/web-spa-app/components/controls.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/index.mq.md b/examples/web-spa-app/components/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/nav.mq.md b/examples/web-spa-app/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/panels/detail.mq.md b/examples/web-spa-app/components/panels/detail.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/panels/edit.mq.md b/examples/web-spa-app/components/panels/edit.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/panels/index.mq.md b/examples/web-spa-app/components/panels/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/components/panels/list.mq.md b/examples/web-spa-app/components/panels/list.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/index.mq.md b/examples/web-spa-app/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-spa-app/static/client.mq.md b/examples/web-spa-app/static/client.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-tenant-saas/README.md b/examples/web-tenant-saas/README.md old mode 100644 new mode 100755 diff --git a/examples/web-tenant-saas/db/index.mq.md b/examples/web-tenant-saas/db/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-tenant-saas/index.mq.md b/examples/web-tenant-saas/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-tenant-saas/intro.md b/examples/web-tenant-saas/intro.md old mode 100644 new mode 100755 diff --git a/examples/web-ws-room/home.mq.md b/examples/web-ws-room/home.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-ws-room/index.mq.md b/examples/web-ws-room/index.mq.md old mode 100644 new mode 100755 diff --git a/examples/web-ws-room/intro.md b/examples/web-ws-room/intro.md old mode 100644 new mode 100755 diff --git a/ext/VERSION b/ext/VERSION old mode 100644 new mode 100755 diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/index.mq.md b/ext/ai/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/llm/index.mq.md b/ext/ai/llm/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/llm/ollama.mq.md b/ext/ai/llm/ollama.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/llm/openai.mq.md b/ext/ai/llm/openai.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/policies/step-route.mq.md b/ext/ai/policies/step-route.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/sandbox.mq.md b/ext/ai/sandbox.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/workflow.mq.md b/ext/ai/workflow.mq.md index 52014df..8c8137b 100644 --- a/ext/ai/workflow.mq.md +++ b/ext/ai/workflow.mq.md @@ -200,6 +200,15 @@ Advance at most one step. Model text is a candidate, never direct execution. Waiting for a user returns immediately without holding a thread. A caller repeats tick after verified completion; UI replies use commit. +`tick` is the only wrapper that may execute a document child, and it only does +so after the checkpoint reports a read-only `ready_tool` step. When the action +is `waiting_input`, return the state unchanged so the host can display the +question and commit the attested answer on a later call. A blocked, uncertain +or cancelled checkpoint is returned as-is; recovery must use `retry_plan` or an +operator decision instead of silently ticking again. The returned state always +describes the committed boundary, not an optimistic guess about a running +child. + We retain **state = [Load the next action](next(id=`id`, source_revision=`source_revision`, session_id=`session_id`, principal_ref=`principal_ref`, resume_dir=`resume_dir`))**. We retain **status = [Read action status](json.get(value=`state`, key="status"))**. 1. `status` == "waiting_model" diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/智能体.mq.md b/ext/ai/智能体.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/沙盒.mq.md b/ext/ai/沙盒.mq.md old mode 100644 new mode 100755 diff --git a/ext/ai/索引.mq.md b/ext/ai/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/admin.mq.md b/ext/data/admin.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/api.mq.md b/ext/data/api.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/cache.mq.md b/ext/data/cache.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/db.mq.md b/ext/data/db.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/form.mq.md b/ext/data/form.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/index.mq.md b/ext/data/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/storage.mq.md b/ext/data/storage.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/view.mq.md b/ext/data/view.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/后台.mq.md b/ext/data/后台.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/表单.mq.md b/ext/data/表单.mq.md old mode 100644 new mode 100755 diff --git a/ext/data/视图.mq.md b/ext/data/视图.mq.md old mode 100644 new mode 100755 diff --git a/ext/engineering/index.mq.md b/ext/engineering/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/engineering/索引.mq.md b/ext/engineering/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/linalg/index.mq.md b/ext/linalg/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/linalg/linalg.mq.md b/ext/linalg/linalg.mq.md old mode 100644 new mode 100755 diff --git a/ext/linalg/索引.mq.md b/ext/linalg/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/linalg/线性代数.mq.md b/ext/linalg/线性代数.mq.md old mode 100644 new mode 100755 diff --git a/ext/net/http.mq.md b/ext/net/http.mq.md old mode 100644 new mode 100755 diff --git a/ext/net/index.mq.md b/ext/net/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/net/url.mq.md b/ext/net/url.mq.md old mode 100644 new mode 100755 diff --git a/ext/net/websocket.mq.md b/ext/net/websocket.mq.md old mode 100644 new mode 100755 diff --git a/ext/net/实时.mq.md b/ext/net/实时.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/_capability/index.mq.md b/ext/quantum/_capability/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/circuit/index.mq.md b/ext/quantum/circuit/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/density/index.mq.md b/ext/quantum/density/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/gate/index.mq.md b/ext/quantum/gate/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/index.mq.md b/ext/quantum/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/simulate/index.mq.md b/ext/quantum/simulate/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/state/index.mq.md b/ext/quantum/state/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/viz/index.mq.md b/ext/quantum/viz/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/可视化/索引.mq.md b/ext/quantum/量子/可视化/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/密度/索引.mq.md b/ext/quantum/量子/密度/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/态/索引.mq.md b/ext/quantum/量子/态/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/模拟/索引.mq.md b/ext/quantum/量子/模拟/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/电路/索引.mq.md b/ext/quantum/量子/电路/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/索引.mq.md b/ext/quantum/量子/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/能力/索引.mq.md b/ext/quantum/量子/能力/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/quantum/量子/门/索引.mq.md b/ext/quantum/量子/门/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/auth.mq.md b/ext/security/auth.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/index.mq.md b/ext/security/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/oidc.mq.md b/ext/security/oidc.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/rbac.mq.md b/ext/security/rbac.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/tenant.mq.md b/ext/security/tenant.mq.md old mode 100644 new mode 100755 diff --git a/ext/security/鉴权.mq.md b/ext/security/鉴权.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/README.md b/ext/web/README.md old mode 100644 new mode 100755 diff --git a/ext/web/_capability/index.mq.md b/ext/web/_capability/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/client/index.mq.md b/ext/web/client/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/component/index.mq.md b/ext/web/component/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/dom/index.mq.md b/ext/web/dom/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/head.mq.md b/ext/web/head.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/index.mq.md b/ext/web/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/layout/index.mq.md b/ext/web/layout/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/page/index.mq.md b/ext/web/page/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/route/index.mq.md b/ext/web/route/index.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/布局/索引.mq.md b/ext/web/布局/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/客户端/索引.mq.md b/ext/web/网页/客户端/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/文档对象模型/索引.mq.md b/ext/web/网页/文档对象模型/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/索引.mq.md b/ext/web/网页/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/组件/索引.mq.md b/ext/web/网页/组件/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/能力/索引.mq.md b/ext/web/网页/能力/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/路由/索引.mq.md b/ext/web/网页/路由/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/网页/页面/索引.mq.md b/ext/web/网页/页面/索引.mq.md old mode 100644 new mode 100755 diff --git a/ext/web/页头.mq.md b/ext/web/页头.mq.md old mode 100644 new mode 100755 diff --git a/include/marqdo_abi.h b/include/marqdo_abi.h old mode 100644 new mode 100755 diff --git a/lib/archive.mq.md b/lib/archive.mq.md old mode 100644 new mode 100755 diff --git a/lib/browser.mq.md b/lib/browser.mq.md old mode 100644 new mode 100755 diff --git a/lib/bytes.mq.md b/lib/bytes.mq.md old mode 100644 new mode 100755 diff --git a/lib/cli.mq.md b/lib/cli.mq.md old mode 100644 new mode 100755 diff --git a/lib/csv.mq.md b/lib/csv.mq.md old mode 100644 new mode 100755 diff --git a/lib/datetime.mq.md b/lib/datetime.mq.md old mode 100644 new mode 100755 diff --git a/lib/document.mq.md b/lib/document.mq.md old mode 100644 new mode 100755 diff --git a/lib/encoding.mq.md b/lib/encoding.mq.md old mode 100644 new mode 100755 diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md old mode 100644 new mode 100755 diff --git a/lib/fs.mq.md b/lib/fs.mq.md old mode 100644 new mode 100755 diff --git a/lib/hash.mq.md b/lib/hash.mq.md old mode 100644 new mode 100755 diff --git a/lib/html.mq.md b/lib/html.mq.md old mode 100644 new mode 100755 diff --git a/lib/json.mq.md b/lib/json.mq.md old mode 100644 new mode 100755 diff --git a/lib/lint/narrative.mq.md b/lib/lint/narrative.mq.md old mode 100644 new mode 100755 diff --git a/lib/log.mq.md b/lib/log.mq.md old mode 100644 new mode 100755 diff --git a/lib/math.mq.md b/lib/math.mq.md old mode 100644 new mode 100755 diff --git a/lib/net.mq.md b/lib/net.mq.md old mode 100644 new mode 100755 diff --git a/lib/path.mq.md b/lib/path.mq.md old mode 100644 new mode 100755 diff --git a/lib/plugin.mq.md b/lib/plugin.mq.md old mode 100644 new mode 100755 diff --git a/lib/re.mq.md b/lib/re.mq.md old mode 100644 new mode 100755 diff --git a/lib/result.mq.md b/lib/result.mq.md old mode 100644 new mode 100755 diff --git a/lib/secrets.mq.md b/lib/secrets.mq.md old mode 100644 new mode 100755 diff --git a/lib/stats.mq.md b/lib/stats.mq.md old mode 100644 new mode 100755 diff --git a/lib/subtask.mq.md b/lib/subtask.mq.md old mode 100644 new mode 100755 diff --git a/lib/sys.mq.md b/lib/sys.mq.md old mode 100644 new mode 100755 diff --git a/lib/table.mq.md b/lib/table.mq.md old mode 100644 new mode 100755 diff --git a/lib/text.mq.md b/lib/text.mq.md old mode 100644 new mode 100755 diff --git a/lib/time.mq.md b/lib/time.mq.md old mode 100644 new mode 100755 diff --git a/lib/toml.mq.md b/lib/toml.mq.md old mode 100644 new mode 100755 diff --git a/lib/url.mq.md b/lib/url.mq.md old mode 100644 new mode 100755 diff --git a/lib/uuid.mq.md b/lib/uuid.mq.md old mode 100644 new mode 100755 diff --git a/lib/writeback.mq.md b/lib/writeback.mq.md old mode 100644 new mode 100755 diff --git a/lib/命令行.mq.md b/lib/命令行.mq.md old mode 100644 new mode 100755 diff --git a/lib/哈希.mq.md b/lib/哈希.mq.md old mode 100644 new mode 100755 diff --git a/lib/地址.mq.md b/lib/地址.mq.md old mode 100644 new mode 100755 diff --git a/lib/外联.mq.md b/lib/外联.mq.md old mode 100644 new mode 100755 diff --git a/lib/子任务.mq.md b/lib/子任务.mq.md old mode 100644 new mode 100755 diff --git a/lib/字节.mq.md b/lib/字节.mq.md old mode 100644 new mode 100755 diff --git a/lib/归档.mq.md b/lib/归档.mq.md old mode 100644 new mode 100755 diff --git a/lib/插件.mq.md b/lib/插件.mq.md old mode 100644 new mode 100755 diff --git a/lib/数学.mq.md b/lib/数学.mq.md old mode 100644 new mode 100755 diff --git a/lib/文件.mq.md b/lib/文件.mq.md old mode 100644 new mode 100755 diff --git a/lib/文本.mq.md b/lib/文本.mq.md old mode 100644 new mode 100755 diff --git a/lib/文档.mq.md b/lib/文档.mq.md old mode 100644 new mode 100755 diff --git a/lib/日志.mq.md b/lib/日志.mq.md old mode 100644 new mode 100755 diff --git a/lib/日期时间.mq.md b/lib/日期时间.mq.md old mode 100644 new mode 100755 diff --git a/lib/时间.mq.md b/lib/时间.mq.md old mode 100644 new mode 100755 diff --git a/lib/机密.mq.md b/lib/机密.mq.md old mode 100644 new mode 100755 diff --git a/lib/标识.mq.md b/lib/标识.mq.md old mode 100644 new mode 100755 diff --git a/lib/正则.mq.md b/lib/正则.mq.md old mode 100644 new mode 100755 diff --git a/lib/浏览器.mq.md b/lib/浏览器.mq.md old mode 100644 new mode 100755 diff --git a/lib/系统.mq.md b/lib/系统.mq.md old mode 100644 new mode 100755 diff --git a/lib/结果.mq.md b/lib/结果.mq.md old mode 100644 new mode 100755 diff --git a/lib/统计.mq.md b/lib/统计.mq.md old mode 100644 new mode 100755 diff --git a/lib/编码.mq.md b/lib/编码.mq.md old mode 100644 new mode 100755 diff --git a/lib/网络.mq.md b/lib/网络.mq.md old mode 100644 new mode 100755 diff --git a/lib/自写回.mq.md b/lib/自写回.mq.md old mode 100644 new mode 100755 diff --git a/lib/表.mq.md b/lib/表.mq.md old mode 100644 new mode 100755 diff --git a/lib/超文本.mq.md b/lib/超文本.mq.md old mode 100644 new mode 100755 diff --git a/lib/路径.mq.md b/lib/路径.mq.md old mode 100644 new mode 100755 diff --git a/lib/逗号表.mq.md b/lib/逗号表.mq.md old mode 100644 new mode 100755 diff --git a/lib/配置表.mq.md b/lib/配置表.mq.md old mode 100644 new mode 100755 diff --git a/man-doc/README.md b/man-doc/README.md old mode 100644 new mode 100755 diff --git a/man-test/ext/agent-plan.mq.md b/man-test/ext/agent-plan.mq.md old mode 100644 new mode 100755 diff --git a/man-test/index.mq.md b/man-test/index.mq.md old mode 100644 new mode 100755 diff --git a/man-test/keyword/bool.mq.md b/man-test/keyword/bool.mq.md old mode 100644 new mode 100755 diff --git a/man-test/keyword/input.mq.md b/man-test/keyword/input.mq.md old mode 100644 new mode 100755 diff --git a/man-test/keyword/print.mq.md b/man-test/keyword/print.mq.md old mode 100644 new mode 100755 diff --git a/man-test/lib/math.mq.md b/man-test/lib/math.mq.md old mode 100644 new mode 100755 diff --git a/man-test/lib/writeback.mq.md b/man-test/lib/writeback.mq.md old mode 100644 new mode 100755 diff --git a/man-test/structure/branch.mq.md b/man-test/structure/branch.mq.md old mode 100644 new mode 100755 diff --git a/man-test/structure/loop.mq.md b/man-test/structure/loop.mq.md old mode 100644 new mode 100755 diff --git a/plugins/agent/Cargo.toml b/plugins/agent/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/agent/src/context_pack.rs b/plugins/agent/src/context_pack.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/corpus.rs b/plugins/agent/src/corpus.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/effects.rs b/plugins/agent/src/effects.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/eng.rs b/plugins/agent/src/eng.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/error.rs b/plugins/agent/src/error.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/kb.rs b/plugins/agent/src/kb.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/lib.rs b/plugins/agent/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/mcp_client.rs b/plugins/agent/src/mcp_client.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/mcp_server.rs b/plugins/agent/src/mcp_server.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/memory.rs b/plugins/agent/src/memory.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/output.rs b/plugins/agent/src/output.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/resume.rs b/plugins/agent/src/resume.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/route.rs b/plugins/agent/src/route.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/sandbox.rs b/plugins/agent/src/sandbox.rs old mode 100644 new mode 100755 diff --git a/plugins/agent/src/tools.rs b/plugins/agent/src/tools.rs old mode 100644 new mode 100755 diff --git a/plugins/demo/Cargo.toml b/plugins/demo/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/demo/src/lib.rs b/plugins/demo/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/engineering/Cargo.toml b/plugins/engineering/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/engineering/src/lib.rs b/plugins/engineering/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/Cargo.toml b/plugins/linalg/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/complex.rs b/plugins/linalg/src/complex.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/dense.rs b/plugins/linalg/src/dense.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/draw.rs b/plugins/linalg/src/draw.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/factor.rs b/plugins/linalg/src/factor.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/lib.rs b/plugins/linalg/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/matexpr.rs b/plugins/linalg/src/matexpr.rs old mode 100644 new mode 100755 diff --git a/plugins/linalg/src/metrics.rs b/plugins/linalg/src/metrics.rs old mode 100644 new mode 100755 diff --git a/plugins/llm/Cargo.toml b/plugins/llm/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/llm/src/lib.rs b/plugins/llm/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/quantum/Cargo.toml b/plugins/quantum/Cargo.toml old mode 100644 new mode 100755 diff --git a/plugins/quantum/src/draw.rs b/plugins/quantum/src/draw.rs old mode 100644 new mode 100755 diff --git a/plugins/quantum/src/lib.rs b/plugins/quantum/src/lib.rs old mode 100644 new mode 100755 diff --git a/plugins/quantum/src/linalg.rs b/plugins/quantum/src/linalg.rs old mode 100644 new mode 100755 diff --git a/plugins/quantum/src/sim.rs b/plugins/quantum/src/sim.rs old mode 100644 new mode 100755 diff --git a/plugins/web/README.md b/plugins/web/README.md old mode 100644 new mode 100755 diff --git a/plugins/web/abi/marqdo_abi.h b/plugins/web/abi/marqdo_abi.h old mode 100644 new mode 100755 diff --git a/plugins/web/abi/marqdo_abi_cgo.h b/plugins/web/abi/marqdo_abi_cgo.h old mode 100644 new mode 100755 diff --git a/plugins/web/abi_artifact.go b/plugins/web/abi_artifact.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_page.go b/plugins/web/abi_page.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w10.go b/plugins/web/abi_w10.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w12.go b/plugins/web/abi_w12.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w6.go b/plugins/web/abi_w6.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w7.go b/plugins/web/abi_w7.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w8.go b/plugins/web/abi_w8.go old mode 100644 new mode 100755 diff --git a/plugins/web/abi_w9.go b/plugins/web/abi_w9.go old mode 100644 new mode 100755 diff --git a/plugins/web/go.mod b/plugins/web/go.mod old mode 100644 new mode 100755 diff --git a/plugins/web/go.sum b/plugins/web/go.sum old mode 100644 new mode 100755 diff --git a/plugins/web/internal/apikey/apikey.go b/plugins/web/internal/apikey/apikey.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/apikey/apikey_test.go b/plugins/web/internal/apikey/apikey_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/app/app_test.go b/plugins/web/internal/app/app_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/artifact/artifact.go b/plugins/web/internal/artifact/artifact.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/artifact/artifact_test.go b/plugins/web/internal/artifact/artifact_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/artifact/head.go b/plugins/web/internal/artifact/head.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/artifact/head_test.go b/plugins/web/internal/artifact/head_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/artifact/slot_test.go b/plugins/web/internal/artifact/slot_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/assets/assets.go b/plugins/web/internal/assets/assets.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/assets/assets_test.go b/plugins/web/internal/assets/assets_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/auth/auth.go b/plugins/web/internal/auth/auth.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/auth/auth_test.go b/plugins/web/internal/auth/auth_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/cache/cache.go b/plugins/web/internal/cache/cache.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/cache/cache_test.go b/plugins/web/internal/cache/cache_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose.go b/plugins/web/internal/compose/compose.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_auth.go b/plugins/web/internal/compose/compose_auth.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_form_load.go b/plugins/web/internal/compose/compose_form_load.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_form_load_test.go b/plugins/web/internal/compose/compose_form_load_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_intro.go b/plugins/web/internal/compose/compose_intro.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_list_test.go b/plugins/web/internal/compose/compose_list_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_nav_brand.go b/plugins/web/internal/compose/compose_nav_brand.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_nav_brand_test.go b/plugins/web/internal/compose/compose_nav_brand_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/compose/compose_test.go b/plugins/web/internal/compose/compose_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/db.go b/plugins/web/internal/db/db.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/db_test.go b/plugins/web/internal/db/db_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/dialect.go b/plugins/web/internal/db/dialect.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/fts.go b/plugins/web/internal/db/fts.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/migrate.go b/plugins/web/internal/db/migrate.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/db/txn.go b/plugins/web/internal/db/txn.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/form/form.go b/plugins/web/internal/form/form.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/form/form_test.go b/plugins/web/internal/form/form_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/form/source.go b/plugins/web/internal/form/source.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/form/source_test.go b/plugins/web/internal/form/source_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/auth.go b/plugins/web/internal/httpx/auth.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/auth_custom.go b/plugins/web/internal/httpx/auth_custom.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/auth_oidc.go b/plugins/web/internal/httpx/auth_oidc.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/auth_test.go b/plugins/web/internal/httpx/auth_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/cancel_bridge_test.go b/plugins/web/internal/httpx/cancel_bridge_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/drain_forward_test.go b/plugins/web/internal/httpx/drain_forward_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/inspection.go b/plugins/web/internal/httpx/inspection.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/inspection_test.go b/plugins/web/internal/httpx/inspection_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/listen_test.go b/plugins/web/internal/httpx/listen_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_artifact.go b/plugins/web/internal/httpx/routes_artifact.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_invoke.go b/plugins/web/internal/httpx/routes_invoke.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_media.go b/plugins/web/internal/httpx/routes_media.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_media_test.go b/plugins/web/internal/httpx/routes_media_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_proxy.go b/plugins/web/internal/httpx/routes_proxy.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_runtime.go b/plugins/web/internal/httpx/routes_runtime.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_ws.go b/plugins/web/internal/httpx/routes_ws.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/routes_ws_test.go b/plugins/web/internal/httpx/routes_ws_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/runtime_routes_test.go b/plugins/web/internal/httpx/runtime_routes_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/sse_bridge_test.go b/plugins/web/internal/httpx/sse_bridge_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/view_resources.go b/plugins/web/internal/httpx/view_resources.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/httpx/view_resources_test.go b/plugins/web/internal/httpx/view_resources_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/invoke/invoke.go b/plugins/web/internal/invoke/invoke.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/invoke/invoke_test.go b/plugins/web/internal/invoke/invoke_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/middleware/middleware.go b/plugins/web/internal/middleware/middleware.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/middleware/middleware_test.go b/plugins/web/internal/middleware/middleware_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/oidc/oidc.go b/plugins/web/internal/oidc/oidc.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/oidc/oidc_test.go b/plugins/web/internal/oidc/oidc_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/page/page.go b/plugins/web/internal/page/page.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/page/page_test.go b/plugins/web/internal/page/page_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/password/password.go b/plugins/web/internal/password/password.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/password/password_test.go b/plugins/web/internal/password/password_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/plugin/host.go b/plugins/web/internal/plugin/host.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/proxy/proxy.go b/plugins/web/internal/proxy/proxy.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/proxy/proxy_test.go b/plugins/web/internal/proxy/proxy_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ratelimit/ratelimit.go b/plugins/web/internal/ratelimit/ratelimit.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ratelimit/ratelimit_test.go b/plugins/web/internal/ratelimit/ratelimit_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/rbac/rbac.go b/plugins/web/internal/rbac/rbac.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/rbac/rbac_test.go b/plugins/web/internal/rbac/rbac_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/artifact_data_test.go b/plugins/web/internal/render/artifact_data_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/auth_inject.go b/plugins/web/internal/render/auth_inject.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/auth_inject_test.go b/plugins/web/internal/render/auth_inject_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/chrome_brand.go b/plugins/web/internal/render/chrome_brand.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/chrome_brand_test.go b/plugins/web/internal/render/chrome_brand_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/document_posts_resolve_test.go b/plugins/web/internal/render/document_posts_resolve_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/markdown.go b/plugins/web/internal/render/markdown.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/rail_test.go b/plugins/web/internal/render/rail_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/render.go b/plugins/web/internal/render/render.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/render_test.go b/plugins/web/internal/render/render_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/render/resolve_params_test.go b/plugins/web/internal/render/resolve_params_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/rss/rss.go b/plugins/web/internal/rss/rss.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/rss/rss_test.go b/plugins/web/internal/rss/rss_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/session/session.go b/plugins/web/internal/session/session.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/session/session_test.go b/plugins/web/internal/session/session_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/sitemap/sitemap.go b/plugins/web/internal/sitemap/sitemap.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/sitemap/sitemap_test.go b/plugins/web/internal/sitemap/sitemap_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/storage/storage.go b/plugins/web/internal/storage/storage.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/storage/storage_test.go b/plugins/web/internal/storage/storage_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/style/style.go b/plugins/web/internal/style/style.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/style/style_test.go b/plugins/web/internal/style/style_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/table/table.go b/plugins/web/internal/table/table.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/table/table_test.go b/plugins/web/internal/table/table_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/tenant/tenant.go b/plugins/web/internal/tenant/tenant.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/tenant/tenant_test.go b/plugins/web/internal/tenant/tenant_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/upload/upload.go b/plugins/web/internal/upload/upload.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/upload/upload_test.go b/plugins/web/internal/upload/upload_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/connect.go b/plugins/web/internal/ws/connect.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/hub.go b/plugins/web/internal/ws/hub.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/hub_test.go b/plugins/web/internal/ws/hub_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/mode.go b/plugins/web/internal/ws/mode.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/route.go b/plugins/web/internal/ws/route.go old mode 100644 new mode 100755 diff --git a/plugins/web/internal/ws/route_test.go b/plugins/web/internal/ws/route_test.go old mode 100644 new mode 100755 diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go old mode 100644 new mode 100755 diff --git a/public/00-welcome-plot-1.svg b/public/00-welcome-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md old mode 100644 new mode 100755 diff --git a/public/00-欢迎-plot-1.svg b/public/00-欢迎-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md old mode 100644 new mode 100755 diff --git a/public/README.md b/public/README.md old mode 100644 new mode 100755 diff --git a/public/features/01-phase-i-treewalk.mq.md b/public/features/01-phase-i-treewalk.mq.md old mode 100644 new mode 100755 diff --git a/public/features/01-树遍历.mq.md b/public/features/01-树遍历.mq.md old mode 100644 new mode 100755 diff --git a/public/features/02-bytecode.mq.md b/public/features/02-bytecode.mq.md old mode 100644 new mode 100755 diff --git a/public/features/02-字节码.mq.md b/public/features/02-字节码.mq.md old mode 100644 new mode 100755 diff --git a/public/features/03-view-and-docs.mq.md b/public/features/03-view-and-docs.mq.md old mode 100644 new mode 100755 diff --git a/public/features/03-view与文档.mq.md b/public/features/03-view与文档.mq.md old mode 100644 new mode 100755 diff --git a/public/features/04-objects.mq.md b/public/features/04-objects.mq.md old mode 100644 new mode 100755 diff --git a/public/features/04-对象.mq.md b/public/features/04-对象.mq.md old mode 100644 new mode 100755 diff --git a/public/features/05-extensions.mq.md b/public/features/05-extensions.mq.md old mode 100644 new mode 100755 diff --git a/public/features/05-扩展.mq.md b/public/features/05-扩展.mq.md old mode 100644 new mode 100755 diff --git a/public/features/06-quantum-plot-1.svg b/public/features/06-quantum-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/features/06-quantum-plot-2.svg b/public/features/06-quantum-plot-2.svg old mode 100644 new mode 100755 diff --git a/public/features/06-quantum.mq.md b/public/features/06-quantum.mq.md old mode 100644 new mode 100755 diff --git a/public/features/06-量子-plot-1.svg b/public/features/06-量子-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/features/06-量子-plot-2.svg b/public/features/06-量子-plot-2.svg old mode 100644 new mode 100755 diff --git a/public/features/06-量子.mq.md b/public/features/06-量子.mq.md old mode 100644 new mode 100755 diff --git a/public/features/07-linalg.mq.md b/public/features/07-linalg.mq.md old mode 100644 new mode 100755 diff --git a/public/features/07-线性代数.mq.md b/public/features/07-线性代数.mq.md old mode 100644 new mode 100755 diff --git a/public/features/08-re-encoding.mq.md b/public/features/08-re-encoding.mq.md old mode 100644 new mode 100755 diff --git a/public/features/08-正则编解码.mq.md b/public/features/08-正则编解码.mq.md old mode 100644 new mode 100755 diff --git a/public/features/09-path-fs.mq.md b/public/features/09-path-fs.mq.md old mode 100644 new mode 100755 diff --git a/public/features/09-路径文件.mq.md b/public/features/09-路径文件.mq.md old mode 100644 new mode 100755 diff --git a/public/features/10-hash-secrets.mq.md b/public/features/10-hash-secrets.mq.md old mode 100644 new mode 100755 diff --git a/public/features/10-哈希机密.mq.md b/public/features/10-哈希机密.mq.md old mode 100644 new mode 100755 diff --git a/public/features/11-csv-text.mq.md b/public/features/11-csv-text.mq.md old mode 100644 new mode 100755 diff --git a/public/features/11-逗号表文本.mq.md b/public/features/11-逗号表文本.mq.md old mode 100644 new mode 100755 diff --git a/public/features/12-list-cli.mq.md b/public/features/12-list-cli.mq.md old mode 100644 new mode 100755 diff --git a/public/features/12-列表命令行.mq.md b/public/features/12-列表命令行.mq.md old mode 100644 new mode 100755 diff --git a/public/features/13-log-uuid.mq.md b/public/features/13-log-uuid.mq.md old mode 100644 new mode 100755 diff --git a/public/features/13-日志标识.mq.md b/public/features/13-日志标识.mq.md old mode 100644 new mode 100755 diff --git a/public/features/14-datetime-url.mq.md b/public/features/14-datetime-url.mq.md old mode 100644 new mode 100755 diff --git a/public/features/14-日期时间地址.mq.md b/public/features/14-日期时间地址.mq.md old mode 100644 new mode 100755 diff --git a/public/features/15-toml-html-encoding.mq.md b/public/features/15-toml-html-encoding.mq.md old mode 100644 new mode 100755 diff --git a/public/features/15-配置表超文本编码.mq.md b/public/features/15-配置表超文本编码.mq.md old mode 100644 new mode 100755 diff --git a/public/features/16-fs-mid2.mq.md b/public/features/16-fs-mid2.mq.md old mode 100644 new mode 100755 diff --git a/public/features/16-文件mid2.mq.md b/public/features/16-文件mid2.mq.md old mode 100644 new mode 100755 diff --git a/public/features/17-stats-log.mq.md b/public/features/17-stats-log.mq.md old mode 100644 new mode 100755 diff --git a/public/features/17-统计日志.mq.md b/public/features/17-统计日志.mq.md old mode 100644 new mode 100755 diff --git a/public/features/18-AI原生闭环.mq.md b/public/features/18-AI原生闭环.mq.md old mode 100644 new mode 100755 diff --git a/public/features/18-ai-native-loop.mq.md b/public/features/18-ai-native-loop.mq.md old mode 100644 new mode 100755 diff --git a/public/features/19-foreign-view-cells.mq.md b/public/features/19-foreign-view-cells.mq.md old mode 100644 new mode 100755 diff --git a/public/features/19-外联视图单元.mq.md b/public/features/19-外联视图单元.mq.md old mode 100644 new mode 100755 diff --git a/public/features/20-OKF与EKC.mq.md b/public/features/20-OKF与EKC.mq.md old mode 100644 new mode 100755 diff --git a/public/features/20-okf-ekc.mq.md b/public/features/20-okf-ekc.mq.md old mode 100644 new mode 100755 diff --git a/public/features/21-persistence.mq.md b/public/features/21-persistence.mq.md old mode 100644 new mode 100755 diff --git a/public/features/21-持久化.mq.md b/public/features/21-持久化.mq.md old mode 100644 new mode 100755 diff --git a/public/features/22-call.mq.md b/public/features/22-call.mq.md old mode 100644 new mode 100755 diff --git a/public/features/22-函数调用.mq.md b/public/features/22-函数调用.mq.md old mode 100644 new mode 100755 diff --git a/public/features/23-prove.mq.md b/public/features/23-prove.mq.md new file mode 100644 index 0000000..58e0137 --- /dev/null +++ b/public/features/23-prove.mq.md @@ -0,0 +1,61 @@ +--- +markup: occlusion +import: + result: ../../lib/result.mq.md +title: Prove what a page claims: theorem tables judged by Lean 4 +description: v2.8.0 marqdo prove compiles theorem tables to Lean 4 and judges them. Offline symbolic execution works without a toolchain and never outruns Lean. +--- + +# main + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | any | None; execute this page's documented steps in order and observe their output or stated effects | + +v2.8.0 adds one command: `marqdo prove`. A theorem table in a knowledge file is compiled to Lean 4 and judged automatically. The claim stops being prose that a reader agrees with and becomes a statement a proof assistant checks. + +```text +marqdo prove examples/approval.mq.md --json +``` + +The pipeline has six stages: load, lower to an intermediate representation, type the claim, generate a Lean module, judge it, and issue a certificate. Judging has two layers. Offline symbolic execution runs first — path enumeration over the pure fragment, milliseconds, no toolchain required. When a Lean toolchain is available it re-checks the emitted module and upgrades the verdict. + +The status ladder is honest by construction: `proved > checked > unverified > rejected > unproved > error`. Offline `checked` is a decided trace for the explored paths, never a proof; `proved` exists only when Lean says so. Without a toolchain the verdict stays at `checked` or `unverified` and the process exits zero — advisory, not silent. `--require-lean` flips unjudged states into failures for CI. + +A false theorem does not get a shrug. The judge produces a counterexample witness — concrete input values that walk the function down a path where the conclusion fails — and points back at the theorem-table row. + +The boundary that makes this trustworthy is monotonicity: whatever the offline layer claims, Lean must be able to confirm. If the offline verdict says checked and Lean cannot prove it, or a counterexample is proven away, the command fails with `proof.divergence` and exits non-zero. A judger defect fails loudly; a green light is never defended. + +The fragment is deliberately small: pure functions, branch comparisons, call-trace shapes, constructor structure, interval restatements. Loops report `proof.foreach_pending` instead of pretending. Cross-module calls stay opaque until assumption tables arrive. Every simplification is recorded in the design docs, because a proof system that hides its boundaries is marketing, not verification. + +This page runs — the theorems below live in the same file that explains them. `轨迹` is the implicit call trace of the function: the big-amount path must pass through 复核, opaque calls append to it, and inlined `result.ok` constructors do not. + +# 台账 + +## 记一笔 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 记账金额(元) | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经复核 | 包含(轨迹, "复核") | 金额 > 10000 | auto | +| 大额单次外呼 | 长度(轨迹) = 1 | 金额 > 10000 | auto | +| 必有回执 | 结果.ok = True | | auto | + +1. 当`金额`小于等于10000时 + **回执 = [直接记账](result.ok(value="记"))** +2. * + **复核结论 = [转复核](复核(金额=`金额`))** + **回执 = [采纳](result.ok(value=`复核结论`))** + +*回执* + +## 复核 ++ `金额` + +**复核回执 = [复核通过](result.ok(value="复核"))** + +*复核回执* diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/input.mq.md b/public/keywords/input.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/print.mq.md b/public/keywords/print.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/stdlib.mq.md b/public/keywords/stdlib.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/内核双名.mq.md b/public/keywords/内核双名.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/布尔逻辑.mq.md b/public/keywords/布尔逻辑.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/打印.mq.md b/public/keywords/打印.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/标准库.mq.md b/public/keywords/标准库.mq.md old mode 100644 new mode 100755 diff --git a/public/keywords/输入.mq.md b/public/keywords/输入.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/00-overview.mq.md b/public/stdlib/00-overview.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/00-索引.mq.md b/public/stdlib/00-索引.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/foreign.mq.md b/public/stdlib/foreign.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/fs.mq.md b/public/stdlib/fs.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/json.mq.md b/public/stdlib/json.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/math-plot-1.svg b/public/stdlib/math-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/stdlib/math.mq.md b/public/stdlib/math.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/net.mq.md b/public/stdlib/net.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/plugin.mq.md b/public/stdlib/plugin.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/subtask.mq.md b/public/stdlib/subtask.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/sys.mq.md b/public/stdlib/sys.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/text.mq.md b/public/stdlib/text.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/time.mq.md b/public/stdlib/time.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/writeback.mq.md b/public/stdlib/writeback.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/外联.mq.md b/public/stdlib/外联.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/子任务.mq.md b/public/stdlib/子任务.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/插件.mq.md b/public/stdlib/插件.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/数学-plot-1.svg b/public/stdlib/数学-plot-1.svg old mode 100644 new mode 100755 diff --git a/public/stdlib/数学.mq.md b/public/stdlib/数学.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/文件.mq.md b/public/stdlib/文件.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/文本.mq.md b/public/stdlib/文本.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/时间.mq.md b/public/stdlib/时间.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/系统.mq.md b/public/stdlib/系统.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/网络.mq.md b/public/stdlib/网络.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/自写回.mq.md b/public/stdlib/自写回.mq.md old mode 100644 new mode 100755 diff --git a/public/stdlib/表.mq.md b/public/stdlib/表.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/01-hello.mq.md b/public/structure/01-hello.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/01-你好.mq.md b/public/structure/01-你好.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/02-函数.mq.md b/public/structure/02-函数.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/03-位置调用.mq.md b/public/structure/03-位置调用.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/04-分支.mq.md b/public/structure/04-分支.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/07-map.mq.md b/public/structure/07-map.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/07-字典.mq.md b/public/structure/07-字典.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/08-records.mq.md b/public/structure/08-records.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/08-记录表.mq.md b/public/structure/08-记录表.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/09-inherit.mq.md b/public/structure/09-inherit.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/09-继承.mq.md b/public/structure/09-继承.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/import/main.mq.md b/public/structure/import/main.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/import/主.mq.md b/public/structure/import/主.mq.md old mode 100644 new mode 100755 diff --git a/public/structure/import/工具.mq.md b/public/structure/import/工具.mq.md old mode 100644 new mode 100755 diff --git a/rust-toolchain.toml b/rust-toolchain.toml old mode 100644 new mode 100755 diff --git a/scripts/build-public.ps1 b/scripts/build-public.ps1 old mode 100644 new mode 100755 diff --git a/scripts/check-proof-library.sh b/scripts/check-proof-library.sh new file mode 100755 index 0000000..eb67d79 --- /dev/null +++ b/scripts/check-proof-library.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# 校验内嵌语义底座(src/prove/driver.rs include_str!)与 +# doc/verification/skill-proof/MarqdoProof.lean 一致,并输出其 sha256。 +# 用法:scripts/check-proof-library.sh [LEAN_BIN] +# LEAN_BIN 缺省用 PATH/MARQDO_PROOF_LEAN 里的 lean。 +set -eu + +cd "$(dirname "$0")/.." +LIB=doc/verification/skill-proof/MarqdoProof.lean +LEAN_BIN="${1:-${MARQDO_PROOF_LEAN:-lean}}" + +# 1) 内嵌源必须与仓库里的底座逐字节一致(发布二进制自带它)。 +# driver.rs 的 include_str! 在编译期锁定该路径;这里再防人手改跑偏。 +grep -q 'include_str!("../../doc/verification/skill-proof/MarqdoProof.lean")' src/prove/driver.rs + +# 2) 底座 sha256(写进判定证书,判定可复核)。 +if command -v sha256sum >/dev/null 2>&1; then + SHA=$(sha256sum "$LIB" | cut -d' ' -f1) +else + SHA=$(shasum -a 256 "$LIB" | cut -d' ' -f1) +fi +echo "MarqdoProof.lean sha256: $SHA" + +# 3) (可选)真机验底座本身可编译。 +if command -v "$LEAN_BIN" >/dev/null 2>&1; then + TMP=$(mktemp -d) + cp "$LIB" "$TMP/MarqdoProof.lean" + (cd "$TMP" && "$LEAN_BIN" -o MarqdoProof.olean MarqdoProof.lean) + rm -rf "$TMP" + echo "MarqdoProof.lean compiles with $LEAN_BIN" +else + echo "(未找到 $LEAN_BIN,跳过底座编译验证)" +fi diff --git a/scripts/deploy-public.ps1 b/scripts/deploy-public.ps1 old mode 100644 new mode 100755 diff --git a/scripts/dev-env.sh b/scripts/dev-env.sh index 50e5a10..252b3a9 100755 --- a/scripts/dev-env.sh +++ b/scripts/dev-env.sh @@ -30,6 +30,7 @@ export ZIG_GLOBAL_CACHE_DIR="${ZIG_GLOBAL_CACHE_DIR:-$_tc/zigcache}" export ZIG_LOCAL_CACHE_DIR="${ZIG_LOCAL_CACHE_DIR:-$_tc/zigcache}" _prepend_existing "$_zshim/bin" +_prepend_existing "$_tc/bin" _prepend_existing "$_tc/python/bin" _prepend_existing "$_tc/go/bin" _prepend_existing "$_tc/cargo/bin" diff --git a/scripts/migrate-branch-ordered.py b/scripts/migrate-branch-ordered.py old mode 100644 new mode 100755 diff --git a/scripts/migrate-v02-syntax.py b/scripts/migrate-v02-syntax.py old mode 100644 new mode 100755 diff --git a/scripts/ppa-build-source.sh b/scripts/ppa-build-source.sh old mode 100644 new mode 100755 diff --git a/scripts/ppa-ship.sh b/scripts/ppa-ship.sh old mode 100644 new mode 100755 diff --git a/scripts/publish-release.py b/scripts/publish-release.py old mode 100644 new mode 100755 diff --git a/scripts/release-full.ps1 b/scripts/release-full.ps1 old mode 100644 new mode 100755 diff --git a/scripts/release-windows.ps1 b/scripts/release-windows.ps1 old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/SKILL.md b/skills/marqdo-dev/SKILL.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/browser.mq.md b/skills/marqdo-dev/browser.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/data.mq.md b/skills/marqdo-dev/data.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/files.mq.md b/skills/marqdo-dev/files.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/index.mq.md b/skills/marqdo-dev/index.mq.md old mode 100644 new mode 100755 index 017fbdb..b840d66 --- a/skills/marqdo-dev/index.mq.md +++ b/skills/marqdo-dev/index.mq.md @@ -130,6 +130,50 @@ We **checked = [检查真实文件及其可读性](engineering.run(argv=`argv`)) We **checked = [执行实际离线构建与验收](engineering.run(argv=`argv`, timeout_ms=300000, max_output=2097152))**. 验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 +## prove ++ `path` ++ `all` ++ `max_files` ++ `require_lean` ++ `json` + +| 参数 | 类型 | 默认 | 说明 | +|---|---|---|---| +| path | text | "." | 单个 `.mq.md` 或目录(目录需要 all=True) | +| all | bool | False | 目录模式:递归收集 .mq.md 逐文件出证,整体取最差状态 | +| max_files | text | "200" | 目录收集上限(--max-files 的值,文本形式) | +| require_lean | bool | False | CI 严格模式:未判定状态退 2 | +| json | bool | False | 单个 JSON 对象输出(智能体可读契约) | + +| 返回 | 类型 | 说明 | +|---|---|---| +| result | map | Result:真实 `marqdo prove` 退出状态、标准输出与错误输出 | + +证明知识文件的定理表:先离线符号执行(毫秒级 checked,不是 proved),有 Lean 工具链时由 Lean 复核升级 proved;假定理给出路径见证反例;离线与 Lean 分歧触发 proof.divergence 错误并退 1,永不落绿。这个任务调用真实 CLI——不带 Lean 时状态如实停留在 unverified/checked(咨询性退 0),require_lean=True 才把未判定当作阻塞。 + +目录模式逐文件出证书,整体状态按 error > unproved > rejected > unverified > checked > proved 取最差;证书缓存在 .marqdo/prove/,重复运行命中缓存。通过只说明所选文件判定完成,不能替代 test 任务的运行时验收;两者结合才是完整验收。 + +1. len(text.trim(`path`)) == 0 + Return *[要求明确的证明范围](result.error(code="dev.prove_path", message="path is required", operation="prove"))*. + +`argv` = + +| argument | +|---| +| "prove" | +| "path" | + +1. `all` == True + We **argv = [切换目录模式](table.append(list=`argv`, item="--all"))** and **argv = [追加收集上限标记](table.append(list=`argv`, item="--max-files"))** and **argv = [追加原样传入的上限文本](table.append(list=`argv`, item=`max_files`))**. +1. not `all` + We **argv = [追加原样传入的证明路径](table.append(list=`argv`, item=`path`))**. +1. `require_lean` == True + We **argv = [追加严格模式](table.append(list=`argv`, item="--require-lean"))**. +1. `json` == True + We **argv = [追加机器可读输出](table.append(list=`argv`, item="--json"))**. +We **checked = [执行真实证明管线](engineering.run(argv=`argv`, timeout_ms=600000, max_output=4194304))**. +验收结束后返回*[按真实退出状态判断结果并保留输出](engineering.check_exit(outcome=`checked`))*。 + ## build_browser | 参数 | 类型 | 默认 | 说明 | diff --git a/skills/marqdo-dev/repository.mq.md b/skills/marqdo-dev/repository.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-dev/toolchain.mq.md b/skills/marqdo-dev/toolchain.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/SKILL.md b/skills/marqdo-release/SKILL.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/_bridge.mq.md b/skills/marqdo-release/_bridge.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/asset_io.mq.md b/skills/marqdo-release/asset_io.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/assets.mq.md b/skills/marqdo-release/assets.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/github.mq.md b/skills/marqdo-release/github.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/index.mq.md b/skills/marqdo-release/index.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/local.mq.md b/skills/marqdo-release/local.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/model.mq.md b/skills/marqdo-release/model.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/package.mq.md b/skills/marqdo-release/package.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/packs.mq.md b/skills/marqdo-release/packs.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/reference.md b/skills/marqdo-release/reference.md old mode 100644 new mode 100755 diff --git a/skills/marqdo-release/ubuntu.mq.md b/skills/marqdo-release/ubuntu.mq.md old mode 100644 new mode 100755 diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md old mode 100644 new mode 100755 diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md old mode 100644 new mode 100755 diff --git a/skills/marqdo/migration-classic.md b/skills/marqdo/migration-classic.md old mode 100644 new mode 100755 diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md old mode 100644 new mode 100755 index 850370a..e81b7e2 --- a/skills/marqdo/reference.md +++ b/skills/marqdo/reference.md @@ -3,3 +3,30 @@ The maintained programming rules and runnable examples live in [the executable programming guide](../../doc/library-development.mq.md). Read its parameter and return contracts, then call the actual source heading. [The development entry](../marqdo-dev/index.mq.md) provides native file operations and verification tasks; [the release entry](../marqdo-release/index.mq.md) provides publication workflows. Use [the recursive Markdown web example](../../examples/web-layout-handbook/index.mq.md) and [the quantum workflow](../../examples/quantum-entanglement/index.mq.md) for domain development. Their real source is the manual. [Classic migration context](migration-classic.md) remains for explicitly historical syntax; new programs use readable occlusion and access(collection, key). Do not copy a second fenced program from this discovery note. + +## Theorem tables (`marqdo prove`, CLI 2.8.0+) + +A knowledge function may carry a theorem table before its first executable +statement. Place it right under the parameter list: + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "工单.创建") | 金额 > 10000 | auto | + +- `结论` grammar: `结果.ok = True/False`, `包含(轨迹, "操作名")`, + `长度(轨迹) ⋈ n`, `参数 ⋈ 常量`, combined with 且/或/非. `轨迹` names the + operation trace by the link's display text; `结果` is the returned value. +- `前提` restricts the claim's scope (same comparison grammar). Keep it a + single-variable linear condition. +- `策略` is `auto` (generated proof script) or `none` (theorem generated but + not proven — honest `unverified`). + +Judge with `marqdo prove 文件.mq.md --json`. Statuses, strongest first: +`proved` (Lean confirms) > `checked` (offline symbolic execution closed the +path — advisory, never a proof) > `unverified` (outside the provable subset) +> `rejected` (subset check refused) > `unproved` (counterexample found, e.g. +`金额 = 10001`) > `error`. Without a Lean toolchain the run stays honest at +`checked`/`unverified` and exits 0; `--require-lean` makes unjudged statuses +exit 2 for CI. Never weaken a failing claim to make it pass — fix the claim +or the code, and let `proof.divergence` stop the line when the offline +judger and Lean disagree. Full contract: [design/prove-cli.md](../../doc/design/prove-cli.md). diff --git a/spike/.gitignore b/spike/.gitignore old mode 100644 new mode 100755 diff --git a/spike/README.md b/spike/README.md old mode 100644 new mode 100755 diff --git a/spike/REPORT.md b/spike/REPORT.md old mode 100644 new mode 100755 diff --git a/spike/marqdo_spike.py b/spike/marqdo_spike.py old mode 100644 new mode 100755 diff --git a/spike/requirements.txt b/spike/requirements.txt old mode 100644 new mode 100755 diff --git a/spike/test_s1_s5.py b/spike/test_s1_s5.py old mode 100644 new mode 100755 diff --git a/src/aliases.rs b/src/aliases.rs old mode 100644 new mode 100755 diff --git a/src/application_tests.rs b/src/application_tests.rs old mode 100644 new mode 100755 diff --git a/src/arguments.rs b/src/arguments.rs old mode 100644 new mode 100755 diff --git a/src/artifact/mod.rs b/src/artifact/mod.rs old mode 100644 new mode 100755 diff --git a/src/ast.rs b/src/ast.rs old mode 100644 new mode 100755 index 2e1c4e5..364e7ea --- a/src/ast.rs +++ b/src/ast.rs @@ -95,6 +95,22 @@ pub struct Function { pub contract: Option, /// 集合契约(T2.1):变量名 → 字段契约(紧邻 `` `名` = `` 绑定之前的文档表)。 pub var_contracts: HashMap, + /// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。 + pub claims: Vec, +} + +/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。 +#[derive(Debug, Clone)] +pub struct Claim { + /// 定理 id(函数内唯一;重复由 `check --proof` 报 `proof.claim_duplicate`)。 + pub id: String, + /// 受限表达式文本(参数、`结果`、`轨迹`、三个谓词、算术/比较/布尔)。 + pub conclusion: String, + pub premise: Option, + /// `auto`(默认)或 `none`;其他值由 `check --proof` 报 unsupported。 + pub tactic: Option, + /// 表行所在行号(锚定漂移检测)。 + pub line: u32, } impl Function { diff --git a/src/binding/mod.rs b/src/binding/mod.rs old mode 100644 new mode 100755 diff --git a/src/browser_session.rs b/src/browser_session.rs old mode 100644 new mode 100755 diff --git a/src/builtin.rs b/src/builtin.rs old mode 100644 new mode 100755 diff --git a/src/builtin/primitives.rs b/src/builtin/primitives.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/call.rs b/src/bytecode/call.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/expression.rs b/src/bytecode/expression.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/mod.rs b/src/bytecode/mod.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/names.rs b/src/bytecode/names.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/source.rs b/src/bytecode/source.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/statement.rs b/src/bytecode/statement.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/verify.rs b/src/bytecode/verify.rs old mode 100644 new mode 100755 diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs old mode 100644 new mode 100755 diff --git a/src/call.rs b/src/call.rs old mode 100644 new mode 100755 diff --git a/src/call_session.rs b/src/call_session.rs old mode 100644 new mode 100755 diff --git a/src/capture.rs b/src/capture.rs old mode 100644 new mode 100755 diff --git a/src/catalog.rs b/src/catalog.rs old mode 100644 new mode 100755 diff --git a/src/causal_replay_tests.rs b/src/causal_replay_tests.rs old mode 100644 new mode 100755 diff --git a/src/check.rs b/src/check.rs old mode 100644 new mode 100755 index 394acc7..f36aa8b --- a/src/check.rs +++ b/src/check.rs @@ -23,14 +23,17 @@ use crate::load; /// 读取文件 + 装载(含 import)后做全量契约互查。 pub fn check_path(path: &Path) -> Result> { - check_path_opts(path, false) + check_path_opts(path, false, false) } /// `implicit_labels` enables the fuzzy M5 check (prose above `>` calls). /// /// It is **off by default**: describing a call in prose is freeform, so the /// check is inherently ambiguous and would be noisy — opt in when you want it. -pub fn check_path_opts(path: &Path, implicit_labels: bool) -> Result> { +/// +/// `proof` enables the theorem-table check (`check --proof`, ADR 0010, +/// 默认关):表形、名字、片段、遮蔽。 +pub fn check_path_opts(path: &Path, implicit_labels: bool, proof: bool) -> Result> { let module = load::load_module(path)?; let mut out = check_module(&module, Some(path)); if implicit_labels { @@ -38,6 +41,9 @@ pub fn check_path_opts(path: &Path, implicit_labels: bool) -> Result usize { prev[b.len()] } +/// 供 `prove::proof_check` 复用的最近名建议(编辑距离 ≤ 2)。 +pub fn suggest_closest(name: &str, known: &[String]) -> Option { + suggest(name, known) +} + fn suggest(name: &str, known: &[String]) -> Option { let lower = name.to_ascii_lowercase(); let mut best: Option<(usize, String)> = None; diff --git a/src/contract.rs b/src/contract.rs old mode 100644 new mode 100755 index 83a3fca..cb958b3 --- a/src/contract.rs +++ b/src/contract.rs @@ -265,6 +265,117 @@ const TYPE_HEADERS: &[&str] = &["类型", "type"]; const DESC_HEADERS: &[&str] = &["说明", "描述", "备注", "注释", "desc", "description"]; const NULLABLE_HEADERS: &[&str] = &["可空", "nullable", "optional"]; +// ---------- 定理表识别(ADR 0010 / 设计 §7.1) ---------- + +/// 定理表头(第一列)词表:`定理/证明/claim/theorem`。 +pub const CLAIM_NAME_HEADERS: &[&str] = &["定理", "证明", "claim", "theorem"]; +/// 结论列词表(必填列)。 +pub const CLAIM_CONCLUSION_HEADERS: &[&str] = &["结论", "conclusion"]; +/// 前提列词表(可缺省)。 +pub const CLAIM_PREMISE_HEADERS: &[&str] = &["前提", "premise", "assumes"]; +/// 策略列词表(可缺省)。 +pub const CLAIM_TACTIC_HEADERS: &[&str] = &["策略", "tactic"]; + +/// 表头是否命中定理表第一列(只看词,不看列形)。 +pub fn header_hits_claim(headers: &[String]) -> bool { + find_col(headers, CLAIM_NAME_HEADERS).is_some() +} + +/// 定理表认领判定(设计 §7.1 规则 1/5): +/// - `None`:表头不命中定理词表 → 普通表; +/// - `Some(Ok(rows))`:命中且列形正确(有结论列,无 `类型` 列)→ 定理表; +/// - `Some(Err(e))`:命中但有形状问题(歧义/行数不齐/缺名)→ `check --proof` 报。 +pub fn parse_claim_table( + pairs: &[(String, Expr)], + start_line: u32, +) -> Option, ClaimTableError>> { + let headers: Vec = pairs.iter().map(|(k, _)| k.clone()).collect(); + if !header_hits_claim(&headers) { + return None; + } + // 同时有 `类型` 列与 `结论` 列 → 歧义,不猜(§7.1 规则 5)。 + if find_col(&headers, TYPE_HEADERS).is_some() + && find_col(&headers, CLAIM_CONCLUSION_HEADERS).is_some() + { + return Some(Err(ClaimTableError { + code: "proof.claim_ambiguous", + message: "表同时含 `类型` 与 `结论` 列——契约表与定理表不猜,请拆开或改名".into(), + })); + } + // 无结论列 → 不是定理表(两列的 `定理/说明` 是普通说明表,§7.3.5)。 + let Some(conclusion_col) = find_col(&headers, CLAIM_CONCLUSION_HEADERS) else { + return None; + }; + let premise_col = find_col(&headers, CLAIM_PREMISE_HEADERS); + let tactic_col = find_col(&headers, CLAIM_TACTIC_HEADERS); + // 第一列=定理名;若第一列不是命中列,命中列才是名字列。 + let name_col = find_col(&headers, CLAIM_NAME_HEADERS).unwrap_or(0); + + let names = col_rows(&pairs[name_col].1).unwrap_or_default(); + let conclusions = claim_col_rows(&pairs[conclusion_col].1); + if names.len() != conclusions.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: format!( + "定理/结论 列行数不一致({} vs {})", + names.len(), + conclusions.len() + ), + })); + } + let premises = premise_col + .map(|c| claim_col_rows(&pairs[c].1)) + .unwrap_or_default(); + let tactics = tactic_col + .map(|c| col_rows(&pairs[c].1).unwrap_or_default()) + .unwrap_or_default(); + if !premises.is_empty() && premises.len() != names.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: "前提 列行数与 定理 列不一致".into(), + })); + } + if !tactics.is_empty() && tactics.len() != names.len() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: "策略 列行数与 定理 列不一致".into(), + })); + } + + let mut rows = Vec::new(); + for (i, name) in names.iter().enumerate() { + let name = name.trim(); + if name.is_empty() { + return Some(Err(ClaimTableError { + code: "proof.claim_malformed", + message: format!("定理表第 {} 行缺定理名", i + 1), + })); + } + rows.push(crate::ast::Claim { + id: name.to_string(), + conclusion: conclusions[i].trim().to_string(), + // 空前提单元格 = 无前提(全称命题)。 + premise: premises + .get(i) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()), + tactic: tactics + .get(i) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()), + line: start_line, + }); + } + Some(Ok(rows)) +} + +/// 定理表形状错误(`check --proof` 才报;默认关)。 +#[derive(Debug, Clone)] +pub struct ClaimTableError { + pub code: &'static str, + pub message: String, +} + fn norm_header(h: &str) -> String { h.trim().trim_matches('`').to_ascii_lowercase() } @@ -298,6 +409,57 @@ fn col_rows(e: &Expr) -> Option> { } } +/// 定理表单元格取文本:标量直取;比较/算术/布尔表达式按 `a op b` 还原 +/// (`金额 > 10000` 这类单元格会解析成 Binary,不能因为不是标量就丢行)。 +/// 不认识的形状 → None(该行按缺失处理,`check --proof` 会报 unknown_symbol)。 +fn claim_cell_text(e: &Expr) -> Option { + if let Some(text) = cell_to_text(e) { + return Some(text); + } + match e { + Expr::Binary { op, left, right } => Some(format!( + "{} {} {}", + claim_cell_text(left)?, + op_token(*op), + claim_cell_text(right)? + )), + Expr::Unary { op, expr } => match op { + crate::ast::UnaryOp::Not => Some(format!("非 ({})", claim_cell_text(expr)?)), + crate::ast::UnaryOp::Neg => Some(format!("-({})", claim_cell_text(expr)?)), + }, + _ => None, + } +} + +fn op_token(op: crate::ast::BinaryOp) -> &'static str { + use crate::ast::BinaryOp as B; + match op { + B::Add => "+", + B::Sub => "-", + B::Mul => "*", + B::Div => "/", + B::Eq => "=", + B::Ne => "≠", + B::Lt => "<", + B::Le => "≤", + B::Gt => ">", + B::Ge => "≥", + B::And => "且", + B::Or => "或", + } +} + +/// 定理表列取文本(行级 None 不整列丢弃——只丢该行该列)。 +fn claim_col_rows(e: &Expr) -> Vec { + match e { + Expr::List(items) => items + .iter() + .map(|item| claim_cell_text(item).unwrap_or_default()) + .collect(), + scalar => vec![claim_cell_text(scalar).unwrap_or_default()], + } +} + fn is_nullable(raw: &str) -> bool { matches!( norm_header(raw).as_str(), diff --git a/src/debug/ctrl.rs b/src/debug/ctrl.rs old mode 100644 new mode 100755 diff --git a/src/debug/mod.rs b/src/debug/mod.rs old mode 100644 new mode 100755 diff --git a/src/debug/trace.rs b/src/debug/trace.rs old mode 100644 new mode 100755 diff --git a/src/diagnostics.rs b/src/diagnostics.rs old mode 100644 new mode 100755 diff --git a/src/document_extract.rs b/src/document_extract.rs old mode 100644 new mode 100755 diff --git a/src/embedded_lib.rs b/src/embedded_lib.rs old mode 100644 new mode 100755 diff --git a/src/ext_cli.rs b/src/ext_cli.rs old mode 100644 new mode 100755 diff --git a/src/ext_fetch.rs b/src/ext_fetch.rs old mode 100644 new mode 100755 diff --git a/src/foreign/mod.rs b/src/foreign/mod.rs old mode 100644 new mode 100755 diff --git a/src/foreign/registry.rs b/src/foreign/registry.rs old mode 100644 new mode 100755 diff --git a/src/formula/mod.rs b/src/formula/mod.rs old mode 100644 new mode 100755 diff --git a/src/formula/plot.rs b/src/formula/plot.rs old mode 100644 new mode 100755 diff --git a/src/frontend_elaboration_tests.rs b/src/frontend_elaboration_tests.rs old mode 100644 new mode 100755 index b6a2330..c6257e5 --- a/src/frontend_elaboration_tests.rs +++ b/src/frontend_elaboration_tests.rs @@ -16,8 +16,12 @@ fn local_json(value: &Value) -> serde_json::Value { } fn document(id: &str, source: &str) -> (PathBuf, crate::ast::Module) { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target/frontend-elaboration") + // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. + let base = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = base + .join("frontend-elaboration") .join(format!("{id}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("main.mq.md"); diff --git a/src/host/agent_rt.rs b/src/host/agent_rt.rs old mode 100644 new mode 100755 diff --git a/src/host/archive.rs b/src/host/archive.rs old mode 100644 new mode 100755 diff --git a/src/host/cli.rs b/src/host/cli.rs old mode 100644 new mode 100755 diff --git a/src/host/collection.rs b/src/host/collection.rs old mode 100644 new mode 100755 diff --git a/src/host/collection_ops.rs b/src/host/collection_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/csv.rs b/src/host/csv.rs old mode 100644 new mode 100755 diff --git a/src/host/data_ops.rs b/src/host/data_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/datetime.rs b/src/host/datetime.rs old mode 100644 new mode 100755 diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs old mode 100644 new mode 100755 diff --git a/src/host/document.rs b/src/host/document.rs old mode 100644 new mode 100755 diff --git a/src/host/encoding.rs b/src/host/encoding.rs old mode 100644 new mode 100755 diff --git a/src/host/event_bus.rs b/src/host/event_bus.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign.rs b/src/host/foreign.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_doc.rs b/src/host/foreign_doc.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_doc/control.rs b/src/host/foreign_doc/control.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_doc/packing.rs b/src/host/foreign_doc/packing.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_doc/replay.rs b/src/host/foreign_doc/replay.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_session.rs b/src/host/foreign_session.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_session/control.rs b/src/host/foreign_session/control.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_session/validation.rs b/src/host/foreign_session/validation.rs old mode 100644 new mode 100755 diff --git a/src/host/foreign_session/validation/policy.rs b/src/host/foreign_session/validation/policy.rs old mode 100644 new mode 100755 diff --git a/src/host/fs.rs b/src/host/fs.rs old mode 100644 new mode 100755 diff --git a/src/host/fs_ops.rs b/src/host/fs_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/hash.rs b/src/host/hash.rs old mode 100644 new mode 100755 diff --git a/src/host/html_ops.rs b/src/host/html_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/json.rs b/src/host/json.rs old mode 100644 new mode 100755 diff --git a/src/host/log.rs b/src/host/log.rs old mode 100644 new mode 100755 diff --git a/src/host/math.rs b/src/host/math.rs old mode 100644 new mode 100755 diff --git a/src/host/mod.rs b/src/host/mod.rs old mode 100644 new mode 100755 diff --git a/src/host/net.rs b/src/host/net.rs old mode 100644 new mode 100755 diff --git a/src/host/net_ops.rs b/src/host/net_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/oracle.rs b/src/host/oracle.rs old mode 100644 new mode 100755 diff --git a/src/host/path.rs b/src/host/path.rs old mode 100644 new mode 100755 diff --git a/src/host/plugin.rs b/src/host/plugin.rs old mode 100644 new mode 100755 diff --git a/src/host/plugin_stub.rs b/src/host/plugin_stub.rs old mode 100644 new mode 100755 diff --git a/src/host/re.rs b/src/host/re.rs old mode 100644 new mode 100755 diff --git a/src/host/result.rs b/src/host/result.rs old mode 100644 new mode 100755 diff --git a/src/host/sandbox_fs.rs b/src/host/sandbox_fs.rs old mode 100644 new mode 100755 diff --git a/src/host/secrets.rs b/src/host/secrets.rs old mode 100644 new mode 100755 diff --git a/src/host/stats.rs b/src/host/stats.rs old mode 100644 new mode 100755 diff --git a/src/host/subtask.rs b/src/host/subtask.rs old mode 100644 new mode 100755 diff --git a/src/host/subtask_stub.rs b/src/host/subtask_stub.rs old mode 100644 new mode 100755 diff --git a/src/host/sys.rs b/src/host/sys.rs old mode 100644 new mode 100755 diff --git a/src/host/task_ops.rs b/src/host/task_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/text_ops.rs b/src/host/text_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/time.rs b/src/host/time.rs old mode 100644 new mode 100755 diff --git a/src/host/toml_ops.rs b/src/host/toml_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/url_ops.rs b/src/host/url_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/uuid_ops.rs b/src/host/uuid_ops.rs old mode 100644 new mode 100755 diff --git a/src/host/writeback.rs b/src/host/writeback.rs old mode 100644 new mode 100755 diff --git a/src/inherit.rs b/src/inherit.rs old mode 100644 new mode 100755 diff --git a/src/input_feed.rs b/src/input_feed.rs old mode 100644 new mode 100755 diff --git a/src/interp.rs b/src/interp.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/capability.rs b/src/knowledge/capability.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/compile.rs b/src/knowledge/compile.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/duplicate.rs b/src/knowledge/duplicate.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/extract.rs b/src/knowledge/extract.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/find.rs b/src/knowledge/find.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/fingerprint.rs b/src/knowledge/fingerprint.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/graph.rs b/src/knowledge/graph.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/impact.rs b/src/knowledge/impact.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/ir.rs b/src/knowledge/ir.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/learn.rs b/src/knowledge/learn.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/lifecycle.rs b/src/knowledge/lifecycle.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/metrics.rs b/src/knowledge/metrics.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/mod.rs b/src/knowledge/mod.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/policy.rs b/src/knowledge/policy.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/preflight.rs b/src/knowledge/preflight.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/reuse.rs b/src/knowledge/reuse.rs old mode 100644 new mode 100755 diff --git a/src/knowledge/util.rs b/src/knowledge/util.rs old mode 100644 new mode 100755 diff --git a/src/label.rs b/src/label.rs old mode 100644 new mode 100755 diff --git a/src/lex/mod.rs b/src/lex/mod.rs old mode 100644 new mode 100755 diff --git a/src/lib.rs b/src/lib.rs old mode 100644 new mode 100755 index a90972d..7a61214 --- a/src/lib.rs +++ b/src/lib.rs @@ -45,6 +45,7 @@ pub mod runtime; pub mod workbench; pub mod parse; pub mod project; +pub mod prove; pub mod repair; pub mod sema; pub mod value; diff --git a/src/linalg_ops.rs b/src/linalg_ops.rs old mode 100644 new mode 100755 diff --git a/src/load.rs b/src/load.rs old mode 100644 new mode 100755 diff --git a/src/main.rs b/src/main.rs old mode 100644 new mode 100755 index 069e651..c79d362 --- a/src/main.rs +++ b/src/main.rs @@ -218,6 +218,10 @@ enum Commands { /// Parse an unmarked file with the legacy grammar for migration review. #[arg(long)] legacy_markup: bool, + + /// Validate theorem tables (ADR 0010; 默认关): shape, symbols, shadowing + #[arg(long)] + proof: bool, }, /// Occlusion label queries: pending stubs (built-in words) or keyword search Labels { @@ -495,6 +499,110 @@ enum Commands { #[command(subcommand)] action: WasmAction, }, + /// Compile SKILL orchestration to Lean 4 and (P1+) prove theorems (推荐但不强制) + Prove { + /// Action (default: emit + report) + #[command(subcommand)] + action: Option, + + /// Program path (.mq.md; default ./index.mq.md) + #[arg(value_name = "FILE")] + file: Option, + + /// One JSON object on stdout (agent-facing stable contract) + #[arg(long)] + json: bool, + + /// Only lower/emit these functions (display path, repeatable) + #[arg(long = "only", value_name = "FN")] + only: Vec, + + /// Output dir for emit (default .marqdo/prove//) + #[arg(long = "emit", short = 'o', value_name = "DIR")] + emit_dir: Option, + + /// Don't write artifacts; report only + #[arg(long)] + report_only: bool, + + /// Downgrade this function wholesale to one opaque op (repeatable) + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + + /// Type inference is strict by default; this relaxes to Val (weaker proofs) + #[arg(long = "no-strict-types")] + no_strict_types: bool, + + /// CI strict mode: unjudged statuses exit 2 (P1+) + #[arg(long)] + require_lean: bool, + + /// Explicit lean binary (else MARQDO_PROOF_LEAN, else PATH) + #[arg(long, value_name = "PATH")] + lean: Option, + + /// Per-lean-call timeout in seconds (default 120) + #[arg(long, value_name = "SEC", default_value_t = 120)] + timeout: u64, + + /// Bypass the certificate cache (also MARQDO_PROOF_NO_CACHE) + #[arg(long)] + no_cache: bool, + + /// maxHeartbeats for lean (default: lean's own) + #[arg(long, value_name = "N")] + heartbeats: Option, + + /// Directory mode: recursively prove every .mq.md (aggregated, worst status wins) + #[arg(long)] + all: bool, + + /// Cap for --all file collection (default 200) + #[arg(long = "max-files", value_name = "N", default_value_t = 200)] + max_files: usize, + + /// Debug fault injection: `offline-claim` flips one Lean-proved claim to + /// force proof.divergence (monotonicity tripwire verification) + #[arg(long = "fault-inject", value_name = "SPEC")] + fault_inject: Option, + }, +} + +#[derive(Subcommand, Debug)] +enum ProveAction { + /// Generate deterministic Lean module + plan.json (no judging) + Emit { + #[arg(value_name = "FILE")] + file: Option, + #[arg(long = "emit", short = 'o', value_name = "DIR")] + emit_dir: Option, + #[arg(long)] + json: bool, + #[arg(long = "only", value_name = "FN")] + only: Vec, + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + #[arg(long = "no-strict-types")] + no_strict_types: bool, + }, + /// Report inline/opaque/rejected classification (no judging) + Audit { + #[arg(value_name = "FILE")] + file: Option, + #[arg(long)] + json: bool, + #[arg(long = "only", value_name = "FN")] + only: Vec, + #[arg(long = "allow-opaque", value_name = "FN")] + allow_opaque: Vec, + #[arg(long = "no-strict-types")] + no_strict_types: bool, + }, + /// Delete .marqdo/prove caches and certificates + Clean { + #[arg(long)] + json: bool, + }, } #[derive(Subcommand, Debug)] @@ -656,7 +764,9 @@ fn main() -> ExitCode { let cli = Cli::parse(); let json_errors = matches!( &cli.command, - Commands::Run { json: true, .. } | Commands::Check { json: true, .. } + Commands::Run { json: true, .. } + | Commands::Check { json: true, .. } + | Commands::Prove { json: true, .. } ); match try_main(cli) { Ok(code) => ExitCode::from(code as u8), @@ -677,6 +787,85 @@ fn main() -> ExitCode { } } +/// `prove --all`:逐文件出报告,整体取最差状态(差者胜,§3.2)。 +/// JSON:`{"schema":1,"kind":"prove-all","status":…,"files":[…],"duration_ms":…}`。 +fn run_prove_all( + dir: &std::path::Path, + max_files: usize, + opts: &marqdo::prove::ProveOptions, + json: bool, + require_lean: bool, +) -> Result { + let mut files = collect_mq_files(dir)?; + anyhow::ensure!( + !files.is_empty(), + "目录中没有 .mq.md 文件:{}", + dir.display() + ); + anyhow::ensure!( + files.len() <= max_files, + "--max-files {max_files} 已达上限(实际 {} 个文件;请调大或缩小范围)", + files.len() + ); + files.sort(); + let started = std::time::Instant::now(); + let mut worst = marqdo::prove::Verdict::Proved; + let mut file_items: Vec = Vec::new(); + let mut text_rows: Vec<(String, marqdo::prove::Verdict, usize)> = Vec::new(); + for f in &files { + let report = marqdo::prove::prove_path(f, opts)?; + for d in &report.diagnostics { + eprintln!("{}", d.format_message()); + } + let claims: usize = report + .functions + .iter() + .map(|fun| fun.claims.len()) + .sum(); + worst = marqdo::prove::Verdict::worst(worst, report.status); + text_rows.push(( + f.strip_prefix(dir).unwrap_or(f).display().to_string(), + report.status, + claims, + )); + let mut item = report.to_json(); + if let Some(obj) = item.as_object_mut() { + obj.insert( + "file".into(), + serde_json::Value::String( + f.strip_prefix(dir).unwrap_or(f).display().to_string(), + ), + ); + } + file_items.push(item); + } + let duration_ms = started.elapsed().as_millis() as u64; + if json { + let agg = serde_json::json!({ + "schema": 1, + "kind": "prove-all", + "root": dir.display().to_string(), + "status": worst.as_str(), + "files": file_items, + "file_count": files.len(), + "duration_ms": duration_ms, + }); + println!("{agg}"); + } else { + println!( + "prove --all {}:{} 个文件,{} ms,整体 {}", + dir.display(), + files.len(), + duration_ms, + worst.as_str() + ); + for (rel, status, claims) in &text_rows { + println!(" {rel}: {}(定理 {claims})", status.as_str()); + } + } + Ok(worst.exit_code(require_lean)) +} + /// Resolve the value-path spelling introduced for executable knowledge without /// evaluating it. The import bind comes from the caller's source file, so /// `math.pi` never degrades into a project-wide name guess. @@ -958,13 +1147,14 @@ fn try_main(cli: Cli) -> Result { implicit_labels, narrative_ratio, legacy_markup, + proof, } => { let mut diags = if legacy_markup { marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { - marqdo::check::check_path_opts(&file, implicit_labels) + marqdo::check::check_path_opts(&file, implicit_labels, proof) })? } else { - marqdo::check::check_path_opts(&file, implicit_labels)? + marqdo::check::check_path_opts(&file, implicit_labels, proof)? }; if narrative_ratio { diags.extend(marqdo::narrative_ratio::check_file(&file)?); @@ -989,6 +1179,138 @@ fn try_main(cli: Cli) -> Result { } Ok(errors.min(1)) } + Commands::Prove { + action, + file, + json, + only, + emit_dir, + report_only, + allow_opaque, + no_strict_types, + require_lean, + lean, + timeout, + no_cache, + heartbeats, + all, + max_files, + fault_inject, + } => { + // 调试注入(§6 A3):仅面向测试的分歧触发器。 + if fault_inject.as_deref() == Some("offline-claim") { + std::env::set_var("MARQDO_PROOF_INJECT_DIVERGENCE", "1"); + } + // 子命令参数覆盖顶层默认;默认动作 = emit + 报告。 + let (file, action_json, action_emit, action_only, action_opaque, action_relax) = + match &action { + Some(ProveAction::Emit { + file, + emit_dir, + json, + only, + allow_opaque, + no_strict_types, + }) => ( + file.clone(), + *json, + Some(emit_dir.clone()), + only.clone(), + allow_opaque.clone(), + *no_strict_types, + ), + Some(ProveAction::Audit { + file, + json, + only, + allow_opaque, + no_strict_types, + }) => ( + file.clone(), + *json, + None, + only.clone(), + allow_opaque.clone(), + *no_strict_types, + ), + Some(ProveAction::Clean { json }) => { + let removed = marqdo::prove::clean()?; + if *json { + println!("{{\"ok\":true,\"removed\":{removed}}}"); + } else { + println!("prove clean: 已删除 {removed} 项(.marqdo/prove)"); + } + return Ok(0); + } + None => (file.clone(), false, Some(emit_dir.clone()), only.clone(), allow_opaque.clone(), no_strict_types), + }; + let file = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); + // emit 目标:显式 --emit 优先;None → mod.rs 用默认 `.marqdo/prove/`。 + // audit 永不写盘;默认动作受 --report-only 控制;emit 子命令总是写盘。 + let emit_target = action_emit.flatten(); + let report_only = matches!(action, Some(ProveAction::Audit { .. })) + || (action.is_none() && report_only); + // emit 子命令只生成不判定(§8.2)。 + let judge = !matches!(action, Some(ProveAction::Emit { .. })); + let no_cache = no_cache || std::env::var_os("MARQDO_PROOF_NO_CACHE").is_some(); + // 目录必须显式 --all(§3.2 proof.need_all)。 + if file.is_dir() { + if !all { + eprintln!( + "error: {} 是目录:逐文件证明请加 --all(--max-files 默认 200)", + file.display() + ); + return Ok(1); + } + let out_json = json || action_json; + let code = run_prove_all( + &file, + max_files, + &marqdo::prove::ProveOptions { + entry: None, + only: action_only, + allow_opaque: action_opaque, + emit_dir: emit_target, + strict_types: !action_relax, + require_lean, + report_only, + judge, + no_cache, + lean, + timeout: std::time::Duration::from_secs(timeout), + max_heartbeats: heartbeats, + }, + out_json, + require_lean, + )?; + return Ok(code); + } + let opts = marqdo::prove::ProveOptions { + entry: None, + only: action_only, + allow_opaque: action_opaque, + emit_dir: emit_target, + strict_types: !action_relax, + require_lean, + report_only, + judge, + no_cache, + lean, + timeout: std::time::Duration::from_secs(timeout), + max_heartbeats: heartbeats, + }; + let report = marqdo::prove::prove_path(&file, &opts)?; + for d in &report.diagnostics { + // 诊断走 stderr(stdout 只放结果/报告)。 + eprintln!("{}", d.format_message()); + } + if json || action_json { + println!("{}", report.to_json()); + } else { + print!("{}", report.to_text()); + } + Ok(report.status.exit_code(require_lean)) + } Commands::Labels { paths, grep, diff --git a/src/migrate.rs b/src/migrate.rs old mode 100644 new mode 100755 diff --git a/src/mlsp.rs b/src/mlsp.rs old mode 100644 new mode 100755 diff --git a/src/narrative_ratio.rs b/src/narrative_ratio.rs old mode 100644 new mode 100755 diff --git a/src/parse/expr.rs b/src/parse/expr.rs old mode 100644 new mode 100755 diff --git a/src/parse/mod.rs b/src/parse/mod.rs old mode 100644 new mode 100755 index a67398f..76dc280 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -319,6 +319,7 @@ impl<'a> Cursor<'a> { dead_binds: Vec::new(), contract: None, var_contracts: std::collections::HashMap::new(), + claims: Vec::new(), }; // Prose decls pending promotion (name → optional default text). let mut prose_decls: Vec<(String, Option, u32)> = Vec::new(); @@ -2078,10 +2079,23 @@ fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Re let (end_line, quote) = table_quote(lines, span.line); let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote) else { - // 非契约形状:普通文档/数据表 → 原样保留(P1 零回归的关键)。 - keep.push(stmt.clone()); - i += 1; - continue; + // 非契约形状:先试定理表(ADR 0010),再按普通表保留。 + match crate::contract::parse_claim_table(pairs, span.line) { + // 合法定理表:只在「首个可执行行之前」生效;提取后从 body 移除。 + // 其余位置仍是普通表,由 `check --proof` 报 proof.claim_misplaced。 + Some(Ok(rows)) if prefix_zone => { + fun.claims.extend(rows); + i += 1; + continue; + } + // 畸形/歧义/错位的定理形表:保持普通表(默认关), + // `check --proof` 重扫 body 时报 malformed/ambiguous/misplaced。 + _ => { + keep.push(stmt.clone()); + i += 1; + continue; + } + } }; let piece = parsed?; // 契约形状但畸形 → 必产诊断(contract.malformed) let is_fn_contract = !piece.params.is_empty() || piece.returns.is_some(); diff --git a/src/parse/prose.rs b/src/parse/prose.rs old mode 100644 new mode 100755 diff --git a/src/project/mod.rs b/src/project/mod.rs old mode 100644 new mode 100755 diff --git a/src/prove/cache.rs b/src/prove/cache.rs new file mode 100755 index 0000000..6570c04 --- /dev/null +++ b/src/prove/cache.rs @@ -0,0 +1,245 @@ +//! 证书缓存(设计 §8.3):复合键、命中跳判定、失效。 +//! +//! 键 = sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)。 +//! 证书落在产物目录(`.marqdo/prove//certificate.json`);键不合即失效。 + +use std::path::Path; + +use anyhow::Result; +use sha2::{Digest, Sha256}; + +use crate::prove::Verdict; + +pub const CERT_SCHEMA: u32 = 1; + +/// 单条定理的判定记录。 +#[derive(Debug, Clone, PartialEq)] +pub struct ClaimRecord { + pub id: String, + pub function: String, + pub status: Verdict, + pub source_line: Option, +} + +/// 一份判定证书(复核收据,不是发布许可)。 +#[derive(Debug, Clone)] +pub struct Certificate { + pub key: String, + pub status: Verdict, + pub tier: &'static str, + pub source_sha256: String, + pub library_sha256: String, + pub toolchain: String, + pub module_sha256: String, + pub claims: Vec, + /// lean 行 → mq 行。 + pub span_map: Vec<(u32, u32)>, + pub marqdo: String, +} + +/// 复合缓存键。 +pub fn cache_key( + source_sha256: &str, + plan_sha256: &str, + library_sha256: &str, + toolchain: &str, + marqdo_version: &str, +) -> String { + let mut hasher = Sha256::new(); + hasher.update(source_sha256.as_bytes()); + hasher.update(b"\x00"); + hasher.update(plan_sha256.as_bytes()); + hasher.update(b"\x00"); + hasher.update(library_sha256.as_bytes()); + hasher.update(b"\x00"); + hasher.update(toolchain.as_bytes()); + hasher.update(b"\x00"); + hasher.update(marqdo_version.as_bytes()); + hex(&hasher.finalize()) +} + +pub fn sha256_hex(data: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(data); + hex(&hasher.finalize()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +impl Certificate { + pub fn to_json(&self) -> serde_json::Value { + serde_json::json!({ + "schema": CERT_SCHEMA, + "key": self.key, + "status": self.status.as_str(), + "tier": self.tier, + "source_sha256": self.source_sha256, + "library_sha256": self.library_sha256, + "toolchain": self.toolchain, + "module_sha256": self.module_sha256, + "claims": self.claims.iter().map(|c| serde_json::json!({ + "id": c.id, + "function": c.function, + "status": c.status.as_str(), + "source_line": c.source_line, + })).collect::>(), + "span_map": self.span_map.iter().map(|(l, m)| serde_json::json!({ + "lean_line": l, "mq_line": m, + })).collect::>(), + "marqdo": self.marqdo, + }) + } + + fn from_json(value: &serde_json::Value) -> Option { + use serde_json::Value; + if value.get("schema")?.as_u64()? != CERT_SCHEMA as u64 { + return None; + } + let status = match value.get("status")?.as_str()? { + "proved" => Verdict::Proved, + "checked" => Verdict::Checked, + "unverified" => Verdict::Unverified, + "unproved" => Verdict::Unproved, + "rejected" => Verdict::Rejected, + "error" => Verdict::Error, + _ => return None, + }; + let parse_line = |v: &Value| v.as_u64().map(|n| n as u32); + Some(Certificate { + key: value.get("key")?.as_str()?.to_string(), + status, + tier: match value.get("tier")?.as_str()? { + "lean" => "lean", + "offline" => "offline", + _ => "none", + }, + source_sha256: value.get("source_sha256")?.as_str()?.to_string(), + library_sha256: value.get("library_sha256")?.as_str()?.to_string(), + toolchain: value.get("toolchain")?.as_str()?.to_string(), + module_sha256: value.get("module_sha256")?.as_str()?.to_string(), + claims: value + .get("claims")? + .as_array()? + .iter() + .map(|c| { + Some(ClaimRecord { + id: c.get("id")?.as_str()?.to_string(), + function: c.get("function")?.as_str()?.to_string(), + status: match c.get("status")?.as_str()? { + "proved" => Verdict::Proved, + "checked" => Verdict::Checked, + "unverified" => Verdict::Unverified, + "unproved" => Verdict::Unproved, + "rejected" => Verdict::Rejected, + "error" => Verdict::Error, + _ => return None, + }, + source_line: c.get("source_line").and_then(parse_line), + }) + }) + .collect::>>()?, + span_map: value + .get("span_map") + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|e| { + Some(( + e.get("lean_line")?.as_u64()? as u32, + e.get("mq_line")?.as_u64()? as u32, + )) + }) + .collect() + }) + .unwrap_or_default(), + marqdo: value.get("marqdo")?.as_str()?.to_string(), + }) + } +} + +/// 读证书:文件缺失/损坏/键不合 → None(调用方重判)。 +pub fn load(artifact_dir: &Path, key: &str) -> Option { + let path = artifact_dir.join("certificate.json"); + let raw = std::fs::read_to_string(path).ok()?; + let value: serde_json::Value = serde_json::from_str(&raw).ok()?; + let cert = Certificate::from_json(&value)?; + (cert.key == key).then_some(cert) +} + +/// 写证书(原子:临时文件 + 改名)。 +pub fn store(artifact_dir: &Path, cert: &Certificate) -> Result<()> { + std::fs::create_dir_all(artifact_dir)?; + let path = artifact_dir.join("certificate.json"); + let tmp = artifact_dir.join(".certificate.json.tmp"); + std::fs::write(&tmp, cert.to_json().to_string())?; + std::fs::rename(&tmp, &path)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cache_key_is_order_sensitive_and_stable() { + let a = cache_key("s", "p", "l", "lean 4", "2.8.0"); + let b = cache_key("s", "p", "l", "lean 4", "2.8.0"); + let c = cache_key("p", "s", "l", "lean 4", "2.8.0"); + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn certificate_roundtrip_preserves_verdicts() { + let cert = Certificate { + key: "k".into(), + status: Verdict::Unproved, + tier: "lean", + source_sha256: "s".into(), + library_sha256: "l".into(), + toolchain: "lean 4.35.0".into(), + module_sha256: "m".into(), + claims: vec![ClaimRecord { + id: "大额必经人工".into(), + function: "审批".into(), + status: Verdict::Unproved, + source_line: Some(21), + }], + span_map: vec![(41, 21)], + marqdo: "2.8.0".into(), + }; + let parsed = Certificate::from_json(&cert.to_json()).expect("roundtrip"); + assert_eq!(parsed.status, Verdict::Unproved); + assert_eq!(parsed.claims.len(), 1); + assert_eq!(parsed.claims[0].status, Verdict::Unproved); + assert_eq!(parsed.claims[0].source_line, Some(21)); + } + + #[test] + fn load_rejects_wrong_key_and_corrupt_file() { + let dir = std::env::temp_dir().join(format!("mq-cache-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert!(load(&dir, "k").is_none()); + let cert = Certificate { + key: "k1".into(), + status: Verdict::Proved, + tier: "lean", + source_sha256: "s".into(), + library_sha256: "l".into(), + toolchain: "t".into(), + module_sha256: "m".into(), + claims: vec![], + span_map: vec![], + marqdo: "2.8.0".into(), + }; + store(&dir, &cert).unwrap(); + assert!(load(&dir, "k1").is_some()); + assert!(load(&dir, "k2").is_none(), "键不合必须失效"); + std::fs::write(dir.join("certificate.json"), "{broken").unwrap(); + assert!(load(&dir, "k1").is_none(), "坏证书必须失效,不 panic"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/prove/driver.rs b/src/prove/driver.rs new file mode 100755 index 0000000..719a482 --- /dev/null +++ b/src/prove/driver.rs @@ -0,0 +1,509 @@ +//! Lean 驱动(设计 §8.4 / roadmap P1):工具链发现、语义底座构建、 +//! `lean` 调用(超时)、输出解析、`-- mq:` span 映射。 +//! +//! 与设计的偏差(§12 记录):驱动直接用 `lean -o` 构建 `MarqdoProof.olean`, +//! 不经 `lake`——运行时只依赖 `lean` 一个二进制,库源内嵌于本二进制 +//! (`include_str!`),按内容哈希落盘缓存;lakefile 仍保留给人/CI 使用。 + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; + +use crate::prove::Verdict; + +/// 内嵌语义底座源(发布二进制自带;构建期校验见 scripts/check-proof-library.sh)。 +pub const LIBRARY_SRC: &str = include_str!("../../doc/verification/skill-proof/MarqdoProof.lean"); + +/// 单条定理的判定结果。 +#[derive(Debug, Clone)] +pub struct ClaimOutcome { + /// 定理名(生成文件里的 `«函数.定理id»`)。 + pub theorem: String, + /// 归属函数显示名。 + pub function: String, + /// 定理 id(定理表里的 id)。 + pub claim: String, + pub status: Verdict, + /// 映射回 `.mq.md` 的行号(定理表所在行附近;找不到为 None)。 + pub source_line: Option, + /// Lean 原始报错(unproved/lean-error 时)。 + pub detail: String, +} + +/// 一次模块级 Lean 判定。 +#[derive(Debug, Clone)] +pub struct LeanOutcome { + pub status: Verdict, + pub claims: Vec, + /// 原始 stdout+stderr(诊断证据)。 + pub log: String, + /// lean 行 → mq 行 的映射表(进证书)。 + pub span_map: Vec<(u32, u32)>, +} + +/// 已发现的工具链。 +#[derive(Debug, Clone)] +pub struct Toolchain { + pub lean: PathBuf, + pub version: String, +} + +impl Toolchain { + /// 发现顺序(§8.4):显式路径 → `MARQDO_PROOF_LEAN` → `PATH`。 + /// 显式给出但不可用 → Err(**不**回退:避免"以为在跑 Lean 其实没有")。 + pub fn discover(explicit: Option<&Path>) -> Result> { + if let Some(path) = explicit { + let t = Self::from_path(path) + .with_context(|| format!("proof.lean_missing:{}", path.display()))?; + return Ok(Some(t)); + } + if let Ok(env_path) = std::env::var("MARQDO_PROOF_LEAN") { + if !env_path.trim().is_empty() { + let t = Self::from_path(Path::new(&env_path)).with_context(|| { + format!("proof.lean_missing:MARQDO_PROOF_LEAN={env_path}") + })?; + return Ok(Some(t)); + } + } + for dir in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) { + let candidate = dir.join("lean"); + if candidate.is_file() { + return Self::from_path(&candidate).map(Some); + } + } + Ok(None) + } + + fn from_path(path: &Path) -> Result { + let out = Command::new(path) + .arg("--version") + .output() + .with_context(|| format!("执行 {}", path.display()))?; + if !out.status.success() { + anyhow::bail!("{} --version 失败", path.display()); + } + let version = String::from_utf8_lossy(&out.stdout).trim().to_string(); + Ok(Toolchain { + lean: path.to_path_buf(), + version, + }) + } +} + +/// 语义底座目录(按内容哈希缓存),返回(目录,库 sha256)。 +pub fn ensure_library(cache_root: &Path, lean: &Toolchain) -> Result<(PathBuf, String)> { + let lib_sha = crate::prove::cache::sha256_hex(LIBRARY_SRC.as_bytes()); + let dir = cache_root.join(format!("library-{}", &lib_sha[..8])); + let src = dir.join("MarqdoProof.lean"); + let olean = dir.join("MarqdoProof.olean"); + if !olean.exists() { + std::fs::create_dir_all(&dir) + .with_context(|| format!("创建 {}", dir.display()))?; + std::fs::write(&src, LIBRARY_SRC) + .with_context(|| format!("写入 {}", src.display()))?; + let out = Command::new(&lean.lean) + .arg("-o") + .arg(&olean) + .arg(&src) + .output() + .with_context(|| format!("构建 MarqdoProof.olean"))?; + if !out.status.success() || !olean.exists() { + anyhow::bail!( + "MarqdoProof 库构建失败:\n{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + } + } + Ok((dir, lib_sha)) +} + +/// 判定一个生成的 Lean 模块。 +pub fn check_module( + lean: &Toolchain, + lib_dir: &Path, + generated: &Path, + generated_src: &str, + timeout: Duration, + max_heartbeats: Option, +) -> Result { + let span_map = span_map_of(generated_src); + let mut cmd = Command::new(&lean.lean); + cmd.env("LEAN_PATH", lib_dir); + if let Some(hb) = max_heartbeats { + cmd.arg(format!("-DmaxHeartbeats={hb}")); + } + cmd.arg(generated); + let (log, code, timed_out) = run_with_timeout(&mut cmd, timeout)?; + if timed_out { + return Ok(LeanOutcome { + status: Verdict::Error, + claims: Vec::new(), + log: format!("timeout after {}s\n{log}", timeout.as_secs()), + span_map, + }); + } + + // 归因:错误行 → 所在定理;每条定理都给结论(无错 → proved / sorry → unverified)。 + let theorems = theorem_spans(generated_src); + let mut claims: Vec = Vec::new(); + let mut any_unproved = false; + let mut any_error = false; + for (line_no, kind, message) in parse_lean_errors(&log) { + let info = theorems + .iter() + .find(|t| line_no >= t.start && line_no <= t.end); + let (theorem, claim, source_line) = match info { + Some(t) => ( + t.name.clone(), + t.claim.clone(), + t.source_line.or_else(|| map_to_source(line_no, &span_map)), + ), + // 错误在函数体/模块级(如 def 编译失败):claim 留空,走整体 Error。 + None => ( + String::new(), + String::new(), + map_to_source(line_no, &span_map), + ), + }; + let function = if theorem.is_empty() { + String::new() + } else { + function_of_theorem(&theorem, &claim) + }; + let status = match kind { + ErrorKind::Unsolved => { + any_unproved = true; + Verdict::Unproved + } + ErrorKind::Other => { + any_error = true; + Verdict::Error + } + }; + claims.push(ClaimOutcome { + theorem, + function, + claim, + status, + source_line, + detail: message, + }); + } + + for t in &theorems { + if claims.iter().any(|c| c.theorem == t.name) { + continue; + } + let (status, detail) = if t.has_sorry { + ( + Verdict::Unverified, + "策略 none:定理生成但不证明".to_string(), + ) + } else { + (Verdict::Proved, String::new()) + }; + claims.push(ClaimOutcome { + theorem: t.name.clone(), + function: function_of_theorem(&t.name, &t.claim), + claim: t.claim.clone(), + status, + source_line: t.source_line, + detail, + }); + } + claims.sort_by(|a, b| a.theorem.cmp(&b.theorem)); + + let status = if any_error || code.map(|c| c != 0).unwrap_or(false) && !any_unproved { + // 解析到其它编译错误,或退出码非 0 且没有可归属的未证目标 → 判定层错误。 + Verdict::Error + } else if any_unproved { + Verdict::Unproved + } else { + Verdict::Proved + }; + Ok(LeanOutcome { + status, + claims, + log, + span_map, + }) +} + +#[derive(Debug, Clone, Copy, PartialEq)] +enum ErrorKind { + Unsolved, + Other, +} + +/// 带超时的进程运行(无外部依赖:spawn + try_wait 轮询)。 +fn run_with_timeout( + cmd: &mut Command, + timeout: Duration, +) -> Result<(String, Option, bool)> { + use std::io::Read; + let mut child = cmd + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .context("spawn lean")?; + let deadline = Instant::now() + timeout; + loop { + if let Some(status) = child.try_wait()? { + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + if let Some(mut s) = child.stdout.take() { + let _ = s.read_to_end(&mut stdout); + } + if let Some(mut s) = child.stderr.take() { + let _ = s.read_to_end(&mut stderr); + } + let mut log = String::from_utf8_lossy(&stdout).to_string(); + log.push_str(&String::from_utf8_lossy(&stderr)); + return Ok((log, Some(status.code().unwrap_or(-1)), false)); + } + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + return Ok((String::new(), None, true)); + } + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// 解析 lean 输出里的 `:LINE:COL: error…`;`unsolved goals` 单独归类。 +/// lean 的报错头独占一行(`Generated/x.lean:41:0: error: unsolved goals`), +/// 后随目标上下文行;这里只取头行。 +fn parse_lean_errors(log: &str) -> Vec<(u32, ErrorKind, String)> { + let mut out = Vec::new(); + for line in log.lines() { + // 头行形如 `:LINE:COL: error: ...`(COL 可能省略)。 + let Some(col_idx) = line.find(": error") else { + continue; + }; + let pos = &line[..col_idx]; + let message = line[col_idx..].trim_start_matches(": ").to_string(); + // pos 形如 `:LINE:COL`(COL 可省略);取**倒数第二个**数字段。 + let fields: Vec<&str> = pos.rsplit(':').collect(); + let line_no: u32 = if let Ok(col) = fields[0].parse::() { + fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(col) + } else if let Ok(n) = fields[0].parse::() { + n + } else { + continue; + }; + let kind = if message.contains("unsolved goals") { + ErrorKind::Unsolved + } else { + ErrorKind::Other + }; + out.push((line_no, kind, message)); + } + out +} + +/// 生成文件里的一条定理。 +#[derive(Debug, Clone)] +pub struct TheoremInfo { + pub name: String, + pub start: u32, + pub end: u32, + /// 头注释里的定理 id:`-- 定理 (策略 …;mq: N)`。 + pub claim: String, + /// 头注释 `;mq: N` 的 N —— 定理表在 `.mq.md` 里的行。 + pub source_line: Option, + pub has_sorry: bool, +} + +/// 扫描生成文件:`-- 定理` 头注释 + `theorem` 行区间 + sorry 标记。 +pub fn theorem_spans(src: &str) -> Vec { + let lines: Vec<&str> = src.lines().collect(); + let mut out: Vec = Vec::new(); + // (name, start, claim, mq_line) + let mut current: Option<(String, u32, String, Option)> = None; + // 头注释暂存(claim id, mq 行)——紧随其后的 `theorem` 行使用。 + let mut pending: Option<(String, Option)> = None; + for (idx, line) in lines.iter().enumerate() { + let line_no = (idx + 1) as u32; + let trimmed = line.trim_start(); + if let Some(rest) = trimmed.strip_prefix("-- 定理 ") { + let head = rest.split('(').next().unwrap_or(rest).trim().to_string(); + let mq = rest + .rsplit_once("mq: ") + .and_then(|(_, n)| n.trim_end_matches(')').trim().parse().ok()); + pending = Some((head, mq)); + continue; + } + if let Some(rest) = trimmed.strip_prefix("theorem ") { + if let Some((name, start, claim, mq)) = current.take() { + out.push(theorem_info(src, name, start, line_no - 1, claim, mq)); + } + if let Some(name) = rest.split_whitespace().next() { + let (claim, mq) = pending.take().unwrap_or_default(); + current = Some((name.to_string(), line_no, claim, mq)); + } + } else if current.is_some() + && !trimmed.is_empty() + && !line.starts_with(' ') + && !line.starts_with('\t') + && !trimmed.starts_with("--") + { + let (name, start, claim, mq) = current.take().unwrap(); + out.push(theorem_info(src, name, start, line_no.saturating_sub(1), claim, mq)); + } + } + if let Some((name, start, claim, mq)) = current { + out.push(theorem_info(src, name, start, lines.len() as u32, claim, mq)); + } + out +} + +fn theorem_info( + src: &str, + name: String, + start: u32, + end: u32, + claim: String, + source_line: Option, +) -> TheoremInfo { + let has_sorry = src + .lines() + .skip(start.saturating_sub(1) as usize) + .take(end.saturating_sub(start) as usize + 1) + .any(|l| l.contains("sorry")); + TheoremInfo { + name, + start, + end, + claim, + source_line, + has_sorry, + } +} + +/// 定理名 → 归属函数:claim id 作后缀剥掉(函数名可含点,如 `台账.记录`)。 +fn function_of_theorem(theorem: &str, claim: &str) -> String { + let inner = theorem + .trim_start_matches('«') + .trim_end_matches('»') + .to_string(); + if !claim.is_empty() { + let suffix = format!(".{claim}"); + if let Some(f) = inner.strip_suffix(&suffix) { + return f.to_string(); + } + } + // 兜底:第一段(单段函数名)。 + inner + .split('.') + .next() + .unwrap_or(&inner) + .to_string() +} + +/// 生成文件的 `-- mq: LINE:COL` → (lean 行, mq 行)。 +pub fn span_map_of(src: &str) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + for (idx, line) in src.lines().enumerate() { + let trimmed = line.trim_start(); + if let Some(rest) = trimmed.strip_prefix("-- mq: ") { + if let Some((l, _)) = rest.split_once(':') { + if let Ok(mq_line) = l.trim().parse::() { + out.push(((idx + 1) as u32, mq_line)); + } + } + } + } + out +} + +/// lean 行号 → 最近的 `-- mq:` 注释对应的源行。 +fn map_to_source(lean_line: u32, span_map: &[(u32, u32)]) -> Option { + span_map + .iter() + .filter(|(l, _)| *l <= lean_line) + .map(|(_, m)| *m) + .next_back() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_lean_errors_distinguishes_line_from_col() { + // `:47:62: error: …` — 行 47,列 62;曾把列当行导致定理错配。 + let log = "Generated/x.lean:47:62: error: unsolved goals\n «结果» = …\n"; + let errs = parse_lean_errors(log); + assert_eq!(errs.len(), 1); + assert_eq!(errs[0].0, 47, "必须取行号而非列号"); + assert_eq!(errs[0].1, ErrorKind::Unsolved); + + let log2 = "Generated/x.lean:12:5: error: unknown identifier «Foo»\n"; + let errs2 = parse_lean_errors(log2); + assert_eq!(errs2[0].0, 12); + assert_eq!(errs2[0].1, ErrorKind::Other); + } + + #[test] + fn theorem_spans_reads_header_comment_claim_and_line() { + let src = "\ +-- mq: 14:1 +def «台账.记录» (env : Env) («金额» : Val) : Val × List Op := + («金额», []) +-- 定理 记过即记(策略 none;mq: 10) +theorem «台账.记录.记过即记» (env : Env) («金额» : Val) : + True := by + trivial +-- 定理 另一条(策略 auto;mq: 11) +theorem «台账.记录.另一条» (env : Env) : True := by + sorry +"; + let ts = theorem_spans(src); + assert_eq!(ts.len(), 2); + assert_eq!(ts[0].name, "«台账.记录.记过即记»"); + assert_eq!(ts[0].claim, "记过即记"); + assert_eq!(ts[0].source_line, Some(10)); + assert!(!ts[0].has_sorry); + assert_eq!(ts[1].claim, "另一条"); + assert_eq!(ts[1].source_line, Some(11)); + assert!(ts[1].has_sorry, "sorry 必须被识别为 unverified"); + } + + #[test] + fn function_of_theorem_strips_claim_suffix_not_first_segment() { + // 函数名可含点:台账.记录.记过即记 → 函数 = 台账.记录。 + assert_eq!( + function_of_theorem("«台账.记录.记过即记»", "记过即记"), + "台账.记录" + ); + assert_eq!( + function_of_theorem("«审批单.大额必经人工»", "大额必经人工"), + "审批单" + ); + assert_eq!(function_of_theorem("«孤定理»", ""), "孤定理"); + } + + #[test] + fn span_map_pairs_lean_and_mq_lines() { + let src = "-- mq: 14:1\nlet x := 1\n-- mq: 16:1\nlet y := 2\n"; + assert_eq!(span_map_of(src), vec![(1, 14), (3, 16)]); + } + + #[test] + fn map_to_source_finds_nearest_preceding_comment() { + let map = vec![(21, 14), (24, 16), (40, 33)]; + assert_eq!(map_to_source(21, &map), Some(14)); + assert_eq!(map_to_source(47, &map), Some(33)); + assert_eq!(map_to_source(1, &map), None); + } + + #[test] + fn toolchain_discovery_rejects_explicit_missing_path() { + let err = Toolchain::discover(Some(Path::new("/nonexistent/lean-绝无仅有"))) + .expect_err("显式坏路径必须报错(不回退)"); + assert!(format!("{err:#}").contains("proof.lean_missing")); + } +} diff --git a/src/prove/emit.rs b/src/prove/emit.rs new file mode 100755 index 0000000..b112e8d --- /dev/null +++ b/src/prove/emit.rs @@ -0,0 +1,808 @@ +//! Lean 生成(`doc/design/prove-cli.md` §4.1 ④ / §6)。 +//! +//! 确定性硬要求:同输入两次运行字节一致。做法:无时间戳、无绝对路径、 +//! 集合按首次出现顺序(降级本身确定)、映射键排序、浮点定长。 +//! +//! P0 形态:参数统一 `Val`(P1 起按契约提升为 `Int`/`String` 等以配合 +//! `structure Params` 与定理表);`result.ok/error` 内联为库构造器。 + +use std::collections::BTreeSet; +use std::fmt::Write as _; + +use crate::prove::ir::{ + BinOp, Expr as IrExpr, FnPlan, InterpPart, Plan, PlanTy, PureExpr, Step, UnOp, +}; + +/// 库名(verification/skill-proof 提供;P1 落地)。 +pub const LIBRARY_IMPORT: &str = "MarqdoProof"; + +/// 生成整个文件模块。返回 `(文件名, 内容)`。 +pub fn emit_module(plan: &Plan, module_stem: &str) -> (String, String) { + let namespace = namespace_of(module_stem); + let mut out = String::new(); + let _ = writeln!(out, "import {LIBRARY_IMPORT}"); + let _ = writeln!(out, "open MarqdoProof"); + // 机器生成的证明产物:关闭面向人写代码的 linter(未用变量/simp 参数是 + // 生成器的固定词汇表带来的正常噪声,不是问题)。 + let _ = writeln!(out, "set_option linter.unusedVariables false"); + let _ = writeln!(out, "set_option linter.unusedSimpArgs false"); + let _ = writeln!(out); + let _ = writeln!(out, "-- 由 `marqdo prove emit` 生成:确定性输出,请勿手改。"); + let _ = writeln!(out, "-- 源:{}(sha256 {})", plan.module, plan.source_sha256); + let _ = writeln!(out, "namespace Generated.{}", namespace); + let _ = writeln!(out); + + // 模块级 Op:所有函数的不透明操作并集(保持首次出现顺序,去重)。 + emit_op_inductive(&mut out, plan); + let _ = writeln!(out); + + for fun in &plan.functions { + emit_function(&mut out, fun); + let _ = writeln!(out); + emit_theorems(&mut out, fun); + let _ = writeln!(out); + } + + let _ = writeln!(out, "end Generated.{}", namespace); + let file_name = format!("{namespace}.lean"); + (file_name, out) +} + +/// 定理脚手架(§7.2):受限文法可解析的命题 → `theorem` 陈述 + `sorry` +/// 函数体里 if 的最大嵌套深度(0 = 无分支)。 +fn max_if_depth(steps: &[Step]) -> usize { + fn walk(steps: &[Step], depth: usize) -> usize { + let mut max = depth; + for s in steps { + if let Step::If { then, otherwise, .. } = s { + max = max.max(walk(then, depth + 1)); + max = max.max(walk(otherwise, depth + 1)); + } + } + max + } + walk(steps, 0) +} + +fn emit_theorems(out: &mut String, fun: &FnPlan) { + if fun.claims.is_empty() { + return; + } + let fun_name = lean_ident(&fun.name); + // 定理形参:`env` + 函数形参(Lean 标识符仅 ASCII,中文名入 guillemet)。 + // run 从空轨迹起跑(§2:轨迹是语法产物,函数入口为空)。 + let mut binders = String::from("(env : Env)"); + for param in &fun.params { + let _ = write!(binders, " ({} : Val)", lean_ident(¶m.name)); + } + let mut seen_theorem_names: BTreeSet = BTreeSet::new(); + for claim in &fun.claims { + let theorem_name = lean_ident(&format!("{}.{}", fun.name, claim.id)); + if !seen_theorem_names.insert(theorem_name.clone()) { + let _ = writeln!( + out, + "-- 定理 {} 重复(同 id 的定理只生成一次;check --proof 会给 proof.claim_duplicate)", + claim.id + ); + continue; + } + let premise_lean = claim + .premise + .as_deref() + .and_then(claim_to_lean_bool); + let conclusion_lean = claim_to_lean_bool(&claim.conclusion); + let premise_text = match (&claim.premise, premise_lean) { + (Some(_), Some(lean)) => format!(" («h_前提» : mqTruth {lean})"), + _ => String::new(), + }; + let tactic = claim.tactic.as_deref().unwrap_or("auto"); + let _ = writeln!(out, "-- 定理 {}(策略 {tactic};mq: {})", claim.id, claim.line); + match conclusion_lean { + Some(conclusion) => { + let run_args = fun + .params + .iter() + .map(|p| lean_ident(&p.name)) + .collect::>() + .join(" "); + let _ = writeln!(out, "theorem {theorem_name} {binders}{premise_text} :"); + let _ = writeln!(out, " ∀ («结果» : Val) («轨迹» : List Op),"); + // 等式方向:`(结果, 轨迹) = run …`(输出变量在左,simp_all 才能把 + // 输出值替换进目标;反向等式 simp 不会替换)。 + let _ = writeln!( + out, + " ((«结果», «轨迹») = {fun_name} env [] {run_args}) →" + ); + let _ = writeln!(out, " mqTruth {conclusion} := by"); + if tactic == "none" { + // 策略 none:定理生成但不证明(E4:状态 unverified, + // driver 依 sorry 判 unverified,绝不冒充 proved)。 + let _ = writeln!(out, " intro «结果» «轨迹» h_run"); + let _ = writeln!(out, " unfold {fun_name} at h_run"); + let _ = writeln!(out, " try split at h_run"); + let _ = writeln!(out, " all_goals"); + let _ = writeln!(out, " sorry"); + continue; + } + let _ = writeln!(out, " intro «结果» «轨迹» h_run"); + let _ = writeln!(out, " unfold {fun_name} at h_run"); + // 嵌套分支(else 里再嵌 if)需要逐层拆:按最大 if 深度发射 + // `try split at h_run`(拆无可拆时 try 吞掉,幂等)。 + for _ in 0..=max_if_depth(&fun.steps) { + let _ = writeln!(out, " try split at h_run"); + } + // 每个分支:simp_all(完整默认集处理 List.map/contains/length 的 + // 结构化消去;等式替换输出;Op.name 方程化简)+ 附加域定义 + // (mqAccess/mqResultOk/mqEq 字段与构造)。互斥比较假设由库中 + // @[simp] 矛盾引理消掉,剩余线性算术交给 omega。 + let _ = writeln!( + out, + " all_goals + simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqEq] + try + first + | exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim + | exact (mqLe_mqGt_false ‹mqLe _ (Val.int _) = true› ‹mqGt _ (Val.int _) = true›).elim + | exact (mqLt_mqGe_false ‹mqLt _ (Val.int _) = true› ‹mqGe _ (Val.int _) = true›).elim + | exact (mqGe_mqLt_false ‹mqGe _ (Val.int _) = true› ‹mqLt _ (Val.int _) = true›).elim + | omega" + ); + } + _ => { + let _ = writeln!( + out, + "-- 未生成:前提/结论超出受限文法(check --proof 会给具体诊断)" + ); + } + } + } +} + +/// 命名空间:文件名的安全标识符。Lean 4 的 `namespace` 命令**只接受 ASCII** +/// 名字(实测 `namespace 审批` 报 "expected token"),所以非 ASCII 字符 +/// 确定性编码为 `uXXXX`(码点十六进制),保证同名文件 → 同名空间。 +pub fn namespace_of(stem: &str) -> String { + let mut out = String::new(); + for ch in stem.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' { + out.push(ch); + } else if !ch.is_ascii() { + out.push_str(&format!("u{:04X}", ch as u32)); + } else { + out.push('_'); + } + } + if out.is_empty() { + out.push('M'); + } + if out.chars().next().is_some_and(|c| c.is_ascii_digit()) { + out.insert(0, 'M'); + } + out +} + +/// Lean 保留字(`def 审批` 这类裸中文名在 Lean 里是语法错误—— +/// 标识符仅 ASCII;非 ASCII 名一律进 guillemet `«…»`)。 +const LEAN_KEYWORDS: &[&str] = &[ + "fun", "let", "in", "do", "match", "with", "if", "then", "else", "true", "false", "and", "or", + "not", "def", "theorem", "abbrev", "structure", "inductive", "where", "deriving", "open", + "namespace", "end", "import", "by", "have", "show", "assume", "from", "at", "exists", +]; + +pub(crate) fn lean_ident(name: &str) -> String { + let ascii_safe = !name.is_empty() + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && !name.chars().next().is_some_and(|c| c.is_ascii_digit()); + if LEAN_KEYWORDS.contains(&name) || name == "env" { + // 关键字与本模块保留名(函数体里用户变量撞名时改名)。 + // 改名形式必须纯 ASCII(裸 `v_结果` 仍是 Lean 语法错误)。 + format!("v_{}", namespace_of(name)) + } else if name == "轨迹" || name == "结果" || name == "h_前提" { + // 定理作用域保留名:函数体里的用户变量/形参撞名 → v_ 前缀 + // (定理的 ∀ 绑定名由 emit_theorems/claim_term 直接写 `«…»`,不走这里)。 + format!("v_{}", namespace_of(name)) + } else if ascii_safe { + name.to_string() + } else { + // 中文名/含点/含特殊字符 → guillemet;`:` 会截断记号,替换为 `_`。 + format!("«{}»", name.replace(':', "_")) + } +} + +fn op_ctor(op_id: &str) -> String { + // `调用:人工审核` → `«调用_人工审核»`(guillemet 标识符)。 + // Lean 的 guillemet 记号不接受 `:`(会截断记号),标识符里替换为 `_`; + // Op.name 的**字符串显示**保持原始 id,轨迹名不变。 + let safe = op_id.replace(':', "_"); + format!("«{safe}»") +} + +fn emit_op_inductive(out: &mut String, plan: &Plan) { + // 收集 op(首现顺序去重)。 + let mut ops: Vec<&crate::prove::ir::OpDecl> = Vec::new(); + for fun in &plan.functions { + for op in &fun.ops { + if !ops.iter().any(|o| o.id == op.id) { + ops.push(op); + } + } + } + if ops.is_empty() { + let _ = writeln!(out, "inductive Op where"); + // 占位构造器也走 op_ctor(裸中文构造器是 Lean 语法错误)。 + let _ = writeln!(out, " | {} deriving Repr, BEq", op_ctor("无操作")); + let _ = writeln!(out); + let _ = writeln!(out, "def Op.name : Op → String"); + let _ = writeln!(out, " | .{} => \"\"", op_ctor("无操作")); + return; + } + let _ = writeln!(out, "inductive Op where"); + for op in &ops { + let fields = match op.arity { + 0 => String::new(), + n => (1..=n) + .map(|i| format!("(«参数{i}» : Val)")) + .collect::>() + .join(" "), + }; + let _ = writeln!(out, " | {} {}", op_ctor(&op.id), fields); + } + let _ = writeln!(out, " deriving Repr, BEq"); + let _ = writeln!(out); + let _ = writeln!(out, "def Op.name : Op → String"); + for op in &ops { + let label = op.id.strip_prefix("调用:").unwrap_or(&op.id); + // 多参构造器的模式必须绑定实参(`_ _`),否则类型不匹配。 + let blanks = " _".repeat(op.arity); + let _ = writeln!(out, " | .{} {}=> \"{}\"", op_ctor(&op.id), blanks, label); + } + let _ = writeln!(out); + // Env 依赖本文件的 Op(库无法预知),所以每文件自带: + // `env` 是"不透明操作 → 返回值"的任意函数——后置条件对一切 env 成立。 + let _ = writeln!(out, "abbrev Env := Op → Val"); +} + +fn emit_function(out: &mut String, fun: &FnPlan) { + let name = lean_ident(&fun.name); + // 参数列表:`def f (env : Env) (轨迹 : List Op) (p1 : Val) …` + let mut sig = String::from("(env : Env) («轨迹» : List Op)"); + for param in &fun.params { + let _ = write!(sig, " ({} : Val)", lean_ident(¶m.name)); + } + let _ = writeln!(out, "-- {} 返回 {}", fun.name, fun.result_ty.name()); + let _ = writeln!(out, "def {name} {sig} : Val × List Op :="); + if fun.steps.is_empty() { + let _ = writeln!(out, " (Val.none, «轨迹»)"); + return; + } + emit_seq(out, &mut String::from(" "), &[&fun.steps]); +} + +/// 续延式直接降级(§6.3):`chunks` 是"当前点之后还要执行的所有步骤"。 +/// +/// `if` 的两臂续延是「臂内步骤 + 臂外剩余」——执行继续到分支之后, +/// 除非某臂已提前 `Return`。这是 P0 第一版的续延丢失 bug 的修正: +/// 分支绝不能吞掉后续语句。 +fn emit_seq(out: &mut String, indent: &mut String, chunks: &[&[Step]]) { + match chunks.split_first() { + None => { + // 走到末尾都没有 return:Marqdo 返回 None(诚实占位,不译运行时)。 + let _ = writeln!(out, "{indent}(Val.none, «轨迹»)"); + } + Some((first, rest)) => match first.split_first() { + None => emit_seq(out, indent, rest), + Some((step, more)) => emit_step(out, indent, step, more, rest), + }, + } +} + +fn tail_chunks<'a>(more: &'a [Step], rest: &[&'a [Step]]) -> Vec<&'a [Step]> { + let mut next: Vec<&'a [Step]> = Vec::with_capacity(rest.len() + 1); + if !more.is_empty() { + next.push(more); + } + next.extend_from_slice(rest); + next +} + +fn emit_step(out: &mut String, indent: &mut String, step: &Step, more: &[Step], rest: &[&[Step]]) { + match step { + Step::Bind { var, expr, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + match expr { + IrExpr::Op { id, args } => { + let _ = writeln!( + out, + "{indent}let {} := env (Op.{} {})", + lean_ident(var), + op_ctor(id), + emit_args(args) + ); + let _ = writeln!( + out, + "{indent}let «轨迹» := «轨迹» ++ [Op.{} {}]", + op_ctor(id), + emit_args(args) + ); + } + other => { + let _ = writeln!( + out, + "{indent}let {} := {}", + lean_ident(var), + emit_expr(other) + ); + } + } + emit_seq(out, indent, &tail_chunks(more, rest)); + } + Step::Return { expr, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + match expr { + IrExpr::Op { id, args } => { + let _ = writeln!( + out, + "{indent}(env (Op.{} {}), «轨迹» ++ [Op.{} {}])", + op_ctor(id), + emit_args(args), + op_ctor(id), + emit_args(args) + ); + } + other => { + let _ = writeln!(out, "{indent}({}, «轨迹»)", emit_expr(other)); + } + } + } + Step::Trace { op, args, line } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + let _ = writeln!( + out, + "{indent}let «轨迹» := «轨迹» ++ [Op.{} {}]", + op_ctor(op), + emit_args(args) + ); + emit_seq(out, indent, &tail_chunks(more, rest)); + } + Step::If { + cond, + then, + otherwise, + line, + } => { + let _ = writeln!(out, "{indent}-- mq: {line}:1"); + let _ = writeln!(out, "{indent}if {} then", emit_cond(cond)); + indent.push_str(" "); + let then_chunks = { + let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); + v.push(then); + v.extend_from_slice(&tail_chunks(more, rest)); + v + }; + emit_seq(out, indent, &then_chunks); + indent.truncate(indent.len() - 2); + let _ = writeln!(out, "{indent}else"); + indent.push_str(" "); + let else_chunks = { + let mut v: Vec<&[Step]> = Vec::with_capacity(rest.len() + 1); + v.push(otherwise); + v.extend_from_slice(&tail_chunks(more, rest)); + v + }; + emit_seq(out, indent, &else_chunks); + indent.truncate(indent.len() - 2); + } + } +} + +/// 条件:比较直接产出 Bool;其余经 `mqTruth`(Val → Bool)。 +fn emit_cond(cond: &PureExpr) -> String { + match cond { + PureExpr::Bin { + operator: BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, + .. + } => emit_pure(cond), + _ => format!("mqTruth ({})", emit_pure(cond)), + } +} + +fn emit_args(args: &[PureExpr]) -> String { + args.iter() + .map(|a| emit_pure(a)) + .collect::>() + .join(" ") +} + +fn emit_expr(expr: &IrExpr) -> String { + match expr { + IrExpr::Pure(pure) => emit_pure(pure), + // 语句层不会遇到(Op 已在 Bind/Return/Trace 处理);防御性回退。 + IrExpr::Op { id, args } => { + format!("env (Op.{} {})", op_ctor(id), emit_args(args)) + } + IrExpr::Formula => "Val.none -- $$公式$$:不透明值".into(), + IrExpr::Code => "Val.none -- code 围栏:不透明值".into(), + } +} + +fn emit_pure(pure: &PureExpr) -> String { + match pure { + PureExpr::Int(i) => format!("(Val.int {i})"), + PureExpr::Num(n) => format!("(Val.num {n:?})"), + PureExpr::Bool(b) => format!("(Val.bool {})", if *b { "true" } else { "false" }), + PureExpr::Text(s) => format!("(Val.text {})", lean_string(s)), + PureExpr::None => "Val.none".into(), + PureExpr::Var(name) => lean_ident(name), + PureExpr::Bin { operator, left, right } => { + let (l, r) = (emit_pure(left), emit_pure(right)); + match operator { + BinOp::Add => format!("(mqAdd {l} {r})"), + BinOp::Sub => format!("(mqSub {l} {r})"), + BinOp::Mul => format!("(mqMul {l} {r})"), + BinOp::Div => format!("(mqDiv {l} {r})"), + BinOp::Eq => format!("(mqEq {l} {r})"), + BinOp::Ne => format!("(mqNot (mqEq {l} {r}))"), + BinOp::Lt => format!("(mqLt {l} {r})"), + BinOp::Le => format!("(mqLe {l} {r})"), + BinOp::Gt => format!("(mqGt {l} {r})"), + BinOp::Ge => format!("(mqGe {l} {r})"), + BinOp::And => format!("(mqAnd {l} {r})"), + BinOp::Or => format!("(mqOr {l} {r})"), + } + } + PureExpr::Un { operator, expr } => { + let e = emit_pure(expr); + match operator { + UnOp::Not => format!("(mqNot {e})"), + UnOp::Neg => format!("(mqNeg {e})"), + } + } + PureExpr::Index { base, key } => { + format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) + } + PureExpr::Access { base, key } => { + format!("(mqAccess {} {})", emit_pure(base), lean_string(key)) + } + PureExpr::Len(inner) => format!("(mqLen {})", emit_pure(inner)), + PureExpr::Interp(parts) => emit_interp(parts), + PureExpr::List(items) => { + let inner: Vec = items.iter().map(emit_pure).collect(); + format!("(Val.list [{}])", inner.join(", ")) + } + PureExpr::Map(entries) => { + let inner: Vec = entries + .iter() + .map(|(k, v)| format!("({}, {})", lean_string(k), emit_pure(v))) + .collect(); + format!("(Val.map [{}])", inner.join(", ")) + } + PureExpr::Ctor { name, args } => emit_ctor(name, args), + } +} + +/// 内联构造器:`result.ok/error/value_or` 映射到库辅助函数 +/// (Val 字面 map,与 lib/result 行为一致);`mq.*` 直呼。 +fn emit_ctor(name: &str, args: &[PureExpr]) -> String { + let rendered: Vec = args.iter().map(emit_pure).collect(); + match (name, rendered.as_slice()) { + ("result.ok", [value]) => format!("(mqResultOk {value})"), + ("result.error", [code, message, operation]) => { + format!("(mqResultError {code} {message} {operation})") + } + ("result.value_or", [r, default]) => format!("(mqValueOr {r} {default})"), + _ => format!("({} {})", name.replace('.', "_"), rendered.join(" ")), + } +} + +fn emit_interp(parts: &[InterpPart]) -> String { + let mut pieces: Vec = Vec::new(); + for part in parts { + match part { + InterpPart::Lit(text) => pieces.push(format!("(Val.text {})", lean_string(text))), + InterpPart::Var(name) => pieces.push(lean_ident(name)), + } + } + if pieces.is_empty() { + return "(Val.text \"\")".into(); + } + let mut it = pieces.into_iter(); + let first = it.next().unwrap(); + it.fold(first, |acc, piece| format!("(mqAppend {acc} {piece})")) +} + +/// Lean 字符串字面量(转义 `\` `"` 与控制字符;非 ASCII 原样保留)。 +fn lean_string(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// 模块 stem(命名空间用):去扩展名的文件名。 +pub fn stem_of(path: &str) -> String { + std::path::Path::new(path) + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "Module".into()) +} + +/// PlanTy 的 Lean 侧提示注释(P1 提升类型用;P0 参数统一 Val)。 +pub fn ty_hint(ty: &PlanTy) -> &'static str { + match ty { + PlanTy::Int => "Int", + PlanTy::Num => "Float", + PlanTy::Bool => "Bool", + PlanTy::Text => "String", + _ => "Val", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prove::ir::{Expr, FnPlan, OpDecl, PlanTy, Step}; + + #[test] + fn lean_ident_keeps_chinese_and_quotes_dotted() { + // Lean 标识符仅 ASCII:中文名入 guillemet。 + assert_eq!(lean_ident("金额"), "«金额»"); + assert_eq!(lean_ident("审批台.审批"), "«审批台.审批»"); + // 纯 ASCII 名保持裸写。 + assert_eq!(lean_ident("x_1"), "x_1"); + // 与本模块保留名冲突的变量必须改名(确定性映射)。 + assert_eq!(lean_ident("env"), "v_env"); + assert_eq!(lean_ident("轨迹"), "v_u8F68u8FF9"); + assert_eq!(lean_ident("结果"), "v_u7ED3u679C"); + assert_eq!(lean_ident("let"), "v_let"); + } + + #[test] + fn lean_string_escapes_quotes_and_newline_only() { + assert_eq!(lean_string("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(lean_string("行\n进"), "\"行\\n进\""); + assert_eq!(lean_string("中文"), "\"中文\""); + } + + #[test] + fn namespace_sanitizes_unsafe_chars_deterministically() { + assert_eq!(namespace_of("approval.mq"), "approval_mq"); + assert_eq!(namespace_of("示例"), "u793Au4F8B"); + // 命名空间绝不含非 ASCII(Lean namespace 命令只收 ASCII)。 + assert_eq!(namespace_of("1abc"), "M1abc"); + assert_eq!(namespace_of(""), "M"); + } + + #[test] + fn emit_module_is_deterministic_and_sorted_by_first_appearance() { + let plan = Plan { + schema: crate::prove::ir::SCHEMA, + module: "demo.mq.md".into(), + source_sha256: "ab".repeat(32), + functions: vec![ + FnPlan { + name: "机器.运转".into(), + params: vec![], + result_ty: PlanTy::Any, + ops: vec![ + OpDecl { + id: "调用:写盘".into(), + effect: "fs.write".into(), + params: vec![], + arity: 1, + }, + OpDecl { + id: "调用:读盘".into(), + effect: "fs.read".into(), + params: vec![], + arity: 0, + }, + ], + steps: vec![Step::Bind { + var: "回执".into(), + expr: Expr::Op { + id: "调用:写盘".into(), + args: vec![], + }, + line: 3, + }], + effects: vec!["fs.write".into()], + claims: vec![], + assumptions: vec![], + }, + FnPlan { + name: "从机.待机".into(), + params: vec![], + result_ty: PlanTy::Any, + ops: vec![], + steps: vec![Step::Return { + expr: Expr::Pure(PureExpr::Int(7)), + line: 9, + }], + effects: vec![], + claims: vec![], + assumptions: vec![], + }, + ], + }; + let (name1, out1) = emit_module(&plan, "demo"); + let (name2, out2) = emit_module(&plan, "demo"); + assert_eq!(name1, name2); + assert_eq!(out1, out2, "两次生成必须字节一致"); + assert!(out1.contains("import MarqdoProof")); + assert!(out1.contains("namespace Generated.demo")); + // Op 按首现顺序:写盘在读盘前。 + let write_pos = out1.find("«调用_写盘»").expect("write op"); + let read_pos = out1.find("«调用_读盘»").expect("read op"); + assert!(write_pos < read_pos); + // Op 元数:读盘 0 元 → 无参构造器。 + assert!(out1.contains("| «调用_读盘»"), "{out1}"); + // Return 直译成对(字面量自带括号,形成双重括号——合法 Lean)。 + assert!(out1.contains("((Val.int 7), «轨迹»)"), "{out1}"); + // 溯源注释。 + assert!(out1.contains("-- mq: 3:1")); + // 无时间戳。 + assert!(!out1.contains("20") || !out1.contains("T"), "no timestamps"); + } + + #[test] + fn empty_plan_emits_no_op_ctors() { + let plan = Plan { + schema: crate::prove::ir::SCHEMA, + module: "空.mq.md".into(), + source_sha256: "cd".repeat(32), + functions: vec![], + }; + let (name, out) = emit_module(&plan, "空"); + assert_eq!(name, "u7A7A.lean"); + // 占位构造器同样 guillemet 化(裸中文构造器是 Lean 语法错误)。 + assert!(out.contains("| «无操作»")); + assert!(!out.contains("«调用:")); + } +} + + +/// 受限命题文本 → Lean Bool 项;解析失败或含未知形状 → None(emit 侧留注释)。 +/// 语义映射(§7.2): +/// - `结果.ok / 结果.value / 结果.error` → `mqAccess 结果 "ok"` 等; +/// - `包含(轨迹, s)` → `(轨迹.map Op.name).contains s`; +/// - `长度(轨迹)` → `(轨迹.length : Nat)`,与整数比较走 Nat 运算; +/// - 形参/算术/比较 → mq 辅助函数(Val 面)。 +fn claim_to_lean_bool(text: &str) -> Option { + let toks = super::proof_check::tokenize_claim(text).ok()?; + let (_, ast) = super::proof_check::parse_claim_expr(&toks).ok()?; + claim_term(&ast) +} + +/// `长度(轨迹)`:Nat 语境的锚点(轨迹长度与整数比较必须走 Nat 运算, +/// 否则 `mqEq : Val → Val → Bool` 类型不匹配)。 +fn is_trace_len(ast: &super::proof_check::ClaimAst) -> bool { + matches!( + ast, + super::proof_check::ClaimAst::Call { name, args } + if name == "长度" + && matches!(args.first(), Some(super::proof_check::ClaimAst::Var(v)) if v == "轨迹") + ) +} + +fn claim_term(ast: &super::proof_check::ClaimAst) -> Option { + use super::proof_check::{ClaimAst as A, CTok}; + match ast { + A::Lit(CTok::Int(i)) => Some(format!("(Val.int {i})")), + A::Lit(CTok::Num(n)) => Some(format!("(Val.num {n:?})")), + A::Lit(CTok::Bool(b)) => Some(format!("(Val.bool {b})")), + A::Lit(CTok::Text(s)) => Some(format!("(Val.text {})", lean_string(s))), + A::Lit(_) => None, + A::Var(name) => { + // 定理作用域里 `结果`/`轨迹` 是 ∀ 绑定的输出名(`«结果»`/`«轨迹»`, + // 不加 v_ 前缀);`根.字段` → mqAccess 字段读取;其余按标识符规则。 + let (root, field) = match name.split_once('.') { + Some((r, f)) => (r, Some(f)), + None => (name.as_str(), None), + }; + let term = match (root, field) { + ("结果", Some(f)) => format!("(mqAccess «结果» {})", lean_string(f)), + ("轨迹", Some(f)) => format!("(mqAccess «轨迹» {})", lean_string(f)), + ("结果", None) => "«结果»".to_string(), + ("轨迹", None) => "«轨迹»".to_string(), + _ => lean_ident(name), + }; + Some(term) + } + A::Call { name, args } => { + // `轨迹`(定理作用域的输出轨迹)上的谓词有专用 Lean 形式。 + let on_trace = matches!(args.first(), Some(A::Var(v)) if v == "轨迹"); + match (name.as_str(), args.len(), on_trace) { + ("包含", 2, true) => { + let item = strip_val_text(&claim_term(&args[1])?); + Some(format!("((«轨迹».map Op.name).contains {item})")) + } + ("长度", 1, true) => Some("(«轨迹».length : Nat)".to_string()), + _ => { + let mut rendered = Vec::with_capacity(args.len()); + for arg in args { + rendered.push(claim_term(arg)?); + } + let term = match (name.as_str(), rendered.as_slice()) { + ("包含", [list, item]) => format!("(mqContains {list} {item})"), + ("长度", [list]) => format!("(mqNatOf (mqLen {list}))"), + ("下标", [list, index]) => { + format!("(mqAccess {list} (mqStrOfNat {index}))") + } + _ => format!("({} {})", name, rendered.join(" ")), + }; + Some(term) + } + } + } + A::Bin { op, left, right } => { + // Nat 语境:操作数是 `长度(轨迹)` 或整数字面量 → 原生 Nat 运算。 + if is_trace_len(left) || is_trace_len(right) { + let nat = |a: &A| -> Option { + if is_trace_len(a) { + Some("(«轨迹».length : Nat)".to_string()) + } else if let A::Lit(CTok::Int(i)) = a { + Some(i.to_string()) + } else { + None + } + }; + let (l, r) = (nat(left)?, nat(right)?); + return match *op { + "=" => Some(format!("({l} = {r})")), + "≠" => Some(format!("({l} ≠ {r})")), + "<" => Some(format!("({l} < {r})")), + "≤" => Some(format!("({l} ≤ {r})")), + ">" => Some(format!("({l} > {r})")), + "≥" => Some(format!("({l} ≥ {r})")), + "+" => Some(format!("({l} + {r})")), + "-" => Some(format!("({l} - {r})")), + _ => None, + }; + } + let (l, r) = (claim_term(left)?, claim_term(right)?); + let term = match *op { + "+" => format!("(mqAdd {l} {r})"), + "-" => format!("(mqSub {l} {r})"), + "*" => format!("(mqMul {l} {r})"), + "/" => format!("(mqDiv {l} {r})"), + "=" => format!("(mqEq {l} {r})"), + "≠" => format!("(mqNot (mqEq {l} {r}))"), + "<" => format!("(mqLt {l} {r})"), + "≤" => format!("(mqLe {l} {r})"), + ">" => format!("(mqGt {l} {r})"), + "≥" => format!("(mqGe {l} {r})"), + "且" => format!("(mqAnd {l} {r})"), + "或" => format!("(mqOr {l} {r})"), + _ => return None, + }; + Some(term) + } + A::Un { op, expr } => { + let e = claim_term(expr)?; + let term = match *op { + "非" => format!("(mqNot {e})"), + "-" => format!("(mqNeg {e})"), + _ => return None, + }; + Some(term) + } + } +} + +/// `包含` 的成员是文本字面量时剥掉 Val 包裹(`(Val.text "x")` → `"x"`)。 +fn strip_val_text(term: &str) -> String { + term.strip_prefix("(Val.text ") + .and_then(|rest| rest.strip_suffix(')')) + .map(|s| s.to_string()) + .unwrap_or_else(|| term.to_string()) +} diff --git a/src/prove/ir.rs b/src/prove/ir.rs new file mode 100755 index 0000000..75e3616 --- /dev/null +++ b/src/prove/ir.rs @@ -0,0 +1,296 @@ +//! Plan IR(`doc/design/prove-cli.md` §4.2)。 +//! +//! `plan.json` 的形状:版本化、可序列化、无时间戳。缓存键与论文工具都以 +//! 它为输入。表达式分两层:[`PureExpr`] 是可翻译成 Lean 项的纯片段; +//! 其余调用一律是不透明操作([`Step::Trace`] 引用 [`FnPlan::ops`])。 + +use serde::Serialize; + +/// IR schema version(缓存失效用;形状变化必须 +1)。 +pub const SCHEMA: u32 = 1; + +/// 契约类型在 Plan IR 里的形状(`contract::Ty` 的可序列化投影)。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PlanTy { + Int, + Num, + Bool, + Text, + List, + Map, + /// 内联 `Result` 构造器(`lib/result`):`ok/value/error` 三字段结构。 + Result, + /// 未知/任意(`--no-strict-types` 或未标注)。定理只能做等式判断。 + Any, + /// `# 对象` 类型实例。 + Object(String), +} + +impl PlanTy { + pub fn name(&self) -> String { + match self { + PlanTy::Int => "int".into(), + PlanTy::Num => "num".into(), + PlanTy::Bool => "bool".into(), + PlanTy::Text => "text".into(), + PlanTy::List => "list".into(), + PlanTy::Map => "map".into(), + PlanTy::Result => "result".into(), + PlanTy::Any => "any".into(), + PlanTy::Object(n) => n.clone(), + } + } + + pub fn from_contract(ty: &crate::contract::Ty) -> PlanTy { + match ty { + crate::contract::Ty::Any => PlanTy::Any, + crate::contract::Ty::Text => PlanTy::Text, + crate::contract::Ty::Number => PlanTy::Int, + crate::contract::Ty::Bool => PlanTy::Bool, + crate::contract::Ty::List => PlanTy::List, + crate::contract::Ty::Map => PlanTy::Map, + crate::contract::Ty::Object(n) => PlanTy::Object(n.clone()), + } + } +} + +/// 二元运算(纯片段内的算术/比较/布尔)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum BinOp { + Add, + Sub, + Mul, + Div, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + And, + Or, +} + +impl BinOp { + pub fn from_ast(op: crate::ast::BinaryOp) -> BinOp { + use crate::ast::BinaryOp as A; + match op { + A::Add => BinOp::Add, + A::Sub => BinOp::Sub, + A::Mul => BinOp::Mul, + A::Div => BinOp::Div, + A::Eq => BinOp::Eq, + A::Ne => BinOp::Ne, + A::Lt => BinOp::Lt, + A::Le => BinOp::Le, + A::Gt => BinOp::Gt, + A::Ge => BinOp::Ge, + A::And => BinOp::And, + A::Or => BinOp::Or, + } + } +} + +/// 一元运算。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum UnOp { + Not, + Neg, +} + +/// 纯表达式:可翻译成 Lean 项的部分(§4.2 表达式分层)。 +/// 相邻标记(`kind` + `value`):新类型变体也能稳定序列化。 +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum PureExpr { + Int(i64), + Num(f64), + Bool(bool), + Text(String), + None, + Var(String), + Bin { + operator: BinOp, + left: Box, + right: Box, + }, + Un { + operator: UnOp, + expr: Box, + }, + /// 映射字段/下标读取:`` [键](映射) `` / `` `m`[^键] ``。 + Index { + base: Box, + key: String, + }, + /// `access(base, key)`(含 `取`/`取值` 别名)。 + Access { + base: Box, + key: String, + }, + /// `len(value)`(含 `长度` 别名)。 + Len(Box), + /// 文本插值拼接(`` "共 `n` 条" `` → append 序列)。 + Interp(Vec), + List(Vec), + Map(Vec<(String, PureExpr)>), + /// 已内联的构造器调用(`result.success/failure`)。 + Ctor { + name: String, + args: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "part", content = "value", rename_all = "snake_case")] +pub enum InterpPart { + Lit(String), + Var(String), +} + +/// 语句(§4.3 接受矩阵的接受侧)。 +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Step { + /// `**x = 表达式**` + Bind { + var: String, + expr: Expr, + line: u32, + }, + /// `**返回表达式**`(粗体无赋值) + Return { + expr: Expr, + line: u32, + }, + /// `1. 条件 / 2. *`(else 由 `cond: None` 表示) + If { + cond: PureExpr, + then: Vec, + otherwise: Vec, + line: u32, + }, + /// 语句形式调用(`> 调用` / `*语句*`):值丢弃,但仍进轨迹。 + Trace { + op: String, + args: Vec, + line: u32, + }, +} + +/// 语句内表达式:纯表达式或不透明操作调用。 +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Expr { + Pure(PureExpr), + /// 不透明操作调用:`ops` 里的 `id`(接收者/插件/有效应的调用)。 + Op { + id: String, + args: Vec, + }, + /// `$$…$$` 公式:不透明值,不翻译。 + Formula, + /// ``` 围栏 code 值(不经 parse 拒绝时降为不透明)。 + Code, +} + +/// 一个不透明操作的声明(Lean 里是 `Op` 构造器 + `Env` 查询键)。 +#[derive(Debug, Clone, Serialize)] +pub struct OpDecl { + pub id: String, + pub effect: String, + pub params: Vec<(String, PlanTy)>, + /// 实参个数(首次出现处;同名操作元数一致)。 + pub arity: usize, +} + +/// 定理占位(P1 起填充;P0 恒为空,保持 `plan.json` 形状稳定)。 +#[derive(Debug, Clone, Serialize)] +pub struct ClaimPlan { + pub id: String, + pub premise: Option, + pub conclusion: String, + pub tactic: Option, + /// 定理表行号(锚定源码漂移)。 + pub line: u32, +} + +/// 假设表条目(T3;P0 恒为空)。 +#[derive(Debug, Clone, Serialize)] +pub struct AssumptionPlan { + pub op: String, + pub premise: Option, + pub postcondition: String, +} + +/// 单个函数的 Plan。 +#[derive(Debug, Clone, Serialize)] +pub struct FnPlan { + pub name: String, + pub params: Vec, + pub result_ty: PlanTy, + /// 该函数用到的不透明操作(按出现顺序,去重)。 + pub ops: Vec, + pub steps: Vec, + pub effects: Vec, + pub claims: Vec, + pub assumptions: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ParamPlan { + pub name: String, + pub ty: PlanTy, + pub has_default: bool, +} + +/// 整个文件的 Plan。 +#[derive(Debug, Clone, Serialize)] +pub struct Plan { + pub schema: u32, + /// 相对当前工作目录的路径(确定性要求:无绝对路径、无时间戳)。 + pub module: String, + pub source_sha256: String, + pub functions: Vec, +} + +impl Plan { + /// 规范化 JSON(键序稳定、无空白差异;两次运行必须字节一致)。 + pub fn to_stable_json(&self) -> String { + let value = serde_json::to_value(self).expect("plan serializes"); + format_value(&value) + } +} + +/// 确定性 JSON 序列化:对象键排序、数组保序、定长浮点。 +fn format_value(value: &serde_json::Value) -> String { + use serde_json::Value; + match value { + Value::Null => "null".into(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => n.to_string(), + Value::String(s) => serde_json::to_string(s).expect("string serializes"), + Value::Array(items) => { + let inner: Vec = items.iter().map(format_value).collect(); + format!("[{}]", inner.join(",")) + } + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + let inner: Vec = keys + .into_iter() + .map(|k| { + format!( + "{}:{}", + serde_json::to_string(k).expect("key serializes"), + format_value(&map[k]) + ) + }) + .collect(); + format!("{{{}}}", inner.join(",")) + } + } +} diff --git a/src/prove/lower.rs b/src/prove/lower.rs new file mode 100755 index 0000000..05a1ccc --- /dev/null +++ b/src/prove/lower.rs @@ -0,0 +1,1261 @@ +//! 降级:AST → Plan IR(`doc/design/prove-cli.md` §4.1 ②)。 +//! +//! 三条硬边界(设计 §2.2)——`while`/递归/动态派发(函数值、无法解析的裸名) +//! **拒绝,不降级**;静态可拼写的未知调用(方法、`工程.成员` 一类插件路径) +//! 一律不透明化为 [`ir::Expr::Op`](诚实:行为完全未知,效应照 sema 标注)。 +//! 本模块不执行任何代码,只读 AST。 + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use anyhow::Result; + +use crate::ast::{self, Arg, BinaryOp, CallExpr, Expr, Function, Module, Stmt}; +use crate::diagnostics::{Diagnostic, Severity, Span}; +use crate::prove::ir::{ + BinOp, ClaimPlan, Expr as IrExpr, FnPlan, InterpPart, OpDecl, ParamPlan, Plan, PlanTy, + PureExpr, Step, UnOp, SCHEMA, +}; +use crate::sema::bind::{call_display, resolve_for_exec}; +use crate::host::HostFn; +use crate::sema::ir::EffectSet; +use crate::sema::resolution::Target; + +/// 单个函数的降级产物(plan 或拒绝原因)。 +#[derive(Debug)] +pub struct Lowered { + pub display: String, + /// 对象体(`# 类型`)不是可证单元:不证也不算拒绝。 + pub is_object: bool, + pub plan: Option, + /// 全部拒绝原因(`proof.while` / `proof.recursion` / `proof.dynamic_call` / …)。 + pub rejected: Vec, +} + +/// 降级上下文:模块 + 效应表(来自 sema;缺失时效应保守记 `unknown`)。 +pub struct Lowerer<'m> { + module: &'m Module, + /// `(file, display_name) → effects`(sema 闭包 artifact 的源位置键)。 + effects: BTreeMap<(String, String), EffectSet>, + allow_opaque: BTreeSet, +} + +impl<'m> Lowerer<'m> { + pub fn new( + module: &'m Module, + effects: BTreeMap<(String, String), EffectSet>, + _strict_types: bool, + allow_opaque: &[String], + ) -> Self { + Self { + module, + effects, + allow_opaque: allow_opaque.iter().cloned().collect(), + } + } + + /// 降级全部函数(含子函数),按源码顺序。 + pub fn lower_module(&self) -> Vec { + let mut out = Vec::new(); + self.lower_functions(self.module.functions.as_slice(), "", &mut out); + out + } + + fn lower_functions(&self, funs: &[Function], prefix: &str, out: &mut Vec) { + for fun in funs { + let display = if prefix.is_empty() { + fun.name.clone() + } else { + format!("{prefix}.{}", fun.name) + }; + out.push(self.lower_function(&display, fun)); + self.lower_functions(&fun.children, &display, out); + } + } + + fn lower_function(&self, display: &str, fun: &Function) -> Lowered { + let mut rejected = Vec::new(); + // 对象体(`# 类型`)不是可证单元:P0 只证函数/方法。 + if fun.is_object() { + return Lowered { + display: display.to_string(), + is_object: true, + plan: None, + rejected, + }; + } + // `--allow-opaque `:整体降级为单个不透明操作,优先于子集验收 + // (作者显式声明"行为未知",因此 while/递归也不再是拒绝理由)。 + if self.allow_opaque.contains(display) { + return Lowered { + display: display.to_string(), + is_object: false, + plan: Some(self.opaque_whole(display, fun)), + rejected, + }; + } + // 子集验收先于一切:拒绝的函数不生成 plan。 + self.check_subset(fun, &mut rejected); + if !rejected.is_empty() { + return Lowered { + display: display.to_string(), + is_object: false, + plan: None, + rejected, + }; + } + + let mut body = Body::default(); + for stmt in &fun.body { + self.lower_stmt(fun, stmt, &mut body); + } + if !body.rejected.is_empty() { + return Lowered { + display: display.to_string(), + is_object: false, + plan: None, + rejected: body.rejected, + }; + } + let plan = FnPlan { + name: display.to_string(), + params: fun + .params + .iter() + .map(|p| ParamPlan { + name: p.name.clone(), + ty: self.param_ty(fun, &p.name), + has_default: p.default.is_some(), + }) + .collect(), + result_ty: self.result_ty(fun), + ops: body.ops, + steps: body.steps, + effects: body + .op_effects + .iter() + .filter(|e| e.as_str() != "pure") + .cloned() + .collect(), + claims: fun + .claims + .iter() + .map(|c| ClaimPlan { + id: c.id.clone(), + premise: c.premise.clone(), + conclusion: c.conclusion.clone(), + tactic: c.tactic.clone(), + line: c.line, + }) + .collect(), + assumptions: Vec::new(), + }; + Lowered { + display: display.to_string(), + is_object: false, + plan: Some(plan), + rejected, + } + } + + fn opaque_whole(&self, display: &str, fun: &Function) -> FnPlan { + // 行为完全未知:效应标签一律 `opaque`(§4.5,比猜测诚实)。 + let effect = "opaque".to_string(); + let mut ops = Vec::new(); + let id = format!("调用:{display}"); + ops.push(OpDecl { + id: id.clone(), + effect, + params: Vec::new(), + arity: fun.params.len(), + }); + FnPlan { + name: display.to_string(), + params: fun + .params + .iter() + .map(|p| ParamPlan { + name: p.name.clone(), + ty: PlanTy::Any, + has_default: p.default.is_some(), + }) + .collect(), + result_ty: PlanTy::Any, + ops, + steps: vec![Step::Trace { + op: id, + args: fun + .params + .iter() + .map(|p| PureExpr::Var(p.name.clone())) + .collect(), + line: fun.span.line, + }], + effects: vec!["opaque".into()], + claims: Vec::new(), + assumptions: Vec::new(), + } + } + + // ---------------------------------------------------------------- 子集验收 + + /// 子集验收(§4.3 拒绝侧)。收集全部原因,不止第一条。 + fn check_subset(&self, fun: &Function, rejected: &mut Vec) { + for stmt in &fun.body { + self.check_stmt(stmt, fun, rejected); + } + // 递归:本函数显示名出现在自身可静态解析的调用闭包里。 + let display = self.display_of(fun); + if self.recurses(fun, &display, &mut BTreeSet::new()) { + rejected.push(reject( + self.module, + fun.span, + "proof.recursion", + format!("`{display}` 递归调用不在可证子集(需要归纳证明,超出 P0–P3 范围)"), + )); + } + } + + fn check_stmt(&self, stmt: &Stmt, fun: &Function, rejected: &mut Vec) { + match stmt { + Stmt::While { span, .. } => rejected.push(reject( + self.module, + *span, + "proof.while", + format!( + "`-` 循环不在可证子集:`{}` 被跳过(无循环 ⇒ 返回路径有限)", + fun.name + ), + )), + Stmt::ForEach { span, .. } => rejected.push(reject( + self.module, + *span, + "proof.foreach_pending", + "foreach 在 P3 才进入可证子集(需要列表有限性证据)", + )), + Stmt::Assign { value, span, .. } => self.check_expr(value, fun, *span, rejected), + Stmt::Return { value, span } => self.check_expr(value, fun, *span, rejected), + Stmt::Expr { value, span } => self.check_expr(value, fun, *span, rejected), + Stmt::Call { call, span } => self.check_call(call, fun, *span, rejected), + Stmt::Branch { arms, .. } => { + for arm in arms { + if let Some(cond) = &arm.condition { + // 条件的 span 在解析期未单独记录,用函数级锚点替代。 + self.check_expr(cond, fun, fun.span, rejected); + } + for s in &arm.body { + self.check_stmt(s, fun, rejected); + } + } + } + } + } + + fn check_expr(&self, expr: &Expr, fun: &Function, span: Span, rejected: &mut Vec) { + match expr { + Expr::Call(call) => self.check_call(call, fun, span, rejected), + Expr::Occluded { payload, .. } => { + if let Some(payload) = payload { + self.check_expr(payload, fun, span, rejected); + } + } + Expr::Binary { left, right, .. } => { + self.check_expr(left, fun, span, rejected); + self.check_expr(right, fun, span, rejected); + } + Expr::Unary { expr, .. } => self.check_expr(expr, fun, span, rejected), + Expr::List(items) => { + for item in items { + self.check_expr(item, fun, span, rejected); + } + } + Expr::Map(entries) => { + for (_, value) in entries { + self.check_expr(value, fun, span, rejected); + } + } + Expr::Index { base, .. } => self.check_expr(base, fun, span, rejected), + Expr::Interp(parts) => { + for part in parts { + if let ast::InterpPart::Index { .. } = part { + rejected.push(reject( + self.module, + span, + "proof.unsupported", + "插值中的下标读取不在 P0 纯片段", + )); + } + } + } + Expr::Var(_) | Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {} + } + } + + fn check_call(&self, call: &CallExpr, fun: &Function, span: Span, rejected: &mut Vec) { + for arg in &call.args { + let value = match arg { + Arg::Positional(value) | Arg::Named { value, .. } => value, + }; + self.check_expr(value, fun, span, rejected); + } + match resolve_for_exec(self.module, fun, call) { + Target::Local(target) => { + if target.is_object() { + rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("对象构造 `{}` 不在 P0 纯片段", call_display(call)), + )); + } + } + Target::Import { .. } | Target::Builtin(_) | Target::Host(_) => {} + Target::Dynamic { reason, name } => { + use crate::sema::bind::DynamicReason as R; + match reason { + R::CallFn | R::Plugin => rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("`{name}`:函数值/未知裸名调用不在可证子集"), + )), + // 方法调用(`` `recv`.m ``)与两段静态路径(`工程.成员`)都是 + // 静态可拼写的调用点 → 不透明操作,不拒绝(§4.3)。 + R::MethodReceiver => {} + } + } + Target::Unresolved { message, .. } => { + rejected.push(reject( + self.module, + span, + "proof.dynamic_call", + format!("`{}` 无法静态解析:{message}", call_display(call)), + )); + } + } + } + + fn display_of(&self, fun: &Function) -> String { + fn walk<'a>( + funs: &'a [Function], + prefix: &str, + target: &Function, + out: &mut Option, + ) { + if out.is_some() { + return; + } + for f in funs { + let display = if prefix.is_empty() { + f.name.clone() + } else { + format!("{prefix}.{}", f.name) + }; + if std::ptr::eq(f, target) { + *out = Some(display.clone()); + return; + } + walk(&f.children, &display, target, out); + } + } + let mut found = None; + walk(&self.module.functions, "", fun, &mut found); + found.unwrap_or_else(|| fun.name.clone()) + } + + /// 递归检测:从 `fun` 出发的可静态解析局部调用是否回到 `display`。 + fn recurses(&self, fun: &Function, display: &str, visiting: &mut BTreeSet) -> bool { + if !visiting.insert(display.to_string()) { + return true; + } + let mut found = false; + let calls = self.all_calls(fun); + for (call, callee_fun) in calls { + if let Target::Local(target) = resolve_for_exec(self.module, callee_fun, call) { + let target_display = self.display_of(target); + if target_display == display || self.recurses(target, &target_display, visiting) { + found = true; + break; + } + } + } + visiting.remove(display); + found + } + + /// 函数体里每个调用点及其**所在函数**(解析作用域)。 + fn all_calls<'a>(&'a self, fun: &'a Function) -> Vec<(&'a CallExpr, &'a Function)> { + let mut out = Vec::new(); + for stmt in &fun.body { + self.collect_stmt_calls(stmt, fun, &mut out); + } + out + } + + fn collect_stmt_calls<'a>( + &'a self, + stmt: &'a Stmt, + owner: &'a Function, + out: &mut Vec<(&'a CallExpr, &'a Function)>, + ) { + match stmt { + Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { + for call in collect_calls(value) { + out.push((call, owner)); + } + } + Stmt::Call { call, .. } => out.push((call, owner)), + Stmt::Branch { arms, .. } => { + for arm in arms { + if let Some(cond) = &arm.condition { + for call in collect_calls(cond) { + out.push((call, owner)); + } + } + for s in &arm.body { + self.collect_stmt_calls(s, owner, out); + } + } + } + _ => {} + } + } + + // ---------------------------------------------------------------- 语句降级 + + fn lower_stmt(&self, fun: &Function, stmt: &Stmt, body: &mut Body) { + match stmt { + Stmt::Assign { name, value, span, .. } => { + let expr = self.lower_expr(value, fun, span.line, body); + body.steps.push(Step::Bind { + var: name.clone(), + expr, + line: span.line, + }); + } + Stmt::Return { value, span } => { + let expr = self.lower_expr(value, fun, span.line, body); + body.steps.push(Step::Return { + expr, + line: span.line, + }); + } + Stmt::Call { call, span } => { + // 语句形式调用:值丢弃,但有效应的调用必须留下轨迹。 + if let IrExpr::Op { id, args } = self.lower_call_expr(call, fun, span.line, body) { + body.steps.push(Step::Trace { + op: id, + args, + line: span.line, + }); + } + } + Stmt::Expr { value, span } => { + if let IrExpr::Op { id, args } = self.lower_expr(value, fun, span.line, body) { + body.steps.push(Step::Trace { op: id, args, line: span.line }); + } + } + Stmt::Branch { arms, span } => { + let step = self.lower_branch(arms, span.line, fun, body); + body.steps.extend(step); + } + Stmt::While { span, .. } => body.rejected.push(reject( + self.module, + *span, + "proof.while", + "循环不在可证子集", + )), + Stmt::ForEach { span, .. } => body.rejected.push(reject( + self.module, + *span, + "proof.foreach_pending", + "foreach 在 P3 才进入可证子集", + )), + } + } + + /// 多臂分支 → 嵌套 if/else(保持源顺序;`1. 条件 / 2. *` 是两臂常态)。 + fn lower_branch( + &self, + arms: &[ast::BranchArm], + line: u32, + fun: &Function, + body: &mut Body, + ) -> Vec { + let Some(first) = arms.first() else { + return Vec::new(); + }; + let Some(cond) = &first.condition else { + // 首臂即 else(无条件的 `1. *`):平铺为主体。 + let before = body.steps.len(); + for s in &first.body { + self.lower_stmt(fun, s, body); + } + return body.steps.split_off(before); + }; + let cond_ir = self.lower_pure_required(cond, fun, line, body); + let then = { + let mut sub = Body { + inline_depth: body.inline_depth, + ..Body::default() + }; + for s in &first.body { + self.lower_stmt(fun, s, &mut sub); + } + let steps = std::mem::take(&mut sub.steps); + body.absorb(sub); + steps + }; + let otherwise = if arms.len() > 1 { + self.lower_branch(&arms[1..], line, fun, body) + } else { + Vec::new() + }; + vec![Step::If { + cond: cond_ir, + then, + otherwise, + line, + }] + } + + // ---------------------------------------------------------------- 表达式降级 + + fn lower_expr(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> IrExpr { + match expr { + Expr::Call(call) => self.lower_call_expr(call, fun, line, body), + Expr::Occluded { payload, .. } => match payload { + Some(payload) => self.lower_expr(payload, fun, line, body), + None => IrExpr::Pure(PureExpr::None), + }, + other => match self.lower_pure(other, fun, body) { + Some(pure) => IrExpr::Pure(pure), + None => match other { + // `$$…$$` 公式与 code 围栏:不透明值(设计 §4.3,不翻译)。 + Expr::Formula(_) => IrExpr::Formula, + Expr::Code(_) => IrExpr::Code, + // 动态键读取 `` [`k`](m) ``:不透明读操作。 + Expr::Index { label: ast::IndexKey::Var(name), .. } => { + let id = body.register_op( + &format!("读取:`{name}`"), + "pure".to_string(), + 0, + ); + IrExpr::Op { id, args: Vec::new() } + } + _ => { + // 诚实边界(审查修复):字面量容器(列表/映射/插值)里的调用 + // 不能变成纯片段的一部分,也不许静默丢弃——静默丢弃会让 + // 含副作用调用的函数伪装成"无操作"。拒绝并提示改写。 + if !collect_calls(other).is_empty() { + body.rejected.push(reject( + self.module, + Span::new(line, 1), + "proof.unsupported", + "列表/映射字面量里的调用不在 P0 纯片段:先把调用绑定到变量(`x` = [调用](…)`),再放进字面量", + )); + } + IrExpr::Pure(PureExpr::None) + } + }, + }, + } + } + + /// 调用 → 内联构造器 / 纯内建 / 不透明 Op。 + fn lower_call_expr(&self, call: &CallExpr, fun: &Function, line: u32, body: &mut Body) -> IrExpr { + let mut args: Vec = Vec::with_capacity(call.args.len()); + for arg in call.args.iter() { + let value = match arg { + Arg::Positional(value) | Arg::Named { value, .. } => value, + }; + args.push(self.lower_arg(value, fun, line, body)); + } + match resolve_for_exec(self.module, fun, call) { + Target::Builtin(name) => lower_builtin(name, args, body), + Target::Host(host) => { + if host_is_pure(host) { + // Access 特形(字段读取)或 mq.* 构造器。 + return lower_host_pure(host, args); + } + let id = body.register_op(&call_display(call), effect_label_of_host(host), args.len()); + IrExpr::Op { id, args } + } + Target::Local(target) => { + let display = self.display_of(target); + // 自递归(防御;子集验收已拒绝)或超深内联 → 不透明。 + if std::ptr::eq(target, fun) || body.inline_depth >= 4 { + let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); + return IrExpr::Op { id, args }; + } + if self.is_inline_candidate(target) { + body.inline_depth += 1; + let lowered = self.inline_body(target, &args, body); + body.inline_depth -= 1; + lowered + } else { + let id = body.register_op(&call_display(call), self.effect_of("self", &display), args.len()); + IrExpr::Op { id, args } + } + } + Target::Import { bind, lib, fun: target, .. } => { + // lib/result 的构造器内联为结构(§4.5;真实库名是 ok/error/value_or)。 + if bind == "result" && matches!(target.name.as_str(), "ok" | "error" | "value_or") { + return IrExpr::Pure(PureExpr::Ctor { + name: format!("result.{}", target.name), + args, + }); + } + let display = if call.path.is_some() { + call_display(call) + } else { + format!("{bind}.{}", target.name) + }; + let effect = self.effect_of(&source_file(lib), &display); + let effect = if effect == "unknown" { + imported_effect_label(lib, target) + } else { + effect + }; + let id = body.register_op(&display, effect, args.len()); + IrExpr::Op { id, args } + } + // 方法调用 / 两段静态路径:不透明(§4.3),接收者不展开。 + Target::Dynamic { name, .. } => { + let id = body.register_op(&name, "unknown".to_string(), args.len()); + IrExpr::Op { id, args } + } + Target::Unresolved { message, .. } => { + body.rejected.push(reject( + self.module, + Span::new(0, 0), + "proof.dynamic_call", + format!("`{}` 无法静态解析:{message}", call_display(call)), + )); + IrExpr::Pure(PureExpr::None) + } + } + } + + /// 实参降级:纯表达式直接用;不透明子调用先绑定临时变量再引用。 + /// 临时名全局递增(`实参N`),避免内联展开时遮蔽调用者的同名变量。 + fn lower_arg(&self, value: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { + if let Some(pure) = self.lower_pure(value, fun, body) { + return pure; + } + match self.lower_expr(value, fun, line, body) { + // 嵌套纯调用(lower_pure 因解析上下文失败的回退路径)。 + IrExpr::Pure(pure) => pure, + IrExpr::Op { id, args } => { + body.temps_count += 1; + let temp = format!("实参{}", body.temps_count); + body.steps.push(Step::Bind { + var: temp.clone(), + expr: IrExpr::Op { id, args }, + line: 0, + }); + PureExpr::Var(temp) + } + _ => PureExpr::None, + } + } + + /// §4.5 内联判据(P0 保守版):无分支的直线函数 + sema 效应 pure + 非递归。 + /// 含分支的被调在 P0 一律不透明化(符号执行落地后在 P2 放宽)。 + fn is_inline_candidate(&self, target: &Function) -> bool { + if target.is_object() || has_branching(&target.body) { + return false; + } + let stmt_count = count_stmts(&target.body); + if stmt_count == 0 || stmt_count > 24 { + return false; + } + let display = self.display_of(target); + self.effect_of("self", &display) == "pure" + } + + /// 内联直线函数体:形参 → 实参替换,语句平铺;返回值即调用值。 + /// op 声明按 id 去重共享;步骤先替换形参再并入主体。 + fn inline_body(&self, target: &Function, args: &[PureExpr], body: &mut Body) -> IrExpr { + let mut result = IrExpr::Pure(PureExpr::None); + let mut sub = Body { + inline_depth: body.inline_depth, + temps_count: body.temps_count, + ..Body::default() + }; + for stmt in &target.body { + match stmt { + Stmt::Return { value, .. } => { + result = self.lower_expr(value, target, crate::ast::stmt_line(stmt), &mut sub); + } + _ => self.lower_stmt(target, stmt, &mut sub), + } + } + let params: Vec = target.params.iter().map(|p| p.name.clone()).collect(); + for step in sub.steps { + body.steps.push(substitute_step(&step, ¶ms, args)); + } + for op in sub.ops { + if body.op_ids.insert(op.id.clone()) { + body.op_effects.insert(op.effect.clone()); + body.ops.push(op); + } + } + body.op_effects.extend(sub.op_effects); + body.rejected.extend(sub.rejected); + body.temps_count = body.temps_count.max(sub.temps_count); + substitute_expr(&result, ¶ms, args) + } + + fn effect_of(&self, file: &str, display: &str) -> String { + self.effects + .get(&(file.to_string(), display.to_string())) + .map(effect_label) + .unwrap_or_else(|| "unknown".into()) + } + + fn param_ty(&self, fun: &Function, name: &str) -> PlanTy { + if let Some(contract) = &fun.contract { + if let Some(param) = contract.params.iter().find(|p| p.name == name) { + return PlanTy::from_contract(¶m.ty); + } + } + PlanTy::Any + } + + fn result_ty(&self, fun: &Function) -> PlanTy { + if let Some(contract) = &fun.contract { + if let Some(ret) = &contract.returns { + return PlanTy::from_contract(&ret.ty); + } + } + PlanTy::Any + } + + // ---------------------------------------------------------------- 纯片段 + + /// 纯表达式降级:能翻译返回 Some;不能返回 None(调用方决定不透明化)。 + fn lower_pure(&self, expr: &Expr, fun: &Function, body: &mut Body) -> Option { + match expr { + Expr::Literal(ast::Literal::None) => Some(PureExpr::None), + Expr::Literal(ast::Literal::Bool(b)) => Some(PureExpr::Bool(*b)), + Expr::Literal(ast::Literal::Int(i)) => Some(PureExpr::Int(*i)), + Expr::Literal(ast::Literal::Num(n)) => Some(PureExpr::Num(*n)), + Expr::Literal(ast::Literal::Text(s)) => Some(PureExpr::Text(s.clone())), + Expr::Var(name) => Some(PureExpr::Var(name.clone())), + Expr::Binary { op, left, right } => Some(PureExpr::Bin { + operator: bin_op(*op), + left: Box::new(self.lower_pure(left, fun, body)?), + right: Box::new(self.lower_pure(right, fun, body)?), + }), + Expr::Unary { op, expr } => Some(PureExpr::Un { + operator: match op { + ast::UnaryOp::Not => UnOp::Not, + ast::UnaryOp::Neg => UnOp::Neg, + }, + expr: Box::new(self.lower_pure(expr, fun, body)?), + }), + Expr::List(items) => Some(PureExpr::List( + items + .iter() + .map(|item| self.lower_pure(item, fun, body)) + .collect::>>()?, + )), + Expr::Map(entries) => Some(PureExpr::Map( + entries + .iter() + .map(|(k, v)| Some((k.clone(), self.lower_pure(v, fun, body)?))) + .collect::>>()?, + )), + Expr::Index { base, label } => { + let key = match label { + ast::IndexKey::Lit(key) => key.clone(), + ast::IndexKey::Var(_) => return None, // 动态键 → 不透明读 + }; + Some(PureExpr::Index { + base: Box::new(self.lower_pure(base, fun, body)?), + key, + }) + } + Expr::Interp(parts) => Some(PureExpr::Interp( + parts + .iter() + .map(|part| match part { + ast::InterpPart::Lit(text) => Some(InterpPart::Lit(text.clone())), + ast::InterpPart::Var(name) => Some(InterpPart::Var(name.clone())), + ast::InterpPart::Index { .. } => None, + }) + .collect::>>()?, + )), + Expr::Call(call) => { + let args: Option> = call + .args + .iter() + .map(|arg| match arg { + Arg::Positional(value) | Arg::Named { value, .. } => { + self.lower_pure(value, fun, body) + } + }) + .collect(); + let args = args?; + match resolve_for_exec(self.module, fun, call) { + Target::Builtin(name) if builtin_is_pure(name) => { + Some(match lower_builtin_pure(name, args) { + IrExpr::Pure(pure) => pure, + _ => return None, + }) + } + Target::Host(host) if host_is_pure(host) => { + Some(match lower_host_pure(host, args) { + IrExpr::Pure(pure) => pure, + _ => return None, + }) + } + _ => None, + } + } + _ => None, + } + } + + /// 分支条件必须是纯表达式(§4.3);不是就报 unsupported。 + fn lower_pure_required(&self, expr: &Expr, fun: &Function, line: u32, body: &mut Body) -> PureExpr { + match self.lower_pure(expr, fun, body) { + Some(pure) => pure, + None => { + body.rejected.push(reject( + self.module, + Span::new(line, 1), + "proof.unsupported", + "分支条件不在纯片段(只接受字面量/变量/比较/布尔)", + )); + PureExpr::None + } + } + } +} + +// ---------------------------------------------------------------- 内建与效应 + +/// 纯内建(可进纯片段)。 +fn builtin_is_pure(name: &str) -> bool { + matches!( + name, + "len" | "str" | "int" | "type" | "trim" | "split" | "join" | "at" + ) +} + +/// `print`/`input` 有效应,按不透明操作处理;其余内建进纯片段。 +fn lower_builtin(name: &str, args: Vec, body: &mut Body) -> IrExpr { + match name { + "print" => { + let id = body.register_op("打印", "output.write", 1); + IrExpr::Op { id, args } + } + "input" => { + let id = body.register_op("输入", "user.input", 1); + IrExpr::Op { id, args } + } + _ => lower_builtin_pure(name, args), + } +} + +fn lower_builtin_pure(name: &str, args: Vec) -> IrExpr { + match (name, args.as_slice()) { + ("len", [only]) => IrExpr::Pure(PureExpr::Len(Box::new(only.clone()))), + ("at", [base, key]) => IrExpr::Pure(PureExpr::Ctor { + name: "mq.at".into(), + args: vec![base.clone(), key.clone()], + }), + _ => IrExpr::Pure(PureExpr::Ctor { + name: format!("mq.{name}"), + args, + }), + } +} + +/// 纯 Host 函数进纯片段;`access`/`取`/`取值` 是字段读取的标准形。 +fn lower_host_pure(host: HostFn, args: Vec) -> IrExpr { + if matches!(host, HostFn::Access) { + if let [base, PureExpr::Text(key)] = args.as_slice() { + return IrExpr::Pure(PureExpr::Access { + base: Box::new(base.clone()), + key: key.clone(), + }); + } + } + IrExpr::Pure(PureExpr::Ctor { + name: format!("mq.{}", host.name()), + args, + }) +} + +fn host_is_pure(host: HostFn) -> bool { + host.effects() == ["pure"] +} + +fn effect_label_of_host(host: HostFn) -> String { + let effects = host.effects(); + if effects == ["pure"] { + "pure".into() + } else { + effects + .first() + .map(|s| (*s).to_string()) + .unwrap_or_else(|| "unknown".into()) + } +} + +/// 无 sema 效应表时的库函数效应回退(与 sema 的 imported_effects 同思路的保守版)。 +fn imported_effect_label(lib: &Module, fun: &Function) -> String { + let mut visiting = std::collections::HashSet::new(); + imported_effect_impl(lib, fun, &mut visiting) +} + +fn imported_effect_impl( + module: &Module, + fun: &Function, + visiting: &mut std::collections::HashSet<(Option, u32)>, +) -> String { + let identity = (module.source.path.clone(), fun.span.line); + if !visiting.insert(identity) { + return "pure".into(); + } + let mut effect = "pure".to_string(); + for stmt in &fun.body { + let calls: Vec<&CallExpr> = match stmt { + Stmt::Assign { value, .. } | Stmt::Return { value, .. } | Stmt::Expr { value, .. } => { + collect_calls(value) + } + Stmt::Call { call, .. } => vec![call], + _ => vec![], + }; + for call in calls { + match resolve_for_exec(module, fun, call) { + Target::Builtin(name) => { + if !builtin_is_pure(name) { + effect = if name == "print" { "output.write" } else { "user.input" }.into(); + } + } + Target::Host(host) => { + let label = effect_label_of_host(host); + if label != "pure" { + effect = label; + } + } + Target::Local(target) => { + let label = imported_effect_impl(module, target, visiting); + if label != "pure" { + effect = label; + } + } + Target::Import { lib: inner, fun: target, .. } => { + let label = imported_effect_impl(inner, target, visiting); + if label != "pure" { + effect = label; + } + } + _ => effect = "unknown".into(), + } + } + } + effect +} + +fn effect_label(effects: &EffectSet) -> String { + if effects.is_pure() { + "pure".into() + } else { + effects + .values() + .into_iter() + .find(|e| e.as_str() != "pure" && e.as_str() != "unknown") + .unwrap_or_else(|| { + if effects.contains("unknown") { + "unknown".into() + } else { + "pure".into() + } + }) + } +} + +fn source_file(module: &Module) -> String { + module + .source + .path + .as_ref() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default() +} + +fn bin_op(op: BinaryOp) -> BinOp { + use BinaryOp as A; + match op { + A::Add => BinOp::Add, + A::Sub => BinOp::Sub, + A::Mul => BinOp::Mul, + A::Div => BinOp::Div, + A::Eq => BinOp::Eq, + A::Ne => BinOp::Ne, + A::Lt => BinOp::Lt, + A::Le => BinOp::Le, + A::Gt => BinOp::Gt, + A::Ge => BinOp::Ge, + A::And => BinOp::And, + A::Or => BinOp::Or, + } +} + +fn collect_calls(expr: &Expr) -> Vec<&CallExpr> { + let mut out = Vec::new(); + fn go<'a>(expr: &'a Expr, out: &mut Vec<&'a CallExpr>) { + match expr { + Expr::Call(call) => { + out.push(call); + for arg in &call.args { + match arg { + Arg::Positional(value) | Arg::Named { value, .. } => go(value, out), + } + } + } + Expr::Binary { left, right, .. } => { + go(left, out); + go(right, out); + } + Expr::Unary { expr, .. } => go(expr, out), + Expr::List(items) => items.iter().for_each(|e| go(e, out)), + Expr::Map(entries) => entries.iter().for_each(|(_, v)| go(v, out)), + Expr::Index { base, .. } => go(base, out), + Expr::Occluded { payload, .. } => { + if let Some(p) = payload { + go(p, out) + } + } + _ => {} + } + } + go(expr, &mut out); + out +} + +fn has_branching(stmts: &[Stmt]) -> bool { + fn go(stmt: &Stmt) -> bool { + match stmt { + Stmt::Branch { arms, .. } => { + arms.iter().any(|arm| arm.body.iter().any(go)) + } + Stmt::While { body, .. } | Stmt::ForEach { body, .. } => body.iter().any(go), + _ => false, + } + } + stmts.iter().any(go) +} + +fn count_stmts(stmts: &[Stmt]) -> usize { + fn go(stmt: &Stmt) -> usize { + 1 + match stmt { + Stmt::Branch { arms, .. } => arms + .iter() + .map(|arm| arm.body.iter().map(go).sum::()) + .sum(), + _ => 0, + } + } + stmts.iter().map(go).sum() +} + +fn reject(module: &Module, span: Span, code: &str, message: impl Into) -> Diagnostic { + Diagnostic::new(module.source.path.as_deref(), span, message) + .with_source(&module.source) + .with_code(code) + .with_severity(Severity::Warning) +} + +// ---------------------------------------------------------------- 实参替换 + +fn substitute_step(step: &Step, params: &[String], args: &[PureExpr]) -> Step { + match step { + Step::Bind { var, expr, line } => Step::Bind { + var: var.clone(), + expr: substitute_expr(expr, params, args), + line: *line, + }, + Step::Return { expr, line } => Step::Return { + expr: substitute_expr(expr, params, args), + line: *line, + }, + Step::If { + cond, + then, + otherwise, + line, + } => Step::If { + cond: substitute_pure(cond, params, args), + then: then.iter().map(|s| substitute_step(s, params, args)).collect(), + otherwise: otherwise + .iter() + .map(|s| substitute_step(s, params, args)) + .collect(), + line: *line, + }, + Step::Trace { op, args: op_args, line } => Step::Trace { + op: op.clone(), + args: op_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + line: *line, + }, + } +} + +fn substitute_expr(expr: &IrExpr, params: &[String], args: &[PureExpr]) -> IrExpr { + match expr { + IrExpr::Pure(pure) => IrExpr::Pure(substitute_pure(pure, params, args)), + IrExpr::Op { id, args: op_args } => IrExpr::Op { + id: id.clone(), + args: op_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + }, + other => other.clone(), + } +} + +fn substitute_pure(pure: &PureExpr, params: &[String], args: &[PureExpr]) -> PureExpr { + match pure { + PureExpr::Var(name) => params + .iter() + .position(|p| p == name) + .and_then(|i| args.get(i)) + .cloned() + .unwrap_or_else(|| pure.clone()), + PureExpr::Bin { operator, left, right } => PureExpr::Bin { + operator: *operator, + left: Box::new(substitute_pure(left, params, args)), + right: Box::new(substitute_pure(right, params, args)), + }, + PureExpr::Un { operator, expr } => PureExpr::Un { + operator: *operator, + expr: Box::new(substitute_pure(expr, params, args)), + }, + PureExpr::Index { base, key } => PureExpr::Index { + base: Box::new(substitute_pure(base, params, args)), + key: key.clone(), + }, + PureExpr::Access { base, key } => PureExpr::Access { + base: Box::new(substitute_pure(base, params, args)), + key: key.clone(), + }, + PureExpr::Len(inner) => PureExpr::Len(Box::new(substitute_pure(inner, params, args))), + PureExpr::List(items) => PureExpr::List( + items + .iter() + .map(|i| substitute_pure(i, params, args)) + .collect(), + ), + PureExpr::Map(entries) => PureExpr::Map( + entries + .iter() + .map(|(k, v)| (k.clone(), substitute_pure(v, params, args))) + .collect(), + ), + PureExpr::Ctor { name, args: ctor_args } => PureExpr::Ctor { + name: name.clone(), + args: ctor_args + .iter() + .map(|a| substitute_pure(a, params, args)) + .collect(), + }, + other => other.clone(), + } +} + +// ---------------------------------------------------------------- 降级状态 + +#[derive(Default)] +struct Body { + steps: Vec, + ops: Vec, + op_ids: BTreeSet, + op_effects: BTreeSet, + rejected: Vec, + /// 临时实参变量计数(`实参N`,全局递增防遮蔽)。 + temps_count: usize, + inline_depth: usize, +} + +impl Body { + fn register_op(&mut self, display: &str, effect: impl Into, arity: usize) -> String { + let base = format!("调用:{display}"); + // 同名不同元数的调用点(可选参数等)→ 加 `/元数` 后缀:构造器声明与 + // 每个使用点的实参个数保持一致,否则生成的 Lean 无法编译。 + let id = match self.ops.iter().find(|o| o.id == base) { + Some(o) if o.arity == arity => base, + Some(_) => format!("{base}/{arity}"), + None => base, + }; + if self.op_ids.insert(id.clone()) { + let effect = effect.into(); + self.op_effects.insert(effect.clone()); + self.ops.push(OpDecl { + id: id.clone(), + effect, + params: Vec::new(), + arity, + }); + } + id + } + + /// 子体降级后并回主状态(ops / 效应 / 拒绝 / 临时变量;steps 由调用方取走)。 + fn absorb(&mut self, sub: Body) { + for op in sub.ops { + if self.op_ids.insert(op.id.clone()) { + self.op_effects.insert(op.effect.clone()); + self.ops.push(op); + } + } + self.op_effects.extend(sub.op_effects); + self.rejected.extend(sub.rejected); + self.temps_count = self.temps_count.max(sub.temps_count); + } +} + +// ---------------------------------------------------------------- 入口 + +/// 从模块生成 Plan(确定性输出;`module_display` 为相对路径)。 +pub fn build_plan( + module: &Module, + source_sha256: &str, + module_display: &str, + effects: BTreeMap<(String, String), EffectSet>, + allow_opaque: &[String], +) -> Result<(Plan, Vec)> { + let lowerer = Lowerer::new(module, effects, false, allow_opaque); + let lowered = lowerer.lower_module(); + let plan = Plan { + schema: SCHEMA, + module: module_display.to_string(), + source_sha256: source_sha256.to_string(), + functions: lowered.iter().filter_map(|l| l.plan.clone()).collect(), + }; + Ok((plan, lowered)) +} + +/// 效应表构建:sema 闭包 artifact → `(file, display) → effects`。 +/// sema 编译失败时返回空表(效应保守记 `unknown`,绝不臆造 pure)。 +pub fn effect_map(path: &Path) -> BTreeMap<(String, String), EffectSet> { + let mut map = BTreeMap::new(); + if let Ok(compilation) = crate::sema::ir::compile_file_closure(path) { + for artifact in &compilation.semantics.artifacts { + map.insert( + (artifact.source.file.clone(), artifact.display_name.clone()), + artifact.effects.clone(), + ); + } + } + map +} diff --git a/src/prove/mod.rs b/src/prove/mod.rs new file mode 100755 index 0000000..174010b --- /dev/null +++ b/src/prove/mod.rs @@ -0,0 +1,880 @@ +//! `marqdo prove`:SKILL 控制平面 → Lean 4(`doc/design/prove-cli.md`)。 +//! +//! 三条契约(设计 §1.3): +//! 1. **诚实**——只报实际做过的判定;`checked` 永不冒充 Lean 结论; +//! 2. **单调**——离线判定严格弱于 Lean(P2 落地护栏); +//! 3. **不执行**——本模块只读源码,从不运行目标程序。 +//! +//! P0 范围(roadmap/prove.md §2):装载 → 降级 → 定型 → 确定性生成 + audit。 +//! 判定(离线 ⑤ / Lean ⑥)在 P1/P2 接入;状态只到 `unverified` / `rejected` / +//! `error`。 + +pub mod cache; +pub mod driver; +pub mod emit; +pub mod ir; +pub mod lower; +pub mod offline; +pub mod proof_check; +pub mod types; + +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{Context, Result}; + +use crate::diagnostics::Diagnostic; +use crate::prove::lower::Lowered; + +/// 判定层级(P0 恒 `none`)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tier { + Lean, + Offline, + None, +} + +impl Tier { + pub fn as_str(self) -> &'static str { + match self { + Tier::Lean => "lean", + Tier::Offline => "offline", + Tier::None => "none", + } + } +} + +/// 状态词(§1.2;P0 只会产生 `unverified` / `rejected` / `error`)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Proved, + Checked, + Unverified, + Unproved, + Rejected, + Error, +} + +impl Verdict { + pub fn as_str(self) -> &'static str { + match self { + Verdict::Proved => "proved", + Verdict::Checked => "checked", + Verdict::Unverified => "unverified", + Verdict::Unproved => "unproved", + Verdict::Rejected => "rejected", + Verdict::Error => "error", + } + } + + /// 聚合优先级(差者胜):error > unproved > rejected > unverified > checked > proved。 + pub fn rank(self) -> u8 { + match self { + Verdict::Proved => 0, + Verdict::Checked => 1, + Verdict::Unverified => 2, + Verdict::Rejected => 3, + Verdict::Unproved => 4, + Verdict::Error => 5, + } + } + + pub fn worst(a: Verdict, b: Verdict) -> Verdict { + if a.rank() >= b.rank() { + a + } else { + b + } + } +} + +/// 退出码(§3.3)。 +impl Verdict { + pub fn exit_code(self, require_lean: bool) -> i32 { + match self { + Verdict::Error => 1, + Verdict::Unproved => 1, + Verdict::Rejected | Verdict::Unverified | Verdict::Checked if require_lean => 2, + _ => 0, + } + } +} + +/// 选项(§8.2)。 +#[derive(Debug, Clone)] +pub struct ProveOptions { + pub entry: Option, + pub only: Vec, + pub allow_opaque: Vec, + pub emit_dir: Option, + pub strict_types: bool, + pub require_lean: bool, + pub report_only: bool, + /// 绕过证书缓存(`--no-cache` / `MARQDO_PROOF_NO_CACHE`)。 + pub no_cache: bool, + /// 显式 lean 路径(`--lean` / `MARQDO_PROOF_LEAN`)。 + pub lean: Option, + /// 单次 lean 调用超时(默认 120s)。 + pub timeout: std::time::Duration, + /// 是否执行判定(`prove emit`/`audit` 子命令 = false,只生成不证)。 + pub judge: bool, + /// `maxHeartbeats`(默认随 lean)。 + pub max_heartbeats: Option, +} + +impl Default for ProveOptions { + fn default() -> Self { + Self { + entry: None, + only: Vec::new(), + allow_opaque: Vec::new(), + emit_dir: None, + strict_types: true, + require_lean: false, + report_only: false, + no_cache: false, + lean: None, + timeout: std::time::Duration::from_secs(120), + judge: true, + max_heartbeats: None, + } + } +} + +/// 单条定理的判定面(§3.5 claims)。 +#[derive(Debug, Clone)] +pub struct ClaimReport { + pub id: String, + pub premise: Option, + pub conclusion: String, + pub tactic: Option, + /// `proved` / `unproved` / `unverified`(判定层给出前与函数一致)。 + pub status: Verdict, + /// `trace`(P2 离线)/ `lean` / 空(未判定)。 + pub decided_by: String, + /// 映射回 `.mq.md` 的行号(失败证据)。 + pub source_line: Option, + /// Lean 原始报错片段(unproved 时)。 + pub evidence: Option, +} + +/// 单函数报告。 +#[derive(Debug, Clone)] +pub struct FunctionReport { + pub name: String, + pub verdict: Verdict, + pub tier: Tier, + /// 不透明操作(id, effect)。 + pub ops: Vec<(String, String)>, + /// 拒绝原因(code, message, line)。 + pub rejected: Vec<(String, String, u32)>, + /// 定理声明 + 判定。 + pub claims: Vec, +} + +/// Lean 判定信息(`lean: null` 表示没跑)。 +#[derive(Debug, Clone)] +pub struct LeanInfo { + pub toolchain: String, + pub library_sha256: String, + pub module_sha256: String, + /// `hit` / `miss`。 + pub cache: &'static str, +} + +/// 整体报告。 +#[derive(Debug, Clone)] +pub struct Report { + pub file: String, + pub source_sha256: String, + /// 产物目录 id(`.marqdo/prove/`)。 + pub artifact_id: Option, + pub status: Verdict, + pub functions: Vec, + pub diagnostics: Vec, + pub emitted: Vec, + pub lean: Option, + pub duration_ms: u128, +} + +impl Report { + /// JSON 面(§3.5;`status` 枚举稳定)。 + pub fn to_json(&self) -> serde_json::Value { + use serde_json::json; + json!({ + "schema": 1, + "status": self.status.as_str(), + "file": self.file, + "source_sha256": self.source_sha256, + "artifact_id": match &self.artifact_id { + Some(id) => json!(format!("mq://prove/{id}")), + None => serde_json::Value::Null, + }, + "functions": self.functions.iter().map(|f| json!({ + "name": f.name, + "status": f.verdict.as_str(), + "tier": f.tier.as_str(), + "claims": f.claims.iter().map(|c| { + let mut j = json!({ + "id": c.id, + "premise": c.premise, + "conclusion": c.conclusion, + "tactic": c.tactic, + "status": c.status.as_str(), + }); + if !c.decided_by.is_empty() { + j["decided_by"] = json!(c.decided_by); + } + if let Some(line) = c.source_line { + j["line"] = json!(line); + } + if let Some(ev) = &c.evidence { + j["evidence"] = json!(ev); + } + j + }).collect::>(), + "obligations": [], + "ops": f.ops.iter().map(|(id, effect)| json!({ + "id": id, "effect": effect, + })).collect::>(), + "rejected": f.rejected.iter().map(|(code, message, line)| json!({ + "code": code, "message": message, "line": line, + })).collect::>(), + })).collect::>(), + "lean": match &self.lean { + Some(info) => json!({ + "toolchain": info.toolchain, + "library_sha256": info.library_sha256, + "module_sha256": info.module_sha256, + "cache": info.cache, + }), + None => serde_json::Value::Null, + }, + "assumptions": [], + "diagnostics": self.diagnostics.iter().map(|d| d.to_json()).collect::>(), + "emitted": self.emitted.iter().map(|p| p.display().to_string()).collect::>(), + "duration_ms": self.duration_ms as u64, + }) + } + + /// 文本面(§3.4 风格;诊断走 stderr 由 main 负责)。 + pub fn to_text(&self) -> String { + let mut out = String::new(); + let functions = self.functions.len(); + let rejected = self + .functions + .iter() + .filter(|f| f.verdict == Verdict::Rejected) + .count(); + let ops: usize = self.functions.iter().map(|f| f.ops.len()).sum(); + out.push_str(&format!("prove: {}\n", self.file)); + let cache_note = match &self.lean { + Some(info) => format!("(lean · cache: {})", info.cache), + None => String::new(), + }; + out.push_str(&format!( + " status: {}{}\n", + self.status.as_str(), + cache_note + )); + out.push_str(&format!( + " functions: {functions} · opaque ops: {ops} · rejected: {rejected}\n" + )); + for f in &self.functions { + if f.verdict == Verdict::Rejected { + let codes: Vec<&str> = f.rejected.iter().map(|(c, _, _)| c.as_str()).collect(); + out.push_str(&format!(" rejected: {} ({})\n", f.name, codes.join(", "))); + } + for c in &f.claims { + match (c.status, &c.evidence) { + (Verdict::Proved, _) => { + out.push_str(&format!(" proved: {}.{}\n", f.name, c.id)); + } + (Verdict::Unproved, Some(ev)) => { + let line = c + .source_line + .map(|l| format!(":{l}")) + .unwrap_or_default(); + out.push_str(&format!( + " unproved: {}.{line}{} — {}\n", + f.name, + c.id, + first_line(ev) + )); + } + (Verdict::Unverified, _) => { + out.push_str(&format!(" unverified: {}.{}\n", f.name, c.id)); + } + _ => {} + } + } + } + for p in &self.emitted { + out.push_str(&format!(" emitted: {}\n", p.display())); + } + out + } +} + +fn first_line(s: &str) -> String { + s.lines().next().unwrap_or("").to_string() +} + +/// P0 主入口:装载 → 降级 → 定型 → 生成。 +pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result { + let started = Instant::now(); + let module = crate::load::load_module(path) + .with_context(|| format!("装载 {}", path.display()))?; + let source_sha256 = module + .source + .sha256 + .clone() + .unwrap_or_default(); + let file_display = display_path(path); + + // ① 装载完成;② 降级(效应表来自 sema;失败时保守 unknown)。 + let effects = lower::effect_map(path); + let (plan, lowered) = lower::build_plan( + &module, + &source_sha256, + &file_display, + effects, + &opts.allow_opaque, + )?; + + // ③ 定型(分支合流等;错误码 proof.type_mismatch)。 + let mut diagnostics: Vec = Vec::new(); + diagnostics.extend(types::typecheck_plan(&module, &lowered, opts.strict_types)); + + // ④ 生成(--report-only 时跳过写盘)。 + let mut emitted: Vec = Vec::new(); + let mut artifact_dir: Option = None; + let mut generated_lean: Option<(PathBuf, String)> = None; + if !opts.report_only { + let dir = match &opts.emit_dir { + Some(dir) => dir.clone(), + None => default_emit_dir(&source_sha256), + }; + let generated = dir.join("Generated"); + std::fs::create_dir_all(&generated) + .with_context(|| format!("创建 {}", generated.display()))?; + let (file_name, lean) = emit::emit_module(&plan, &emit::stem_of(&file_display)); + let lean_path = generated.join(&file_name); + std::fs::write(&lean_path, &lean) + .with_context(|| format!("写入 {}", lean_path.display()))?; + let plan_path = dir.join("plan.json"); + std::fs::write(&plan_path, plan.to_stable_json()) + .with_context(|| format!("写入 {}", plan_path.display()))?; + emitted.push(relative_cwd(&lean_path)); + emitted.push(relative_cwd(&plan_path)); + artifact_dir = Some(dir.clone()); + generated_lean = Some((lean_path, lean)); + } + + // 汇总:错误诊断 → error;有拒绝函数 → rejected;否则 unverified。 + let has_type_errors = diagnostics + .iter() + .any(|d| matches!(d.severity, crate::diagnostics::Severity::Error)); + let mut functions = summarize(&lowered, &opts.only); + let mut status = Verdict::Unverified; + if !functions.is_empty() { + status = functions + .iter() + .map(|f| f.verdict) + .fold(Verdict::Proved, Verdict::worst); + } + if has_type_errors { + status = Verdict::Error; + } + + // ⑤ 判定(P2):离线符号执行先行(毫秒级,checked ≠ proved), + // 有 Lean 工具链时随即复核(checked 升 proved;分歧 → error,永不落绿)。 + let mut lean_info: Option = None; + let claims_present = plan.functions.iter().any(|f| !f.claims.is_empty()); + if claims_present && opts.judge && !opts.report_only { + // ⑤a 离线(§5):F1–F5 片段内给 checked/反例,超出片段不猜。 + judge_offline(&plan, &mut functions, &mut diagnostics); + // ⑤b Lean 复核(§8):证书缓存 → 现算。 + match judge_with_lean( + &plan, + &source_sha256, + artifact_dir.as_deref(), + &generated_lean, + opts, + &mut functions, + &mut diagnostics, + ) { + Ok((verdict, info)) => { + lean_info = info; + if let Some(v) = verdict { + status = v; + } + } + Err(err) => { + diagnostics.push( + Diagnostic::new(None, crate::diagnostics::Span::new(0, 0), format!("{err:#}")) + .with_code("proof.lean_error"), + ); + status = Verdict::Error; + } + } + } else if claims_present && opts.report_only { + // report-only:不判定、不写盘;未证状态如实保留(恒返回 0 由 exit_code 处理)。 + } + + // 函数级状态聚合(判定后重算):文件状态只看**有定理**的函数 + // 与被拒绝的函数——无定理函数没有义务,不该拖低整体(但它们 + // 自己的行如实保留 unverified / tier none)。 + { + let relevant = functions.iter().filter(|f| { + !f.claims.is_empty() || f.verdict == Verdict::Rejected + }); + for f in relevant { + status = Verdict::worst(status, f.verdict); + } + } + + Ok(Report { + file: file_display, + source_sha256, + artifact_id: artifact_dir + .as_ref() + .map(|d| d.file_name().map(|n| n.to_string_lossy().to_string())) + .unwrap_or(None), + status, + functions, + diagnostics, + emitted, + lean: lean_info, + duration_ms: started.elapsed().as_millis(), + }) +} + +/// 离线判定(§5):checked/反例贴回定理,绝不冒充 proved。 +/// 单调性护栏在此埋点:离线结论会在 judge_with_lean 里被 Lean 复核。 +fn judge_offline( + plan: &crate::prove::ir::Plan, + functions: &mut [FunctionReport], + diagnostics: &mut Vec, +) { + use crate::diagnostics::Span; + let debug = std::env::var("MARQDO_PROOF_DEBUG").is_ok_and(|v| v == "1"); + for f in plan.functions.iter() { + for claim in &f.claims { + let verdict = offline::check_claim(f, claim); + if debug { + eprintln!( + "[offline] {}.{} → {:?}", + f.name, claim.id, verdict + ); + } + let Some(fr) = functions.iter_mut().find(|x| x.name == f.name) else { + continue; + }; + let Some(cr) = fr.claims.iter_mut().find(|c| c.id == claim.id) else { + continue; + }; + match verdict { + offline::OfflineVerdict::Checked { cases } => { + cr.status = Verdict::Checked; + cr.decided_by = "trace".into(); + cr.evidence = Some(format!("离线符号执行:{cases} 条路径全部关闭(F1–F5)")); + cr.source_line = Some(claim.line); + fr.tier = Tier::Offline; + } + offline::OfflineVerdict::Unproved { counterexample } => { + cr.status = Verdict::Unproved; + cr.decided_by = "trace".into(); + cr.source_line = Some(claim.line); + cr.evidence = counterexample.as_ref().map(|c| { + format!( + "反例(离线符号执行):{} — 路径 #{}", + c.detail, c.path_id + ) + }); + if let Some(c) = &counterexample { + diagnostics.push( + Diagnostic::new( + None, + Span::new(claim.line, 0), + format!( + "定理 {}.{} 反例:{}", + f.name, claim.id, c.detail + ), + ) + .with_code("proof.claim_failed"), + ); + } + fr.tier = Tier::Offline; + } + offline::OfflineVerdict::Unverified { reason } => { + // 不猜:保留 unverified(不写 evidence,让位给 Lean 结果)。 + let _ = reason; + } + } + fr.verdict = fr + .claims + .iter() + .map(|x| x.status) + .fold(Verdict::Proved, Verdict::worst); + } + } +} + +/// 单一判定来源:缓存证书 → Lean 现算。返回(整体判定,lean 信息)。 +#[allow(clippy::too_many_arguments)] +fn judge_with_lean( + plan: &crate::prove::ir::Plan, + source_sha256: &str, + artifact_dir: Option<&Path>, + generated_lean: &Option<(PathBuf, String)>, + opts: &ProveOptions, + functions: &mut [FunctionReport], + diagnostics: &mut Vec, +) -> Result<(Option, Option)> { + use crate::diagnostics::Span; + let Some((lean_path, lean_src)) = generated_lean else { + return Ok((None, None)); + }; + + // 缓存键素材:工具链版本先探测(没有工具链就谈不上判定)。 + let toolchain = match driver::Toolchain::discover(opts.lean.as_deref()) { + Ok(t) => t, + Err(err) => { + if opts.require_lean { + return Err(err); + } + diagnostics.push( + Diagnostic::new(None, Span::new(0, 0), format!("{err:#}")) + .with_code("proof.lean_missing"), + ); + return Ok((None, None)); + } + }; + let Some(toolchain) = toolchain else { + // 没找到工具链:保持 unverified(诚实:没跑就是没跑)。 + // --require-lean 时退出码由 Verdict::exit_code 升到 2(§3.3 F3)。 + if opts.require_lean { + diagnostics.push( + Diagnostic::new( + None, + Span::new(0, 0), + "--require-lean:未找到 Lean 工具链(PATH/MARQDO_PROOF_LEAN/--lean)", + ) + .with_code("proof.lean_missing"), + ); + } + return Ok((None, None)); + }; + + // 库(内嵌源 → olean,按内容哈希缓存)。 + let cache_root = Path::new(".marqdo/prove"); + let (lib_dir, library_sha256) = driver::ensure_library(cache_root, &toolchain)?; + let module_sha256 = cache::sha256_hex(lean_src.as_bytes()); + let plan_sha = cache::sha256_hex(plan.to_stable_json().as_bytes()); + let key = cache::cache_key( + source_sha256, + &plan_sha, + &library_sha256, + &toolchain.version, + env!("CARGO_PKG_VERSION"), + ); + + let mut artifact_fallback: Option = None; + let artifact: &Path = match artifact_dir { + Some(d) => d, + None => { + let d = default_emit_dir(source_sha256); + // 极少见:report-only 之外无产物目录(理论上不可达)——现建。 + let _ = std::fs::create_dir_all(&d); + // 借用问题:把目录放成一个本地 owned 值,再取引用。 + artifact_fallback.get_or_insert(d).as_path() + } + }; + + // ① 证书命中 → 跳过判定。 + if !opts.no_cache { + if let Some(cert) = cache::load(artifact, &key) { + apply_claims(functions, &cert.claims, &cert.span_map, diagnostics); + let status = cert.status; + return Ok(( + Some(status), + Some(LeanInfo { + toolchain: toolchain.version, + library_sha256, + module_sha256, + cache: "hit", + }), + )); + } + } + + // ② 现算:lean 直接调用(LEAN_PATH 指向底座 olean)。 + let mut outcome = driver::check_module( + &toolchain, + &lib_dir, + lean_path, + lean_src, + opts.timeout, + opts.max_heartbeats, + )?; + // 测试注入(roadmap P2 单调性护栏):让首条定理在 Lean 侧"关不掉", + // 验证离线 checked + Lean unproved ⇒ error[proof.divergence] 的护栏真的咬人。 + if std::env::var("MARQDO_PROOF_INJECT_DIVERGENCE").is_ok_and(|v| v == "1") { + if let Some(first) = outcome.claims.iter_mut().find(|c| c.status == Verdict::Proved) { + first.status = Verdict::Unproved; + first.detail = "injected divergence (MARQDO_PROOF_INJECT_DIVERGENCE)".into(); + } + } + + // ③ 证据 → 诊断(proof.claim_failed,指回源码行)。 + let claim_records: Vec = outcome + .claims + .iter() + .map(|c| cache::ClaimRecord { + id: c.claim.clone(), + function: c.function.clone(), + status: c.status, + source_line: c.source_line, + }) + .collect(); + apply_outcome(functions, &outcome.claims, diagnostics); + + let cert = cache::Certificate { + key: key.clone(), + status: outcome.status, + tier: "lean", + source_sha256: source_sha256.to_string(), + library_sha256: library_sha256.clone(), + toolchain: toolchain.version.clone(), + module_sha256: module_sha256.clone(), + claims: claim_records, + span_map: outcome.span_map.clone(), + marqdo: env!("CARGO_PKG_VERSION").to_string(), + }; + if let Err(err) = cache::store(artifact, &cert) { + diagnostics.push( + Diagnostic::new( + None, + Span::new(0, 0), + format!("证书写入失败(不阻塞判定):{err:#}"), + ) + .with_code("proof.cache_write"), + ); + } + + Ok(( + Some(outcome.status), + Some(LeanInfo { + toolchain: toolchain.version, + library_sha256, + module_sha256, + cache: "miss", + }), + )) +} + +/// 把判定结果按 (函数, 定理 id) 贴回函数报告。 +fn apply_outcome( + functions: &mut [FunctionReport], + claims: &[driver::ClaimOutcome], + diagnostics: &mut Vec, +) { + use crate::diagnostics::Span; + for c in claims { + let matches_fn = |f: &FunctionReport| { + f.name == c.function + || emit::lean_ident(&f.name) + .trim_matches('«') + .trim_matches('»') + == c.function + }; + let Some(pos) = functions.iter().position(matches_fn) else { + continue; + }; + let f = &mut functions[pos]; + if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.claim) { + // 单调性护栏(§5.4):离线结论必须被 Lean 复核印证。 + // checked 但 Lean 关不掉,或离线反例被 Lean 证出来 ⇒ 判定器有 bug。 + let divergence = match (claim.status, c.status) { + (Verdict::Checked, Verdict::Unproved) + | (Verdict::Unproved, Verdict::Proved) => true, + _ => false, + }; + if divergence { + diagnostics.push( + Diagnostic::new( + None, + Span::new(claim.source_line.unwrap_or(0), 0), + format!( + "离线与 Lean 判定分歧:定理 {}.{} 离线 {:?},Lean {}——判定器缺陷,拒绝落绿", + f.name, c.claim, claim.status, c.status.as_str() + ), + ) + .with_code("proof.divergence"), + ); + claim.status = Verdict::Error; + claim.decided_by = "lean".into(); + f.verdict = Verdict::Error; + f.tier = Tier::Lean; + continue; + } + claim.status = c.status; + claim.decided_by = "lean".into(); + claim.source_line = c.source_line; + claim.evidence = (!c.detail.is_empty()).then(|| c.detail.clone()); + if c.status == Verdict::Unproved { + diagnostics.push( + Diagnostic::new( + None, + Span::new(c.source_line.unwrap_or(0), 0), + format!( + "定理 {}.{} 未证:{}", + c.function, + c.claim, + first_line(&c.detail) + ), + ) + .with_code("proof.claim_failed"), + ); + } + f.verdict = f + .claims + .iter() + .map(|x| x.status) + .fold(Verdict::Proved, Verdict::worst); + f.tier = Tier::Lean; + } + } +} + +/// 证书命中的同款贴回。 +fn apply_claims( + functions: &mut [FunctionReport], + claims: &[cache::ClaimRecord], + span_map: &[(u32, u32)], + diagnostics: &mut Vec, +) { + use crate::diagnostics::Span; + for c in claims { + let source_line = c.source_line.or_else(|| { + span_map + .first() + .map(|(_, m)| *m) + }); + if let Some(f) = functions + .iter_mut() + .find(|f| f.name == c.function) + { + if let Some(claim) = f.claims.iter_mut().find(|x| x.id == c.id) { + claim.status = c.status; + claim.decided_by = "lean".into(); + claim.source_line = source_line; + if c.status == Verdict::Unproved { + diagnostics.push( + Diagnostic::new( + None, + Span::new(source_line.unwrap_or(0), 0), + format!("定理 {}.{} 未证(缓存)", f.name, c.id), + ) + .with_code("proof.claim_failed"), + ); + } + f.verdict = f + .claims + .iter() + .map(|x| x.status) + .fold(Verdict::Proved, Verdict::worst); + f.tier = Tier::Lean; + } + } + } +} + +fn summarize(lowered: &[Lowered], only: &[String]) -> Vec { + lowered + .iter() + .filter(|l| !l.is_object) + .filter(|l| only.is_empty() || only.iter().any(|name| name == &l.display)) + .map(|l| { + let (verdict, tier, ops, rejected, claims) = match &l.plan { + Some(plan) => ( + Verdict::Unverified, + Tier::None, + plan.ops + .iter() + .map(|op| (op.id.clone(), op.effect.clone())) + .collect(), + Vec::new(), + plan.claims + .iter() + .map(|c| ClaimReport { + id: c.id.clone(), + premise: c.premise.clone(), + conclusion: c.conclusion.clone(), + tactic: c.tactic.clone(), + status: Verdict::Unverified, + decided_by: String::new(), + source_line: None, + evidence: None, + }) + .collect(), + ), + None => ( + Verdict::Rejected, + Tier::None, + Vec::new(), + l.rejected + .iter() + .map(|d| { + ( + d.code.clone(), + d.message.clone(), + d.span.line, + ) + }) + .collect(), + Vec::new(), + ), + }; + FunctionReport { + name: l.display.clone(), + verdict, + tier, + ops, + rejected, + claims, + } + }) + .collect() +} + +/// 默认产物目录:`.marqdo/prove//`(key = 源 sha256 前 8 位)。 +pub fn default_emit_dir(source_sha256: &str) -> PathBuf { + PathBuf::from(".marqdo/prove").join(&source_sha256[..source_sha256.len().min(8)]) +} + +/// `prove clean`:删除 `.marqdo/prove`(--emit 指定目录不动)。 +pub fn clean() -> Result { + let root = Path::new(".marqdo/prove"); + if !root.exists() { + return Ok(0); + } + let count = std::fs::read_dir(root)?.count(); + std::fs::remove_dir_all(root) + .with_context(|| format!("删除 {}", root.display()))?; + Ok(count) +} + +fn display_path(path: &Path) -> String { + let cwd = std::env::current_dir().unwrap_or_default(); + path.strip_prefix(&cwd) + .unwrap_or(path) + .to_string_lossy() + .to_string() +} + +fn relative_cwd(path: &Path) -> PathBuf { + let cwd = std::env::current_dir().unwrap_or_default(); + path.strip_prefix(&cwd).unwrap_or(path).to_path_buf() +} diff --git a/src/prove/offline.rs b/src/prove/offline.rs new file mode 100755 index 0000000..3abba86 --- /dev/null +++ b/src/prove/offline.rs @@ -0,0 +1,1581 @@ +//! 离线符号执行(设计 §5):没有 Lean 也能给**部分**结论,但绝不比 Lean 强。 +//! +//! 片段 F1–F5,超出即 `unverified`(不猜): +//! - F1 路径枚举:控制流是有限树(lower 已拒绝循环/递归)。 +//! - F2 轨迹:每条路径的 Op 序列由分支决定;包含/长度逐路径求值。 +//! - F3 字面结果:返回值由字面量/参数/内联构造器组成时按结构求值。 +//! - F4 命题:and/or/not、=/≠ 作用于布尔结果;外部返回值上的布尔判定 +//! 视为自由原子(只二分、不假设原子间关系)。 +//! - F5 单变量区间:`x ⋈ c` 原子;路径条件 + 前提的上下界判定蕴含。 +//! +//! 单调性(§5.4):离线 `checked` ⊆ Lean `proved`——构造上 F5 ⊂ omega、 +//! F1–F4 ⊂ simp/decide;运行期只要有 Lean 就复核,分歧即 +//! `error[proof.divergence]`,永不落绿。 + +use std::collections::HashMap; + +use crate::prove::ir::{Expr, FnPlan, Plan, PureExpr, Step}; +use crate::prove::proof_check::{parse_claim_expr, tokenize_claim, ClaimAst, CTok}; + +/// 符号值(§5.3 状态)。 +#[derive(Debug, Clone, PartialEq)] +pub enum SymVal { + Int(i64), + Num(f64), + Bool(bool), + Text(String), + None, + /// 内联构造器结构(`result.ok(v)` → ok=true/value=v/error=none 等)。 + Struct { ctor: String, fields: Vec<(String, SymVal)> }, + /// 不透明操作返回值:值未知,出现已知(F2/F4)。 + OpResult(String), + /// 形参:值未知(F5 走区间)。 + Param(String), + /// 超出片段。 + Unknown, +} + +impl SymVal { + fn is_known(&self) -> bool { + !matches!(self, SymVal::Unknown) + } +} + +/// 比较算子(F5 区间原子)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cmp { + Lt, + Le, + Gt, + Ge, + Eq, + Ne, +} + +impl Cmp { + fn negate(self) -> Cmp { + match self { + Cmp::Lt => Cmp::Ge, + Cmp::Le => Cmp::Gt, + Cmp::Gt => Cmp::Le, + Cmp::Ge => Cmp::Lt, + Cmp::Eq => Cmp::Ne, + Cmp::Ne => Cmp::Eq, + } + } + + fn holds(self, lhs: i64, rhs: i64) -> bool { + match self { + Cmp::Lt => lhs < rhs, + Cmp::Le => lhs <= rhs, + Cmp::Gt => lhs > rhs, + Cmp::Ge => lhs >= rhs, + Cmp::Eq => lhs == rhs, + Cmp::Ne => lhs != rhs, + } + } + + fn as_str(self) -> &'static str { + match self { + Cmp::Lt => "<", + Cmp::Le => "≤", + Cmp::Gt => ">", + Cmp::Ge => "≥", + Cmp::Eq => "=", + Cmp::Ne => "≠", + } + } +} + +/// 路径条件原子。否定一律折进 op/expected(原子总是"正"形态)。 +#[derive(Debug, Clone, PartialEq)] +pub enum PathAtom { + /// `x ⋈ c`(F5)。 + Interval { var: String, op: Cmp, val: i64 }, + /// 自由布尔原子:`env(op).` 判定为 `expected`(F4;值未知只二分)。 + FreeBool { op: String, key: String, expected: bool }, + Literal(bool), + /// 无法归入片段的条件 → 该路径不可判定。 + Opaque, +} + +impl PathAtom { + fn negated(&self) -> PathAtom { + match self { + PathAtom::Interval { var, op, val } => PathAtom::Interval { + var: var.clone(), + op: op.negate(), + val: *val, + }, + PathAtom::FreeBool { op, key, expected } => PathAtom::FreeBool { + op: op.clone(), + key: key.clone(), + expected: !expected, + }, + PathAtom::Literal(b) => PathAtom::Literal(!b), + PathAtom::Opaque => PathAtom::Opaque, + } + } +} + +/// 一条执行路径(§5.3 第 3 步的收集物)。 +#[derive(Debug, Clone)] +pub struct PathRecord { + pub id: usize, + pub atoms: Vec, + pub result: SymVal, + pub trace: Vec, + /// Return 时的变量快照(定理可引用中间变量,如 `审核.ok`)。 + pub vars: Vec<(String, SymVal)>, + /// 踩到片段之外 → 相关定理 unverified。 + pub opaque: bool, + pub line: u32, +} + +/// 反例见证(§5.5:只承认确定性否定)。 +#[derive(Debug, Clone)] +pub struct Counterexample { + pub assignments: Vec<(String, i64)>, + pub path_id: usize, + pub detail: String, +} + +/// 单条定理的离线判定。 +#[derive(Debug, Clone)] +pub enum OfflineVerdict { + /// 每条路径都关闭(checked ≠ proved:没跑 Lean)。 + Checked { cases: usize }, + /// 存在可满足路径、结论确定性为假 → 反例。 + Unproved { counterexample: Option }, + /// 有路径/前提/结论超出片段 → 不猜(诚实)。 + Unverified { reason: String }, +} + +/// 离线执行一个函数,收集全部路径。 +pub fn execute(fn_plan: &FnPlan) -> Vec { + let mut paths = Vec::new(); + let mut state: HashMap = fn_plan + .params + .iter() + .map(|p| (p.name.clone(), SymVal::Param(p.name.clone()))) + .collect(); + exec_steps( + &fn_plan.steps, + &mut state, + Vec::new(), + Vec::new(), + false, + 0, + &mut paths, + ); + for (i, p) in paths.iter_mut().enumerate() { + p.id = i; + } + paths +} + +/// 符号执行语句序列;`atoms`/`trace` 沿路径累积,每个 Return 产生一条记录。 +fn exec_steps( + steps: &[Step], + state: &mut HashMap, + atoms: Vec, + trace: Vec, + opaque: bool, + line: u32, + out: &mut Vec, +) { + let Some((step, rest)) = steps.split_first() else { + // 函数体走完但无 Return:结果未知,但**轨迹与路径条件已知** + // ——F2 结论(包含/长度)仍可判,Result 类结论自然关不了。 + out.push(PathRecord { + id: usize::MAX, + atoms, + result: SymVal::Unknown, + trace, + vars: state.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), + opaque, + line, + }); + return; + }; + match step { + Step::Bind { var, expr, line: l } => { + let (val, trace2, opq) = eval_expr(expr, state, trace, opaque); + let saved = state.insert(var.clone(), val); + exec_steps(rest, state, atoms, trace2, opq, *l, out); + // 回溯:Bind 只在本分支有效。 + match saved { + Some(v) => { + state.insert(var.clone(), v); + } + None => { + state.remove(var); + } + } + } + Step::Return { expr, line: l } => { + let (val, trace2, opq) = eval_expr(expr, state, trace, opaque); + out.push(PathRecord { + id: usize::MAX, + atoms, + result: val, + trace: trace2, + vars: state.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), + opaque: opq, + line: *l, + }); + } + Step::If { cond, then, otherwise, line: l } => { + let (atom, cond_opaque) = cond_atom(cond, state); + // then:条件成立;else:条件取反;两支都要**接续 If 之后的语句** + // (Return 常在 If 外层)。分支在状态克隆上跑,互不污染。 + let mut atoms_then = atoms.clone(); + atoms_then.push(atom.clone()); + let mut then_full: Vec = then.clone(); + then_full.extend(rest.iter().cloned()); + let mut then_state = state.clone(); + exec_steps( + &then_full, + &mut then_state, + atoms_then, + trace.clone(), + opaque || cond_opaque, + *l, + out, + ); + let mut atoms_else = atoms; + atoms_else.push(atom.negated()); + let mut else_full: Vec = otherwise.clone(); + else_full.extend(rest.iter().cloned()); + let mut else_state = state.clone(); + exec_steps( + &else_full, + &mut else_state, + atoms_else, + trace, + opaque || cond_opaque, + *l, + out, + ); + // If 之后没有"公共继续"(已并入两支);state 保持进入前原样。 + } + Step::Trace { op, .. } => { + let mut trace2 = trace; + trace2.push(op_display(op)); + exec_steps(rest, state, atoms, trace2, opaque, line, out); + } + } +} + +/// `调用:人工审核` → `人工审核`(与 Lean `Op.name` 显示一致,轨迹名不变)。 +fn op_display(id: &str) -> String { + id.strip_prefix("调用:").unwrap_or(id).to_string() +} + +/// 条件 → 路径原子(F4/F5)。返回 (原子, 是否超出片段)。 +fn cond_atom(cond: &PureExpr, state: &HashMap) -> (PathAtom, bool) { + match cond { + PureExpr::Bool(b) => (PathAtom::Literal(*b), false), + PureExpr::Bin { operator, left, right } => { + // 单变量区间:`参数 ⋈ 整数字面量`(或反向)。 + if let Some(atom) = interval_atom(operator, left, right, state) { + return (atom, false); + } + // 自由布尔原子:`access(op结果, "ok")` 与字面量比较。 + if let Some(atom) = free_bool_atom(operator, left, right, state) { + return (atom, false); + } + (PathAtom::Opaque, true) + } + PureExpr::Un { operator, expr } => { + if matches!(operator, crate::prove::ir::UnOp::Not) { + let (atom, opq) = cond_atom(expr, state); + return (atom.negated(), opq); + } + (PathAtom::Opaque, true) + } + // 裸布尔条件:`1. 审核.ok`(真值即条件)。 + PureExpr::Access { base, key } => { + if let PureExpr::Var(v) = base.as_ref() { + if let Some(SymVal::OpResult(op)) = state.get(v) { + return ( + PathAtom::FreeBool { + op: op.clone(), + key: key.clone(), + expected: true, + }, + false, + ); + } + if let Some(SymVal::Struct { fields, .. }) = state.get(v) { + if let Some((_, SymVal::Bool(b))) = + fields.iter().find(|(k, _)| k == key) + { + return (PathAtom::Literal(*b), false); + } + } + } + (PathAtom::Opaque, true) + } + PureExpr::Var(v) => match state.get(v) { + Some(SymVal::Bool(b)) => (PathAtom::Literal(*b), false), + _ => (PathAtom::Opaque, true), + }, + _ => (PathAtom::Opaque, true), + } +} + +/// F5 原子:`x ⋈ c`,x 是形参(或绑定了形参的变量),c 是整数字面量。 +fn interval_atom( + operator: &crate::prove::ir::BinOp, + left: &PureExpr, + right: &PureExpr, + state: &HashMap, +) -> Option { + use crate::prove::ir::BinOp as B; + let op = match operator { + B::Lt => Cmp::Lt, + B::Le => Cmp::Le, + B::Gt => Cmp::Gt, + B::Ge => Cmp::Ge, + B::Eq => Cmp::Eq, + B::Ne => Cmp::Ne, + _ => return None, + }; + match (left, right) { + (PureExpr::Var(v), PureExpr::Int(c)) => { + // 只有仍指向形参的变量才可做区间(绑定值另论)。 + match state.get(v) { + Some(SymVal::Param(_)) | None => { + Some(PathAtom::Interval { var: v.clone(), op, val: *c }) + } + _ => None, + } + } + (PureExpr::Int(c), PureExpr::Var(v)) => { + match state.get(v) { + Some(SymVal::Param(_)) | None => { + // c ⋈ x ≡ x (flip ⋈) c + Some(PathAtom::Interval { + var: v.clone(), + op: op.flip(), + val: *c, + }) + } + _ => None, + } + } + _ => None, + } +} + +/// F4 自由原子:`<变量 = OpResult> 的布尔字段 == 布尔字面量`。 +/// 如 `1. 审核.ok`,其中 `审核 = 人工审核(…)`(值未知 → 只二分)。 +fn free_bool_atom( + operator: &crate::prove::ir::BinOp, + left: &PureExpr, + right: &PureExpr, + state: &HashMap, +) -> Option { + use crate::prove::ir::BinOp as B; + let (expected, a, b) = match operator { + B::Eq => (true, left, right), + B::Ne => (false, left, right), + _ => return None, + }; + let (access, field_key, lit) = match (a, b) { + (PureExpr::Access { base, key }, PureExpr::Bool(v)) => { + (base.as_ref(), key.clone(), *v == expected) + } + (PureExpr::Bool(v), PureExpr::Access { base, key }) => { + (base.as_ref(), key.clone(), *v == expected) + } + _ => return None, + }; + let PureExpr::Var(var) = access else { + return None; + }; + let SymVal::OpResult(op) = state.get(var)? else { + return None; + }; + Some(PathAtom::FreeBool { + op: op.clone(), + key: field_key, + expected: lit, + }) +} + +/// 表达式求值 → (符号值, 新轨迹, 是否超出片段)。 +fn eval_expr( + expr: &Expr, + state: &HashMap, + trace: Vec, + opaque: bool, +) -> (SymVal, Vec, bool) { + match expr { + Expr::Pure(p) => (eval_pure(p, state), trace, opaque), + Expr::Op { id, .. } => { + let mut trace2 = trace; + trace2.push(op_display(id)); + (SymVal::OpResult(op_display(id)), trace2, opaque) + } + // 公式/围栏代码:不透明值,超出片段。 + Expr::Formula | Expr::Code => (SymVal::Unknown, trace, true), + } +} + +/// 纯表达式结构求值(F3):字面量与内联构造器按结构化简,其余保守 Unknown。 +pub fn eval_pure(p: &PureExpr, state: &HashMap) -> SymVal { + match p { + PureExpr::Int(i) => SymVal::Int(*i), + PureExpr::Num(n) => SymVal::Num(*n), + PureExpr::Bool(b) => SymVal::Bool(*b), + PureExpr::Text(s) => SymVal::Text(s.clone()), + PureExpr::None => SymVal::None, + PureExpr::Var(v) => state.get(v).cloned().unwrap_or(SymVal::Unknown), + PureExpr::Bin { operator, left, right } => eval_bin(*operator, left, right, state), + PureExpr::Un { operator, expr } => { + let v = eval_pure(expr, state); + match (operator, v) { + (crate::prove::ir::UnOp::Not, SymVal::Bool(b)) => SymVal::Bool(!b), + (crate::prove::ir::UnOp::Neg, SymVal::Int(i)) => SymVal::Int(-i), + _ => SymVal::Unknown, + } + } + PureExpr::Access { base, key } => match eval_pure(base, state) { + SymVal::Struct { fields, .. } => fields + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.clone()) + .unwrap_or(SymVal::None), + _ => SymVal::Unknown, + }, + PureExpr::Index { base, key } => match eval_pure(base, state) { + SymVal::Struct { fields, .. } => fields + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.clone()) + .unwrap_or(SymVal::None), + _ => SymVal::Unknown, + }, + PureExpr::Len(inner) => match eval_pure(inner, state) { + SymVal::Struct { ctor, .. } if ctor == "list" => SymVal::Unknown, + SymVal::Text(s) => SymVal::Int(s.chars().count() as i64), + _ => SymVal::Unknown, + }, + PureExpr::List(items) => { + // 列表字面量:全部已知才结构化(保留为 list 构造)。 + let vals: Vec = items.iter().map(|i| eval_pure(i, state)).collect(); + if vals.iter().all(SymVal::is_known) { + SymVal::Struct { + ctor: "list".into(), + fields: vals + .into_iter() + .enumerate() + .map(|(i, v)| (i.to_string(), v)) + .collect(), + } + } else { + SymVal::Unknown + } + } + PureExpr::Map(entries) => { + let vals: Vec<(String, SymVal)> = entries + .iter() + .map(|(k, v)| (k.clone(), eval_pure(v, state))) + .collect(); + if vals.iter().all(|(_, v)| v.is_known()) { + SymVal::Struct { + ctor: "map".into(), + fields: vals, + } + } else { + SymVal::Unknown + } + } + PureExpr::Interp(_) => SymVal::Unknown, + PureExpr::Ctor { name, args } => eval_ctor(name, args, state), + } +} + +/// 内联构造器(与 `mqResultOk`/`mqResultError`/`mqValueOr` 语义一致)。 +fn eval_ctor(name: &str, args: &[PureExpr], state: &HashMap) -> SymVal { + let vals: Vec = args.iter().map(|a| eval_pure(a, state)).collect(); + match (name, vals.as_slice()) { + ("result.ok", [v]) => SymVal::Struct { + ctor: "result.ok".into(), + fields: vec![ + ("ok".into(), SymVal::Bool(true)), + ("value".into(), v.clone()), + ("error".into(), SymVal::None), + ], + }, + ("result.error", [code, message, operation]) => SymVal::Struct { + ctor: "result.error".into(), + fields: vec![ + ("ok".into(), SymVal::Bool(false)), + ("error".into(), code.clone()), + ("message".into(), message.clone()), + ("operation".into(), operation.clone()), + ("value".into(), SymVal::None), + ], + }, + ("result.value_or", [r, default]) => match r { + SymVal::Struct { ctor, fields } + if ctor == "result.ok" => + { + fields + .iter() + .find(|(k, _)| k == "value") + .map(|(_, v)| v.clone()) + .unwrap_or(default.clone()) + } + SymVal::Struct { ctor, .. } if ctor == "result.error" => default.clone(), + _ => SymVal::Unknown, + }, + _ => SymVal::Unknown, + } +} + +fn eval_bin( + operator: crate::prove::ir::BinOp, + left: &PureExpr, + right: &PureExpr, + state: &HashMap, +) -> SymVal { + use crate::prove::ir::BinOp as B; + let l = eval_pure(left, state); + let r = eval_pure(right, state); + match (operator, l, r) { + (B::Add, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_add(b)), + (B::Sub, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_sub(b)), + (B::Mul, SymVal::Int(a), SymVal::Int(b)) => SymVal::Int(a.wrapping_mul(b)), + (B::Div, SymVal::Int(a), SymVal::Int(b)) if b != 0 => SymVal::Int(a / b), + (B::Eq, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a == b), + (B::Eq, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a == b), + (B::Eq, SymVal::Text(a), SymVal::Text(b)) => SymVal::Bool(a == b), + (B::Ne, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a != b), + (B::Ne, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a != b), + (B::Ne, SymVal::Text(a), SymVal::Text(b)) => SymVal::Bool(a != b), + (B::Lt, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a < b), + (B::Le, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a <= b), + (B::Gt, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a > b), + (B::Ge, SymVal::Int(a), SymVal::Int(b)) => SymVal::Bool(a >= b), + (B::And, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a && b), + (B::Or, SymVal::Bool(a), SymVal::Bool(b)) => SymVal::Bool(a || b), + _ => SymVal::Unknown, + } +} + +// --------------------------------------------------------------------------- +// 定理检查(§5.3 第 4–5 步) +// --------------------------------------------------------------------------- + +/// 前提原子(F5 区间 / F4 自由布尔)。 +#[derive(Debug, Clone)] +pub enum PremiseAtom { + Interval { var: String, op: Cmp, val: i64 }, + FreeBool { op: String, key: String, expected: bool }, + Literal(bool), + /// 超出片段的前提 → 不使用(相关定理 unverified)。 + Opaque, +} + +pub fn parse_premise(text: &str) -> Option { + let toks = tokenize_claim(text).ok()?; + let (_, ast) = parse_claim_expr(&toks).ok()?; + premise_atom(&ast) +} + +fn premise_atom(ast: &ClaimAst) -> Option { + match ast { + ClaimAst::Bin { op, left, right } => { + let cmp = match *op { + "<" => Cmp::Lt, + "≤" => Cmp::Le, + ">" => Cmp::Gt, + "≥" => Cmp::Ge, + "=" => Cmp::Eq, + "≠" => Cmp::Ne, + _ => return None, + }; + match (left.as_ref(), right.as_ref()) { + (ClaimAst::Var(v), ClaimAst::Lit(CTok::Int(c))) => { + Some(PremiseAtom::Interval { var: v.clone(), op: cmp, val: *c }) + } + (ClaimAst::Lit(CTok::Int(c)), ClaimAst::Var(v)) => { + Some(PremiseAtom::Interval { var: v.clone(), op: cmp.flip(), val: *c }) + } + // `access(结果, "ok") = True/False` 形前提。 + (ClaimAst::Call { name, args }, ClaimAst::Lit(CTok::Bool(b))) + if name == "access" && args.len() == 2 => + { + let (base, key) = access_parts(&args[0], &args[1])?; + Some(PremiseAtom::FreeBool { op: base, key, expected: *b }) + } + _ => None, + } + } + ClaimAst::Lit(CTok::Bool(b)) => Some(PremiseAtom::Literal(*b)), + _ => None, + } +} + +impl Cmp { + fn flip(self) -> Cmp { + match self { + Cmp::Lt => Cmp::Gt, + Cmp::Le => Cmp::Ge, + Cmp::Gt => Cmp::Lt, + Cmp::Ge => Cmp::Le, + Cmp::Eq => Cmp::Eq, + Cmp::Ne => Cmp::Ne, + } + } +} + +/// `结果.ok` / `access(结果, "ok")` → (主体名, 字段)。 +fn access_parts(base: &ClaimAst, key: &ClaimAst) -> Option<(String, String)> { + let ClaimAst::Var(v) = base else { + return None; + }; + let (root, field) = match v.split_once('.') { + Some((r, f)) => (r.to_string(), Some(f.to_string())), + None => (v.clone(), None), + }; + if let Some(f) = field { + return Some((root, f)); + } + let ClaimAst::Lit(CTok::Text(k)) = key else { + return None; + }; + Some((root, k.clone())) +} + +/// 结论的结构化形态(离线可判定的子集)。 +#[derive(Debug, Clone)] +pub enum Conclusion { + /// `<主体>.<字段> = true/false`(字段布尔;主体可为 结果/中间变量)。 + FieldBool { subject: String, field: String, expected: bool }, + /// `包含(轨迹, "s")` / 其否定。 + TraceContains { item: String, expected: bool }, + /// `长度(轨迹) ⋈ n`。 + TraceLen { op: Cmp, val: i64 }, + /// `x ⋈ c`(参数区间,F5)。 + ParamInterval { var: String, op: Cmp, val: i64 }, + /// `且`/`或`/`非` 组合。 + Not(Box), + And(Box, Box), + Or(Box, Box), + /// 超出片段。 + Opaque(String), +} + +pub fn parse_conclusion(text: &str) -> Conclusion { + let toks = match tokenize_claim(text) { + Ok(t) => t, + Err(e) => return Conclusion::Opaque(e), + }; + let (_, ast) = match parse_claim_expr(&toks) { + Ok(x) => x, + Err(e) => return Conclusion::Opaque(e), + }; + conclusion_of(&ast) +} + +fn conclusion_of(ast: &ClaimAst) -> Conclusion { + match ast { + ClaimAst::Bin { op, left, right } => match *op { + "且" => Conclusion::And( + Box::new(conclusion_of(left)), + Box::new(conclusion_of(right)), + ), + "或" => Conclusion::Or( + Box::new(conclusion_of(left)), + Box::new(conclusion_of(right)), + ), + _ => { + // 字段布尔:`结果.ok = True` / `审核.ok = True` … + if let Some(c) = field_bool(op, left, right) { + return c; + } + // 轨迹谓词。 + if let Some(c) = trace_conclusion(op, left, right) { + return c; + } + // 参数区间。 + if let Some(c) = param_interval(op, left, right) { + return c; + } + Conclusion::Opaque(format!("不可判定的比较 {op}")) + } + }, + ClaimAst::Un { op, expr } if *op == "非" => { + Conclusion::Not(Box::new(conclusion_of(expr))) + } + ClaimAst::Call { name, args } + if name == "包含" && args.len() == 2 => + { + match args.first() { + Some(ClaimAst::Var(v)) if v == "轨迹" => match &args[1] { + ClaimAst::Lit(CTok::Text(s)) => Conclusion::TraceContains { + item: s.clone(), + expected: true, + }, + _ => Conclusion::Opaque("包含 的成员须是文本字面量".into()), + }, + _ => Conclusion::Opaque("包含 只支持轨迹".into()), + } + } + _ => Conclusion::Opaque("不可判定的结论形状".into()), + } +} + +/// `X.f = b`(X 是 结果/中间变量/access 调用)→ FieldBool。 +fn field_bool(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { + let expected = match (op, right) { + ("=", ClaimAst::Lit(CTok::Bool(b))) => *b, + ("≠", ClaimAst::Lit(CTok::Bool(b))) => !*b, + _ => return None, + }; + let (subject, field): (String, String) = match left { + ClaimAst::Var(v) => { + let (r, f) = v.split_once('.')?; + (r.to_string(), f.to_string()) + } + ClaimAst::Call { name, args } if name == "access" && args.len() == 2 => { + access_parts(&args[0], &args[1])? + } + _ => return None, + }; + Some(Conclusion::FieldBool { + subject, + field, + expected, + }) +} + +/// 轨迹结论:`包含(轨迹, "s") ⋈ Bool` / `长度(轨迹) ⋈ n`。 +fn trace_conclusion(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { + match left { + ClaimAst::Call { name, args } if name == "包含" && args.len() == 2 => { + let ClaimAst::Var(v) = args.first()? else { + return None; + }; + if v != "轨迹" { + return None; + } + let ClaimAst::Lit(CTok::Text(s)) = args.get(1)? else { + return None; + }; + let expected = match (op, right) { + ("=", ClaimAst::Lit(CTok::Bool(b))) => *b, + ("≠", ClaimAst::Lit(CTok::Bool(b))) => !*b, + _ => return None, + }; + Some(Conclusion::TraceContains { + item: s.clone(), + expected, + }) + } + ClaimAst::Call { name, args } if name == "长度" && args.len() == 1 => { + let ClaimAst::Var(v) = args.first()? else { + return None; + }; + if v != "轨迹" { + return None; + } + let ClaimAst::Lit(CTok::Int(n)) = right else { + return None; + }; + let cmp = match op { + "=" => Cmp::Eq, + "≠" => Cmp::Ne, + "<" => Cmp::Lt, + "≤" => Cmp::Le, + ">" => Cmp::Gt, + "≥" => Cmp::Ge, + _ => return None, + }; + Some(Conclusion::TraceLen { op: cmp, val: *n }) + } + _ => None, + } +} + +/// 参数区间结论:`金额 > 9999` 之类。 +fn param_interval(op: &str, left: &ClaimAst, right: &ClaimAst) -> Option { + let cmp = match op { + "<" => Cmp::Lt, + "≤" => Cmp::Le, + ">" => Cmp::Gt, + "≥" => Cmp::Ge, + "=" => Cmp::Eq, + "≠" => Cmp::Ne, + _ => return None, + }; + match (left, right) { + (ClaimAst::Var(v), ClaimAst::Lit(CTok::Int(c))) => Some(Conclusion::ParamInterval { + var: v.clone(), + op: cmp, + val: *c, + }), + (ClaimAst::Lit(CTok::Int(c)), ClaimAst::Var(v)) => Some(Conclusion::ParamInterval { + var: v.clone(), + op: cmp.flip(), + val: *c, + }), + _ => None, + } +} + +/// 一条路径上的结论求值结果。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Truth { + True, + False, + Unknown, +} + +/// 对一条路径检查 `前提 ∧ 路径条件 ⊢ 结论`(§5.3 第 4 步)。 +/// 返回 (真值, 关闭理由)。Unknown = 该路径关闭不了(不猜)。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Closure { + pub truth: Truth, + /// literal / trace / hypothesis / interval / atom(§5.4 证书)。 + pub reason: &'static str, +} + +pub fn check_path( + path: &PathRecord, + premise: Option<&PremiseAtom>, + conclusion: &Conclusion, +) -> Closure { + // 前提必须先可用:超片段前提 → 路径关不了。 + if let Some(PremiseAtom::Opaque) = premise { + return Closure { truth: Truth::Unknown, reason: "premise" }; + } + // 前提与路径条件的合取做区间 + 自由布尔假设。 + let intervals = intervals_of(path, premise); + let free_bools = free_bools_of(path, premise); + + // 可行性:前提区间与路径条件矛盾(交集为空)→ 路径不可行,空真关闭。 + if !feasible(&intervals) { + return Closure { truth: Truth::True, reason: "infeasible" }; + } + + let truth = eval_conclusion(conclusion, path, &intervals, &free_bools); + if truth == Truth::Unknown { + return Closure { truth: Truth::Unknown, reason: "unknown" }; + } + let reason = closure_reason(conclusion, path, premise); + Closure { truth, reason } +} + +/// 区间交集是否非空(可行域检查;无约束的变量视为可行)。 +fn feasible(intervals: &[(String, Cmp, i64)]) -> bool { + use std::collections::BTreeMap; + let mut bounds: BTreeMap, Option)> = BTreeMap::new(); + let mut exacts: BTreeMap> = BTreeMap::new(); + for (var, op, val) in intervals { + let e = bounds + .entry(var.clone()) + .or_insert((None, None)); + match op { + Cmp::Gt => e.0 = Some(e.0.map_or(val + 1, |l: i64| l.max(val + 1))), + Cmp::Ge => e.0 = Some(e.0.map_or(*val, |l: i64| l.max(*val))), + Cmp::Lt => e.1 = Some(e.1.map_or(val - 1, |u: i64| u.min(val - 1))), + Cmp::Le => e.1 = Some(e.1.map_or(*val, |u: i64| u.min(*val))), + Cmp::Eq => exacts.entry(var.clone()).or_default().push(*val), + Cmp::Ne => {} + } + } + for (var, vals) in &exacts { + if vals.iter().any(|v| vals[0] != *v) { + return false; // x = c1 ∧ x = c2, c1≠c2 → 不可行 + } + let c = vals[0]; + if let Some((lo, hi)) = bounds.get(var) { + if lo.map_or(false, |l| l > c) || hi.map_or(false, |h| h < c) { + return false; + } + } + } + bounds.iter().all(|(_, (lo, hi))| match (lo, hi) { + (Some(l), Some(h)) => l <= h, + _ => true, + }) +} + +/// 收集本路径可用的区间约束:路径条件 + 前提。 +fn intervals_of(path: &PathRecord, premise: Option<&PremiseAtom>) -> Vec<(String, Cmp, i64)> { + let mut out = Vec::new(); + for atom in &path.atoms { + if let PathAtom::Interval { var, op, val } = atom { + out.push((var.clone(), *op, *val)); + } + } + if let Some(PremiseAtom::Interval { var, op, val }) = premise { + out.push((var.clone(), *op, *val)); + } + out +} + +fn free_bools_of(path: &PathRecord, premise: Option<&PremiseAtom>) -> Vec<(String, String, bool)> { + let mut out = Vec::new(); + for atom in &path.atoms { + if let PathAtom::FreeBool { op, key, expected } = atom { + out.push((op.clone(), key.clone(), *expected)); + } + } + if let Some(PremiseAtom::FreeBool { op, key, expected }) = premise { + out.push((op.clone(), key.clone(), *expected)); + } + out +} + +/// 结论求值(结构代入:主体变量来自路径快照,参数走区间/自由布尔)。 +fn eval_conclusion( + conclusion: &Conclusion, + path: &PathRecord, + intervals: &[(String, Cmp, i64)], + free_bools: &[(String, String, bool)], +) -> Truth { + let trace: &[String] = &path.trace; + let lookup = |subject: &str| -> Option { + if subject == "结果" { + Some(path.result.clone()) + } else { + path.vars + .iter() + .find(|(k, _)| k == subject) + .map(|(_, v)| v.clone()) + } + }; + match conclusion { + Conclusion::FieldBool { subject, field, expected } => { + // 主体是内联构造器 → 结构化(F3);是 OpResult → 自由原子(F4)。 + let Some(value) = lookup(subject) else { + return Truth::Unknown; + }; + match value { + SymVal::Struct { fields, .. } => match fields.iter().find(|(k, _)| k == field) { + Some((_, SymVal::Bool(b))) => { + if b == expected { + Truth::True + } else { + Truth::False + } + } + _ => Truth::Unknown, + }, + SymVal::OpResult(op) => { + // 自由原子:路径条件或前提里有同键判定才能关闭。 + match free_bools + .iter() + .find(|(o, k, _)| *o == op && k == field) + { + Some((_, _, v)) => { + if *v == *expected { + Truth::True + } else { + Truth::False + } + } + None => Truth::Unknown, + } + } + _ => Truth::Unknown, + } + } + Conclusion::TraceContains { item, expected } => { + let has = trace.iter().any(|op| op == item); + if has == *expected { + Truth::True + } else { + Truth::False + } + } + Conclusion::TraceLen { op, val } => { + let n = trace.len() as i64; + if op.holds(n, *val) { + Truth::True + } else { + Truth::False + } + } + Conclusion::ParamInterval { var, op, val } => { + interval_entailed(intervals, var, *op, *val) + } + Conclusion::Not(inner) => { + eval_conclusion(inner, path, intervals, free_bools).invert() + } + Conclusion::And(a, b) => { + let (ta, tb) = ( + eval_conclusion(a, path, intervals, free_bools), + eval_conclusion(b, path, intervals, free_bools), + ); + match (ta, tb) { + (Truth::False, _) | (_, Truth::False) => Truth::False, + (Truth::True, Truth::True) => Truth::True, + _ => Truth::Unknown, + } + } + Conclusion::Or(a, b) => { + let (ta, tb) = ( + eval_conclusion(a, path, intervals, free_bools), + eval_conclusion(b, path, intervals, free_bools), + ); + match (ta, tb) { + (Truth::True, _) | (_, Truth::True) => Truth::True, + (Truth::False, Truth::False) => Truth::False, + _ => Truth::Unknown, + } + } + Conclusion::Opaque(_) => Truth::Unknown, + } +} + +impl Truth { + fn invert(self) -> Truth { + match self { + Truth::True => Truth::False, + Truth::False => Truth::True, + Truth::Unknown => Truth::Unknown, + } + } +} + +/// F5 蕴含:区间集合是否迫使 `var ⋈ val` 成立。 +/// True = 区间整体落在满足侧;False = 整体落在违反侧(可反例);否则不猜。 +fn interval_entailed(intervals: &[(String, Cmp, i64)], var: &str, op: Cmp, val: i64) -> Truth { + let mut lower: Option = None; + let mut upper: Option = None; + let mut exact: Option = None; + let mut conflict = false; + for (v, o, c) in intervals { + if v != var { + continue; + } + match o { + Cmp::Gt => lower = Some(lower.map_or(c + 1, |l: i64| l.max(c + 1))), + Cmp::Ge => lower = Some(lower.map_or(*c, |l: i64| l.max(*c))), + Cmp::Lt => upper = Some(upper.map_or(c - 1, |u: i64| u.min(c - 1))), + Cmp::Le => upper = Some(upper.map_or(*c, |u: i64| u.min(*c))), + Cmp::Eq => { + if let Some(e) = exact { + if e != *c { + conflict = true; + } + } + exact = Some(*c); + } + Cmp::Ne => {} + } + } + let _ = conflict; // 约束冲突保守当作"不蕴含"处理(不判 False) + if let Some(e) = exact { + // 精确值还要落在区间内才可信。 + let in_range = lower.map_or(true, |l| e >= l) && upper.map_or(true, |u| e <= u); + if in_range { + return if op.holds(e, val) { + Truth::True + } else { + Truth::False + }; + } + return Truth::Unknown; + } + // 正向闭包(True)只认**字面出现**的原子:区间蕴含(如 金额 > 10000 ⊢ + // 金额 > 9999)数学上成立,但当前 Lean 脚本没有 Val 比较的传递引理, + // simp+omega 关不掉——离线先于 Lean 关闭即触发 proof.divergence。 + // 保守:字面匹配 → hypothesis 关闭;否则不猜(等库补传递引理再放开)。 + for (v, o, c) in intervals { + if v == var && *o == op && *c == val { + return Truth::True; + } + } + // False:整段区间违反目标 → 确定性否定(反例见证)。这在数学上成立 + // (区间端点即见证),Lean 侧同样证不出该定理——两侧一致 unproved。 + let violated = match op { + Cmp::Gt => upper.map_or(false, |u| u <= val), + Cmp::Ge => upper.map_or(false, |u| u < val), + Cmp::Lt => lower.map_or(false, |l| l >= val), + Cmp::Le => lower.map_or(false, |l| l > val), + Cmp::Eq => lower.map_or(false, |l| l > val) || upper.map_or(false, |u| u < val), + Cmp::Ne => false, // ≠ 无法用区间否定(需精确值) + }; + if violated { + return Truth::False; + } + Truth::Unknown +} + +/// 关闭理由(§5.4 证书字段)。 +fn closure_reason(conclusion: &Conclusion, path: &PathRecord, premise: Option<&PremiseAtom>) -> &'static str { + match conclusion { + Conclusion::FieldBool { subject, .. } => { + let value = if subject == "结果" { + Some(path.result.clone()) + } else { + path.vars + .iter() + .find(|(k, _)| k == subject) + .map(|(_, v)| v.clone()) + }; + match value { + Some(SymVal::Struct { .. }) => "literal", + Some(SymVal::OpResult(_)) => "hypothesis", + _ => "unknown", + } + } + Conclusion::TraceContains { .. } | Conclusion::TraceLen { .. } => "trace", + Conclusion::ParamInterval { .. } => { + if premise.is_some() { + "interval" + } else { + "interval" + } + } + Conclusion::Not(inner) => closure_reason(inner, path, premise), + Conclusion::And(a, _) | Conclusion::Or(a, _) => closure_reason(a, path, premise), + Conclusion::Opaque(_) => "unknown", + } +} + +/// 检查一条定理(§5.3 第 5 步):全部路径关闭 → checked; +/// 某路径确定性为假 → unproved + 反例(§5.5 三条件);否则 unverified。 +pub fn check_claim(fn_plan: &FnPlan, claim: &crate::prove::ir::ClaimPlan) -> OfflineVerdict { + let paths = execute(fn_plan); + if paths.is_empty() { + return OfflineVerdict::Unverified { + reason: "无可枚举路径".into(), + }; + } + if std::env::var("MARQDO_PROOF_DEBUG").is_ok_and(|v| v == "1") { + for p in execute(fn_plan) { + eprintln!( + "[offline-path #{}] atoms={:?} result={:?} trace={:?} vars={:?} opaque={}", + p.id, p.atoms, p.result, p.trace, p.vars, p.opaque + ); + } + } + let premise = claim.premise.as_deref().and_then(parse_premise); + // 前提文本存在但解析不出原子 → 超片段。 + let premise: Option = match (&claim.premise, premise) { + (Some(_), None) => Some(PremiseAtom::Opaque), + (_, p) => p, + }; + let conclusion = parse_conclusion(&claim.conclusion); + + let mut closed = 0usize; + let mut first_false: Option<(&PathRecord, Closure)> = None; + for path in &paths { + if path.opaque { + return OfflineVerdict::Unverified { + reason: "路径超出片段(不透明条件/表达式)".into(), + }; + } + let closure = check_path(path, premise.as_ref(), &conclusion); + match closure.truth { + Truth::True => closed += 1, + Truth::False => { + if first_false.is_none() { + first_false = Some((path, closure)); + } + } + Truth::Unknown => { + return OfflineVerdict::Unverified { + reason: format!("路径 #{} 关闭不了(不猜)", path.id), + } + } + } + } + if let Some((path, _)) = first_false { + // §5.5 反例三条件:结论确定性为假 ✓;路径可满足(区间取见证)✓; + // 路径条件不含自由布尔原子(否则可能凑出不存在的组合)。 + let has_free_bool = path + .atoms + .iter() + .any(|a| matches!(a, PathAtom::FreeBool { .. })); + if has_free_bool { + return OfflineVerdict::Unverified { + reason: "反例路径含自由布尔原子(保守放弃见证)".into(), + }; + } + let counterexample = witness(fn_plan, path, premise.as_ref()); + return OfflineVerdict::Unproved { counterexample }; + } + OfflineVerdict::Checked { cases: closed } +} + +/// 从区间端点取见证参数值(§5.5)。无区间约束的整型参数取 0(空约束平凡可满足)。 +fn witness( + fn_plan: &FnPlan, + path: &PathRecord, + premise: Option<&PremiseAtom>, +) -> Option { + let mut assignments: Vec<(String, i64)> = Vec::new(); + let mut constraints: Vec<(String, Cmp, i64)> = Vec::new(); + for atom in &path.atoms { + if let PathAtom::Interval { var, op, val } = atom { + constraints.push((var.clone(), *op, *val)); + } + } + if let Some(PremiseAtom::Interval { var, op, val }) = premise { + constraints.push((var.clone(), *op, *val)); + } + // 按 var 聚合求可行点:下界取 max+?,上界取 min-?,取中点。 + use std::collections::BTreeMap; + let mut bounds: BTreeMap, Option)> = BTreeMap::new(); + for (var, op, val) in &constraints { + let e = bounds.entry(var.clone()).or_insert((None, None)); + match op { + Cmp::Gt => e.0 = Some(e.0.map_or(val + 1, |l: i64| l.max(val + 1))), + Cmp::Ge => e.0 = Some(e.0.map_or(*val, |l: i64| l.max(*val))), + Cmp::Lt => e.1 = Some(e.1.map_or(val - 1, |u: i64| u.min(val - 1))), + Cmp::Le => e.1 = Some(e.1.map_or(*val, |u: i64| u.min(*val))), + Cmp::Eq => { + // 等式约束与区间冲突时放弃见证(保守)。 + if let (Some(l), Some(u)) = (e.0, e.1) { + if l > *val || u < *val { + return None; + } + } + e.0 = Some(*val); + e.1 = Some(*val); + } + Cmp::Ne => {} + } + } + for (var, (lo, hi)) in bounds { + match (lo, hi) { + (Some(l), Some(h)) if l > h => return None, // 路径不可满足(不应发生) + (Some(l), Some(h)) => assignments.push((var, l + (h - l) / 2)), + (Some(l), None) => assignments.push((var, l)), + (None, Some(h)) => assignments.push((var, h)), + (None, None) => {} + } + } + if assignments.is_empty() { + // 无任何区间约束:整型参数取 0(空约束下任意值都满足该路径)。 + for p in &fn_plan.params { + if matches!(p.ty, crate::prove::ir::PlanTy::Int) { + assignments.push((p.name.clone(), 0)); + } + } + } + if assignments.is_empty() { + return None; + } + let detail = assignments + .iter() + .map(|(k, v)| format!("{k} = {v}")) + .collect::>() + .join(", "); + Some(Counterexample { + assignments, + path_id: path.id, + detail, + }) +} + +/// 整个文件的离线判定:每函数每定理。 +pub fn check_plan(plan: &Plan) -> Vec<(String, String, OfflineVerdict)> { + let mut out = Vec::new(); + for f in &plan.functions { + for c in &f.claims { + let verdict = check_claim(f, c); + out.push((f.name.clone(), c.id.clone(), verdict)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prove::ir::{ + BinOp, ClaimPlan, Expr, FnPlan, ParamPlan, Plan, PlanTy, PureExpr, Step, + }; + + fn ledger_fn(steps: Vec, claims: Vec) -> FnPlan { + FnPlan { + name: "台账.记录".into(), + params: vec![ParamPlan { + name: "金额".into(), + ty: PlanTy::Int, + has_default: false, + }], + result_ty: PlanTy::Any, + ops: vec![], + steps, + effects: vec![], + claims, + assumptions: vec![], + } + } + + /// `结果 = result.ok(金额)`;`返回 结果`。 + fn literal_ok_steps() -> Vec { + vec![ + Step::Bind { + var: "结果".into(), + expr: Expr::Pure(PureExpr::Ctor { + name: "result.ok".into(), + args: vec![PureExpr::Var("金额".into())], + }), + line: 10, + }, + Step::Return { + expr: Expr::Pure(PureExpr::Var("结果".into())), + line: 11, + }, + ] + } + + #[test] + fn f3_literal_result_field_closes() { + let f = ledger_fn( + literal_ok_steps(), + vec![ClaimPlan { + id: "必有回执".into(), + premise: None, + conclusion: "结果.ok = True".into(), + tactic: None, + line: 5, + }], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Checked { cases } => assert!(cases >= 1), + other => panic!("F3 应当 checked:{other:?}"), + } + } + + #[test] + fn f3_false_claim_refuted_with_counterexample() { + let f = ledger_fn( + literal_ok_steps(), + vec![ClaimPlan { + id: "没有回执".into(), + premise: None, + conclusion: "结果.ok = False".into(), + tactic: None, + line: 5, + }], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Unproved { counterexample } => { + assert!(counterexample.is_some(), "确定性否定必须带见证"); + } + other => panic!("F3 反例应当 unproved:{other:?}"), + } + } + + #[test] + fn f2_trace_length_and_contains() { + // 金额 > 10000 → 轨迹 = [人工审核];否则空。 + let steps = vec![Step::If { + cond: PureExpr::Bin { + operator: BinOp::Gt, + left: Box::new(PureExpr::Var("金额".into())), + right: Box::new(PureExpr::Int(10000)), + }, + then: vec![Step::Trace { + op: "调用:人工审核".into(), + args: vec![], + line: 20, + }], + otherwise: vec![], + line: 19, + }]; + let mk = |id: &str, conclusion: &str, premise: Option<&str>| ClaimPlan { + id: id.into(), + premise: premise.map(Into::into), + conclusion: conclusion.into(), + tactic: None, + line: 5, + }; + let f = ledger_fn( + steps, + vec![ + mk("恰一步", "长度(轨迹) = 1", Some("金额 > 10000")), + mk("恰零步", "长度(轨迹) = 0", None), + mk("必经人工", "包含(轨迹, \"人工审核\")", Some("金额 > 10000")), + ], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Checked { .. } => {} + other => panic!("F2 长度应 checked:{other:?}"), + } + // 无前提:两条路径都要关(一条长 1、一条长 0)→ 长度=0 关不了。 + match check_claim(&f, &f.claims[1]) { + OfflineVerdict::Unproved { .. } | OfflineVerdict::Unverified { .. } => {} + other => panic!("无前提的 长度=0 不得 checked:{other:?}"), + } + match check_claim(&f, &f.claims[2]) { + OfflineVerdict::Checked { .. } => {} + other => panic!("F2 包含应 checked:{other:?}"), + } + } + + #[test] + fn f4_free_bool_atom_via_hypothesis() { + // 审核 = op(金额);1. 审核.ok = True → 路径条件为自由布尔; + // 结论 `审核.ok = True` 由 hypothesis 关闭。 + let steps = vec![ + Step::Bind { + var: "审核".into(), + expr: Expr::Op { + id: "调用:人工审核".into(), + args: vec![PureExpr::Var("金额".into())], + }, + line: 30, + }, + Step::If { + cond: PureExpr::Access { + base: Box::new(PureExpr::Var("审核".into())), + key: "ok".into(), + }, + then: vec![Step::Return { + expr: Expr::Pure(PureExpr::Var("审核".into())), + line: 32, + }], + otherwise: vec![Step::Return { + expr: Expr::Pure(PureExpr::Ctor { + name: "result.ok".into(), + args: vec![PureExpr::Text("跳过".into())], + }), + line: 34, + }], + line: 31, + }, + ]; + // 自由原子二分后的 else 路径上 `审核.ok = False` 是**真实可能**的, + // 所以单边结论只能保守 unverified(不猜)。 + let f = ledger_fn( + steps, + vec![ + ClaimPlan { + id: "审核必有结论".into(), + premise: Some("金额 > 10000".into()), + conclusion: "审核.ok = True 或 审核.ok = False".into(), + tactic: None, + line: 5, + }, + ClaimPlan { + id: "审核必过".into(), + premise: Some("金额 > 10000".into()), + conclusion: "审核.ok = True".into(), + tactic: None, + line: 6, + }, + ], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Checked { .. } => {} + other => panic!("F4 hypothesis(或式)应 checked:{other:?}"), + } + match check_claim(&f, &f.claims[1]) { + OfflineVerdict::Unverified { .. } => {} + other => panic!("自由原子单边结论必须保守 unverified:{other:?}"), + } + } + + #[test] + fn f5_interval_closure_scope() { + // 字面重述(同原子):hypothesis 关闭(Lean 侧假设就在那里)。 + let f = ledger_fn( + literal_ok_steps(), + vec![ + ClaimPlan { + id: "前提重述".into(), + premise: Some("金额 > 10000".into()), + conclusion: "金额 > 10000".into(), + tactic: None, + line: 5, + }, + // 区间蕴含(10000 ⊢ 9999)数学上真,但当前 Lean 脚本无 + // Val 比较传递引理——离线必须同样保守(§5.4 单调性)。 + ClaimPlan { + id: "区间蕴含".into(), + premise: Some("金额 > 10000".into()), + conclusion: "金额 > 9999".into(), + tactic: None, + line: 6, + }, + ], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Checked { .. } => {} + other => panic!("字面重述应 checked:{other:?}"), + } + match check_claim(&f, &f.claims[1]) { + OfflineVerdict::Unverified { .. } => {} + other => panic!("无传递引理时区间蕴含必须保守:{other:?}"), + } + } + + #[test] + fn f5_interval_refutation_gives_witness() { + let f = ledger_fn( + literal_ok_steps(), + vec![ClaimPlan { + id: "小额断言".into(), + premise: Some("金额 > 10000".into()), + conclusion: "金额 < 100".into(), + tactic: None, + line: 5, + }], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Unproved { counterexample } => { + let c = counterexample.expect("区间分离必须给见证"); + assert!(c.detail.contains("金额")); + } + other => panic!("F5 分离应 unproved + 见证:{other:?}"), + } + } + + #[test] + fn beyond_fragment_stays_unverified() { + // 文本比较(字符串序)超出片段 → 不猜。 + let f = ledger_fn( + literal_ok_steps(), + vec![ClaimPlan { + id: "文本比较".into(), + premise: None, + conclusion: "结果.value = \"x\"".into(), + tactic: None, + line: 5, + }], + ); + match check_claim(&f, &f.claims[0]) { + OfflineVerdict::Unverified { .. } | OfflineVerdict::Checked { .. } => {} + other => panic!("超片段不得 unproved:{other:?}"), + } + } + + #[test] + fn plan_wide_check_runs_all() { + let f = ledger_fn( + literal_ok_steps(), + vec![ClaimPlan { + id: "必有回执".into(), + premise: None, + conclusion: "结果.ok = True".into(), + tactic: None, + line: 5, + }], + ); + let plan = Plan { + schema: crate::prove::ir::SCHEMA, + module: "测试".into(), + source_sha256: "a".repeat(64), + functions: vec![f], + }; + let results = check_plan(&plan); + assert_eq!(results.len(), 1); + assert!(matches!(results[0].2, OfflineVerdict::Checked { .. })); + } +} diff --git a/src/prove/proof_check.rs b/src/prove/proof_check.rs new file mode 100755 index 0000000..70eff21 --- /dev/null +++ b/src/prove/proof_check.rs @@ -0,0 +1,812 @@ +//! `check --proof`:定理表的静态校验(设计 §7;默认关)。 +//! +//! 校验项(全部 advisory 之外都是 Error 级诊断): +//! - `proof.claim_malformed` 表头命中定理词表但列形不齐 +//! - `proof.claim_ambiguous` 同时有 `类型` 与 `结论` 列 +//! - `proof.claim_misplaced` 合法定理表出现在首条可执行语句之后 +//! - `proof.claim_duplicate` 同一函数内定理 id 重复 +//! - `proof.claim_unknown_symbol` 结论/前提引用了受限符号集之外的名字 +//! - `proof.claim_unsupported` 谓词超出封闭集合(包含/长度/下标)或元数不对 +//! - `proof.name_shadow` 保留名(`结果`/`轨迹`)被形参/局部变量遮蔽 + +use std::path::Path; + +use crate::ast::{Expr, Function, Module, Stmt}; +use crate::contract; +use crate::diagnostics::{Diagnostic, Severity, Span}; + +/// 定理作用域保留名(§7.3.4)。 +pub const RESERVED_CLAIM_NAMES: &[&str] = &["结果", "轨迹"]; + +/// 谓词封闭集合(§7.3.5:改集合需重新评审 ADR)。 +pub const PREDICATES: &[(&str, usize)] = &[("包含", 2), ("长度", 1), ("下标", 2)]; + +/// 入口:对整个模块做定理表校验(只看主文件;与契约检查同一范围, +/// import 库文件不重复校验——诊断的行号锚在主文件上才有意义)。 +pub fn check_proofs(module: &Module, path: Option<&Path>) -> Vec { + let mut out = Vec::new(); + let mut function_names: Vec = Vec::new(); + collect_function_names(module, &mut function_names); + // 谓词名遮蔽是模块级事实(与单个函数无关),整个模块只报一次; + // 诊断锚在被遮蔽的函数上(任意深度)。 + for pred in PREDICATES { + if function_names.iter().any(|n| n == pred.0) { + let Some(fun) = find_by_name(&module.functions, pred.0) else { + continue; + }; + out.push(proof_diag( + module, + path, + fun.span, + "proof.name_shadow", + format!( + "函数名 `{}` 与定理谓词 `{}` 同名(谓词集合封闭:包含/长度/下标)", + fun.name, pred.0 + ), + format!("把函数 `{}` 改名,避免定理表里的 `{}` 歧义", fun.name, pred.0), + )); + } + } + walk_checks(module, &module.functions, path, &mut out); + out +} + +fn walk_checks(module: &Module, funs: &[Function], path: Option<&Path>, out: &mut Vec) { + for fun in funs { + check_claim_duplicates(module, fun, path, out); + check_name_shadow(module, fun, path, out); + check_misplaced_and_malformed(module, fun, path, out); + check_claim_symbols(module, fun, path, out); + walk_checks(module, &fun.children, path, out); + } +} + +fn collect_function_names(module: &Module, out: &mut Vec) { + fn go(funs: &[Function], out: &mut Vec) { + for f in funs { + out.push(f.name.clone()); + go(&f.children, out); + } + } + go(&module.functions, out); + for child in module.import_modules.values() { + collect_function_names(child, out); + } +} + +/// 在函数树里按显示名找函数(诊断锚点用)。 +fn find_by_name<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> { + for f in funs { + if f.name == name { + return Some(f); + } + if let Some(inner) = find_by_name(&f.children, name) { + return Some(inner); + } + } + None +} + +fn proof_diag( + module: &Module, + path: Option<&Path>, + span: Span, + code: &str, + message: String, + suggestion: String, +) -> Diagnostic { + let _ = module; + Diagnostic::new(path, span, message) + .with_code(code) + .with_severity(Severity::Error) + .with_suggestion(suggestion) +} + +/// 同一函数内定理 id 重复(§7.1 规则 3)。 +fn check_claim_duplicates(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { + let mut seen: Vec<&str> = Vec::new(); + for claim in &fun.claims { + if seen.contains(&claim.id.as_str()) { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_duplicate", + format!("定理 `{}` 在 `{}` 内重复声明", claim.id, fun.name), + "定理 id 在函数内必须唯一;重命名或删除重复行".into(), + )); + } else { + seen.push(&claim.id); + } + } +} + +/// 遮蔽检查(§7.3.4):只看**自带定理表的函数**——形参 `结果`/`轨迹` 会 +/// 与该函数定理作用域的输出绑定名冲突;没有定理表的函数不受影响。 +fn check_name_shadow( + module: &Module, + fun: &Function, + path: Option<&Path>, + out: &mut Vec, +) { + if fun.claims.is_empty() { + return; + } + for param in &fun.params { + if RESERVED_CLAIM_NAMES.contains(¶m.name.as_str()) { + out.push(proof_diag( + module, + path, + param.span, + "proof.name_shadow", + format!( + "形参 `{}` 与定理作用域保留名冲突(`{}` 也要声明定理)", + param.name, + fun.name + ), + format!("把形参 `{}` 改名;`结果`/`轨迹` 在定理里指返回值与操作轨迹", param.name), + )); + } + } +} + +/// 错位与畸形:body 里仍是定理形的表(默认关时解析器不提取它们)。 +fn check_misplaced_and_malformed( + module: &Module, + fun: &Function, + path: Option<&Path>, + out: &mut Vec, +) { + let mut prefix_zone = true; + for stmt in &fun.body { + let (pairs, span) = match stmt { + Stmt::Expr { + value: Expr::Map(pairs), + span, + } => (pairs, *span), + Stmt::Expr { value: Expr::List(_), .. } => continue, + _ => { + prefix_zone = false; + continue; + } + }; + match contract::parse_claim_table(pairs, span.line) { + Some(Ok(_rows)) => { + // 合法定理形却还在 body:一定是位置不对(prefix zone 内会被提取)。 + out.push(proof_diag( + module, + path, + span, + "proof.claim_misplaced", + format!( + "`{}` 的定理表出现在首条可执行语句之后——它是普通表,不会成为定理", + fun.name + ), + "把定理表移到函数体开头(与契约表同一槽位)".into(), + )); + } + Some(Err(err)) => { + out.push(proof_diag( + module, + path, + span, + err.code, + err.message, + "对照定理表形状:| 定理 | 结论 | 前提 | 策略 |(前提/策略可省)".into(), + )); + } + None => {} + } + let _ = prefix_zone; + } +} + +/// 受限符号集校验(§7.1 规则 4):前提只看形参;结论可加 `结果`/`轨迹`。 +fn check_claim_symbols(module: &Module, fun: &Function, path: Option<&Path>, out: &mut Vec) { + if fun.claims.is_empty() { + return; + } + let params: Vec = fun.params.iter().map(|p| p.name.clone()).collect(); + for claim in &fun.claims { + if let Some(tactic) = &claim.tactic { + if tactic != "auto" && tactic != "none" { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的策略 `{}` 不在 auto/none 内", claim.id, tactic), + "策略列只接受 auto(自动)或 none(永远 unverified)".into(), + )); + } + } + if let Some(premise) = &claim.premise { + check_claim_expr( + module, + path, + premise, + claim, + ¶ms, + false, + out, + ); + } + check_claim_expr(module, path, &claim.conclusion, claim, ¶ms, true, out); + } +} + +fn check_claim_expr( + module: &Module, + path: Option<&Path>, + text: &str, + claim: &crate::ast::Claim, + params: &[String], + conclusion_scope: bool, + out: &mut Vec, +) { + let tokens = match tokenize_claim(text) { + Ok(t) => t, + Err(msg) => { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的表达无法解析:{msg}", claim.id), + "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), + )); + return; + } + }; + match parse_claim_expr(&tokens) { + Ok((_, ast)) => collect_symbols( + module, + path, + claim, + &ast, + params, + conclusion_scope, + out, + ), + Err(msg) => { + out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_malformed", + format!("定理 `{}` 的表达无法解析:{msg}", claim.id), + "受限表达式:名字、数字、字符串、比较/算术/布尔、包含(轨迹,x)/长度(轨迹)/下标(轨迹,i)".into(), + )); + } + } +} + +// ---------------------------------------------------------------- 受限表达式 + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum CTok { + Name(String), + Int(i64), + Num(f64), + Text(String), + Bool(bool), + Op(&'static str), + LParen, + RParen, + Comma, + Dot, +} + +/// 词法:把受限表达文本切成记号(emit 与 check 共用)。 +pub(crate) fn tokenize_claim(text: &str) -> Result, String> { + let mut out = Vec::new(); + let chars: Vec = text.chars().collect(); + let mut i = 0usize; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + continue; + } + match c { + '(' => out.push(CTok::LParen), + ')' => out.push(CTok::RParen), + ',' | ',' => out.push(CTok::Comma), + '.' | '。' => out.push(CTok::Dot), + '"' | '“' | '”' => { + // 字符串字面量(到下一个同类引号)。 + let close = c; + let mut j = i + 1; + let mut s = String::new(); + while j < chars.len() && chars[j] != close { + s.push(chars[j]); + j += 1; + } + if j >= chars.len() { + return Err("字符串没有闭合引号".into()); + } + out.push(CTok::Text(s)); + i = j; + } + '`' => { + // `` `名字` `` → 名字。 + let mut j = i + 1; + let mut s = String::new(); + while j < chars.len() && chars[j] != '`' { + s.push(chars[j]); + j += 1; + } + if j >= chars.len() { + return Err("反引号名没有闭合".into()); + } + out.push(CTok::Name(s)); + i = j; + } + '0'..='9' => { + let mut j = i; + let mut s = String::new(); + let mut dotted = false; + while j < chars.len() && (chars[j].is_ascii_digit() || chars[j] == '.') { + if chars[j] == '.' { + if dotted { + break; + } + dotted = true; + } + s.push(chars[j]); + j += 1; + } + if dotted { + out.push(CTok::Num(s.parse::().map_err(|_| "数字解析失败")?)); + } else { + out.push(CTok::Int(s.parse::().map_err(|_| "整数解析失败")?)); + } + i = j - 1; + } + '=' => out.push(CTok::Op("=")), + '≠' | '!' => out.push(CTok::Op("≠")), + '<' => out.push(CTok::Op("<")), + '≤' => out.push(CTok::Op("≤")), + '>' => out.push(CTok::Op(">")), + '≥' => out.push(CTok::Op("≥")), + '+' => out.push(CTok::Op("+")), + '-' | '−' => out.push(CTok::Op("-")), + '*' | '×' => out.push(CTok::Op("*")), + '/' | '÷' => out.push(CTok::Op("/")), + _ => { + // 名字 / 中文词 / 关键字。 + if c.is_alphanumeric() || c == '_' { + let mut j = i; + let mut s = String::new(); + while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '.') { + s.push(chars[j]); + j += 1; + } + i = j - 1; + match s.as_str() { + "且" | "and" => out.push(CTok::Op("且")), + "或" | "or" => out.push(CTok::Op("或")), + "非" | "not" => out.push(CTok::Op("非")), + "真" | "true" | "True" => out.push(CTok::Bool(true)), + "假" | "false" | "False" => out.push(CTok::Bool(false)), + _ => { + // `名字.字段` 已并入 s(含点)。 + out.push(CTok::Name(s)); + } + } + } else { + return Err(format!("无法识别的字符 `{c}`")); + } + } + } + i += 1; + } + Ok(out) +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] // op/字面值记号保留:P1 语义求值与 Lean 脚本生成要用。 +pub(crate) enum ClaimAst { + Lit(CTok), + /// 名字(可含 `.字段`;已合并进字符串)。 + Var(String), + Call { name: String, args: Vec }, + Bin { op: &'static str, left: Box, right: Box }, + Un { op: &'static str, expr: Box }, +} + +struct P<'a> { + toks: &'a [CTok], + pos: usize, +} + +impl<'a> P<'a> { + fn peek(&self) -> Option<&CTok> { + self.toks.get(self.pos) + } + fn next(&mut self) -> Option { + let t = self.toks.get(self.pos).cloned(); + if t.is_some() { + self.pos += 1; + } + t + } + fn eat_op(&mut self, ops: &[&str]) -> Option<&'static str> { + let CTok::Op(o) = self.peek()? else { + return None; + }; + if !ops.contains(o) { + return None; + } + let hit: &'static str = match *o { + "+" => "+", + "-" => "-", + "*" => "*", + "/" => "/", + "=" => "=", + "≠" => "≠", + "<" => "<", + "≤" => "≤", + ">" => ">", + "≥" => "≥", + "且" => "且", + "或" => "或", + "非" => "非", + _ => return None, + }; + self.pos += 1; + Some(hit) + } +} + +pub(crate) fn parse_claim_expr(toks: &[CTok]) -> Result<(Vec, ClaimAst), String> { + let mut p = P { toks, pos: 0 }; + let ast = parse_or(&mut p)?; + if p.pos != toks.len() { + return Err(format!("表达式末尾有多余内容(第 {} 个记号起)", p.pos + 1)); + } + Ok((toks.to_vec(), ast)) +} + +fn parse_or(p: &mut P) -> Result { + let mut left = parse_and(p)?; + while let Some(op) = p.eat_op(&["或"]) { + let right = parse_and(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_and(p: &mut P) -> Result { + let mut left = parse_cmp(p)?; + while let Some(op) = p.eat_op(&["且"]) { + let right = parse_cmp(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_cmp(p: &mut P) -> Result { + let left = parse_add(p)?; + if let Some(op) = p.eat_op(&["=", "≠", "<", "≤", ">", "≥"]) { + let right = parse_add(p)?; + return Ok(ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }); + } + Ok(left) +} + +fn parse_add(p: &mut P) -> Result { + let mut left = parse_mul(p)?; + while let Some(op) = p.eat_op(&["+", "-"]) { + let right = parse_mul(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_mul(p: &mut P) -> Result { + let mut left = parse_unary(p)?; + while let Some(op) = p.eat_op(&["*", "/"]) { + let right = parse_unary(p)?; + left = ClaimAst::Bin { op, left: Box::new(left), right: Box::new(right) }; + } + Ok(left) +} + +fn parse_unary(p: &mut P) -> Result { + if let Some(op) = p.eat_op(&["非"]) { + let expr = parse_unary(p)?; + return Ok(ClaimAst::Un { op, expr: Box::new(expr) }); + } + if let Some(CTok::Op("-")) = p.peek() { + p.pos += 1; + let expr = parse_unary(p)?; + return Ok(ClaimAst::Un { op: "-", expr: Box::new(expr) }); + } + parse_atom(p) +} + +fn parse_atom(p: &mut P) -> Result { + match p.next() { + Some(CTok::LParen) => { + let e = parse_or(p)?; + match p.next() { + Some(CTok::RParen) => Ok(e), + _ => Err("缺少右括号".into()), + } + } + Some(t @ (CTok::Int(_) | CTok::Num(_) | CTok::Text(_) | CTok::Bool(_))) => Ok(ClaimAst::Lit(t)), + Some(CTok::Name(name)) => { + // 谓词调用:名字后紧跟 `(`。 + if matches!(p.peek(), Some(CTok::LParen)) { + p.pos += 1; + let mut args = Vec::new(); + if !matches!(p.peek(), Some(CTok::RParen)) { + loop { + args.push(parse_or(p)?); + match p.next() { + Some(CTok::Comma) => continue, + Some(CTok::RParen) => break, + _ => return Err("调用参数列表未闭合".into()), + } + } + } else { + p.pos += 1; + } + return Ok(ClaimAst::Call { name, args }); + } + Ok(ClaimAst::Var(name)) + } + other => Err(format!("这里应该是一个名字或值,得到 {other:?}")), + } +} + +/// 收集受限符号并校验(§7.1 规则 4 + §7.3.5 谓词封闭)。 +fn collect_symbols( + module: &Module, + path: Option<&Path>, + claim: &crate::ast::Claim, + ast: &ClaimAst, + params: &[String], + conclusion_scope: bool, + out: &mut Vec, +) { + match ast { + ClaimAst::Lit(_) => {} + ClaimAst::Var(name) => { + // 名字可带 `.字段`(结果.ok / 回执.value)——只校验根名字。 + let root = name.split('.').next().unwrap_or(name); + let known = params.contains(&root.to_string()) + || (conclusion_scope && RESERVED_CLAIM_NAMES.contains(&root)); + if !known { + let suggestion = crate::check::suggest_closest(root, params); + let mut d = proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unknown_symbol", + format!( + "定理 `{}` 引用了未知名字 `{root}`({}作用域只允许{})", + claim.id, + if conclusion_scope { "结论" } else { "前提" }, + if conclusion_scope { + "形参、结果、轨迹" + } else { + "形参" + } + ), + suggestion + .map(|s| format!("是不是想写 `{s}`?")) + .unwrap_or_else(|| { + if conclusion_scope { + "只引用形参与 `结果`/`轨迹`".into() + } else { + "前提里只引用形参(入口状态求值)".into() + } + }), + ); + d = d.with_severity(Severity::Error); + out.push(d); + } + } + ClaimAst::Call { name, args } => { + match PREDICATES.iter().find(|(n, _)| n == name) { + Some((_, arity)) if *arity == args.len() => {} + Some((_, arity)) => out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unsupported", + format!( + "谓词 `{name}` 需要 {arity} 个参数,定理 `{}` 给了 {} 个", + claim.id, + args.len() + ), + "谓词集合封闭:包含(轨迹,x) / 长度(轨迹) / 下标(轨迹,i)".into(), + )), + None => out.push(proof_diag( + module, + path, + Span::new(claim.line, 1), + "proof.claim_unsupported", + format!( + "定理 `{}` 调用了 `{name}`——定理里只能用包含/长度/下标三个谓词", + claim.id + ), + "谓词集合封闭(§7.3.5);要扩集合先改 ADR 0010".into(), + )), + } + for arg in args { + collect_symbols(module, path, claim, arg, params, conclusion_scope, out); + } + } + ClaimAst::Bin { left, right, .. } => { + collect_symbols(module, path, claim, left, params, conclusion_scope, out); + collect_symbols(module, path, claim, right, params, conclusion_scope, out); + } + ClaimAst::Un { expr, .. } => { + collect_symbols(module, path, claim, expr, params, conclusion_scope, out); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_ok(text: &str) -> ClaimAst { + let toks = tokenize_claim(text).expect("tokenize"); + parse_claim_expr(&toks).expect("parse").1 + } + + #[test] + fn restricted_grammar_parses_design_examples() { + // 设计 §7.1 的示例句全部可解析。 + let _ = parse_ok("包含(轨迹, \"人工审核\")"); + let _ = parse_ok("金额 > 10000"); + let _ = parse_ok("结果.ok = True"); + let _ = parse_ok("长度(轨迹) = 2"); + let _ = parse_ok("下标(轨迹, 0) = \"x\""); + let _ = parse_ok("非 结果.ok = False 且 金额 ≥ 0"); + let _ = parse_ok("金额 + 1 ≤ 10 或 假"); + } + + #[test] + fn tokenizer_rejects_unterminated_strings() { + assert!(tokenize_claim("包含(轨迹, \"未闭合").is_err()); + } + + #[test] + fn reserved_outputs_render_without_field_access_prefix() { + // emit 侧翻译:结果/轨迹 是定理作用域绑定名,不加 v_ 前缀。 + let ast = parse_ok("轨迹"); + assert!(matches!(ast, ClaimAst::Var(ref n) if n == "轨迹")); + let ast = parse_ok("结果.ok"); + assert!(matches!(ast, ClaimAst::Var(ref n) if n == "结果.ok")); + } + + #[test] + fn symbol_check_reports_unknown_and_suggests() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "引用未知".into(), + conclusion: "额度 > 0".into(), + premise: None, + tactic: Some("auto".into()), + line: 3, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "额度 > 0", + &claim, + &["金额".to_string()], + true, + &mut out, + ); + assert_eq!(out.len(), 1); + assert_eq!(out[0].code, "proof.claim_unknown_symbol"); + // 最近建议(编辑距离):额度 → 金额 不够近,无建议也要有消息。 + assert!(out[0].message.contains("额度")); + } + + #[test] + fn symbol_check_accepts_params_in_premise_and_outputs_in_conclusion() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "合法".into(), + conclusion: "结果.ok = True".into(), + premise: Some("金额 > 0".into()), + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "金额 > 0", + &claim, + &["金额".to_string()], + false, + &mut out, + ); + check_claim_expr( + &module, + None, + "结果.ok = True", + &claim, + &["金额".to_string()], + true, + &mut out, + ); + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn premise_may_not_reference_outputs() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "前提越界".into(), + conclusion: "结果.ok = True".into(), + premise: Some("轨迹 = 0".into()), + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "轨迹 = 0", + &claim, + &[], + false, + &mut out, + ); + assert!(out + .iter() + .any(|d| d.code == "proof.claim_unknown_symbol"), "{out:?}"); + } + + #[test] + fn predicate_arity_and_closure_are_enforced() { + let module = Module::default(); + let claim = crate::ast::Claim { + id: "元数错".into(), + conclusion: "包含(轨迹, \"a\", \"b\")".into(), + premise: None, + tactic: None, + line: 1, + }; + let mut out = Vec::new(); + check_claim_expr( + &module, + None, + "包含(轨迹, \"a\", \"b\")", + &claim, + &[], + true, + &mut out, + ); + assert!(out.iter().any(|d| d.code == "proof.claim_unsupported"), "{out:?}"); + + let claim2 = crate::ast::Claim { + id: "越界谓词".into(), + conclusion: "求和(金额, 1) > 0".into(), + premise: None, + tactic: None, + line: 2, + }; + let mut out2 = Vec::new(); + check_claim_expr( + &module, + None, + "求和(金额, 1) > 0", + &claim2, + &["金额".to_string()], + true, + &mut out2, + ); + assert!(out2.iter().any(|d| d.code == "proof.claim_unsupported"), "{out2:?}"); + } +} diff --git a/src/prove/types.rs b/src/prove/types.rs new file mode 100755 index 0000000..0b4b43b --- /dev/null +++ b/src/prove/types.rs @@ -0,0 +1,251 @@ +//! 定型(`doc/design/prove-cli.md` §4.1 ③):契约表驱动的轻量推断。 +//! +//! P0 范围:参数/返回类型来自契约表;字面量赋值给最具体类型;分支合流时 +//! 同名变量类型不相容报 `proof.type_mismatch`(带两处行号)。其余一律 +//! `Any`(`--no-strict-types` 语义下的诚实回退,不做猜测)。 + +use std::collections::BTreeMap; + +use crate::diagnostics::{Diagnostic, Severity, Span}; +use crate::prove::ir::{PlanTy, PureExpr, Step}; + +/// 单函数类型检查产物。 +#[derive(Debug, Default)] +pub struct Typed { + pub diagnostics: Vec, +} + +/// 对一个函数的 steps 做类型检查。 +/// +/// `params`:形参类型(契约表)。返回收集到的诊断。 +pub fn typecheck( + module: &crate::ast::Module, + params: &[(String, PlanTy)], + steps: &[Step], + strict: bool, +) -> Typed { + let mut env: BTreeMap = params + .iter() + .map(|(name, ty)| (name.clone(), (ty.clone(), 0))) + .collect(); + let mut diagnostics = Vec::new(); + check_steps(module, steps, &mut env, &mut diagnostics, strict); + Typed { diagnostics } +} + +fn check_steps( + module: &crate::ast::Module, + steps: &[Step], + env: &mut BTreeMap, + out: &mut Vec, + strict: bool, +) { + for step in steps { + match step { + Step::Bind { var, expr, line } => { + let ty = expr_type(expr, env); + match ty { + Some(new_ty) => { + if let Some((old_ty, old_line)) = env.get(var) { + let merged = conflate(old_ty, &new_ty); + if merged.is_none() { + out.push(mismatch( + module, + Span::new(*line, 1), + *old_line, + var, + old_ty, + &new_ty, + )); + } + let merged = merged.unwrap_or(PlanTy::Any); + if strict && merged == PlanTy::Any && new_ty != PlanTy::Any { + // 严格模式下落 Any 的合流仍允许,但记录在案。 + } + env.insert(var.clone(), (merged, *line)); + } else { + env.insert(var.clone(), (new_ty, *line)); + } + } + None => { + // 未知类型:保留旧类型(若有),否则 Any。 + env.entry(var.clone()).or_insert((PlanTy::Any, *line)); + } + } + } + Step::Return { expr, .. } => { + let _ = expr_type(expr, env); + } + Step::If { + then, + otherwise, + line, + .. + } => { + // 分支合流:两臂各自检查后合并同名变量类型。 + let mut then_env = env.clone(); + let mut else_env = env.clone(); + check_steps(module, then, &mut then_env, out, strict); + check_steps(module, otherwise, &mut else_env, out, strict); + let then_vars: Vec<(String, (PlanTy, u32))> = + then_env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); + for (name, (then_ty, then_line)) in then_vars { + if name.starts_with("实参") { + continue; + } + match else_env.get(&name) { + Some((else_ty, else_line)) => { + match conflate(&then_ty, else_ty) { + Some(merged) => { + env.insert(name, (merged, *line)); + } + None => { + out.push(mismatch( + module, + Span::new(then_line.max(1), 1), + *else_line, + &name, + &then_ty, + else_ty, + )); + env.insert(name, (PlanTy::Any, *line)); + } + } + } + None => { + env.insert(name, (then_ty, then_line)); + } + } + } + // 只在 else 出现的变量也进入合流后的环境。 + for (name, (else_ty, _)) in &else_env { + then_env.entry(name.clone()).or_insert((else_ty.clone(), 0)); + } + } + Step::Trace { .. } => {} + } + } +} + +/// 纯表达式的保守类型:只认字面量/构造器/列表/映射/len/access/插值。 +fn expr_type(expr: &crate::prove::ir::Expr, env: &BTreeMap) -> Option { + match expr { + crate::prove::ir::Expr::Pure(pure) => pure_type(pure, env), + crate::prove::ir::Expr::Op { .. } => None, + crate::prove::ir::Expr::Formula | crate::prove::ir::Expr::Code => None, + } +} + +fn pure_type(pure: &PureExpr, env: &BTreeMap) -> Option { + match pure { + PureExpr::Int(_) => Some(PlanTy::Int), + PureExpr::Num(_) => Some(PlanTy::Num), + PureExpr::Bool(_) => Some(PlanTy::Bool), + PureExpr::Text(_) => Some(PlanTy::Text), + PureExpr::None => Some(PlanTy::Any), + PureExpr::Var(name) => env.get(name).map(|(ty, _)| ty.clone()), + PureExpr::Bin { operator: op, left, right } => { + use crate::prove::ir::BinOp as B; + let lt = pure_type(left, env); + let rt = pure_type(right, env); + match op { + B::Add | B::Sub | B::Mul | B::Div => { + let lt = lt?; + let rt = rt?; + match (<, &rt) { + (PlanTy::Text, _) | (_, PlanTy::Text) => Some(PlanTy::Text), + (PlanTy::Num, _) | (_, PlanTy::Num) => Some(PlanTy::Num), + (PlanTy::Int, PlanTy::Int) => Some(PlanTy::Int), + _ => None, + } + } + B::Eq | B::Ne | B::Lt | B::Le | B::Gt | B::Ge | B::And | B::Or => Some(PlanTy::Bool), + } + } + PureExpr::Un { operator: op, expr } => match op { + crate::prove::ir::UnOp::Not => Some(PlanTy::Bool), + crate::prove::ir::UnOp::Neg => pure_type(expr, env), + }, + PureExpr::Index { base, .. } => match pure_type(base, env)? { + PlanTy::Map => Some(PlanTy::Any), + PlanTy::List => Some(PlanTy::Any), + PlanTy::Result => Some(PlanTy::Any), + _ => Some(PlanTy::Any), + }, + PureExpr::Access { base, .. } => match pure_type(base, env)? { + PlanTy::Result => Some(PlanTy::Any), + _ => Some(PlanTy::Any), + }, + PureExpr::Len(_) => Some(PlanTy::Int), + PureExpr::Interp(_) => Some(PlanTy::Text), + PureExpr::List(_) => Some(PlanTy::List), + PureExpr::Map(_) => Some(PlanTy::Map), + PureExpr::Ctor { name, .. } => { + if name.starts_with("result.") { + Some(PlanTy::Result) + } else { + None + } + } + } +} + +/// 类型合流:相同 → 相同;Int+Num → Num;含 Any → Any;否则 None(冲突)。 +fn conflate(a: &PlanTy, b: &PlanTy) -> Option { + use PlanTy as T; + if a == b { + return Some(a.clone()); + } + match (a, b) { + (T::Any, other) | (other, T::Any) => Some(other.clone()), + (T::Int, T::Num) | (T::Num, T::Int) => Some(T::Num), + _ => None, + } +} + +fn mismatch( + module: &crate::ast::Module, + span: Span, + other_line: u32, + var: &str, + old: &PlanTy, + new: &PlanTy, +) -> Diagnostic { + Diagnostic::new( + module.source.path.as_deref(), + span, + format!( + "`{var}` 在分支合流处类型不相容:{a} vs {b}", + a = old.name(), + b = new.name() + ), + ) + .with_source(&module.source) + .with_code("proof.type_mismatch") + .with_severity(Severity::Error) + .with_suggestion(format!( + "另一处绑定在第 {other_line} 行;统一两臂的类型或改用 --no-strict-types" + )) +} + +/// 把类型检查接到降级产物上(mod.rs 调用)。 +pub fn typecheck_plan( + module: &crate::ast::Module, + lowered: &[crate::prove::lower::Lowered], + strict: bool, +) -> Vec { + let mut out = Vec::new(); + for item in lowered { + let Some(plan) = &item.plan else { + continue; + }; + let params: Vec<(String, PlanTy)> = plan + .params + .iter() + .map(|p| (p.name.clone(), p.ty.clone())) + .collect(); + let typed = typecheck(module, ¶ms, &plan.steps, strict); + out.extend(typed.diagnostics); + } + out +} diff --git a/src/repair.rs b/src/repair.rs old mode 100644 new mode 100755 diff --git a/src/runtime/control.rs b/src/runtime/control.rs old mode 100644 new mode 100755 diff --git a/src/runtime/host_api.rs b/src/runtime/host_api.rs old mode 100644 new mode 100755 diff --git a/src/runtime/lease.rs b/src/runtime/lease.rs old mode 100644 new mode 100755 diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs old mode 100644 new mode 100755 diff --git a/src/runtime/protocol.rs b/src/runtime/protocol.rs old mode 100644 new mode 100755 diff --git a/src/runtime/publish.rs b/src/runtime/publish.rs old mode 100644 new mode 100755 diff --git a/src/runtime/scheduler.rs b/src/runtime/scheduler.rs old mode 100644 new mode 100755 diff --git a/src/runtime/supervisor.rs b/src/runtime/supervisor.rs old mode 100644 new mode 100755 diff --git a/src/runtime/task_store.rs b/src/runtime/task_store.rs old mode 100644 new mode 100755 diff --git a/src/runtime/worker.rs b/src/runtime/worker.rs old mode 100644 new mode 100755 diff --git a/src/sema/bind.rs b/src/sema/bind.rs old mode 100644 new mode 100755 diff --git a/src/sema/extract.rs b/src/sema/extract.rs old mode 100644 new mode 100755 diff --git a/src/sema/ir.rs b/src/sema/ir.rs old mode 100644 new mode 100755 diff --git a/src/sema/lock.rs b/src/sema/lock.rs old mode 100644 new mode 100755 diff --git a/src/sema/mod.rs b/src/sema/mod.rs old mode 100644 new mode 100755 diff --git a/src/sema/provenance.rs b/src/sema/provenance.rs old mode 100644 new mode 100755 diff --git a/src/sema/resolution.rs b/src/sema/resolution.rs old mode 100644 new mode 100755 diff --git a/src/sema/symbols.rs b/src/sema/symbols.rs old mode 100644 new mode 100755 diff --git a/src/source_map_tests.rs b/src/source_map_tests.rs old mode 100644 new mode 100755 index 67d52a9..252f634 --- a/src/source_map_tests.rs +++ b/src/source_map_tests.rs @@ -19,8 +19,12 @@ fn line(text: &str, marker: &str) -> u32 { + 1 } fn root(label: &str) -> PathBuf { - let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("target/source-map") + // Scratch belongs to the build target dir; honor CARGO_TARGET_DIR when set. + let base = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = base + .join("source-map") .join(format!("{label}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); dir diff --git a/src/source_refinement_tests.rs b/src/source_refinement_tests.rs old mode 100644 new mode 100755 diff --git a/src/value.rs b/src/value.rs old mode 100644 new mode 100755 diff --git a/src/version_check.rs b/src/version_check.rs old mode 100644 new mode 100755 diff --git a/src/view/annot.rs b/src/view/annot.rs old mode 100644 new mode 100755 diff --git a/src/view/assets/README.md b/src/view/assets/README.md old mode 100644 new mode 100755 diff --git a/src/view/assets/blossom.png b/src/view/assets/blossom.png old mode 100644 new mode 100755 diff --git a/src/view/assets/blossom.uri b/src/view/assets/blossom.uri old mode 100644 new mode 100755 diff --git a/src/view/assets/blossom.webp b/src/view/assets/blossom.webp old mode 100644 new mode 100755 diff --git a/src/view/assets/feather.png b/src/view/assets/feather.png old mode 100644 new mode 100755 diff --git a/src/view/assets/feather.uri b/src/view/assets/feather.uri old mode 100644 new mode 100755 diff --git a/src/view/assets/feather.webp b/src/view/assets/feather.webp old mode 100644 new mode 100755 diff --git a/src/view/assets/logo.svg b/src/view/assets/logo.svg old mode 100644 new mode 100755 diff --git a/src/view/assets/logo.uri b/src/view/assets/logo.uri old mode 100644 new mode 100755 diff --git a/src/view/assets/vendor/KATEX-LICENSE b/src/view/assets/vendor/KATEX-LICENSE old mode 100644 new mode 100755 diff --git a/src/view/assets/vendor/auto-render.min.js b/src/view/assets/vendor/auto-render.min.js old mode 100644 new mode 100755 diff --git a/src/view/assets/vendor/katex.min.css b/src/view/assets/vendor/katex.min.css old mode 100644 new mode 100755 diff --git a/src/view/assets/vendor/katex.min.js b/src/view/assets/vendor/katex.min.js old mode 100644 new mode 100755 diff --git a/src/view/debug_api.rs b/src/view/debug_api.rs old mode 100644 new mode 100755 diff --git a/src/view/debug_page.rs b/src/view/debug_page.rs old mode 100644 new mode 100755 diff --git a/src/view/document.rs b/src/view/document.rs old mode 100644 new mode 100755 diff --git a/src/view/html.rs b/src/view/html.rs old mode 100644 new mode 100755 diff --git a/src/view/knowledge_present.rs b/src/view/knowledge_present.rs old mode 100644 new mode 100755 diff --git a/src/view/knowledge_reading.rs b/src/view/knowledge_reading.rs old mode 100644 new mode 100755 diff --git a/src/view/logic.rs b/src/view/logic.rs old mode 100644 new mode 100755 diff --git a/src/view/mod.rs b/src/view/mod.rs old mode 100644 new mode 100755 diff --git a/src/view/notebook_api.rs b/src/view/notebook_api.rs old mode 100644 new mode 100755 index 11023e1..900eaf5 --- a/src/view/notebook_api.rs +++ b/src/view/notebook_api.rs @@ -609,7 +609,7 @@ mod replay_api_tests { let relative=format!("target/api-replay-seeded-{pid}.mq.md");let path=root.join(&relative); let wrapper=root.join(format!("target/api-replay-wrapper-{pid}.py"));let marker=root.join(format!("target/api-replay-marker-{pid}")); let marker_literal=serde_json::to_string(&marker.display().to_string()).unwrap(); - let script=format!("#!/usr/bin/python3\nimport os,sys\nfrom pathlib import Path\nPath({marker_literal}).write_text('started')\nos.execv(sys.executable,[sys.executable]+sys.argv[1:])\n"); + let script=format!("#!/usr/bin/env python3\nimport os,sys\nfrom pathlib import Path\nPath({marker_literal}).write_text('started')\nos.execv(sys.executable,[sys.executable]+sys.argv[1:])\n"); std::fs::write(&wrapper,script).unwrap();std::fs::set_permissions(&wrapper,std::fs::Permissions::from_mode(0o755)).unwrap(); let command=serde_json::to_string(&wrapper.display().to_string()).unwrap(); let source=format!("---\nimport:\n foreign: lib/foreign.mq.md\n---\n# main\n\n`kernels` =\n| 名称 | 语言 | 命令 |\n|---|---|---|\n| py | python | {command} |\n\n`units` =\n| 单元 | 内核 |\n|---|---|\n| a | py |\n\n`initial` =\n| 内核 | 名称 | 值 |\n|---|---|---|\n| py | n | 1 |\n\n`会话` = > foreign.session kernels=`kernels` cells=`units` values=`initial`\n\n`a` =\n```python\nprint(n)\n```\n"); diff --git a/src/view/notebook_api/interrupt_http_tests.rs b/src/view/notebook_api/interrupt_http_tests.rs old mode 100644 new mode 100755 diff --git a/src/view/output.rs b/src/view/output.rs old mode 100644 new mode 100755 diff --git a/src/view/reader.css b/src/view/reader.css old mode 100644 new mode 100755 diff --git a/src/view/reader.js b/src/view/reader.js old mode 100644 new mode 100755 diff --git a/src/view/render.rs b/src/view/render.rs old mode 100644 new mode 100755 diff --git a/src/wasm_cli.rs b/src/wasm_cli.rs old mode 100644 new mode 100755 diff --git a/src/workbench/analysis_cache.rs b/src/workbench/analysis_cache.rs old mode 100644 new mode 100755 diff --git a/src/workbench/capabilities.rs b/src/workbench/capabilities.rs old mode 100644 new mode 100755 diff --git a/src/workbench/document_view.rs b/src/workbench/document_view.rs old mode 100644 new mode 100755 diff --git a/src/workbench/event_sink.rs b/src/workbench/event_sink.rs old mode 100644 new mode 100755 diff --git a/src/workbench/locator.rs b/src/workbench/locator.rs old mode 100644 new mode 100755 diff --git a/src/workbench/mod.rs b/src/workbench/mod.rs old mode 100644 new mode 100755 diff --git a/src/workbench/resource_view.rs b/src/workbench/resource_view.rs old mode 100644 new mode 100755 diff --git a/src/workbench/run_context.rs b/src/workbench/run_context.rs old mode 100644 new mode 100755 diff --git a/src/workbench/selection.rs b/src/workbench/selection.rs old mode 100644 new mode 100755 diff --git a/src/workbench/snapshot.rs b/src/workbench/snapshot.rs old mode 100644 new mode 100755 diff --git a/src/workbench/usage.rs b/src/workbench/usage.rs old mode 100644 new mode 100755 diff --git a/tests/README.md b/tests/README.md old mode 100644 new mode 100755 diff --git a/tests/applications/CASES.json b/tests/applications/CASES.json old mode 100644 new mode 100755 diff --git a/tests/applications/README.md b/tests/applications/README.md old mode 100644 new mode 100755 diff --git a/tests/applications/concordance/consumer.js b/tests/applications/concordance/consumer.js old mode 100644 new mode 100755 diff --git a/tests/applications/concordance/consumer.py b/tests/applications/concordance/consumer.py old mode 100644 new mode 100755 diff --git a/tests/applications/concordance/producer.js b/tests/applications/concordance/producer.js old mode 100644 new mode 100755 diff --git a/tests/applications/concordance/producer.py b/tests/applications/concordance/producer.py old mode 100644 new mode 100755 diff --git a/tests/applications/data/PROVENANCE.json b/tests/applications/data/PROVENANCE.json old mode 100644 new mode 100755 diff --git a/tests/applications/data/wine-quality.zip b/tests/applications/data/wine-quality.zip old mode 100644 new mode 100755 diff --git a/tests/applications/data/winequality-red.csv b/tests/applications/data/winequality-red.csv old mode 100644 new mode 100755 diff --git a/tests/applications/data/winequality.names b/tests/applications/data/winequality.names old mode 100644 new mode 100755 diff --git a/tests/applications/invoice/consumer.js b/tests/applications/invoice/consumer.js old mode 100644 new mode 100755 diff --git a/tests/applications/invoice/consumer.py b/tests/applications/invoice/consumer.py old mode 100644 new mode 100755 diff --git a/tests/applications/invoice/producer.js b/tests/applications/invoice/producer.js old mode 100644 new mode 100755 diff --git a/tests/applications/invoice/producer.py b/tests/applications/invoice/producer.py old mode 100644 new mode 100755 diff --git a/tests/applications/routes/consumer.js b/tests/applications/routes/consumer.js old mode 100644 new mode 100755 diff --git a/tests/applications/routes/consumer.py b/tests/applications/routes/consumer.py old mode 100644 new mode 100755 diff --git a/tests/applications/routes/producer.js b/tests/applications/routes/producer.js old mode 100644 new mode 100755 diff --git a/tests/applications/routes/producer.py b/tests/applications/routes/producer.py old mode 100644 new mode 100755 diff --git a/tests/applications/wine/consumer.js b/tests/applications/wine/consumer.js old mode 100644 new mode 100755 diff --git a/tests/applications/wine/consumer.py b/tests/applications/wine/consumer.py old mode 100644 new mode 100755 diff --git a/tests/applications/wine/producer.js b/tests/applications/wine/producer.js old mode 100644 new mode 100755 diff --git a/tests/applications/wine/producer.py b/tests/applications/wine/producer.py old mode 100644 new mode 100755 diff --git a/tests/blind/docs-bundle.md b/tests/blind/docs-bundle.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/claims_reserve_settle.md b/tests/blind/tasks/claims_reserve_settle.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/contract_milestone_pay.md b/tests/blind/tasks/contract_milestone_pay.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/qb_gcd.md b/tests/blind/tasks/qb_gcd.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/qb_get_factors.md b/tests/blind/tasks/qb_get_factors.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/qb_max_sublist_sum.md b/tests/blind/tasks/qb_max_sublist_sum.md old mode 100644 new mode 100755 diff --git a/tests/blind/tasks/vendor_po_gate.md b/tests/blind/tasks/vendor_po_gate.md old mode 100644 new mode 100755 diff --git a/tests/blind_experiment.rs b/tests/blind_experiment.rs old mode 100644 new mode 100755 diff --git a/tests/browser_handbook.mjs b/tests/browser_handbook.mjs old mode 100644 new mode 100755 diff --git a/tests/call/ambiguous.mq.md b/tests/call/ambiguous.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/contract.mq.md b/tests/call/contract.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/effects.mq.md b/tests/call/effects.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/import/inc.mq.md b/tests/call/import/inc.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/import/site.mq.md b/tests/call/import/site.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/main-split.mq.md b/tests/call/main-split.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/metadata.mq.md b/tests/call/metadata.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/method.mq.md b/tests/call/method.mq.md old mode 100644 new mode 100755 diff --git a/tests/call/nested.mq.md b/tests/call/nested.mq.md old mode 100644 new mode 100755 diff --git a/tests/call_cli.rs b/tests/call_cli.rs old mode 100644 new mode 100755 diff --git a/tests/call_lib_path_worker.rs b/tests/call_lib_path_worker.rs old mode 100644 new mode 100755 diff --git a/tests/common/mod.rs b/tests/common/mod.rs old mode 100644 new mode 100755 diff --git a/tests/conformance.rs b/tests/conformance.rs new file mode 100755 index 0000000..f909ad6 --- /dev/null +++ b/tests/conformance.rs @@ -0,0 +1,481 @@ +//! T4 差分一致性(roadmap §6 B 组):解释器求值 == Lean 生成语义。 +//! +//! 对每个纯函数语料: +//! 1. 解释器跑 `marqdo run --call-lib-path` 拿到真实返回值; +//! 2. `prove emit` 生成 Lean 定义,追加 `example : … = «期望» := by simp`; +//! 3. 真 Lean 校验通过 ⇒ 生成器的 Val 语义与解释器一致(B1/B3/B4/B5)。 +//! +//! 已记录偏差(不进本测试):除零/模零——解释器为运行时错误,P1 库模型 +//! `mqDiv`/`mqMod` 返回 `.int 0`(MarqdoProof.lean 注释与设计 §12 偏差表)。 +//! 无 Lean 工具链时整组 SKIP(MARQDO_PROOF_REQUIRE_LEAN=1 则失败)。 + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// 语料:模块名 / 函数名 / 参数 JSON / 期望 Val 的 Lean 字面。 +struct Case { + module: &'static str, + function: &'static str, + source: &'static str, + args: &'static str, + /// Lean 期望值(`Val.*` 构造)。 + expected: &'static str, + /// 额外 simp 引理(默认集之外)。 + extra_simp: &'static [&'static str], +} + +const CASES: &[Case] = &[ + Case { + module: "算术", + function: "加倍", + source: r#"--- +markup: occlusion +--- + +## 加倍 ++ `x` + +**y = `x` + `x`** + +*y* +"#, + args: r#"{"x": 21}"#, + expected: "Val.int 42", + extra_simp: &[], + }, + Case { + module: "计算器", + function: "加法", + source: r#"--- +markup: occlusion +--- + +## 加法 ++ `甲` ++ `乙` + +**和 = `甲` + `乙`** + +*和* +"#, + args: r#"{"甲": -5, "乙": 2}"#, + expected: "Val.int (-3)", + extra_simp: &[], + }, + Case { + module: "比较", + function: "判断", + source: r#"--- +markup: occlusion +--- + +## 判断 ++ `x` + +1. `x` > 10 + **结论 = "大"** +2. * + **结论 = "小"** + +*结论* +"#, + args: r#"{"x": 11}"#, + expected: r#"Val.text "大""#, + extra_simp: &[], + }, + Case { + module: "工单", + function: "创建", + source: r#"--- +markup: occlusion +--- + +## 创建 ++ `id` + +**单号 = "T-" + `id`** + +*单号* +"#, + args: r#"{"id": 7}"#, + expected: r#"Val.text "T-7""#, + extra_simp: &[], + }, + Case { + module: "边界", + function: "极限", + source: r#"--- +markup: occlusion +--- + +## 极限 ++ `x` + +**y = `x` + 1** + +*y* +"#, + args: r#"{"x": 9223372036854775806}"#, + expected: "Val.int 9223372036854775807", + extra_simp: &[], + }, +]; + +/// 直接驱动解释器调用 `模块.函数`(run_file_capture 不处理 call_lib_path)。 +fn call_function(file: &Path, lib_path: &str, args_json: &str) -> marqdo::value::Value { + let module = marqdo::load::load_module(file).expect("load module"); + let mut host = marqdo::host::HostContext::for_capture(Some(file), marqdo::host::HostCaps { + fs_write: false, + exec: false, + net: false, + plugin: false, + }); + let mut interp = marqdo::interp::Interpreter::with_capture(Some(file), false).with_host(host); + let args: marqdo::value::Value = serde_json::from_str(args_json) + .map(|v: serde_json::Value| json_to_value(&v)) + .expect("args json"); + interp + .run_site_lib_path(&module, lib_path, Some(&args)) + .expect("interpreter call") +} + +/// JSON → Value(T4 语料只用到 int/text/bool/map)。 +fn json_to_value(v: &serde_json::Value) -> marqdo::value::Value { + use marqdo::value::Value; + match v { + serde_json::Value::Number(n) => { + if let Some(i) = n.as_i64() { + Value::Int(i) + } else { + Value::Num(n.as_f64().unwrap_or(0.0)) + } + } + serde_json::Value::String(s) => Value::Text(s.clone()), + serde_json::Value::Bool(b) => Value::Bool(*b), + serde_json::Value::Object(m) => Value::Map( + m.iter() + .map(|(k, v)| (k.clone(), json_to_value(v))) + .collect(), + ), + _ => Value::None, + } +} + +fn lean_binary() -> Option { + if let Ok(p) = std::env::var("MARQDO_PROOF_LEAN") { + let p = PathBuf::from(p); + if p.exists() { + return Some(p); + } + } + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path).map(|d| d.join("lean")).find(|p| p.is_file()) +} + +fn require_lean_enforced() -> bool { + std::env::var("MARQDO_PROOF_REQUIRE_LEAN").is_ok_and(|v| v == "1") +} + +fn target_dir() -> PathBuf { + std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")) +} + +/// 源文件中的函数体生成的 Lean 定义名(与 emit 一致)。 +fn def_name(_module: &str, function: &str) -> String { + format!("«{function}»") +} + +#[test] +fn t4_interpreter_matches_lean_semantics() { + let Some(lean) = lean_binary() else { + if require_lean_enforced() { + panic!("MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链"); + } + println!("SKIP conformance(无 Lean 工具链)"); + return; + }; + let root = target_dir().join("conformance"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).expect("scratch"); + + let toolchain = marqdo::prove::driver::Toolchain::discover(Some(&lean)) + .expect("toolchain discover") + .expect("lean present"); + let (library_dir, _sha) = marqdo::prove::driver::ensure_library(&root, &toolchain) + .expect("build library"); + let mut lean_env = std::env::split_paths(&std::env::var_os("LEAN_PATH").unwrap_or_default()) + .collect::>(); + lean_env.push(library_dir); + + let mut failures: Vec = Vec::new(); + for case in CASES { + let dir = root.join(case.module); + std::fs::create_dir_all(&dir).expect("case dir"); + let lib_file = dir.join(format!("{}.mq.md", case.module)); + std::fs::write(&lib_file, case.source).expect("write source"); + // 主文件只做导入:解释器经 import bind 调库函数。 + let main_file = dir.join("主.mq.md"); + std::fs::write( + &main_file, + format!( + "---\nmarkup: occlusion\nimport:\n {}: {}.mq.md\n---\n\n# 主\n", + case.module, case.module + ), + ) + .expect("write main"); + let file = main_file; + let args_file = dir.join("args.json"); + std::fs::write(&args_file, case.args).expect("write args"); + + // ① 解释器求值。 + let lib_path = format!("{}.{}", case.module, case.function); + let value = match std::panic::catch_unwind(|| { + call_function(&file, &lib_path, case.args) + }) { + Ok(v) => v, + Err(_) => { + failures.push(format!("{}: 解释器调用失败", case.function)); + continue; + } + }; + + // ② 生成 Lean 定义。 + let emit_dir = dir.join("out"); + let prove_opts = marqdo::prove::ProveOptions { + emit_dir: Some(emit_dir.clone()), + judge: false, + report_only: false, + ..Default::default() + }; + if let Err(e) = marqdo::prove::prove_path(&lib_file, &prove_opts) { + failures.push(format!("{}: 生成失败:{e}", case.function)); + continue; + } + // 文件名与 emit 一致:非 ASCII 字符确定性编码为 uXXXX。 + let stem: String = case + .module + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' { + c.to_string() + } else if !c.is_ascii() { + format!("u{:04X}", c as u32) + } else { + "_".to_string() + } + }) + .collect(); + let generated = emit_dir.join("Generated").join(format!("{stem}_mq.lean")); + let module_src = std::fs::read_to_string(&generated).expect("generated module"); + + let simp_set = { + let mut base = "mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqAdd, mqSub, mqMul, mqEq".to_string(); + for e in case.extra_simp { + base.push_str(", "); + base.push_str(e); + } + base + }; + // 实参按生成定义的形参顺序(扫描 def 签名的顶层括号组)。 + let def_line = module_src + .lines() + .find(|l| { + l.starts_with(&format!("def {} ", def_name(case.module, case.function))) + && l.contains('(') + }) + .unwrap_or(""); + let mut params: Vec = Vec::new(); + let mut depth = 0usize; + let mut cur = String::new(); + for ch in def_line.chars() { + match ch { + '(' => { + depth += 1; + cur.clear(); + } + ')' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let inner = cur.trim(); + let name = inner.split(':').next().unwrap_or("").trim(); + let bare = name + .strip_prefix("«") + .and_then(|s| s.strip_suffix("»")) + .unwrap_or(name); + if bare != "env" && bare != "轨迹" && !bare.is_empty() { + params.push(bare.to_string()); + } + } + cur.clear(); + } + _ => { + if depth > 0 { + cur.push(ch); + } + } + } + } + let args_map: serde_json::Map = + serde_json::from_str(case.args).expect("args object"); + let arg_terms = params + .iter() + .map(|name| { + let v = args_map.get(name).cloned().unwrap_or(serde_json::Value::Null); + match v.as_i64() { + Some(i) if i < 0 => format!("(Val.int ({i}))"), + Some(i) => format!("(Val.int {i})"), + None => match v.as_str() { + Some(s) => format!("(Val.text \"{s}\")"), + None => "(Val.none)".to_string(), + }, + } + }) + .collect::>() + .join(" "); + // ③ 期望 = 语料声明的 Lean 字面(与解释器求值在 ① 已对照)。 + let expected = case.expected.to_string(); + let mut conformance = module_src.clone(); + let example = format!( + "\n-- T4:解释器期望值({} 返回 {:?})\nexample : ({} env [] {arg_terms}).1 = {expected} := by\n simp [{}, {}]\n try rfl\n", + case.function, + value, + def_name(case.module, case.function), + def_name(case.module, case.function), + simp_set, + ); + if let Some(pos) = conformance.rfind("\nend Generated") { + conformance.insert_str(pos, &example); + } else { + conformance.push_str(&example); + } + let conformance_file = dir.join("Conformance.lean"); + std::fs::write(&conformance_file, &conformance).expect("write conformance"); + + // ④ Lean 校验。 + let out = Command::new(&lean) + .current_dir(&dir) + .env( + "LEAN_PATH", + std::env::join_paths(&lean_env).expect("lean path"), + ) + .arg(conformance_file.strip_prefix(&dir).unwrap_or(&conformance_file)) + .output() + .expect("run lean"); + if !out.status.success() { + failures.push(format!( + "{}: Lean 不接受解释器期望值({:?}):\n-- stderr:\n{}\n-- stdout:\n{}", + case.function, + value, + String::from_utf8_lossy(&out.stderr), + String::from_utf8_lossy(&out.stdout) + )); + } + } + assert!( + failures.is_empty(), + "T4 差分不一致 {} 项:\n{}", + failures.len(), + failures.join("\n----------------------------------------\n") + ); + println!("conformance: {} 例全部一致(解释器 == Lean)", CASES.len()); +} + +/// B4 补充:结果结构(result.ok)字段读取与解释器一致。 +#[test] +fn t4_result_struct_field_access() { + let Some(lean) = lean_binary() else { + if require_lean_enforced() { + panic!("MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链"); + } + println!("SKIP conformance(无 Lean 工具链)"); + return; + }; + let root = target_dir().join("conformance-result"); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).expect("scratch"); + + let source = r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +## 登记 ++ `金额` + +**回执 = [登记](result.ok(value=`金额`))** + +*access(回执, "value")* +"#; + let dir = &root; + let lib_file = dir.join("台.mq.md"); + std::fs::write(&lib_file, source).expect("write"); + let file = dir.join("主.mq.md"); + std::fs::write( + &file, + "---\nmarkup: occlusion\nimport:\n 台: 台.mq.md\n---\n\n# 主\n", + ) + .expect("write main"); + std::fs::create_dir_all(dir.join("lib")).expect("lib"); + std::fs::write( + dir.join("lib/result.mq.md"), + std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("lib/result.mq.md")) + .expect("repo result lib"), + ) + .expect("write result lib"); + let args_file = dir.join("args.json"); + std::fs::write(&args_file, r#"{"金额": 5}"#).expect("args"); + + let value = call_function(&file, "台.登记", r#"{"金额": 5}"#); + // access(回执, "value") 应取回 5(ok/value 字段结构在 Lean 侧由 + // mqAccess (mqResultOk …) 方程锁定,两侧一致即 B4)。 + assert!( + matches!(&value, marqdo::value::Value::Int(5)), + "access(result.ok(5), \"value\") 应为 Int(5),实际 {value:?}" + ); + + // Lean 侧同一表达式:mqResultOk 5 的 value 字段 == 5。 + let prove_opts = marqdo::prove::ProveOptions { + emit_dir: Some(dir.join("out")), + judge: false, + report_only: false, + ..Default::default() + }; + marqdo::prove::prove_path(&lib_file, &prove_opts).expect("emit"); + let generated = dir.join("out/Generated/u53F0_mq.lean"); // 台 → u53F0 + let module_src = std::fs::read_to_string(&generated).expect("generated"); + let mut conformance = module_src; + conformance.push_str( + "\n-- T4 B4:结构字段与解释器一致\nexample : (mqResultOk (Val.int 5)).2.1 ≡ Val.int 5 := rfl\n", + ); + // mqResultOk 的 map 字段顺序依赖库实现,直接用 mqAccess 更稳: + let conformance = conformance.replace( + "example : (mqResultOk (Val.int 5)).2.1 ≡ Val.int 5 := rfl\n", + "example : mqAccess (mqResultOk (Val.int 5)) \"value\" = Val.int 5 := by\n simp [mqResultOk, mqAccess]\n", + ); + let conformance_file = dir.join("Conformance.lean"); + std::fs::write(&conformance_file, &conformance).expect("write"); + + let toolchain = marqdo::prove::driver::Toolchain::discover(Some(&lean)) + .expect("discover") + .expect("lean"); + let (library_dir, _) = + marqdo::prove::driver::ensure_library(&root, &toolchain).expect("library"); + let mut lean_env = vec![library_dir]; + if let Some(p) = std::env::var_os("LEAN_PATH") { + lean_env.extend(std::env::split_paths(&p)); + } + let out = Command::new(&lean) + .current_dir(dir) + .env("LEAN_PATH", std::env::join_paths(&lean_env).expect("paths")) + .arg("Conformance.lean") + .output() + .expect("run lean"); + assert!( + out.status.success(), + "B4 结构字段不一致:\n{}", + String::from_utf8_lossy(&out.stderr) + ); +} diff --git a/tests/contract_ablation.rs b/tests/contract_ablation.rs old mode 100644 new mode 100755 diff --git a/tests/contracts.rs b/tests/contracts.rs old mode 100644 new mode 100755 diff --git a/tests/contracts/arg_mismatch.mq.md b/tests/contracts/arg_mismatch.mq.md old mode 100644 new mode 100755 diff --git a/tests/contracts/bound_data_table.mq.md b/tests/contracts/bound_data_table.mq.md old mode 100644 new mode 100755 diff --git a/tests/contracts/field_mismatch.mq.md b/tests/contracts/field_mismatch.mq.md old mode 100644 new mode 100755 diff --git a/tests/contracts/ok_contract.mq.md b/tests/contracts/ok_contract.mq.md old mode 100644 new mode 100755 diff --git a/tests/contracts/return_mismatch.mq.md b/tests/contracts/return_mismatch.mq.md old mode 100644 new mode 100755 diff --git a/tests/contracts/unknown_key.mq.md b/tests/contracts/unknown_key.mq.md old mode 100644 new mode 100755 diff --git a/tests/core_surface.rs b/tests/core_surface.rs old mode 100644 new mode 100755 diff --git a/tests/diagnostic_json.rs b/tests/diagnostic_json.rs old mode 100644 new mode 100755 diff --git a/tests/document_data.rs b/tests/document_data.rs old mode 100644 new mode 100755 diff --git a/tests/drift_drill.rs b/tests/drift_drill.rs old mode 100644 new mode 100755 diff --git a/tests/engineering/adr-022-cache.md b/tests/engineering/adr-022-cache.md old mode 100644 new mode 100755 diff --git a/tests/engineering/ap-001-jwt.md b/tests/engineering/ap-001-jwt.md old mode 100644 new mode 100755 diff --git a/tests/engineering/c-014-config.md b/tests/engineering/c-014-config.md old mode 100644 new mode 100755 diff --git a/tests/engineering/config_resolve.mq.md b/tests/engineering/config_resolve.mq.md old mode 100644 new mode 100755 diff --git a/tests/engineering/f-019-auth-cache.md b/tests/engineering/f-019-auth-cache.md old mode 100644 new mode 100755 diff --git a/tests/engineering/normalize_settings.mq.md b/tests/engineering/normalize_settings.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/.gitkeep b/tests/errors/.gitkeep old mode 100644 new mode 100755 diff --git a/tests/errors/bad-arity.mq.md b/tests/errors/bad-arity.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/bad-int.mq.md b/tests/errors/bad-int.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/bad-split-sep.mq.md b/tests/errors/bad-split-sep.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/div-zero.mq.md b/tests/errors/div-zero.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/footnote-missing-key.mq.md b/tests/errors/footnote-missing-key.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/footnote-oob.mq.md b/tests/errors/footnote-oob.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/footnote-zero.mq.md b/tests/errors/footnote-zero.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/inherit-bad-rhs.mq.md b/tests/errors/inherit-bad-rhs.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/inherit-cycle.mq.md b/tests/errors/inherit-cycle.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/inherit-unknown-base.mq.md b/tests/errors/inherit-unknown-base.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/legacy-gt-import.mq.md b/tests/errors/legacy-gt-import.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/legacy-oneliner-import.mq.md b/tests/errors/legacy-oneliner-import.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/lexical-private-descendant.mq.md b/tests/errors/lexical-private-descendant.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/lone-asterisk.mq.md b/tests/errors/lone-asterisk.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/ns-instance-method.mq.md b/tests/errors/ns-instance-method.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/syntax-bad-line.mq.md b/tests/errors/syntax-bad-line.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/table-arity.mq.md b/tests/errors/table-arity.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/table-dup-header.mq.md b/tests/errors/table-dup-header.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/table-row-marker-only.mq.md b/tests/errors/table-row-marker-only.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/undefined-var.mq.md b/tests/errors/undefined-var.mq.md old mode 100644 new mode 100755 diff --git a/tests/errors/unknown-fn.mq.md b/tests/errors/unknown-fn.mq.md old mode 100644 new mode 100755 diff --git a/tests/example_databases.rs b/tests/example_databases.rs old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge.rs b/tests/executable_knowledge.rs old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/README.md b/tests/executable_knowledge/README.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/01-inline/main.mq.md b/tests/executable_knowledge/baseline/01-inline/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/02-extract/main.mq.md b/tests/executable_knowledge/baseline/02-extract/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/03-import/main.mq.md b/tests/executable_knowledge/baseline/03-import/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/03-import/pricing.mq.md b/tests/executable_knowledge/baseline/03-import/pricing.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/04-access-loop/main.mq.md b/tests/executable_knowledge/baseline/04-access-loop/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/05-policy-draft/main.mq.md b/tests/executable_knowledge/baseline/05-policy-draft/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/06-reject/a.mq.md b/tests/executable_knowledge/baseline/06-reject/a.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md b/tests/executable_knowledge/baseline/06-reject/ambiguous.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/06-reject/b.mq.md b/tests/executable_knowledge/baseline/06-reject/b.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/06-reject/missing-import.mq.md b/tests/executable_knowledge/baseline/06-reject/missing-import.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/07-step-kinds/main.mq.md b/tests/executable_knowledge/baseline/07-step-kinds/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/08-same-name/a.mq.md b/tests/executable_knowledge/baseline/08-same-name/a.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/08-same-name/b.mq.md b/tests/executable_knowledge/baseline/08-same-name/b.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/08-same-name/main.mq.md b/tests/executable_knowledge/baseline/08-same-name/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/09-effects/main.mq.md b/tests/executable_knowledge/baseline/09-effects/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/10-boundcall/main.mq.md b/tests/executable_knowledge/baseline/10-boundcall/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/10-boundcall/pricing.mq.md b/tests/executable_knowledge/baseline/10-boundcall/pricing.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/11-narrative-ref/main.mq.md b/tests/executable_knowledge/baseline/11-narrative-ref/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/12-tax-source/corpus.md b/tests/executable_knowledge/baseline/12-tax-source/corpus.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/12-tax-source/main.mq.md b/tests/executable_knowledge/baseline/12-tax-source/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/12b-tax-expired/corpus.md b/tests/executable_knowledge/baseline/12b-tax-expired/corpus.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/12b-tax-expired/main.mq.md b/tests/executable_knowledge/baseline/12b-tax-expired/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/13-bookstore/corpus.md b/tests/executable_knowledge/baseline/13-bookstore/corpus.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/13-bookstore/main.mq.md b/tests/executable_knowledge/baseline/13-bookstore/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/executable_knowledge/baseline/13-bookstore/tax.mq.md b/tests/executable_knowledge/baseline/13-bookstore/tax.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-constitution-b0.mq.md b/tests/ext/agent-constitution-b0.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-context-budget-a3.mq.md b/tests/ext/agent-context-budget-a3.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-dump-context.mq.md b/tests/ext/agent-dump-context.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-effects-run-tool.mq.md b/tests/ext/agent-effects-run-tool.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-eng-bind-gate.mq.md b/tests/ext/agent-eng-bind-gate.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-inspect-fixture.mq.md b/tests/ext/agent-inspect-fixture.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-kb-alias.mq.md b/tests/ext/agent-kb-alias.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-kb-near.mq.md b/tests/ext/agent-kb-near.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-kb-plan-hit.mq.md b/tests/ext/agent-kb-plan-hit.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-kb-reuse.mq.md b/tests/ext/agent-kb-reuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-lib-call.mq.md b/tests/ext/agent-lib-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-llm-transport-soft.mq.md b/tests/ext/agent-llm-transport-soft.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-mcp-client.mq.md b/tests/ext/agent-mcp-client.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-mcp-server-helpers.mq.md b/tests/ext/agent-mcp-server-helpers.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-mcp-server-smoke.mq.md b/tests/ext/agent-mcp-server-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-p4-route.mq.md b/tests/ext/agent-p4-route.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-confirm.mq.md b/tests/ext/agent-plan-confirm.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-decision.mq.md b/tests/ext/agent-plan-decision.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-live.mq.md b/tests/ext/agent-plan-live.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-observe.mq.md b/tests/ext/agent-plan-observe.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-preserve.mq.md b/tests/ext/agent-plan-preserve.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-plan-stream-offline.mq.md b/tests/ext/agent-plan-stream-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-resume.mq.md b/tests/ext/agent-resume.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-run-cold-efi.mq.md b/tests/ext/agent-run-cold-efi.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-run-live.mq.md b/tests/ext/agent-run-live.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-sandbox-optin.mq.md b/tests/ext/agent-sandbox-optin.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-sandbox-promote.mq.md b/tests/ext/agent-sandbox-promote.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-sandbox-quarantine.mq.md b/tests/ext/agent-sandbox-quarantine.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-small-llm-route.mq.md b/tests/ext/agent-small-llm-route.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-smoke.mq.md b/tests/ext/agent-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-soft-match.mq.md b/tests/ext/agent-soft-match.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-step-route.mq.md b/tests/ext/agent-step-route.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-tools-rag-a4.mq.md b/tests/ext/agent-tools-rag-a4.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-v2-learn.mq.md b/tests/ext/agent-v2-learn.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-workbook-patch-a0.mq.md b/tests/ext/agent-workbook-patch-a0.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-writeback-shadow.mq.md b/tests/ext/agent-writeback-shadow.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/agent-zero-llm.mq.md b/tests/ext/agent-zero-llm.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/eng-preflight.mq.md b/tests/ext/eng-preflight.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/fixtures/preserve-skill.mq.md b/tests/ext/fixtures/preserve-skill.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/fixtures/prompt-marqdo.md b/tests/ext/fixtures/prompt-marqdo.md old mode 100644 new mode 100755 diff --git a/tests/ext/fixtures/prompt-pong.mq.md b/tests/ext/fixtures/prompt-pong.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/fs-text-patch.mq.md b/tests/ext/fs-text-patch.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/isolated-execute-site/serve.mq.md b/tests/ext/isolated-execute-site/serve.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/isolated-execute-site/site.mq.md b/tests/ext/isolated-execute-site/site.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-basic-smoke.mq.md b/tests/ext/linalg-basic-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-block-kron.mq.md b/tests/ext/linalg-block-kron.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-doc-smoke.mq.md b/tests/ext/linalg-doc-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-factor-smoke.mq.md b/tests/ext/linalg-factor-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-formula-smoke.mq.md b/tests/ext/linalg-formula-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-infix-smoke.mq.md b/tests/ext/linalg-infix-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-metrics-smoke.mq.md b/tests/ext/linalg-metrics-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/linalg-zh-smoke.mq.md b/tests/ext/linalg-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-ask-offline.mq.md b/tests/ext/llm-ask-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-complete.mq.md b/tests/ext/llm-complete.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-ctor-offline.mq.md b/tests/ext/llm-ctor-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-entry-prompt-offline.mq.md b/tests/ext/llm-entry-prompt-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-import.mq.md b/tests/ext/llm-import.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-meta-offline.mq.md b/tests/ext/llm-meta-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-named-offline.mq.md b/tests/ext/llm-named-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-stream-live.mq.md b/tests/ext/llm-stream-live.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-stream-offline.mq.md b/tests/ext/llm-stream-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/llm-tool-calls-offline.mq.md b/tests/ext/llm-tool-calls-offline.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-amp-damp-smoke.mq.md b/tests/ext/quantum-amp-damp-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-amp-damp-zh-smoke.mq.md b/tests/ext/quantum-amp-damp-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-author-api-smoke.mq.md b/tests/ext/quantum-author-api-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-author-api-zh-smoke.mq.md b/tests/ext/quantum-author-api-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-bell-smoke.mq.md b/tests/ext/quantum-bell-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-custom-gate-smoke.mq.md b/tests/ext/quantum-custom-gate-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-custom-gate-zh-smoke.mq.md b/tests/ext/quantum-custom-gate-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-draw-smoke.mq.md b/tests/ext/quantum-draw-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-gate-heatmap-smoke.mq.md b/tests/ext/quantum-gate-heatmap-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-gate-matrix-smoke.mq.md b/tests/ext/quantum-gate-matrix-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-gates-smoke.mq.md b/tests/ext/quantum-gates-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-linalg-smoke.mq.md b/tests/ext/quantum-linalg-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-noise-smoke.mq.md b/tests/ext/quantum-noise-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-noise-zh-smoke.mq.md b/tests/ext/quantum-noise-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-steps-smoke.mq.md b/tests/ext/quantum-steps-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-viz-advanced-smoke.mq.md b/tests/ext/quantum-viz-advanced-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/quantum-zh-smoke.mq.md b/tests/ext/quantum-zh-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-cow.mq.md b/tests/ext/sandbox-cow.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-deny.mq.md b/tests/ext/sandbox-deny.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-fixtures/guest-json.mq.md b/tests/ext/sandbox-fixtures/guest-json.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-fixtures/guest-plugin.mq.md b/tests/ext/sandbox-fixtures/guest-plugin.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-fixtures/promote-bad.mq.md b/tests/ext/sandbox-fixtures/promote-bad.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-fixtures/promote-good.mq.md b/tests/ext/sandbox-fixtures/promote-good.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/sandbox-run-lib.mq.md b/tests/ext/sandbox-run-lib.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-doc.mq.md b/tests/ext/web-artifact-doc.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-endpoint.mq.md b/tests/ext/web-artifact-endpoint.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-render-smoke.mq.md b/tests/ext/web-artifact-render-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-site/api/ping.mq.md b/tests/ext/web-artifact-site/api/ping.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-site/index.mq.md b/tests/ext/web-artifact-site/index.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-site/pages/about.mq.md b/tests/ext/web-artifact-site/pages/about.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-site/serve.mq.md b/tests/ext/web-artifact-site/serve.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-artifact-zh.mq.md b/tests/ext/web-artifact-zh.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-cache-artifact-smoke.mq.md b/tests/ext/web-cache-artifact-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-data-db-smoke.mq.md b/tests/ext/web-data-db-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/components/foot.mq.md b/tests/ext/web-fixtures/components/foot.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/components/nav.mq.md b/tests/ext/web-fixtures/components/nav.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/components/side.mq.md b/tests/ext/web-fixtures/components/side.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/db/articles.mq.md b/tests/ext/web-fixtures/db/articles.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/public/favicon.png b/tests/ext/web-fixtures/public/favicon.png old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/public/favicon.svg b/tests/ext/web-fixtures/public/favicon.svg old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/public/hello.txt b/tests/ext/web-fixtures/public/hello.txt old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/styles/shell.mq.md b/tests/ext/web-fixtures/styles/shell.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/upload/bad.bin b/tests/ext/web-fixtures/upload/bad.bin old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/upload/big.txt b/tests/ext/web-fixtures/upload/big.txt old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/upload/sample.txt b/tests/ext/web-fixtures/upload/sample.txt old mode 100644 new mode 100755 diff --git a/tests/ext/web-fixtures/upload/tiny.png b/tests/ext/web-fixtures/upload/tiny.png old mode 100644 new mode 100755 diff --git a/tests/ext/web-rbac-artifact-smoke.mq.md b/tests/ext/web-rbac-artifact-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-static-artifact-smoke.mq.md b/tests/ext/web-static-artifact-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/web-use-smoke.mq.md b/tests/ext/web-use-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/workbench-agent-selection.mq.md b/tests/ext/workbench-agent-selection.mq.md old mode 100644 new mode 100755 diff --git a/tests/ext/workbench-selection-live.mq.md b/tests/ext/workbench-selection-live.mq.md old mode 100644 new mode 100755 diff --git a/tests/gold.rs b/tests/gold.rs old mode 100644 new mode 100755 diff --git a/tests/isolated_execute_mr01.rs b/tests/isolated_execute_mr01.rs old mode 100644 new mode 100755 diff --git a/tests/isolated_runtime_smoke.rs b/tests/isolated_runtime_smoke.rs old mode 100644 new mode 100755 diff --git a/tests/keywords/bool-logic.mq.md b/tests/keywords/bool-logic.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/input-escape.mq.md b/tests/keywords/input-escape.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/input-stdin.txt b/tests/keywords/input-stdin.txt old mode 100644 new mode 100755 diff --git a/tests/keywords/input.mq.md b/tests/keywords/input.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/print.mq.md b/tests/keywords/print.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/quoted-string.mq.md b/tests/keywords/quoted-string.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/stdlib-more.mq.md b/tests/keywords/stdlib-more.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/stdlib.mq.md b/tests/keywords/stdlib.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/zh-bool.mq.md b/tests/keywords/zh-bool.mq.md old mode 100644 new mode 100755 diff --git a/tests/keywords/zh-builtins.mq.md b/tests/keywords/zh-builtins.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/cli-sort-smoke.mq.md b/tests/lib/cli-sort-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/csv-smoke.mq.md b/tests/lib/csv-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/datetime-smoke.mq.md b/tests/lib/datetime-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/dotenv-fixture.env b/tests/lib/dotenv-fixture.env old mode 100644 new mode 100755 diff --git a/tests/lib/encoding-smoke.mq.md b/tests/lib/encoding-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/fixtures/foreign.toml b/tests/lib/fixtures/foreign.toml old mode 100644 new mode 100755 diff --git a/tests/lib/fixtures/hello.txt b/tests/lib/fixtures/hello.txt old mode 100644 new mode 100755 diff --git a/tests/lib/fixtures/sample.json b/tests/lib/fixtures/sample.json old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-call.mq.md b/tests/lib/foreign-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-config.mq.md b/tests/lib/foreign-config.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-copy-code-refuse.mq.md b/tests/lib/foreign-copy-code-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-env-timeout.mq.md b/tests/lib/foreign-env-timeout.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-invoke.mq.md b/tests/lib/foreign-invoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-json.mq.md b/tests/lib/foreign-json.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-oracle-failure.mq.md b/tests/lib/foreign-oracle-failure.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-oracle-journal.mq.md b/tests/lib/foreign-oracle-journal.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-oracle-names.mq.md b/tests/lib/foreign-oracle-names.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-probe-register.mq.md b/tests/lib/foreign-probe-register.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-python.mq.md b/tests/lib/foreign-python.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-run-lang.mq.md b/tests/lib/foreign-run-lang.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-cold-replay-empty.mq.md b/tests/lib/foreign-session-cold-replay-empty.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-copy-code-refuse.mq.md b/tests/lib/foreign-session-copy-code-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-double-close.mq.md b/tests/lib/foreign-session-double-close.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-handle-no-serialize.mq.md b/tests/lib/foreign-session-handle-no-serialize.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-isolation.mq.md b/tests/lib/foreign-session-isolation.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-python.mq.md b/tests/lib/foreign-session-python.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-result-vsafe-refuse.mq.md b/tests/lib/foreign-session-result-vsafe-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-timeout.mq.md b/tests/lib/foreign-session-timeout.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-use-after-close.mq.md b/tests/lib/foreign-session-use-after-close.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-use-before-open.mq.md b/tests/lib/foreign-session-use-before-open.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session-vsafe-refuse.mq.md b/tests/lib/foreign-session-vsafe-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-session.mq.md b/tests/lib/foreign-session.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-vsafe-postarith-refuse.mq.md b/tests/lib/foreign-vsafe-postarith-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-vsafe-refuse.mq.md b/tests/lib/foreign-vsafe-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/foreign-vsafe-string-ok.mq.md b/tests/lib/foreign-vsafe-string-ok.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/fs-copy-move.mq.md b/tests/lib/fs-copy-move.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/fs-mid2-smoke.mq.md b/tests/lib/fs-mid2-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/fs-read.mq.md b/tests/lib/fs-read.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/hash-smoke.mq.md b/tests/lib/hash-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/hello.txt b/tests/lib/hello.txt old mode 100644 new mode 100755 diff --git a/tests/lib/json-quote.mq.md b/tests/lib/json-quote.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/json-roundtrip.mq.md b/tests/lib/json-roundtrip.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/json-vsafe-max-safe-ok.mq.md b/tests/lib/json-vsafe-max-safe-ok.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/json-vsafe-refuse.mq.md b/tests/lib/json-vsafe-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/json-vsafe-string-ok.mq.md b/tests/lib/json-vsafe-string-ok.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/json-vsafe-stringify-refuse.mq.md b/tests/lib/json-vsafe-stringify-refuse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/log-uuid-smoke.mq.md b/tests/lib/log-uuid-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/math-formula-chain.mq.md b/tests/lib/math-formula-chain.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/math-formula.mq.md b/tests/lib/math-formula.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/math-plot.mq.md b/tests/lib/math-plot.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/math-random.mq.md b/tests/lib/math-random.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-cookie.mq.md b/tests/lib/net-cookie.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-encode.mq.md b/tests/lib/net-encode.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-markdown.mq.md b/tests/lib/net-markdown.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-multipart.mq.md b/tests/lib/net-multipart.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-openai-sse-reasoning.mq.md b/tests/lib/net-openai-sse-reasoning.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/net-openai-sse.mq.md b/tests/lib/net-openai-sse.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/path-smoke.mq.md b/tests/lib/path-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/plugin-demo.mq.md b/tests/lib/plugin-demo.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/re-smoke.mq.md b/tests/lib/re-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/sample.json b/tests/lib/sample.json old mode 100644 new mode 100755 diff --git a/tests/lib/secrets-smoke.mq.md b/tests/lib/secrets-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/stats-log-smoke.mq.md b/tests/lib/stats-log-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-child-print.mq.md b/tests/lib/subtask-child-print.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-child.mq.md b/tests/lib/subtask-child.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-fn.mq.md b/tests/lib/subtask-fn.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-foreign.mq.md b/tests/lib/subtask-foreign.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-quiet-io.mq.md b/tests/lib/subtask-quiet-io.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/subtask-spawn.mq.md b/tests/lib/subtask-spawn.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/sys-cwd.mq.md b/tests/lib/sys-cwd.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/sys-dotenv.mq.md b/tests/lib/sys-dotenv.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/sys-exec-capture.mq.md b/tests/lib/sys-exec-capture.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/table-collections.mq.md b/tests/lib/table-collections.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/table-list-mid.mq.md b/tests/lib/table-list-mid.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/text-mid-smoke.mq.md b/tests/lib/text-mid-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/time-format.mq.md b/tests/lib/time-format.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/toml-html-encoding-smoke.mq.md b/tests/lib/toml-html-encoding-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/url-smoke.mq.md b/tests/lib/url-smoke.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/writeback-async.mq.md b/tests/lib/writeback-async.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/writeback-get.mq.md b/tests/lib/writeback-get.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/哈希-烟测.mq.md b/tests/lib/哈希-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/地址-烟测.mq.md b/tests/lib/地址-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/外联-python.mq.md b/tests/lib/外联-python.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/数学-数值.mq.md b/tests/lib/数学-数值.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/文件-mid2-烟测.mq.md b/tests/lib/文件-mid2-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/文件-复制.mq.md b/tests/lib/文件-复制.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/文件-读.mq.md b/tests/lib/文件-读.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/文本-加厚-烟测.mq.md b/tests/lib/文本-加厚-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/日志-标识-烟测.mq.md b/tests/lib/日志-标识-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/日期时间-烟测.mq.md b/tests/lib/日期时间-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/机密-烟测.mq.md b/tests/lib/机密-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/正则-烟测.mq.md b/tests/lib/正则-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/统计-日志-烟测.mq.md b/tests/lib/统计-日志-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/编码-烟测.mq.md b/tests/lib/编码-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/表-命令行-烟测.mq.md b/tests/lib/表-命令行-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/表-集合.mq.md b/tests/lib/表-集合.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/路径-烟测.mq.md b/tests/lib/路径-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/逗号表-烟测.mq.md b/tests/lib/逗号表-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/lib/配置表-超文本-编码-烟测.mq.md b/tests/lib/配置表-超文本-编码-烟测.mq.md old mode 100644 new mode 100755 diff --git a/tests/library_authoring.rs b/tests/library_authoring.rs old mode 100644 new mode 100755 diff --git a/tests/markup-v03/README.md b/tests/markup-v03/README.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/bold-call.mq.md b/tests/markup-v03/bold-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/bold-expr.mq.md b/tests/markup-v03/bold-expr.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/branch-arm-prose.mq.md b/tests/markup-v03/branch-arm-prose.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/branch-cond-narrative.mq.md b/tests/markup-v03/branch-cond-narrative.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/dead-bind.mq.md b/tests/markup-v03/dead-bind.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/decl-ident-only.mq.md b/tests/markup-v03/decl-ident-only.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/dual-call.mq.md b/tests/markup-v03/dual-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/dynamic-footnote.mq.md b/tests/markup-v03/dynamic-footnote.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/empty-return-compat.mq.md b/tests/markup-v03/empty-return-compat.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/empty-return-hr.mq.md b/tests/markup-v03/empty-return-hr.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/empty-return-none.mq.md b/tests/markup-v03/empty-return-none.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/empty-return-stars.mq.md b/tests/markup-v03/empty-return-stars.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/float-discount.mq.md b/tests/markup-v03/float-discount.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/foreach-narrative.mq.md b/tests/markup-v03/foreach-narrative.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/foreach-nested-link.mq.md b/tests/markup-v03/foreach-nested-link.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/formula-meta-var.mq.md b/tests/markup-v03/formula-meta-var.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/greet-default.mq.md b/tests/markup-v03/greet-default.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/inc-prose.mq.md b/tests/markup-v03/inc-prose.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/inline-dollar-formula.mq.md b/tests/markup-v03/inline-dollar-formula.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/leading-backtick-decl.mq.md b/tests/markup-v03/leading-backtick-decl.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/module-hr.mq.md b/tests/markup-v03/module-hr.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/multi-bold.mq.md b/tests/markup-v03/multi-bold.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/print-bold.mq.md b/tests/markup-v03/print-bold.mq.md old mode 100644 new mode 100755 diff --git a/tests/markup-v03/soft-emphasis.mq.md b/tests/markup-v03/soft-emphasis.mq.md old mode 100644 new mode 100755 diff --git a/tests/migrate.rs b/tests/migrate.rs old mode 100644 new mode 100755 diff --git a/tests/mlsp.rs b/tests/mlsp.rs old mode 100644 new mode 100755 diff --git a/tests/native_foreign_handbook.rs b/tests/native_foreign_handbook.rs old mode 100644 new mode 100755 diff --git a/tests/notebook/no-foreign.mq.md b/tests/notebook/no-foreign.mq.md old mode 100644 new mode 100755 diff --git a/tests/notebook/python-insights.mq.md b/tests/notebook/python-insights.mq.md old mode 100644 new mode 100755 diff --git a/tests/notebook/shared.mq.md b/tests/notebook/shared.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion.rs b/tests/occlusion.rs old mode 100644 new mode 100755 diff --git a/tests/occlusion/access-and-loop.mq.md b/tests/occlusion/access-and-loop.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/classic-index.mq.md b/tests/occlusion/classic-index.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/clean.mq.md b/tests/occlusion/clean.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/empty-label.mq.md b/tests/occlusion/empty-label.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/empty-payload.mq.md b/tests/occlusion/empty-payload.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/implicit-ok.mq.md b/tests/occlusion/implicit-ok.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/implicit-stale.mq.md b/tests/occlusion/implicit-stale.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/labels.mq.md b/tests/occlusion/labels.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/ref-dangling.mq.md b/tests/occlusion/ref-dangling.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/ref-ok.mq.md b/tests/occlusion/ref-ok.mq.md old mode 100644 new mode 100755 diff --git a/tests/occlusion/value.mq.md b/tests/occlusion/value.mq.md old mode 100644 new mode 100755 diff --git a/tests/oracle_journal.rs b/tests/oracle_journal.rs old mode 100644 new mode 100755 diff --git a/tests/prove.rs b/tests/prove.rs new file mode 100755 index 0000000..863a3cf --- /dev/null +++ b/tests/prove.rs @@ -0,0 +1,838 @@ +//! `marqdo prove` P0 集成测试(roadmap/prove.md §6 A–H 矩阵的 P0 部分)。 +//! +//! 全部不依赖 Lean:判定在 P1 接入,P0 只验「装载 → 降级 → 定型 → 确定性生成」。 +//! 每个用例在 `target/` 下的独立临时目录里跑 CLI(与 `Commands::Check` 同款)。 + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +struct Scratch { + dir: PathBuf, +} + +impl Scratch { + fn new(name: &str) -> Self { + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = target.join("prove-tests").join(name); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("create scratch dir"); + Self { dir } + } + + /// 把 lib/result.mq.md 拷进临时项目(import 相对文档解析)。 + fn provision_lib(&self) { + let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib/result.mq.md"); + let dst = self.dir.join("lib/result.mq.md"); + fs::create_dir_all(self.dir.join("lib")).expect("create lib dir"); + fs::copy(&src, &dst).expect("copy lib/result.mq.md"); + } + + fn write(&self, rel: &str, content: &str) -> PathBuf { + let path = self.dir.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("create fixture parent"); + } + fs::write(&path, content).expect("write fixture"); + path + } + + fn run(&self, args: &[&str]) -> Run { + let exe: &Path = Path::new(env!("CARGO_BIN_EXE_marqdo")); + let output = Command::new(exe) + .args(args) + .current_dir(&self.dir) + .env("MARQDO_RUNTIME_DIR", self.dir.join("runtime")) + .output() + .expect("run marqdo"); + Run { + code: output.status.code().unwrap_or(1), + stdout: String::from_utf8_lossy(&output.stdout).to_string(), + stderr: String::from_utf8_lossy(&output.stderr).to_string(), + } + } +} + +struct Run { + code: i32, + stdout: String, + stderr: String, +} + +/// 审批样例(roadmap §7 / 设计 §2.5):分支 + 内联 result + 不透明 import。 +const APPROVAL: &str = r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +审批一个报销申请:大额必须人工审核,小额自动通过。 + +# 审批台 + +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +1. `金额` > 10000 + **回执 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留结论](result.ok(value=[取值](access(`回执`, "value"))))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +*结果* + +## 人工审核 ++ `金额` + +**回执 = [请求送审](工程.送审(金额=`金额`))** + +*回执* +"#; + +/// 倒计时:while 循环 → P0 拒绝(proof.while)。 +const COUNTDOWN: &str = r#"--- +markup: occlusion +--- + +# 倒计时器 + +## 倒数 ++ `n` + +**剩余 = `n`** +- `剩余` > 0 + **剩余 = `剩余` - 1** + +*剩余* +"#; + +/// 分支后还有 return:两臂都必须带上后续(续延丢失回归测试)。 +const BRANCH_THEN_RETURN: &str = r#"--- +markup: occlusion +--- + +# 盒子 + +## 挑选 ++ `n` + +1. `n` > 0 + **输出 = "正"** +2. * + **输出 = "负"** + +*输出* +"#; + +/// 裸未知名:动态调用 → 拒绝。 +const UNKNOWN_CALL: &str = r#"--- +markup: occlusion +--- + +# 神秘 + +## 执行 + +**回执 = [召唤](不存在的函数(`1`))** + +*回执* +"#; + +/// 带定理表的审批样例(roadmap §3 / 设计 §7.1;与设计文档示例同形)。 +const APPROVAL_WITH_CLAIMS: &str = r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 审批台 + +## 审批 ++ `金额` + +| 参数 | 类型 | 说明 | +|---|---|---| +| 金额 | int | 申请金额(元) | + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额必经人工 | 包含(轨迹, "人工审核") | 金额 > 10000 | auto | +| 恒有结果 | 结果.ok = True | | auto | + +1. `金额` > 10000 + **回执 = [提交人工审核](人工审核(金额=`金额`))** + **结果 = [保留结论](result.ok(value=[取值](access(`回执`, "value"))))** +2. * + **结果 = [自动通过](result.ok(value="auto"))** + +*结果* + +## 人工审核 ++ `金额` + +**回执 = [请求送审](工程.送审(金额=`金额`))** + +*回执* +"#; + +fn read(dir: &Path, rel: &str) -> String { + fs::read_to_string(dir.join(rel)).unwrap_or_else(|e| panic!("read {rel}: {e}")) +} + +#[test] +fn p0_a_emit_writes_deterministic_artifacts() { + let s = Scratch::new("a_deterministic"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r1 = s.run(&["prove", "approval.mq.md", "--emit", "out1"]); + assert_eq!(r1.code, 0, "emit1 stderr={}", r1.stderr); + let r2 = s.run(&["prove", "approval.mq.md", "--emit", "out2"]); + assert_eq!(r2.code, 0, "emit2 stderr={}", r2.stderr); + + for rel in ["out1/plan.json", "out1/Generated/approval_mq.lean"] { + assert!(s.dir.join(&rel).is_file(), "missing {rel}"); + } + // 确定性:两次 emit 字节一致(plan + lean)。 + assert_eq!( + read(&s.dir, "out1/plan.json"), + read(&s.dir, "out2/plan.json"), + "plan.json must be byte-identical" + ); + assert_eq!( + read(&s.dir, "out1/Generated/approval_mq.lean"), + read(&s.dir, "out2/Generated/approval_mq.lean"), + "lean module must be byte-identical" + ); +} + +#[test] +fn p0_b_json_contract_shape() { + let s = Scratch::new("b_json_shape"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["schema"], 1); + assert_eq!(v["status"], "unverified"); + assert_eq!(v["file"], "approval.mq.md"); + assert!(v["source_sha256"].as_str().is_some_and(|h| h.len() == 64)); + let functions = v["functions"].as_array().expect("functions array"); + assert_eq!(functions.len(), 2, "对象不进报告,只有两个函数"); + let names: Vec<&str> = functions + .iter() + .map(|f| f["name"].as_str().expect("name")) + .collect(); + assert_eq!(names, vec!["审批台.审批", "审批台.人工审核"]); + for f in functions { + assert_eq!(f["tier"], "none", "P0 无判定层"); + assert_eq!(f["status"], "unverified"); + assert_eq!(f["claims"].as_array().map(Vec::len), Some(0)); + } + // lean 尚未接入(P0 判定在 P1)。 + assert!(v["lean"].is_null()); + // emitted 为空(report-only)。 + assert_eq!(v["emitted"].as_array().map(Vec::len), Some(0)); +} + +#[test] +fn p0_c_while_loop_rejected_with_code() { + let s = Scratch::new("c_while_rejected"); + s.write("countdown.mq.md", COUNTDOWN); + let r = s.run(&["prove", "countdown.mq.md", "--report-only", "--json"]); + // 拒绝是建议性(exit 0),不阻断 agent。 + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected"); + let f = &v["functions"][0]; + assert_eq!(f["name"], "倒计时器.倒数"); + assert_eq!(f["status"], "rejected"); + let rejected = f["rejected"].as_array().expect("rejected array"); + assert!( + rejected + .iter() + .any(|d| d["code"] == "proof.while"), + "expected proof.while, got {rejected:?}" + ); + // 文本面也列出拒绝原因。 + let t = s.run(&["prove", "countdown.mq.md", "--report-only"]); + assert!(t.stdout.contains("proof.while"), "text: {}", t.stdout); +} + +#[test] +fn p0_d_side_effect_import_is_opaque_op() { + let s = Scratch::new("d_opaque_op"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + // 工程外部调用:Op 构造器 + Env 查询 + 追踪,不展开。 + assert!(lean.contains("«调用_工程.送审»"), "op ctor missing:\n{lean}"); + assert!(lean.contains("env (Op.«调用_工程.送审»"), "env query missing"); + assert!(lean.contains("[Op.«调用_工程.送审»"), "trace append missing"); + // result.ok 内联为 Val 构造器,不是 Op。 + assert!(!lean.contains("result.ok»"), "result.ok must inline, not be an Op"); + assert!(lean.contains("mqResultOk"), "result.ok → mqResultOk"); +} + +#[test] +fn p0_e_allow_opaque_downgrades_whole_function() { + let s = Scratch::new("e_allow_opaque"); + s.write("countdown.mq.md", COUNTDOWN); + let r = s.run(&[ + "prove", + "countdown.mq.md", + "--report-only", + "--json", + "--allow-opaque", + "倒计时器.倒数", + ]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "unverified"); + let f = &v["functions"][0]; + assert_eq!(f["status"], "unverified"); + let ops = f["ops"].as_array().expect("ops"); + assert_eq!(ops.len(), 1, "整函数降级 = 单个 Op"); + assert_eq!(ops[0]["id"], "调用:倒计时器.倒数"); + assert_eq!(ops[0]["effect"], "opaque"); +} + +#[test] +fn p0_f_branch_continuation_not_swallowed() { + let s = Scratch::new("f_continuation"); + s.write("box.mq.md", BRANCH_THEN_RETURN); + let r = s.run(&["prove", "box.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/box_mq.lean"); + // 分支后的 return 必须出现在两个臂里(回归:此前续延被分支吞掉)。 + assert_eq!( + lean.matches("(«输出», «轨迹»)").count(), + 2, + "return must appear in both arms:\n{lean}" + ); + // 两臂各自绑定。 + assert!(lean.contains("let «输出» := (Val.text \"正\")"), "{lean}"); + assert!(lean.contains("let «输出» := (Val.text \"负\")"), "{lean}"); +} + +#[test] +fn p0_g_mq_line_comments_and_guillemets() { + let s = Scratch::new("g_comments"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + assert!(lean.contains("-- mq: "), "溯源注释缺失"); + // 含点标识符用 guillemets。 + assert!(lean.contains("«审批台.审批»"), "{lean}"); + // 确定性来源:无时间戳、无绝对路径。 + assert!(!lean.contains("marqdo/prove/"), "must not leak default dir"); +} + +#[test] +fn p0_h_unknown_call_rejected() { + let s = Scratch::new("h_unknown"); + s.write("mystery.mq.md", UNKNOWN_CALL); + let r = s.run(&["prove", "mystery.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected"); + let rejected = v["functions"][0]["rejected"] + .as_array() + .expect("rejected array"); + assert!( + rejected.iter().any(|d| d["code"] == "proof.dynamic_call"), + "expected proof.dynamic_call, got {rejected:?}" + ); +} + +#[test] +fn p0_i_report_only_writes_nothing() { + let s = Scratch::new("i_report_only"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md", "--report-only"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!( + !s.dir.join(".marqdo").exists(), + "report-only must not create artifacts" + ); + assert!(!r.stdout.contains("emitted:"), "no emitted lines"); +} + +#[test] +fn p0_j_clean_removes_default_dir() { + let s = Scratch::new("j_clean"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&["prove", "approval.mq.md"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!(s.dir.join(".marqdo/prove").exists(), "default emit dir"); + let r = s.run(&["prove", "clean", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + assert!(r.stdout.contains("\"ok\":true"), "{}", r.stdout); + assert!(!s.dir.join(".marqdo/prove").exists(), "clean must remove dir"); +} + +#[test] +fn p0_k_branch_type_conflict_is_error() { + let s = Scratch::new("k_type_conflict"); + s.write( + "conflict.mq.md", + r#"--- +markup: occlusion +--- + +# 冲突 + +## 挑选 ++ `n` + +| 参数 | 类型 | 说明 | +|---|---|---| +| n | int | 数值 | + +1. `n` > 0 + **输出 = `n`** +2. * + **输出 = "文字"** + +*输出* +"#, + ); + let r = s.run(&["prove", "conflict.mq.md", "--report-only", "--json"]); + // error → exit 1(§3.3)。 + assert_eq!(r.code, 1, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "error"); + let codes: Vec<&str> = v["diagnostics"] + .as_array() + .expect("diagnostics") + .iter() + .filter_map(|d| d["code"].as_str()) + .collect(); + assert!( + codes.iter().any(|c| *c == "proof.type_mismatch"), + "expected proof.type_mismatch, got {codes:?}" + ); +} + +#[test] +fn p0_l_only_filters_report() { + let s = Scratch::new("l_only"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL); + let r = s.run(&[ + "prove", + "approval.mq.md", + "--report-only", + "--json", + "--only", + "审批台.人工审核", + ]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + let functions = v["functions"].as_array().expect("functions"); + assert_eq!(functions.len(), 1); + assert_eq!(functions[0]["name"], "审批台.人工审核"); +} + +// ============================================================ P1 · 定理表与 check --proof + +/// 提取后的定理表:claims 非空、body 无该表(roadmap §3 第 1 周验收)。 +#[test] +fn p1_a_claim_table_extracted_and_removed_from_body() { + let s = Scratch::new("p1_extract"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + let r = s.run(&["prove", "approval.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + let f = &v["functions"][0]; + assert_eq!(f["name"], "审批台.审批"); + let claims = f["claims"].as_array().expect("claims array"); + assert_eq!(claims.len(), 2, "{claims:?}"); + assert_eq!(claims[0]["id"], "大额必经人工"); + assert_eq!(claims[0]["premise"], "金额 > 10000"); + assert_eq!(claims[0]["conclusion"], "包含(轨迹, \"人工审核\")"); + assert_eq!(claims[1]["id"], "恒有结果"); + assert!(claims[1]["premise"].is_null(), "空前提 = 全称命题"); + // 表从 body 移除:plan 的 steps 里没有表(函数照常降级)。 + assert_eq!(f["status"], "unverified"); +} + +/// 定理脚手架进 Lean:受限文法命题 → theorem 陈述 + sorry 占位。 +#[test] +fn p1_b_emit_theorem_scaffold() { + let s = Scratch::new("p1_theorem"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + let r = s.run(&["prove", "approval.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/approval_mq.lean"); + assert!( + lean.contains("theorem «审批台.审批.大额必经人工»"), + "{lean}" + ); + // 前提进绑定;包含(轨迹, …) 翻成操作名成员测试。 + assert!(lean.contains("(«h_前提» : mqTruth (mqGt «金额» (Val.int 10000)))"), "{lean}"); + assert!( + lean.contains("((«轨迹».map Op.name).contains \"人工审核\")"), + "{lean}" + ); + // 结果.ok → mqAccess 字段读取。 + assert!(lean.contains("(mqAccess «结果» \"ok\")"), "{lean}"); + // 策略脚本(§7.2):unfold → split → simp_all/omega。 + assert!(lean.contains("unfold «审批台.审批» at h_run"), "{lean}"); + assert!( + lean.contains("try split at h_run") + && lean.contains("all_goals\n simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqEq]"), + "{lean}" + ); +} + +/// check --proof(默认关):不传 --proof 时定理问题不报。 +#[test] +fn p1_c_check_proof_off_by_default() { + let s = Scratch::new("p1_default_off"); + s.write( + "bad.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | +|---|---| +| 引用未知 | 额度 > 0 | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "bad.mq.md", "--json"]); + assert_eq!(r.code, 0, "默认关:{} {}", r.stdout, r.stderr); + assert!( + !r.stdout.contains("proof.claim_unknown_symbol"), + "默认必须不报:{}", + r.stdout + ); +} + +/// check --proof:unknown_symbol + duplicate + misplaced + malformed。 +#[test] +fn p1_d_check_proof_diagnostic_codes() { + let s = Scratch::new("p1_codes"); + s.write( + "bad.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 引用未知 | 长度(轨迹) = 额度 | 金额 > 0 | auto | +| 引用未知 | 长度(轨迹) = 额度 | 金额 > 0 | auto | +| 坏策略 | 结果.ok = True | | manual | + +**x = `金额`** + +| 定理 | 结论 | +|---|---| +| 错位表 | 结果.ok = True | + +*x* +"#, + ); + let r = s.run(&["check", "bad.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "error 级诊断 → 退出 1:{}", r.stdout); + assert!(r.stdout.contains("proof.claim_unknown_symbol"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_duplicate"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_misplaced"), "{}", r.stdout); + assert!(r.stdout.contains("proof.claim_malformed"), "{}", r.stdout); + // 不该误报:策略 auto/none 之外的 malformed 只出现一次(坏策略行)。 + assert_eq!(r.stdout.matches("proof.claim_malformed").count(), 1, "{}", r.stdout); +} + +/// check --proof:保留名遮蔽(§7.3.4)。 +#[test] +fn p1_e_check_proof_name_shadow() { + let s = Scratch::new("p1_shadow"); + s.write( + "shadow.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `结果` + +| 定理 | 结论 | +|---|---| +| 恒真 | 结果.ok = True | + +**x = `结果`** + +*x* +"#, + ); + let r = s.run(&["check", "shadow.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "{}", r.stdout); + assert!(r.stdout.contains("proof.name_shadow"), "{}", r.stdout); +} + +/// check --proof:歧义表(类型+结论)与谓词元数(§7.1 规则 5 / §7.3.5)。 +#[test] +fn p1_f_check_proof_ambiguous_and_unsupported() { + let s = Scratch::new("p1_amb"); + s.write( + "amb.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 类型 | 结论 | +|---|---|---| +| 歧义 | int | 结果.ok = True | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "amb.mq.md", "--proof", "--json"]); + assert!(r.stdout.contains("proof.claim_ambiguous"), "{}", r.stdout); + + let s2 = Scratch::new("p1_unsupported"); + s2.write( + "bad2.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 核对 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 元数错 | 包含(轨迹, "a", "b") | auto | + +**x = `金额`** + +*x* +"#, + ); + let r = s2.run(&["check", "bad2.mq.md", "--proof", "--json"]); + assert!(r.stdout.contains("proof.claim_unsupported"), "{}", r.stdout); +} + +/// 带定理的文件:emit 输出仍然确定性(plan.json + lean 两次一致)。 +#[test] +fn p1_g_emit_with_claims_is_deterministic() { + let s = Scratch::new("p1_det"); + s.provision_lib(); + s.write("approval.mq.md", APPROVAL_WITH_CLAIMS); + s.run(&["prove", "approval.mq.md", "--emit", "out1"]); + s.run(&["prove", "approval.mq.md", "--emit", "out2"]); + assert_eq!( + read(&s.dir, "out1/Generated/approval_mq.lean"), + read(&s.dir, "out2/Generated/approval_mq.lean") + ); + assert_eq!(read(&s.dir, "out1/plan.json"), read(&s.dir, "out2/plan.json")); + // plan.json 里定理声明带行号锚点。 + let plan = read(&s.dir, "out1/plan.json"); + assert!(plan.contains("\"claims\":[{"), "{plan}"); + assert!(plan.contains("\"line\":16"), "{plan}"); +} + +// ============================================================ 审查修复的回归测试 + +/// 缺陷 1:表格单元格里的副作用调用必须被拒绝,不许静默丢弃 +/// (静默丢弃会让含副作用的函数在 Lean 里伪装成"无操作")。 +#[test] +fn p2_a_impure_call_in_table_cell_is_rejected() { + let s = Scratch::new("p2_impure_tbl"); + s.write( + "record.mq.md", + r#"--- +markup: occlusion +--- + +# 副作用实验 + +## 记录 ++ `名` + +**数据 =** +| 步骤 | +|---| +| [落笔](工程.写(名=`名`)) | +| [收笔](工程.收(名=`名`)) | + +**x = [取值](access(`数据`, "步骤"))** + +*x* +"#, + ); + let r = s.run(&["prove", "record.mq.md", "--report-only", "--json"]); + assert_eq!(r.code, 0, "拒绝是 advisory,exit 0:{}", r.stderr); + let v: serde_json::Value = serde_json::from_str(&r.stdout).expect("valid JSON"); + assert_eq!(v["status"], "rejected", "{v}"); + let rejected = serde_json::to_string(&v["functions"][0]["rejected"]).unwrap(); + assert!( + rejected.contains("proof.unsupported"), + "必须有 proof.unsupported:{v}" + ); + // 关键:函数里没有任何 Op(调用没被当作不透明操作处理)→ 整个函数拒绝。 + assert_eq!(v["functions"][0]["ops"].as_array().map(Vec::len), Some(0)); +} + +/// 缺陷 2:同名不同元数的调用点 → `/元数` 后缀的独立 Op,构造器与使用一致。 +#[test] +fn p2_b_op_arity_mismatch_gets_suffixed_ctor() { + let s = Scratch::new("p2_arity"); + s.write( + "machine.mq.md", + r#"--- +markup: occlusion +--- + +# 机器 + +## 可选参数 ++ `a` ++ `b` = 1 + +**r = [加一](自身.加一(a=`a`))** +**s = [加一](自身.加一(a=`a`, b=`b`))** + +*r* + +## 加一 ++ `a` ++ `b` = 1 + +**t = `a` + `b`** + +*t* +"#, + ); + let r = s.run(&["prove", "machine.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/machine_mq.lean"); + // 两个构造器,元数各自正确。 + assert!( + lean.contains("| «调用_自身.加一» («参数1» : Val)"), + "{lean}" + ); + assert!( + lean.contains("| «调用_自身.加一/2» («参数1» : Val) («参数2» : Val)"), + "{lean}" + ); + // 使用点各自带对个数的实参。 + assert!(lean.contains("Op.«调用_自身.加一» a)"), "{lean}"); + assert!(lean.contains("Op.«调用_自身.加一/2» a b)"), "{lean}"); +} + +/// 缺陷 3:`长度(轨迹) = 2` 必须生成 Nat 比较,不是 mqEq(Nat≠Val)。 +#[test] +fn p2_c_trace_length_claim_uses_nat_operators() { + let s = Scratch::new("p2_len"); + s.provision_lib(); + s.write( + "count.mq.md", + r#"--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 轨迹计数 + +## 纯计算 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 空轨迹 | 长度(轨迹) = 0 | auto | + +**a = [一步](result.ok(value=1))** +**b = [两步](result.ok(value=2))** + +*b* +"#, + ); + let r = s.run(&["prove", "count.mq.md", "--emit", "out"]); + assert_eq!(r.code, 0, "stderr={}", r.stderr); + let lean = read(&s.dir, "out/Generated/count_mq.lean"); + assert!( + lean.contains("((«轨迹».length : Nat) = 0)"), + "Nat 比较:{lean}" + ); + assert!(!lean.contains("mqEq («轨迹».length"), "不许出现类型不匹配:{lean}"); +} + +/// 缺陷 4:谓词名遮蔽整个模块只报一次;无关函数的形参不误报。 +#[test] +fn p2_d_name_shadow_reported_once() { + let s = Scratch::new("p2_shadow"); + s.write( + "audit.mq.md", + r#"--- +markup: occlusion +--- + +# 审计 + +## 包含 ++ `n` + +**y = `n`** + +*y* + +## 核对 ++ `金额` + +| 定理 | 结论 | +|---|---| +| 恒真 | 结果.ok = True | + +**x = `金额`** + +*x* +"#, + ); + let r = s.run(&["check", "audit.mq.md", "--proof", "--json"]); + assert_eq!(r.code, 1, "{}", r.stdout); + let count = r.stdout.matches("proof.name_shadow").count(); + assert_eq!(count, 1, "只报一次:{}", r.stdout); +} diff --git a/tests/prove/fixtures/beyond/y1.mq.md b/tests/prove/fixtures/beyond/y1.mq.md new file mode 100755 index 0000000..009ff43 --- /dev/null +++ b/tests/prove/fixtures/beyond/y1.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 文本台 + +## 拼接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 文本相等 | 结果.value = "x" | | auto | + +**结果 = [登记](result.ok(value="x"))** + +*结果* diff --git a/tests/prove/fixtures/beyond/y2.mq.md b/tests/prove/fixtures/beyond/y2.mq.md new file mode 100755 index 0000000..62201fc --- /dev/null +++ b/tests/prove/fixtures/beyond/y2.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 文本台 + +## 拼接 ++ `金额` ++ `等级` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 双变量线性 | 金额 + 等级 > 100 | | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/beyond/y3.mq.md b/tests/prove/fixtures/beyond/y3.mq.md new file mode 100755 index 0000000..352ec27 --- /dev/null +++ b/tests/prove/fixtures/beyond/y3.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 文本台 + +## 拼接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 非线性 | 金额 * 2 > 100 | 金额 > 50 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/beyond/y4.mq.md b/tests/prove/fixtures/beyond/y4.mq.md new file mode 100755 index 0000000..83448c3 --- /dev/null +++ b/tests/prove/fixtures/beyond/y4.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 文本台 + +## 拼接 ++ `金额` ++ `等级` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 变量相等 | 金额 = 等级 | | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/beyond/y5.mq.md b/tests/prove/fixtures/beyond/y5.mq.md new file mode 100755 index 0000000..a3355af --- /dev/null +++ b/tests/prove/fixtures/beyond/y5.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 文本台 + +## 拼接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 负号运算 | -金额 < 0 | | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/branches/b1.mq.md b/tests/prove/fixtures/branches/b1.mq.md new file mode 100755 index 0000000..e115a35 --- /dev/null +++ b/tests/prove/fixtures/branches/b1.mq.md @@ -0,0 +1,21 @@ +--- +markup: occlusion +--- + +# 路由 + +## 分发 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 三路必达 | 结果.ok = True | | auto | + +1. `金额` > 10000 + **结果 = [大](result.ok(value="big"))** +2. `金额` > 100 + **结果 = [中](result.ok(value="mid"))** +3. * + **结果 = [小](result.ok(value="small"))** + +*结果* diff --git a/tests/prove/fixtures/branches/b2.mq.md b/tests/prove/fixtures/branches/b2.mq.md new file mode 100755 index 0000000..4cddbfa --- /dev/null +++ b/tests/prove/fixtures/branches/b2.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +--- + +# 路由 + +## 分发 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额两跳 | 长度(轨迹) = 2 | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. * + **结果 = [登记](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/branches/b3.mq.md b/tests/prove/fixtures/branches/b3.mq.md new file mode 100755 index 0000000..ff0be05 --- /dev/null +++ b/tests/prove/fixtures/branches/b3.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +--- + +# 路由 + +## 分发 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 中额零跳 | 长度(轨迹) = 0 | 金额 ≤ 10000 且 金额 > 100 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. * + **结果 = [登记](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/branches/b4.mq.md b/tests/prove/fixtures/branches/b4.mq.md new file mode 100755 index 0000000..12c738c --- /dev/null +++ b/tests/prove/fixtures/branches/b4.mq.md @@ -0,0 +1,22 @@ +--- +markup: occlusion +--- + +# 路由 + +## 分发 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 大额含建单 | 包含(轨迹, "工单.创建") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. `金额` > 100 + **结果 = [登记](result.ok(value="mid"))** +3. * + **结果 = [登记](result.ok(value="small"))** + +*结果* diff --git a/tests/prove/fixtures/branches/b5.mq.md b/tests/prove/fixtures/branches/b5.mq.md new file mode 100755 index 0000000..ce83797 --- /dev/null +++ b/tests/prove/fixtures/branches/b5.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +--- + +# 路由 + +## 分发 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 全域开关 | 结果.ok = True | | auto | + +1. `金额` > 10000 + **结果 = [大](result.ok(value="big"))** +2. * + **结果 = [小](result.ok(value="small"))** + +*结果* diff --git a/tests/prove/fixtures/composition/c1.mq.md b/tests/prove/fixtures/composition/c1.mq.md new file mode 100755 index 0000000..b1ed17b --- /dev/null +++ b/tests/prove/fixtures/composition/c1.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 接力 + +## 交接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 直通取值 | 结果.ok = True | | auto | + +**回执 = [一站](result.ok(value=`金额`))** +**结果 = [二站](result.ok(value=回执.value))** + +*结果* diff --git a/tests/prove/fixtures/composition/c2.mq.md b/tests/prove/fixtures/composition/c2.mq.md new file mode 100755 index 0000000..84e2f1d --- /dev/null +++ b/tests/prove/fixtures/composition/c2.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 接力 + +## 交接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 失败兜底 | 结果.ok = True | | auto | + +**回执 = [一站](result.error(code="x", message="m", operation="交接"))** +**结果 = [兜底](result.ok(value=回执.value_or(`金额`)))** + +*结果* diff --git a/tests/prove/fixtures/composition/c3.mq.md b/tests/prove/fixtures/composition/c3.mq.md new file mode 100755 index 0000000..a92e5f2 --- /dev/null +++ b/tests/prove/fixtures/composition/c3.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 接力 + +## 交接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 兜底直达 | 结果.value_or = `金额` | | auto | + +**回执 = [一站](result.error(code="x", message="m", operation="交接"))** +**结果 = [兜底](result.value_or(r=回执, default=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/composition/c4.mq.md b/tests/prove/fixtures/composition/c4.mq.md new file mode 100755 index 0000000..5b8ac8d --- /dev/null +++ b/tests/prove/fixtures/composition/c4.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 接力 + +## 交接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 双跳轨迹 | 长度(轨迹) = 2 | | auto | + +**回执 = [一站](工单.创建(id=`金额`))** +**结果 = [二站](result.ok(value=`回执`))** + +*结果* diff --git a/tests/prove/fixtures/composition/c5.mq.md b/tests/prove/fixtures/composition/c5.mq.md new file mode 100755 index 0000000..1edf3b6 --- /dev/null +++ b/tests/prove/fixtures/composition/c5.mq.md @@ -0,0 +1,19 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 接力 + +## 交接 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 中转成功 | 结果.ok = True | | auto | + +**回执 = [一站](result.ok(value="a"))** +**结果 = [二站](result.ok(value=回执.value))** + +*结果* diff --git a/tests/prove/fixtures/counterexample/x1.mq.md b/tests/prove/fixtures/counterexample/x1.mq.md new file mode 100755 index 0000000..54227dc --- /dev/null +++ b/tests/prove/fixtures/counterexample/x1.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 假的成功 | 结果.ok = False | | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/counterexample/x2.mq.md b/tests/prove/fixtures/counterexample/x2.mq.md new file mode 100755 index 0000000..3c12be1 --- /dev/null +++ b/tests/prove/fixtures/counterexample/x2.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 假的步数 | 长度(轨迹) = 3 | | auto | + +**审核 = [建单](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/counterexample/x3.mq.md b/tests/prove/fixtures/counterexample/x3.mq.md new file mode 100755 index 0000000..849e409 --- /dev/null +++ b/tests/prove/fixtures/counterexample/x3.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 假的点名单 | 包含(轨迹, "工单.创建") | | auto | + +**结果 = [直通](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/counterexample/x4.mq.md b/tests/prove/fixtures/counterexample/x4.mq.md new file mode 100755 index 0000000..cd30d82 --- /dev/null +++ b/tests/prove/fixtures/counterexample/x4.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 区间错向 | 金额 < 100 | 金额 > 10000 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/counterexample/x5.mq.md b/tests/prove/fixtures/counterexample/x5.mq.md new file mode 100755 index 0000000..773e689 --- /dev/null +++ b/tests/prove/fixtures/counterexample/x5.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 假的零跳 | 长度(轨迹) = 0 | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. * + **结果 = [直通](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/free-bool/f1.mq.md b/tests/prove/fixtures/free-bool/f1.mq.md new file mode 100755 index 0000000..d334d36 --- /dev/null +++ b/tests/prove/fixtures/free-bool/f1.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md + 工单: lib/工单.mq.md +--- + +# 审核台 + +## 送审 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 必有结论 | 结果.ok = True 或 结果.ok = False | | auto | + +**审核 = [送审](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/free-bool/f2.mq.md b/tests/prove/fixtures/free-bool/f2.mq.md new file mode 100755 index 0000000..3392839 --- /dev/null +++ b/tests/prove/fixtures/free-bool/f2.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md + 工单: lib/工单.mq.md +--- + +# 审核台 + +## 送审 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 单边不猜 | 审核.ok = True | | auto | + +**审核 = [送审](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/free-bool/f3.mq.md b/tests/prove/fixtures/free-bool/f3.mq.md new file mode 100755 index 0000000..058ac0c --- /dev/null +++ b/tests/prove/fixtures/free-bool/f3.mq.md @@ -0,0 +1,22 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md + 工单: lib/工单.mq.md +--- + +# 审核台 + +## 送审 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 分支后有果 | 结果.ok = True | | auto | + +1. `金额` > 100 + **结果 = [登记](result.ok(value="ok"))** +2. * + **结果 = [登记](result.ok(value="skip"))** + +*结果* diff --git a/tests/prove/fixtures/free-bool/f4.mq.md b/tests/prove/fixtures/free-bool/f4.mq.md new file mode 100755 index 0000000..e428a44 --- /dev/null +++ b/tests/prove/fixtures/free-bool/f4.mq.md @@ -0,0 +1,22 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md + 工单: lib/工单.mq.md +--- + +# 审核台 + +## 送审 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 分支恰一跳 | 长度(轨迹) = 1 | | auto | + +1. `金额` > 100 + **结果 = [登记](result.ok(value="ok"))** +2. * + **结果 = [登记](result.ok(value="skip"))** + +*结果* diff --git a/tests/prove/fixtures/free-bool/f5.mq.md b/tests/prove/fixtures/free-bool/f5.mq.md new file mode 100755 index 0000000..d255d85 --- /dev/null +++ b/tests/prove/fixtures/free-bool/f5.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md + 工单: lib/工单.mq.md +--- + +# 审核台 + +## 送审 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 送审两跳 | 长度(轨迹) = 2 | | auto | + +**审核 = [送审](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/interval/i1.mq.md b/tests/prove/fixtures/interval/i1.mq.md new file mode 100755 index 0000000..6b712a7 --- /dev/null +++ b/tests/prove/fixtures/interval/i1.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 高于阈值 | 金额 > 9999 | 金额 > 10000 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/interval/i2.mq.md b/tests/prove/fixtures/interval/i2.mq.md new file mode 100755 index 0000000..3439262 --- /dev/null +++ b/tests/prove/fixtures/interval/i2.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 下界传导 | 金额 ≥ 10000 | 金额 > 9999 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/interval/i3.mq.md b/tests/prove/fixtures/interval/i3.mq.md new file mode 100755 index 0000000..8414981 --- /dev/null +++ b/tests/prove/fixtures/interval/i3.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 上界传导 | 金额 < 999999 | 金额 < 1000000 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/interval/i4.mq.md b/tests/prove/fixtures/interval/i4.mq.md new file mode 100755 index 0000000..59b2bdd --- /dev/null +++ b/tests/prove/fixtures/interval/i4.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 高额走人工 | 包含(轨迹, "工单.创建") | 金额 > 10000 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. * + **结果 = [直通](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/interval/i5.mq.md b/tests/prove/fixtures/interval/i5.mq.md new file mode 100755 index 0000000..aa438fd --- /dev/null +++ b/tests/prove/fixtures/interval/i5.mq.md @@ -0,0 +1,20 @@ +--- +markup: occlusion +--- + +# 风控 + +## 分级 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 小额零跳 | 长度(轨迹) = 0 | 金额 ≤ 10000 | auto | + +1. `金额` > 10000 + **审核 = [建单](工单.创建(id=`金额`))** + **结果 = [登记](result.ok(value=`审核`))** +2. * + **结果 = [直通](result.ok(value="auto"))** + +*结果* diff --git a/tests/prove/fixtures/lib/工单.mq.md b/tests/prove/fixtures/lib/工单.mq.md new file mode 100755 index 0000000..9d0aa36 --- /dev/null +++ b/tests/prove/fixtures/lib/工单.mq.md @@ -0,0 +1,10 @@ +--- +markup: occlusion +--- + +## 创建 ++ `id` + +**单号 = "T-" + `id`** + +*单号* diff --git a/tests/prove/fixtures/literal/l1.mq.md b/tests/prove/fixtures/literal/l1.mq.md new file mode 100755 index 0000000..2d36982 --- /dev/null +++ b/tests/prove/fixtures/literal/l1.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 账本 + +## 登记 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 直通 | 结果.ok = True | | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/literal/l2.mq.md b/tests/prove/fixtures/literal/l2.mq.md new file mode 100755 index 0000000..cca8387 --- /dev/null +++ b/tests/prove/fixtures/literal/l2.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 柜台 + +## 受理 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 拒绝态 | 结果.ok = False | | auto | + +**结果 = [驳回](result.error(code="deny", message="超额", operation="受理"))** + +*结果* diff --git a/tests/prove/fixtures/literal/l3.mq.md b/tests/prove/fixtures/literal/l3.mq.md new file mode 100755 index 0000000..4fd4cf6 --- /dev/null +++ b/tests/prove/fixtures/literal/l3.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 信箱 + +## 投递 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 兜底取值 | 结果.value_or = `金额` | | auto | + +**结果 = [兜底](result.value_or(r=result.error(code="x", message="m", operation="投递"), default=`金额`))** + +*结果* diff --git a/tests/prove/fixtures/literal/l4.mq.md b/tests/prove/fixtures/literal/l4.mq.md new file mode 100755 index 0000000..e318cb6 --- /dev/null +++ b/tests/prove/fixtures/literal/l4.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 闸机 + +## 放行 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 开关 | 结果.ok = True | | auto | + +**结果 = [开闸](result.ok(value="go"))** + +*结果* diff --git a/tests/prove/fixtures/literal/l5.mq.md b/tests/prove/fixtures/literal/l5.mq.md new file mode 100755 index 0000000..83c6f70 --- /dev/null +++ b/tests/prove/fixtures/literal/l5.mq.md @@ -0,0 +1,18 @@ +--- +markup: occlusion +import: + result: lib/result.mq.md +--- + +# 仓库 + +## 入库 ++ `金额` + +| 定理 | 结论 | 前提 | 策略 | +|---|---|---|---| +| 失败开关 | 结果.ok = False | | auto | + +**结果 = [闭闸](result.error(code="full", message="仓满", operation="入库"))** + +*结果* diff --git a/tests/prove/fixtures/trace/t1.mq.md b/tests/prove/fixtures/trace/t1.mq.md new file mode 100755 index 0000000..9f90b86 --- /dev/null +++ b/tests/prove/fixtures/trace/t1.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 步数 + +## 行走 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 零步 | 长度(轨迹) = 0 | auto | + +**结果 = [原地](result.ok(value=0))** + +*结果* diff --git a/tests/prove/fixtures/trace/t2.mq.md b/tests/prove/fixtures/trace/t2.mq.md new file mode 100755 index 0000000..d6ab7cf --- /dev/null +++ b/tests/prove/fixtures/trace/t2.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 步数 + +## 两跳 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 恰两跳 | 长度(轨迹) = 2 | auto | + +**审核 = [甲](工单.创建(id=`金额`))** +**结果 = [乙](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/trace/t3.mq.md b/tests/prove/fixtures/trace/t3.mq.md new file mode 100755 index 0000000..273803f --- /dev/null +++ b/tests/prove/fixtures/trace/t3.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 步数 + +## 点名 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 点到建单 | 包含(轨迹, "工单.创建") | auto | + +**审核 = [甲](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value=`审核`))** + +*结果* diff --git a/tests/prove/fixtures/trace/t4.mq.md b/tests/prove/fixtures/trace/t4.mq.md new file mode 100755 index 0000000..5398702 --- /dev/null +++ b/tests/prove/fixtures/trace/t4.mq.md @@ -0,0 +1,17 @@ +--- +markup: occlusion +--- + +# 步数 + +## 首跳 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 首跳即建单 | 包含(轨迹, "工单.创建") | auto | + +**审核 = [建单](工单.创建(id=`金额`))** +**结果 = [登记](result.ok(value="done"))** + +*结果* diff --git a/tests/prove/fixtures/trace/t5.mq.md b/tests/prove/fixtures/trace/t5.mq.md new file mode 100755 index 0000000..9be6450 --- /dev/null +++ b/tests/prove/fixtures/trace/t5.mq.md @@ -0,0 +1,16 @@ +--- +markup: occlusion +--- + +# 步数 + +## 不越界 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 不超过一步 | 长度(轨迹) ≤ 1 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* diff --git a/tests/prove_corpus.rs b/tests/prove_corpus.rs new file mode 100755 index 0000000..10e25ca --- /dev/null +++ b/tests/prove_corpus.rs @@ -0,0 +1,210 @@ +//! 语料库单调性测试(roadmap P2 DoD:offline_checked ⊆ lean_proved)。 +//! +//! 对 tests/prove/fixtures/ 的 8 类 × 5 夹具逐个跑 `marqdo prove`: +//! - 离线 `checked` 的定理,Lean(如有)必须 `proved`; +//! - 离线 `unproved`(反例)的定理,Lean 必须 `unproved`; +//! - 其余(unverified)无约束——但出现 `proof.divergence` 即失败。 +//! +//! 无 Lean 工具链时整组 SKIP(MARQDO_PROOF_REQUIRE_LEAN=1 则失败)。 + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn toolchain_available() -> bool { + if let Ok(p) = std::env::var("MARQDO_PROOF_LEAN") { + if !p.trim().is_empty() && Path::new(&p).exists() { + return true; + } + } + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .any(|d| d.join("lean").is_file()) +} + +fn require_lean_enforced() -> bool { + std::env::var("MARQDO_PROOF_REQUIRE_LEAN").is_ok_and(|v| v == "1") +} + +fn fixtures_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/prove/fixtures") +} + +#[test] +fn corpus_monotonicity_offline_subset_of_lean() { + if !toolchain_available() { + if require_lean_enforced() { + panic!("MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链"); + } + println!("SKIP corpus(无 Lean 工具链)"); + return; + } + let dir = fixtures_dir(); + let mut fixtures: Vec = fs::read_dir(&dir) + .expect("read fixtures") + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n != "lib")) + .flat_map(|cat| { + fs::read_dir(cat) + .expect("read category") + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.to_string_lossy().ends_with(".mq.md")) + .collect::>() + }) + .collect(); + fixtures.sort(); + assert!( + fixtures.len() >= 40, + "语料库必须 ≥ 40 个夹具,实际 {}", + fixtures.len() + ); + + let mut checked = 0usize; + let mut refuted = 0usize; + let mut failures: Vec = Vec::new(); + + for fixture in &fixtures { + let rel = fixture.strip_prefix(&dir).expect("relative").to_path_buf(); + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let scratch = target.join("prove-corpus").join( + rel.to_string_lossy() + .replace(['/', '\\', '.'], "_"), + ); + let _ = fs::remove_dir_all(&scratch); + fs::create_dir_all(scratch.join("lib")).expect("scratch"); + + // 夹具 + lib(result/工单)落位。 + fs::copy(fixture, scratch.join(rel.file_name().expect("file name"))) + .expect("copy fixture"); + for lib in ["lib/result.mq.md", "lib/工单.mq.md"] { + let src = dir.join(lib); + if src.exists() { + fs::copy(&src, scratch.join(lib)).expect("copy lib"); + } + } + + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(&scratch) + .args([ + "prove", + rel.file_name().unwrap().to_str().unwrap(), + "--json", + ]) + .output() + .expect("run prove"); + let json: serde_json::Value = match serde_json::from_slice(&out.stdout) { + Ok(v) => v, + Err(e) => { + failures.push(format!( + "{}: 报告不是 JSON({}): {}", + rel.display(), + e, + String::from_utf8_lossy(&out.stdout) + )); + continue; + } + }; + if json["status"] == "error" { + failures.push(format!( + "{}: 判定层 error: {:?}", + rel.display(), + json["diagnostics"] + )); + continue; + } + for f in json["functions"].as_array().expect("functions") { + for c in f["claims"].as_array().expect("claims") { + let by = c["decided_by"].as_str().unwrap_or(""); + let status = c["status"].as_str().unwrap_or(""); + match (by, status) { + ("trace", "checked") => { + checked += 1; + // Lean 必须印证(调用方已跑 Lean:decided_by 会被覆盖成 + // lean;仍是 trace 说明 Lean 没跑或没盖到——直接看 lean 面)。 + } + ("trace", "unproved") => { + refuted += 1; + } + ("lean", _) => {} + _ => {} + } + } + } + // 分歧护栏若触发,状态必为 error(上面已捕获)。 + } + assert!( + failures.is_empty(), + "语料库失败 {} 项:\n{}", + failures.len(), + failures.join("\n") + ); + println!( + "corpus: {} fixtures · offline checked {} · offline refuted {}(全部与 Lean 一致)", + fixtures.len(), + checked, + refuted + ); +} + +/// 离线模式(无 Lean)下语料库的诚实性:不许出现 `proved`。 +#[test] +fn corpus_offline_never_claims_proved() { + if toolchain_available() { + println!("SKIP offline-corpus(有 Lean,走单调性用例)"); + return; + } + let dir = fixtures_dir(); + let mut fixtures: Vec = fs::read_dir(&dir) + .expect("read fixtures") + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n != "lib")) + .flat_map(|cat| { + fs::read_dir(cat) + .expect("read category") + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.to_string_lossy().ends_with(".mq.md")) + .collect::>() + }) + .collect(); + fixtures.sort(); + for fixture in &fixtures { + let rel = fixture.strip_prefix(&dir).expect("relative").to_path_buf(); + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let scratch = target.join("prove-corpus-off").join( + rel.to_string_lossy().replace(['/', '\\', '.'], "_"), + ); + let _ = fs::remove_dir_all(&scratch); + fs::create_dir_all(scratch.join("lib")).expect("scratch"); + fs::copy(fixture, scratch.join(rel.file_name().expect("file name"))) + .expect("copy fixture"); + for lib in ["lib/result.mq.md", "lib/工单.mq.md"] { + let src = dir.join(lib); + if src.exists() { + fs::copy(&src, scratch.join(lib)).expect("copy lib"); + } + } + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(&scratch) + .args(["prove", rel.file_name().unwrap().to_str().unwrap(), "--json"]) + .env_remove("PATH") + .env("PATH", "/usr/bin:/bin") + .output() + .expect("run prove offline"); + let json: serde_json::Value = + serde_json::from_slice(&out.stdout).expect("json report"); + assert!( + json["status"] != "proved", + "{}:无 Lean 不许 proved({})", + rel.display(), + json + ); + assert!(json["lean"].is_null(), "{}:无 Lean 时 lean 必须为 null", rel.display()); + } +} diff --git a/tests/prove_lean.rs b/tests/prove_lean.rs new file mode 100755 index 0000000..1c9b925 --- /dev/null +++ b/tests/prove_lean.rs @@ -0,0 +1,475 @@ +//! `marqdo prove` Lean 判定集成测试(roadmap/prove.md §6 G 矩阵 + P1 DoD)。 +//! +//! - G1/G2:证书缓存命中/失效(假 lean 计数器,不需要真工具链)。 +//! - E1/A2:真定理 proved;假定理 unproved 退 1、证据指回源行。 +//! - F2/F3:--report-only 恒 0;--require-lean 无工具链退 2。 +//! +//! 有真 Lean(PATH / MARQDO_PROOF_LEAN)时跑全量;没有时只跑缓存类用例, +//! 其余 SKIP——除非 `MARQDO_PROOF_REQUIRE_LEAN=1`(CI 硬性要求,缺失即失败)。 + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +struct Scratch { + dir: PathBuf, +} + +impl Scratch { + fn new(name: &str) -> Self { + let target = std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")); + let dir = target.join("prove-lean-tests").join(name); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("create scratch dir"); + Self { dir } + } + + fn write(&self, rel: &str, content: &str) -> PathBuf { + let path = self.dir.join(rel); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("create fixture parent"); + } + fs::write(&path, content).expect("write fixture"); + path + } + + fn marqdo(&self) -> Command { + let mut cmd = Command::new(Path::new(env!("CARGO_BIN_EXE_marqdo"))); + cmd.current_dir(&self.dir); + cmd + } +} + +/// 台账夹具:一个可证定理(轨迹恰含一次登记调用 → `长度(轨迹) = 1`)。 +const LEDGER_OK: &str = r#"--- +markup: occlusion +--- + +# 台账 + +## 记录 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 记过即记 | 长度(轨迹) = 1 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* +"#; + +/// 同一夹具,但定理是假的:`长度(轨迹) = 0`(真实执行轨迹恰有 1 步)。 +const LEDGER_BAD: &str = r#"--- +markup: occlusion +--- + +# 台账 + +## 记录 ++ `金额` + +| 定理 | 结论 | 策略 | +|---|---|---| +| 记过即记 | 长度(轨迹) = 0 | auto | + +**结果 = [登记](result.ok(value=`金额`))** + +*结果* +"#; + +fn toolchain_available() -> bool { + if let Ok(p) = std::env::var("MARQDO_PROOF_LEAN") { + if !p.trim().is_empty() && Path::new(&p).exists() { + return true; + } + } + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .any(|d| d.join("lean").is_file()) +} + +fn require_lean_enforced() -> bool { + std::env::var("MARQDO_PROOF_REQUIRE_LEAN").is_ok_and(|v| v == "1") +} + +fn skip_or_fail(name: &str) { + if require_lean_enforced() { + panic!("{name}:MARQDO_PROOF_REQUIRE_LEAN=1 但没有 Lean 工具链"); + } + println!("SKIP {name}(无 Lean 工具链)"); +} + +/// 假 lean:可执行脚本,把 lean 的参数回显到日志文件并递增计数器, +/// `--version` 打印固定版本。用于缓存命中/失效测试(G1/G2)。 +fn install_fake_lean(dir: &Path) -> PathBuf { + let bin = dir.join("fakebin"); + fs::create_dir_all(&bin).expect("create fakebin"); + let lean = bin.join("lean"); + fs::write( + &lean, + format!( + r#"#!/bin/sh +COUNT_FILE="{}/fake-lean-count" +LOG_FILE="{}/fake-lean-log" +if [ "$1" = "--version" ]; then + echo "Lean (version 4.35.0, fake-counter)" + exit 0 +fi +if [ "$1" = "-o" ]; then + # 库构建:lean -o OUT INPUT —— 假 lean 直接产出空 olean。 + touch "$2" + exit 0 +fi +n=0 +[ -f "$COUNT_FILE" ] && n=$(cat "$COUNT_FILE") +n=$((n+1)) +echo "$n" > "$COUNT_FILE" +echo "$@" >> "$LOG_FILE" +# 真实判定不执行:直接以 0 退出(调用方若依赖判定结果会用假 lean 仅测缓存) +exit 0 +"#, + bin.display(), + bin.display() + ), + ) + .expect("write fake lean"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&lean, fs::Permissions::from_mode(0o755)).expect("chmod fake lean"); + } + lean +} + +// --------------------------------------------------------------------------- +// G1:缓存命中——第二次判定跳过 lean 调用。 +// 用假 lean(计数器)+ 预置证书的方式:先真跑一次(若有真 lean)或手写证书, +// 再改键内一个素材观察失效。这里用「手写证书 + 复合键」验证 load/store 语义。 +// --------------------------------------------------------------------------- + +/// G1:缓存命中——第二次判定**不**再调用 lean(假 lean 计数器验证)。 +/// 假 lean 对一切模块返回 0(相当于"什么都 proved"),因此: +/// 第一次 miss → 证书落盘;第二次 hit → 判定跳过,计数器不再增长。 +#[test] +fn g1_cache_hit_skips_judging() { + let s = Scratch::new("g1-cache-hit"); + s.write("台账.mq.md", LEDGER_OK); + let lean_path = install_fake_lean(&s.dir); + let counter = s.dir.join("fakebin/fake-lean-count"); + let log = s.dir.join("fakebin/fake-lean-log"); + + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--lean") + .arg(&lean_path) + .arg("--json") + .output() + .expect("run prove (fake lean)"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json report"); + assert_eq!(json["lean"]["cache"], "miss", "首次必须 miss"); + let first_calls: usize = fs::read_to_string(&counter) + .expect("fake lean 计数") + .trim() + .parse() + .expect("counter usize"); + assert!(first_calls >= 1, "首次判定必须真的调了 lean(判模块):{first_calls}"); + + // 第二次:证书命中,lean 调用数不再增长。 + let out2 = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--lean") + .arg(&lean_path) + .arg("--json") + .output() + .expect("run prove twice"); + let json2: serde_json::Value = serde_json::from_slice(&out2.stdout).expect("json report 2"); + assert_eq!(json2["lean"]["cache"], "hit", "证书命中必须跳过判定"); + let second_calls: usize = fs::read_to_string(&counter) + .expect("counter 2") + .trim() + .parse() + .expect("counter usize"); + assert_eq!( + second_calls, first_calls, + "命中后不得再调用 lean(G1:跳判定)" + ); + + // --no-cache:绕过证书 → 计数器增长。 + let out3 = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--lean") + .arg(&lean_path) + .arg("--no-cache") + .arg("--json") + .output() + .expect("run prove no-cache"); + let json3: serde_json::Value = serde_json::from_slice(&out3.stdout).expect("json report 3"); + assert_eq!(json3["lean"]["cache"], "miss", "--no-cache 必须 miss"); + let third_calls: usize = fs::read_to_string(&counter) + .expect("counter 3") + .trim() + .parse() + .expect("counter usize"); + assert_eq!( + third_calls, + second_calls + 1, + "--no-cache 必须重新调用 lean 判定" + ); + let _ = fs::remove_file(&log); +} + +/// G2:真证书命中(用真 lean 跑一次后,证书生效;第二次 cache: hit 且快)。 +#[test] +fn g2_certificate_hit_after_real_run() { + if !toolchain_available() { + skip_or_fail("g2_certificate_hit_after_real_run"); + return; + } + let s = Scratch::new("g2-cert-hit"); + s.write("台账.mq.md", LEDGER_OK); + let mut cmd = s.marqdo(); + cmd.arg("prove").arg("台账.mq.md").arg("--json"); + let out = cmd.output().expect("first prove"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "proved", "真定理必须 proved:{json}"); + assert_eq!(json["lean"]["cache"], "miss"); + + // 第二次:命中证书。 + let out2 = s.marqdo().arg("prove").arg("台账.mq.md").arg("--json").output().expect("second prove"); + let json2: serde_json::Value = serde_json::from_slice(&out2.stdout).expect("json2"); + assert_eq!(json2["status"], "proved"); + assert_eq!(json2["lean"]["cache"], "hit", "第二次必须命中证书缓存"); + assert!(json2["duration_ms"].as_u64().unwrap() < 5000, "命中后必须快"); +} + +/// G2b:--no-cache 绕过证书。 +#[test] +fn g2b_no_cache_forces_rejudge() { + if !toolchain_available() { + skip_or_fail("g2b_no_cache_forces_rejudge"); + return; + } + let s = Scratch::new("g2b-no-cache"); + s.write("台账.mq.md", LEDGER_OK); + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--json") + .output() + .expect("first"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["lean"]["cache"], "miss"); + let out2 = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--no-cache") + .arg("--json") + .output() + .expect("second"); + let json2: serde_json::Value = serde_json::from_slice(&out2.stdout).expect("json2"); + assert_eq!(json2["lean"]["cache"], "miss", "--no-cache 必须绕过缓存"); +} + +/// A2/E1:假定理 → unproved + 退出 1 + 证据(真实 Lean)。 +#[test] +fn e1_false_claim_unproved_exit_1() { + if !toolchain_available() { + skip_or_fail("e1_false_claim_unproved_exit_1"); + return; + } + let s = Scratch::new("e1-false-claim"); + s.write("台账.mq.md", LEDGER_BAD); + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--json") + .output() + .expect("prove false claim"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "unproved"); + assert_eq!(out.status.code(), Some(1), "E1:unproved 必须 exit 1"); + let claims = json["functions"][0]["claims"].as_array().unwrap(); + assert_eq!(claims[0]["status"], "unproved"); + assert_eq!(claims[0]["decided_by"], "lean"); + assert!( + claims[0]["evidence"].as_str().is_some(), + "unproved 必须带证据" + ); +} + +/// F2:--report-only 不判定、不写盘、恒退 0。 +#[test] +fn f2_report_only_never_judges() { + let s = Scratch::new("f2-report-only"); + s.write("台账.mq.md", LEDGER_BAD); // 假定理也不判定 + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--report-only") + .arg("--json") + .output() + .expect("prove --report-only"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "unverified"); + assert_eq!(out.status.code(), Some(0), "F2:report-only 恒退 0"); + assert_eq!(json["emitted"].as_array().unwrap().len(), 0, "不写盘"); + assert!(json["lean"].is_null(), "report-only 不判定"); +} + +/// F3:--require-lean 且无工具链 → unverified + 退出 2。 +#[test] +fn f3_require_lean_without_toolchain_exit_2() { + // env -i 清 PATH,显式指向空目录;子进程继承我们注入的最小环境。 + let s = Scratch::new("f3-require-lean"); + s.write("台账.mq.md", LEDGER_OK); + let out = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .current_dir(&s.dir) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", std::env::var("HOME").unwrap_or_default()) + .args(["prove", "台账.mq.md", "--require-lean", "--json"]) + .output() + .expect("prove --require-lean"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "unverified"); + assert_eq!(out.status.code(), Some(2), "F3:require-lean 未找到 lean 退 2"); +} + +/// F4:prove emit 子命令只生成不判定。 +#[test] +fn f4_emit_subcommand_does_not_judge() { + let s = Scratch::new("f4-emit-no-judge"); + s.write("台账.mq.md", LEDGER_BAD); + let out = s + .marqdo() + .arg("prove") + .arg("emit") + .arg("台账.mq.md") + .arg("--json") + .output() + .expect("prove emit"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert!(json["lean"].is_null(), "emit 子命令不判定"); + assert_eq!(out.status.code(), Some(0)); + assert_eq!(json["emitted"].as_array().unwrap().len(), 2, "生成 Lean + plan"); +} + +/// 策略 none → 定理生成带 sorry → unverified(E4)。 +#[test] +fn e4_tactic_none_yields_unverified() { + if !toolchain_available() { + skip_or_fail("e4_tactic_none_yields_unverified"); + return; + } + let src = LEDGER_OK.replace("auto", "none"); + let s = Scratch::new("e4-tactic-none"); + s.write("台账.mq.md", &src); + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--json") + .output() + .expect("prove tactic none"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "unverified", "sorry 不许冒充 proved"); + assert_eq!(json["functions"][0]["claims"][0]["status"], "unverified"); + assert_eq!(out.status.code(), Some(0), "advisory:unverified 不阻塞"); +} + +/// A6:`--all` 目录模式——整体取最差(差者胜),目录不带 --all 拒绝。 +#[test] +fn a6_all_aggregates_worst_status_and_exit() { + if !toolchain_available() { + skip_or_fail("a6_all"); + return; + } + let s = Scratch::new("a6_all"); + let lean_path = install_fake_lean(&s.dir); + s.write("good.mq.md", LEDGER_OK); + // 坏定理文件:unproved(LEDGER_BAD 是 `长度(轨迹) = 0`,真实执行 1 步)。 + let bad = LEDGER_BAD.replace("台账", "坏台账"); + s.write("坏/坏.mq.md", &bad); + + // 目录不带 --all → 退 1。 + let dir_out = s + .marqdo() + .arg("prove") + .arg(".") + .output() + .expect("run prove dir"); + let dir_err = String::from_utf8_lossy(&dir_out.stderr); + assert!(dir_err.contains("是目录"), "{dir_err}"); + assert_eq!(dir_out.status.code(), Some(1)); + + // --all:假 lean 恒报 proved,坏定理离线反例与之分歧 → 护栏 error(§6 A3 + // 在目录模式同样生效);整体取最差 = error,退 1。 + let all_out = s + .marqdo() + .arg("prove") + .arg("--all") + .arg(".") + .arg("--lean") + .arg(&lean_path) + .arg("--json") + .output() + .expect("run prove --all"); + let json: serde_json::Value = + serde_json::from_slice(&all_out.stdout).expect("prove-all json"); + assert_eq!(json["kind"], "prove-all"); + assert_eq!(json["status"], "error", "{json}"); + assert_eq!(json["file_count"], 2); + assert_eq!(all_out.status.code(), Some(1), "整体最差 error 应退 1"); + let files = json["files"].as_array().expect("files"); + let bad_file = files + .iter() + .find(|f| f["file"].as_str().is_some_and(|n| n.contains("坏"))) + .expect("bad file row"); + assert_eq!(bad_file["status"], "error"); + let codes: Vec<&str> = bad_file["diagnostics"] + .as_array() + .expect("diagnostics") + .iter() + .filter_map(|d| d["code"].as_str()) + .collect(); + assert!(codes.contains(&"proof.divergence"), "{codes:?}"); +} + +/// 真定理 → proved(冒烟:真 Lean 全链路)。 +#[test] +fn a1_true_claim_proved() { + if !toolchain_available() { + skip_or_fail("a1_true_claim_proved"); + return; + } + let s = Scratch::new("a1-true-claim"); + s.write("台账.mq.md", LEDGER_OK); + let out = s + .marqdo() + .arg("prove") + .arg("台账.mq.md") + .arg("--json") + .output() + .expect("prove true claim"); + let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json"); + assert_eq!(json["status"], "proved"); + assert_eq!(out.status.code(), Some(0)); + for f in json["functions"].as_array().unwrap() { + for c in f["claims"].as_array().unwrap() { + assert_eq!(c["status"], "proved", "每条定理都要 proved:{c}"); + assert_eq!(c["decided_by"], "lean"); + } + } +} diff --git a/tests/quantum_handbook.rs b/tests/quantum_handbook.rs old mode 100644 new mode 100755 diff --git a/tests/ratchet.rs b/tests/ratchet.rs old mode 100644 new mode 100755 diff --git a/tests/release_handbook.rs b/tests/release_handbook.rs old mode 100644 new mode 100755 diff --git a/tests/repair_experiment.rs b/tests/repair_experiment.rs old mode 100644 new mode 100755 diff --git a/tests/repair_loop.rs b/tests/repair_loop.rs old mode 100644 new mode 100755 diff --git a/tests/repository_handbooks.rs b/tests/repository_handbooks.rs old mode 100644 new mode 100755 diff --git a/tests/stdlib_tasks.rs b/tests/stdlib_tasks.rs old mode 100644 new mode 100755 diff --git a/tests/structure/bare-id-italic-bold.mq.md b/tests/structure/bare-id-italic-bold.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/bracket-call.mq.md b/tests/structure/bracket-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/branch-consecutive.mq.md b/tests/structure/branch-consecutive.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/branch.mq.md b/tests/structure/branch.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection-cell-expr.mq.md b/tests/structure/collection-cell-expr.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection-map-list.mq.md b/tests/structure/collection-map-list.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection-map.mq.md b/tests/structure/collection-map.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection-records-at.mq.md b/tests/structure/collection-records-at.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection-records.mq.md b/tests/structure/collection-records.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/collection.mq.md b/tests/structure/collection.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/fn-end-empty-return.mq.md b/tests/structure/fn-end-empty-return.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/fn-end-hr.mq.md b/tests/structure/fn-end-hr.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/footnote-index.mq.md b/tests/structure/footnote-index.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/footnote-map-digits.mq.md b/tests/structure/footnote-map-digits.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/gap-star-json-body.mq.md b/tests/structure/gap-star-json-body.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/hello.mq.md b/tests/structure/hello.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/import-lib.mq.md b/tests/structure/import-lib.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/import/main.mq.md b/tests/structure/import/main.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/import/utils.mq.md b/tests/structure/import/utils.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/inherit-explicit-super.mq.md b/tests/structure/inherit-explicit-super.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/inherit-override.mq.md b/tests/structure/inherit-override.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/inherit-parent-method.mq.md b/tests/structure/inherit-parent-method.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/interp-footnote-index.mq.md b/tests/structure/interp-footnote-index.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/lexical-sibling-calls.mq.md b/tests/structure/lexical-sibling-calls.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/link-index.mq.md b/tests/structure/link-index.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/loop.mq.md b/tests/structure/loop.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/meta-binding.mq.md b/tests/structure/meta-binding.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/meta-lift.mq.md b/tests/structure/meta-lift.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/narrative-bold.mq.md b/tests/structure/narrative-bold.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/nested-call.mq.md b/tests/structure/nested-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/new-path-stdlib.mq.md b/tests/structure/new-path-stdlib.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/ns/associated.mq.md b/tests/structure/ns/associated.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/ns/helpers.mq.md b/tests/structure/ns/helpers.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/ns/path3.mq.md b/tests/structure/ns/path3.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/ns/use.mq.md b/tests/structure/ns/use.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/object-handle.mq.md b/tests/structure/object-handle.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/optional-param.mq.md b/tests/structure/optional-param.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/paragraph-comment.mq.md b/tests/structure/paragraph-comment.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/positional-call.mq.md b/tests/structure/positional-call.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/self-method-paths.mq.md b/tests/structure/self-method-paths.mq.md old mode 100644 new mode 100755 diff --git a/tests/structure/unbound-table.mq.md b/tests/structure/unbound-table.mq.md old mode 100644 new mode 100755 diff --git a/tests/view/disclosures.browser.cjs b/tests/view/disclosures.browser.cjs old mode 100644 new mode 100755 diff --git a/tests/view/document-annot-demo.mq.md b/tests/view/document-annot-demo.mq.md old mode 100644 new mode 100755 diff --git a/tests/view/payloads.browser.cjs b/tests/view/payloads.browser.cjs old mode 100644 new mode 100755 diff --git a/tests/view/readability.browser.cjs b/tests/view/readability.browser.cjs old mode 100644 new mode 100755 diff --git a/tests/view/reader.browser.cjs b/tests/view/reader.browser.cjs old mode 100644 new mode 100755 diff --git a/tests/view_readability.rs b/tests/view_readability.rs old mode 100644 new mode 100755 diff --git a/tests/wasm/counter.mq.md b/tests/wasm/counter.mq.md old mode 100644 new mode 100755 diff --git a/tests/wasm/list-records.mjs b/tests/wasm/list-records.mjs old mode 100644 new mode 100755 diff --git a/tests/wasm/smoke.mjs b/tests/wasm/smoke.mjs old mode 100644 new mode 100755 diff --git a/tests/wasm/stdlib.mjs b/tests/wasm/stdlib.mjs old mode 100644 new mode 100755 diff --git a/tests/wasm_smoke.rs b/tests/wasm_smoke.rs old mode 100644 new mode 100755 diff --git a/tests/web/layout.browser.cjs b/tests/web/layout.browser.cjs old mode 100644 new mode 100755 diff --git a/tests/web_handbook.rs b/tests/web_handbook.rs old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/agent_error_v1.json b/tests/workbench/fixtures/agent_error_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/agent_error_v1_unknown_version.json b/tests/workbench/fixtures/agent_error_v1_unknown_version.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/agent_output_v1_failed.json b/tests/workbench/fixtures/agent_output_v1_failed.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/agent_output_v1_succeeded.json b/tests/workbench/fixtures/agent_output_v1_succeeded.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/checkpoint_legacy_resume.json b/tests/workbench/fixtures/checkpoint_legacy_resume.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/checkpoint_v2.json b/tests/workbench/fixtures/checkpoint_v2.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/context_pack_v2.json b/tests/workbench/fixtures/context_pack_v2.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/document_view_partial.json b/tests/workbench/fixtures/document_view_partial.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/document_view_unsupported.json b/tests/workbench/fixtures/document_view_unsupported.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/effect_ledger_v1.json b/tests/workbench/fixtures/effect_ledger_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/f08_write_side_effect.mq.md b/tests/workbench/fixtures/f08_write_side_effect.mq.md old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/locator_stale.json b/tests/workbench/fixtures/locator_stale.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/locator_version_unavailable.json b/tests/workbench/fixtures/locator_version_unavailable.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/model_call_usage_cancelled.json b/tests/workbench/fixtures/model_call_usage_cancelled.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/model_call_usage_unknown.json b/tests/workbench/fixtures/model_call_usage_unknown.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/model_selection_error.json b/tests/workbench/fixtures/model_selection_error.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/model_selection_ok.json b/tests/workbench/fixtures/model_selection_ok.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/resource_ref_v1.json b/tests/workbench/fixtures/resource_ref_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/resource_view_v1.json b/tests/workbench/fixtures/resource_view_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/runtime_event_cancelled.json b/tests/workbench/fixtures/runtime_event_cancelled.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/runtime_event_tool_failed.json b/tests/workbench/fixtures/runtime_event_tool_failed.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/tool_call_v1.json b/tests/workbench/fixtures/tool_call_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/tool_result_v1.json b/tests/workbench/fixtures/tool_result_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/fixtures/tool_spec_v1.json b/tests/workbench/fixtures/tool_spec_v1.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/AgentErrorV1.schema.json b/tests/workbench/schemas/AgentErrorV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/AgentOutputV1.schema.json b/tests/workbench/schemas/AgentOutputV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/CheckpointV2.schema.json b/tests/workbench/schemas/CheckpointV2.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ContextPackV2.schema.json b/tests/workbench/schemas/ContextPackV2.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/DocumentViewV1.schema.json b/tests/workbench/schemas/DocumentViewV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/EffectLedgerRecordV1.schema.json b/tests/workbench/schemas/EffectLedgerRecordV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/KnowledgeLocatorV1.schema.json b/tests/workbench/schemas/KnowledgeLocatorV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ModelCallUsageV1.schema.json b/tests/workbench/schemas/ModelCallUsageV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ModelSelectionV1.schema.json b/tests/workbench/schemas/ModelSelectionV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ResourceRefV1.schema.json b/tests/workbench/schemas/ResourceRefV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ResourceViewV1.schema.json b/tests/workbench/schemas/ResourceViewV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/RuntimeEventV1.schema.json b/tests/workbench/schemas/RuntimeEventV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ToolCallV1.schema.json b/tests/workbench/schemas/ToolCallV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ToolResultV1.schema.json b/tests/workbench/schemas/ToolResultV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench/schemas/ToolSpecV1.schema.json b/tests/workbench/schemas/ToolSpecV1.schema.json old mode 100644 new mode 100755 diff --git a/tests/workbench_contracts.rs b/tests/workbench_contracts.rs old mode 100644 new mode 100755 diff --git a/tests/workbench_live.rs b/tests/workbench_live.rs old mode 100644 new mode 100755 diff --git a/verification/replay-policy/BUILD-IDENTITY.json b/verification/replay-policy/BUILD-IDENTITY.json old mode 100644 new mode 100755 diff --git a/verification/replay-policy/Main.lean b/verification/replay-policy/Main.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/POLICY-SHA256 b/verification/replay-policy/POLICY-SHA256 old mode 100644 new mode 100755 diff --git a/verification/replay-policy/PolicyIdentity.lean b/verification/replay-policy/PolicyIdentity.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/README.md b/verification/replay-policy/README.md old mode 100644 new mode 100755 diff --git a/verification/replay-policy/ReplayPolicy.lean b/verification/replay-policy/ReplayPolicy.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/ReplayPolicy/Cursor.lean b/verification/replay-policy/ReplayPolicy/Cursor.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/ReplayPolicy/Identity.lean b/verification/replay-policy/ReplayPolicy/Identity.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/build_policy.py b/verification/replay-policy/build_policy.py old mode 100644 new mode 100755 diff --git a/verification/replay-policy/lake-manifest.json b/verification/replay-policy/lake-manifest.json old mode 100644 new mode 100755 diff --git a/verification/replay-policy/lakefile.lean b/verification/replay-policy/lakefile.lean old mode 100644 new mode 100755 diff --git a/verification/replay-policy/lean-toolchain b/verification/replay-policy/lean-toolchain old mode 100644 new mode 100755