diff --git a/Cargo.lock b/Cargo.lock index cc963b5..c3f1a18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 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", @@ -1456,12 +1456,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", @@ -1469,9 +1468,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", @@ -1479,9 +1478,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", @@ -1492,9 +1491,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 index b1f6a29..ebb81c3 100644 --- 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" diff --git a/doc/design/prove-cli.md b/doc/design/prove-cli.md index 77c615c..5e26056 100644 --- a/doc/design/prove-cli.md +++ b/doc/design/prove-cli.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **实施中(Partial)**:P0 全部、P1 Lean 判定已落地(见 §12);P2 离线符号执行、P3 目录模式进行中。路线图:[roadmap/prove.md](../roadmap/prove.md) | +| 状态 | **已实施(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 伴随判定的先例) | @@ -894,3 +894,35 @@ CI:`.github/workflows/proof.yml` —— 装 Lean 4.35.0 → 底座校验 → **已记录的文法限制**:分支条件尚不支持字段访问(`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 待仓库权限合入的内容 + +以下文件 root 属主、当前工作目录不可写(uid=1000): + +- `CHANGELOG.md`:v2.8.0 条目(见 `doc/roadmap/prove-release-2.8.0.md`) +- `README.md`:版本行 2.7.1→2.8.0 + prove 简介(同上文件附文案) +- `doc/releases/v2.8.0.md`:双语发布说明(同上文件附全文) +- `skills/marqdo-dev/index.mq.md`:`prove` 任务(契约见本节 §12.3 表) diff --git a/doc/roadmap/prove-release-2.8.0.md b/doc/roadmap/prove-release-2.8.0.md new file mode 100644 index 0000000..7240b12 --- /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. + +详见 [双语发布说明](doc/roadmap/prove-release-2.8.0.md)。 +``` + +### 4.2 `README.md` 修改 + +版本行(第 19–21 行)替换为: + +```markdown +当前 CLI **2.8.0** 新增 `marqdo prove`:知识文件的定理表编译为 Lean 4 并自动 +判定真假——没有 Lean 工具链也能离线符号执行(诚实降级,绝不冒充证明), +有 Lean 时全链路证明并给出反例见证。参见[发布说明](doc/roadmap/prove-release-2.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 index ea2320f..929f17a 100644 --- a/doc/roadmap/prove.md +++ b/doc/roadmap/prove.md @@ -2,11 +2,11 @@ | | | |---|---| -| 状态 | **计划(Proposed)· 未开工** | +| 状态 | **已实施(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 | +| 目标版本 | CLI 2.8.0(已发) | | 总工期 | 6.5 人周(单人;P0+P1 共 3 周可演示) | --- diff --git a/doc/tutorial/13-命令行工具.md b/doc/tutorial/13-命令行工具.md index 5002750..6d38268 100644 --- 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/verification/skill-proof-theory.md b/doc/verification/skill-proof-theory.md new file mode 100644 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 index e2ae92a..852b4e6 100644 --- a/doc/verification/skill-proof/MarqdoProof.lean +++ b/doc/verification/skill-proof/MarqdoProof.lean @@ -33,9 +33,35 @@ def mqAccess : Val → String → Val -- ---------------------------------------------------------------- 算术 -/-- `+`:仅 int 参与算术;其它形状 → `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 diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md index 850370a..e81b7e2 100644 --- 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/src/main.rs b/src/main.rs index 33e79b0..c79d362 100644 --- a/src/main.rs +++ b/src/main.rs @@ -552,6 +552,19 @@ enum Commands { /// 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, }, } @@ -774,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. @@ -1101,7 +1193,14 @@ fn try_main(cli: Cli) -> Result { 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 { @@ -1154,6 +1253,38 @@ fn try_main(cli: Cli) -> Result { // 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, diff --git a/tests/conformance.rs b/tests/conformance.rs new file mode 100644 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/prove_lean.rs b/tests/prove_lean.rs index be055e5..1c9b925 100644 --- a/tests/prove_lean.rs +++ b/tests/prove_lean.rs @@ -389,6 +389,64 @@ fn e4_tactic_none_yields_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() {