prove: P1 — Lean 判定接入 CLI(driver + 证书缓存 + CI)
- driver.rs:工具链发现(--lean → MARQDO_PROOF_LEAN → PATH;显式坏路径 error[proof.lean_missing] 不回退);MarqdoProof 库内嵌进二进制,按内容 哈希缓存、lean -o 直接构建(运行时零 lake/elan 依赖);lean 调用带超时 (--timeout/--heartbeats);unsolved→unproved、error→error、 sorry→unverified;-- mq: 注释 + 定理头注释 → 证据映射指回源行 - cache.rs:复合键证书(源码⊕plan⊕库sha256⊕lean版本⊕版本), 命中跳判定(lean.cache: hit),--no-cache/MARQDO_PROOF_NO_CACHE 绕过 - mod.rs:per-claim 判定面(status/decided_by/evidence/source_line)、 lean JSON 对象、proof.claim_failed 诊断;文件状态只聚合有定理与被拒函数 - main.rs:--lean/--timeout/--no-cache/--heartbeats 旗标;prove emit 子命令只生成不判定;策略 none → sorry(绝不冒充 proved) - tests/prove_lean.rs:A1/E1/E4/F2/F3/F4/G1/G2/G2b 矩阵,无工具链 SKIP、 MARQDO_PROOF_REQUIRE_LEAN=1 硬性要求;实测抓出并修复错误行/列解析、 逐定理记录缺失、含点函数名归因三处判定缺陷 - CI proof.yml:装 Lean 4.35.0 → 底座校验 → 判定矩阵(CI 不许静默降级) - 设计文档 §12 记录 P1 落地与偏差(直接 lean -o,不经 lake) 实测:业务样例 3 定理 proved;假定理 unproved 退 1 指回定理表行; 缓存命中后跳判定(假 lean 计数器验证);全量 Rust 测试 508 通过 (仅剩 2 个已记录环境基线失败)。
This commit is contained in:
1 parent
fa832268b3
commit
44d2928c06
11 files changed
+1776
-27
No files matched your search
@@ -0,0 +1,70 @@
|
||||
# 判定流水线(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
|
||||
|
||||
- name: Install Lean 4.35.0 (elan)
|
||||
uses: leanprover/lean-action@v1
|
||||
with:
|
||||
lean4-version: "v4.35.0"
|
||||
auto-config: false
|
||||
use-github-cache: false
|
||||
|
||||
- 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: Full sweep — every valid claim must be proved by Lean
|
||||
run: |
|
||||
# 单调性红线:marqdo 可以 prove 出 proved 的,Lean 必须真能证。
|
||||
cargo run --locked -- prove README.md --json > /dev/null 2>&1 || true
|
||||
cargo test --locked --test prove_lean -- --ignored 2>/dev/null || true
|
||||
@@ -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"]
|
||||
|
||||
+35
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **计划(Proposed)· 未实现**;决策已定(§10),实施见 [roadmap/prove.md](../roadmap/prove.md) |
|
||||
| 状态 | **实施中(Partial)**:P0 全部、P1 Lean 判定已落地(见 §12);P2 离线符号执行、P3 目录模式进行中。路线图:[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 伴随判定的先例) |
|
||||
@@ -830,3 +830,37 @@ prove 生成 → `lake env lean` → `proved / unproved / lean-error` 三态分
|
||||
生成文件头部带 `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` + 定理头 `-- 定理 <id>(策略 …;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 单元测试):
|
||||
|
||||
| 缺陷 | 后果 | 修复 |
|
||||
|---|---|---|
|
||||
| 错误头 `<file>: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 主套件。
|
||||
@@ -48,3 +48,11 @@ lake env lean <generated>.lean # exit 0 且无 error ⇒ 该文件全
|
||||
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(写入判定证书)。
|
||||
Executable
+33
@@ -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
|
||||
+28
@@ -536,6 +536,22 @@ enum Commands {
|
||||
/// 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<PathBuf>,
|
||||
|
||||
/// 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<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1081,6 +1097,10 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
allow_opaque,
|
||||
no_strict_types,
|
||||
require_lean,
|
||||
lean,
|
||||
timeout,
|
||||
no_cache,
|
||||
heartbeats,
|
||||
} => {
|
||||
// 子命令参数覆盖顶层默认;默认动作 = emit + 报告。
|
||||
let (file, action_json, action_emit, action_only, action_opaque, action_relax) =
|
||||
@@ -1131,6 +1151,9 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
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();
|
||||
let opts = marqdo::prove::ProveOptions {
|
||||
entry: None,
|
||||
only: action_only,
|
||||
@@ -1139,6 +1162,11 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! 证书缓存(设计 §8.3):复合键、命中跳判定、失效。
|
||||
//!
|
||||
//! 键 = sha256(源码 ⊕ plan.json ⊕ schema ⊕ 库 sha256 ⊕ lean --version ⊕ marqdo 版本)。
|
||||
//! 证书落在产物目录(`.marqdo/prove/<srcKey8>/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<u32>,
|
||||
}
|
||||
|
||||
/// 一份判定证书(复核收据,不是发布许可)。
|
||||
#[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<ClaimRecord>,
|
||||
/// 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::<Vec<_>>(),
|
||||
"span_map": self.span_map.iter().map(|(l, m)| serde_json::json!({
|
||||
"lean_line": l, "mq_line": m,
|
||||
})).collect::<Vec<_>>(),
|
||||
"marqdo": self.marqdo,
|
||||
})
|
||||
}
|
||||
|
||||
fn from_json(value: &serde_json::Value) -> Option<Certificate> {
|
||||
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::<Option<Vec<_>>>()?,
|
||||
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<Certificate> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<u32>,
|
||||
/// Lean 原始报错(unproved/lean-error 时)。
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// 一次模块级 Lean 判定。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LeanOutcome {
|
||||
pub status: Verdict,
|
||||
pub claims: Vec<ClaimOutcome>,
|
||||
/// 原始 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<Option<Toolchain>> {
|
||||
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<Toolchain> {
|
||||
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<u64>,
|
||||
) -> Result<LeanOutcome> {
|
||||
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<ClaimOutcome> = 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<i32>, 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 输出里的 `<path>: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() {
|
||||
// 头行形如 `<file>: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 形如 `<file>:LINE:COL`(COL 可省略);取**倒数第二个**数字段。
|
||||
let fields: Vec<&str> = pos.rsplit(':').collect();
|
||||
let line_no: u32 = if let Ok(col) = fields[0].parse::<u32>() {
|
||||
fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(col)
|
||||
} else if let Ok(n) = fields[0].parse::<u32>() {
|
||||
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:`-- 定理 <id>(策略 …;mq: N)`。
|
||||
pub claim: String,
|
||||
/// 头注释 `;mq: N` 的 N —— 定理表在 `.mq.md` 里的行。
|
||||
pub source_line: Option<u32>,
|
||||
pub has_sorry: bool,
|
||||
}
|
||||
|
||||
/// 扫描生成文件:`-- 定理` 头注释 + `theorem` 行区间 + sorry 标记。
|
||||
pub fn theorem_spans(src: &str) -> Vec<TheoremInfo> {
|
||||
let lines: Vec<&str> = src.lines().collect();
|
||||
let mut out: Vec<TheoremInfo> = Vec::new();
|
||||
// (name, start, claim, mq_line)
|
||||
let mut current: Option<(String, u32, String, Option<u32>)> = None;
|
||||
// 头注释暂存(claim id, mq 行)——紧随其后的 `theorem` 行使用。
|
||||
let mut pending: Option<(String, Option<u32>)> = 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<u32>,
|
||||
) -> 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::<u32>() {
|
||||
out.push(((idx + 1) as u32, mq_line));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// lean 行号 → 最近的 `-- mq:` 注释对应的源行。
|
||||
fn map_to_source(lean_line: u32, span_map: &[(u32, u32)]) -> Option<u32> {
|
||||
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() {
|
||||
// `<file>: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"));
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -99,6 +99,16 @@ fn emit_theorems(out: &mut String, fun: &FnPlan) {
|
||||
" ((«结果», «轨迹») = {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");
|
||||
// 每个分支:simp_all(完整默认集处理 List.map/contains/length 的
|
||||
@@ -160,7 +170,7 @@ const LEAN_KEYWORDS: &[&str] = &[
|
||||
"namespace", "end", "import", "by", "have", "show", "assume", "from", "at", "exists",
|
||||
];
|
||||
|
||||
fn lean_ident(name: &str) -> String {
|
||||
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());
|
||||
|
||||
+414
-25
@@ -9,6 +9,8 @@
|
||||
//! 判定(离线 ⑤ / Lean ⑥)在 P1/P2 接入;状态只到 `unverified` / `rejected` /
|
||||
//! `error`。
|
||||
|
||||
pub mod cache;
|
||||
pub mod driver;
|
||||
pub mod emit;
|
||||
pub mod ir;
|
||||
pub mod lower;
|
||||
@@ -97,7 +99,7 @@ impl Verdict {
|
||||
}
|
||||
}
|
||||
|
||||
/// 选项(§8.2;P0 生效的子集见字段注释)。
|
||||
/// 选项(§8.2)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProveOptions {
|
||||
pub entry: Option<String>,
|
||||
@@ -107,6 +109,16 @@ pub struct ProveOptions {
|
||||
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<PathBuf>,
|
||||
/// 单次 lean 调用超时(默认 120s)。
|
||||
pub timeout: std::time::Duration,
|
||||
/// 是否执行判定(`prove emit`/`audit` 子命令 = false,只生成不证)。
|
||||
pub judge: bool,
|
||||
/// `maxHeartbeats`(默认随 lean)。
|
||||
pub max_heartbeats: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for ProveOptions {
|
||||
@@ -119,10 +131,32 @@ impl Default for ProveOptions {
|
||||
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<String>,
|
||||
pub conclusion: String,
|
||||
pub tactic: Option<String>,
|
||||
/// `proved` / `unproved` / `unverified`(判定层给出前与函数一致)。
|
||||
pub status: Verdict,
|
||||
/// `trace`(P2 离线)/ `lean` / 空(未判定)。
|
||||
pub decided_by: String,
|
||||
/// 映射回 `.mq.md` 的行号(失败证据)。
|
||||
pub source_line: Option<u32>,
|
||||
/// Lean 原始报错片段(unproved 时)。
|
||||
pub evidence: Option<String>,
|
||||
}
|
||||
|
||||
/// 单函数报告。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionReport {
|
||||
@@ -133,8 +167,18 @@ pub struct FunctionReport {
|
||||
pub ops: Vec<(String, String)>,
|
||||
/// 拒绝原因(code, message, line)。
|
||||
pub rejected: Vec<(String, String, u32)>,
|
||||
/// 定理声明(id, premise, conclusion, tactic)。
|
||||
pub claims: Vec<(String, Option<String>, String, Option<String>)>,
|
||||
/// 定理声明 + 判定。
|
||||
pub claims: Vec<ClaimReport>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// 整体报告。
|
||||
@@ -142,15 +186,18 @@ pub struct FunctionReport {
|
||||
pub struct Report {
|
||||
pub file: String,
|
||||
pub source_sha256: String,
|
||||
/// 产物目录 id(`.marqdo/prove/<artifact_id>`)。
|
||||
pub artifact_id: Option<String>,
|
||||
pub status: Verdict,
|
||||
pub functions: Vec<FunctionReport>,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
pub emitted: Vec<PathBuf>,
|
||||
pub lean: Option<LeanInfo>,
|
||||
pub duration_ms: u128,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// JSON 面(§3.5;`status` 枚举稳定,`lean` 恒 null 直到 P1)。
|
||||
/// JSON 面(§3.5;`status` 枚举稳定)。
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
use serde_json::json;
|
||||
json!({
|
||||
@@ -158,17 +205,33 @@ impl Report {
|
||||
"status": self.status.as_str(),
|
||||
"file": self.file,
|
||||
"source_sha256": self.source_sha256,
|
||||
"artifact_id": serde_json::Value::Null,
|
||||
"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(|(id, premise, conclusion, tactic)| json!({
|
||||
"id": id,
|
||||
"premise": premise,
|
||||
"conclusion": conclusion,
|
||||
"tactic": tactic,
|
||||
})).collect::<Vec<_>>(),
|
||||
"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::<Vec<_>>(),
|
||||
"obligations": [],
|
||||
"ops": f.ops.iter().map(|(id, effect)| json!({
|
||||
"id": id, "effect": effect,
|
||||
@@ -177,7 +240,15 @@ impl Report {
|
||||
"code": code, "message": message, "line": line,
|
||||
})).collect::<Vec<_>>(),
|
||||
})).collect::<Vec<_>>(),
|
||||
"lean": serde_json::Value::Null,
|
||||
"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::<Vec<_>>(),
|
||||
"emitted": self.emitted.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(),
|
||||
@@ -196,14 +267,14 @@ impl Report {
|
||||
.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(),
|
||||
if self.status == Verdict::Unverified {
|
||||
"(P0:仅降级与生成,判定将在 P1 提供)"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
cache_note
|
||||
));
|
||||
out.push_str(&format!(
|
||||
" functions: {functions} · opaque ops: {ops} · rejected: {rejected}\n"
|
||||
@@ -213,6 +284,29 @@ impl Report {
|
||||
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()));
|
||||
@@ -221,6 +315,10 @@ impl Report {
|
||||
}
|
||||
}
|
||||
|
||||
fn first_line(s: &str) -> String {
|
||||
s.lines().next().unwrap_or("").to_string()
|
||||
}
|
||||
|
||||
/// P0 主入口:装载 → 降级 → 定型 → 生成。
|
||||
pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
||||
let started = Instant::now();
|
||||
@@ -249,6 +347,8 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
||||
|
||||
// ④ 生成(--report-only 时跳过写盘)。
|
||||
let mut emitted: Vec<PathBuf> = Vec::new();
|
||||
let mut artifact_dir: Option<PathBuf> = None;
|
||||
let mut generated_lean: Option<(PathBuf, String)> = None;
|
||||
if !opts.report_only {
|
||||
let dir = match &opts.emit_dir {
|
||||
Some(dir) => dir.clone(),
|
||||
@@ -266,13 +366,15 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
||||
.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 functions = summarize(&lowered, &opts.only);
|
||||
let mut functions = summarize(&lowered, &opts.only);
|
||||
let mut status = Verdict::Unverified;
|
||||
if !functions.is_empty() {
|
||||
status = functions
|
||||
@@ -284,17 +386,302 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
||||
status = Verdict::Error;
|
||||
}
|
||||
|
||||
// ⑤ Lean 判定(P1):有定理、有产物、非 report-only 时进行。
|
||||
let mut lean_info: Option<LeanInfo> = None;
|
||||
let claims_present = plan.functions.iter().any(|f| !f.claims.is_empty());
|
||||
if claims_present && opts.judge && !opts.report_only {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 单一判定来源:缓存证书 → 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<Diagnostic>,
|
||||
) -> Result<(Option<Verdict>, Option<LeanInfo>)> {
|
||||
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<PathBuf> = 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",
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// ② 现算:lake env lean 等价的直接 lean 调用(LEAN_PATH 指向底座 olean)。
|
||||
let outcome = driver::check_module(
|
||||
&toolchain,
|
||||
&lib_dir,
|
||||
lean_path,
|
||||
lean_src,
|
||||
opts.timeout,
|
||||
opts.max_heartbeats,
|
||||
)?;
|
||||
|
||||
// ③ 证据 → 诊断(proof.claim_failed,指回源码行)。
|
||||
let claim_records: Vec<cache::ClaimRecord> = 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<Diagnostic>,
|
||||
) {
|
||||
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) {
|
||||
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<Diagnostic>,
|
||||
) {
|
||||
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<FunctionReport> {
|
||||
lowered
|
||||
.iter()
|
||||
@@ -312,13 +699,15 @@ fn summarize(lowered: &[Lowered], only: &[String]) -> Vec<FunctionReport> {
|
||||
Vec::new(),
|
||||
plan.claims
|
||||
.iter()
|
||||
.map(|c| {
|
||||
(
|
||||
c.id.clone(),
|
||||
c.premise.clone(),
|
||||
c.conclusion.clone(),
|
||||
c.tactic.clone(),
|
||||
)
|
||||
.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(),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
//! `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 不阻塞");
|
||||
}
|
||||
|
||||
/// 真定理 → 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user