Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
180a111799 | ||
|
|
a3948dbe0d |
No files matched your search
@@ -2,15 +2,7 @@
|
|||||||
name: Extension Release
|
name: Extension Release
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: Extension version to validate
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
push:
|
push:
|
||||||
branches:
|
|
||||||
- codex/ext-release-validation
|
|
||||||
tags:
|
tags:
|
||||||
- "ext-v*"
|
- "ext-v*"
|
||||||
|
|
||||||
@@ -22,7 +14,6 @@ jobs:
|
|||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GITHUB_REF_NAME_OVERRIDE: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || format('ext-v{0}', inputs.version || '2.8.1') }}
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
@@ -44,9 +35,8 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
GITHUB_REF_NAME="$GITHUB_REF_NAME_OVERRIDE" ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json
|
./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json
|
||||||
- name: Attach source and Windows native packs without replacement
|
- name: Attach source and Windows native packs without replacement
|
||||||
if: startsWith(github.ref, 'refs/tags/ext-v')
|
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -57,7 +47,6 @@ jobs:
|
|||||||
needs: windows
|
needs: windows
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GITHUB_REF_NAME_OVERRIDE: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || format('ext-v{0}', inputs.version || '2.8.1') }}
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
@@ -74,7 +63,6 @@ jobs:
|
|||||||
cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering
|
cargo build --release -p marqdo -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg -p marqdo_plugin_llm -p marqdo_plugin_engineering
|
||||||
bash scripts/build-web-plugin.sh
|
bash scripts/build-web-plugin.sh
|
||||||
- name: Build and validate the runner's exact pack bytes
|
- name: Build and validate the runner's exact pack bytes
|
||||||
run: GITHUB_REF_NAME="$GITHUB_REF_NAME_OVERRIDE" target/release/marqdo call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json
|
run: target/release/marqdo call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.read,fs.write,environment.read --fs-root . --require-ok --json
|
||||||
- name: Attach Linux native pack without replacement
|
- name: Attach Linux native pack without replacement
|
||||||
if: startsWith(github.ref, 'refs/tags/ext-v')
|
|
||||||
run: target/release/marqdo call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json
|
run: target/release/marqdo call skills/marqdo-release/packs.mq.md attach_ci --effects plugin,fs.read,environment.read --fs-root . --require-ok --json
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
name: knowledge-proof-full-gate
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "src/knowledge/**"
|
||||||
|
- "src/sema/**"
|
||||||
|
- "src/prove/**"
|
||||||
|
- "tests/**"
|
||||||
|
- "doc/verification/skill-proof/**"
|
||||||
|
- ".github/workflows/knowledge-proof-full-gate.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: knowledge-proof-full-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
complete-proof-regression:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- name: Install pinned Lean kernel
|
||||||
|
run: |
|
||||||
|
curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0
|
||||||
|
echo "$HOME/.elan/bin" >> "$GITHUB_PATH"
|
||||||
|
- name: Validate Lean kernel and embedded proof library
|
||||||
|
run: |
|
||||||
|
lean --version
|
||||||
|
bash scripts/check-proof-library.sh
|
||||||
|
lean doc/verification/skill-proof/MarqdoModularProof.lean
|
||||||
|
lean doc/verification/skill-proof/MarqdoEffects.lean
|
||||||
|
- name: Build and run all knowledge unit tests
|
||||||
|
run: |
|
||||||
|
cargo build --locked
|
||||||
|
cargo test --locked --lib knowledge::
|
||||||
|
cargo test --locked --lib sema::ir::tests
|
||||||
|
- name: Knowledge and execution compatibility suites
|
||||||
|
run: |
|
||||||
|
cargo test --locked --test knowledge_proof
|
||||||
|
cargo test --locked --test executable_knowledge
|
||||||
|
cargo test --locked --test prove
|
||||||
|
- name: Full genuine Lean proof matrix
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: |
|
||||||
|
cargo test --locked --test prove_lean
|
||||||
|
cargo test --locked --test prove_corpus
|
||||||
|
cargo test --locked --test conformance
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
name: modular-proof-smoke
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "src/knowledge/**"
|
||||||
|
- "src/sema/ir.rs"
|
||||||
|
- "src/prove/**"
|
||||||
|
- "tests/prove_lean.rs"
|
||||||
|
- "doc/verification/skill-proof/**"
|
||||||
|
- ".github/workflows/modular-proof-smoke.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
concurrency:
|
||||||
|
group: modular-proof-smoke-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
jobs:
|
||||||
|
modular:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- name: Compile isolated modular proof candidates
|
||||||
|
run: cargo test --locked --lib knowledge::composition::tests -- --nocapture
|
||||||
|
- name: Compile parameter-projection proof backend
|
||||||
|
run: cargo test --locked --lib knowledge::projection -- --nocapture
|
||||||
|
- name: Compile pure-expression VC backend
|
||||||
|
run: cargo test --locked --lib knowledge::expression::tests -- --nocapture
|
||||||
|
- name: Unified contract engine and evidence lattice unit tests
|
||||||
|
run: |
|
||||||
|
cargo test --locked --lib knowledge::unified::tests -- --nocapture
|
||||||
|
cargo test --locked --lib knowledge::evidence::tests -- --nocapture
|
||||||
|
- name: Compile path-sensitive VCs
|
||||||
|
run: cargo test --locked --lib knowledge::symbolic::tests -- --nocapture
|
||||||
|
- name: Compile closed-argument VCs
|
||||||
|
run: cargo test --locked --lib knowledge::vc::tests -- --nocapture
|
||||||
|
- name: Install Lean 4.35
|
||||||
|
run: |
|
||||||
|
curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0
|
||||||
|
echo "$HOME/.elan/bin" >> "$GITHUB_PATH"
|
||||||
|
- name: Lean proof of exception, ABI and fuel-bound models
|
||||||
|
run: |
|
||||||
|
lean doc/verification/skill-proof/MarqdoModularProof.lean
|
||||||
|
lean doc/verification/skill-proof/MarqdoEffects.lean
|
||||||
|
- name: Independently composed Lean modules
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean composition_emits_independently_replayable_caller_certificate -- --nocapture
|
||||||
|
- name: Symbolic parameter projection with independent Lean replay
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean projection_composition_proves_symbolic_caller_and_replays_from_source -- --nocapture
|
||||||
|
- name: Independent arithmetic contract composition with real Lean
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean pure_expression_composition_proves_and_replays_real_lean -- --nocapture
|
||||||
|
- name: Three module DAG and branching caller with independent Lean replay
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean unified_modular_contract_proves_multicall_branch_and_transitive_dag -- --nocapture
|
||||||
|
- name: Regenerated provenance for original Lean certificates
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean g2_certificate_hit_after_real_run -- --nocapture
|
||||||
|
- name: Linear symbolic arithmetic path implication with real Lean
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean arithmetic_symbolic_path_implication_uses_real_lean -- --nocapture
|
||||||
|
- name: Symbolic path implication with real Lean
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: cargo test --locked --test prove_lean symbolic_path_implication_uses_real_lean_without_runtime_promotion -- --nocapture
|
||||||
Executable → Regular
File mode changed.
@@ -0,0 +1,91 @@
|
|||||||
|
# One-time, fail-closed promotion from verified main to immutable v2.9.0.
|
||||||
|
# GITHUB_TOKEN-created tag pushes do not recursively start tag workflows.
|
||||||
|
# Explicit workflow_dispatch is used to run the existing multi-platform
|
||||||
|
# Release workflow against the immutable tag itself.
|
||||||
|
name: Release v2.9.0 promotion
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths:
|
||||||
|
- "Cargo.toml"
|
||||||
|
- "doc/releases/v2.9.0.md"
|
||||||
|
- ".github/workflows/release-v2.9.yml"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "Cargo.toml"
|
||||||
|
- "Cargo.lock"
|
||||||
|
- "crates/marqdo-wasm/Cargo.toml"
|
||||||
|
- "ext/VERSION"
|
||||||
|
- "doc/releases/v2.9.0.md"
|
||||||
|
- ".github/workflows/release-v2.9.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
actions: write
|
||||||
|
concurrency:
|
||||||
|
group: release-v2.9-promotion
|
||||||
|
cancel-in-progress: false
|
||||||
|
jobs:
|
||||||
|
verify-and-dispatch:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: true
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- name: Verify complete, matching release metadata
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 - <<'PY'
|
||||||
|
import re, pathlib
|
||||||
|
want = '2.9.0'
|
||||||
|
for file in ['Cargo.toml', 'crates/marqdo-wasm/Cargo.toml']:
|
||||||
|
data = pathlib.Path(file).read_text()
|
||||||
|
assert re.search(r'^version\s*=\s*"2\.9\.0"\s*$', data, re.M), file
|
||||||
|
lock = pathlib.Path('Cargo.lock').read_text()
|
||||||
|
for name in ['marqdo', 'marqdo-wasm']:
|
||||||
|
assert re.search(r'\[\[package\]\]\nname = "'+name+r'"\nversion = "2\.9\.0"', lock), name
|
||||||
|
assert pathlib.Path('ext/VERSION').read_text().strip() == want
|
||||||
|
assert pathlib.Path('doc/releases/v2.9.0.md').exists()
|
||||||
|
PY
|
||||||
|
git diff --exit-code
|
||||||
|
- name: Install pinned Lean checker
|
||||||
|
run: |
|
||||||
|
curl -sSf https://elan.lean-lang.org/elan-init.sh | sh -s -- -y --default-toolchain leanprover/lean4:v4.35.0
|
||||||
|
echo "$HOME/.elan/bin" >> "$GITHUB_PATH"
|
||||||
|
- name: Validate Lean and source-derived proof library
|
||||||
|
run: |
|
||||||
|
lean --version
|
||||||
|
bash scripts/check-proof-library.sh
|
||||||
|
lean doc/verification/skill-proof/MarqdoModularProof.lean
|
||||||
|
lean doc/verification/skill-proof/MarqdoEffects.lean
|
||||||
|
- name: Build and gate source semantics, actual Lean and compatibility
|
||||||
|
env:
|
||||||
|
MARQDO_PROOF_REQUIRE_LEAN: "1"
|
||||||
|
run: |
|
||||||
|
cargo build --locked
|
||||||
|
cargo test --locked --lib knowledge::
|
||||||
|
cargo test --locked --test knowledge_proof
|
||||||
|
cargo test --locked --test prove_lean
|
||||||
|
cargo test --locked --test prove_corpus
|
||||||
|
cargo test --locked --test conformance
|
||||||
|
cargo test --locked --test executable_knowledge
|
||||||
|
cargo test --locked --test release_handbook
|
||||||
|
- name: Create v2.9.0 only once and dispatch full platform release
|
||||||
|
if: github.repository == 'cflmy/marqdo' && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if git ls-remote --exit-code --tags origin refs/tags/v2.9.0 >/dev/null 2>&1; then
|
||||||
|
echo "v2.9.0 already exists; refusing to replace or re-dispatch assets"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
git tag -a v2.9.0 "$GITHUB_SHA" -m "Marqdo v2.9.0 full: Verified Knowledge Compiler"
|
||||||
|
git push origin refs/tags/v2.9.0
|
||||||
|
gh workflow run release.yml --ref v2.9.0
|
||||||
|
echo "Dispatched Release workflow for immutable tag v2.9.0"
|
||||||
Executable → Regular
+2
@@ -5,6 +5,7 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- "v*"
|
- "v*"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -51,6 +52,7 @@ jobs:
|
|||||||
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||||
Push-Location vscode-extension
|
Push-Location vscode-extension
|
||||||
npm ci
|
npm ci
|
||||||
|
npm version "$ver" --no-git-tag-version --allow-same-version
|
||||||
npm run compile
|
npm run compile
|
||||||
npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-$ver.vsix"
|
npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-$ver.vsix"
|
||||||
Pop-Location
|
Pop-Location
|
||||||
|
|||||||
@@ -2,6 +2,21 @@
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
## v2.9.0 — 2026-11-18 · Full release / 正式完整版本
|
||||||
|
|
||||||
|
Marqdo Verified Knowledge Compiler: source-addressable knowledge proof artifacts, bounded Lean 4 modular contract composition, precise evidence grades, independent replay, and fail-closed unsupported semantics.
|
||||||
|
|
||||||
|
- Unified source-derived pure-function proof DAG with symbolic parameters, sequential calls, total conditional branches, multi-module imports, and kernel-checked caller contracts.
|
||||||
|
- Stable statement and theorem anchors, dependency closure signatures, proof indexes and source-change invalidation.
|
||||||
|
- `proved`, `model_proved`, `tested`, `assumed`, `unknown`, `refuted`, `stale` are distinct; Lean Int-model proofs **do not** prove the complete Marqdo `number` or i64 runtime.
|
||||||
|
- Independent Lean replay and negative regression tests for changed source, missing preconditions, unsupported effects, and false caller conclusions.
|
||||||
|
- Full CLI/WASM/ext version synchronization, Windows/Linux native archives and editor release packaging (completion requires actual release workflow and asset verification).
|
||||||
|
- Existing `marqdo prove` behavior, classic knowledge references, and `marqdo call` remain supported. Unsupported loops, recursive functions, dynamic dispatch, plugins and unverified runtime behaviors never become auto-proved.
|
||||||
|
|
||||||
|
Marqdo 2.9.0(full)发布可寻址知识制品、统一纯函数模块化契约组合、真实 Lean 证书独立重放与证据等级;保留旧证明证书重放。仅支持明确的纯整数抽象子集,不宣称完整运行时正确性或所有函数自动可证。
|
||||||
|
|
||||||
|
详情 / Details: [2.9.0 release notes](doc/releases/v2.9.0.md) · [Trust boundaries](doc/design/verified-knowledge-compiler-boundaries.md).
|
||||||
|
|
||||||
## Ext pack v2.8.1 — 2026-11-18
|
## Ext pack v2.8.1 — 2026-11-18
|
||||||
|
|
||||||
### Highlights
|
### Highlights
|
||||||
|
|||||||
+2
-2
@@ -615,7 +615,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "2.8.0"
|
version = "2.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"assert_cmd",
|
"assert_cmd",
|
||||||
@@ -656,7 +656,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "2.8.0"
|
version = "2.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"marqdo",
|
"marqdo",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
Executable → Regular
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo"
|
name = "marqdo"
|
||||||
version = "2.8.0"
|
version = "2.9.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<p align="center"><em>让 SKILL 真正成为工具:文档即知识,知识即可执行。</em></p>
|
<p align="center"><em>让 SKILL 真正成为工具:文档即知识,知识即可执行。</em></p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/cflmy/marqdo/releases/tag/v2.7.1"><img alt="release" src="https://img.shields.io/badge/release-v2.7.1-DDBA86?style=flat-square"></a>
|
<a href="https://github.com/cflmy/marqdo/releases/tag/v2.9.0"><img alt="release" src="https://img.shields.io/badge/release-v2.9.0-DDBA86?style=flat-square"></a>
|
||||||
<a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
|
<a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
|
||||||
<img alt="Rust runtime" src="https://img.shields.io/badge/runtime-Rust-B38E68?style=flat-square">
|
<img alt="Rust runtime" src="https://img.shields.io/badge/runtime-Rust-B38E68?style=flat-square">
|
||||||
<img alt="Pure by default" src="https://img.shields.io/badge/call-pure_by_default-467C83?style=flat-square">
|
<img alt="Pure by default" src="https://img.shields.io/badge/call-pure_by_default-467C83?style=flat-square">
|
||||||
@@ -21,9 +21,13 @@
|
|||||||
<a href="#explore-the-view">View</a> ·
|
<a href="#explore-the-view">View</a> ·
|
||||||
<a href="doc/library-development.mq.md">Guide</a> ·
|
<a href="doc/library-development.mq.md">Guide</a> ·
|
||||||
<a href="https://www.marqdo.com/">Website</a> ·
|
<a href="https://www.marqdo.com/">Website</a> ·
|
||||||
<a href="doc/releases/v2.7.1.md">Release notes</a>
|
<a href="doc/releases/v2.9.0.md">Release notes</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
## Marqdo 2.9.0 — Verified Knowledge Compiler
|
||||||
|
|
||||||
|
Knowledge statements and claims have stable addresses; verified pure contracts compose across static modules and produce independently replayable Lean certificates. Evidence distinguishes abstract `model_proved` from true runtime `proved`. Unsupported runtime effects and semantics are explicitly unverified. [Proof scope and acceptance](doc/design/verified-knowledge-compiler-boundaries.md) · [Release notes](doc/releases/v2.9.0.md).
|
||||||
|
|
||||||
## One Markdown file. Three views. Real execution.
|
## One Markdown file. Three views. Real execution.
|
||||||
|
|
||||||
[](assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4)
|
[](assets/marketing/marqdo-2.7.1-markdown-to-execution.mp4)
|
||||||
@@ -47,7 +51,7 @@
|
|||||||
|
|
||||||
## Quickstart — one function, one command
|
## Quickstart — one function, one command
|
||||||
|
|
||||||
Install the [2.7.1 CLI release for Windows or Linux](https://github.com/cflmy/marqdo/releases/tag/v2.7.1), then run from this repository's root:
|
Install the [latest 2.9.0 CLI release for Windows or Linux](https://github.com/cflmy/marqdo/releases/tag/v2.9.0), then run from this repository's root:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
|
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
|
||||||
|
|||||||
Executable → Regular
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo-wasm"
|
name = "marqdo-wasm"
|
||||||
version = "2.8.0"
|
version = "2.9.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
# Marqdo 知识锚点与证明制品(2.8 → 2.9)
|
||||||
|
|
||||||
|
> 实现状态:PR #2 第一阶段。保持解释器和原有 `[]()` 求值语义不变,复用 2.8.0 `prove` 与既有 SemanticProject。以下明确区分**已经写入分支的功能**和**尚未完成的跨模块证明**。
|
||||||
|
|
||||||
|
## 核心语义
|
||||||
|
|
||||||
|
- AST 内部步骤仍有原来的 `#step-N` 序号,供旧查询、调试与执行日志使用。
|
||||||
|
- 在**同一个函数内名称唯一**的标记步骤,获得独立的 `anchor_id = SymbolId#anchor-sha256(normalized_label)`;在前面插入其他步骤不会改变地址。
|
||||||
|
- 同函数重复的标记名称**不产生公共锚点**;必须重命名,不得静默采用首个。
|
||||||
|
- `definition_digest` 来自该语句源码位置的内容,与稳定身份分开;语句内容更改时身份保留、定义指纹改变。
|
||||||
|
- 两种文档引用不执行目标:同函数的 `[阅读依据](#@演算)` 和跨模块绝对地址 `[阅读依据](mq://...#anchor-<sha256>)`。后者应从编译生成的 anchors.json 拿完整 ID,不应凭空手写。
|
||||||
|
- 2.8.0 定理表每条唯一声明生成稳定 `ClaimId = SymbolId#claim-sha256(定理名称)`;正文 `[阅读定理](#@定理名称)` 可以定位**声明**,但不会读取或伪造证明状态;同一名称同时匹配知识步骤和定理声明时标记 `ambiguous_anchor`,不猜测。\n- 普通 `[说明](https://...)` 仍为导航,原来表达式位置的 `[描述](payload)` 仍依照原 Marqdo 执行规则求值。
|
||||||
|
- **链接不意味着执行权**:解析到知识锚点只生成引用边,不自动调用函数、加载插件或赋予权限。
|
||||||
|
|
||||||
|
## 制品
|
||||||
|
|
||||||
|
`marqdo knowledge` 所用的 SemanticProject 原子生成目录下新增:
|
||||||
|
|
||||||
|
| 路径 | 内容 |
|
||||||
|
|---|---|
|
||||||
|
| `steps.json` / `refs.json` | 增量字段 `anchor_id`、`definition_digest`、`link_target`、`target_anchor` |
|
||||||
|
| `claims.json` | 定理声明索引,初始状态固定为 `declared_unverified`,不等同于证明通过 |\n| `anchors.json` | 稳定公共步骤索引,附所有者、标记文本、源码、效应、定义指纹 |
|
||||||
|
| `graph/edges.json` | `defines_anchor`、`references_anchor`、知识步骤到已解析调用目标的 `calls` |
|
||||||
|
| `proof-index.json` | 可用或过期的证明收据索引;它不是可执行授权,也不自动证明步骤 |
|
||||||
|
|
||||||
|
`marqdo prove` 在原本的证明目录附带 `knowledge-links.json`:
|
||||||
|
每个定理通过文件 + 函数全名唯一绑定到 `SymbolId`,稳定 `claim_anchor_id` 附带前提、结论、来源、函数的 interface/implementation/closure digest 与可用时的 Lean 证书摘要。
|
||||||
|
无法安全绑定时输出 `unresolved`,不匹配别的同名函数。
|
||||||
|
`related_anchor_ids` 仅是 **defined_in_same_function_not_individually_proved** 导航关系,绝不意味着 Lean 已分别证明这些内部锚点的性质。
|
||||||
|
|
||||||
|
## 证据有效性
|
||||||
|
|
||||||
|
1. 离线 `checked` 不能当作 `proved`。
|
||||||
|
2. 只有 `ClaimReport` 显示真实 Lean 判定,且匹配当前报告的原始 `certificate.json`、命题、文件、Lean 工具链与证明库,才可输出 `proved` 关联。
|
||||||
|
3. 在知识编译时复核文件源码 SHA、函数接口、实现指纹、传递依赖 closure 指纹及证书字节摘要;失败 => `stale` / `unverified`,`usable=false`。
|
||||||
|
4. 同一个声明出现多份可见报告时 => `ambiguous`,不能随意取旧证书或新证书。
|
||||||
|
5. 当前证明文件是**本地缓存收据**,不是经过签名的远程授权凭证。对抗性环境必须在可信 CI 中再次用 Lean 验证,不能仅相信 JSON 内的 `status`。
|
||||||
|
|
||||||
|
## 下一阶段:跨模块 assume–guarantee
|
||||||
|
|
||||||
|
这是比单纯增加更多 Lean tactic 更重要的方向,但 **本 PR 第一阶段尚未实现**:
|
||||||
|
|
||||||
|
- 将函数可复用契约分成 `requires / ensures / effects`,全部有已解析 SymbolId 作为身份;
|
||||||
|
- 在调用方生成 “调用前提满足” 的证明义务,并以被调者的已验证后置条件作为假设,**明确记录假设链**;
|
||||||
|
- 若被调者实现改变、但同一契约被重新证明支持,允许复用不受影响的调用方证明;
|
||||||
|
- 若契约失效、闭包改变或假设不能满足,所有受影响证明回退 `stale`,不能保持 `proved`;
|
||||||
|
- 对外部 ABI 插件调用,必须给出明确 effect 契约、来源和可信主体,不能把不透明调用宣告为纯函数;
|
||||||
|
- 保留 Lean 与解释器对 i64 溢出、除零/模零行为的差异护栏,在证明模型不等价时不给出无限定的成功保证。
|
||||||
|
|
||||||
|
## 验收指标
|
||||||
|
|
||||||
|
1. 在任意步骤前插入不相关语句,公共锚点地址不漂移;旧内部编号可以变化。
|
||||||
|
2. 只修改锚点表达式,定义 digest 必须变化,锚点地址保持;同名重复拒绝公开。
|
||||||
|
3. `#@标签` 与完整 `mq://...` 必须精确解析;不存在锚点报告 unresolved,且不能变成 BoundCall。
|
||||||
|
4. `prove` 的函数证明只能关联函数知识,不能将所有带标记步骤标成 proved。
|
||||||
|
5. 更改源码、契约、传递依赖或证书后,知识索引拒绝使用过期证明。
|
||||||
|
6. 与 2.8.0 原有 CLI / SemanticProject / Lean 测试保持兼容。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## M4:模块化证明内核与当前信任边界
|
||||||
|
|
||||||
|
本工作在 `src/knowledge/modular.rs` 增加证明义务图,输出于
|
||||||
|
`proof-obligations.json`;可通过命令:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo knowledge proof-deps --json --strict .
|
||||||
|
```
|
||||||
|
|
||||||
|
`--strict` 在缺少来源校验、证明收据或契约时非零退出。这个
|
||||||
|
`audit_passes` **不是**一个 Lean 证明的调用方定理,也不能发布
|
||||||
|
`proved`。它只说明当前本地可见的证明收据与契约引用是否完整。
|
||||||
|
|
||||||
|
T3 声明采用既有 GFM 表格(不增加解释器语法):
|
||||||
|
|
||||||
|
| 假设 | 前置 | 后置 |
|
||||||
|
|---|---|---|
|
||||||
|
| rates.lookup | 金额 > 0 | 返回 = 2 |
|
||||||
|
|
||||||
|
函数开头的此表现在被 parser 提取进 `Function.assumptions`,映射到
|
||||||
|
`FnPlan.assumptions`,由 `SemanticProject` 生成 `assumptions.json`;
|
||||||
|
不参与运行时执行、也不赋予事实可信度。重复、未找到、前置条件待验证
|
||||||
|
均应 fail closed。
|
||||||
|
|
||||||
|
`doc/verification/skill-proof/MarqdoModularProof.lean` 定义参数化的
|
||||||
|
`Contract`、`Implements` 和 `compose_sound`:
|
||||||
|
|
||||||
|
- 被调函数真正满足其前后置条件;
|
||||||
|
- 调用方/前一个函数真正满足其前后置条件;
|
||||||
|
- 显式桥接引理证明前一个函数的后置条件足以满足后一个函数的前置条件;
|
||||||
|
|
||||||
|
Lean 才能得出组合契约成立。文件含一个缺少桥接前提时组合错误的反例,
|
||||||
|
以防未来实现将“被调者 proved”直接等价于“调用者 proved”。
|
||||||
|
|
||||||
|
### 尚未完成的关键项(不得标记 done)
|
||||||
|
|
||||||
|
1. **参数绑定**:从真实 Marqdo `BoundCall` 的表达式实参生成
|
||||||
|
调用点前置条件的 Lean 目标。不能直接复用未绑定实参的 `前置` 文本。
|
||||||
|
2. **模块化执行语义**:在 Lean 中准确表示 import / 调用 / 返回 / 效应,
|
||||||
|
并与原解释器的数值和异常行为建立等价性。
|
||||||
|
3. **证明组合与导出**:仅在被调证明证书经过受信核验、桥接义务
|
||||||
|
由 Lean 消除且调用方自己的 Lean 定理成立时,输出新的模块化证明证书。
|
||||||
|
4. **可靠的跨实现复用**:不能因为后置条件文字未改变就绕过重新核验;
|
||||||
|
必须要有新实现支持同一契约的证明,且证明/模块 ABI 版本匹配。
|
||||||
|
5. **安全与正确性测试**:成功与失败调用、条件前置、不透明调用、效应、
|
||||||
|
多版本证书、循环依赖、证书篡改、解释器/Lean 差分一致性与崩溃恢复。
|
||||||
|
|
||||||
|
所以目前 **已经实现的是可寻址知识编译、证明绑定和保守的模块依赖审计**;
|
||||||
|
**没有实现完整跨模块自动推理并生成 `proved` 的系统**,不应声称后者已完成。
|
||||||
|
|
||||||
|
|
||||||
|
## M5:跨模块纯叶函数的受限源码透明证明
|
||||||
|
|
||||||
|
`src/prove/lower.rs` 新增第一条**真实跨文件执行语义**通路。
|
||||||
|
`Target::Import` 仅对以下情形将导入函数源码透明降级入调用方 Proof IR:
|
||||||
|
|
||||||
|
- 被调函数体只有一个 `Return`;表达式由字面量、形参、无副作用一元/二元表达式和遮蔽表达式构成,不得依赖全局状态或其他函数;
|
||||||
|
- 调用实参全部显式传入、位置匹配且与参数数目一致,不能通过默认参数或任意命名重排来隐式猜测绑定;
|
||||||
|
- 展开深度有严格上界;不支持分支、循环、递归、动态分派、ABI 效应或未知调用;
|
||||||
|
- 当导入表达式包含算术操作时,必须通过实际实参的静态整数求值确保 `i64` 不溢出、不除零。包含变量或非整数的未知算术保持不透明,绝不因 Lean 的无界 `Int` 语义而自动升级。
|
||||||
|
|
||||||
|
这条通路设计的真实 Lean 正例分别是无参数的跨文件纯返回,以及带实际参数绑定的加一计算;`tests/knowledge_proof.rs` 包含导入文件产生副作用和 `i64` 溢出的反例。
|
||||||
|
|
||||||
|
**该特性是源码透明的跨模块证明(有限展开),不是抽象契约复用。**
|
||||||
|
只有独立证明调用点前置条件、将已证被调契约接入调用方而无需展开实现,并由 Lean 校验接口桥接,才算真正完成通用 assume–guarantee 模块化证明。
|
||||||
|
|
||||||
|
|
||||||
|
## M6:真实 Lean 的封闭调用前置条件(2026-11-18)
|
||||||
|
|
||||||
|
模块化校验现在有两种不同的操作:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 纯分析:不会冒充 Lean 已检查
|
||||||
|
marqdo knowledge proof-deps --json .
|
||||||
|
|
||||||
|
# 要求真实 Lean:先重放被调函数证明,再检查可闭合的调用点前提
|
||||||
|
marqdo knowledge proof-deps --verify --json .
|
||||||
|
|
||||||
|
# 审计严格退出码;不是“整个程序的模块化定理已被证明”
|
||||||
|
marqdo knowledge proof-deps --verify --strict --json .
|
||||||
|
```
|
||||||
|
|
||||||
|
工作过程:
|
||||||
|
|
||||||
|
1. `BoundCall` 保留精确的 caller/target 知识身份,以及**按解释器执行约定归一化后的实参**(名称、顺序、保守静态整数值、源表达式摘要)。
|
||||||
|
2. `knowledge/vc.rs` 用被调方函数签名,将受限前提(整数比较/加减乘/布尔连接)绑定到**真实实参**。拒绝除法、溢出、动态变量、不匹配的命名/顺序参数及无法解释的谓词。
|
||||||
|
3. 先校验原 `certificate.json` 的复合缓存键、`plan.json`、嵌入证明库哈希、生成 Lean 文件 SHA、源码和语义闭包。
|
||||||
|
4. `--verify` 额外使用现有 Lean 工具链**重新检查被调方生成的 Lean 定理**。仅当重放后的确具有精确匹配的 proved 定理时,才承认该条 callee 收据。
|
||||||
|
5. 从验证过的收据与闭合前提生成 `closed-goals.lean`,对每个目标使用 `theorem vc_i : ... := by decide`;调用 Lean 4 核验。Rust 计算的布尔结果只能用于提前拒绝,不能独立充当证据。
|
||||||
|
6. `proof-obligations.json` 与实时 JSON 审计报告分别记录 `precondition_pending` / `precondition_refuted` / `lean_kernel_verified` 等状态。无工具链、超时、证书篡改、Lean 不接受、源变更全部拒绝进入成功状态。
|
||||||
|
|
||||||
|
两个严格区分的边界:
|
||||||
|
|
||||||
|
- `lean_kernel_verified` 表示**当前闭合调用点的条件命题已被核验**,而非调用方的完整结论定理。
|
||||||
|
- `proof_completion` 仍为 `not_established_by_dependency_analysis`。目前缺少通用符号实参、分支路径条件、任意效应 ABI 的正式组合证明与可重放的跨模块结论证明证书。**不得将依赖图审计通过升级为完整模块化 proved。**
|
||||||
|
|
||||||
|
新增 `tests/prove_lean.rs` 场景验证被调定理与调用前置条件**双重重放**,且实参不满足前置条件时必然退出非零;新增单元测试覆盖实际工程导入、整数溢出和未绑定实参。此处描述的是提交的实现及其预期测试,最终验收仍以最新提交 CI 结果为准。
|
||||||
|
|
||||||
|
|
||||||
|
## M7:路径敏感符号证明和独立组合证书(限定子集)
|
||||||
|
|
||||||
|
### 路径条件
|
||||||
|
|
||||||
|
`SemanticProject.BoundCall` 保存调用身份、归一化实参、直接变量、
|
||||||
|
进入该调用点的分支条件(包括 else 否定条件)以及无法证明时的
|
||||||
|
`control_blocker`。副作用条件、循环、迭代和未知运算不作为已证前提。
|
||||||
|
|
||||||
|
`src/knowledge/symbolic.rs` 对纯整数比较和布尔条件产生带
|
||||||
|
`(v0 : Int)` 等量词绑定与路径假设的 Lean 定理;调用 Lean 核验后仅为
|
||||||
|
`symbolic_path_lean_model_proved`,不等于运行时契约通过。数学 Int 与
|
||||||
|
Marqdo 动态值、有界 i64 语义对应仍需独立证明。
|
||||||
|
|
||||||
|
### 独立 Lean 组合证明(首个真正闭环)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo knowledge compose --json --strict .
|
||||||
|
marqdo knowledge replay .marqdo/modular/composed/{proof-id}/composition-certificate.json --json .
|
||||||
|
```
|
||||||
|
|
||||||
|
`compose` 仅接受:不同文件间的唯一静态调用;纯整数函数;
|
||||||
|
调用方直接返回或一次局部赋值再返回被调结果;被调方只有一条整数常量返回;
|
||||||
|
参数均有明确 int 契约、无默认参数;实参仅为调用方参数或安全整数常量;
|
||||||
|
双方具有相同的无条件结果定理;无分支、循环、递归、异常、ABI 效应。
|
||||||
|
|
||||||
|
分别生成 `CalleeModule.lean` 和 `CallerModule.lean`:
|
||||||
|
|
||||||
|
- 被调方源码生成定义,其契约由 Lean 证明。
|
||||||
|
- 调用方 `import CalleeModule`,只使用被调方证明的契约,不展开其函数体。
|
||||||
|
- 两模块独立生成 .olean 并通过真实 Lean 4 核验。
|
||||||
|
- `composition-certificate.json` 绑定符号、源码闭包、Lean 版本、Lean 源文件
|
||||||
|
和编译模块哈希,证明作用域限定为
|
||||||
|
`typed_int_pure_forwarder_constant_postcondition`。
|
||||||
|
- `replay` 必须从**当前项目**重新编译出相同的 Lean 源,匹配依赖闭包,
|
||||||
|
然后独立重新执行两个 Lean 模块并校验产物哈希;源码/证书有变即失效。
|
||||||
|
|
||||||
|
此证书状态是 `lean_kernel_proved_model`,**不是** Marqdo 运行时全部语义已证。
|
||||||
|
|
||||||
|
### 异常、循环、递归与 ABI 的保守边界
|
||||||
|
|
||||||
|
`MarqdoModularProof.lean` 用 `Exit.ok / Exit.error / Exit.diverged`
|
||||||
|
显式区分成功、异常、不终止;`total_sequence_sound` 证明包含异常和
|
||||||
|
发散结果的总正确性契约只有在前置条件桥接被证明后才能组合。
|
||||||
|
异常结果和发散结果不能等同于正常返回。
|
||||||
|
|
||||||
|
这是经过 Lean 检查的**抽象组合规则**,并非已证明所有插件、循环与递归
|
||||||
|
实现满足这一模型。遇到 ABI 不透明效应、无法验证的异常处理、缺失循环
|
||||||
|
不变式/终止性或递归下降变元时,编译器保守拒绝组合。
|
||||||
|
|
||||||
|
### 未达到完整通用系统的部分
|
||||||
|
|
||||||
|
动态类型语义保持、复杂算术的安全条件、任意路径的 WP、
|
||||||
|
循环不变式与终止性、递归归纳证明、插件状态转换可信契约、
|
||||||
|
并发效应,以及一般性参数化后置条件的源码无关组合,目前仍不完整。
|
||||||
|
不能将已完成的限定子集扩大宣传为完整的通用模块化证明系统。
|
||||||
|
|
||||||
|
### 2026-11-18 类型安全修正
|
||||||
|
|
||||||
|
目前类型表源文本中的 `int` 被契约解析器归一化为 `number`,它也允许 Num 和 Formula。因此**不能**把 `number` 的证明自动解释为任意 Marqdo 运行时输入均为 i64。组合证书作用域改为 `number_contract_int_model_pure_forwarder_constant_result`,且根报告固定标注 `full_marqdo_runtime_semantics_proved: false`。这仅证明整数抽象模型上的独立模块组合。完整运行时证明必须新增可执行类型收窄及类型保持定理。
|
||||||
|
|
||||||
|
另新增 `MarqdoEffects.lean`:把状态、插件异常、未决结果和耗尽 fuel 的循环统一建模,证明异常与未决结果不能充当成功返回;该抽象 ABI 契约仍须具体插件的实现见证,不能由表格声明自动授予。
|
||||||
|
|
||||||
|
|
||||||
|
## M8:组合证书闭包与调用身份加固(2026-11-18)
|
||||||
|
|
||||||
|
`knowledge replay` 现在要求证明证书的 identity 在当前语义工程中**恰好对应一个**可组合的 BoundCall;禁止采用 `find first` 策略选择多个候选中的第一个。调用方与被调用方的 closure 收据必须与重编译得到的**两个精确身份与哈希**集合完全一致:重复、额外注入、缺失、替换记录均拒绝重放。
|
||||||
|
|
||||||
|
`composition.rs` 新增单元回归测试 `certificate_closures_must_be_exact_and_unique`。这仅加固证书来源绑定,不扩大已证明的运行时语义范围。CI 需以分支最新 head 为准;不同提交上曾经成功的检查不等于本提交已验证。
|
||||||
|
|
||||||
|
|
||||||
|
## M9:合约声明歧义与同模块伪组合防护
|
||||||
|
|
||||||
|
组合候选现在要求被调函数和调用方各自恰好拥有 **一条** 符合目标常量结果的无条件定理声明。此前使用 `any` 的逻辑可能让两个不同名称、同一结论的声明被当成唯一证据;现在这种情况按歧义处理并拒绝出证。测试在真实的 `.mq.md` 表格中构造两个同结论声明。
|
||||||
|
|
||||||
|
此外,当前受限组合证明只面向不同源文件的静态导入调用,显式拒绝同文件以及自调用,避免将本地调用伪装成可复用跨模块契约证书。此项是准入安全性改进,不表示抽象插件、分支、循环和递归已经实现具体语义证明。
|
||||||
|
|
||||||
|
验证仍须以最终提交的 GitHub Actions 为准,尤其关注 `modular-proof-smoke`、`proof` 和 `knowledge-proof-integration`。工作流无作业失败不应解释为单元测试失败或测试成功,必须另行定位 YAML / GitHub Actions 工作流事件层面问题。
|
||||||
|
|
||||||
|
|
||||||
|
## M10:带符号实参的独立模块组合证书(受限整数投影)
|
||||||
|
|
||||||
|
`src/knowledge/projection.rs` 现实现一条**源码驱动、Lean 内核证明、证书可重放**的参数化调用路径:
|
||||||
|
|
||||||
|
- 被调函数在单一返回语句中返回唯一的形参,且该函数必须是无副作用的静态目标;
|
||||||
|
- 调用方仅直接返回被调调用结果,或将该调用赋给局部变量后立刻返回;
|
||||||
|
- 支持多个形参及重排后的实参,实参只能是调用方形参或已通过安全静态求值的 i64 常量;
|
||||||
|
- 被调方声明唯一无条件契约 `结果 = 被投影形参`,调用方声明唯一无条件契约 `结果 = 对应实际形参或常量`;
|
||||||
|
- 正式构建 `CalleeModule.lean`,以真实返回源生成 `callee_contract`;`CallerModule.lean` 导入前者,经实际实参实例化、以 `simpa [caller]` 得出调用方定理,**不在调用方展开被调实现**;
|
||||||
|
- `composition-certificate.json` 与源码的唯一符号、精确双依赖闭包、工具链版本、Lean 源和编译产物摘要绑定;重放时从当前 `.mq.md` 重新生成两份 Lean 源并重新执行 Lean;
|
||||||
|
- 重复函数名、重复语义实体、重名合同结论、未知或不匹配实参、路径条件、控制阻碍、效应函数、同文件调用、动态调度、源码漂移全部拒绝出证或重放。
|
||||||
|
|
||||||
|
使用既有接口:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo knowledge compose --strict --json .
|
||||||
|
marqdo knowledge replay .marqdo/modular/composed/projection-*/composition-certificate.json --json .
|
||||||
|
```
|
||||||
|
|
||||||
|
新增真实 Lean 测试 `projection_composition_proves_symbolic_caller_and_replays_from_source`,以及参数重排/错误结论/重复声明单元测试。专项 CI `modular-proof-smoke` 运行这条路径。
|
||||||
|
|
||||||
|
**严守边界**:这里的后置条件组合是抽象 Lean `Int` 模型中的`返回等于某个形参`关系,而不是任意谓词、循环不变式、递归归纳或有状态插件契约。Marqdo 的 `int` 声明会归一化到可容纳非整数值的 `number`,故证书显式只给出 `lean_kernel_proved_model`,不能声称动态运行时完全对应。用户定义的插件效应、异常、循环和递归仅有抽象逻辑,不得提升为源码级已证明执行。实现仍处于实验性 Draft,未达到完整通用模块化证明标准。
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
# Marqdo 可验证知识编译器:目标、可信边界与阶段性验收
|
||||||
|
|
||||||
|
> 状态:设计决策 + 当前实现对应。形成于 2026-11-18 关于知识编译、Lean 自动证明边界、AI 智能体知识沉淀与模块化组合的讨论。
|
||||||
|
>
|
||||||
|
> 本文规定目标边界,不以“任意 Marqdo 程序都能被 Lean 证明”为目标。具体实现应以当前源代码、真实 Lean 证书与 CI 结果为准;不能通过修改文档把尚未验证的语义宣布为已证明。
|
||||||
|
|
||||||
|
## 1. 问题与共同认识
|
||||||
|
|
||||||
|
Marqdo 的核心目标不是取代 Lean,也不是成为全自动程序验证器:
|
||||||
|
|
||||||
|
> 代码即文档,文档即知识库,知识即可执行。
|
||||||
|
|
||||||
|
更严格的工程定位:
|
||||||
|
|
||||||
|
> 将人类可读文档编译为**可寻址、可验证、可执行、可复用的知识制品**的语言与编译系统。
|
||||||
|
|
||||||
|
其中,“可验证”不是“所有性质都能被形式化证明”;“知识即可执行”也不是“所有外部世界事实都有数学定理”。
|
||||||
|
|
||||||
|
形式证明必然面临不可判定性、求解器资源上限、环境非确定性、外部依赖以及不完整的语义模型。即使 Lean 内核确认一个命题正确,它确认的也是**给定 Lean 定义及假设下的命题**。如果 Marqdo 源码到 Lean 定义的映射未建立可信性,该证明不能无条件提升为 Marqdo 运行时正确性。
|
||||||
|
|
||||||
|
因此,整个设计遵守四条约束:
|
||||||
|
|
||||||
|
1. **证明精确标注作用域**:明确对象、输入域、效应、数值模型及前提;不要将模型证明冒充完整运行时证明。
|
||||||
|
2. **可证明则证明**:在受支持且能建立可信模型的子集内,由真实 Lean 内核验证;失败不得降级成虚假的 proved。
|
||||||
|
3. **不能证明仍可成为知识**:保留测试、执行轨迹、实验数据、来源与未经验证的假设;这些证据不等价于逻辑证明。
|
||||||
|
4. **不会静默取得执行权**:锚点引用、知识收据、定理声明或插件假设都不自动执行工具、授权访问环境或改变运行时行为。
|
||||||
|
|
||||||
|
## 2. 三层可信性,不由一个 Lean 布尔值代替
|
||||||
|
|
||||||
|
### L1:结构与来源验证——基础必需
|
||||||
|
|
||||||
|
对象包括 Markdown/Marqdo AST、唯一锚点、符号和模块解析、精确调用绑定、源码与契约指纹、引用有效性、依赖闭包、过期证据识别。
|
||||||
|
|
||||||
|
主要由解析器、SemanticProject、知识图谱、哈希与回放机制验证,无须假装数学证明。
|
||||||
|
|
||||||
|
### L2:形式证明——限定作用域
|
||||||
|
|
||||||
|
对象包括函数前/后置条件、调用前提、符号路径、算术结论、可组合的跨模块性质。
|
||||||
|
|
||||||
|
Lean 执行核验;Rust 只能生成目标、提前拒绝以及绑定真实源码,不能凭主机端的计算结果自行宣称定理成立。
|
||||||
|
|
||||||
|
### L3:执行和经验验证——不可省略
|
||||||
|
|
||||||
|
对象包括插件和 API 调用、量子硬件实验、非确定性智能体决策、实际数据质量与第三方网络服务。
|
||||||
|
|
||||||
|
应携带可复现测试、日志、测量、环境版本和来源,不应自动转化为 Lean proof。
|
||||||
|
|
||||||
|
量子科研例子:门矩阵幺正性可以有形式证明,具体设备的实验保真度必须由观测数据和校准记录支持;两种证据可组合引用,但不能互相冒充。
|
||||||
|
|
||||||
|
## 3. 证据等级(Proof is not a Boolean)
|
||||||
|
|
||||||
|
知识制品采用与旧版 \`status\` **正交**的 \`evidence.grade\`。已在 \`src/knowledge/evidence.rs\` 建立类型化模型:
|
||||||
|
|
||||||
|
| 证据等级 | 含义 | 禁止的推断 |
|
||||||
|
|---|---|---|
|
||||||
|
| \`proved\` | 目标语言、输入域及其运行时语义对应已得到可信证明 | 不覆盖未纳入证明的插件、浮点或硬件 |
|
||||||
|
| \`model_proved\` | Lean 核验了明示抽象模型下的命题 | 不得称为全部 Marqdo 运行时正确 |
|
||||||
|
| \`tested\` | 存在真实、可追溯的测试/实验结果 | 通过测试不等于数学证明 |
|
||||||
|
| \`assumed\` | 明示的外部假设、作者/插件契约 | 不得自动变成 proved |
|
||||||
|
| \`unknown\` | 未建立证据、超时、求解失败或超出可证子集 | 不等价于“命题错误” |
|
||||||
|
| \`refuted\` | 已提供可信反例 | 单纯 Lean proof 失败不能判为 refuted |
|
||||||
|
| \`stale\` | 当前源码、依赖或证明环境改变导致证据失效 | 不得复用旧证书 |
|
||||||
|
|
||||||
|
**关键规则**:
|
||||||
|
|
||||||
|
- \`proved\` 必须同时要求具体语义对应与内核证明,不能通过修改 JSON 证据字段获得。
|
||||||
|
- 目前整数算术的 Lean \`Int\` 定理通常属于 \`model_proved\`。Marqdo 的 \`number\` 契约可能包含 \`Num\`、\`Formula\` 等,且 i64 溢出、动态类型转换与异常行为尚未普遍与 \`Int\` 对齐。
|
||||||
|
- \`tested\`、\`assumed\`、\`refuted\` 的证据需要**相应来源**;不能因为某个测试通过、表格声明或求解失败就随意升级。
|
||||||
|
- 证据等级用于解释保证性质;\`usable\`、\`kernel_replayed\` 和 \`current_source_verified\` 是独立的可用性/核验状态,不能混淆。
|
||||||
|
- 知识检索、智能体与工具链看到 \`unknown\` 或 \`assumed\` 时,可以请求额外验证、执行测试、询问外部系统或拒绝高风险动作,但不能修改证明结论。
|
||||||
|
|
||||||
|
## 4. 统一契约组合:通用的是机制,不是自动化证明能力
|
||||||
|
|
||||||
|
函数契约规范化为 \`requires / ensures / effects / evidence\`,每个契约绑定明确的 \`SymbolId\`、源码来源和依赖身份。
|
||||||
|
|
||||||
|
一般调用 \(g(x)=f(a(x))\) 的组合义务:
|
||||||
|
|
||||||
|
1. **被调函数确实满足自己的已声明契约**:有可信的源码与证据绑定。
|
||||||
|
2. **调用点满足前提**:从调用方条件和实参绑定证明 \`requires_f(a(x))\`;不得把任意声明当成假设。
|
||||||
|
3. **组合后调用方结论成立**:使用被调函数的已证保证、调用方实际执行流和路径条件,向 Lean 提交调用方定理。
|
||||||
|
4. **失效传播**:源码、签名、接口、契约或依赖证明改变,旧证书不可继续使用,除非新的实现已经重新满足相应保证。
|
||||||
|
|
||||||
|
\`src/knowledge/unified.rs\` 是统一入口,逐个从当前 Marqdo AST 降级受支持的纯函数,按静态导入 DAG **自底向上**生成独立 Lean 模块。每个模块定义源派生函数并证明该函数自己的契约;调用方导入已经编译的下游模块,以其契约定理为假设链的可验证依据,既不添加 \`axiom\`,也不内联下游源码。生成的每个模块均单独通过 Lean 内核,证书绑定:
|
||||||
|
|
||||||
|
- 精确的源语义身份与传递依赖闭包;
|
||||||
|
- 受支持的源码表达式及控制结构;
|
||||||
|
- 模块生成次序、导入关系、源码摘要和已编译 Lean 摘要;
|
||||||
|
- 工具链版本及受限证明作用域。
|
||||||
|
|
||||||
|
\`marqdo knowledge replay\` 必须重读当前源文件,重新生成这些模块与依赖,再独立编译并逐项比较,不能仅仅读取带有 \`proved\` 标记的本地 JSON。
|
||||||
|
|
||||||
|
旧有常量、参数投影、表达式后端的证书仍可重放;新证明优先走统一管线,避免把多个实现拼成互相矛盾的证明状态。
|
||||||
|
|
||||||
|
### 当前统一后端的精确定义
|
||||||
|
|
||||||
|
当前实现接受:
|
||||||
|
|
||||||
|
- 静态、无副作用、跨文件的纯函数调用与有限、无环调用图;
|
||||||
|
- 参数完整、必要且无默认值;源代码参数、签名和调用点均匹配;
|
||||||
|
- 整数字面量、形参/局部变量、加减、一元负号,以及在支持的片段内由常数参与的乘法;
|
||||||
|
- 顺序局部赋值、直接返回、具有显式 \`else\` 且每条分支都返回结果的普通条件分支;
|
||||||
|
- 每个函数一个可识别、无条件、以 \`结果\` 为左侧的受限数值比较契约(等于或简单大小比较);
|
||||||
|
- 多次静态调用与递归依赖**图上的多层模块**,由证明模块的拓扑顺序组合。
|
||||||
|
|
||||||
|
当前实现**不接受**:
|
||||||
|
|
||||||
|
- 循环、递归、非终止、并发、隐式/动态分派、插件副作用、没有可信模型的异常;
|
||||||
|
- 任意表达式值、除法/浮点/公式数值、未核验的运行时整数范围、缺省或非位置实参;
|
||||||
|
- 需要证明前置条件却没有调用方路径桥接证据的**条件契约**(可先由 \`proof-deps --verify\` 生成/检验独立义务;不能直接用无条件契约代替);
|
||||||
|
- 非穷尽分支、分支后复杂状态合并、无法静态绑定的调用、未覆盖的语句类型;
|
||||||
|
- 任何企图把 \`model_proved\` 直接提升为全语言 \`proved\` 的操作。
|
||||||
|
|
||||||
|
这个子集提供真正的**组合机制**,不宣称任意 WP 自动求解、全部 Marqdo 运行时对应、完整 Hoare Logic 或未限制的程序正确性。
|
||||||
|
|
||||||
|
## 5. 还需要开发哪些内容、哪些明确不需要
|
||||||
|
|
||||||
|
### 当前阶段必需(完成后可停止无界扩张)
|
||||||
|
|
||||||
|
1. 所有源文件上的可寻址索引、定理证据与版本来源绑定有效。
|
||||||
|
2. 一个可用的静态契约组合通路,而非恒定返回、形参返回、算术返回三套互不兼容的证明规则。
|
||||||
|
3. 在明示纯函数子集中支持符号实参、顺序组合、基本条件分支、多层静态模块组合。
|
||||||
|
4. 真 Lean 证书独立重放与完整负例护栏(假结论、来源变化、未解义务、插件、溢出风险)。
|
||||||
|
5. 可查询的 \`evidence.grade\`,让智能体区分证明、模型证明、测试、外部假设、未知与过期。
|
||||||
|
6. 编译、知识索引、原有运行命令和解释器不发生回归。
|
||||||
|
|
||||||
|
### 扩展按需求逐步添加
|
||||||
|
|
||||||
|
- 对实际量子算法或标准库有价值的归纳、循环不变式、递归终止、特殊数据类型、插件实现见证;
|
||||||
|
- 更大范围的契约谓词、复杂路径 WP、数值类型收窄和溢出条件;
|
||||||
|
- 与真实外部测量、实验数据和 agent 轨迹对接的可复现证据。
|
||||||
|
|
||||||
|
### 当前明确不作为完成门槛
|
||||||
|
|
||||||
|
- Lean 对所有 Marqdo 代码自动证明;
|
||||||
|
- 为每个外部 API、未知插件、远程服务或量子硬件建立形式语义;
|
||||||
|
- 完整并发语义、全部递归及任意循环的自动终止证明;
|
||||||
|
- 把不可判定问题或自动证明超时当成系统故障;
|
||||||
|
- 把抽象模型的可证明性与真实环境事实的真实性混为一谈。
|
||||||
|
|
||||||
|
**阶段完成**指有明确的支持清单、严格的拒绝行为、自动 CI 与不夸大的证据等级,而不是新增语言特性就继续追逐无限泛化。
|
||||||
|
|
||||||
|
## 6. 智能体视角:知识制品应怎样使用
|
||||||
|
|
||||||
|
对 agent 的安全接口不应只返回 \`true/false\`,而应返回:
|
||||||
|
|
||||||
|
- 地址:\`SymbolId\` / 锚点;
|
||||||
|
- 执行接口:签名、前置条件、效应权限;
|
||||||
|
- 逻辑保证:受支持契约及其 \`proof_scope\`;
|
||||||
|
- 证据:\`grade\`、来源、版本、独立重放状态;
|
||||||
|
- 未解决义务:待证谓词、未建模效应、需要测试/实验的事实;
|
||||||
|
- 依赖闭包与失效原因。
|
||||||
|
|
||||||
|
智能体可以优先选择 \`model_proved\` 且输入满足限制的算法片段;在真实科研设备/外部系统调用上,同时查询 \`tested\` 证据与 \`assumed\` 的安全边界。过期制品不得直接复用。
|
||||||
|
|
||||||
|
这体现 Marqdo 的原创价值:**文档直接成为知识身份、工具接口、形式契约和执行证据的共同承载体**,而不是简单把 Markdown 文字翻译成另一种程序语言。
|
||||||
|
|
||||||
|
## 7. 验收清单与真实 CI
|
||||||
|
|
||||||
|
核心命令:
|
||||||
|
|
||||||
|
\`\`\`bash
|
||||||
|
marqdo knowledge compose --strict --json .
|
||||||
|
marqdo knowledge replay <generated-certificate> --json .
|
||||||
|
marqdo knowledge proof-deps --verify --json .
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
\`.github/workflows/modular-proof-smoke.yml\` 用真实 Lean 核验统一契约的模块组合和独立重放;\`.github/workflows/knowledge-proof-full-gate.yml\` 跑旧版证明、知识关联、可执行知识和差分测试。
|
||||||
|
|
||||||
|
正例至少包含:跨文件纯函数证明、符号参数、两次连续调用、三层静态模块导入、穷尽分支以及调用方不等式结论。反例至少包含:假契约、修改传递依赖、重放过期证明、模糊签名、未支持运算、动态/外部调用、非穷尽分支,以及错误的证据等级提升。
|
||||||
|
|
||||||
|
任何失败、缺少 Lean、证书与源码不一致、依赖过期或不支持的语义都必须显式拒绝出证或返回未核验状态。运行中的 CI 和缓存报告不能代替最新提交的核验结果。
|
||||||
|
|
||||||
|
## 8. 结论
|
||||||
|
|
||||||
|
Marqdo 知识编译的合理完成形态是 **Verified Knowledge Compiler(可验证知识编译器)**:
|
||||||
|
|
||||||
|
> 能证明的知识生成可复用的形式证明;不能证明的知识保留明确证据与假设;所有知识均可统一寻址、依赖追踪、组合与执行,永不把未证明的内容伪装成已证明。
|
||||||
|
|
||||||
|
证明的是**明确作用域中的性质**,可信性依靠**证据分级、语义对应、来源追踪与受控执行**共同建立。这个目标可验收、可维护,也适合智能体与量子科研应用的发展方向。
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Marqdo v2.9.0 · Full Release / 正式完整版本
|
||||||
|
|
||||||
|
## 核心更新 · Highlights
|
||||||
|
|
||||||
|
Marqdo 2.9.0 将 Markdown 原生可执行知识库推进为 **可验证知识编译器(Verified Knowledge Compiler)**。这不是全语言自动证明工具:Lean 4 仅证明明确支持的逻辑模型,系统继续保存来源、信任边界与失效原因。
|
||||||
|
|
||||||
|
- **统一模块契约**:`knowledge compose` 支持静态纯函数的形参、整数表达式、连续赋值、穷尽分支、多次函数调用和多级模块调用 DAG。
|
||||||
|
- **独立 Lean 模块证明**:每个受支持函数由源码生成可检查模块;调用方导入被调方定理,而不是将定理声明自动当成公理。
|
||||||
|
- **知识锚点**:带标记步骤和定理声明具有稳定身份;`[]()` 用于可寻址引用,绝不自动赋予执行权。
|
||||||
|
- **可信证据**:`model_proved`、`proved`、`tested`、`assumed`、`unknown`、`refuted`、`stale` 严格区分;证明收据绑定源码与依赖闭包,支持失效检测和独立重放。
|
||||||
|
- **兼容性**:旧版 `marqdo prove`、`marqdo call`、知识视图和旧式简单组合证书继续兼容,Rust 与 Lean 差分测试保护语义边界。
|
||||||
|
|
||||||
|
**EN:** Marqdo 2.9.0 introduces a Verified Knowledge Compiler for native Markdown knowledge artifacts, stable anchors, source-derived bounded assume/guarantee composition, and independently replayable Lean 4 certificates. The implementation **does not** claim universal program correctness: supported Lean `Int` theorems are labeled `model_proved` until a runtime semantic correspondence is established.
|
||||||
|
|
||||||
|
## 可信边界 · Verification boundaries
|
||||||
|
|
||||||
|
Lean 自动组合仅适用于源码可精确翻译的无副作用、静态纯整数模型片段;有界整数溢出、动态 `number` / `Formula`、插件效应、未知异常、循环和递归不会自动升级为已证明。前置条件未证明、源码漂移、证书篡改、Lean 不可用或超出支持范围时,必须拒绝出证或明确返回未验证状态。
|
||||||
|
|
||||||
|
Formal logic proves **properties of the declared model**, not empirical facts or the entire runtime. External API responses, quantum hardware measurements and agent behavior require explicit experiment/test/provenance evidence. See [design decision](../design/verified-knowledge-compiler-boundaries.md).
|
||||||
|
|
||||||
|
## 使用 · Usage
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo knowledge .
|
||||||
|
marqdo knowledge compose --strict --json .
|
||||||
|
marqdo knowledge proof-deps --verify --json .
|
||||||
|
marqdo knowledge replay <path/to/composition-certificate.json> --json .
|
||||||
|
```
|
||||||
|
|
||||||
|
A `model_proved` certificate is **not** an unconditional authorization to call plugins or execute side effects.
|
||||||
|
|
||||||
|
## 完整发行产物 · Full distribution
|
||||||
|
|
||||||
|
The `v2.9.0` full packaging workflow produces:
|
||||||
|
- Windows x86_64 native CLI (standalone EXE and bundled ZIP);
|
||||||
|
- Linux x86_64 CLI+libraries bundle;
|
||||||
|
- standard library ZIP, source ZIP and static user-site ZIP;
|
||||||
|
- editor `marqdo-2.9.0.vsix` from the independent editor branch;
|
||||||
|
- both Windows and Linux official native plugin packs, plus the versioned extension source pack when `ext/VERSION` matches `2.9.0`.
|
||||||
|
|
||||||
|
**Release completion is determined by actual CI artifacts and publication evidence, not by this note.** In addition to GitHub assets the repository's [release handbook](../../skills/marqdo-release/index.mq.md) requires CDN/R2 byte parity and Ubuntu PPA publication/apt verification. Missing credentials, failed cross-platform builds or unverified publication channels must be reported as incomplete; never invent hashes or success.
|
||||||
|
|
||||||
|
## 质量验收 · Quality gates
|
||||||
|
|
||||||
|
- `modular-proof-smoke` — actual Lean kernel-checkable intermodule source contracts, negative/stale replay tests.
|
||||||
|
- `knowledge-proof-full-gate` — knowledge, semantic-IR, proof corpus and interpreter/Lean differential tests.
|
||||||
|
- `executable-knowledge` — backward compatibility and knowledge execution tests.
|
||||||
|
- `Release` — verify both platform assets were built from the exact immutable tag.
|
||||||
|
- `release-v2.9` gate — verify metadata, build/test on main and create the immutable tag only when checks pass.
|
||||||
|
|
||||||
|
Version 2.9.0 is a **scoped Verified Knowledge Compiler**, not a theorem that every program or scientific experiment is automatically correct.
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/- Abstract stateful ABI and bounded-loop semantics.
|
||||||
|
These are proof rules, not an axiom that an arbitrary ABI plugin
|
||||||
|
satisfies its declared contract. Implementation witnesses are required. -/
|
||||||
|
namespace MarqdoEffects
|
||||||
|
|
||||||
|
inductive Outcome (σ α ε : Type) where
|
||||||
|
| ok : α → σ → Outcome σ α ε
|
||||||
|
| error : ε → σ → Outcome σ α ε
|
||||||
|
| unknown : Outcome σ α ε
|
||||||
|
|
||||||
|
def bind {σ α β ε : Type}
|
||||||
|
(first : Outcome σ α ε)
|
||||||
|
(next : α → σ → Outcome σ β ε) : Outcome σ β ε :=
|
||||||
|
match first with
|
||||||
|
| .ok value state => next value state
|
||||||
|
| .error e state => .error e state
|
||||||
|
| .unknown => .unknown
|
||||||
|
|
||||||
|
structure AbiContract (σ α β : Type) where
|
||||||
|
requires : σ → α → Prop
|
||||||
|
ensures : σ → α → σ → β → Prop
|
||||||
|
|
||||||
|
def Implements {σ α β ε : Type}
|
||||||
|
(run : σ → α → Outcome σ β ε)
|
||||||
|
(contract : AbiContract σ α β) : Prop :=
|
||||||
|
∀ state arg, contract.requires state arg →
|
||||||
|
∃ value updated, run state arg = .ok value updated ∧
|
||||||
|
contract.ensures state arg updated value
|
||||||
|
|
||||||
|
theorem impl_requires_witness {σ α β ε : Type}
|
||||||
|
(run : σ → α → Outcome σ β ε) (contract : AbiContract σ α β)
|
||||||
|
(h : Implements run contract) (state : σ) (arg : α)
|
||||||
|
(pre : contract.requires state arg) :
|
||||||
|
∃ value updated, run state arg = .ok value updated := by
|
||||||
|
obtain ⟨v, s, hr, _⟩ := h state arg pre
|
||||||
|
exact ⟨v, s, hr⟩
|
||||||
|
|
||||||
|
-- The plugin's failure case remains observable. A declared contract alone
|
||||||
|
-- never rules out this case, unless a concrete implementation proof exists.
|
||||||
|
theorem error_not_abi_success {σ α ε : Type}
|
||||||
|
(reason : ε) (state : σ) :
|
||||||
|
¬ (∃ v s, (Outcome.error reason state : Outcome σ α ε) =
|
||||||
|
Outcome.ok v s) := by
|
||||||
|
intro h
|
||||||
|
obtain ⟨v, s, hs⟩ := h
|
||||||
|
cases hs
|
||||||
|
|
||||||
|
theorem unknown_not_abi_success {σ α ε : Type} :
|
||||||
|
¬ (∃ v s, (Outcome.unknown : Outcome σ α ε) =
|
||||||
|
Outcome.ok v s) := by
|
||||||
|
intro h
|
||||||
|
obtain ⟨v, s, hs⟩ := h
|
||||||
|
cases hs
|
||||||
|
|
||||||
|
theorem bind_preserves_error {σ α β ε : Type}
|
||||||
|
(next : α → σ → Outcome σ β ε) (reason : ε) (state : σ) :
|
||||||
|
bind (Outcome.error reason state) next = Outcome.error reason state := by
|
||||||
|
rfl
|
||||||
|
|
||||||
|
theorem bind_preserves_unknown {σ α β ε : Type}
|
||||||
|
(next : α → σ → Outcome σ β ε) :
|
||||||
|
bind Outcome.unknown next = Outcome.unknown := by
|
||||||
|
rfl
|
||||||
|
|
||||||
|
-- Running out of fuel is UNRESOLVED, not a proof of termination or divergence.
|
||||||
|
def runFuel {σ ε : Type}
|
||||||
|
(step : σ → Outcome σ σ ε) : Nat → σ → Outcome σ σ ε
|
||||||
|
| 0, _ => .unknown
|
||||||
|
| n + 1, state =>
|
||||||
|
match step state with
|
||||||
|
| .ok _ updated => runFuel step n updated
|
||||||
|
| .error e updated => .error e updated
|
||||||
|
| .unknown => .unknown
|
||||||
|
|
||||||
|
theorem fuel_zero_not_success {σ ε : Type}
|
||||||
|
(step : σ → Outcome σ σ ε) (state : σ) :
|
||||||
|
¬ (∃ v s, runFuel step 0 state = Outcome.ok v s) := by
|
||||||
|
intro h
|
||||||
|
obtain ⟨v, s, hs⟩ := h
|
||||||
|
cases hs
|
||||||
|
|
||||||
|
end MarqdoEffects
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
/-
|
||||||
|
Core assume–guarantee composition lemma for Marqdo module contracts.
|
||||||
|
|
||||||
|
This checks the *logic* of composing contracts, NOT that a particular
|
||||||
|
Marqdo function implements one. The compiler must separately establish
|
||||||
|
implementation correspondence and the call-site bridge obligation.
|
||||||
|
-/
|
||||||
|
|
||||||
|
namespace MarqdoModularProof
|
||||||
|
|
||||||
|
structure Contract (α β : Type) where
|
||||||
|
requires : α → Prop
|
||||||
|
ensures : α → β → Prop
|
||||||
|
|
||||||
|
def Implements {α β : Type} (f : α → β) (c : Contract α β) : Prop :=
|
||||||
|
∀ x, c.requires x → c.ensures x (f x)
|
||||||
|
|
||||||
|
def composed {α β γ : Type}
|
||||||
|
(first : Contract α β) (second : Contract β γ) : Contract α γ where
|
||||||
|
requires := first.requires
|
||||||
|
ensures := fun x z =>
|
||||||
|
∃ y, first.ensures x y ∧ second.ensures y z
|
||||||
|
|
||||||
|
-- Caller obligation is explicit. In particular, callee contract validity
|
||||||
|
-- alone does not establish the precondition of the following component.
|
||||||
|
theorem compose_sound {α β γ : Type}
|
||||||
|
(f : α → β) (g : β → γ)
|
||||||
|
(first : Contract α β) (second : Contract β γ)
|
||||||
|
(hf : Implements f first)
|
||||||
|
(hg : Implements g second)
|
||||||
|
(bridge : ∀ x, first.requires x →
|
||||||
|
first.ensures x (f x) → second.requires (f x)) :
|
||||||
|
Implements (fun x => g (f x)) (composed first second) := by
|
||||||
|
intro x hx
|
||||||
|
have hfirst := hf x hx
|
||||||
|
have hnext := hg (f x) (bridge x hx hfirst)
|
||||||
|
exact ⟨f x, hfirst, hnext⟩
|
||||||
|
|
||||||
|
-- Trust-boundary test: the bridge is genuinely needed. Without it,
|
||||||
|
-- the conclusion would fail for suitable partial contracts.
|
||||||
|
example :
|
||||||
|
¬ (∀ (f : Nat → Nat) (g : Nat → Nat)
|
||||||
|
(first : Contract Nat Nat) (second : Contract Nat Nat),
|
||||||
|
Implements f first →
|
||||||
|
Implements g second →
|
||||||
|
Implements (fun x => g (f x)) (composed first second)) := by
|
||||||
|
intro h
|
||||||
|
let f : Nat → Nat := fun _ => 0
|
||||||
|
let g : Nat → Nat := fun y => y
|
||||||
|
let first : Contract Nat Nat := {
|
||||||
|
requires := fun _ => True
|
||||||
|
ensures := fun _ _ => True
|
||||||
|
}
|
||||||
|
let second : Contract Nat Nat := {
|
||||||
|
requires := fun y => y = 1
|
||||||
|
ensures := fun _ z => z = 1
|
||||||
|
}
|
||||||
|
have hf : Implements f first := by
|
||||||
|
intro _ _
|
||||||
|
trivial
|
||||||
|
have hg : Implements g second := by
|
||||||
|
intro y hy
|
||||||
|
simpa [second, g] using hy
|
||||||
|
have hcomp := h f g first second hf hg
|
||||||
|
have target := hcomp 0 True.intro
|
||||||
|
cases target with
|
||||||
|
| intro y hpair =>
|
||||||
|
have impossible : (0 : Nat) = 1 := by
|
||||||
|
simpa [second, g, f] using hpair.right
|
||||||
|
exact Nat.zero_ne_one impossible
|
||||||
|
|
||||||
|
-- Execution is a *partial* result: host/plugin failures and divergence
|
||||||
|
-- must remain visible. Loops/recursion can be reasoned about only after
|
||||||
|
-- separate termination proofs, and ABI effects require a proven contract.
|
||||||
|
inductive Exit (α ε : Type) where
|
||||||
|
| ok (value : α)
|
||||||
|
| error (reason : ε)
|
||||||
|
| diverged
|
||||||
|
|
||||||
|
def sequence {α β ε : Type}
|
||||||
|
(first : Exit α ε) (next : α → Exit β ε) : Exit β ε :=
|
||||||
|
match first with
|
||||||
|
| .ok value => next value
|
||||||
|
| .error e => .error e
|
||||||
|
| .diverged => .diverged
|
||||||
|
|
||||||
|
structure TotalContract (α β : Type) where
|
||||||
|
requires : α → Prop
|
||||||
|
ensures : α → β → Prop
|
||||||
|
|
||||||
|
def Satisfies {α β ε : Type}
|
||||||
|
(run : α → Exit β ε) (c : TotalContract α β) : Prop :=
|
||||||
|
∀ x, c.requires x → ∃ y, run x = .ok y ∧ c.ensures x y
|
||||||
|
|
||||||
|
def combined {α β γ : Type}
|
||||||
|
(first : TotalContract α β)
|
||||||
|
(second : TotalContract β γ) : TotalContract α γ where
|
||||||
|
requires := first.requires
|
||||||
|
ensures := fun x z => ∃ y, first.ensures x y ∧ second.ensures y z
|
||||||
|
|
||||||
|
theorem total_sequence_sound {α β γ ε : Type}
|
||||||
|
(f : α → Exit β ε) (g : β → Exit γ ε)
|
||||||
|
(cf : TotalContract α β) (cg : TotalContract β γ)
|
||||||
|
(hf : Satisfies f cf)
|
||||||
|
(hg : Satisfies g cg)
|
||||||
|
(bridge : ∀ x y, cf.requires x → cf.ensures x y →
|
||||||
|
cg.requires y) :
|
||||||
|
Satisfies (fun x => sequence (f x) g) (combined cf cg) := by
|
||||||
|
intro x hx
|
||||||
|
obtain ⟨y, hrunF, hpostF⟩ := hf x hx
|
||||||
|
obtain ⟨z, hrunG, hpostG⟩ := hg y (bridge x y hx hpostF)
|
||||||
|
refine ⟨z, ?_, ⟨y, hpostF, hpostG⟩⟩
|
||||||
|
simpa [sequence, hrunF] using hrunG
|
||||||
|
|
||||||
|
-- A crashing plugin and a diverging loop cannot satisfy a total contract.
|
||||||
|
theorem error_not_success {α ε : Type} (e : ε) :
|
||||||
|
¬ (∃ v : α, Exit.error e = Exit.ok v) := by
|
||||||
|
intro h
|
||||||
|
obtain ⟨v, hv⟩ := h
|
||||||
|
cases hv
|
||||||
|
|
||||||
|
theorem diverged_not_success {α ε : Type} :
|
||||||
|
¬ (∃ v : α, (Exit.diverged : Exit α ε) = Exit.ok v) := by
|
||||||
|
intro h
|
||||||
|
obtain ⟨v, hv⟩ := h
|
||||||
|
cases hv
|
||||||
|
|
||||||
|
end MarqdoModularProof
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Marqdo 知识锚点 + 自动证明示例
|
||||||
|
|
||||||
|
面向 CLI 2.8.0,原 Markdown 语法不变:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
marqdo knowledge examples/knowledge-proof/
|
||||||
|
marqdo prove examples/knowledge-proof/main.mq.md --json
|
||||||
|
marqdo knowledge examples/knowledge-proof/
|
||||||
|
```
|
||||||
|
|
||||||
|
知识编译后,查看 `.marqdo/anchors.json`、`.marqdo/claims.json`、`.marqdo/refs.json`、`.marqdo/graph/edges.json` 以及 `.marqdo/proof-index.json`(具体输出目录取决于 CLI --out)。
|
||||||
|
证明调用另外生成其证明目录下的 `knowledge-links.json`。运行 CLI 时是否有 Lean 决定该定理能否获得真正的 `proved` 状态;没有 Lean 只能是 `checked` 或 `unverified`。在此案例中,`长度(轨迹)=0` 是函数级定理,并非内部的“计算结果”步骤已经独立证明正确。
|
||||||
|
|
||||||
|
`[计算知识节点](#@计算结果)` 是**同函数内的静态知识引用**。跨文件引用请从 `anchors.json` 拿完整 `mq://...#anchor-...` 地址,不要猜测哈希。两个同名标记不共享地址,会被标记为无公共锚点。
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
---
|
||||||
|
markup: occlusion
|
||||||
|
title: 可寻址、可验证的知识步骤
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## 计算
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 无外部操作 | 长度(轨迹) = 0 | | auto |
|
||||||
|
|
||||||
|
这里的 [计算知识节点](#@计算结果) 和 [定理声明](#@无外部操作) 都是可解析的知识引用;
|
||||||
|
它不会再次执行运算,也不会自动继承函数的形式化证明。
|
||||||
|
|
||||||
|
**答案 = [计算结果](2 * 3)**
|
||||||
|
|
||||||
|
*答案*
|
||||||
Executable → Regular
+1
-1
@@ -1 +1 @@
|
|||||||
2.8.1
|
2.9.0
|
||||||
+12
@@ -97,6 +97,18 @@ pub struct Function {
|
|||||||
pub var_contracts: HashMap<String, crate::contract::Contract>,
|
pub var_contracts: HashMap<String, crate::contract::Contract>,
|
||||||
/// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。
|
/// 定理表(ADR 0010):函数级命题声明;首条可执行语句之前提取,不参与运行。
|
||||||
pub claims: Vec<Claim>,
|
pub claims: Vec<Claim>,
|
||||||
|
/// Non-executable modular assumptions, never accepted as proven facts.
|
||||||
|
pub assumptions: Vec<Assumption>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Author-declared operation contract. Call-site obligations must still be
|
||||||
|
/// proved and callee implementation identity checked before it can be reused.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Assumption {
|
||||||
|
pub op: String,
|
||||||
|
pub premise: Option<String>,
|
||||||
|
pub postcondition: String,
|
||||||
|
pub line: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。
|
/// 一条定理声明(设计 §7.1):`| 定理 | 结论 | 前提 | 策略 |` 的一行。
|
||||||
|
|||||||
@@ -369,6 +369,43 @@ pub fn parse_claim_table(
|
|||||||
Some(Ok(rows))
|
Some(Ok(rows))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Parse the v2.9 modular assumption table. An assumption is metadata,
|
||||||
|
/// never a runtime statement or an independently verified theorem.
|
||||||
|
pub fn parse_assumption_table(
|
||||||
|
pairs: &[(String, Expr)], line: u32,
|
||||||
|
) -> Option<std::result::Result<Vec<crate::ast::Assumption>,String>> {
|
||||||
|
const OP: &[&str] = &["假设","assumption"];
|
||||||
|
const PRE: &[&str] = &["前置","requires","precondition"];
|
||||||
|
const POST: &[&str] = &["后置","ensures","postcondition"];
|
||||||
|
let headers:Vec<String>=pairs.iter().map(|(k,_)|k.clone()).collect();
|
||||||
|
let op=find_col(&headers,OP)?;
|
||||||
|
let post=match find_col(&headers,POST){
|
||||||
|
Some(i)=>i,
|
||||||
|
None=>return Some(Err("assumption table requires a 后置 / ensures column".into()))
|
||||||
|
};
|
||||||
|
let op_names=col_rows(&pairs[op].1).unwrap_or_default();
|
||||||
|
let posts=claim_col_rows(&pairs[post].1);
|
||||||
|
let pres=find_col(&headers,PRE).map(|i|claim_col_rows(&pairs[i].1));
|
||||||
|
if op_names.len()!=posts.len()
|
||||||
|
|| pres.as_ref().is_some_and(|p|p.len()!=op_names.len()) {
|
||||||
|
return Some(Err("assumption table columns have different row counts".into()));
|
||||||
|
}
|
||||||
|
let mut results=Vec::new();
|
||||||
|
for (i,name) in op_names.into_iter().enumerate(){
|
||||||
|
if name.trim().is_empty() || posts[i].trim().is_empty() {
|
||||||
|
return Some(Err(format!("assumption row {} lacks operation or postcondition",i+1)));
|
||||||
|
}
|
||||||
|
results.push(crate::ast::Assumption{
|
||||||
|
op:name.trim().to_string(),
|
||||||
|
premise:pres.as_ref().and_then(|p|p.get(i))
|
||||||
|
.map(|s|s.trim().to_string()).filter(|s|!s.is_empty()),
|
||||||
|
postcondition:posts[i].trim().to_string(),
|
||||||
|
line,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Some(Ok(results))
|
||||||
|
}
|
||||||
|
|
||||||
/// 定理表形状错误(`check --proof` 才报;默认关)。
|
/// 定理表形状错误(`check --proof` 才报;默认关)。
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct ClaimTableError {
|
pub struct ClaimTableError {
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ pub fn compile(opts: KnowledgeOptions) -> Result<KnowledgeGraph> {
|
|||||||
// Legacy EKC retrieval catalog writes only under `ekc/` and must never
|
// Legacy EKC retrieval catalog writes only under `ekc/` and must never
|
||||||
// overwrite `graph/edges.json` (G01).
|
// overwrite `graph/edges.json` (G01).
|
||||||
let semantic_root = if opts.path.is_file() {
|
let semantic_root = if opts.path.is_file() {
|
||||||
opts.path.parent().unwrap_or_else(|| Path::new(".")).to_path_buf()
|
opts.path.parent().filter(|p| !p.as_os_str().is_empty())
|
||||||
|
.unwrap_or_else(|| Path::new(".")).to_path_buf()
|
||||||
} else {
|
} else {
|
||||||
opts.path.clone()
|
opts.path.clone()
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,490 @@
|
|||||||
|
//! Reusable, independently replayable **restricted** module composition.
|
||||||
|
//!
|
||||||
|
//! Scope: pure typed-int forwarding caller and source-constant callee. Two
|
||||||
|
//! independently compiled Lean modules: caller imports the callee's theorem,
|
||||||
|
//! not its implementation. Every unmodeled construct fails closed.
|
||||||
|
//! This is not a theorem about arbitrary Marqdo programs.
|
||||||
|
use std::{fs,path::Path,time::Duration};
|
||||||
|
use anyhow::{Context,Result};
|
||||||
|
use serde_json::{json,Value};
|
||||||
|
use sha2::{Digest,Sha256};
|
||||||
|
use crate::{
|
||||||
|
ast::{CallExpr,Expr,Function,Literal,Stmt},
|
||||||
|
prove::driver::{Toolchain,compile_import_module},
|
||||||
|
sema::ir::{Compilation,SemanticArtifact,BoundCall}
|
||||||
|
};
|
||||||
|
fn sha(input:&[u8])->String{format!("sha256:{:x}",Sha256::digest(input))}
|
||||||
|
fn lookup<'a>(items:&'a [Function],path:&[&str])->Option<&'a Function>{
|
||||||
|
let (first,rest)=path.split_first()?;
|
||||||
|
let fun=items.iter().find(|f|f.name==*first)?;
|
||||||
|
if rest.is_empty(){Some(fun)}else{lookup(&fun.children,rest)}
|
||||||
|
}
|
||||||
|
fn function(compiled:&Compilation,a:&SemanticArtifact)->Option<Function>{
|
||||||
|
let raw=fs::read_to_string(compiled.semantics.root.join(&a.source.file)).ok()?;
|
||||||
|
let doc=crate::parse::parse_source(&raw).ok()?;
|
||||||
|
let path=a.display_name.split('.').collect::<Vec<_>>();
|
||||||
|
lookup(&doc.functions,&path).cloned()
|
||||||
|
}
|
||||||
|
fn call_inside(expr:&Expr)->Option<&CallExpr>{
|
||||||
|
match expr{
|
||||||
|
Expr::Call(c)=>Some(c),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>call_inside(inner),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn forwarded(fun:&Function)->Option<&CallExpr>{
|
||||||
|
match fun.body.as_slice(){
|
||||||
|
[Stmt::Return{value,..}]=>call_inside(value),
|
||||||
|
[Stmt::Assign{name,value,..},Stmt::Return{value:Expr::Var(v),..}]
|
||||||
|
if name==v=>call_inside(value),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn constant_return(fun:&Function)->Option<i64>{
|
||||||
|
match fun.body.as_slice(){
|
||||||
|
[Stmt::Return{value:Expr::Literal(Literal::Int(n)),..}]=>Some(*n),
|
||||||
|
[Stmt::Return{value:Expr::Occluded{payload:Some(v),..},..}] =>
|
||||||
|
if let Expr::Literal(Literal::Int(n))=v.as_ref(){Some(*n)}else{None},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn claim_is_constant(compiled:&Compilation,owner:&SemanticArtifact,n:i64)->bool{
|
||||||
|
// Treat duplicate eligible claims as ambiguity, never as evidence.
|
||||||
|
// A single matching declaration is required at the exact owner SymbolId.
|
||||||
|
owner.symbol_id.as_ref().is_some_and(|id|
|
||||||
|
compiled.semantics.claims.iter().filter(|c|
|
||||||
|
c.owner==*id
|
||||||
|
&& c.premise.as_deref().map_or(true,|p|p.trim().is_empty())
|
||||||
|
&& c.conclusion.trim()==format!("结果 = {n}")).count()==1)
|
||||||
|
}
|
||||||
|
fn candidate(compiled:&Compilation,call:&BoundCall)
|
||||||
|
->Option<(String,String,String,i64)>{
|
||||||
|
let ca=compiled.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.caller) && a.kind=="function")?;
|
||||||
|
let ce=compiled.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target) && a.kind=="function")?;
|
||||||
|
// The contract is strictly inter-module: local recursion and aliases
|
||||||
|
// must not inherit an import-composition certificate.
|
||||||
|
if ca.source.file==ce.source.file || call.caller==call.target{return None}
|
||||||
|
if !ca.effects.is_pure()||!ce.effects.is_pure()
|
||||||
|
||!call.required_effects.is_pure()
|
||||||
|
||call.control_blocker.is_some()||!call.path_guards.is_empty(){return None}
|
||||||
|
let caller=function(compiled,ca)?;
|
||||||
|
let callee=function(compiled,ce)?;
|
||||||
|
let forwarded=forwarded(&caller)?;
|
||||||
|
let runtime=forwarded.for_evaluation().ok()?;
|
||||||
|
if crate::sema::bind::call_display(&runtime)!=call.call_site
|
||||||
|
||compiled.semantics.bound_calls.iter().filter(|item|
|
||||||
|
item.caller==call.caller).count()!=1 {return None}
|
||||||
|
if runtime.path.as_ref().is_none()||runtime.receiver.is_some()
|
||||||
|
||caller.is_object()||callee.is_object(){return None}
|
||||||
|
let n=constant_return(&callee)?;
|
||||||
|
if !claim_is_constant(compiled,ca,n)||!claim_is_constant(compiled,ce,n){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let cs=ca.signature.as_ref()?;
|
||||||
|
let es=ce.signature.as_ref()?;
|
||||||
|
if cs.params.len()!=caller.params.len()
|
||||||
|
||es.params.len()!=callee.params.len()
|
||||||
|
||es.params.len()!=call.args.len()
|
||||||
|
||call.args.len()!=runtime.args.len(){return None}
|
||||||
|
if cs.params.iter().chain(es.params.iter())
|
||||||
|
// Marqdo currently canonicalizes int/num/float to "number".
|
||||||
|
// This certificate is explicitly about the *Lean Int model*, NOT
|
||||||
|
// all runtime Number variants. Runtime-equivalence remains false.
|
||||||
|
.any(|p|!p.ty.eq_ignore_ascii_case("number")||!p.required){return None}
|
||||||
|
let arg_expr=call.args.iter().zip(es.params.iter()).map(|(a,p)|{
|
||||||
|
if a.name.as_ref().is_some_and(|x|x!=&p.name){return None}
|
||||||
|
if let Some(v)=a.integer {return Some(format!("({v} : Int)"))}
|
||||||
|
let symbol=a.symbol.as_ref()?;
|
||||||
|
let position=cs.params.iter().position(|x|x.name==*symbol)?;
|
||||||
|
Some(format!("v{position}"))
|
||||||
|
}).collect::<Option<Vec<_>>>()?.join(" ");
|
||||||
|
let callee_binders=(0..es.params.len()).map(|i|format!("(v{i} : Int)"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
let caller_binders=(0..cs.params.len()).map(|i|format!("(v{i} : Int)"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
let callee_args=(0..es.params.len()).map(|i|format!("v{i}"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
let caller_args=(0..cs.params.len()).map(|i|format!("v{i}"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
// This callee theorem is verified from the translated source *inside its
|
||||||
|
// own module*. The caller only imports its proved interface theorem.
|
||||||
|
let callee_src=format!(
|
||||||
|
"-- pure typed-int fragment of {}\n\
|
||||||
|
def callee {callee_binders} : Int := ({n} : Int)\n\
|
||||||
|
theorem callee_contract {callee_binders} : callee {callee_args} = ({n} : Int) := by rfl\n",
|
||||||
|
ce.artifact_id.0);
|
||||||
|
let caller_src=format!(
|
||||||
|
"import CalleeModule\n\
|
||||||
|
-- exact forwarded import call from {}\n\
|
||||||
|
def caller {caller_binders} : Int := callee {arg_expr}\n\
|
||||||
|
theorem caller_contract {caller_binders} : caller {caller_args} = ({n} : Int) := by\n\
|
||||||
|
\x20\x20simpa [caller] using (callee_contract {arg_expr})\n",
|
||||||
|
ca.artifact_id.0);
|
||||||
|
Some((callee_src,caller_src,format!("{}#{}",ca.artifact_id.0,
|
||||||
|
ce.artifact_id.0),n))
|
||||||
|
}
|
||||||
|
/// Explain why a caller cannot receive a scoped composition certificate.
|
||||||
|
/// Missing evidence is reported, never fixed up by guessing call identities.
|
||||||
|
fn rejection_diagnostics(c:&Compilation,call:&BoundCall)->Value{
|
||||||
|
let caller=c.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.caller));
|
||||||
|
let callee=c.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target));
|
||||||
|
let cf=caller.and_then(|a|function(c,a));
|
||||||
|
let ef=callee.and_then(|a|function(c,a));
|
||||||
|
let constant=ef.as_ref().and_then(constant_return);
|
||||||
|
json!({
|
||||||
|
"caller_semantics_resolved":caller.is_some(),
|
||||||
|
"callee_semantics_resolved":callee.is_some(),
|
||||||
|
"caller_effects":caller.map(|a|a.effects.values()),
|
||||||
|
"callee_effects":callee.map(|a|a.effects.values()),
|
||||||
|
"call_effects":call.required_effects.values(),
|
||||||
|
"caller_forward_shape":cf.as_ref().and_then(forwarded).is_some(),
|
||||||
|
"caller_ast_body":cf.as_ref().map(|f|format!("{:?}",f.body)),
|
||||||
|
"callee_ast_body":ef.as_ref().map(|f|format!("{:?}",f.body)),
|
||||||
|
"callee_constant_return":constant,
|
||||||
|
"runtime_forward_name":cf.as_ref().and_then(forwarded)
|
||||||
|
.and_then(|f|f.for_evaluation().ok())
|
||||||
|
.map(|c|crate::sema::bind::call_display(&c)),
|
||||||
|
"bound_call_name":call.call_site,
|
||||||
|
"caller_bound_call_count":c.semantics.bound_calls.iter()
|
||||||
|
.filter(|item|item.caller==call.caller).count(),
|
||||||
|
"caller_has_expected_claim":caller.zip(constant).is_some_and(|(a,n)|
|
||||||
|
claim_is_constant(c,a,n)),
|
||||||
|
"callee_has_expected_claim":callee.zip(constant).is_some_and(|(a,n)|
|
||||||
|
claim_is_constant(c,a,n)),
|
||||||
|
"caller_signature":caller.and_then(|a|a.signature.as_ref())
|
||||||
|
.map(|s|s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,
|
||||||
|
"required":p.required})).collect::<Vec<_>>()),
|
||||||
|
"callee_signature":callee.and_then(|a|a.signature.as_ref())
|
||||||
|
.map(|s|s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,
|
||||||
|
"required":p.required})).collect::<Vec<_>>()),
|
||||||
|
"actual_arguments":call.args.iter().map(|a|json!({
|
||||||
|
"name":a.name,"symbol":a.symbol,"integer":a.integer})).collect::<Vec<_>>(),
|
||||||
|
"path_guards":call.path_guards,"control_blocker":call.control_blocker
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// Emit one sealed bundle per eligible call. An unsuccessful Lean command
|
||||||
|
/// never creates a certificate; the JSON report carries the failure.
|
||||||
|
pub fn prove(compiled:&Compilation,out:&Path,toolchain:&Toolchain)->Result<Value>{
|
||||||
|
let mut records=Vec::new();
|
||||||
|
for call in &compiled.semantics.bound_calls{
|
||||||
|
if super::unified::covers(compiled,&call.caller){continue}
|
||||||
|
let Some((source,client,identity,n))=candidate(compiled,call) else {
|
||||||
|
// Projection contracts have their own independently replayable
|
||||||
|
// backend, and must not also appear as unsupported constant claims.
|
||||||
|
if super::projection::eligible(compiled,call)
|
||||||
|
||super::expression::eligible(compiled,call){continue}
|
||||||
|
records.push(json!({"caller":call.caller.as_str(),
|
||||||
|
"callee":call.target.as_str(),"status":"unsupported_fragment",
|
||||||
|
"reason":"requires_pure_number_contract_int_model_forwarder_with_constant_claims",
|
||||||
|
"diagnostics":rejection_diagnostics(compiled,call)}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let key=sha(format!("{}|{}|{}|{}",identity,
|
||||||
|
compiled.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.caller))
|
||||||
|
.map(|a|a.hashes.closure.0.as_str()).unwrap_or(""),
|
||||||
|
compiled.semantics.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target))
|
||||||
|
.map(|a|a.hashes.closure.0.as_str()).unwrap_or(""),
|
||||||
|
toolchain.version).as_bytes());
|
||||||
|
let folder=out.join("composed").join(&key[7..23]);
|
||||||
|
fs::create_dir_all(&folder)?;
|
||||||
|
let callee=folder.join("CalleeModule.lean");
|
||||||
|
let caller=folder.join("CallerModule.lean");
|
||||||
|
let built=folder.join("CalleeModule.olean");
|
||||||
|
fs::write(&callee,&source)?;
|
||||||
|
fs::write(&caller,&client)?;
|
||||||
|
let run=(|| ->Result<()>{
|
||||||
|
compile_import_module(toolchain,&callee,&built,&folder,
|
||||||
|
Duration::from_secs(120)).context("callee interface")?;
|
||||||
|
let verified=folder.join("CallerModule.olean");
|
||||||
|
compile_import_module(toolchain,&caller,&verified,&folder,
|
||||||
|
Duration::from_secs(120)).context("caller composition")?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if let Err(e)=run{
|
||||||
|
let _=fs::remove_file(folder.join("composition-certificate.json"));
|
||||||
|
records.push(json!({"identity":identity,
|
||||||
|
"status":"lean_rejected","error":format!("{e:#}")}));
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let cert=json!({
|
||||||
|
"schema_version":1,"kind":"marqdo_restricted_composition",
|
||||||
|
"scope":"number_contract_int_model_pure_forwarder_constant_result",
|
||||||
|
"status":"lean_kernel_proved_model",
|
||||||
|
"identity":identity,"caller":call.caller.as_str(),
|
||||||
|
"callee":call.target.as_str(),
|
||||||
|
"claimed_result":n,
|
||||||
|
"callee_source_sha256":sha(source.as_bytes()),
|
||||||
|
"caller_source_sha256":sha(client.as_bytes()),
|
||||||
|
"callee_compiled_sha256":sha(&fs::read(&built)?),
|
||||||
|
"caller_compiled_sha256":sha(&fs::read(folder.join("CallerModule.olean"))?),
|
||||||
|
"toolchain":toolchain.version,
|
||||||
|
"source_closures":compiled.semantics.artifacts.iter()
|
||||||
|
.filter(|a|a.symbol_id.as_ref()==Some(&call.caller)
|
||||||
|
||a.symbol_id.as_ref()==Some(&call.target))
|
||||||
|
.map(|a|json!({"id":a.artifact_id.0,
|
||||||
|
"closure":a.hashes.closure.0})).collect::<Vec<_>>(),
|
||||||
|
"independent_replay":"CalleeModule.lean then CallerModule.lean"
|
||||||
|
});
|
||||||
|
let receipt=folder.join("composition-certificate.json");
|
||||||
|
fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?;
|
||||||
|
records.push(json!({"identity":identity,
|
||||||
|
"status":"lean_kernel_proved_model","artifact":receipt,
|
||||||
|
"scope":"number_contract_int_model_pure_forwarder_constant_result"}));
|
||||||
|
}
|
||||||
|
records.extend(super::projection::prove(compiled,out,toolchain)?);
|
||||||
|
records.extend(super::expression::prove(compiled,out,toolchain)?);
|
||||||
|
records.extend(super::unified::prove(compiled,out,toolchain)?);
|
||||||
|
for record in &mut records {
|
||||||
|
if record["evidence"].is_null(){
|
||||||
|
record["evidence"]=if record["status"]=="lean_kernel_proved_model"{
|
||||||
|
super::evidence::model_proved()
|
||||||
|
}else{super::evidence::unknown("unproved_or_unsupported_fragment")};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(json!({"schema_version":1,"role":"restricted_composed_lean_module",
|
||||||
|
"results":records,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false}))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// Strict receipt-to-source correspondence; any duplicate row is a hard failure.
|
||||||
|
fn ensure_exact_closures(
|
||||||
|
rows:usize,
|
||||||
|
received:&std::collections::BTreeSet<(String,String)>,
|
||||||
|
expected:&std::collections::BTreeSet<(String,String)>
|
||||||
|
)->Result<()>{
|
||||||
|
anyhow::ensure!(rows==expected.len() && received==expected,
|
||||||
|
"proof.compose_stale_or_ambiguous_closure");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replay a composition certificate *against the current project source*.
|
||||||
|
/// The certificate never supplies Lean source code: it must byte-match source
|
||||||
|
/// recompiled from the current Marqdo AST, and both Lean modules are rechecked.
|
||||||
|
pub fn replay(compiled:&Compilation,certificate:&Path,lean:&Toolchain)->Result<Value>{
|
||||||
|
let receipt:Value=serde_json::from_slice(&fs::read(certificate)?)?;
|
||||||
|
if receipt["kind"]=="marqdo_parameter_projection_composition"{
|
||||||
|
return super::projection::replay(compiled,certificate,lean)
|
||||||
|
}
|
||||||
|
if receipt["kind"]=="marqdo_pure_expression_composition"{
|
||||||
|
return super::expression::replay(compiled,certificate,lean)
|
||||||
|
}
|
||||||
|
if receipt["kind"]=="marqdo_unified_modular_contract"{
|
||||||
|
return super::unified::replay(compiled,certificate,lean)
|
||||||
|
}
|
||||||
|
anyhow::ensure!(receipt["schema_version"]==1
|
||||||
|
&&receipt["kind"]=="marqdo_restricted_composition"
|
||||||
|
&&receipt["scope"]=="number_contract_int_model_pure_forwarder_constant_result"
|
||||||
|
&&receipt["status"]=="lean_kernel_proved_model",
|
||||||
|
"proof.compose_invalid_certificate: unexpected status or scope");
|
||||||
|
anyhow::ensure!(receipt["toolchain"]==lean.version,
|
||||||
|
"proof.compose_stale_toolchain");
|
||||||
|
let identity=receipt["identity"].as_str().context("missing identity")?;
|
||||||
|
// A certificate identity is a unique proof subject, not a search hint.
|
||||||
|
// Reject ambiguous candidates instead of silently selecting the first.
|
||||||
|
let matching=compiled.semantics.bound_calls.iter()
|
||||||
|
.filter_map(|call|{
|
||||||
|
let (a,b,id,n)=candidate(compiled,call)?;
|
||||||
|
(id==identity).then_some((a,b,id,n,call))
|
||||||
|
}).collect::<Vec<_>>();
|
||||||
|
anyhow::ensure!(matching.len()==1,
|
||||||
|
"proof.compose_ambiguous_or_stale_source: expected exactly one callsite");
|
||||||
|
let (callee,caller,_,n,call)=matching.into_iter().next()
|
||||||
|
.context("proof.compose_missing_candidate")?;
|
||||||
|
anyhow::ensure!(receipt["claimed_result"]==n,
|
||||||
|
"proof.compose_claim_changed");
|
||||||
|
anyhow::ensure!(receipt["caller"]==call.caller.as_str()
|
||||||
|
&&receipt["callee"]==call.target.as_str(),
|
||||||
|
"proof.compose_symbol_changed");
|
||||||
|
// Exact-set comparison blocks duplicate, injected, and omitted dependency
|
||||||
|
// rows. The receipt does not get to choose the dependency closure.
|
||||||
|
let expected_closures=compiled.semantics.artifacts.iter()
|
||||||
|
.filter(|a|a.symbol_id.as_ref()==Some(&call.caller)
|
||||||
|
||a.symbol_id.as_ref()==Some(&call.target))
|
||||||
|
.map(|a|(a.artifact_id.0.clone(),a.hashes.closure.0.clone()))
|
||||||
|
.collect::<std::collections::BTreeSet<_>>();
|
||||||
|
anyhow::ensure!(expected_closures.len()==2,
|
||||||
|
"proof.compose_ambiguous_artifact");
|
||||||
|
let received=receipt["source_closures"].as_array()
|
||||||
|
.context("proof.compose_missing_source_closures")?;
|
||||||
|
let actual_closures=received.iter().map(|r|{
|
||||||
|
Ok((r["id"].as_str().context("proof.compose_invalid_closure_id")?.to_owned(),
|
||||||
|
r["closure"].as_str().context("proof.compose_invalid_closure_hash")?.to_owned()))
|
||||||
|
}).collect::<Result<std::collections::BTreeSet<_>>>()?;
|
||||||
|
ensure_exact_closures(received.len(),&actual_closures,&expected_closures)?;
|
||||||
|
let folder=certificate.parent().context("missing certificate parent")?;
|
||||||
|
let callee_path=folder.join("CalleeModule.lean");
|
||||||
|
let caller_path=folder.join("CallerModule.lean");
|
||||||
|
anyhow::ensure!(fs::read_to_string(&callee_path)?==callee
|
||||||
|
&&fs::read_to_string(&caller_path)?==caller,
|
||||||
|
"proof.compose_generated_source_mismatch");
|
||||||
|
anyhow::ensure!(receipt["callee_source_sha256"]==sha(callee.as_bytes())
|
||||||
|
&&receipt["caller_source_sha256"]==sha(caller.as_bytes()),
|
||||||
|
"proof.compose_hash_mismatch");
|
||||||
|
let callee_obj=folder.join("CalleeModule.olean");
|
||||||
|
let caller_obj=folder.join("CallerModule.olean");
|
||||||
|
compile_import_module(lean,&callee_path,&callee_obj,folder,
|
||||||
|
Duration::from_secs(120))?;
|
||||||
|
compile_import_module(lean,&caller_path,&caller_obj,folder,
|
||||||
|
Duration::from_secs(120))?;
|
||||||
|
anyhow::ensure!(receipt["callee_compiled_sha256"]==sha(&fs::read(&callee_obj)?)
|
||||||
|
&&receipt["caller_compiled_sha256"]==sha(&fs::read(&caller_obj)?),
|
||||||
|
"proof.compose_replay_output_changed");
|
||||||
|
Ok(json!({"schema_version":1,"kind":"independent_composition_replay",
|
||||||
|
"status":"lean_kernel_replayed","scope":receipt["scope"],
|
||||||
|
"identity":identity,"current_source_verified":true,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn certificate_closures_must_be_exact_and_unique(){
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
let expected=BTreeSet::from([
|
||||||
|
("caller".into(),"sha256:a".into()),
|
||||||
|
("callee".into(),"sha256:b".into())
|
||||||
|
]);
|
||||||
|
assert!(ensure_exact_closures(2,&expected,&expected).is_ok());
|
||||||
|
assert!(ensure_exact_closures(3,&expected,&expected).is_err());
|
||||||
|
let missing=BTreeSet::from([("caller".into(),"sha256:a".into())]);
|
||||||
|
assert!(ensure_exact_closures(1,&missing,&expected).is_err());
|
||||||
|
let mut injected=expected.clone();
|
||||||
|
injected.insert(("third".into(),"sha256:c".into()));
|
||||||
|
assert!(ensure_exact_closures(3,&injected,&expected).is_err());
|
||||||
|
let mut changed=expected.clone();
|
||||||
|
changed.remove(&("callee".into(),"sha256:b".into()));
|
||||||
|
changed.insert(("callee".into(),"sha256:wrong".into()));
|
||||||
|
assert!(ensure_exact_closures(2,&changed,&expected).is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn pure_forwarder_can_be_compiled_into_two_independent_lean_sources(){
|
||||||
|
let root=std::env::temp_dir().join(
|
||||||
|
format!("marqdo-compose-unit-{}",std::process::id()));
|
||||||
|
let _=fs::remove_dir_all(&root);
|
||||||
|
fs::create_dir_all(&root).unwrap();
|
||||||
|
fs::write(root.join("math.mq.md"),r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# math
|
||||||
|
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| fixed | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#).unwrap();
|
||||||
|
fs::write(root.join("main.mq.md"),r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## forward
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| same | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
**v = [调用](math.math.exact(`n`))**
|
||||||
|
*v*
|
||||||
|
"#).unwrap();
|
||||||
|
let c=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=c.semantics.bound_calls.iter().find(|x|
|
||||||
|
x.call_site=="math.math.exact").unwrap();
|
||||||
|
let (callee,caller,_,result)=candidate(&c,call)
|
||||||
|
.unwrap_or_else(||panic!("composition candidate rejected: {}",
|
||||||
|
rejection_diagnostics(&c,call)));
|
||||||
|
assert_eq!(result,2);
|
||||||
|
assert!(callee.contains("theorem callee_contract"));
|
||||||
|
assert!(caller.starts_with("import CalleeModule"));
|
||||||
|
assert!(caller.contains("using (callee_contract"));
|
||||||
|
// Duplicate matching declarations must not be treated as a
|
||||||
|
// unique contractual source of truth.
|
||||||
|
let duplicate=std::fs::read_to_string(root.join("math.mq.md")).unwrap()
|
||||||
|
.replace("| fixed | 结果 = 2 | auto |",
|
||||||
|
"| fixed | 结果 = 2 | auto |\n| other | 结果 = 2 | auto |");
|
||||||
|
std::fs::write(root.join("math.mq.md"),duplicate).unwrap();
|
||||||
|
let ambiguous=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let ambiguous_call=ambiguous.semantics.bound_calls.iter().find(|x|
|
||||||
|
x.call_site=="math.math.exact").unwrap();
|
||||||
|
assert!(candidate(&ambiguous,ambiguous_call).is_none(),
|
||||||
|
"duplicate constant claims must fail closed");
|
||||||
|
std::fs::write(root.join("math.mq.md"),r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# math
|
||||||
|
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| fixed | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#).unwrap();
|
||||||
|
// Branching is explicitly outside the certificate scope.
|
||||||
|
fs::write(root.join("main.mq.md"),r#"---
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## forward
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| same | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
1. `n` > 0
|
||||||
|
**v = [调用](math.math.exact(`n`))**
|
||||||
|
2. *
|
||||||
|
**v = 0**
|
||||||
|
|
||||||
|
*v*
|
||||||
|
"#).unwrap();
|
||||||
|
let changed=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let guarded=changed.semantics.bound_calls.iter().find(|x|
|
||||||
|
x.call_site=="math.math.exact").unwrap();
|
||||||
|
assert!(candidate(&changed,guarded).is_none());
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
//! Explicit evidence levels: a Lean proof of the mathematical model is
|
||||||
|
//! categorically different from a proof about the dynamic Marqdo runtime.
|
||||||
|
//! Neither source metadata nor an asserted plugin contract grants authority.
|
||||||
|
use serde::{Serialize,Deserialize};
|
||||||
|
use serde_json::{json,Value};
|
||||||
|
|
||||||
|
#[derive(Clone,Copy,Debug,PartialEq,Eq,Serialize,Deserialize)]
|
||||||
|
#[serde(rename_all="snake_case")]
|
||||||
|
pub enum EvidenceGrade{
|
||||||
|
/// Only when correspondence to supported runtime semantics was proven.
|
||||||
|
Proved,
|
||||||
|
/// Kernel checked theorem over an explicitly identified abstract model.
|
||||||
|
ModelProved,
|
||||||
|
/// Observed by supplied tests/experiments. Not a mathematical proof.
|
||||||
|
Tested,
|
||||||
|
/// Trust or environmental assertion, not proven from source.
|
||||||
|
Assumed,
|
||||||
|
/// Insufficient evidence, timeout, unsupported language, or no proof.
|
||||||
|
Unknown,
|
||||||
|
/// An actual counterexample, never just a missing Lean derivation.
|
||||||
|
Refuted,
|
||||||
|
/// The source, contract, toolchain, or dependency changed.
|
||||||
|
Stale
|
||||||
|
}
|
||||||
|
impl EvidenceGrade{
|
||||||
|
pub fn as_str(self)->&'static str{
|
||||||
|
match self{
|
||||||
|
Self::Proved=>"proved",Self::ModelProved=>"model_proved",
|
||||||
|
Self::Tested=>"tested",Self::Assumed=>"assumed",
|
||||||
|
Self::Unknown=>"unknown",Self::Refuted=>"refuted",
|
||||||
|
Self::Stale=>"stale"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn record(grade:EvidenceGrade,basis:&str,kernel_replayed:bool,
|
||||||
|
runtime_correspondence:bool)->Value{
|
||||||
|
let effective=if grade==EvidenceGrade::Proved && !runtime_correspondence{
|
||||||
|
EvidenceGrade::ModelProved
|
||||||
|
}else{grade};
|
||||||
|
json!({
|
||||||
|
"schema_version":1,"grade":effective.as_str(),"basis":basis,
|
||||||
|
"model":"lean_int_abstract",
|
||||||
|
"kernel_replayed":kernel_replayed,
|
||||||
|
"runtime_correspondence_verified":runtime_correspondence,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false,
|
||||||
|
"not_execution_authority":true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// Kernel checked at issuance; no independent replay has happened yet.
|
||||||
|
pub fn model_proved()->Value{
|
||||||
|
record(EvidenceGrade::ModelProved,"source_regenerated_lean_kernel",
|
||||||
|
false,false)
|
||||||
|
}
|
||||||
|
/// Source-regenerated modules were independently recompiled on replay.
|
||||||
|
pub fn model_replayed()->Value{
|
||||||
|
record(EvidenceGrade::ModelProved,"independently_replayed_lean_kernel",
|
||||||
|
true,false)
|
||||||
|
}
|
||||||
|
pub fn unknown(reason:&str)->Value{
|
||||||
|
record(EvidenceGrade::Unknown,reason,false,false)
|
||||||
|
}
|
||||||
|
pub fn assumed()->Value{
|
||||||
|
record(EvidenceGrade::Assumed,"external_or_author_declaration",false,false)
|
||||||
|
}
|
||||||
|
pub fn for_receipt(status:&str,usable:bool,kernel_replayed:bool)->Value{
|
||||||
|
if status=="stale"{
|
||||||
|
return record(EvidenceGrade::Stale,"source_or_dependency_changed",
|
||||||
|
false,false)
|
||||||
|
}
|
||||||
|
if !usable {
|
||||||
|
return unknown(if status=="ambiguous"{"ambiguous_receipt"}
|
||||||
|
else if status=="unproved"{"lean_not_proved"}
|
||||||
|
else{"no_trusted_replayable_proof"})
|
||||||
|
}
|
||||||
|
if status=="proved"{
|
||||||
|
return record(EvidenceGrade::ModelProved,
|
||||||
|
"source_bound_lean_certificate",kernel_replayed,false)
|
||||||
|
}
|
||||||
|
unknown("unsupported_receipt_status")
|
||||||
|
}
|
||||||
|
pub fn with_grade(grade:EvidenceGrade,source:&str)->Value{
|
||||||
|
// This constructor is for explicitly sourced tests/assumptions and is
|
||||||
|
// intentionally never allowed to create runtime-level Proved by fiat.
|
||||||
|
record(grade,source,false,false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests{
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn grades_do_not_promote_abstract_integer_proofs(){
|
||||||
|
let fresh=model_proved();
|
||||||
|
assert_eq!(fresh["kernel_replayed"],false);
|
||||||
|
assert_eq!(fresh["grade"],"model_proved");
|
||||||
|
let replayed=model_replayed();
|
||||||
|
assert_eq!(replayed["kernel_replayed"],true);
|
||||||
|
let proved=for_receipt("proved",true,true);
|
||||||
|
assert_eq!(proved["grade"],"model_proved");
|
||||||
|
assert_eq!(proved["full_marqdo_runtime_semantics_proved"],false);
|
||||||
|
assert_eq!(with_grade(EvidenceGrade::Proved,"asserted")["grade"],
|
||||||
|
"model_proved");
|
||||||
|
assert_eq!(for_receipt("stale",false,false)["grade"],"stale");
|
||||||
|
assert_eq!(for_receipt("unproved",false,false)["grade"],"unknown");
|
||||||
|
assert_eq!(for_receipt("ambiguous",false,false)["grade"],"unknown");
|
||||||
|
assert_eq!(with_grade(EvidenceGrade::Refuted,
|
||||||
|
"actual_counterexample")["grade"],"refuted");
|
||||||
|
assert_eq!(assumed()["grade"],"assumed");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
//! Independent assume/guarantee composition of source-backed pure arithmetic
|
||||||
|
//! expressions. All results are **Lean Int-model** theorems, NOT dynamic
|
||||||
|
//! Marqdo Number/i64 runtime equivalence. Every unsupported case fails closed.
|
||||||
|
use std::{collections::BTreeSet,fs,path::Path,time::Duration};
|
||||||
|
use anyhow::{Context,Result};
|
||||||
|
use serde_json::{json,Value};
|
||||||
|
use sha2::{Digest,Sha256};
|
||||||
|
use crate::{
|
||||||
|
ast::{BinaryOp,Expr,Function,Stmt,UnaryOp},
|
||||||
|
prove::{driver::{Toolchain,compile_import_module},
|
||||||
|
proof_check::{self,ClaimAst,CTok}},
|
||||||
|
sema::ir::{BoundCall,Compilation,SemanticArtifact,CanonicalParam}
|
||||||
|
};
|
||||||
|
use super::projection::{load_function,forwarder,closures};
|
||||||
|
|
||||||
|
const KIND:&str="marqdo_pure_expression_composition";
|
||||||
|
const SCOPE:&str="number_contract_int_model_pure_expression_forwarder";
|
||||||
|
fn sha(s:&[u8])->String{format!("sha256:{:x}",Sha256::digest(s))}
|
||||||
|
|
||||||
|
#[derive(Clone,Debug,PartialEq,Eq)]
|
||||||
|
enum Term{
|
||||||
|
Number(i64), Param(usize), Neg(Box<Term>),
|
||||||
|
Add(Box<Term>,Box<Term>),Sub(Box<Term>,Box<Term>),
|
||||||
|
Mul(Box<Term>,Box<Term>)
|
||||||
|
}
|
||||||
|
impl Term{
|
||||||
|
fn source(e:&Expr,params:&[CanonicalParam],depth:usize)->Option<Self>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
match e{
|
||||||
|
Expr::Literal(crate::ast::Literal::Int(n))=>Some(Self::Number(*n)),
|
||||||
|
Expr::Var(s)=>Some(Self::Param(unique_param(params,s)?)),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>Self::source(inner,params,depth+1),
|
||||||
|
Expr::Unary{op:UnaryOp::Neg,expr}=>
|
||||||
|
Some(Self::Neg(Box::new(Self::source(expr,params,depth+1)?))),
|
||||||
|
Expr::Binary{op,left,right}=>{
|
||||||
|
let l=Box::new(Self::source(left,params,depth+1)?);
|
||||||
|
let r=Box::new(Self::source(right,params,depth+1)?);
|
||||||
|
match op{
|
||||||
|
BinaryOp::Add=>Some(Self::Add(l,r)),
|
||||||
|
BinaryOp::Sub=>Some(Self::Sub(l,r)),
|
||||||
|
BinaryOp::Mul=>Some(Self::Mul(l,r)),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn claim(e:&ClaimAst,params:&[CanonicalParam],depth:usize)->Option<Self>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
match e{
|
||||||
|
ClaimAst::Lit(CTok::Int(n))=>Some(Self::Number(*n)),
|
||||||
|
ClaimAst::Var(s)=>Some(Self::Param(unique_param(params,s)?)),
|
||||||
|
ClaimAst::Un{op:"-",expr}=>Some(Self::Neg(Box::new(
|
||||||
|
Self::claim(expr,params,depth+1)?))),
|
||||||
|
ClaimAst::Bin{op,left,right}=>{
|
||||||
|
let l=Box::new(Self::claim(left,params,depth+1)?);
|
||||||
|
let r=Box::new(Self::claim(right,params,depth+1)?);
|
||||||
|
match *op{
|
||||||
|
"+"=>Some(Self::Add(l,r)),
|
||||||
|
"-"=>Some(Self::Sub(l,r)),
|
||||||
|
"*"=>Some(Self::Mul(l,r)),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn substitute(&self,args:&[Term],depth:usize)->Option<Self>{
|
||||||
|
if depth>=64{return None}
|
||||||
|
match self{
|
||||||
|
Self::Number(n)=>Some(Self::Number(*n)),
|
||||||
|
Self::Param(i)=>args.get(*i).cloned(),
|
||||||
|
Self::Neg(a)=>Some(Self::Neg(Box::new(a.substitute(args,depth+1)?))),
|
||||||
|
Self::Add(a,b)=>Some(Self::Add(Box::new(a.substitute(args,depth+1)?),
|
||||||
|
Box::new(b.substitute(args,depth+1)?))),
|
||||||
|
Self::Sub(a,b)=>Some(Self::Sub(Box::new(a.substitute(args,depth+1)?),
|
||||||
|
Box::new(b.substitute(args,depth+1)?))),
|
||||||
|
Self::Mul(a,b)=>Some(Self::Mul(Box::new(a.substitute(args,depth+1)?),
|
||||||
|
Box::new(b.substitute(args,depth+1)?)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn lean(&self)->String{
|
||||||
|
match self{
|
||||||
|
Self::Number(n)=>format!("({n} : Int)"),
|
||||||
|
Self::Param(i)=>format!("v{i}"),
|
||||||
|
Self::Neg(a)=>format!("(-{})",a.lean()),
|
||||||
|
Self::Add(a,b)=>format!("({} + {})",a.lean(),b.lean()),
|
||||||
|
Self::Sub(a,b)=>format!("({} - {})",a.lean(),b.lean()),
|
||||||
|
Self::Mul(a,b)=>format!("({} * {})",a.lean(),b.lean())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn is_composite(&self)->bool{
|
||||||
|
matches!(self,Self::Neg(..)|Self::Add(..)|Self::Sub(..)|Self::Mul(..))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn unique_param(params:&[CanonicalParam],name:&str)->Option<usize>{
|
||||||
|
let i=params.iter().position(|p|p.name==name)?;
|
||||||
|
(params.iter().filter(|p|p.name==name).count()==1).then_some(i)
|
||||||
|
}
|
||||||
|
fn claim_matches(compiled:&Compilation,artifact:&SemanticArtifact,
|
||||||
|
params:&[CanonicalParam],want:&Term)->bool{
|
||||||
|
let Some(owner)=artifact.symbol_id.as_ref() else{return false};
|
||||||
|
// The declaration must unambiguously refer to the exact source equation.
|
||||||
|
// Do not convert any arbitrary author-written proposition into an axiom.
|
||||||
|
compiled.semantics.claims.iter().filter(|c|{
|
||||||
|
if c.owner!=*owner||
|
||||||
|
!c.premise.as_deref().map_or(true,|s|s.trim().is_empty()){
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let Ok(tokens)=proof_check::tokenize_claim(&c.conclusion) else{return false};
|
||||||
|
let Ok((_,tree))=proof_check::parse_claim_expr(&tokens) else{return false};
|
||||||
|
match tree{
|
||||||
|
ClaimAst::Bin{op:"=",left,right}
|
||||||
|
if matches!(*left,ClaimAst::Var(ref v) if v=="结果")=>
|
||||||
|
Term::claim(&right,params,0).as_ref()==Some(want),
|
||||||
|
_=>false
|
||||||
|
}
|
||||||
|
}).count()==1
|
||||||
|
}
|
||||||
|
fn callee_expression(fun:&Function,params:&[CanonicalParam])->Option<Term>{
|
||||||
|
match fun.body.as_slice(){
|
||||||
|
[Stmt::Return{value,..}]=>Term::source(value,params,0),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Prepared{
|
||||||
|
identity:String,
|
||||||
|
callee:String,
|
||||||
|
caller:String
|
||||||
|
}
|
||||||
|
fn candidate(c:&Compilation,call:&BoundCall)->Option<Prepared>{
|
||||||
|
let sem=&c.semantics;
|
||||||
|
let ca=single_artifact(c,&call.caller)?;
|
||||||
|
let ce=single_artifact(c,&call.target)?;
|
||||||
|
if ca.source.file==ce.source.file||call.caller==call.target
|
||||||
|
||!ca.effects.is_pure()||!ce.effects.is_pure()
|
||||||
|
||!call.required_effects.is_pure()
|
||||||
|
||call.control_blocker.is_some()||!call.path_guards.is_empty(){return None}
|
||||||
|
if sem.bound_calls.iter().filter(|x|x.caller==call.caller).count()!=1{
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let cs=ca.signature.as_ref()?;
|
||||||
|
let es=ce.signature.as_ref()?;
|
||||||
|
let caller=load_function(c,ca)?;
|
||||||
|
let callee=load_function(c,ce)?;
|
||||||
|
if caller.is_object()||callee.is_object(){return None}
|
||||||
|
if caller.params.len()!=cs.params.len()
|
||||||
|
||callee.params.len()!=es.params.len()
|
||||||
|
||call.args.len()!=es.params.len(){return None}
|
||||||
|
if !caller.params.iter().zip(cs.params.iter()).all(|(a,b)|a.name==b.name)
|
||||||
|
||!callee.params.iter().zip(es.params.iter()).all(|(a,b)|a.name==b.name){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
if cs.params.iter().chain(es.params.iter())
|
||||||
|
.any(|p|p.ty!="number"||!p.required||p.default_digest.is_some()){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let body=callee_expression(&callee,&es.params)?;
|
||||||
|
if !body.is_composite(){return None}
|
||||||
|
if !claim_matches(c,ce,&es.params,&body){return None}
|
||||||
|
let forwarded=forwarder(&caller)?.for_evaluation().ok()?;
|
||||||
|
if forwarded.path.is_none()||forwarded.receiver.is_some()
|
||||||
|
||crate::sema::bind::call_display(&forwarded)!=call.call_site
|
||||||
|
||forwarded.args.len()!=call.args.len(){return None}
|
||||||
|
let args=call.args.iter().zip(es.params.iter()).map(|(a,p)|{
|
||||||
|
if a.name.as_ref().is_some_and(|name|name!=&p.name){return None}
|
||||||
|
if let Some(n)=a.integer{return Some(Term::Number(n))}
|
||||||
|
let symbol=a.symbol.as_ref()?;
|
||||||
|
Some(Term::Param(unique_param(&cs.params,symbol)?))
|
||||||
|
}).collect::<Option<Vec<_>>>()?;
|
||||||
|
let expected=body.substitute(&args,0)?;
|
||||||
|
if !claim_matches(c,ca,&cs.params,&expected){return None}
|
||||||
|
let callee_binders=binders(es.params.len());
|
||||||
|
let caller_binders=binders(cs.params.len());
|
||||||
|
let callee_vars=vars(es.params.len());
|
||||||
|
let caller_vars=vars(cs.params.len());
|
||||||
|
let call_args=args.iter().map(Term::lean).collect::<Vec<_>>().join(" ");
|
||||||
|
let callee_src=format!(
|
||||||
|
"-- Source-derived callee expression; Lean Int abstraction only.\n\
|
||||||
|
def callee {callee_binders} : Int := {}\n\
|
||||||
|
theorem callee_contract {callee_binders} : callee {callee_vars} = {} := by rfl\n",
|
||||||
|
body.lean(),body.lean());
|
||||||
|
let caller_src=format!(
|
||||||
|
"import CalleeModule\n\
|
||||||
|
-- The caller imports the callee's theorem, never its implementation body.\n\
|
||||||
|
def caller {caller_binders} : Int := callee {call_args}\n\
|
||||||
|
theorem caller_contract {caller_binders} : caller {caller_vars} = {} := by\n\
|
||||||
|
\x20\x20simpa [caller] using (callee_contract {call_args})\n",
|
||||||
|
expected.lean());
|
||||||
|
Some(Prepared{
|
||||||
|
identity:format!("{}#{}",ca.artifact_id.0,ce.artifact_id.0),
|
||||||
|
callee:callee_src,caller:caller_src
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn single_artifact<'a>(c:&'a Compilation,
|
||||||
|
symbol:&crate::sema::SymbolId)->Option<&'a SemanticArtifact>{
|
||||||
|
let mut found=c.semantics.artifacts.iter().filter(|a|
|
||||||
|
a.kind=="function"&&a.symbol_id.as_ref()==Some(symbol));
|
||||||
|
let item=found.next()?;
|
||||||
|
found.next().is_none().then_some(item)
|
||||||
|
}
|
||||||
|
fn binders(n:usize)->String{
|
||||||
|
(0..n).map(|i|format!("(v{i} : Int)")).collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
fn vars(n:usize)->String{
|
||||||
|
(0..n).map(|i|format!("v{i}")).collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
pub(super) fn eligible(c:&Compilation,call:&BoundCall)->bool{
|
||||||
|
candidate(c,call).is_some()
|
||||||
|
}
|
||||||
|
pub(super) fn prove(c:&Compilation,out:&Path,lean:&Toolchain)->Result<Vec<Value>>{
|
||||||
|
let mut results=Vec::new();
|
||||||
|
for call in &c.semantics.bound_calls{
|
||||||
|
if super::unified::covers(c,&call.caller){continue}
|
||||||
|
let Some(plan)=candidate(c,call) else{continue};
|
||||||
|
let closure=closures(c,call)?;
|
||||||
|
let key=sha(format!("{}|{:?}|{}",plan.identity,closure,lean.version).as_bytes());
|
||||||
|
let dir=out.join("composed").join(format!("expr-{}",&key[7..23]));
|
||||||
|
fs::create_dir_all(&dir)?;
|
||||||
|
let callee_src=dir.join("CalleeModule.lean");
|
||||||
|
let caller_src=dir.join("CallerModule.lean");
|
||||||
|
let callee_obj=dir.join("CalleeModule.olean");
|
||||||
|
let caller_obj=dir.join("CallerModule.olean");
|
||||||
|
fs::write(&callee_src,&plan.callee)?;
|
||||||
|
fs::write(&caller_src,&plan.caller)?;
|
||||||
|
let checked=(||->Result<()>{
|
||||||
|
compile_import_module(lean,&callee_src,&callee_obj,&dir,
|
||||||
|
Duration::from_secs(120)).context("expression callee proof")?;
|
||||||
|
compile_import_module(lean,&caller_src,&caller_obj,&dir,
|
||||||
|
Duration::from_secs(120)).context("expression caller composition")?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if let Err(e)=checked{
|
||||||
|
let _=fs::remove_file(dir.join("composition-certificate.json"));
|
||||||
|
results.push(json!({"identity":plan.identity,"status":"lean_rejected",
|
||||||
|
"scope":SCOPE,"error":format!("{e:#}")}));
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let cert=json!({
|
||||||
|
"schema_version":1,"kind":KIND,"scope":SCOPE,
|
||||||
|
"status":"lean_kernel_proved_model",
|
||||||
|
"caller":call.caller.as_str(),"callee":call.target.as_str(),
|
||||||
|
"identity":plan.identity,"toolchain":lean.version,
|
||||||
|
"source_closures":closure.iter().map(|(id,digest)|
|
||||||
|
json!({"id":id,"closure":digest})).collect::<Vec<_>>(),
|
||||||
|
"callee_source_sha256":sha(plan.callee.as_bytes()),
|
||||||
|
"caller_source_sha256":sha(plan.caller.as_bytes()),
|
||||||
|
"callee_compiled_sha256":sha(&fs::read(&callee_obj)?),
|
||||||
|
"caller_compiled_sha256":sha(&fs::read(&caller_obj)?),
|
||||||
|
"full_marqdo_runtime_semantics_proved":false,
|
||||||
|
"independent_replay":"CalleeModule.lean then CallerModule.lean"
|
||||||
|
});
|
||||||
|
let receipt=dir.join("composition-certificate.json");
|
||||||
|
fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?;
|
||||||
|
results.push(json!({"identity":plan.identity,"status":"lean_kernel_proved_model",
|
||||||
|
"scope":SCOPE,"artifact":receipt}));
|
||||||
|
}
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
pub(super) fn replay(c:&Compilation,certificate:&Path,lean:&Toolchain)
|
||||||
|
->Result<Value>{
|
||||||
|
let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?;
|
||||||
|
anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND
|
||||||
|
&&cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model",
|
||||||
|
"proof.expression_invalid_certificate");
|
||||||
|
anyhow::ensure!(cert["toolchain"]==lean.version,"proof.expression_toolchain_mismatch");
|
||||||
|
let identity=cert["identity"].as_str().context("proof.expression_missing_identity")?;
|
||||||
|
let candidates=c.semantics.bound_calls.iter().filter_map(|call|
|
||||||
|
candidate(c,call).and_then(|plan|(plan.identity==identity).then_some((call,plan))))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
anyhow::ensure!(candidates.len()==1,"proof.expression_ambiguous_or_stale_source");
|
||||||
|
let (call,plan)=&candidates[0];
|
||||||
|
anyhow::ensure!(cert["caller"]==call.caller.as_str()
|
||||||
|
&&cert["callee"]==call.target.as_str(),"proof.expression_changed_symbols");
|
||||||
|
let expected=closures(c,call)?;
|
||||||
|
let rows=cert["source_closures"].as_array().context("proof.expression_missing_closures")?;
|
||||||
|
let actual=rows.iter().map(|r|Ok((
|
||||||
|
r["id"].as_str().context("proof.expression_bad_id")?.to_owned(),
|
||||||
|
r["closure"].as_str().context("proof.expression_bad_digest")?.to_owned()
|
||||||
|
))).collect::<Result<BTreeSet<_>>>()?;
|
||||||
|
anyhow::ensure!(rows.len()==expected.len()&&actual==expected,
|
||||||
|
"proof.expression_stale_or_ambiguous_closure");
|
||||||
|
let dir=certificate.parent().context("proof.expression_missing_parent")?;
|
||||||
|
let callee_src=dir.join("CalleeModule.lean");
|
||||||
|
let caller_src=dir.join("CallerModule.lean");
|
||||||
|
anyhow::ensure!(fs::read_to_string(&callee_src)?==plan.callee
|
||||||
|
&&fs::read_to_string(&caller_src)?==plan.caller
|
||||||
|
&&cert["callee_source_sha256"]==sha(plan.callee.as_bytes())
|
||||||
|
&&cert["caller_source_sha256"]==sha(plan.caller.as_bytes()),
|
||||||
|
"proof.expression_source_mismatch");
|
||||||
|
let callee_obj=dir.join("CalleeModule.olean");
|
||||||
|
let caller_obj=dir.join("CallerModule.olean");
|
||||||
|
compile_import_module(lean,&callee_src,&callee_obj,dir,Duration::from_secs(120))?;
|
||||||
|
compile_import_module(lean,&caller_src,&caller_obj,dir,Duration::from_secs(120))?;
|
||||||
|
anyhow::ensure!(cert["callee_compiled_sha256"]==sha(&fs::read(callee_obj)?)
|
||||||
|
&&cert["caller_compiled_sha256"]==sha(&fs::read(caller_obj)?),
|
||||||
|
"proof.expression_compiled_mismatch");
|
||||||
|
Ok(json!({"schema_version":1,"kind":"independent_composition_replay",
|
||||||
|
"status":"lean_kernel_replayed","scope":SCOPE,
|
||||||
|
"identity":identity,"current_source_verified":true,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false}))
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests{
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn arithmetic_contract_requires_exact_structural_match(){
|
||||||
|
let params=vec![CanonicalParam{name:"n".into(),ty:"number".into(),
|
||||||
|
required:true,default_digest:None,unit:None}];
|
||||||
|
let lhs=crate::parse::parse_expr("`n` + 1").unwrap();
|
||||||
|
let want=Term::source(&lhs,¶ms,0).unwrap();
|
||||||
|
let good=proof_check::parse_claim_expr(
|
||||||
|
&proof_check::tokenize_claim("n + 1").unwrap()).unwrap().1;
|
||||||
|
assert_eq!(Term::claim(&good,¶ms,0),Some(want.clone()));
|
||||||
|
let bad=proof_check::parse_claim_expr(
|
||||||
|
&proof_check::tokenize_claim("n + 2").unwrap()).unwrap().1;
|
||||||
|
assert_ne!(Term::claim(&bad,¶ms,0),Some(want));
|
||||||
|
assert!(Term::source(&crate::parse::parse_expr("`n` / 2").unwrap(),¶ms,0).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,7 @@ pub fn extract_graph(opts: &ExtractOptions) -> Result<KnowledgeGraph> {
|
|||||||
let root = if opts.path.is_file() {
|
let root = if opts.path.is_file() {
|
||||||
opts.path
|
opts.path
|
||||||
.parent()
|
.parent()
|
||||||
|
.filter(|p| !p.as_os_str().is_empty())
|
||||||
.map(|p| p.to_path_buf())
|
.map(|p| p.to_path_buf())
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -16,6 +16,15 @@ pub mod learn;
|
|||||||
pub mod lifecycle;
|
pub mod lifecycle;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
pub mod policy;
|
pub mod policy;
|
||||||
|
pub mod proof;
|
||||||
|
pub mod modular;
|
||||||
|
pub mod vc;
|
||||||
|
pub mod symbolic;
|
||||||
|
pub mod composition;
|
||||||
|
pub mod projection;
|
||||||
|
pub mod expression;
|
||||||
|
pub mod unified;
|
||||||
|
pub mod evidence;
|
||||||
pub mod preflight;
|
pub mod preflight;
|
||||||
pub mod reuse;
|
pub mod reuse;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|||||||
@@ -0,0 +1,237 @@
|
|||||||
|
//! Conservative inter-module proof dependency planning.
|
||||||
|
//!
|
||||||
|
//! This is NOT a rule that a proved callee theorem magically proves its
|
||||||
|
//! caller. It records which Lean-checked callee contracts a caller could rely
|
||||||
|
//! on and refuses to discharge parameter-dependent preconditions by guesswork.
|
||||||
|
//! The independently proved caller claim remains a separate obligation.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use crate::sema::ir::SemanticProject;
|
||||||
|
|
||||||
|
fn linked_claims<'a>(proofs:&'a Value, symbol:&str)->Vec<&'a Value>{
|
||||||
|
proofs["claims"].as_array().into_iter()
|
||||||
|
.flat_map(|rows|rows.iter())
|
||||||
|
.filter(|r|r["owner_symbol_id"].as_str()==Some(symbol))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn analyze(semantic:&SemanticProject, proof_index:&Value)->Value{
|
||||||
|
analyze_with_verified(semantic,proof_index,&BTreeSet::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The accepted set must come from the real Lean kernel, never from the host
|
||||||
|
/// calculator or an untrusted JSON status.
|
||||||
|
pub fn analyze_with_verified(semantic:&SemanticProject, proof_index:&Value,
|
||||||
|
kernel_verified:&BTreeSet<String>)->Value{
|
||||||
|
let known:BTreeSet<&str>=semantic.artifacts.iter()
|
||||||
|
.filter_map(|a|a.symbol_id.as_ref().map(|id|id.as_str())).collect();
|
||||||
|
let mut obligations=Vec::new();
|
||||||
|
let mut links:BTreeMap<String,Vec<String>>=BTreeMap::new();
|
||||||
|
for call in &semantic.bound_calls {
|
||||||
|
let callee=call.target.as_str();
|
||||||
|
let caller_id=call.caller.as_str();
|
||||||
|
let caller=Some(caller_id);
|
||||||
|
let assumption=semantic.assumptions.iter()
|
||||||
|
.find(|a|a.owner.as_str()==caller_id &&
|
||||||
|
(a.operation==call.call_site || a.operation==callee));
|
||||||
|
let id=format!("{}:{}:{}",call.source.file,call.source.line,callee);
|
||||||
|
let exported=semantic.claims.iter().any(|c|c.owner.as_str()==callee);
|
||||||
|
let receipts=linked_claims(proof_index,callee);
|
||||||
|
let contracts:Vec<Value>=semantic.claims.iter()
|
||||||
|
.filter(|c|c.owner.as_str()==callee)
|
||||||
|
.map(|c|{
|
||||||
|
let matched=receipts.iter().find(|r|
|
||||||
|
r["claim_anchor_id"]==c.anchor_id
|
||||||
|
&& r["conclusion"]==c.conclusion
|
||||||
|
&& r["premise"]==json!(c.premise));
|
||||||
|
let verified=matched.is_some_and(|r|r["status"]=="proved"
|
||||||
|
&& r["usable"]==true);
|
||||||
|
let unconditional=c.premise.as_deref()
|
||||||
|
.map_or(true,|s|s.trim().is_empty());
|
||||||
|
let goal=if unconditional {None} else {
|
||||||
|
c.premise.as_deref().and_then(|pre|
|
||||||
|
super::vc::instantiate(semantic,call,pre))
|
||||||
|
};
|
||||||
|
let symbolic=if unconditional {None} else {
|
||||||
|
c.premise.as_deref().and_then(|pre|
|
||||||
|
super::symbolic::plan(semantic,call,pre))
|
||||||
|
};
|
||||||
|
let key=format!("{}#{}",id,c.anchor_id);
|
||||||
|
let kernel_passed=goal.as_ref().is_some_and(|g|
|
||||||
|
g.holds && kernel_verified.contains(&key));
|
||||||
|
json!({
|
||||||
|
"claim_anchor_id":c.anchor_id,
|
||||||
|
"premise":c.premise,
|
||||||
|
"conclusion":c.conclusion,
|
||||||
|
"callee_certificate_valid":verified,
|
||||||
|
"callee_evidence":super::evidence::for_receipt(
|
||||||
|
if verified {"proved"}else{"unverified"},verified,false),
|
||||||
|
// An unbound premise is a caller-side proof obligation;
|
||||||
|
// it is never discharged merely because callee was proved.
|
||||||
|
"precondition_goal_key":if unconditional {None} else {Some(key)},
|
||||||
|
"lean_proposition":goal.as_ref().map(|g|g.proposition.as_str()),
|
||||||
|
"closed_host_check":goal.as_ref().map(|g|g.holds),
|
||||||
|
"symbolic_model_proposition":symbolic.as_ref().map(|g|g.proposition.as_str()),
|
||||||
|
"symbolic_model_guard_count":symbolic.as_ref().map(|g|g.guard_propositions.len()),
|
||||||
|
"symbolic_model_runtime_domain_verified":symbolic.as_ref().map(|g|g.runtime_domain_verified),
|
||||||
|
"symbolic_int_abstract_supported":symbolic.as_ref().map(|g|g.abstract_integer_model_supported),
|
||||||
|
"path_guards":call.path_guards,
|
||||||
|
"control_blocker":call.control_blocker,
|
||||||
|
"call_precondition_status":if unconditional {"none"}
|
||||||
|
else if kernel_passed {"lean_kernel_verified"}
|
||||||
|
else if goal.as_ref().is_some_and(|g|!g.holds) {"refuted_closed_precondition"}
|
||||||
|
else if goal.is_some() {"requires_lean_kernel"}
|
||||||
|
else if symbolic.is_some() {"symbolic_path_lean_model_pending"}
|
||||||
|
else {"requires_symbolic_callsite_proof"},
|
||||||
|
"status":if !verified {"missing_verified_callee_claim"}
|
||||||
|
else if unconditional || kernel_passed {"available_as_contract"}
|
||||||
|
else if goal.as_ref().is_some_and(|g|!g.holds) {"precondition_refuted"}
|
||||||
|
else {"precondition_pending"}
|
||||||
|
})
|
||||||
|
}).collect();
|
||||||
|
let controls_sufficient=call.control_blocker.is_none()
|
||||||
|
&& call.required_effects.is_pure();
|
||||||
|
let all_available=controls_sufficient && exported && !contracts.is_empty()
|
||||||
|
&& contracts.iter().all(|x|x["status"]=="available_as_contract");
|
||||||
|
let status=if !known.contains(callee) {
|
||||||
|
"external_without_semantic_definition"
|
||||||
|
} else if !controls_sufficient {
|
||||||
|
"unmodeled_control_or_effect"
|
||||||
|
} else if !exported {
|
||||||
|
"callee_without_declared_contract"
|
||||||
|
} else if all_available {
|
||||||
|
"callee_contracts_verified"
|
||||||
|
} else {
|
||||||
|
"proof_obligations_pending"
|
||||||
|
};
|
||||||
|
obligations.push(json!({
|
||||||
|
"id":id,"caller":caller,"callee":callee,
|
||||||
|
"call_site":call.call_site,
|
||||||
|
"source":{"file":call.source.file,"line":call.source.line},
|
||||||
|
"status":status,"contracts":contracts,
|
||||||
|
"caller_proof_required":true,
|
||||||
|
"evidence":super::evidence::unknown("dependency_audit_is_not_caller_proof"),
|
||||||
|
"runtime_link_required":true,
|
||||||
|
"path_guards":call.path_guards,
|
||||||
|
"control_blocker":call.control_blocker,
|
||||||
|
"effects":call.required_effects.values(),
|
||||||
|
"runtime_effect_model":"not_established_by_knowledge_audit",
|
||||||
|
"caller_assumption":assumption.map(|a|json!({
|
||||||
|
"id":a.id,"premise":a.premise,
|
||||||
|
"postcondition":a.postcondition,
|
||||||
|
"verified":false,
|
||||||
|
"evidence":super::evidence::assumed(),
|
||||||
|
"status":"requires_lean_callsite_derivation"
|
||||||
|
})),
|
||||||
|
"caller_assumption_binding":if assumption.is_some(){"declared_unproved"}
|
||||||
|
else {"absent"}
|
||||||
|
}));
|
||||||
|
if let Some(caller)=caller {
|
||||||
|
links.entry(caller.to_string()).or_default().push(callee.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for call in &semantic.dynamic_calls {
|
||||||
|
obligations.push(json!({
|
||||||
|
"id":format!("{}:{}:dynamic",call.source.file,call.source.line),
|
||||||
|
"source":{"file":call.source.file,"line":call.source.line},
|
||||||
|
"status":"dynamic_or_unresolved_no_modular_proof",
|
||||||
|
"reason":call.reason,"caller_proof_required":true
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
obligations.sort_by(|a,b|a["id"].as_str().cmp(&b["id"].as_str()));
|
||||||
|
let cycles=find_cycles(&links);
|
||||||
|
let verified_claims:Vec<Value>=semantic.claims.iter().map(|c|{
|
||||||
|
let found=linked_claims(proof_index,c.owner.as_str()).iter().any(|r|
|
||||||
|
r["claim_anchor_id"]==c.anchor_id &&
|
||||||
|
r["conclusion"]==c.conclusion &&
|
||||||
|
r["premise"]==json!(c.premise) &&
|
||||||
|
r["status"]=="proved" && r["usable"]==true);
|
||||||
|
json!({"claim_anchor_id":c.anchor_id,"owner":c.owner.as_str(),
|
||||||
|
"status":if found {"proved_with_local_lean_receipt"} else {"unverified"}})
|
||||||
|
}).collect();
|
||||||
|
let linked=obligations.iter().all(|o|o["status"]=="callee_contracts_verified")
|
||||||
|
&& cycles.is_empty();
|
||||||
|
let declarations_proved=!verified_claims.is_empty()
|
||||||
|
&& verified_claims.iter().all(|c|c["status"]=="proved_with_local_lean_receipt");
|
||||||
|
let audit_passes=linked && declarations_proved;
|
||||||
|
json!({
|
||||||
|
"schema_version":1,
|
||||||
|
"kind":"modular_proof_obligations",
|
||||||
|
"status":if audit_passes {"dependency_receipts_valid"}
|
||||||
|
else {"open_obligations"},
|
||||||
|
"audit_passes":audit_passes,
|
||||||
|
"verified_claims":verified_claims,
|
||||||
|
// Even a successful audit is NOT a modular Lean theorem:
|
||||||
|
// the runtime-link and caller entailment obligations remain.
|
||||||
|
"proof_completion":"not_established_by_dependency_analysis",
|
||||||
|
"obligations":obligations,
|
||||||
|
"cycles":cycles
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_cycles(graph:&BTreeMap<String,Vec<String>>)->Vec<Vec<String>>{
|
||||||
|
fn visit<'a>(node:&'a str,g:&'a BTreeMap<String,Vec<String>>,
|
||||||
|
visiting:&mut BTreeSet<String>,done:&mut BTreeSet<String>,
|
||||||
|
stack:&mut Vec<String>,cycles:&mut Vec<Vec<String>>){
|
||||||
|
if done.contains(node){return}
|
||||||
|
if !visiting.insert(node.to_string()){
|
||||||
|
if let Some(start)=stack.iter().position(|x|x==node){
|
||||||
|
let mut cycle=stack[start..].to_vec();
|
||||||
|
cycle.push(node.to_string());
|
||||||
|
cycles.push(cycle);
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stack.push(node.to_string());
|
||||||
|
if let Some(next)=g.get(node){
|
||||||
|
for target in next {visit(target,g,visiting,done,stack,cycles)}
|
||||||
|
}
|
||||||
|
stack.pop();visiting.remove(node);done.insert(node.to_string());
|
||||||
|
}
|
||||||
|
let mut visiting=BTreeSet::new();
|
||||||
|
let mut done=BTreeSet::new();
|
||||||
|
let mut cycles=Vec::new();
|
||||||
|
for key in graph.keys(){visit(key,graph,&mut visiting,&mut done,&mut Vec::new(),&mut cycles)}
|
||||||
|
cycles
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn contracts_never_discharge_callsite_preconditions_implicitly(){
|
||||||
|
let source=std::env::temp_dir().join(format!("marqdo-modular-{}",std::process::id()));
|
||||||
|
let _=std::fs::remove_dir_all(&source);
|
||||||
|
std::fs::create_dir_all(&source).unwrap();
|
||||||
|
std::fs::write(source.join("callee.mq.md"),
|
||||||
|
"# callee\n\n## f\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | x > 0 | auto |\n\n*2*\n").unwrap();
|
||||||
|
std::fs::write(source.join("main.mq.md"),
|
||||||
|
"---\nimport:\n callee: callee.mq.md\n---\n# main\n\n## call\n\n**x = [外部调用](callee.callee.f())**\n*x*\n").unwrap();
|
||||||
|
let compilation=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&source).unwrap()).unwrap();
|
||||||
|
let report=analyze(&compilation.semantics,&json!({"claims":[]}));
|
||||||
|
let obligations=report["obligations"].as_array().unwrap();
|
||||||
|
assert!(!obligations.is_empty());
|
||||||
|
assert!(obligations.iter().all(|x|x["status"]!="proved"));
|
||||||
|
assert_eq!(report["proof_completion"],"not_established_by_dependency_analysis");
|
||||||
|
// Even a caller-supplied "valid" callee receipt cannot discharge the
|
||||||
|
// actual-argument bridge for a conditional requires clause.
|
||||||
|
let callee=compilation.semantics.claims.iter().find(|c|c.label=="c").unwrap();
|
||||||
|
let forged=json!({"claims":[{
|
||||||
|
"owner_symbol_id":callee.owner.as_str(),
|
||||||
|
"claim_anchor_id":callee.anchor_id,
|
||||||
|
"conclusion":callee.conclusion,
|
||||||
|
"premise":callee.premise,
|
||||||
|
"status":"proved","usable":true
|
||||||
|
}]});
|
||||||
|
let conditional=analyze(&compilation.semantics,&forged);
|
||||||
|
let first=conditional["obligations"].as_array().unwrap()
|
||||||
|
.iter().find(|x|x["callee"]==callee.owner.as_str()).unwrap();
|
||||||
|
assert_eq!(first["contracts"][0]["status"],"precondition_pending");
|
||||||
|
assert_eq!(first["contracts"][0]["call_precondition_status"],
|
||||||
|
"requires_symbolic_callsite_proof");
|
||||||
|
assert_eq!(conditional["audit_passes"],false);
|
||||||
|
std::fs::remove_dir_all(source).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
//! Cross-module projection contracts for the *abstract* Lean Int model.
|
||||||
|
//!
|
||||||
|
//! This is a source-regenerated, kernel-replayed proof: the callee returns
|
||||||
|
//! exactly one of its own arguments and the caller forwards one static import.
|
||||||
|
//! No arithmetic, dynamic dispatch, effects, exceptions or runtime Number
|
||||||
|
//! equivalence is inferred. Unmodeled programs never get a certificate.
|
||||||
|
use std::{collections::BTreeSet,fs,path::Path,time::Duration};
|
||||||
|
use anyhow::{Context,Result};
|
||||||
|
use serde_json::{json,Value};
|
||||||
|
use sha2::{Digest,Sha256};
|
||||||
|
use crate::{
|
||||||
|
ast::{CallExpr,Expr,Function,Stmt},
|
||||||
|
prove::driver::{Toolchain,compile_import_module},
|
||||||
|
sema::ir::{BoundCall,Compilation,SemanticArtifact}
|
||||||
|
};
|
||||||
|
|
||||||
|
const SCOPE:&str="number_contract_int_model_pure_forwarder_parameter_projection";
|
||||||
|
const KIND:&str="marqdo_parameter_projection_composition";
|
||||||
|
fn sha(bytes:&[u8])->String{format!("sha256:{:x}",Sha256::digest(bytes))}
|
||||||
|
|
||||||
|
struct Prepared {
|
||||||
|
callee_source:String,
|
||||||
|
caller_source:String,
|
||||||
|
identity:String,
|
||||||
|
result_label:String,
|
||||||
|
parameter_index:usize,
|
||||||
|
}
|
||||||
|
fn lookup<'a>(functions:&'a [Function],segments:&[&str])->Option<&'a Function>{
|
||||||
|
let (head,tail)=segments.split_first()?;
|
||||||
|
let mut candidates=functions.iter().filter(|f|f.name==*head);
|
||||||
|
let found=candidates.next()?;
|
||||||
|
if candidates.next().is_some(){return None}
|
||||||
|
if tail.is_empty(){Some(found)}else{lookup(&found.children,tail)}
|
||||||
|
}
|
||||||
|
pub(super) fn load_function(compiled:&Compilation,artifact:&SemanticArtifact)->Option<Function>{
|
||||||
|
let text=fs::read_to_string(compiled.semantics.root.join(&artifact.source.file)).ok()?;
|
||||||
|
let parsed=crate::parse::parse_source(&text).ok()?;
|
||||||
|
lookup(&parsed.functions,&artifact.display_name.split('.').collect::<Vec<_>>()).cloned()
|
||||||
|
}
|
||||||
|
fn unwrap_var(expr:&Expr)->Option<&str>{
|
||||||
|
match expr{
|
||||||
|
Expr::Var(v)=>Some(v.as_str()),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>unwrap_var(inner),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn unwrap_call(expr:&Expr)->Option<&CallExpr>{
|
||||||
|
match expr{
|
||||||
|
Expr::Call(c)=>Some(c),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>unwrap_call(inner),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn projection(fun:&Function)->Option<&str>{
|
||||||
|
match fun.body.as_slice(){
|
||||||
|
[Stmt::Return{value,..}]=>unwrap_var(value),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(super) fn forwarder(fun:&Function)->Option<&CallExpr>{
|
||||||
|
match fun.body.as_slice(){
|
||||||
|
[Stmt::Return{value,..}]=>unwrap_call(value),
|
||||||
|
[Stmt::Assign{name,value,..},Stmt::Return{value:Expr::Var(result),..}]
|
||||||
|
if name==result=>unwrap_call(value),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn exact_unconditional_claim(compiled:&Compilation,artifact:&SemanticArtifact,
|
||||||
|
expected:&str)->bool{
|
||||||
|
artifact.symbol_id.as_ref().is_some_and(|owner|
|
||||||
|
compiled.semantics.claims.iter().filter(|c|
|
||||||
|
c.owner==*owner &&
|
||||||
|
c.premise.as_deref().map_or(true,|p|p.trim().is_empty()) &&
|
||||||
|
c.conclusion.trim()==expected
|
||||||
|
).count()==1)
|
||||||
|
}
|
||||||
|
fn candidate(compiled:&Compilation,call:&BoundCall)->Option<Prepared>{
|
||||||
|
let sem=&compiled.semantics;
|
||||||
|
let mut caller_artifacts=sem.artifacts.iter().filter(|a|
|
||||||
|
a.kind=="function"&&a.symbol_id.as_ref()==Some(&call.caller));
|
||||||
|
let ca=caller_artifacts.next()?;
|
||||||
|
if caller_artifacts.next().is_some(){return None}
|
||||||
|
let mut callee_artifacts=sem.artifacts.iter().filter(|a|
|
||||||
|
a.kind=="function"&&a.symbol_id.as_ref()==Some(&call.target));
|
||||||
|
let ce=callee_artifacts.next()?;
|
||||||
|
if callee_artifacts.next().is_some(){return None}
|
||||||
|
if ca.source.file==ce.source.file||call.caller==call.target||
|
||||||
|
!ca.effects.is_pure()||!ce.effects.is_pure()||
|
||||||
|
!call.required_effects.is_pure()||
|
||||||
|
call.control_blocker.is_some()||!call.path_guards.is_empty(){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let caller=load_function(compiled,ca)?;
|
||||||
|
let callee=load_function(compiled,ce)?;
|
||||||
|
if caller.is_object()||callee.is_object(){return None}
|
||||||
|
let return_parameter=projection(&callee)?;
|
||||||
|
let forwarded=forwarder(&caller)?.for_evaluation().ok()?;
|
||||||
|
if forwarded.path.is_none()||forwarded.receiver.is_some()||
|
||||||
|
crate::sema::bind::call_display(&forwarded)!=call.call_site ||
|
||||||
|
sem.bound_calls.iter().filter(|c|c.caller==call.caller).count()!=1{
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let cs=ca.signature.as_ref()?;
|
||||||
|
let es=ce.signature.as_ref()?;
|
||||||
|
if cs.params.len()!=caller.params.len()||
|
||||||
|
es.params.len()!=callee.params.len()||
|
||||||
|
es.params.len()!=call.args.len()||
|
||||||
|
forwarded.args.len()!=call.args.len(){return None}
|
||||||
|
// Canonical "number" includes non-integer variants at runtime.
|
||||||
|
// Our result is exclusively about the mathematical Int abstraction.
|
||||||
|
if cs.params.iter().chain(es.params.iter())
|
||||||
|
.any(|p|!p.ty.eq_ignore_ascii_case("number")||!p.required||
|
||||||
|
p.default_digest.is_some()){return None}
|
||||||
|
if !cs.params.iter().zip(caller.params.iter())
|
||||||
|
.all(|(a,b)|a.name==b.name) ||
|
||||||
|
!es.params.iter().zip(callee.params.iter())
|
||||||
|
.all(|(a,b)|a.name==b.name){return None}
|
||||||
|
let k=es.params.iter().position(|p|p.name==return_parameter)?;
|
||||||
|
if es.params.iter().filter(|p|p.name==return_parameter).count()!=1{
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
if !exact_unconditional_claim(compiled,ce,
|
||||||
|
&format!("结果 = {return_parameter}")){return None}
|
||||||
|
let mut args=Vec::new();
|
||||||
|
let mut caller_result=None;
|
||||||
|
for (i,(formal,arg)) in es.params.iter().zip(call.args.iter()).enumerate(){
|
||||||
|
if arg.name.as_ref().is_some_and(|name|name!=&formal.name){return None}
|
||||||
|
let (term,label)=if let Some(value)=arg.integer{
|
||||||
|
(format!("({value} : Int)"),value.to_string())
|
||||||
|
}else{
|
||||||
|
let symbol=arg.symbol.as_ref()?;
|
||||||
|
let index=cs.params.iter().position(|p|p.name==*symbol)?;
|
||||||
|
if cs.params.iter().filter(|p|p.name==*symbol).count()!=1{return None}
|
||||||
|
(format!("v{index}"),symbol.clone())
|
||||||
|
};
|
||||||
|
args.push(term);
|
||||||
|
if i==k{caller_result=Some(label)}
|
||||||
|
}
|
||||||
|
let result_label=caller_result?;
|
||||||
|
if !exact_unconditional_claim(compiled,ca,
|
||||||
|
&format!("结果 = {result_label}")){return None}
|
||||||
|
let callee_binders=(0..es.params.len())
|
||||||
|
.map(|i|format!("(v{i} : Int)")).collect::<Vec<_>>().join(" ");
|
||||||
|
let caller_binders=(0..cs.params.len())
|
||||||
|
.map(|i|format!("(v{i} : Int)")).collect::<Vec<_>>().join(" ");
|
||||||
|
let callee_vars=(0..es.params.len())
|
||||||
|
.map(|i|format!("v{i}")).collect::<Vec<_>>().join(" ");
|
||||||
|
let caller_vars=(0..cs.params.len())
|
||||||
|
.map(|i|format!("v{i}")).collect::<Vec<_>>().join(" ");
|
||||||
|
let call_terms=args.join(" ");
|
||||||
|
let projected_term=&args[k];
|
||||||
|
// No author-controlled identifiers appear in generated Lean code.
|
||||||
|
let callee_source=format!(
|
||||||
|
"def callee {callee_binders} : Int := v{k}\n\
|
||||||
|
theorem callee_contract {callee_binders} : callee {callee_vars} = v{k} := by rfl\n");
|
||||||
|
let caller_source=format!(
|
||||||
|
"import CalleeModule\n\
|
||||||
|
def caller {caller_binders} : Int := callee {call_terms}\n\
|
||||||
|
theorem caller_contract {caller_binders} : caller {caller_vars} = {projected_term} := by\n\
|
||||||
|
\x20\x20simpa [caller] using (callee_contract {call_terms})\n");
|
||||||
|
Some(Prepared{
|
||||||
|
callee_source,caller_source,
|
||||||
|
identity:format!("{}#{}",ca.artifact_id.0,ce.artifact_id.0),
|
||||||
|
result_label,parameter_index:k
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub(super) fn eligible(compiled:&Compilation,call:&BoundCall)->bool{
|
||||||
|
candidate(compiled,call).is_some()
|
||||||
|
}
|
||||||
|
pub(super) fn closures(compiled:&Compilation,call:&BoundCall)->Result<BTreeSet<(String,String)>>{
|
||||||
|
let set=compiled.semantics.artifacts.iter()
|
||||||
|
.filter(|a|a.symbol_id.as_ref()==Some(&call.caller)||
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target))
|
||||||
|
.map(|a|(a.artifact_id.0.clone(),a.hashes.closure.0.clone()))
|
||||||
|
.collect::<BTreeSet<_>>();
|
||||||
|
anyhow::ensure!(set.len()==2,"proof.projection_ambiguous_dependency");
|
||||||
|
Ok(set)
|
||||||
|
}
|
||||||
|
pub(super) fn prove(compiled:&Compilation,out:&Path,lean:&Toolchain)->Result<Vec<Value>>{
|
||||||
|
let mut rows=Vec::new();
|
||||||
|
for call in &compiled.semantics.bound_calls{
|
||||||
|
if super::unified::covers(compiled,&call.caller){continue}
|
||||||
|
let Some(plan)=candidate(compiled,call) else{continue};
|
||||||
|
let dependencies=closures(compiled,call)?;
|
||||||
|
let key=sha(format!("{}|{:?}|{}",plan.identity,dependencies,lean.version).as_bytes());
|
||||||
|
let dir=out.join("composed").join(format!("projection-{}",&key[7..23]));
|
||||||
|
fs::create_dir_all(&dir)?;
|
||||||
|
let callee=dir.join("CalleeModule.lean");
|
||||||
|
let caller=dir.join("CallerModule.lean");
|
||||||
|
let callee_obj=dir.join("CalleeModule.olean");
|
||||||
|
let caller_obj=dir.join("CallerModule.olean");
|
||||||
|
fs::write(&callee,&plan.callee_source)?;
|
||||||
|
fs::write(&caller,&plan.caller_source)?;
|
||||||
|
let checked=(||->Result<()>{
|
||||||
|
compile_import_module(lean,&callee,&callee_obj,&dir,
|
||||||
|
Duration::from_secs(120)).context("projection callee")?;
|
||||||
|
compile_import_module(lean,&caller,&caller_obj,&dir,
|
||||||
|
Duration::from_secs(120)).context("projection caller")?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if let Err(e)=checked{
|
||||||
|
let _=fs::remove_file(dir.join("composition-certificate.json"));
|
||||||
|
rows.push(json!({"identity":plan.identity,"status":"lean_rejected",
|
||||||
|
"scope":SCOPE,"error":format!("{e:#}")}));
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let cert=json!({
|
||||||
|
"schema_version":1,"kind":KIND,"scope":SCOPE,
|
||||||
|
"status":"lean_kernel_proved_model",
|
||||||
|
"identity":plan.identity,
|
||||||
|
"caller":call.caller.as_str(),"callee":call.target.as_str(),
|
||||||
|
"result_label":plan.result_label,
|
||||||
|
"parameter_index":plan.parameter_index,
|
||||||
|
"callee_source_sha256":sha(plan.callee_source.as_bytes()),
|
||||||
|
"caller_source_sha256":sha(plan.caller_source.as_bytes()),
|
||||||
|
"callee_compiled_sha256":sha(&fs::read(&callee_obj)?),
|
||||||
|
"caller_compiled_sha256":sha(&fs::read(&caller_obj)?),
|
||||||
|
"toolchain":lean.version,
|
||||||
|
"source_closures":dependencies.iter().map(|(id,closure)|
|
||||||
|
json!({"id":id,"closure":closure})).collect::<Vec<_>>(),
|
||||||
|
"runtime_domain_verified":false,
|
||||||
|
"independent_replay":"CalleeModule.lean then CallerModule.lean"
|
||||||
|
});
|
||||||
|
let receipt=dir.join("composition-certificate.json");
|
||||||
|
fs::write(&receipt,serde_json::to_vec_pretty(&cert)?)?;
|
||||||
|
rows.push(json!({"identity":plan.identity,"status":"lean_kernel_proved_model",
|
||||||
|
"artifact":receipt,"scope":SCOPE}));
|
||||||
|
}
|
||||||
|
Ok(rows)
|
||||||
|
}
|
||||||
|
pub(super) fn replay(compiled:&Compilation,certificate:&Path,lean:&Toolchain)
|
||||||
|
->Result<Value>{
|
||||||
|
let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?;
|
||||||
|
anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND&&
|
||||||
|
cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model",
|
||||||
|
"proof.projection_invalid_certificate");
|
||||||
|
anyhow::ensure!(cert["toolchain"]==lean.version,
|
||||||
|
"proof.projection_stale_toolchain");
|
||||||
|
let identity=cert["identity"].as_str().context("missing identity")?;
|
||||||
|
let matches=compiled.semantics.bound_calls.iter().filter_map(|call|
|
||||||
|
candidate(compiled,call).and_then(|p|
|
||||||
|
(p.identity==identity).then_some((call,p)))).collect::<Vec<_>>();
|
||||||
|
anyhow::ensure!(matches.len()==1,
|
||||||
|
"proof.projection_ambiguous_or_stale_source");
|
||||||
|
let (call,plan)=&matches[0];
|
||||||
|
anyhow::ensure!(cert["caller"]==call.caller.as_str()&&
|
||||||
|
cert["callee"]==call.target.as_str()&&
|
||||||
|
cert["parameter_index"]==plan.parameter_index&&
|
||||||
|
cert["result_label"]==plan.result_label,
|
||||||
|
"proof.projection_changed_proof_subject");
|
||||||
|
let expected=closures(compiled,call)?;
|
||||||
|
let rows=cert["source_closures"].as_array()
|
||||||
|
.context("proof.projection_missing_closures")?;
|
||||||
|
let actual=rows.iter().map(|r|Ok((
|
||||||
|
r["id"].as_str().context("proof.projection_bad_id")?.to_string(),
|
||||||
|
r["closure"].as_str().context("proof.projection_bad_closure")?.to_string()
|
||||||
|
))).collect::<Result<BTreeSet<_>>>()?;
|
||||||
|
anyhow::ensure!(rows.len()==expected.len()&&actual==expected,
|
||||||
|
"proof.projection_stale_or_ambiguous_closure");
|
||||||
|
let dir=certificate.parent().context("missing certificate parent")?;
|
||||||
|
let callee=dir.join("CalleeModule.lean");
|
||||||
|
let caller=dir.join("CallerModule.lean");
|
||||||
|
anyhow::ensure!(fs::read_to_string(&callee)?==plan.callee_source&&
|
||||||
|
fs::read_to_string(&caller)?==plan.caller_source&&
|
||||||
|
cert["callee_source_sha256"]==sha(plan.callee_source.as_bytes())&&
|
||||||
|
cert["caller_source_sha256"]==sha(plan.caller_source.as_bytes()),
|
||||||
|
"proof.projection_generated_source_mismatch");
|
||||||
|
let callee_obj=dir.join("CalleeModule.olean");
|
||||||
|
let caller_obj=dir.join("CallerModule.olean");
|
||||||
|
compile_import_module(lean,&callee,&callee_obj,dir,
|
||||||
|
Duration::from_secs(120))?;
|
||||||
|
compile_import_module(lean,&caller,&caller_obj,dir,
|
||||||
|
Duration::from_secs(120))?;
|
||||||
|
anyhow::ensure!(cert["callee_compiled_sha256"]==sha(&fs::read(callee_obj)?)&&
|
||||||
|
cert["caller_compiled_sha256"]==sha(&fs::read(caller_obj)?),
|
||||||
|
"proof.projection_replay_output_changed");
|
||||||
|
Ok(json!({"schema_version":1,"kind":"independent_composition_replay",
|
||||||
|
"status":"lean_kernel_replayed","scope":SCOPE,"identity":identity,
|
||||||
|
"current_source_verified":true,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false}))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests{
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn symbolic_projection_uses_only_the_selected_actual(){
|
||||||
|
let root=std::env::temp_dir().join(format!(
|
||||||
|
"marqdo-projection-unit-{}",std::process::id()));
|
||||||
|
let _=fs::remove_dir_all(&root);
|
||||||
|
fs::create_dir_all(&root).unwrap();
|
||||||
|
let callee=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
# math
|
||||||
|
## select
|
||||||
|
+ `first`
|
||||||
|
+ `second`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| first | int | integer |
|
||||||
|
| second | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| proj | 结果 = second | auto |
|
||||||
|
|
||||||
|
*`second`*
|
||||||
|
"#;
|
||||||
|
let caller=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
# main
|
||||||
|
## use
|
||||||
|
+ `x`
|
||||||
|
+ `y`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| x | int | integer |
|
||||||
|
| y | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| forwarded | 结果 = x | auto |
|
||||||
|
|
||||||
|
**v = [选择](math.math.select(`y`, `x`))**
|
||||||
|
*v*
|
||||||
|
"#;
|
||||||
|
fs::write(root.join("math.mq.md"),callee).unwrap();
|
||||||
|
fs::write(root.join("main.mq.md"),caller).unwrap();
|
||||||
|
let project=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=project.semantics.bound_calls.iter().find(|c|
|
||||||
|
c.call_site=="math.math.select").expect("static call");
|
||||||
|
let proof=candidate(&project,call).expect("symbolic projection");
|
||||||
|
assert_eq!(proof.parameter_index,1);
|
||||||
|
assert_eq!(proof.result_label,"x");
|
||||||
|
assert!(proof.callee_source.contains(":= v1"));
|
||||||
|
assert!(proof.caller_source.contains("callee v1 v0"));
|
||||||
|
assert!(proof.caller_source.contains("= v0"));
|
||||||
|
assert!(!proof.caller_source.contains("sorry"));
|
||||||
|
|
||||||
|
// Reordering the actuals without changing the asserted result must
|
||||||
|
// invalidate the caller contract; source is the authority.
|
||||||
|
let incorrect=caller.replace(
|
||||||
|
"math.math.select(`y`, `x`)",
|
||||||
|
"math.math.select(`x`, `y`)");
|
||||||
|
fs::write(root.join("main.mq.md"),incorrect).unwrap();
|
||||||
|
let changed=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=changed.semantics.bound_calls.iter().find(|c|
|
||||||
|
c.call_site=="math.math.select").unwrap();
|
||||||
|
assert!(candidate(&changed,call).is_none());
|
||||||
|
|
||||||
|
// A declaration with an unsatisfied precondition is NOT a proof.
|
||||||
|
fs::write(root.join("main.mq.md"),caller).unwrap();
|
||||||
|
fs::write(root.join("math.mq.md"),
|
||||||
|
callee.replace("| proj | 结果 = second | auto |",
|
||||||
|
"| proj | 结果 = second | auto |\n| other | 结果 = second | auto |")).unwrap();
|
||||||
|
let ambiguous=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=ambiguous.semantics.bound_calls.iter().find(|c|
|
||||||
|
c.call_site=="math.math.select").unwrap();
|
||||||
|
assert!(candidate(&ambiguous,call).is_none());
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
//! Bind a proved function claim to one semantic symbol, never to every
|
||||||
|
//! marked step. Unmatched identities and stale evidence fail closed.
|
||||||
|
|
||||||
|
use std::{collections::BTreeMap, fs, path::Path};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use crate::{prove::{Report, Verdict}, sema::ir::{Compilation, SemanticArtifact, SemanticProject}};
|
||||||
|
|
||||||
|
fn sha(bytes: &[u8]) -> String {
|
||||||
|
format!("sha256:{:x}", Sha256::digest(bytes))
|
||||||
|
}
|
||||||
|
fn generated_module_valid(folder:&Path,expected:&Value)->bool {
|
||||||
|
let source_dir=folder.join("Generated");
|
||||||
|
let Ok(files)=fs::read_dir(&source_dir) else {return false};
|
||||||
|
let mut candidates=files.flatten().filter(|f|
|
||||||
|
f.path().extension().is_some_and(|ext|ext=="lean")).collect::<Vec<_>>();
|
||||||
|
if candidates.len()!=1{return false}
|
||||||
|
let Some(generated)=candidates.pop() else{return false};
|
||||||
|
let Ok(source)=fs::read(generated.path()) else{return false};
|
||||||
|
sha(&source).trim_start_matches("sha256:")==expected.as_str().unwrap_or("")
|
||||||
|
}
|
||||||
|
/// Never accept a mutable cached Lean source as proof authority. Rebuild the
|
||||||
|
/// expected module and plan from the current Marqdo source with the same
|
||||||
|
/// compiler pipeline used by prove_path; a forged axiom/sorry in the cached
|
||||||
|
/// Lean file will not match the deterministic generated source.
|
||||||
|
fn cached_translation_matches_current(
|
||||||
|
folder:&Path, entry:&Value,semantic:&SemanticProject
|
||||||
|
)->bool {
|
||||||
|
let Some(rel)=entry["source_file"].as_str() else{return false};
|
||||||
|
let Some(display)=entry["proof_module_display"].as_str() else{return false};
|
||||||
|
let abs=semantic.root.join(rel);
|
||||||
|
let Ok(module)=crate::load::load_module(&abs) else{return false};
|
||||||
|
let Some(source_sha)=module.source.sha256.as_deref() else{return false};
|
||||||
|
if entry["source_sha256"]!=source_sha{return false}
|
||||||
|
let effects=crate::prove::lower::effect_map(&abs);
|
||||||
|
let Ok((plan,_))=crate::prove::lower::build_plan(
|
||||||
|
&module,source_sha,display,effects,&[]) else{return false};
|
||||||
|
if fs::read(folder.join("plan.json")).ok().as_deref()
|
||||||
|
!=Some(plan.to_stable_json().as_bytes()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let (generated_name,expected)=crate::prove::emit::emit_module(
|
||||||
|
&plan,&crate::prove::emit::stem_of(display));
|
||||||
|
let generated=folder.join("Generated").join(generated_name);
|
||||||
|
if fs::read(generated).ok().as_deref()!=Some(expected.as_bytes()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
sha(expected.as_bytes()).trim_start_matches("sha256:")
|
||||||
|
==entry["module_sha256"].as_str().unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn certificate_identity_valid(folder:&Path,cert:&Value)->bool {
|
||||||
|
let Ok(plan)=fs::read(folder.join("plan.json")) else {return false};
|
||||||
|
let source=cert["source_sha256"].as_str().unwrap_or("");
|
||||||
|
let library=cert["library_sha256"].as_str().unwrap_or("");
|
||||||
|
let toolchain=cert["toolchain"].as_str().unwrap_or("");
|
||||||
|
let actual_library=crate::prove::cache::sha256_hex(
|
||||||
|
crate::prove::driver::LIBRARY_SRC.as_bytes());
|
||||||
|
let expected_key=crate::prove::cache::cache_key(
|
||||||
|
source,&crate::prove::cache::sha256_hex(&plan),
|
||||||
|
library,toolchain,env!("CARGO_PKG_VERSION"));
|
||||||
|
library==actual_library
|
||||||
|
&& cert["marqdo"]==env!("CARGO_PKG_VERSION")
|
||||||
|
&& cert["key"]==expected_key
|
||||||
|
&& generated_module_valid(folder,&cert["module_sha256"])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn certificate(dir: &Path, report: &Report) -> Option<(Value, String)> {
|
||||||
|
let bytes = fs::read(dir.join("certificate.json")).ok()?;
|
||||||
|
let cert: Value = serde_json::from_slice(&bytes).ok()?;
|
||||||
|
let lean = report.lean.as_ref()?;
|
||||||
|
if cert["schema"] != 1 || cert["source_sha256"] != report.source_sha256
|
||||||
|
|| cert["tier"] != "lean" || cert["library_sha256"] != lean.library_sha256
|
||||||
|
|| cert["toolchain"] != lean.toolchain || cert["module_sha256"] != lean.module_sha256 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((cert, sha(&bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matching<'a>(compiled: &'a Compilation, path: &Path, name: &str)
|
||||||
|
-> Option<&'a SemanticArtifact> {
|
||||||
|
let file=path.canonicalize().ok()?;
|
||||||
|
let mut all=compiled.semantics.artifacts.iter()
|
||||||
|
.filter(|a|a.kind=="function" && a.display_name==name)
|
||||||
|
.filter(|a|compiled.semantics.root.join(&a.source.file)
|
||||||
|
.canonicalize().ok().as_deref()==Some(file.as_path()));
|
||||||
|
let first=all.next()?;
|
||||||
|
all.next().is_none().then_some(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exact owner binding; related step anchors are navigation only, not proved.
|
||||||
|
pub fn link_report(compiled: &Compilation, file: &Path, report: &Report, dir: &Path) -> Value {
|
||||||
|
let cert=certificate(dir,report);
|
||||||
|
let mut claims=Vec::new();
|
||||||
|
let mut unresolved=Vec::new();
|
||||||
|
for f in &report.functions {
|
||||||
|
let Some(owner)=matching(compiled,file,&f.name) else {
|
||||||
|
unresolved.push(json!({"function":f.name,"reason":"unbound_or_ambiguous"}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(symbol)=owner.symbol_id.as_ref() else {
|
||||||
|
unresolved.push(json!({"function":f.name,"reason":"missing_symbol_id"}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let steps:Vec<&str>=compiled.semantics.steps.iter()
|
||||||
|
.filter(|s|s.id.0.starts_with(&format!("{}#step-",symbol.as_str())))
|
||||||
|
.filter_map(|s|s.anchor_id.as_deref()).collect();
|
||||||
|
for claim in &f.claims {
|
||||||
|
// A proof receipt must be bound to the exact theorem declaration
|
||||||
|
// present in the same AST, not merely to a similarly named function.
|
||||||
|
let mut matching_claims=compiled.semantics.claims.iter().filter(|decl|
|
||||||
|
decl.owner==*symbol && decl.label==claim.id
|
||||||
|
&& decl.conclusion==claim.conclusion
|
||||||
|
&& decl.premise==claim.premise);
|
||||||
|
let Some(declared)=matching_claims.next() else {
|
||||||
|
unresolved.push(json!({"function":f.name,"claim":claim.id,
|
||||||
|
"reason":"theorem_declaration_missing_or_changed"}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if matching_claims.next().is_some() {
|
||||||
|
unresolved.push(json!({"function":f.name,"claim":claim.id,
|
||||||
|
"reason":"ambiguous_theorem_declaration"}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cert_ok=cert.as_ref().is_some_and(|(v,_)|
|
||||||
|
v["claims"].as_array().is_some_and(|records|
|
||||||
|
records.iter().any(|r|
|
||||||
|
r["id"]==claim.id && r["function"]==f.name
|
||||||
|
&& r["status"]=="proved")));
|
||||||
|
let proved=claim.status==Verdict::Proved && claim.decided_by=="lean" && cert_ok;
|
||||||
|
let status=if claim.status==Verdict::Proved && !proved {
|
||||||
|
"unverified"
|
||||||
|
} else { claim.status.as_str() };
|
||||||
|
claims.push(json!({
|
||||||
|
"claim_anchor_id":declared.anchor_id,
|
||||||
|
"owner_symbol_id":symbol.as_str(),
|
||||||
|
"function":f.name,"claim_id":claim.id,
|
||||||
|
"premise":claim.premise,"conclusion":claim.conclusion,
|
||||||
|
"source_line":claim.source_line,
|
||||||
|
"status":status,
|
||||||
|
"decided_by":if proved {"lean"} else if status=="checked" {"offline"} else {"none"},
|
||||||
|
"certificate_digest":if proved {cert.as_ref().map(|(_,h)|h.as_str())} else {None},
|
||||||
|
"proof_scope":"function",
|
||||||
|
"evidence":super::evidence::for_receipt(
|
||||||
|
status,proved,false),
|
||||||
|
"related_anchor_ids":steps,
|
||||||
|
"related_anchor_relation":"defined_in_same_function_not_individually_proved",
|
||||||
|
"semantic_hashes":{"interface":owner.hashes.interface.0,
|
||||||
|
"implementation":owner.hashes.implementation.0,
|
||||||
|
"closure":owner.hashes.closure.0},
|
||||||
|
"source_file":owner.source.file,
|
||||||
|
"source_sha256":report.source_sha256,
|
||||||
|
"library_sha256":report.lean.as_ref().map(|l|l.library_sha256.as_str()),
|
||||||
|
"toolchain":report.lean.as_ref().map(|l|l.toolchain.as_str()),
|
||||||
|
"module_sha256":report.lean.as_ref().map(|l|l.module_sha256.as_str()),
|
||||||
|
"proof_module_display":report.file
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
claims.sort_by(|a,b|a["claim_anchor_id"].as_str().cmp(&b["claim_anchor_id"].as_str()));
|
||||||
|
let assumptions:Vec<Value>=compiled.semantics.assumptions.iter()
|
||||||
|
.filter(|a|compiled.semantics.root.join(&a.source.file)
|
||||||
|
.canonicalize().ok().as_deref()==file.canonicalize().ok().as_deref())
|
||||||
|
.map(|a|json!({"id":a.id,"owner":a.owner.as_str(),
|
||||||
|
"operation":a.operation,"premise":a.premise,
|
||||||
|
"postcondition":a.postcondition,
|
||||||
|
"status":"declared_not_disclosed_as_proved"}))
|
||||||
|
.collect();
|
||||||
|
json!({"schema_version":1,"kind":"knowledge_proof_linkage",
|
||||||
|
"source_sha256":report.source_sha256,"file":report.file,
|
||||||
|
"claims":claims,"assumptions":assumptions,"unresolved":unresolved})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn emit_links(file: &Path, report: &Report, dir: &Path) -> Result<()> {
|
||||||
|
let result=match crate::sema::ir::compile_file_closure(file) {
|
||||||
|
Ok(compiled)=>link_report(&compiled,file,report,dir),
|
||||||
|
Err(err)=>json!({"schema_version":1,"kind":"knowledge_proof_linkage",
|
||||||
|
"status":"unbound","source_sha256":report.source_sha256,"claims":[],
|
||||||
|
"unresolved":[{"reason":"semantic_compile_failed","detail":format!("{err:#}")}]}),
|
||||||
|
};
|
||||||
|
let path=dir.join("knowledge-links.json");
|
||||||
|
fs::write(&path,serde_json::to_vec_pretty(&result)?)
|
||||||
|
.with_context(||format!("write {}",path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalidate proof links against both semantic owner hashes and source bytes.
|
||||||
|
/// Certificate integrity is rechecked; duplicate claim identities are refused.
|
||||||
|
pub fn index_links(prove_dir:&Path, semantic:&SemanticProject)->Value {
|
||||||
|
let owners:BTreeMap<_,_>=semantic.artifacts.iter()
|
||||||
|
.filter_map(|a|a.symbol_id.as_ref().map(|id|(id.as_str().to_string(),a)))
|
||||||
|
.collect();
|
||||||
|
let mut entries=Vec::new();
|
||||||
|
if let Ok(folders)=fs::read_dir(prove_dir) {
|
||||||
|
for folder in folders.flatten().filter(|f|f.path().is_dir()) {
|
||||||
|
let Ok(bytes)=fs::read(folder.path().join("knowledge-links.json")) else {continue};
|
||||||
|
let Ok(link) = serde_json::from_slice::<Value>(&bytes) else {continue};
|
||||||
|
let Some(claims)=link["claims"].as_array() else {continue};
|
||||||
|
for claim in claims {
|
||||||
|
let mut entry=claim.clone();
|
||||||
|
entry["receipt_artifact"]=json!(folder.file_name().to_string_lossy().to_string());
|
||||||
|
let owner=claim["owner_symbol_id"].as_str().and_then(|id|owners.get(id));
|
||||||
|
let theorem_present=claim["owner_symbol_id"].as_str().is_some_and(|id|
|
||||||
|
semantic.claims.iter().any(|c|
|
||||||
|
c.owner.as_str()==id
|
||||||
|
&& claim["claim_anchor_id"]==c.anchor_id
|
||||||
|
&& claim["claim_id"]==c.label
|
||||||
|
&& claim["conclusion"]==c.conclusion
|
||||||
|
&& claim["premise"]==json!(c.premise)));
|
||||||
|
let fresh=theorem_present && owner.is_some_and(|a| {
|
||||||
|
claim["source_file"]==a.source.file
|
||||||
|
&& claim["semantic_hashes"]["interface"]==a.hashes.interface.0
|
||||||
|
&& claim["semantic_hashes"]["implementation"]==a.hashes.implementation.0
|
||||||
|
&& claim["semantic_hashes"]["closure"]==a.hashes.closure.0
|
||||||
|
&& fs::read(semantic.root.join(&a.source.file)).ok().is_some_and(
|
||||||
|
|raw|sha(&raw).trim_start_matches("sha256:")==claim["source_sha256"])
|
||||||
|
});
|
||||||
|
let certified=cached_translation_matches_current(
|
||||||
|
&folder.path(),&entry,semantic)
|
||||||
|
&& entry["status"]=="proved" && entry["decided_by"]=="lean"
|
||||||
|
&& entry["certificate_digest"].as_str().is_some_and(|digest|
|
||||||
|
fs::read(folder.path().join("certificate.json")).ok().is_some_and(|bytes| {
|
||||||
|
if sha(&bytes)!=digest { return false; }
|
||||||
|
let Ok(cert)=serde_json::from_slice::<Value>(&bytes) else {
|
||||||
|
return false
|
||||||
|
};
|
||||||
|
cert["schema"]==1 && cert["tier"]=="lean"
|
||||||
|
&& certificate_identity_valid(&folder.path(),&cert)
|
||||||
|
&& cert["source_sha256"]==entry["source_sha256"]
|
||||||
|
&& cert["library_sha256"]==entry["library_sha256"]
|
||||||
|
&& cert["toolchain"]==entry["toolchain"]
|
||||||
|
&& cert["module_sha256"]==entry["module_sha256"]
|
||||||
|
&& cert["claims"].as_array().is_some_and(|records|
|
||||||
|
records.iter().any(|r|
|
||||||
|
r["id"]==entry["claim_id"]
|
||||||
|
&& r["function"]==entry["function"]
|
||||||
|
&& r["status"]=="proved"))
|
||||||
|
}));
|
||||||
|
if !fresh {
|
||||||
|
entry["status"]=json!("stale");
|
||||||
|
entry["stale_reason"]=json!("source_or_semantic_dependency_changed");
|
||||||
|
} else if entry["status"]=="proved" && !certified {
|
||||||
|
entry["status"]=json!("unverified");
|
||||||
|
entry["stale_reason"]=json!("missing_or_changed_lean_certificate");
|
||||||
|
}
|
||||||
|
entry["usable"]=json!(fresh && certified);
|
||||||
|
entries.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries.sort_by(|a,b|a["claim_anchor_id"].as_str().cmp(&b["claim_anchor_id"].as_str()));
|
||||||
|
let mut freq=BTreeMap::new();
|
||||||
|
for e in &entries {
|
||||||
|
if let Some(id)=e["claim_anchor_id"].as_str() {
|
||||||
|
*freq.entry(id.to_string()).or_insert(0usize)+=1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for e in &mut entries {
|
||||||
|
if e["claim_anchor_id"].as_str().and_then(|id|freq.get(id))
|
||||||
|
.is_some_and(|n|*n>1) {
|
||||||
|
e["status"]=json!("ambiguous");
|
||||||
|
e["stale_reason"]=json!("multiple_proof_link_records");
|
||||||
|
e["usable"]=json!(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Evidence is orthogonal to legacy `status`: a verified Lean receipt
|
||||||
|
// means model_proved, NOT unrestricted Marqdo runtime correctness.
|
||||||
|
for e in &mut entries {
|
||||||
|
e["evidence"]=super::evidence::for_receipt(
|
||||||
|
e["status"].as_str().unwrap_or("unknown"),
|
||||||
|
e["usable"]==true,e["kernel_replayed"]==true);
|
||||||
|
}
|
||||||
|
json!({"schema_version":1,"role":"proof_receipts_not_execution_authority",
|
||||||
|
"claims":entries})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Recheck every locally cached *usable* Lean receipt with an actual Lean
|
||||||
|
/// invocation. Hash-only certificates are not trusted for --verify. An error
|
||||||
|
/// at one folder revokes all its receipts; no JSON proof flag can override it.
|
||||||
|
pub fn replay_index(
|
||||||
|
prove_dir:&Path, index:&mut Value,
|
||||||
|
toolchain:&crate::prove::driver::Toolchain,
|
||||||
|
timeout:std::time::Duration
|
||||||
|
)->Result<()> {
|
||||||
|
let (libdir,_)=crate::prove::driver::ensure_library(prove_dir,toolchain)?;
|
||||||
|
let mut replayed:BTreeMap<String,Vec<(String,String)>>=BTreeMap::new();
|
||||||
|
let mut rejected:std::collections::BTreeSet<String>=std::collections::BTreeSet::new();
|
||||||
|
let Some(entries)=index["claims"].as_array_mut() else {return Ok(())};
|
||||||
|
let artifacts:std::collections::BTreeSet<_>=entries.iter()
|
||||||
|
.filter(|e|e["usable"]==true)
|
||||||
|
.filter_map(|e|e["receipt_artifact"].as_str().map(str::to_owned))
|
||||||
|
.collect();
|
||||||
|
for id in artifacts {
|
||||||
|
if id=="." || id==".." || id.contains('/') || id.contains('\\'){
|
||||||
|
rejected.insert(id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let src_dir=prove_dir.join(&id).join("Generated");
|
||||||
|
let files=fs::read_dir(&src_dir).ok().into_iter()
|
||||||
|
.flat_map(|items|items.flatten())
|
||||||
|
.filter(|f|f.path().extension().is_some_and(|ext|ext=="lean"))
|
||||||
|
.map(|f|f.path()).collect::<Vec<_>>();
|
||||||
|
if files.len()!=1 {rejected.insert(id);continue;}
|
||||||
|
let path=&files[0];
|
||||||
|
let Ok(source)=fs::read_to_string(path) else {rejected.insert(id);continue};
|
||||||
|
let Ok(outcome)=crate::prove::driver::check_module(
|
||||||
|
toolchain,&libdir,path,&source,timeout,None) else {
|
||||||
|
rejected.insert(id);continue;
|
||||||
|
};
|
||||||
|
if outcome.status!=Verdict::Proved ||
|
||||||
|
fs::read_to_string(path).ok().as_deref()!=Some(source.as_str()) {
|
||||||
|
rejected.insert(id);continue;
|
||||||
|
}
|
||||||
|
replayed.insert(id,outcome.claims.into_iter()
|
||||||
|
.filter(|c|c.status==Verdict::Proved)
|
||||||
|
.map(|c|(c.function,c.claim)).collect());
|
||||||
|
}
|
||||||
|
for entry in entries {
|
||||||
|
if entry["usable"]!=true {continue;}
|
||||||
|
let id=entry["receipt_artifact"].as_str().unwrap_or("");
|
||||||
|
let found=replayed.get(id).is_some_and(|claims|claims.iter().any(|(fun,claim)|
|
||||||
|
entry["function"]==fun.as_str() && entry["claim_id"]==claim.as_str()));
|
||||||
|
if !found || rejected.contains(id) {
|
||||||
|
entry["usable"]=json!(false);
|
||||||
|
entry["status"]=json!("unverified");
|
||||||
|
entry["stale_reason"]=json!("lean_kernel_replay_failed");
|
||||||
|
} else {
|
||||||
|
entry["kernel_replayed"]=json!(true);
|
||||||
|
}
|
||||||
|
entry["evidence"]=super::evidence::for_receipt(
|
||||||
|
entry["status"].as_str().unwrap_or("unknown"),
|
||||||
|
entry["usable"]==true,entry["kernel_replayed"]==true);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
//! Symbolic branch VCs for a deliberately restricted, pure integer fragment.
|
||||||
|
//! A proved proposition in the Int abstraction is NOT by itself a proof of
|
||||||
|
//! Marqdo runtime semantics (i64, dynamic values and exceptions).
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use crate::prove::proof_check::{self,ClaimAst as A,CTok as T};
|
||||||
|
use crate::sema::ir::{BoundCall,SemanticProject};
|
||||||
|
|
||||||
|
#[derive(Debug,Clone)]
|
||||||
|
pub struct SymbolicGoal{
|
||||||
|
pub proposition:String,
|
||||||
|
pub guard_propositions:Vec<String>,
|
||||||
|
pub guard_index:Option<usize>,
|
||||||
|
pub binders:Vec<String>,
|
||||||
|
pub runtime_domain_verified:bool,
|
||||||
|
pub abstract_integer_model_supported:bool,
|
||||||
|
}
|
||||||
|
fn identifier(s:&str)->bool {
|
||||||
|
!s.is_empty()&&s.chars().all(|c|c.is_alphanumeric()||c=='_')
|
||||||
|
}
|
||||||
|
fn term(expr:&A,bindings:&BTreeMap<String,String>)->Option<(String,bool)>{
|
||||||
|
match expr {
|
||||||
|
A::Lit(T::Int(n))=>Some((format!("({n} : Int)"),false)),
|
||||||
|
A::Lit(T::Bool(b))=>Some((if *b{"True"}else{"False"}.into(),true)),
|
||||||
|
A::Var(v)=>Some((bindings.get(v)?.clone(),false)),
|
||||||
|
A::Bin{op,left,right}=>{
|
||||||
|
let (l,lb)=term(left,bindings)?;
|
||||||
|
let (r,rb)=term(right,bindings)?;
|
||||||
|
match *op{
|
||||||
|
"+" | "-" if !lb && !rb=>Some((format!("({l} {op} {r})"),false)),
|
||||||
|
// omega only reasons about *linear* arithmetic. A variable
|
||||||
|
// multiplied by another variable is never assumed linear.
|
||||||
|
"*" if !lb && !rb
|
||||||
|
&& (matches!(left.as_ref(),A::Lit(T::Int(_)))
|
||||||
|
||matches!(right.as_ref(),A::Lit(T::Int(_))))=>
|
||||||
|
Some((format!("({l} * {r})"),false)),
|
||||||
|
"=" | "≠" | "<" | "≤" | ">" | "≥" if !lb && !rb=>
|
||||||
|
Some((format!("({l} {op} {r})"),true)),
|
||||||
|
"且" if lb && rb=>Some((format!("({l} ∧ {r})"),true)),
|
||||||
|
"或" if lb && rb=>Some((format!("({l} ∨ {r})"),true)),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
A::Un{op:"非",expr}=>{
|
||||||
|
let (inner,boolean)=term(expr,bindings)?;
|
||||||
|
boolean.then(||(format!("(¬ {inner})"),true))
|
||||||
|
},
|
||||||
|
A::Un{op:"-",expr}=>{
|
||||||
|
let (inner,boolean)=term(expr,bindings)?;
|
||||||
|
(!boolean).then(||(format!("(-{inner})"),false))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn proposition(source:&str,bindings:&BTreeMap<String,String>)->Option<String>{
|
||||||
|
let tokens=proof_check::tokenize_claim(source).ok()?;
|
||||||
|
let (_,expr)=proof_check::parse_claim_expr(&tokens).ok()?;
|
||||||
|
let (text,boolean)=term(&expr,bindings)?;
|
||||||
|
boolean.then_some(text)
|
||||||
|
}
|
||||||
|
/// Source-backed branch facts are the only assumptions accepted; no theorem
|
||||||
|
/// premise provided by a model/user is silently promoted to an axiom.
|
||||||
|
pub fn plan(semantic:&SemanticProject,call:&BoundCall,premise:&str)->Option<SymbolicGoal>{
|
||||||
|
if call.control_blocker.is_some()||call.path_guards.is_empty(){return None}
|
||||||
|
let callee=semantic.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target))?.signature.as_ref()?;
|
||||||
|
let caller=semantic.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.caller))?.signature.as_ref()?;
|
||||||
|
if callee.params.len()!=call.args.len(){return None}
|
||||||
|
let mut caller_bind=BTreeMap::new();
|
||||||
|
let mut binders=Vec::new();
|
||||||
|
for (i,param) in caller.params.iter().enumerate(){
|
||||||
|
if !identifier(¶m.name){return None}
|
||||||
|
let variable=format!("v{i}");
|
||||||
|
caller_bind.insert(param.name.clone(),format!("({variable} : Int)"));
|
||||||
|
binders.push(variable);
|
||||||
|
}
|
||||||
|
// Marqdo canonical Number may include Int, Num and Formula.
|
||||||
|
// Proof is over Int only; never claim a runtime type proof here.
|
||||||
|
let model_supported=caller.params.iter()
|
||||||
|
.all(|p|p.ty.eq_ignore_ascii_case("number"));
|
||||||
|
if !model_supported {return None}
|
||||||
|
let mut callee_bind=BTreeMap::new();
|
||||||
|
for (formal,arg) in callee.params.iter().zip(call.args.iter()){
|
||||||
|
if arg.name.as_ref().is_some_and(|s|s!=&formal.name){return None}
|
||||||
|
let actual=if let Some(n)=arg.integer {
|
||||||
|
format!("({n} : Int)")
|
||||||
|
}else{
|
||||||
|
caller_bind.get(arg.symbol.as_ref()?)?.clone()
|
||||||
|
};
|
||||||
|
if !identifier(&formal.name){return None}
|
||||||
|
callee_bind.insert(formal.name.clone(),actual);
|
||||||
|
}
|
||||||
|
let wanted=proposition(premise,&callee_bind)?;
|
||||||
|
let all=call.path_guards.iter().map(|guard|proposition(guard,&caller_bind))
|
||||||
|
.collect::<Option<Vec<_>>>()?;
|
||||||
|
let idx=all.iter().position(|guard|guard==&wanted);
|
||||||
|
Some(SymbolicGoal {
|
||||||
|
proposition:wanted,guard_propositions:all,guard_index:idx,
|
||||||
|
binders,runtime_domain_verified:false,
|
||||||
|
abstract_integer_model_supported:model_supported
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn emit_lean(goals:&[(String,SymbolicGoal)])->String{
|
||||||
|
let mut text=String::from("-- Symbolic path theorem over Int model; not runtime equivalence.\nnamespace MarqdoSymbolic\n");
|
||||||
|
for (i,(_,g)) in goals.iter().enumerate(){
|
||||||
|
let vars=g.binders.iter().map(|x|format!("({x} : Int)"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
let hypotheses=g.guard_propositions.iter().enumerate()
|
||||||
|
.map(|(n,p)|format!("(h{n} : {p})"))
|
||||||
|
.collect::<Vec<_>>().join(" ");
|
||||||
|
let tactic=if let Some(n)=g.guard_index {
|
||||||
|
format!(" exact h{n}")
|
||||||
|
} else {
|
||||||
|
" omega".to_string()
|
||||||
|
};
|
||||||
|
text.push_str(&format!("theorem path_vc_{i} {vars} {hypotheses} : {} := by\n{tactic}\n",
|
||||||
|
g.proposition));
|
||||||
|
}
|
||||||
|
text.push_str("end MarqdoSymbolic\n");
|
||||||
|
text
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests{
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn branch_condition_generates_symbolic_lean_obligation() {
|
||||||
|
let root=std::env::temp_dir().join(format!(
|
||||||
|
"marqdo-symbolic-branch-{}",std::process::id()));
|
||||||
|
let _=std::fs::remove_dir_all(&root);
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
std::fs::write(root.join("math.mq.md"),
|
||||||
|
"# math\n\n## exact\n+ `n`\n\n| 参数 | 类型 | 说明 |\n|---|---|---|\n| n | int | integer |\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | n > 0 | auto |\n\n*2*\n").unwrap();
|
||||||
|
std::fs::write(root.join("main.mq.md"),
|
||||||
|
"---\nimport:\n math: math.mq.md\n---\n# main\n\n## f\n+ `n`\n\n| 参数 | 类型 | 说明 |\n|---|---|---|\n| n | int | integer |\n\n1. `n` > 0\n **v = [调用](math.math.exact(`n`))**\n2. *\n **v = 0**\n\n*v*\n").unwrap();
|
||||||
|
let c=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=c.semantics.bound_calls.iter().find(|x|
|
||||||
|
x.call_site=="math.math.exact").expect("import binding");
|
||||||
|
assert_eq!(call.path_guards.len(),1);
|
||||||
|
assert!(call.control_blocker.is_none());
|
||||||
|
let goal=plan(&c.semantics,call,"n > 0")
|
||||||
|
.expect("path condition should imply imported precondition");
|
||||||
|
assert!(!goal.runtime_domain_verified);
|
||||||
|
assert!(goal.abstract_integer_model_supported);
|
||||||
|
assert_eq!(goal.guard_index,Some(0));
|
||||||
|
let source=emit_lean(&[("branch-call".into(),goal)]);
|
||||||
|
assert!(source.contains("theorem path_vc_0"));
|
||||||
|
assert!(source.contains("exact h0"));
|
||||||
|
assert!(!source.contains("sorry"));
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn linear_arithmetic_path_goals_are_supported_but_nonlinear_goals_fail_closed(){
|
||||||
|
let params=BTreeMap::from([("n".into(),"(v0 : Int)".into()),
|
||||||
|
("m".into(),"(v1 : Int)".into())]);
|
||||||
|
let stronger=proposition("n + 5 > 10",¶ms)
|
||||||
|
.expect("linear path condition");
|
||||||
|
let weaker=proposition("n > 0",¶ms)
|
||||||
|
.expect("linear callee precondition");
|
||||||
|
let goal=SymbolicGoal{
|
||||||
|
proposition:weaker,guard_propositions:vec![stronger],
|
||||||
|
guard_index:None,binders:vec!["v0".into(),"v1".into()],
|
||||||
|
runtime_domain_verified:false,abstract_integer_model_supported:true
|
||||||
|
};
|
||||||
|
let generated=emit_lean(&[("linear".into(),goal)]);
|
||||||
|
assert!(generated.contains("omega"));
|
||||||
|
assert!(generated.contains("+"));
|
||||||
|
assert!(proposition("n * m > 0",¶ms).is_none(),
|
||||||
|
"nonlinear multiplication cannot silently enter omega fragment");
|
||||||
|
assert!(proposition("n * 3 > 0",¶ms).is_some());
|
||||||
|
assert!(proposition("-n < 0",¶ms).is_some());
|
||||||
|
assert!(proposition("n / 2 > 0",¶ms).is_none());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn symbolic_guards_cannot_be_invented_from_unsupported_calls(){
|
||||||
|
assert!(proposition("lib.fetch(x) > 0",&BTreeMap::new()).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,498 @@
|
|||||||
|
//! Unified source-derived, kernel-checked modular contracts over the Lean Int
|
||||||
|
//! abstraction. NOT an unrestricted Marqdo runtime correctness theorem.
|
||||||
|
//!
|
||||||
|
//! Each function is translated ONCE from its current AST into a separate Lean
|
||||||
|
//! module. Contracts are proved from that source; callers use only imported
|
||||||
|
//! contracts, never synthetic axioms or inlined callee implementations.
|
||||||
|
//! Supported: pure, statically bound positional calls; integer linear terms,
|
||||||
|
//! immutable expressions, sequential local assignments and total if/else
|
||||||
|
//! branches; arbitrarily nested acyclic cross-file dependencies (depth capped).
|
||||||
|
//! Unsupported: missing/multiple contracts, loops, recursive calls, plugins,
|
||||||
|
//! effects, dynamic dispatch, defaults, conditional contracts, non-total branches,
|
||||||
|
//! runtime Number/i64/Formula equivalence. Every such case fails closed.
|
||||||
|
use std::{collections::{BTreeMap,BTreeSet},fs,path::Path,time::Duration};
|
||||||
|
use anyhow::{Context,Result};
|
||||||
|
use serde_json::{json,Value};
|
||||||
|
use sha2::{Digest,Sha256};
|
||||||
|
use crate::{
|
||||||
|
ast::{Arg,BinaryOp,CallExpr,Expr,Function,Literal,Stmt,UnaryOp},
|
||||||
|
prove::{driver::{Toolchain,compile_import_module},
|
||||||
|
proof_check::{self,ClaimAst,CTok}},
|
||||||
|
sema::{SymbolId,ir::{BoundCall,CanonicalParam,Compilation,SemanticArtifact}}
|
||||||
|
};
|
||||||
|
use super::projection::load_function;
|
||||||
|
|
||||||
|
const KIND:&str="marqdo_unified_modular_contract";
|
||||||
|
const SCOPE:&str="pure_number_int_model_sequential_branch_dag";
|
||||||
|
fn sha(bytes:&[u8])->String{format!("sha256:{:x}",Sha256::digest(bytes))}
|
||||||
|
fn id_for(symbol:&str)->String{
|
||||||
|
let value=sha(symbol.as_bytes());
|
||||||
|
format!("f_{}",&value[7..31])
|
||||||
|
}
|
||||||
|
fn module_for(symbol:&str)->String{
|
||||||
|
let value=sha(symbol.as_bytes());
|
||||||
|
format!("M{}",&value[7..31])
|
||||||
|
}
|
||||||
|
fn args_text(args:&[String])->String{
|
||||||
|
if args.is_empty(){String::new()}else{format!(" {}",args.join(" "))}
|
||||||
|
}
|
||||||
|
fn variables(count:usize)->Vec<String>{
|
||||||
|
(0..count).map(|i|format!("v{i}")).collect()
|
||||||
|
}
|
||||||
|
fn binders(count:usize)->String{
|
||||||
|
variables(count).iter().map(|v|format!(" ({v} : Int)")).collect()
|
||||||
|
}
|
||||||
|
fn unique_artifact<'a>(compiled:&'a Compilation,id:&str)
|
||||||
|
->Option<&'a SemanticArtifact>{
|
||||||
|
let mut found=compiled.semantics.artifacts.iter().filter(|a|
|
||||||
|
a.kind=="function" && a.symbol_id.as_ref().is_some_and(|s|s.as_str()==id));
|
||||||
|
let one=found.next()?;
|
||||||
|
found.next().is_none().then_some(one)
|
||||||
|
}
|
||||||
|
fn basic_signature(params:&[CanonicalParam])->bool{
|
||||||
|
params.iter().all(|p|p.ty.eq_ignore_ascii_case("number")
|
||||||
|
&&p.required&&p.default_digest.is_none())
|
||||||
|
&¶ms.iter().map(|p|&p.name).collect::<BTreeSet<_>>().len()==params.len()
|
||||||
|
}
|
||||||
|
fn claim_term(ast:&ClaimAst,params:&BTreeMap<String,String>,depth:usize)
|
||||||
|
->Option<String>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
match ast{
|
||||||
|
ClaimAst::Lit(CTok::Int(n))=>Some(format!("({n} : Int)")),
|
||||||
|
ClaimAst::Var(v)=>params.get(v).cloned(),
|
||||||
|
ClaimAst::Un{op:"-",expr}=>Some(format!("(-{})",
|
||||||
|
claim_term(expr,params,depth+1)?)),
|
||||||
|
ClaimAst::Bin{op,left,right}=>{
|
||||||
|
let symbol=match *op{"+"|"-"|"*"=>*op,_=>return None};
|
||||||
|
// Multiplication between symbolic terms is outside the omega
|
||||||
|
// fragment. Only multiplication by a literal is admitted.
|
||||||
|
if symbol=="*" && !matches!(left.as_ref(),ClaimAst::Lit(CTok::Int(_)))
|
||||||
|
&&!matches!(right.as_ref(),ClaimAst::Lit(CTok::Int(_))){return None}
|
||||||
|
Some(format!("({} {symbol} {})",
|
||||||
|
claim_term(left,params,depth+1)?,
|
||||||
|
claim_term(right,params,depth+1)?))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn result_claim(compiled:&Compilation,artifact:&SemanticArtifact,
|
||||||
|
params:&BTreeMap<String,String>)->Option<String>{
|
||||||
|
let owner=artifact.symbol_id.as_ref()?;
|
||||||
|
let mut matches=compiled.semantics.claims.iter().filter(|c|
|
||||||
|
c.owner==*owner&&c.premise.as_deref()
|
||||||
|
.map_or(true,|p|p.trim().is_empty())).filter_map(|c|{
|
||||||
|
let tokens=proof_check::tokenize_claim(&c.conclusion).ok()?;
|
||||||
|
let (_,ast)=proof_check::parse_claim_expr(&tokens).ok()?;
|
||||||
|
match ast{
|
||||||
|
ClaimAst::Bin{op,left,right}
|
||||||
|
if matches!(*left,ClaimAst::Var(ref n) if n=="结果")=>{
|
||||||
|
let operator=match op{
|
||||||
|
"="=>"=", ">"=>">", "<"=>"<", "≥"=>">=", "≤"=>"<=", "≠"=>"!=",
|
||||||
|
_=>return None
|
||||||
|
};
|
||||||
|
Some(format!("{operator} {}",claim_term(&right,params,0)?))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let first=matches.next()?;
|
||||||
|
// One exported claim per function is an explicit, auditable boundary;
|
||||||
|
// other statements are never silently promoted into assumptions.
|
||||||
|
matches.next().is_none().then_some(first)
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct CallUse{
|
||||||
|
callee:String,args:Vec<String>
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Built{
|
||||||
|
symbol:String,artifact:String,closure:String,module:String,lean:String,
|
||||||
|
file:String,dep_symbols:BTreeSet<String>,result_operator:String
|
||||||
|
}
|
||||||
|
struct Builder<'a>{
|
||||||
|
compilation:&'a Compilation,
|
||||||
|
active:BTreeSet<String>,
|
||||||
|
built:BTreeMap<String,Built>,
|
||||||
|
order:Vec<String>
|
||||||
|
}
|
||||||
|
impl<'a> Builder<'a>{
|
||||||
|
fn new(c:&'a Compilation)->Self{
|
||||||
|
Self{compilation:c,active:BTreeSet::new(),
|
||||||
|
built:BTreeMap::new(),order:Vec::new()}
|
||||||
|
}
|
||||||
|
fn number(&mut self,expr:&Expr,env:&BTreeMap<String,String>,owner:&str,
|
||||||
|
line:u32,uses:&mut Vec<CallUse>,depth:usize)->Option<String>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
match expr{
|
||||||
|
Expr::Literal(Literal::Int(n))=>Some(format!("({n} : Int)")),
|
||||||
|
Expr::Var(v)=>env.get(v).cloned(),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>
|
||||||
|
self.number(inner,env,owner,line,uses,depth+1),
|
||||||
|
Expr::Unary{op:UnaryOp::Neg,expr}=>Some(format!("(-{})",
|
||||||
|
self.number(expr,env,owner,line,uses,depth+1)?)),
|
||||||
|
Expr::Binary{op,left,right}=>{
|
||||||
|
let symbol=match op{
|
||||||
|
BinaryOp::Add=>"+",BinaryOp::Sub=>"-",
|
||||||
|
BinaryOp::Mul=>"*",_=>return None
|
||||||
|
};
|
||||||
|
if symbol=="*" && !matches!(left.as_ref(),Expr::Literal(Literal::Int(_)))
|
||||||
|
&&!matches!(right.as_ref(),Expr::Literal(Literal::Int(_))){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let a=self.number(left,env,owner,line,uses,depth+1)?;
|
||||||
|
let b=self.number(right,env,owner,line,uses,depth+1)?;
|
||||||
|
Some(format!("({a} {symbol} {b})"))
|
||||||
|
},
|
||||||
|
Expr::Call(call)=>self.call(call,env,owner,line,uses,depth+1),
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn condition(&mut self,expr:&Expr,env:&BTreeMap<String,String>,
|
||||||
|
owner:&str,line:u32,uses:&mut Vec<CallUse>,depth:usize)->Option<String>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
match expr{
|
||||||
|
Expr::Literal(Literal::Bool(b))=>Some(if *b{"True"}else{"False"}.into()),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>
|
||||||
|
self.condition(inner,env,owner,line,uses,depth+1),
|
||||||
|
Expr::Unary{op:UnaryOp::Not,expr}=>Some(format!("(¬ {})",
|
||||||
|
self.condition(expr,env,owner,line,uses,depth+1)?)),
|
||||||
|
Expr::Binary{op,left,right}=>{
|
||||||
|
let relation=match op{
|
||||||
|
BinaryOp::Eq=>Some("="),BinaryOp::Ne=>Some("≠"),
|
||||||
|
BinaryOp::Lt=>Some("<"),BinaryOp::Le=>Some("≤"),
|
||||||
|
BinaryOp::Gt=>Some(">"),BinaryOp::Ge=>Some("≥"),
|
||||||
|
_=>None
|
||||||
|
};
|
||||||
|
if let Some(rel)=relation{
|
||||||
|
let a=self.number(left,env,owner,line,uses,depth+1)?;
|
||||||
|
let b=self.number(right,env,owner,line,uses,depth+1)?;
|
||||||
|
return Some(format!("({a} {rel} {b})"))
|
||||||
|
}
|
||||||
|
let relation=match op{BinaryOp::And=>"∧",
|
||||||
|
BinaryOp::Or=>"∨",_=>return None};
|
||||||
|
let a=self.condition(left,env,owner,line,uses,depth+1)?;
|
||||||
|
let b=self.condition(right,env,owner,line,uses,depth+1)?;
|
||||||
|
Some(format!("({a} {relation} {b})"))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn call(&mut self,call:&CallExpr,env:&BTreeMap<String,String>,
|
||||||
|
owner:&str,line:u32,uses:&mut Vec<CallUse>,depth:usize)->Option<String>{
|
||||||
|
if depth>=32 ||call.path.is_none()||call.receiver.is_some()
|
||||||
|
||!call.pre_modifiers.is_empty(){return None}
|
||||||
|
let normalized=call.for_evaluation().ok()?;
|
||||||
|
let display=crate::sema::bind::call_display(&normalized);
|
||||||
|
let mut matches=self.compilation.semantics.bound_calls.iter().filter(|bc|
|
||||||
|
bc.caller.as_str()==owner &&bc.source.line==line&&
|
||||||
|
bc.call_site==display);
|
||||||
|
let bound=matches.next()?.clone();
|
||||||
|
if matches.next().is_some()||bound.control_blocker.is_some()
|
||||||
|
||!bound.required_effects.is_pure()||bound.args.len()!=call.args.len(){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let callee=bound.target.as_str();
|
||||||
|
if callee==owner{return None}
|
||||||
|
let artifact=unique_artifact(self.compilation,callee)?;
|
||||||
|
if !artifact.effects.is_pure(){return None}
|
||||||
|
let signature=artifact.signature.as_ref()?;
|
||||||
|
if !basic_signature(&signature.params)||
|
||||||
|
signature.params.len()!=call.args.len(){return None}
|
||||||
|
// Only positional arguments, in executable order, are trusted here.
|
||||||
|
// Named/default/variadic semantics require their own binding proof.
|
||||||
|
let mut args=Vec::new();
|
||||||
|
for (actual,static_arg) in call.args.iter().zip(&bound.args){
|
||||||
|
if static_arg.name.is_some(){return None}
|
||||||
|
let Arg::Positional(value)=actual else{return None};
|
||||||
|
args.push(self.number(value,env,owner,line,uses,depth+1)?);
|
||||||
|
}
|
||||||
|
self.visit(callee)?;
|
||||||
|
uses.push(CallUse{callee:callee.to_owned(),args:args.clone()});
|
||||||
|
Some(format!("({}{})",id_for(callee),args_text(&args)))
|
||||||
|
}
|
||||||
|
fn block(&mut self,items:&[Stmt],mut env:BTreeMap<String,String>,
|
||||||
|
owner:&str,uses:&mut Vec<CallUse>,conditions:&mut Vec<String>,depth:usize)->Option<String>{
|
||||||
|
if depth>=32{return None}
|
||||||
|
for (index,st) in items.iter().enumerate(){
|
||||||
|
match st{
|
||||||
|
Stmt::Assign{name,value,span,..}=>{
|
||||||
|
let rhs=self.number(value,&env,owner,span.line,uses,0)?;
|
||||||
|
env.insert(name.clone(),rhs);
|
||||||
|
},
|
||||||
|
Stmt::Return{value,span} if index+1==items.len()=>{
|
||||||
|
return self.number(value,&env,owner,span.line,uses,0)
|
||||||
|
},
|
||||||
|
Stmt::Branch{arms,span} if index+1==items.len()=>{
|
||||||
|
// A branch must explicitly cover all outcomes, including
|
||||||
|
// its else arm. No unproved fallthrough is accepted.
|
||||||
|
let mut otherwise=None;
|
||||||
|
for arm in arms.iter().rev(){
|
||||||
|
let expression=self.block(&arm.body,env.clone(),
|
||||||
|
owner,uses,conditions,depth+1)?;
|
||||||
|
otherwise=Some(if let Some(condition)=&arm.condition{
|
||||||
|
let cond=self.condition(condition,&env,owner,
|
||||||
|
span.line,uses,0)?;
|
||||||
|
if !conditions.contains(&cond){conditions.push(cond.clone())}
|
||||||
|
let rest=otherwise?;
|
||||||
|
format!("(if {cond} then {expression} else {rest})")
|
||||||
|
}else{
|
||||||
|
if otherwise.is_some(){return None}
|
||||||
|
expression
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return otherwise
|
||||||
|
},
|
||||||
|
_=>return None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
fn visit(&mut self,symbol:&str)->Option<()>{
|
||||||
|
if self.built.contains_key(symbol){return Some(())}
|
||||||
|
if self.active.len()>=24||!self.active.insert(symbol.to_owned()){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let result=(||->Option<Built>{
|
||||||
|
let a=unique_artifact(self.compilation,symbol)?.clone();
|
||||||
|
if !a.effects.is_pure(){return None}
|
||||||
|
let sig=a.signature.as_ref()?;
|
||||||
|
if !basic_signature(&sig.params){return None}
|
||||||
|
let fun:Function=load_function(self.compilation,&a)?;
|
||||||
|
if fun.is_object()||fun.params.len()!=sig.params.len()
|
||||||
|
||!fun.params.iter().zip(&sig.params)
|
||||||
|
.all(|(f,p)|f.name==p.name){return None}
|
||||||
|
let env=sig.params.iter().enumerate().map(|(i,p)|
|
||||||
|
(p.name.clone(),format!("v{i}"))).collect::<BTreeMap<_,_>>();
|
||||||
|
let contract=result_claim(self.compilation,&a,&env)?;
|
||||||
|
let mut call_uses=Vec::new();
|
||||||
|
let mut conditions=Vec::new();
|
||||||
|
let body=self.block(&fun.body,env,symbol,&mut call_uses,
|
||||||
|
&mut conditions,0)?;
|
||||||
|
// No semantically relevant BoundCall may remain unmodeled:
|
||||||
|
// every source call requires a unique static binding.
|
||||||
|
let source_count=self.compilation.semantics.bound_calls.iter()
|
||||||
|
.filter(|c|c.caller.as_str()==symbol).count();
|
||||||
|
if call_uses.len()!=source_count{return None}
|
||||||
|
let deps=call_uses.iter().map(|use_|use_.callee.clone())
|
||||||
|
.collect::<BTreeSet<_>>();
|
||||||
|
if deps.contains(symbol){return None}
|
||||||
|
let fname=id_for(symbol);
|
||||||
|
let args=variables(sig.params.len());
|
||||||
|
let bind=binders(sig.params.len());
|
||||||
|
let invocation=format!("{fname}{}",args_text(&args));
|
||||||
|
let mut source=String::new();
|
||||||
|
for dep in &deps{
|
||||||
|
source.push_str(&format!("import {}\n",module_for(dep)));
|
||||||
|
}
|
||||||
|
source.push_str(&format!(
|
||||||
|
"-- Generated from a pure Marqdo AST. Int abstraction only.\n\
|
||||||
|
def {fname}{bind} : Int := {body}\n\
|
||||||
|
theorem {fname}_contract{bind} : {invocation} {contract} := by\n"));
|
||||||
|
for (i,use_) in call_uses.iter().enumerate(){
|
||||||
|
let callee_contract=format!("{}_contract",id_for(&use_.callee));
|
||||||
|
source.push_str(&format!(
|
||||||
|
" have hc{i} := {callee_contract}{}\n",args_text(&use_.args)));
|
||||||
|
}
|
||||||
|
// `split_ifs` is a Mathlib tactic, unavailable under the
|
||||||
|
// pinned core Lean toolchain. Case-split on source-derived
|
||||||
|
// conditions using core `by_cases`, then simplify each case.
|
||||||
|
let mut tactic=format!(" simp only [{fname}] at *");
|
||||||
|
for (i,condition) in conditions.iter().enumerate(){
|
||||||
|
tactic.push_str(&format!(" <;> by_cases h{i} : {condition}"));
|
||||||
|
}
|
||||||
|
if conditions.is_empty(){
|
||||||
|
tactic.push_str(" <;> omega\n");
|
||||||
|
}else{
|
||||||
|
tactic.push_str(" <;> simp_all <;> omega\n");
|
||||||
|
}
|
||||||
|
source.push_str(&tactic);
|
||||||
|
let operator=contract.split_whitespace().next()?.to_string();
|
||||||
|
Some(Built{
|
||||||
|
symbol:symbol.to_owned(),artifact:a.artifact_id.0.clone(),
|
||||||
|
closure:a.hashes.closure.0.clone(),module:module_for(symbol),
|
||||||
|
lean:source,file:a.source.file.clone(),dep_symbols:deps,
|
||||||
|
result_operator:operator
|
||||||
|
})
|
||||||
|
})();
|
||||||
|
self.active.remove(symbol);
|
||||||
|
if let Some(built)=result{
|
||||||
|
self.order.push(symbol.to_owned());
|
||||||
|
self.built.insert(symbol.to_owned(),built);
|
||||||
|
Some(())
|
||||||
|
}else{None}
|
||||||
|
}
|
||||||
|
fn plan(mut self,root:&str)->Option<Plan>{
|
||||||
|
self.visit(root)?;
|
||||||
|
if self.built.len()<2{return None}
|
||||||
|
let nodes=self.order.iter().map(|id|self.built.get(id).cloned())
|
||||||
|
.collect::<Option<Vec<_>>>()?;
|
||||||
|
// Actually prove a caller that uses imported source definitions.
|
||||||
|
if nodes.last()?.dep_symbols.is_empty(){return None}
|
||||||
|
Some(Plan{root:root.into(),nodes})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Plan{root:String,nodes:Vec<Built>}
|
||||||
|
impl Plan{
|
||||||
|
fn identities(&self)->BTreeSet<(String,String)>{
|
||||||
|
self.nodes.iter().map(|n|(n.artifact.clone(),n.closure.clone()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn key(&self,version:&str)->String{
|
||||||
|
sha(format!("{}|{:?}|{}",self.root,self.identities(),version).as_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn candidate(c:&Compilation,root:&str)->Option<Plan>{
|
||||||
|
Builder::new(c).plan(root)
|
||||||
|
}
|
||||||
|
/// Retain the stable legacy certificate format for simple one-call
|
||||||
|
/// forwarders. Use the unified engine for actual sequential, branched or
|
||||||
|
/// transitive contracts, where the legacy shape cannot represent the proof.
|
||||||
|
fn advanced(c:&Compilation,plan:&Plan)->bool{
|
||||||
|
if plan.nodes.len()>2{return true}
|
||||||
|
if c.semantics.bound_calls.iter()
|
||||||
|
.filter(|call|call.caller.as_str()==plan.root).count()>1{return true}
|
||||||
|
let Some(artifact)=unique_artifact(c,&plan.root) else{return false};
|
||||||
|
let Some(function)=load_function(c,artifact) else{return false};
|
||||||
|
function.body.iter().any(|stmt|matches!(stmt,Stmt::Branch{..}))
|
||||||
|
}
|
||||||
|
pub(super) fn covers(c:&Compilation,root:&SymbolId)->bool{
|
||||||
|
candidate(c,root.as_str()).is_some_and(|plan|advanced(c,&plan))
|
||||||
|
}
|
||||||
|
pub(super) fn prove(c:&Compilation,out:&Path,lean:&Toolchain)->Result<Vec<Value>>{
|
||||||
|
let roots=c.semantics.bound_calls.iter().map(|call|call.caller.as_str())
|
||||||
|
.collect::<BTreeSet<_>>();
|
||||||
|
let mut results=Vec::new();
|
||||||
|
for root in roots{
|
||||||
|
let Some(plan)=candidate(c,root)else{continue};
|
||||||
|
if !advanced(c,&plan){continue}
|
||||||
|
let key=plan.key(&lean.version);
|
||||||
|
let dir=out.join("composed").join(format!("unified-{}",&key[7..23]));
|
||||||
|
fs::create_dir_all(&dir)?;
|
||||||
|
let checked=(||->Result<Vec<Value>>{
|
||||||
|
let mut files=Vec::new();
|
||||||
|
for node in &plan.nodes{
|
||||||
|
let src=dir.join(format!("{}.lean",node.module));
|
||||||
|
let obj=dir.join(format!("{}.olean",node.module));
|
||||||
|
fs::write(&src,&node.lean)?;
|
||||||
|
compile_import_module(lean,&src,&obj,&dir,Duration::from_secs(120))
|
||||||
|
.with_context(||format!("module {}",node.module))?;
|
||||||
|
files.push(json!({
|
||||||
|
"symbol":node.symbol,"artifact":node.artifact,
|
||||||
|
"module":node.module,"source_sha256":sha(node.lean.as_bytes()),
|
||||||
|
"compiled_sha256":sha(&fs::read(obj)?),
|
||||||
|
"dependencies":node.dep_symbols,"result_operator":node.result_operator,
|
||||||
|
"source_file":node.file
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Ok(files)
|
||||||
|
})();
|
||||||
|
match checked{
|
||||||
|
Ok(files)=>{
|
||||||
|
let certificate=json!({
|
||||||
|
"schema_version":1,"kind":KIND,"scope":SCOPE,
|
||||||
|
"status":"lean_kernel_proved_model",
|
||||||
|
"evidence_grade":"model_proved",
|
||||||
|
"full_marqdo_runtime_semantics_proved":false,
|
||||||
|
"identity":plan.root,"toolchain":lean.version,
|
||||||
|
"source_closures":plan.identities().iter().map(|(id,h)|
|
||||||
|
json!({"id":id,"closure":h})).collect::<Vec<_>>(),
|
||||||
|
"modules":files,
|
||||||
|
"independent_replay":"topological module recompilation from current source"
|
||||||
|
});
|
||||||
|
let certificate_path=dir.join("composition-certificate.json");
|
||||||
|
fs::write(&certificate_path,serde_json::to_vec_pretty(&certificate)?)?;
|
||||||
|
results.push(json!({"identity":plan.root,
|
||||||
|
"status":"lean_kernel_proved_model",
|
||||||
|
"scope":SCOPE,"artifact":certificate_path,
|
||||||
|
"evidence":super::evidence::model_proved()}));
|
||||||
|
},
|
||||||
|
Err(e)=>{
|
||||||
|
let _=fs::remove_file(dir.join("composition-certificate.json"));
|
||||||
|
results.push(json!({"identity":plan.root,"status":"lean_rejected",
|
||||||
|
"scope":SCOPE,"error":format!("{e:#}"),
|
||||||
|
"evidence":super::evidence::unknown("lean_rejected")}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
pub(super) fn replay(c:&Compilation,certificate:&Path,lean:&Toolchain)->Result<Value>{
|
||||||
|
let cert:Value=serde_json::from_slice(&fs::read(certificate)?)?;
|
||||||
|
anyhow::ensure!(cert["schema_version"]==1&&cert["kind"]==KIND
|
||||||
|
&&cert["scope"]==SCOPE&&cert["status"]=="lean_kernel_proved_model"
|
||||||
|
&&cert["evidence_grade"]=="model_proved"
|
||||||
|
&&cert["full_marqdo_runtime_semantics_proved"]==false,
|
||||||
|
"proof.unified_invalid_certificate");
|
||||||
|
anyhow::ensure!(cert["toolchain"]==lean.version,
|
||||||
|
"proof.unified_stale_toolchain");
|
||||||
|
let root=cert["identity"].as_str().context("proof.unified_missing_identity")?;
|
||||||
|
let plan=candidate(c,root).context("proof.unified_stale_or_unsupported_source")?;
|
||||||
|
let expected=plan.identities();
|
||||||
|
let items=cert["source_closures"].as_array()
|
||||||
|
.context("proof.unified_missing_source_closures")?;
|
||||||
|
let actual=items.iter().map(|r|Ok((
|
||||||
|
r["id"].as_str().context("proof.unified_invalid_id")?.to_string(),
|
||||||
|
r["closure"].as_str().context("proof.unified_invalid_hash")?.to_string()
|
||||||
|
))).collect::<Result<BTreeSet<_>>>()?;
|
||||||
|
anyhow::ensure!(items.len()==expected.len()&&actual==expected,
|
||||||
|
"proof.unified_stale_or_ambiguous_source_closure");
|
||||||
|
let rows=cert["modules"].as_array().context("proof.unified_missing_modules")?;
|
||||||
|
anyhow::ensure!(rows.len()==plan.nodes.len(),
|
||||||
|
"proof.unified_module_count_changed");
|
||||||
|
let dir=certificate.parent().context("proof.unified_missing_parent")?;
|
||||||
|
for (node,row) in plan.nodes.iter().zip(rows){
|
||||||
|
anyhow::ensure!(row["symbol"]==node.symbol&&row["artifact"]==node.artifact
|
||||||
|
&&row["module"]==node.module
|
||||||
|
&&row["dependencies"]==json!(node.dep_symbols)
|
||||||
|
&&row["result_operator"]==node.result_operator
|
||||||
|
&&row["source_file"]==node.file,
|
||||||
|
"proof.unified_module_identity_changed");
|
||||||
|
let src=dir.join(format!("{}.lean",node.module));
|
||||||
|
let obj=dir.join(format!("{}.olean",node.module));
|
||||||
|
anyhow::ensure!(fs::read_to_string(&src)?==node.lean
|
||||||
|
&&row["source_sha256"]==sha(node.lean.as_bytes()),
|
||||||
|
"proof.unified_generated_source_changed");
|
||||||
|
compile_import_module(lean,&src,&obj,dir,Duration::from_secs(120))?;
|
||||||
|
anyhow::ensure!(row["compiled_sha256"]==sha(&fs::read(&obj)?),
|
||||||
|
"proof.unified_compiled_module_changed");
|
||||||
|
}
|
||||||
|
Ok(json!({"schema_version":1,"kind":"independent_composition_replay",
|
||||||
|
"status":"lean_kernel_replayed","scope":SCOPE,"identity":root,
|
||||||
|
"evidence":super::evidence::model_replayed(),
|
||||||
|
"current_source_verified":true,
|
||||||
|
"full_marqdo_runtime_semantics_proved":false}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests{
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn simple_source_contracts_must_not_be_promoted_without_unique_claim(){
|
||||||
|
let c=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(
|
||||||
|
Path::new("doc/verification/skill-proof")).unwrap());
|
||||||
|
if let Ok(project)=c{
|
||||||
|
for artifact in project.semantics.artifacts.iter()
|
||||||
|
.filter(|a|a.kind=="function"){
|
||||||
|
assert!(!project.semantics.claims.iter()
|
||||||
|
.any(|r|r.owner.as_str()=="__invented_symbol__"));
|
||||||
|
let _=artifact;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn claim_language_refuses_nonlinear_and_unknown_values(){
|
||||||
|
let bind=BTreeMap::from([("n".into(),"v0".into()),
|
||||||
|
("m".into(),"v1".into())]);
|
||||||
|
let parse=|s:&str|{
|
||||||
|
let toks=proof_check::tokenize_claim(s).unwrap();
|
||||||
|
proof_check::parse_claim_expr(&toks).unwrap().1
|
||||||
|
};
|
||||||
|
assert_eq!(claim_term(&parse("n + 2"),&bind,0),
|
||||||
|
Some("(v0 + (2 : Int))".into()));
|
||||||
|
assert!(claim_term(&parse("n * m"),&bind,0).is_none());
|
||||||
|
assert!(claim_term(&parse("n / 2"),&bind,0).is_none());
|
||||||
|
assert!(claim_term(&parse("secret"),&bind,0).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
//! Closed, overflow-safe callsite verification conditions. A generated
|
||||||
|
//! formula is a Lean *goal*, not evidence. Only a subsequent kernel invocation
|
||||||
|
//! can discharge it. Unknown/symbolic arguments always remain open.
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use crate::prove::proof_check::{self,ClaimAst as A,CTok as T};
|
||||||
|
use crate::sema::ir::{BoundCall, SemanticProject};
|
||||||
|
|
||||||
|
#[derive(Debug,Clone,PartialEq,Eq)]
|
||||||
|
pub struct Goal {
|
||||||
|
/// Exact statement of the instantiated proposition.
|
||||||
|
pub proposition: String,
|
||||||
|
/// Conservative host-side check for early rejection only; not a proof.
|
||||||
|
pub holds: bool,
|
||||||
|
}
|
||||||
|
enum Term {
|
||||||
|
Int(i64,String),
|
||||||
|
Bool(bool,String),
|
||||||
|
}
|
||||||
|
fn calc(ast:&A, actuals:&BTreeMap<String,i64>)->Option<Term>{
|
||||||
|
match ast {
|
||||||
|
A::Lit(T::Int(n))=>Some(Term::Int(*n,format!("({n} : Int)"))),
|
||||||
|
A::Lit(T::Bool(b))=>Some(Term::Bool(*b,
|
||||||
|
if *b{"True"}else{"False"}.into())),
|
||||||
|
A::Var(v)=>actuals.get(v).map(|n|Term::Int(*n,format!("({n} : Int)"))),
|
||||||
|
A::Un{op,expr}=>match (*op,calc(expr,actuals)?) {
|
||||||
|
("-",Term::Int(n,code))=>Some(Term::Int(n.checked_neg()?,format!("(-{code})"))),
|
||||||
|
("非",Term::Bool(b,code))=>Some(Term::Bool(!b,format!("(¬ {code})"))),
|
||||||
|
_=>None
|
||||||
|
},
|
||||||
|
A::Bin{op,left,right}=>{
|
||||||
|
let l=calc(left,actuals)?;
|
||||||
|
let r=calc(right,actuals)?;
|
||||||
|
match (l,r) {
|
||||||
|
(Term::Int(x,a),Term::Int(y,b))=>{
|
||||||
|
let pair=match *op {
|
||||||
|
"+"=>Some((x.checked_add(y)?,format!("({a} + {b})"))),
|
||||||
|
"-"=>Some((x.checked_sub(y)?,format!("({a} - {b})"))),
|
||||||
|
"*"=>Some((x.checked_mul(y)?,format!("({a} * {b})"))),
|
||||||
|
_=>None
|
||||||
|
};
|
||||||
|
if let Some((n,code))=pair {return Some(Term::Int(n,code))}
|
||||||
|
let (truth,rel)=match *op {
|
||||||
|
"="=>(x==y,"="),"≠"=>(x!=y,"≠"),
|
||||||
|
"<"=>(x<y,"<"),"≤"=>(x<=y,"≤"),
|
||||||
|
">"=>(x>y,">"),"≥"=>(x>=y,"≥"),_=>return None
|
||||||
|
};
|
||||||
|
Some(Term::Bool(truth,format!("({a} {rel} {b})")))
|
||||||
|
},
|
||||||
|
(Term::Bool(x,a),Term::Bool(y,b))=>{
|
||||||
|
let (truth,code)=match *op {
|
||||||
|
"且"=>(x&&y,format!("({a} ∧ {b})")),
|
||||||
|
"或"=>(x||y,format!("({a} ∨ {b})")),
|
||||||
|
"="=>(x==y,format!("({a} ↔ {b})")),
|
||||||
|
"≠"=>(x!=y,format!("(¬ ({a} ↔ {b}))")),
|
||||||
|
_=>return None
|
||||||
|
};
|
||||||
|
Some(Term::Bool(truth,code))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn instantiate(semantic:&SemanticProject,call:&BoundCall,premise:&str)->Option<Goal>{
|
||||||
|
let owner=semantic.artifacts.iter().find(|a|
|
||||||
|
a.symbol_id.as_ref()==Some(&call.target))?;
|
||||||
|
let signature=owner.signature.as_ref()?;
|
||||||
|
if signature.params.len()!=call.args.len(){return None}
|
||||||
|
// No implicit defaults, no mixed positional/named ambiguity. Explicitly
|
||||||
|
// require that the exact ordered actuals match the callee signature.
|
||||||
|
let mut bindings=BTreeMap::new();
|
||||||
|
for (formal,actual) in signature.params.iter().zip(call.args.iter()){
|
||||||
|
if actual.name.as_ref().is_some_and(|name|name!=&formal.name){
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
bindings.insert(formal.name.clone(),actual.integer?);
|
||||||
|
}
|
||||||
|
let tokens=proof_check::tokenize_claim(premise).ok()?;
|
||||||
|
let (_,expr)=proof_check::parse_claim_expr(&tokens).ok()?;
|
||||||
|
match calc(&expr,&bindings)? {
|
||||||
|
Term::Bool(holds,proposition)=>Some(Goal{holds,proposition}),
|
||||||
|
Term::Int(..)=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn emit_lean(goals:&[(String,Goal)])->String{
|
||||||
|
let mut out=String::from(
|
||||||
|
"-- Generated closed obligations. These are not accepted until Lean checks them.\n");
|
||||||
|
out.push_str("namespace MarqdoClosedCallsite\n");
|
||||||
|
for (i,(_,goal)) in goals.iter().enumerate(){
|
||||||
|
out.push_str(&format!(
|
||||||
|
"theorem vc_{i} : {} := by decide\n",goal.proposition));
|
||||||
|
}
|
||||||
|
out.push_str("end MarqdoClosedCallsite\n");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn bool_and_arithmetic_propositions_are_kernel_goals_not_certs(){
|
||||||
|
let ast=proof_check::parse_claim_expr(
|
||||||
|
&proof_check::tokenize_claim("金额 > 0 且 金额 < 10").unwrap()).unwrap().1;
|
||||||
|
let args=BTreeMap::from([("金额".into(),3)]);
|
||||||
|
let Term::Bool(holds,prop)=calc(&ast,&args).unwrap() else {panic!("not boolean")};
|
||||||
|
assert!(holds);
|
||||||
|
assert!(prop.contains("∧")&&prop.contains("(3 : Int)"));
|
||||||
|
let lean=emit_lean(&[("test".into(),Goal{proposition:prop,holds})]);
|
||||||
|
assert!(lean.contains("theorem vc_0"));
|
||||||
|
assert!(!lean.contains("sorry"));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn real_project_call_actuals_generate_closed_goal_without_claiming_proof(){
|
||||||
|
let root=std::env::temp_dir().join(
|
||||||
|
format!("marqdo-closed-vc-{}",std::process::id()));
|
||||||
|
let _=std::fs::remove_dir_all(&root);
|
||||||
|
std::fs::create_dir_all(&root).unwrap();
|
||||||
|
std::fs::write(root.join("math.mq.md"),
|
||||||
|
"# math\n\n## exact\n+ `n`\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| c | 结果 = 2 | n > 0 | auto |\n\n*2*\n").unwrap();
|
||||||
|
std::fs::write(root.join("main.mq.md"),
|
||||||
|
"---\nimport:\n math: math.mq.md\n---\n# main\n\n## f\n\n**v = [调用](math.math.exact(3))**\n*v*\n").unwrap();
|
||||||
|
let compiled=crate::sema::ir::compile_project(
|
||||||
|
&crate::sema::ir::CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let call=compiled.semantics.bound_calls.iter().find(
|
||||||
|
|c|c.call_site=="math.math.exact").expect("real imported bound call");
|
||||||
|
assert_eq!(call.args.len(),1);
|
||||||
|
assert_eq!(call.args[0].integer,Some(3));
|
||||||
|
let goal=instantiate(&compiled.semantics,call,"n > 0").unwrap();
|
||||||
|
assert!(goal.holds);
|
||||||
|
assert!(goal.proposition.contains("(3 : Int)"));
|
||||||
|
assert!(instantiate(&compiled.semantics,call,"n > 10")
|
||||||
|
.is_some_and(|goal|!goal.holds));
|
||||||
|
std::fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overflowing_i64_expression_is_not_silently_lean_unbounded(){
|
||||||
|
let ast=proof_check::parse_claim_expr(
|
||||||
|
&proof_check::tokenize_claim("x + 1 > 0").unwrap()).unwrap().1;
|
||||||
|
assert!(calc(&ast,&BTreeMap::from([("x".into(),i64::MAX)])).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
+170
@@ -609,6 +609,29 @@ enum ProveAction {
|
|||||||
enum KnowledgeAction {
|
enum KnowledgeAction {
|
||||||
/// Compile L0–L4 projections (default)
|
/// Compile L0–L4 projections (default)
|
||||||
Compile,
|
Compile,
|
||||||
|
/// Inspect verified theorem receipts and inter-module proof obligations.
|
||||||
|
ProofDeps {
|
||||||
|
/// Fail if the receipt/contract graph contains unresolved obligations.
|
||||||
|
#[arg(long)]
|
||||||
|
strict: bool,
|
||||||
|
/// Actually discharge closed callsite preconditions in Lean; without
|
||||||
|
/// this switch the command only emits pending proof obligations.
|
||||||
|
#[arg(long)]
|
||||||
|
verify: bool,
|
||||||
|
},
|
||||||
|
/// Emit independent Lean callee+caller proofs for restricted pure forwarders.
|
||||||
|
/// Unsupported constructs are rejected and never receive certificates.
|
||||||
|
Compose {
|
||||||
|
/// Exit nonzero if any call is unsupported or Lean rejects it.
|
||||||
|
#[arg(long)]
|
||||||
|
strict: bool,
|
||||||
|
},
|
||||||
|
/// Independently replay a previously issued composition certificate
|
||||||
|
/// against current source, Lean modules and toolchain.
|
||||||
|
Replay {
|
||||||
|
#[arg(value_name = "CERTIFICATE")]
|
||||||
|
certificate: PathBuf,
|
||||||
|
},
|
||||||
/// Inspect stable project symbols by exact URI or display name
|
/// Inspect stable project symbols by exact URI or display name
|
||||||
Inspect {
|
Inspect {
|
||||||
/// Symbol URI (`mq://…`) or declaration name
|
/// Symbol URI (`mq://…`) or declaration name
|
||||||
@@ -1769,6 +1792,153 @@ fn try_main(cli: Cli) -> Result<i32> {
|
|||||||
write_knowledge(KnowledgeOptions { path, out_dir: out })?;
|
write_knowledge(KnowledgeOptions { path, out_dir: out })?;
|
||||||
Ok(0)
|
Ok(0)
|
||||||
}
|
}
|
||||||
|
KnowledgeAction::Replay { certificate } => {
|
||||||
|
let root=if path.is_file(){
|
||||||
|
path.parent().filter(|p|!p.as_os_str().is_empty())
|
||||||
|
.unwrap_or_else(||std::path::Path::new(".")).to_path_buf()
|
||||||
|
}else{path.clone()};
|
||||||
|
let compiled=marqdo::sema::ir::compile_project(
|
||||||
|
&marqdo::sema::ir::CompileOptions{
|
||||||
|
project_root:root,
|
||||||
|
entry:path.is_file().then_some(path),
|
||||||
|
lock_mode:marqdo::sema::ir::LockMode::Off
|
||||||
|
})?;
|
||||||
|
let lean=marqdo::prove::driver::Toolchain::discover(None)?
|
||||||
|
.ok_or_else(||anyhow::anyhow!("proof.compose_lean_missing"))?;
|
||||||
|
let proof=marqdo::knowledge::composition::replay(
|
||||||
|
&compiled,&certificate,&lean)?;
|
||||||
|
if json{println!("{proof}");}else{
|
||||||
|
println!("{}",serde_json::to_string_pretty(&proof)?);
|
||||||
|
}
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
KnowledgeAction::Compose { strict } => {
|
||||||
|
let root=if path.is_file(){
|
||||||
|
path.parent().filter(|p|!p.as_os_str().is_empty())
|
||||||
|
.unwrap_or_else(||std::path::Path::new(".")).to_path_buf()
|
||||||
|
}else{path.clone()};
|
||||||
|
let compiled=marqdo::sema::ir::compile_project(
|
||||||
|
&marqdo::sema::ir::CompileOptions{
|
||||||
|
project_root:root,
|
||||||
|
entry:path.is_file().then_some(path),
|
||||||
|
lock_mode:marqdo::sema::ir::LockMode::Off
|
||||||
|
})?;
|
||||||
|
let lean=marqdo::prove::driver::Toolchain::discover(None)?
|
||||||
|
.ok_or_else(||anyhow::anyhow!(
|
||||||
|
"proof.compose_lean_missing: Lean required"))?;
|
||||||
|
let result=marqdo::knowledge::composition::prove(
|
||||||
|
&compiled,&out.join("modular"),&lean)?;
|
||||||
|
let failures=result["results"].as_array().map_or(true,|entries|
|
||||||
|
entries.is_empty()||entries.iter().any(|e|
|
||||||
|
e["status"]!="lean_kernel_proved_model"));
|
||||||
|
if json {println!("{result}");} else {
|
||||||
|
println!("{}",serde_json::to_string_pretty(&result)?);
|
||||||
|
}
|
||||||
|
Ok(if strict && failures {2} else {0})
|
||||||
|
}
|
||||||
|
KnowledgeAction::ProofDeps { strict,verify } => {
|
||||||
|
let semantic_root=if path.is_file() {
|
||||||
|
path.parent().filter(|p|!p.as_os_str().is_empty())
|
||||||
|
.unwrap_or_else(||std::path::Path::new(".")).to_path_buf()
|
||||||
|
} else {path.clone()};
|
||||||
|
let compiled=marqdo::sema::ir::compile_project(
|
||||||
|
&marqdo::sema::ir::CompileOptions {
|
||||||
|
project_root:semantic_root,
|
||||||
|
entry:path.is_file().then_some(path),
|
||||||
|
lock_mode:marqdo::sema::ir::LockMode::Off,
|
||||||
|
})?;
|
||||||
|
let mut receipts=marqdo::knowledge::proof::index_links(
|
||||||
|
&out.join("prove"),&compiled.semantics);
|
||||||
|
let toolchain=if verify {
|
||||||
|
Some(marqdo::prove::driver::Toolchain::discover(None)?
|
||||||
|
.ok_or_else(||anyhow::anyhow!(
|
||||||
|
"proof.modular_lean_missing: Lean is required for --verify"))?)
|
||||||
|
} else {None};
|
||||||
|
if let Some(lean)=toolchain.as_ref(){
|
||||||
|
marqdo::knowledge::proof::replay_index(
|
||||||
|
&out.join("prove"),&mut receipts,lean,
|
||||||
|
std::time::Duration::from_secs(120))?;
|
||||||
|
}
|
||||||
|
let replayed=receipts["claims"].as_array().map_or(0,|records|
|
||||||
|
records.iter().filter(|c|c["kernel_replayed"]==true).count());
|
||||||
|
let draft=marqdo::knowledge::modular::analyze(
|
||||||
|
&compiled.semantics,&receipts);
|
||||||
|
let mut accepted=std::collections::BTreeSet::new();
|
||||||
|
let verified_toolchain=toolchain.as_ref().map(|t|t.version.clone());
|
||||||
|
if verify {
|
||||||
|
let goals:Vec<(String,marqdo::knowledge::vc::Goal)>=draft["obligations"]
|
||||||
|
.as_array().into_iter().flat_map(|rows|rows.iter())
|
||||||
|
.flat_map(|row|row["contracts"].as_array().into_iter()
|
||||||
|
.flat_map(|contracts|contracts.iter()))
|
||||||
|
.filter_map(|c|{
|
||||||
|
if c["callee_certificate_valid"]!=true
|
||||||
|
|| c["closed_host_check"]!=true {return None}
|
||||||
|
Some((
|
||||||
|
c["precondition_goal_key"].as_str()?.to_string(),
|
||||||
|
marqdo::knowledge::vc::Goal{
|
||||||
|
holds:true,
|
||||||
|
proposition:c["lean_proposition"].as_str()?.to_string()
|
||||||
|
}
|
||||||
|
))
|
||||||
|
}).collect();
|
||||||
|
if !goals.is_empty(){
|
||||||
|
let toolchain=toolchain.as_ref().expect("verify implies Lean");
|
||||||
|
let target=out.join("modular");
|
||||||
|
std::fs::create_dir_all(&target)?;
|
||||||
|
let lean_file=target.join("closed-goals.lean");
|
||||||
|
let content=marqdo::knowledge::vc::emit_lean(&goals);
|
||||||
|
std::fs::write(&lean_file,content)?;
|
||||||
|
marqdo::prove::driver::check_closed_goals(
|
||||||
|
&toolchain,&lean_file,std::time::Duration::from_secs(120))?;
|
||||||
|
accepted.extend(goals.into_iter().map(|(id,_)|id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut symbolic_checked=0usize;
|
||||||
|
if let Some(lean)=toolchain.as_ref(){
|
||||||
|
let symbolic:Vec<(String,marqdo::knowledge::symbolic::SymbolicGoal)>=
|
||||||
|
compiled.semantics.bound_calls.iter().flat_map(|call|{
|
||||||
|
compiled.semantics.claims.iter()
|
||||||
|
.filter(|c|c.owner==call.target)
|
||||||
|
.filter(|c|receipts["claims"].as_array().is_some_and(|rows|
|
||||||
|
rows.iter().any(|r|
|
||||||
|
r["claim_anchor_id"]==c.anchor_id
|
||||||
|
&& r["status"]=="proved"
|
||||||
|
&& r["usable"]==true)))
|
||||||
|
.filter_map(|c|Some((
|
||||||
|
c.anchor_id.clone(),
|
||||||
|
marqdo::knowledge::symbolic::plan(
|
||||||
|
&compiled.semantics,call,c.premise.as_deref()?)?
|
||||||
|
)))
|
||||||
|
.filter(|(_,g)|g.abstract_integer_model_supported)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}).collect();
|
||||||
|
if !symbolic.is_empty(){
|
||||||
|
let target=out.join("modular");
|
||||||
|
std::fs::create_dir_all(&target)?;
|
||||||
|
let path=target.join("symbolic-path-goals.lean");
|
||||||
|
std::fs::write(&path,
|
||||||
|
marqdo::knowledge::symbolic::emit_lean(&symbolic))?;
|
||||||
|
marqdo::prove::driver::check_closed_goals(lean,&path,
|
||||||
|
std::time::Duration::from_secs(120))?;
|
||||||
|
symbolic_checked=symbolic.len();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut report=marqdo::knowledge::modular::analyze_with_verified(
|
||||||
|
&compiled.semantics,&receipts,&accepted);
|
||||||
|
report["symbolic_path_lean_model_proved"]=
|
||||||
|
serde_json::json!(symbolic_checked);
|
||||||
|
report["symbolic_proof_scope"]=
|
||||||
|
serde_json::json!("integer_path_model_not_runtime_equivalence");
|
||||||
|
report["lean_preconditions_verified"]=serde_json::json!(accepted.len());
|
||||||
|
report["lean_toolchain"]=serde_json::json!(verified_toolchain);
|
||||||
|
report["lean_receipts_replayed"]=serde_json::json!(replayed);
|
||||||
|
if json {
|
||||||
|
println!("{report}");
|
||||||
|
} else {
|
||||||
|
println!("{}",serde_json::to_string_pretty(&report)?);
|
||||||
|
}
|
||||||
|
Ok(if strict && report["audit_passes"]!=true {2} else {0})
|
||||||
|
}
|
||||||
KnowledgeAction::Inspect { symbol } => {
|
KnowledgeAction::Inspect { symbol } => {
|
||||||
// A supplied directory is an explicit compilation scope;
|
// A supplied directory is an explicit compilation scope;
|
||||||
// a supplied file inherits the nearest project boundary.
|
// a supplied file inherits the nearest project boundary.
|
||||||
|
|||||||
@@ -320,6 +320,7 @@ impl<'a> Cursor<'a> {
|
|||||||
contract: None,
|
contract: None,
|
||||||
var_contracts: std::collections::HashMap::new(),
|
var_contracts: std::collections::HashMap::new(),
|
||||||
claims: Vec::new(),
|
claims: Vec::new(),
|
||||||
|
assumptions: Vec::new(),
|
||||||
};
|
};
|
||||||
// Prose decls pending promotion (name → optional default text).
|
// Prose decls pending promotion (name → optional default text).
|
||||||
let mut prose_decls: Vec<(String, Option<String>, u32)> = Vec::new();
|
let mut prose_decls: Vec<(String, Option<String>, u32)> = Vec::new();
|
||||||
@@ -2080,6 +2081,14 @@ fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Re
|
|||||||
let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote)
|
let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote)
|
||||||
else {
|
else {
|
||||||
// 非契约形状:先试定理表(ADR 0010),再按普通表保留。
|
// 非契约形状:先试定理表(ADR 0010),再按普通表保留。
|
||||||
|
if let Some(parsed) = crate::contract::parse_assumption_table(pairs, span.line) {
|
||||||
|
if prefix_zone {
|
||||||
|
fun.assumptions.extend(parsed.map_err(|msg|
|
||||||
|
bail_at(None, span, format!("proof.assumption_malformed: {msg}")))?);
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
match crate::contract::parse_claim_table(pairs, span.line) {
|
match crate::contract::parse_claim_table(pairs, span.line) {
|
||||||
// 合法定理表:只在「首个可执行行之前」生效;提取后从 body 移除。
|
// 合法定理表:只在「首个可执行行之前」生效;提取后从 body 移除。
|
||||||
// 其余位置仍是普通表,由 `check --proof` 报 proof.claim_misplaced。
|
// 其余位置仍是普通表,由 `check --proof` 报 proof.claim_misplaced。
|
||||||
@@ -2550,6 +2559,31 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::ast::Stmt;
|
use crate::ast::Stmt;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assumption_tables_are_metadata_and_never_runtime_steps() {
|
||||||
|
let src=r#"# main
|
||||||
|
|
||||||
|
## guarded
|
||||||
|
|
||||||
|
| 假设 | 前置 | 后置 |
|
||||||
|
|---|---|---|
|
||||||
|
| backend.fetch | 金额 > 0 | 返回.ok = True |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 安全 | 长度(轨迹) = 0 | | auto |
|
||||||
|
|
||||||
|
*1*
|
||||||
|
"#;
|
||||||
|
let m=parse_source(src).unwrap();
|
||||||
|
let f=&m.functions[0].children[0];
|
||||||
|
assert_eq!(f.assumptions.len(),1);
|
||||||
|
assert_eq!(f.assumptions[0].op,"backend.fetch");
|
||||||
|
assert_eq!(f.assumptions[0].premise.as_deref(),Some("金额 > 0"));
|
||||||
|
assert_eq!(f.claims.len(),1);
|
||||||
|
assert_eq!(f.body.len(),1,"assumption and theorem tables must not execute");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_formula_meta_var_standalone() {
|
fn parse_formula_meta_var_standalone() {
|
||||||
let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n";
|
let src = "# main\n\n$$\n% marqdo: var=f\nx^2 - 2\n$$\n";
|
||||||
|
|||||||
@@ -57,6 +57,11 @@ pub struct NarrativeLink {
|
|||||||
/// Classify a link target without parsing it as an expression.
|
/// Classify a link target without parsing it as an expression.
|
||||||
pub fn classify_narrative_target(target: &str) -> NarrativeLinkKind {
|
pub fn classify_narrative_target(target: &str) -> NarrativeLinkKind {
|
||||||
let t = target.trim();
|
let t = target.trim();
|
||||||
|
// Compiler-owned mq:// anchor addresses are inert knowledge references,
|
||||||
|
// never external URLs or auto-executable code.
|
||||||
|
if t.starts_with("mq://") && (t.contains("#anchor-") || t.contains("#claim-")) {
|
||||||
|
return NarrativeLinkKind::Narrate;
|
||||||
|
}
|
||||||
if t.starts_with("http://")
|
if t.starts_with("http://")
|
||||||
|| t.starts_with("https://")
|
|| t.starts_with("https://")
|
||||||
|| t.starts_with("mailto:")
|
|| t.starts_with("mailto:")
|
||||||
|
|||||||
@@ -121,6 +121,41 @@ pub fn ensure_library(cache_root: &Path, lean: &Toolchain) -> Result<(PathBuf, S
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 判定一个生成的 Lean 模块。
|
/// 判定一个生成的 Lean 模块。
|
||||||
|
/// Compile a self-contained Lean module for a reusable, independent caller
|
||||||
|
/// proof. Source and output must both be inside the immutable build directory.
|
||||||
|
pub fn compile_import_module(lean:&Toolchain,src:&Path,olean:&Path,
|
||||||
|
import_root:&Path,timeout:Duration)->Result<()> {
|
||||||
|
let original=std::fs::read(src)?;
|
||||||
|
let mut command=Command::new(&lean.lean);
|
||||||
|
command.env("LEAN_PATH",import_root)
|
||||||
|
.arg("-o").arg(olean).arg(src);
|
||||||
|
let (log,status,timed_out)=run_with_timeout(&mut command,timeout)?;
|
||||||
|
anyhow::ensure!(!timed_out,"proof.compose_timeout: {}",src.display());
|
||||||
|
anyhow::ensure!(status==Some(0)&&olean.is_file(),
|
||||||
|
"proof.compose_lean_failed: {log}");
|
||||||
|
anyhow::ensure!(std::fs::read(src)?==original,
|
||||||
|
"proof.compose_source_race: generated Lean changed during verification");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-check a generated, closed proof-obligation module with the Lean kernel.
|
||||||
|
/// No local JSON certificate or Rust-side decision may replace this check.
|
||||||
|
pub fn check_closed_goals(
|
||||||
|
toolchain:&Toolchain, source:&Path, timeout:Duration
|
||||||
|
)->Result<()>{
|
||||||
|
let source_before=std::fs::read(source)?;
|
||||||
|
let mut command=Command::new(&toolchain.lean);
|
||||||
|
command.arg(source);
|
||||||
|
let (log,code,timed_out)=run_with_timeout(&mut command,timeout)?;
|
||||||
|
anyhow::ensure!(std::fs::read(source)?==source_before,
|
||||||
|
"proof.modular_source_race: Lean goal module changed during verification");
|
||||||
|
anyhow::ensure!(!timed_out,
|
||||||
|
"proof.modular_timeout: Lean did not finish within {}s",timeout.as_secs());
|
||||||
|
anyhow::ensure!(code==Some(0),
|
||||||
|
"proof.modular_unproved: Lean rejected callsite goals: {log}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn check_module(
|
pub fn check_module(
|
||||||
lean: &Toolchain,
|
lean: &Toolchain,
|
||||||
lib_dir: &Path,
|
lib_dir: &Path,
|
||||||
|
|||||||
@@ -139,6 +139,7 @@ fn emit_theorems(out: &mut String, fun: &FnPlan) {
|
|||||||
out,
|
out,
|
||||||
" all_goals
|
" all_goals
|
||||||
simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqEq]
|
simp_all [mqTruth, Op.name, mqAccess, mqResultOk, mqResultError, mqValueOr, mqAnd, mqOr, mqNot, mqEq]
|
||||||
|
try simp_all [mqAdd, mqSub, mqMul, mqNeg]
|
||||||
try
|
try
|
||||||
first
|
first
|
||||||
| exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim
|
| exact (mqGt_mqLe_false ‹mqGt _ (Val.int _) = true› ‹mqLe _ (Val.int _) = true›).elim
|
||||||
|
|||||||
+108
-2
@@ -13,7 +13,7 @@ use anyhow::Result;
|
|||||||
use crate::ast::{self, Arg, BinaryOp, CallExpr, Expr, Function, Module, Stmt};
|
use crate::ast::{self, Arg, BinaryOp, CallExpr, Expr, Function, Module, Stmt};
|
||||||
use crate::diagnostics::{Diagnostic, Severity, Span};
|
use crate::diagnostics::{Diagnostic, Severity, Span};
|
||||||
use crate::prove::ir::{
|
use crate::prove::ir::{
|
||||||
BinOp, ClaimPlan, Expr as IrExpr, FnPlan, InterpPart, OpDecl, ParamPlan, Plan, PlanTy,
|
AssumptionPlan, BinOp, ClaimPlan, Expr as IrExpr, FnPlan, InterpPart, OpDecl, ParamPlan, Plan, PlanTy,
|
||||||
PureExpr, Step, UnOp, SCHEMA,
|
PureExpr, Step, UnOp, SCHEMA,
|
||||||
};
|
};
|
||||||
use crate::sema::bind::{call_display, resolve_for_exec};
|
use crate::sema::bind::{call_display, resolve_for_exec};
|
||||||
@@ -148,7 +148,10 @@ impl<'m> Lowerer<'m> {
|
|||||||
line: c.line,
|
line: c.line,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
assumptions: Vec::new(),
|
assumptions: fun.assumptions.iter().map(|a|AssumptionPlan{
|
||||||
|
op:a.op.clone(), premise:a.premise.clone(),
|
||||||
|
postcondition:a.postcondition.clone()
|
||||||
|
}).collect(),
|
||||||
};
|
};
|
||||||
Lowered {
|
Lowered {
|
||||||
display: display.to_string(),
|
display: display.to_string(),
|
||||||
@@ -599,6 +602,21 @@ impl<'m> Lowerer<'m> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Target::Import { bind, lib, fun: target, .. } => {
|
Target::Import { bind, lib, fun: target, .. } => {
|
||||||
|
// Source-level verification of a tightly restricted imported
|
||||||
|
// pure leaf: one return expression, only literal/parameter
|
||||||
|
// arithmetic, exact positional args. This is NOT abstract
|
||||||
|
// contract reuse; Lean verifies the actual substituted body.
|
||||||
|
if body.inline_depth < 4
|
||||||
|
&& imported_pure_leaf(target)
|
||||||
|
&& imported_leaf_arithmetic_safe(target,call)
|
||||||
|
&& call.args.len()==target.params.len()
|
||||||
|
&& call.args.iter().all(|a|matches!(a,Arg::Positional(_)))
|
||||||
|
{
|
||||||
|
body.inline_depth+=1;
|
||||||
|
let lowered=self.inline_body(target,&args,body);
|
||||||
|
body.inline_depth-=1;
|
||||||
|
return lowered;
|
||||||
|
}
|
||||||
// lib/result 的构造器内联为结构(§4.5;真实库名是 ok/error/value_or)。
|
// lib/result 的构造器内联为结构(§4.5;真实库名是 ok/error/value_or)。
|
||||||
if bind == "result" && matches!(target.name.as_str(), "ok" | "error" | "value_or") {
|
if bind == "result" && matches!(target.name.as_str(), "ok" | "error" | "value_or") {
|
||||||
return IrExpr::Pure(PureExpr::Ctor {
|
return IrExpr::Pure(PureExpr::Ctor {
|
||||||
@@ -906,6 +924,94 @@ fn effect_label_of_host(host: HostFn) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Imported source transparency is enabled only for a pure expression
|
||||||
|
/// fragment that cannot inspect module globals or call external operations.
|
||||||
|
fn imported_pure_leaf(fun:&Function)->bool {
|
||||||
|
fn closed(expr:&Expr,params:&std::collections::BTreeSet<&str>)->bool {
|
||||||
|
match expr {
|
||||||
|
Expr::Literal(_)=>true,
|
||||||
|
Expr::Var(v)=>params.contains(v.as_str()),
|
||||||
|
Expr::Occluded {payload:Some(inner),..}=>closed(inner,params),
|
||||||
|
Expr::Unary {expr,..}=>closed(expr,params),
|
||||||
|
Expr::Binary {left,right,..}=>closed(left,params)&&closed(right,params),
|
||||||
|
_=>false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fun.is_object() || fun.body.len()!=1{return false}
|
||||||
|
let params:std::collections::BTreeSet<&str>=fun.params.iter()
|
||||||
|
.map(|p|p.name.as_str()).collect();
|
||||||
|
match &fun.body[0]{
|
||||||
|
Stmt::Return {value,..}=>closed(value,¶ms),
|
||||||
|
_=>false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The interpreter uses bounded i64 while Lean's arithmetic is unbounded.
|
||||||
|
/// Therefore imported source expansion of arithmetic is allowed only if all
|
||||||
|
/// arithmetic subexpressions close to checked i64 constants after applying
|
||||||
|
/// the *actual* call arguments. Unknown/overflow/div-zero stays opaque.
|
||||||
|
fn imported_leaf_arithmetic_safe(target:&Function, call:&CallExpr)->bool {
|
||||||
|
let Some(Stmt::Return {value,..})=target.body.first() else {return false};
|
||||||
|
if target.params.len()!=call.args.len(){return false}
|
||||||
|
let bindings:Vec<(&str,&Expr)>=target.params.iter().zip(call.args.iter())
|
||||||
|
.filter_map(|(p,a)|match a {
|
||||||
|
Arg::Positional(expr)=>Some((p.name.as_str(),expr)),
|
||||||
|
_=>None
|
||||||
|
}).collect();
|
||||||
|
if bindings.len()!=call.args.len(){return false}
|
||||||
|
fn int_value(expr:&Expr,bindings:&[(&str,&Expr)],depth:usize)->Option<i64>{
|
||||||
|
if depth>24 {return None}
|
||||||
|
match expr{
|
||||||
|
Expr::Literal(ast::Literal::Int(n))=>Some(*n),
|
||||||
|
Expr::Var(v)=> {
|
||||||
|
let bound=bindings.iter().find(|(key,_)|*key==v.as_str())?.1;
|
||||||
|
// A bound argument must be self-contained to avoid recursion
|
||||||
|
int_value(bound,&[],depth+1)
|
||||||
|
}
|
||||||
|
Expr::Occluded {payload:Some(inner),..}=>
|
||||||
|
int_value(inner,bindings,depth+1),
|
||||||
|
Expr::Unary {op:ast::UnaryOp::Neg,expr}=>
|
||||||
|
int_value(expr,bindings,depth+1)?.checked_neg(),
|
||||||
|
Expr::Binary {op,left,right}=>{
|
||||||
|
let x=int_value(left,bindings,depth+1)?;
|
||||||
|
let y=int_value(right,bindings,depth+1)?;
|
||||||
|
match op{
|
||||||
|
BinaryOp::Add=>x.checked_add(y),
|
||||||
|
BinaryOp::Sub=>x.checked_sub(y),
|
||||||
|
BinaryOp::Mul=>x.checked_mul(y),
|
||||||
|
// Division semantics (integer rounding/Num coercion)
|
||||||
|
// require a differential proof before source transparency.
|
||||||
|
BinaryOp::Div=>None,
|
||||||
|
_=>None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_=>None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn safe(expr:&Expr,bindings:&[(&str,&Expr)])->bool{
|
||||||
|
match expr{
|
||||||
|
Expr::Literal(_)=>true,
|
||||||
|
Expr::Var(v)=>bindings.iter().any(|(key,_)|*key==v.as_str()),
|
||||||
|
Expr::Occluded{payload:Some(inner),..}=>safe(inner,bindings),
|
||||||
|
Expr::Unary {op,expr}=>match op {
|
||||||
|
ast::UnaryOp::Neg=>int_value(
|
||||||
|
&Expr::Unary{op:*op,expr:expr.clone()},bindings,0).is_some(),
|
||||||
|
ast::UnaryOp::Not=>safe(expr,bindings),
|
||||||
|
},
|
||||||
|
Expr::Binary {op,left,right}=>{
|
||||||
|
match op {
|
||||||
|
BinaryOp::Add|BinaryOp::Sub|BinaryOp::Mul|BinaryOp::Div=>
|
||||||
|
int_value(expr,bindings,0).is_some(),
|
||||||
|
_=>safe(left,bindings)&&safe(right,bindings),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_=>false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
safe(value,&bindings)
|
||||||
|
&& bindings.iter().all(|(_,argument)|safe(argument,&[]))
|
||||||
|
}
|
||||||
|
|
||||||
/// 无 sema 效应表时的库函数效应回退(与 sema 的 imported_effects 同思路的保守版)。
|
/// 无 sema 效应表时的库函数效应回退(与 sema 的 imported_effects 同思路的保守版)。
|
||||||
fn imported_effect_label(lib: &Module, fun: &Function) -> String {
|
fn imported_effect_label(lib: &Module, fun: &Function) -> String {
|
||||||
let mut visiting = std::collections::HashSet::new();
|
let mut visiting = std::collections::HashSet::new();
|
||||||
|
|||||||
+11
-2
@@ -434,7 +434,7 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Report {
|
let report = Report {
|
||||||
file: file_display,
|
file: file_display,
|
||||||
source_sha256,
|
source_sha256,
|
||||||
artifact_id: artifact_dir
|
artifact_id: artifact_dir
|
||||||
@@ -447,7 +447,16 @@ pub fn prove_path(path: &Path, opts: &ProveOptions) -> Result<Report> {
|
|||||||
emitted,
|
emitted,
|
||||||
lean: lean_info,
|
lean: lean_info,
|
||||||
duration_ms: started.elapsed().as_millis(),
|
duration_ms: started.elapsed().as_millis(),
|
||||||
})
|
};
|
||||||
|
// Knowledge linkage is advisory. Failing to bind must not invent a proof
|
||||||
|
// or change the judgment of the underlying v2.8.0 prover.
|
||||||
|
#[cfg(feature = "cli")]
|
||||||
|
if let Some(dir) = artifact_dir.as_deref() {
|
||||||
|
if let Err(err) = crate::knowledge::proof::emit_links(path, &report, dir) {
|
||||||
|
eprintln!("warning[knowledge.proof_linkage]: {err:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(report)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 离线判定(§5):checked/反例贴回定理,绝不冒充 proved。
|
/// 离线判定(§5):checked/反例贴回定理,绝不冒充 proved。
|
||||||
|
|||||||
@@ -170,6 +170,16 @@ fn check_misplaced_and_malformed(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if let Some(assumption)=contract::parse_assumption_table(pairs,span.line){
|
||||||
|
let (code,msg)=match assumption {
|
||||||
|
Ok(_)=>("proof.assumption_misplaced",
|
||||||
|
"假设表必须在第一条可执行语句之前;此处不会自动生效".to_string()),
|
||||||
|
Err(err)=>("proof.assumption_malformed",err)
|
||||||
|
};
|
||||||
|
out.push(proof_diag(module,path,span,code,msg,
|
||||||
|
"移动并修正 | 假设 | 前置 | 后置 | 表到函数开头".into()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
match contract::parse_claim_table(pairs, span.line) {
|
match contract::parse_claim_table(pairs, span.line) {
|
||||||
Some(Ok(_rows)) => {
|
Some(Ok(_rows)) => {
|
||||||
// 合法定理形却还在 body:一定是位置不对(prefix zone 内会被提取)。
|
// 合法定理形却还在 body:一定是位置不对(prefix zone 内会被提取)。
|
||||||
|
|||||||
+550
-7
@@ -183,6 +183,14 @@ pub struct SemanticArtifact {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct KnowledgeRef {
|
pub struct KnowledgeRef {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
|
/// Stable public address of the marked step, absent for ambiguous labels.
|
||||||
|
pub anchor_id: Option<String>,
|
||||||
|
/// Original Markdown target when this reference occurs in prose.
|
||||||
|
pub link_target: Option<String>,
|
||||||
|
/// Resolved stable anchor target; never an executable call.
|
||||||
|
pub target_anchor: Option<String>,
|
||||||
|
/// Reference to a theorem declaration, not a proof certificate.
|
||||||
|
pub target_claim: Option<String>,
|
||||||
pub label: String,
|
pub label: String,
|
||||||
pub context: String,
|
pub context: String,
|
||||||
pub source: SourceLocation,
|
pub source: SourceLocation,
|
||||||
@@ -190,9 +198,36 @@ pub struct KnowledgeRef {
|
|||||||
pub target: Option<SymbolId>,
|
pub target: Option<SymbolId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Stable identity and unproved declaration of a v2.8.0 function theorem.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct KnowledgeClaim {
|
||||||
|
pub anchor_id: String,
|
||||||
|
pub owner: SymbolId,
|
||||||
|
pub label: String,
|
||||||
|
pub conclusion: String,
|
||||||
|
pub premise: Option<String>,
|
||||||
|
pub line: u32,
|
||||||
|
pub source: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Declared operation assumption, not an accepted proof or runtime binding.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct KnowledgeAssumption {
|
||||||
|
pub id: String,
|
||||||
|
pub owner: SymbolId,
|
||||||
|
pub operation: String,
|
||||||
|
pub premise: Option<String>,
|
||||||
|
pub postcondition: String,
|
||||||
|
pub source: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct KnowledgeStep {
|
pub struct KnowledgeStep {
|
||||||
pub id: ArtifactId,
|
pub id: ArtifactId,
|
||||||
|
/// Stable public anchor; legacy #step-N is kept as an internal step identity.
|
||||||
|
pub anchor_id: Option<String>,
|
||||||
|
/// Hash of the authored source line (or fallback label when line unavailable).
|
||||||
|
pub definition_digest: Digest,
|
||||||
pub reference: String,
|
pub reference: String,
|
||||||
pub kind: String,
|
pub kind: String,
|
||||||
pub calls: Vec<SymbolId>,
|
pub calls: Vec<SymbolId>,
|
||||||
@@ -200,12 +235,73 @@ pub struct KnowledgeStep {
|
|||||||
pub source: SourceLocation,
|
pub source: SourceLocation,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fully static i64 call-site argument. Non-constant expressions are kept
|
||||||
|
/// as unresolved proof obligations rather than guessed values.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct StaticCallArg {
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub integer: Option<i64>,
|
||||||
|
pub expression_digest: Digest,
|
||||||
|
/// Only a direct identifier; arbitrary expressions do not become symbolic identities.
|
||||||
|
pub symbol: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn checked_constant_int(expr: &Expr, depth: usize) -> Option<i64> {
|
||||||
|
if depth > 32 { return None; }
|
||||||
|
match expr {
|
||||||
|
Expr::Literal(crate::ast::Literal::Int(n)) => Some(*n),
|
||||||
|
Expr::Occluded { payload: Some(inner), .. } =>
|
||||||
|
checked_constant_int(inner, depth+1),
|
||||||
|
Expr::Unary {op: crate::ast::UnaryOp::Neg, expr} =>
|
||||||
|
checked_constant_int(expr,depth+1)?.checked_neg(),
|
||||||
|
Expr::Binary {op,left,right} => {
|
||||||
|
let a=checked_constant_int(left,depth+1)?;
|
||||||
|
let b=checked_constant_int(right,depth+1)?;
|
||||||
|
match op {
|
||||||
|
crate::ast::BinaryOp::Add=>a.checked_add(b),
|
||||||
|
crate::ast::BinaryOp::Sub=>a.checked_sub(b),
|
||||||
|
crate::ast::BinaryOp::Mul=>a.checked_mul(b),
|
||||||
|
// Division and its rounding/coercion are not yet proven
|
||||||
|
// equivalent to the Lean abstract numeric model.
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn static_call_args(call:&CallExpr)->Vec<StaticCallArg>{
|
||||||
|
// The exact same alias/modifier expansion used by runtime resolution
|
||||||
|
// must determine the proof's argument list. An invalid normalization
|
||||||
|
// must never yield a recoverable proof argument.
|
||||||
|
let Ok(normalized)=call.for_evaluation() else {return Vec::new()};
|
||||||
|
normalized.args.iter().map(|a|{
|
||||||
|
let (name,expr)=match a {
|
||||||
|
crate::ast::Arg::Positional(expr)=>(None,expr),
|
||||||
|
crate::ast::Arg::Named{name,value}=>(Some(name.clone()),value)
|
||||||
|
};
|
||||||
|
StaticCallArg {
|
||||||
|
name, integer:checked_constant_int(expr,0),
|
||||||
|
expression_digest:digest(format!("{expr:?}")),
|
||||||
|
symbol:match expr {Expr::Var(v)=>Some(v.clone()),_=>None}
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// Static call site bound to a SymbolId (G02).
|
/// Static call site bound to a SymbolId (G02).
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct BoundCall {
|
pub struct BoundCall {
|
||||||
|
/// Exact owning function symbol at the AST callsite.
|
||||||
|
pub caller: SymbolId,
|
||||||
pub target: SymbolId,
|
pub target: SymbolId,
|
||||||
pub call_site: String,
|
pub call_site: String,
|
||||||
pub source: SourceLocation,
|
pub source: SourceLocation,
|
||||||
|
/// Exact, ordered actual arguments with conservative closed-int decoding.
|
||||||
|
pub args: Vec<StaticCallArg>,
|
||||||
|
/// Guard predicates are source-derived and never independently trusted.
|
||||||
|
pub path_guards: Vec<String>,
|
||||||
|
/// Loop, unknown guard, etc: no modular proof may pass this callsite.
|
||||||
|
pub control_blocker: Option<String>,
|
||||||
pub required_effects: EffectSet,
|
pub required_effects: EffectSet,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,6 +321,8 @@ pub struct SemanticProject {
|
|||||||
pub artifacts: Vec<SemanticArtifact>,
|
pub artifacts: Vec<SemanticArtifact>,
|
||||||
pub refs: Vec<KnowledgeRef>,
|
pub refs: Vec<KnowledgeRef>,
|
||||||
pub steps: Vec<KnowledgeStep>,
|
pub steps: Vec<KnowledgeStep>,
|
||||||
|
pub claims: Vec<KnowledgeClaim>,
|
||||||
|
pub assumptions: Vec<KnowledgeAssumption>,
|
||||||
pub bound_calls: Vec<BoundCall>,
|
pub bound_calls: Vec<BoundCall>,
|
||||||
pub dynamic_calls: Vec<DynamicCall>,
|
pub dynamic_calls: Vec<DynamicCall>,
|
||||||
}
|
}
|
||||||
@@ -275,6 +373,8 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
let mut artifacts = Vec::new();
|
let mut artifacts = Vec::new();
|
||||||
let mut refs = Vec::new();
|
let mut refs = Vec::new();
|
||||||
let mut steps = Vec::new();
|
let mut steps = Vec::new();
|
||||||
|
let mut claims = Vec::new();
|
||||||
|
let mut assumptions = Vec::new();
|
||||||
let mut bound_calls = Vec::new();
|
let mut bound_calls = Vec::new();
|
||||||
let mut dynamic_calls = Vec::new();
|
let mut dynamic_calls = Vec::new();
|
||||||
let mut local_by_name: BTreeMap<(ModuleId, String), SymbolId> = BTreeMap::new();
|
let mut local_by_name: BTreeMap<(ModuleId, String), SymbolId> = BTreeMap::new();
|
||||||
@@ -291,6 +391,53 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
let module_symbols = index.symbols_in_module(module_id);
|
let module_symbols = index.symbols_in_module(module_id);
|
||||||
for symbol in index.symbols_in_module(module_id) {
|
for symbol in index.symbols_in_module(module_id) {
|
||||||
let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module");
|
let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module");
|
||||||
|
let mut claim_counts=BTreeMap::new();
|
||||||
|
for claim in &function.claims {
|
||||||
|
*claim_counts.entry(claim.id.as_str()).or_insert(0usize)+=1;
|
||||||
|
}
|
||||||
|
for claim in &function.claims {
|
||||||
|
if claim_counts.get(claim.id.as_str())!=Some(&1) {
|
||||||
|
diagnostics.push(Diagnostic::new(Some(path.as_path()),
|
||||||
|
Span::new(claim.line,1),
|
||||||
|
format!("ambiguous theorem declaration: {}",claim.id))
|
||||||
|
.with_code("knowledge.claim_duplicate")
|
||||||
|
.with_severity(Severity::Warning));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
claims.push(KnowledgeClaim {
|
||||||
|
anchor_id: format!("{}#claim-{}",symbol.id.as_str(),
|
||||||
|
digest(claim.id.as_bytes()).0.trim_start_matches("sha256:")),
|
||||||
|
owner:symbol.id.clone(),
|
||||||
|
label:claim.id.clone(),
|
||||||
|
conclusion:claim.conclusion.clone(),
|
||||||
|
premise:claim.premise.clone(),
|
||||||
|
line:claim.line,
|
||||||
|
source:source_location(index.root().path(),path,claim.line,claim.line),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut assumption_counts=BTreeMap::new();
|
||||||
|
for assumption in &function.assumptions {
|
||||||
|
*assumption_counts.entry(assumption.op.as_str()).or_insert(0usize)+=1;
|
||||||
|
}
|
||||||
|
for assumption in &function.assumptions {
|
||||||
|
if assumption_counts.get(assumption.op.as_str())!=Some(&1) {
|
||||||
|
diagnostics.push(Diagnostic::new(Some(path.as_path()),
|
||||||
|
Span::new(assumption.line,1),
|
||||||
|
format!("ambiguous assumption operation: {}",assumption.op))
|
||||||
|
.with_code("proof.assumption_duplicate")
|
||||||
|
.with_severity(Severity::Warning));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assumptions.push(KnowledgeAssumption{
|
||||||
|
id:format!("{}#assumption-{}",symbol.id.as_str(),
|
||||||
|
digest(assumption.op.as_bytes()).0.trim_start_matches("sha256:")),
|
||||||
|
owner:symbol.id.clone(),
|
||||||
|
operation:assumption.op.clone(),
|
||||||
|
premise:assumption.premise.clone(),
|
||||||
|
postcondition:assumption.postcondition.clone(),
|
||||||
|
source:source_location(index.root().path(),path,assumption.line,assumption.line)
|
||||||
|
});
|
||||||
|
}
|
||||||
let owned_links: Vec<_> = narrative_links
|
let owned_links: Vec<_> = narrative_links
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|link| enclosing_symbol(&module_symbols, link.line).is_some_and(|s| s.id == symbol.id))
|
.filter(|link| enclosing_symbol(&module_symbols, link.line).is_some_and(|s| s.id == symbol.id))
|
||||||
@@ -304,6 +451,7 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
path,
|
path,
|
||||||
function,
|
function,
|
||||||
symbol,
|
symbol,
|
||||||
|
text,
|
||||||
&local_by_name,
|
&local_by_name,
|
||||||
&owned_links,
|
&owned_links,
|
||||||
&module_prov,
|
&module_prov,
|
||||||
@@ -323,6 +471,20 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
close_effect_dependencies(&mut artifacts);
|
close_effect_dependencies(&mut artifacts);
|
||||||
|
resolve_anchor_references(&mut refs, &claims);
|
||||||
|
for reference in refs.iter().filter(|r|
|
||||||
|
r.resolution=="unresolved_anchor" || r.resolution=="ambiguous_anchor") {
|
||||||
|
let source_path=root.path().join(&reference.source.file);
|
||||||
|
diagnostics.push(Diagnostic::new(
|
||||||
|
Some(source_path.as_path()),
|
||||||
|
Span::new(reference.source.line, 1),
|
||||||
|
format!("knowledge target cannot be uniquely resolved: {}",
|
||||||
|
reference.link_target.as_deref().unwrap_or("<missing>")))
|
||||||
|
.with_code(if reference.resolution=="ambiguous_anchor" {
|
||||||
|
"knowledge.anchor_ambiguous"
|
||||||
|
} else {"knowledge.anchor_unresolved"})
|
||||||
|
.with_severity(Severity::Warning));
|
||||||
|
}
|
||||||
let resolved_effects: BTreeMap<_,_> = artifacts.iter()
|
let resolved_effects: BTreeMap<_,_> = artifacts.iter()
|
||||||
.map(|artifact|(artifact.artifact_id.clone(),artifact.effects.clone())).collect();
|
.map(|artifact|(artifact.artifact_id.clone(),artifact.effects.clone())).collect();
|
||||||
for bound in &mut bound_calls {
|
for bound in &mut bound_calls {
|
||||||
@@ -345,6 +507,8 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0));
|
artifacts.sort_by(|a, b| a.artifact_id.0.cmp(&b.artifact_id.0));
|
||||||
refs.sort_by(|a, b| a.id.cmp(&b.id));
|
refs.sort_by(|a, b| a.id.cmp(&b.id));
|
||||||
steps.sort_by(|a, b| a.id.0.cmp(&b.id.0));
|
steps.sort_by(|a, b| a.id.0.cmp(&b.id.0));
|
||||||
|
claims.sort_by(|a,b| a.anchor_id.cmp(&b.anchor_id));
|
||||||
|
assumptions.sort_by(|a,b|a.id.cmp(&b.id));
|
||||||
bound_calls.sort_by(|a, b| {
|
bound_calls.sort_by(|a, b| {
|
||||||
a.source
|
a.source
|
||||||
.file
|
.file
|
||||||
@@ -368,6 +532,8 @@ fn compile_index(index: ProjectIndex) -> Result<Compilation> {
|
|||||||
artifacts,
|
artifacts,
|
||||||
refs,
|
refs,
|
||||||
steps,
|
steps,
|
||||||
|
claims,
|
||||||
|
assumptions,
|
||||||
bound_calls,
|
bound_calls,
|
||||||
dynamic_calls,
|
dynamic_calls,
|
||||||
},
|
},
|
||||||
@@ -514,6 +680,168 @@ fn resolve_narrative_target(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The label is a human-facing name, not an execution permission.
|
||||||
|
fn normalize_anchor_label(label: &str) -> String {
|
||||||
|
label.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn public_anchor(owner: &SymbolId, label: &str, counts: &BTreeMap<String, usize>) -> Option<String> {
|
||||||
|
let normalized = normalize_anchor_label(label);
|
||||||
|
if normalized.is_empty() || counts.get(&normalized) != Some(&1) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Full SHA-256 avoids truncation collisions; unrelated step insertions
|
||||||
|
// do not change the address, while changing the label intentionally does.
|
||||||
|
Some(format!("{}#anchor-{}", owner.as_str(), digest(normalized.as_bytes()).0.trim_start_matches("sha256:")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn anchor_definition_digest(source: &str, line: u32, label: &str, kind: &str) -> Digest {
|
||||||
|
let body = if line > 0 { source.lines().nth(line as usize - 1) } else { None };
|
||||||
|
digest(format!("{kind}\0{label}\0{}", body.unwrap_or("<unknown-source-line>")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicit knowledge references are inert: resolving a link never invokes a
|
||||||
|
/// function. Short #@label binds ONLY inside the current function. Full
|
||||||
|
/// mq://...#anchor-<sha256> targets support cross-module references.
|
||||||
|
fn resolve_anchor_references(refs: &mut [KnowledgeRef], claims: &[KnowledgeClaim]) {
|
||||||
|
let declared: BTreeSet<String> = refs.iter()
|
||||||
|
.filter_map(|r| r.anchor_id.clone()).collect();
|
||||||
|
let theorem_ids: BTreeSet<String> = claims.iter().map(|c|c.anchor_id.clone()).collect();
|
||||||
|
for reference in refs {
|
||||||
|
let Some(raw) = reference.link_target.as_deref() else {continue};
|
||||||
|
let sought = if let Some(label) = raw.trim().strip_prefix("#@") {
|
||||||
|
let Some(owner) = reference.id.split("#ref-").next() else {continue};
|
||||||
|
if label.is_empty() {continue}
|
||||||
|
Some((format!("{}#anchor-{}", owner,
|
||||||
|
digest(normalize_anchor_label(label).as_bytes()).0.trim_start_matches("sha256:")),
|
||||||
|
format!("{}#claim-{}", owner,
|
||||||
|
digest(label.as_bytes()).0.trim_start_matches("sha256:"))))
|
||||||
|
} else if raw.starts_with("mq://")
|
||||||
|
&& (raw.contains("#anchor-") || raw.contains("#claim-")) {
|
||||||
|
Some((raw.trim().to_string(), raw.trim().to_string()))
|
||||||
|
} else { None };
|
||||||
|
if let Some((anchor, claim)) = sought {
|
||||||
|
let step_match=declared.contains(&anchor);
|
||||||
|
let theorem_match=theorem_ids.contains(&claim);
|
||||||
|
match (step_match,theorem_match) {
|
||||||
|
(true,false)=>{
|
||||||
|
reference.target_anchor=Some(anchor);
|
||||||
|
reference.resolution="anchor".into();
|
||||||
|
}
|
||||||
|
(false,true)=>{
|
||||||
|
reference.target_claim=Some(claim);
|
||||||
|
reference.resolution="claim".into();
|
||||||
|
}
|
||||||
|
(true,true)=>reference.resolution="ambiguous_anchor".into(),
|
||||||
|
_=>reference.resolution="unresolved_anchor".into()
|
||||||
|
}
|
||||||
|
reference.target=None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone,Default)]
|
||||||
|
struct CallsiteControl {
|
||||||
|
guards: Vec<String>,
|
||||||
|
blocker: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only side-effect-free boolean and integer-comparison guards are projected.
|
||||||
|
/// Unknown guards and any loops remain explicit unresolved obligations.
|
||||||
|
fn guard_text(expr:&Expr)->Option<String>{
|
||||||
|
match expr {
|
||||||
|
Expr::Var(v)=>Some(v.clone()),
|
||||||
|
Expr::Literal(crate::ast::Literal::Int(n))=>Some(n.to_string()),
|
||||||
|
Expr::Literal(crate::ast::Literal::Bool(v))=>Some(
|
||||||
|
if *v {"真"}else{"假"}.into()),
|
||||||
|
Expr::Occluded {payload:Some(e),..}=>guard_text(e),
|
||||||
|
Expr::Unary {op:crate::ast::UnaryOp::Not,expr}=>
|
||||||
|
Some(format!("非 ({})",guard_text(expr)?)),
|
||||||
|
Expr::Unary {op:crate::ast::UnaryOp::Neg,expr}=>
|
||||||
|
Some(format!("-({})",guard_text(expr)?)),
|
||||||
|
Expr::Binary {op,left,right}=>{
|
||||||
|
let symbol=match op {
|
||||||
|
crate::ast::BinaryOp::Eq=>"=",
|
||||||
|
crate::ast::BinaryOp::Ne=>"≠",
|
||||||
|
crate::ast::BinaryOp::Lt=>"<",
|
||||||
|
crate::ast::BinaryOp::Le=>"≤",
|
||||||
|
crate::ast::BinaryOp::Gt=>">",
|
||||||
|
crate::ast::BinaryOp::Ge=>"≥",
|
||||||
|
crate::ast::BinaryOp::And=>"且",
|
||||||
|
crate::ast::BinaryOp::Or=>"或",
|
||||||
|
// Preserve source arithmetic in *guard obligations* only.
|
||||||
|
// This does not certify i64 overflow or dynamic Number
|
||||||
|
// behavior; the symbolic Lean Int backend checks linearity.
|
||||||
|
crate::ast::BinaryOp::Add=>"+",
|
||||||
|
crate::ast::BinaryOp::Sub=>"-",
|
||||||
|
crate::ast::BinaryOp::Mul=>"*",
|
||||||
|
_=>return None
|
||||||
|
};
|
||||||
|
Some(format!("({} {} {})",
|
||||||
|
guard_text(left)?,symbol,guard_text(right)?))
|
||||||
|
},
|
||||||
|
_=>None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn callsite_control(fun:&Function)->BTreeMap<u32,CallsiteControl>{
|
||||||
|
fn walk(items:&[Stmt],conditions:&[String],block:Option<String>,
|
||||||
|
output:&mut BTreeMap<u32,CallsiteControl>){
|
||||||
|
for stmt in items{
|
||||||
|
match stmt {
|
||||||
|
Stmt::Branch{arms,span}=>{
|
||||||
|
// Calls within branch test expressions require separate
|
||||||
|
// evaluation-order reasoning and must not borrow arm facts.
|
||||||
|
output.entry(span.line).or_insert_with(||CallsiteControl{
|
||||||
|
guards:conditions.to_vec(),
|
||||||
|
blocker:Some("call_in_condition_not_modeled".into())
|
||||||
|
});
|
||||||
|
let mut negated=Vec::new();
|
||||||
|
let mut prior_unknown_condition=false;
|
||||||
|
for arm in arms{
|
||||||
|
let mut path=conditions.to_vec();
|
||||||
|
path.extend(negated.iter().cloned());
|
||||||
|
// A previous unmodelled if/elif test also controls the
|
||||||
|
// reachability of all later arms, including else.
|
||||||
|
let mut arm_block=if prior_unknown_condition {
|
||||||
|
Some("prior_non_pure_branch_guard".into())
|
||||||
|
} else {block.clone()};
|
||||||
|
if let Some(cond)=&arm.condition{
|
||||||
|
match guard_text(cond){
|
||||||
|
Some(guard)=>{
|
||||||
|
path.push(guard.clone());
|
||||||
|
negated.push(format!("非 ({guard})"));
|
||||||
|
},
|
||||||
|
None=>{
|
||||||
|
arm_block=Some("non_pure_branch_guard".into());
|
||||||
|
prior_unknown_condition=true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(&arm.body,&path,arm_block,output);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Stmt::While{body,span,..}|Stmt::ForEach{body,span,..}=>{
|
||||||
|
output.insert(span.line,CallsiteControl{
|
||||||
|
guards:conditions.to_vec(),
|
||||||
|
blocker:Some("loop_or_iterator_requires_invariant".into())
|
||||||
|
});
|
||||||
|
walk(body,conditions,
|
||||||
|
Some("loop_or_iterator_requires_invariant".into()),output);
|
||||||
|
},
|
||||||
|
_=>{
|
||||||
|
let line=crate::ast::stmt_line(stmt);
|
||||||
|
output.insert(line,CallsiteControl{
|
||||||
|
guards:conditions.to_vec(),blocker:block.clone()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut found=BTreeMap::new();
|
||||||
|
walk(&fun.body,&[],None,&mut found);
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
fn artifact_for_function(
|
fn artifact_for_function(
|
||||||
index: &ProjectIndex,
|
index: &ProjectIndex,
|
||||||
module_id: &ModuleId,
|
module_id: &ModuleId,
|
||||||
@@ -521,6 +849,7 @@ fn artifact_for_function(
|
|||||||
path: &Path,
|
path: &Path,
|
||||||
function: &Function,
|
function: &Function,
|
||||||
symbol: &SymbolDecl,
|
symbol: &SymbolDecl,
|
||||||
|
source_text: &str,
|
||||||
local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
|
local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
|
||||||
narrative_links: &[crate::parse::NarrativeLink],
|
narrative_links: &[crate::parse::NarrativeLink],
|
||||||
module_prov: &super::provenance::ModuleProvenance,
|
module_prov: &super::provenance::ModuleProvenance,
|
||||||
@@ -533,6 +862,7 @@ fn artifact_for_function(
|
|||||||
Vec<super::provenance::ProvenanceDiag>,
|
Vec<super::provenance::ProvenanceDiag>,
|
||||||
) {
|
) {
|
||||||
let calls = collect_call_sites(function);
|
let calls = collect_call_sites(function);
|
||||||
|
let controls=callsite_control(function);
|
||||||
let mut effects = direct_effects(index, ast_module, function, &calls);
|
let mut effects = direct_effects(index, ast_module, function, &calls);
|
||||||
let mut dependencies = Vec::new();
|
let mut dependencies = Vec::new();
|
||||||
let mut bound_calls = Vec::new();
|
let mut bound_calls = Vec::new();
|
||||||
@@ -543,9 +873,13 @@ fn artifact_for_function(
|
|||||||
CallClass::Bound { target, effects: call_effects } => {
|
CallClass::Bound { target, effects: call_effects } => {
|
||||||
dependencies.push(ArtifactId(target.as_str().to_string()));
|
dependencies.push(ArtifactId(target.as_str().to_string()));
|
||||||
bound_calls.push(BoundCall {
|
bound_calls.push(BoundCall {
|
||||||
|
caller:symbol.id.clone(),
|
||||||
target,
|
target,
|
||||||
call_site: call_display(call),
|
call_site: call_display(call),
|
||||||
source,
|
source,
|
||||||
|
args:static_call_args(call),
|
||||||
|
path_guards:controls.get(line).map(|c|c.guards.clone()).unwrap_or_default(),
|
||||||
|
control_blocker:controls.get(line).and_then(|c|c.blocker.clone()),
|
||||||
required_effects: call_effects,
|
required_effects: call_effects,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -560,6 +894,12 @@ fn artifact_for_function(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let named = collect_named_steps(function);
|
let named = collect_named_steps(function);
|
||||||
|
// Only a unique author-visible label in this function receives a public
|
||||||
|
// address. Duplicate names are deliberately not resolved by source order.
|
||||||
|
let mut label_counts = BTreeMap::new();
|
||||||
|
for site in &named {
|
||||||
|
*label_counts.entry(normalize_anchor_label(&site.label)).or_insert(0usize) += 1;
|
||||||
|
}
|
||||||
let mut refs = Vec::new();
|
let mut refs = Vec::new();
|
||||||
let mut steps = Vec::new();
|
let mut steps = Vec::new();
|
||||||
let mut step_n = 0u32;
|
let mut step_n = 0u32;
|
||||||
@@ -572,7 +912,13 @@ fn artifact_for_function(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
|
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
|
||||||
|
let anchor = public_anchor(&symbol.id, &named.label, &label_counts);
|
||||||
|
let definition_digest = anchor_definition_digest(source_text, named.line, &named.label, &named.kind);
|
||||||
refs.push(KnowledgeRef {
|
refs.push(KnowledgeRef {
|
||||||
|
anchor_id: anchor.clone(),
|
||||||
|
link_target: None,
|
||||||
|
target_anchor: None,
|
||||||
|
target_claim: None,
|
||||||
id: ref_id.clone(),
|
id: ref_id.clone(),
|
||||||
label: named.label.clone(),
|
label: named.label.clone(),
|
||||||
context: named.context.clone(),
|
context: named.context.clone(),
|
||||||
@@ -589,6 +935,8 @@ fn artifact_for_function(
|
|||||||
}
|
}
|
||||||
steps.push(KnowledgeStep {
|
steps.push(KnowledgeStep {
|
||||||
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
|
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
|
||||||
|
anchor_id: anchor,
|
||||||
|
definition_digest,
|
||||||
reference: ref_id,
|
reference: ref_id,
|
||||||
kind: named.kind.clone(),
|
kind: named.kind.clone(),
|
||||||
calls: target.into_iter().collect(),
|
calls: target.into_iter().collect(),
|
||||||
@@ -606,7 +954,13 @@ fn artifact_for_function(
|
|||||||
crate::parse::NarrativeLinkKind::Navigation => None,
|
crate::parse::NarrativeLinkKind::Navigation => None,
|
||||||
};
|
};
|
||||||
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
|
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
|
||||||
|
// A narrative link is a reference, not a definition. It never creates
|
||||||
|
// a public executable anchor of its own.
|
||||||
refs.push(KnowledgeRef {
|
refs.push(KnowledgeRef {
|
||||||
|
anchor_id: None,
|
||||||
|
link_target: Some(link.target.clone()),
|
||||||
|
target_anchor: None,
|
||||||
|
target_claim: None,
|
||||||
id: ref_id.clone(),
|
id: ref_id.clone(),
|
||||||
label: link.label.clone(),
|
label: link.label.clone(),
|
||||||
context: "narrative".into(),
|
context: "narrative".into(),
|
||||||
@@ -620,6 +974,8 @@ fn artifact_for_function(
|
|||||||
});
|
});
|
||||||
steps.push(KnowledgeStep {
|
steps.push(KnowledgeStep {
|
||||||
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
|
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
|
||||||
|
anchor_id: None,
|
||||||
|
definition_digest: anchor_definition_digest(source_text, link.line, &link.label, link.kind.as_str()),
|
||||||
reference: ref_id,
|
reference: ref_id,
|
||||||
kind: link.kind.as_str().into(),
|
kind: link.kind.as_str().into(),
|
||||||
calls: target.into_iter().collect(),
|
calls: target.into_iter().collect(),
|
||||||
@@ -763,10 +1119,14 @@ fn classify_call(
|
|||||||
}) else {
|
}) else {
|
||||||
return CallClass::Other;
|
return CallClass::Other;
|
||||||
};
|
};
|
||||||
let decl = if path.len() >= 2 {
|
// Resolve the *declaration* path in the imported module, not
|
||||||
path[1..].to_vec()
|
// the syntactic call path: `rates.lookup()` may refer to a
|
||||||
} else if let Some(d) = declaration_path_of(lib, fun) {
|
// nested `# rates / ## lookup` function. Losing the parent
|
||||||
|
// would silently break transitive proof invalidation.
|
||||||
|
let decl = if let Some(d) = declaration_path_of(lib, fun) {
|
||||||
d
|
d
|
||||||
|
} else if path.len() >= 2 {
|
||||||
|
path[1..].to_vec()
|
||||||
} else {
|
} else {
|
||||||
return CallClass::Other;
|
return CallClass::Other;
|
||||||
};
|
};
|
||||||
@@ -1315,6 +1675,8 @@ impl SemanticProject {
|
|||||||
"artifacts": self.artifacts.iter().map(artifact_json).collect::<Vec<_>>(),
|
"artifacts": self.artifacts.iter().map(artifact_json).collect::<Vec<_>>(),
|
||||||
"refs": self.refs.iter().map(ref_json).collect::<Vec<_>>(),
|
"refs": self.refs.iter().map(ref_json).collect::<Vec<_>>(),
|
||||||
"steps": self.steps.iter().map(step_json).collect::<Vec<_>>(),
|
"steps": self.steps.iter().map(step_json).collect::<Vec<_>>(),
|
||||||
|
"claims": self.claims.iter().map(claim_json).collect::<Vec<_>>(),
|
||||||
|
"assumptions": self.assumptions.iter().map(assumption_json).collect::<Vec<_>>(),
|
||||||
"bound_calls": self.bound_calls.iter().map(bound_call_json).collect::<Vec<_>>(),
|
"bound_calls": self.bound_calls.iter().map(bound_call_json).collect::<Vec<_>>(),
|
||||||
"dynamic_calls": self.dynamic_calls.iter().map(dynamic_call_json).collect::<Vec<_>>(),
|
"dynamic_calls": self.dynamic_calls.iter().map(dynamic_call_json).collect::<Vec<_>>(),
|
||||||
})
|
})
|
||||||
@@ -1324,12 +1686,31 @@ impl SemanticProject {
|
|||||||
pub fn artifact_json(artifact: &SemanticArtifact) -> Value {
|
pub fn artifact_json(artifact: &SemanticArtifact) -> Value {
|
||||||
json!({"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(SymbolId::as_str), "display_name": artifact.display_name, "kind": artifact.kind, "callable": artifact.callable, "source": {"file": artifact.source.file, "line": artifact.source.line, "end_line": artifact.source.end_line}, "signature": artifact.signature.as_ref().map(|s| json!({"receiver":s.receiver,"params":s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d|&d.0),"unit":p.unit})).collect::<Vec<_>>(),"returns":s.returns,"effects":s.effects.values()})), "contract":{"params":artifact.contract.params,"returns":artifact.contract.returns,"fields":artifact.contract.fields}, "effects":artifact.effects.values(), "dependencies":artifact.dependencies.iter().map(|d|&d.0).collect::<Vec<_>>(), "provenance":artifact.provenance.iter().map(|p|json!({"uri":p.uri,"locator":p.locator,"content_digest":p.content_digest.as_ref().map(|d|&d.0),"relation":p.relation})).collect::<Vec<_>>(), "applicability":artifact.applicability, "hashes":{"interface":artifact.hashes.interface.0,"implementation":artifact.hashes.implementation.0,"evidence":artifact.hashes.evidence.0,"artifact":artifact.hashes.artifact.0,"closure":artifact.hashes.closure.0}, "verification":{"parse":artifact.verification.parse,"resolve":artifact.verification.resolve,"contract":artifact.verification.contract,"execution":artifact.verification.execution,"tests":artifact.verification.tests,"evidence":artifact.verification.evidence,"domain":artifact.verification.domain,"methods":artifact.verification.methods}, "lifecycle":artifact.lifecycle})
|
json!({"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id.0, "symbol_id": artifact.symbol_id.as_ref().map(SymbolId::as_str), "display_name": artifact.display_name, "kind": artifact.kind, "callable": artifact.callable, "source": {"file": artifact.source.file, "line": artifact.source.line, "end_line": artifact.source.end_line}, "signature": artifact.signature.as_ref().map(|s| json!({"receiver":s.receiver,"params":s.params.iter().map(|p|json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d|&d.0),"unit":p.unit})).collect::<Vec<_>>(),"returns":s.returns,"effects":s.effects.values()})), "contract":{"params":artifact.contract.params,"returns":artifact.contract.returns,"fields":artifact.contract.fields}, "effects":artifact.effects.values(), "dependencies":artifact.dependencies.iter().map(|d|&d.0).collect::<Vec<_>>(), "provenance":artifact.provenance.iter().map(|p|json!({"uri":p.uri,"locator":p.locator,"content_digest":p.content_digest.as_ref().map(|d|&d.0),"relation":p.relation})).collect::<Vec<_>>(), "applicability":artifact.applicability, "hashes":{"interface":artifact.hashes.interface.0,"implementation":artifact.hashes.implementation.0,"evidence":artifact.hashes.evidence.0,"artifact":artifact.hashes.artifact.0,"closure":artifact.hashes.closure.0}, "verification":{"parse":artifact.verification.parse,"resolve":artifact.verification.resolve,"contract":artifact.verification.contract,"execution":artifact.verification.execution,"tests":artifact.verification.tests,"evidence":artifact.verification.evidence,"domain":artifact.verification.domain,"methods":artifact.verification.methods}, "lifecycle":artifact.lifecycle})
|
||||||
}
|
}
|
||||||
fn ref_json(reference: &KnowledgeRef) -> Value { json!({"id":reference.id,"label":reference.label,"context":reference.context,"source":{"file":reference.source.file,"line":reference.source.line,"end_line":reference.source.end_line},"resolution":reference.resolution,"target":reference.target.as_ref().map(SymbolId::as_str)}) }
|
fn ref_json(reference: &KnowledgeRef) -> Value { json!({"id":reference.id,"anchor_id":reference.anchor_id,"link_target":reference.link_target,"target_anchor":reference.target_anchor,"target_claim":reference.target_claim,"label":reference.label,"context":reference.context,"source":{"file":reference.source.file,"line":reference.source.line,"end_line":reference.source.end_line},"resolution":reference.resolution,"target":reference.target.as_ref().map(SymbolId::as_str)}) }
|
||||||
fn step_json(step: &KnowledgeStep) -> Value { json!({"id":step.id.0,"reference":step.reference,"kind":step.kind,"calls":step.calls.iter().map(SymbolId::as_str).collect::<Vec<_>>(),"effects":step.effects.values(),"source":{"file":step.source.file,"line":step.source.line,"end_line":step.source.end_line}}) }
|
fn assumption_json(a:&KnowledgeAssumption)->Value{
|
||||||
|
json!({"id":a.id,"owner":a.owner.as_str(),"operation":a.operation,
|
||||||
|
"premise":a.premise,"postcondition":a.postcondition,
|
||||||
|
"verification":"declared_not_proved",
|
||||||
|
"source":{"file":a.source.file,"line":a.source.line}})
|
||||||
|
}
|
||||||
|
fn claim_json(claim: &KnowledgeClaim) -> Value {
|
||||||
|
json!({"anchor_id":claim.anchor_id,"owner":claim.owner.as_str(),
|
||||||
|
"label":claim.label,"conclusion":claim.conclusion,"premise":claim.premise,
|
||||||
|
"verification":"declared_unverified",
|
||||||
|
"source":{"file":claim.source.file,"line":claim.line}})
|
||||||
|
}
|
||||||
|
fn step_json(step: &KnowledgeStep) -> Value { json!({"id":step.id.0,"anchor_id":step.anchor_id,"definition_digest":step.definition_digest.0,"reference":step.reference,"kind":step.kind,"calls":step.calls.iter().map(SymbolId::as_str).collect::<Vec<_>>(),"effects":step.effects.values(),"source":{"file":step.source.file,"line":step.source.line,"end_line":step.source.end_line}}) }
|
||||||
fn bound_call_json(call: &BoundCall) -> Value {
|
fn bound_call_json(call: &BoundCall) -> Value {
|
||||||
json!({
|
json!({
|
||||||
|
"caller":call.caller.as_str(),
|
||||||
"target": call.target.as_str(),
|
"target": call.target.as_str(),
|
||||||
"call_site": call.call_site,
|
"call_site": call.call_site,
|
||||||
|
"args":call.args.iter().map(|a|json!({
|
||||||
|
"name":a.name,"integer":a.integer,"symbol":a.symbol,
|
||||||
|
"expression_digest":a.expression_digest.0
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
"path_guards":call.path_guards,
|
||||||
|
"control_blocker":call.control_blocker,
|
||||||
"source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line},
|
"source": {"file": call.source.file, "line": call.source.line, "end_line": call.source.end_line},
|
||||||
"required_effects": call.required_effects.values(),
|
"required_effects": call.required_effects.values(),
|
||||||
"binding": "BoundCall",
|
"binding": "BoundCall",
|
||||||
@@ -1349,6 +1730,11 @@ const SEMANTIC_NAMES: &[&str] = &[
|
|||||||
"symbols.json",
|
"symbols.json",
|
||||||
"refs.json",
|
"refs.json",
|
||||||
"steps.json",
|
"steps.json",
|
||||||
|
"anchors.json",
|
||||||
|
"claims.json",
|
||||||
|
"assumptions.json",
|
||||||
|
"proof-index.json",
|
||||||
|
"proof-obligations.json",
|
||||||
"bound_calls.json",
|
"bound_calls.json",
|
||||||
"dynamic_calls.json",
|
"dynamic_calls.json",
|
||||||
"artifacts",
|
"artifacts",
|
||||||
@@ -1400,7 +1786,7 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) ->
|
|||||||
fs::create_dir_all(gen_dir.join("artifacts"))?;
|
fs::create_dir_all(gen_dir.join("artifacts"))?;
|
||||||
fs::create_dir_all(gen_dir.join("graph"))?;
|
fs::create_dir_all(gen_dir.join("graph"))?;
|
||||||
fs::create_dir_all(gen_dir.join("verification"))?;
|
fs::create_dir_all(gen_dir.join("verification"))?;
|
||||||
write_generation_tree(&gen_dir, compilation)?;
|
write_generation_tree(&gen_dir, compilation, &out_dir.join("prove"))?;
|
||||||
|
|
||||||
// Publish journal + CAS (M-R6): record expected CURRENT before switching.
|
// Publish journal + CAS (M-R6): record expected CURRENT before switching.
|
||||||
let expected = fs::read_to_string(out_dir.join("CURRENT"))
|
let expected = fs::read_to_string(out_dir.join("CURRENT"))
|
||||||
@@ -1463,7 +1849,7 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) ->
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_generation_tree(stage: &Path, compilation: &Compilation) -> Result<()> {
|
fn write_generation_tree(stage: &Path, compilation: &Compilation, prove_root: &Path) -> Result<()> {
|
||||||
let project = compilation.semantics.to_json();
|
let project = compilation.semantics.to_json();
|
||||||
write_json(
|
write_json(
|
||||||
&stage.join("project.json"),
|
&stage.join("project.json"),
|
||||||
@@ -1477,6 +1863,37 @@ fn write_generation_tree(stage: &Path, compilation: &Compilation) -> Result<()>
|
|||||||
write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::<Vec<_>>() }))?;
|
write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::<Vec<_>>() }))?;
|
||||||
write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?;
|
write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?;
|
||||||
write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?;
|
write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?;
|
||||||
|
write_json(&stage.join("claims.json"), &json!({
|
||||||
|
"schema_version":SCHEMA_VERSION,
|
||||||
|
"role":"theorem_declarations_not_proof_results",
|
||||||
|
"claims":project["claims"]
|
||||||
|
}))?;
|
||||||
|
let proofs=crate::knowledge::proof::index_links(prove_root, &compilation.semantics);
|
||||||
|
write_json(&stage.join("assumptions.json"), &json!({
|
||||||
|
"schema_version":SCHEMA_VERSION,
|
||||||
|
"role":"declared_modular_contracts_require_callsite_proof",
|
||||||
|
"assumptions":project["assumptions"]
|
||||||
|
}))?;
|
||||||
|
write_json(&stage.join("proof-index.json"), &proofs)?;
|
||||||
|
write_json(&stage.join("proof-obligations.json"),
|
||||||
|
&crate::knowledge::modular::analyze(&compilation.semantics, &proofs))?;
|
||||||
|
write_json(&stage.join("anchors.json"), &json!({
|
||||||
|
"schema_version":SCHEMA_VERSION,
|
||||||
|
"role":"stable_public_knowledge_addresses",
|
||||||
|
"anchors": compilation.semantics.steps.iter()
|
||||||
|
.filter(|step| step.anchor_id.is_some())
|
||||||
|
.map(|step| json!({
|
||||||
|
"anchor_id":step.anchor_id,
|
||||||
|
"owner":step.id.0.split('#').next(),
|
||||||
|
"label":compilation.semantics.refs.iter()
|
||||||
|
.find(|r| r.id == step.reference).map(|r| r.label.as_str()),
|
||||||
|
"step_id":step.id.0,
|
||||||
|
"kind":step.kind,
|
||||||
|
"source":step_json(step)["source"],
|
||||||
|
"definition_digest":step.definition_digest.0,
|
||||||
|
"effects":step.effects.values(),
|
||||||
|
})).collect::<Vec<_>>()
|
||||||
|
}))?;
|
||||||
write_json(&stage.join("bound_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"bound_calls":project["bound_calls"]}))?;
|
write_json(&stage.join("bound_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"bound_calls":project["bound_calls"]}))?;
|
||||||
write_json(&stage.join("dynamic_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"dynamic_calls":project["dynamic_calls"]}))?;
|
write_json(&stage.join("dynamic_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"dynamic_calls":project["dynamic_calls"]}))?;
|
||||||
write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?;
|
write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?;
|
||||||
@@ -1490,7 +1907,33 @@ fn write_generation_tree(stage: &Path, compilation: &Compilation) -> Result<()>
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
for assumption in &compilation.semantics.assumptions {
|
||||||
|
edges.push(json!({"from":assumption.owner.as_str(),
|
||||||
|
"to":assumption.id,"kind":"declares_assumption"}));
|
||||||
|
}
|
||||||
|
for claim in &compilation.semantics.claims {
|
||||||
|
edges.push(json!({"from":claim.owner.as_str(),
|
||||||
|
"to":claim.anchor_id,"kind":"declares_claim"}));
|
||||||
|
}
|
||||||
|
for reference in &compilation.semantics.refs {
|
||||||
|
if let Some(claim) = &reference.target_claim {
|
||||||
|
let owner=reference.id.split("#ref-").next().unwrap_or("");
|
||||||
|
edges.push(json!({"from":owner,"to":claim,"kind":"references_claim"}));
|
||||||
|
}
|
||||||
|
if let Some(target) = &reference.target_anchor {
|
||||||
|
let owner = reference.id.split("#ref-").next().unwrap_or("");
|
||||||
|
edges.push(json!({"from":owner,"to":target,"kind":"references_anchor"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
for step in &compilation.semantics.steps {
|
for step in &compilation.semantics.steps {
|
||||||
|
if let Some(anchor) = &step.anchor_id {
|
||||||
|
if let Some(owner) = step.id.0.split('#').next() {
|
||||||
|
edges.push(json!({"from":owner,"to":anchor,"kind":"defines_anchor"}));
|
||||||
|
}
|
||||||
|
for target in &step.calls {
|
||||||
|
edges.push(json!({"from":anchor,"to":target.as_str(),"kind":"calls"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
if step.kind == "narrate" {
|
if step.kind == "narrate" {
|
||||||
for target in &step.calls {
|
for target in &step.calls {
|
||||||
edges.push(json!({
|
edges.push(json!({
|
||||||
@@ -1651,6 +2094,106 @@ import:
|
|||||||
fs::remove_dir_all(root).unwrap();
|
fs::remove_dir_all(root).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn public_anchors_survive_unrelated_insertions_and_track_definition_changes() {
|
||||||
|
let root = root();
|
||||||
|
let file = root.join("main.mq.md");
|
||||||
|
let source = |prefix: &str, amount: i32| format!(
|
||||||
|
"# main\n\n## calculate\n\n{prefix}**x = [计算税额]({amount} * 2)**\n*x*\n"
|
||||||
|
);
|
||||||
|
fs::write(&file, source("", 3)).unwrap();
|
||||||
|
let one = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let anchor1 = one.semantics.steps.iter().find(|s| s.anchor_id.is_some()).unwrap();
|
||||||
|
let identity = anchor1.anchor_id.clone();
|
||||||
|
let digest1 = anchor1.definition_digest.clone();
|
||||||
|
fs::write(&file, source("**other = [准备参数](1)**\n", 3)).unwrap();
|
||||||
|
let two = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let anchor2 = two.semantics.steps.iter()
|
||||||
|
.find(|s| s.anchor_id == identity).unwrap();
|
||||||
|
assert_eq!(anchor1.anchor_id, anchor2.anchor_id);
|
||||||
|
assert_eq!(digest1, anchor2.definition_digest);
|
||||||
|
assert_ne!(anchor1.id, anchor2.id, "legacy ordinal step id may move");
|
||||||
|
fs::write(&file, source("**other = [准备参数](1)**\n", 4)).unwrap();
|
||||||
|
let three = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let anchor3 = three.semantics.steps.iter()
|
||||||
|
.find(|s| s.anchor_id == identity).unwrap();
|
||||||
|
assert_ne!(digest1, anchor3.definition_digest);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markdown_knowledge_links_bind_only_to_registered_anchors() {
|
||||||
|
let root=root();
|
||||||
|
fs::write(root.join("main.mq.md"),
|
||||||
|
"# main\n\n## f\n\n[说明](#@演算)\n[不存在](#@没有)\n**x = [演算](2 * 3)**\n*x*\n"
|
||||||
|
).unwrap();
|
||||||
|
let c=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let target=c.semantics.steps.iter().find_map(|s|s.anchor_id.as_deref()).unwrap();
|
||||||
|
let link=c.semantics.refs.iter().find(|r|r.label=="说明").unwrap();
|
||||||
|
assert_eq!(link.target_anchor.as_deref(),Some(target));
|
||||||
|
assert_eq!(link.resolution,"anchor");
|
||||||
|
assert!(link.target.is_none(),"narrative links must never become executable calls");
|
||||||
|
let bad=c.semantics.refs.iter().find(|r|r.label=="不存在").unwrap();
|
||||||
|
assert_eq!(bad.resolution,"unresolved_anchor");
|
||||||
|
assert!(bad.target_anchor.is_none());
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn canonical_mq_uri_resolves_across_functions_without_calling_knowledge() {
|
||||||
|
let root=root();
|
||||||
|
let src=root.join("main.mq.md");
|
||||||
|
fs::write(&src,"# main\n\n## source\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let initial=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let anchor=initial.semantics.steps.iter().find_map(|s|s.anchor_id.clone()).unwrap();
|
||||||
|
let updated=format!(
|
||||||
|
"# main\n\n## source\n\n**x = [演算](2 * 3)**\n*x*\n\n## consumer\n\n[阅读计算知识]({anchor})\n*None*\n"
|
||||||
|
);
|
||||||
|
fs::write(&src,updated).unwrap();
|
||||||
|
let parsed=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let read=parsed.semantics.refs.iter().find(|r|r.label=="阅读计算知识").unwrap();
|
||||||
|
assert_eq!(read.target_anchor.as_deref(),Some(anchor.as_str()));
|
||||||
|
assert_eq!(read.resolution,"anchor");
|
||||||
|
assert!(read.target.is_none());
|
||||||
|
assert!(parsed.semantics.bound_calls.iter().all(|c|c.call_site!="阅读计算知识"));
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theorem_claims_are_addressable_but_never_implicitly_proved() {
|
||||||
|
let root=root();
|
||||||
|
fs::write(root.join("main.mq.md"),
|
||||||
|
"# main\n\n## f\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| 安全性质 | 长度(轨迹) = 0 | | auto |\n\n[阅读定理](#@安全性质)\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let c=compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
assert_eq!(c.semantics.claims.len(),1);
|
||||||
|
let claim=&c.semantics.claims[0];
|
||||||
|
let link=c.semantics.refs.iter().find(|r|r.label=="阅读定理").unwrap();
|
||||||
|
assert_eq!(link.target_claim.as_deref(),Some(claim.anchor_id.as_str()));
|
||||||
|
assert_eq!(link.resolution,"claim");
|
||||||
|
assert!(link.target.is_none());
|
||||||
|
let serialized=c.semantics.to_json();
|
||||||
|
assert_eq!(serialized["claims"][0]["verification"],"declared_unverified");
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_labels_fail_closed_in_public_anchor_projection() {
|
||||||
|
let root = root();
|
||||||
|
fs::write(root.join("main.mq.md"),
|
||||||
|
"# main\n\n## f\n\n**x = [重复](1)**\n**y = [重复](2)**\n*y*\n").unwrap();
|
||||||
|
let compilation = compile_project(&CompileOptions::for_path(&root).unwrap()).unwrap();
|
||||||
|
let duplicated: Vec<_> = compilation.semantics.refs.iter()
|
||||||
|
.filter(|r| r.label == "重复").collect();
|
||||||
|
assert_eq!(duplicated.len(), 2);
|
||||||
|
assert!(duplicated.iter().all(|r| r.anchor_id.is_none()));
|
||||||
|
let out = root.join(".marqdo");
|
||||||
|
write_semantic_projections(&out, &compilation).unwrap();
|
||||||
|
let anchors: Value = serde_json::from_str(
|
||||||
|
&fs::read_to_string(out.join("anchors.json")).unwrap()).unwrap();
|
||||||
|
assert!(anchors["anchors"].as_array().unwrap().is_empty());
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn named_steps_classify_observe_derive_iterate_call() {
|
fn named_steps_classify_observe_derive_iterate_call() {
|
||||||
let root = root();
|
let root = root();
|
||||||
|
|||||||
@@ -0,0 +1,434 @@
|
|||||||
|
//! Knowledge-anchored proof receipts are a *narrow* verified linkage layer.
|
||||||
|
//! No synthetic test here is evidence that Lean proved a statement.
|
||||||
|
|
||||||
|
use std::{fs, path::PathBuf};
|
||||||
|
use marqdo::knowledge::proof::{link_report, index_links};
|
||||||
|
use marqdo::prove::{ClaimReport, FunctionReport, LeanInfo, Report, Tier, Verdict};
|
||||||
|
use marqdo::sema::ir::{compile_project, CompileOptions};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
fn root(label: &str) -> PathBuf {
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
static SEQ: AtomicU64=AtomicU64::new(0);
|
||||||
|
let dir=std::env::temp_dir().join(format!("mq-proof-links-{}-{}-{}",
|
||||||
|
label,std::process::id(),SEQ.fetch_add(1,Ordering::Relaxed)));
|
||||||
|
fs::create_dir_all(&dir).unwrap();dir
|
||||||
|
}
|
||||||
|
fn sha(bytes:&[u8])->String {format!("{:x}",Sha256::digest(bytes))}
|
||||||
|
fn report(file:&PathBuf, status:Verdict, decided_by:&str, lean:Option<LeanInfo>)->Report {
|
||||||
|
Report {
|
||||||
|
file:"main.mq.md".into(),source_sha256:sha(&fs::read(file).unwrap()),
|
||||||
|
artifact_id:None,status,
|
||||||
|
functions:vec![FunctionReport{
|
||||||
|
name:"main.compute".into(),verdict:status,
|
||||||
|
tier:if lean.is_some(){Tier::Lean}else{Tier::Offline},
|
||||||
|
ops:vec![],rejected:vec![],
|
||||||
|
claims:vec![ClaimReport{
|
||||||
|
id:"rule".into(),premise:None,conclusion:"结果 = 6".into(),
|
||||||
|
tactic:None,status,decided_by:decided_by.into(),
|
||||||
|
source_line:Some(5),evidence:None,
|
||||||
|
}]
|
||||||
|
}],
|
||||||
|
diagnostics:vec![],emitted:vec![],lean,duration_ms:0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn links_bind_to_exact_owner_and_stale_after_source_change() {
|
||||||
|
let dir=root("stale");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let compiled=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let receipt=link_report(&compiled,&file,&report(&file,Verdict::Checked,"trace",None),&dir);
|
||||||
|
assert_eq!(receipt["claims"][0]["status"],"checked");
|
||||||
|
assert_eq!(receipt["claims"][0]["proof_scope"],"function");
|
||||||
|
assert!(receipt["claims"][0]["owner_symbol_id"].as_str().unwrap().len()>10);
|
||||||
|
assert_eq!(receipt["claims"][0]["certificate_digest"],serde_json::Value::Null);
|
||||||
|
assert_eq!(receipt["claims"][0]["related_anchor_ids"].as_array().unwrap().len(),1);
|
||||||
|
let sidecar=dir.join(".marqdo/prove/one");
|
||||||
|
fs::create_dir_all(&sidecar).unwrap();
|
||||||
|
fs::write(sidecar.join("knowledge-links.json"),serde_json::to_vec(&receipt).unwrap()).unwrap();
|
||||||
|
let current=index_links(&dir.join(".marqdo/prove"),&compiled.semantics);
|
||||||
|
assert_eq!(current["claims"][0]["status"],"checked");
|
||||||
|
assert_eq!(current["claims"][0]["usable"],false);
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n**x = [演算](2 * 4)**\n*x*\n").unwrap();
|
||||||
|
let changed=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let stale=index_links(&dir.join(".marqdo/prove"),&changed.semantics);
|
||||||
|
assert_eq!(stale["claims"][0]["status"],"stale");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overflowing_actual_argument_cannot_be_source_inlined_to_lean_int() {
|
||||||
|
let dir=root("overflow-actual-arg");
|
||||||
|
fs::write(dir.join("numbers.mq.md"),r#"# numbers
|
||||||
|
|
||||||
|
## identity
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
*`n`*
|
||||||
|
"#).unwrap();
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,r#"---
|
||||||
|
import:
|
||||||
|
numbers: numbers.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| bad | 结果 = 0 | auto |
|
||||||
|
|
||||||
|
**value = [溢出](numbers.numbers.identity(9223372036854775807 + 1))**
|
||||||
|
*value*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join("prove");
|
||||||
|
let _=marqdo::prove::prove_path(&file,&marqdo::prove::ProveOptions{
|
||||||
|
emit_dir:Some(out.clone()),judge:false,..Default::default()
|
||||||
|
}).unwrap();
|
||||||
|
let plan:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("plan.json")).unwrap()).unwrap();
|
||||||
|
let f=plan["functions"].as_array().unwrap().iter()
|
||||||
|
.find(|x|x["name"]=="main.compute").unwrap();
|
||||||
|
assert!(!f["ops"].as_array().unwrap().is_empty(),
|
||||||
|
"an overflowing actual argument must not be silently turned into Lean Int");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overflowing_imported_arithmetic_cannot_be_source_inlined_to_lean_int() {
|
||||||
|
let dir=root("overflow-import");
|
||||||
|
fs::write(dir.join("numbers.mq.md"),r#"# numbers
|
||||||
|
|
||||||
|
## increment
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
*`n` + 1*
|
||||||
|
"#).unwrap();
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,r#"---
|
||||||
|
import:
|
||||||
|
numbers: numbers.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| bad | 结果 = 0 | auto |
|
||||||
|
|
||||||
|
**value = [溢出](numbers.numbers.increment(9223372036854775807))**
|
||||||
|
*value*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join("prove");
|
||||||
|
let _=marqdo::prove::prove_path(&file,&marqdo::prove::ProveOptions{
|
||||||
|
emit_dir:Some(out.clone()),judge:false,..Default::default()
|
||||||
|
}).unwrap();
|
||||||
|
let plan:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("plan.json")).unwrap()).unwrap();
|
||||||
|
let f=plan["functions"].as_array().unwrap().iter()
|
||||||
|
.find(|x|x["name"]=="main.compute").unwrap();
|
||||||
|
assert!(!f["ops"].as_array().unwrap().is_empty(),
|
||||||
|
"i64 overflow must never silently become total unbounded Lean arithmetic");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effectful_import_stays_opaque_in_proof_plan() {
|
||||||
|
let dir=root("effectful-import");
|
||||||
|
fs::write(dir.join("lib.mq.md"),r#"# external
|
||||||
|
|
||||||
|
## lookup
|
||||||
|
|
||||||
|
> print text="side effect"
|
||||||
|
*2*
|
||||||
|
"#).unwrap();
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,r#"---
|
||||||
|
import:
|
||||||
|
lib: lib.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| invariant | 长度(轨迹) = 0 | auto |
|
||||||
|
|
||||||
|
**value = [读取](lib.external.lookup())**
|
||||||
|
*value*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join("prove");
|
||||||
|
let _=marqdo::prove::prove_path(&file,&marqdo::prove::ProveOptions{
|
||||||
|
emit_dir:Some(out.clone()),judge:false,..Default::default()
|
||||||
|
}).unwrap();
|
||||||
|
let plan:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("plan.json")).unwrap()).unwrap();
|
||||||
|
let f=plan["functions"].as_array().unwrap().iter()
|
||||||
|
.find(|x|x["name"]=="main.compute").unwrap();
|
||||||
|
assert!(!f["ops"].as_array().unwrap().is_empty(),
|
||||||
|
"effectful import must remain an opaque operation and never be source-inlined");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assumption_table_is_in_proof_ir_but_cannot_grant_proved_status() {
|
||||||
|
let dir=root("assumptions");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## call
|
||||||
|
|
||||||
|
| 假设 | 前置 | 后置 |
|
||||||
|
|---|---|---|
|
||||||
|
| provider.lookup | 金额 > 0 | 返回 = 2 |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| no_effect | 长度(轨迹) = 0 | | auto |
|
||||||
|
|
||||||
|
*1*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join("prove");
|
||||||
|
let report=marqdo::prove::prove_path(&file,
|
||||||
|
&marqdo::prove::ProveOptions{
|
||||||
|
emit_dir:Some(out.clone()),judge:false,..Default::default()
|
||||||
|
}).unwrap();
|
||||||
|
let plan:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("plan.json")).unwrap()).unwrap();
|
||||||
|
let f=plan["functions"].as_array().unwrap().iter()
|
||||||
|
.find(|x|x["name"]=="main.call").unwrap();
|
||||||
|
assert_eq!(f["assumptions"][0]["op"],"provider.lookup");
|
||||||
|
assert_eq!(f["assumptions"][0]["premise"],"金额 > 0");
|
||||||
|
assert_ne!(report.status,Verdict::Proved);
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modular_assumption_projection_is_never_self_certifying() {
|
||||||
|
let dir=root("assumption-projection");
|
||||||
|
let src=dir.join("main.mq.md");
|
||||||
|
fs::write(&src,r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 假设 | 前置 | 后置 |
|
||||||
|
|---|---|---|
|
||||||
|
| rates.lookup | 金额 > 0 | 返回 = 2 |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| has_result | 结果 = 2 | | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join(".marqdo");
|
||||||
|
marqdo::knowledge::write_knowledge(marqdo::knowledge::KnowledgeOptions{
|
||||||
|
path:dir.clone(),out_dir:out.clone()
|
||||||
|
}).unwrap();
|
||||||
|
let a:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("assumptions.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(a["assumptions"][0]["operation"],"rates.lookup");
|
||||||
|
assert_eq!(a["assumptions"][0]["verification"],"declared_not_proved");
|
||||||
|
let plan:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("proof-obligations.json")).unwrap()).unwrap();
|
||||||
|
assert_ne!(plan["status"],"proved");
|
||||||
|
assert_eq!(plan["proof_completion"],"not_established_by_dependency_analysis");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strict_modular_cli_exposes_unproved_conditions_as_nonzero_exit() {
|
||||||
|
let dir=root("strict-modular");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| obligation | 结果 = 6 | | auto |\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let output=std::process::Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||||
|
.arg("knowledge").arg("proof-deps")
|
||||||
|
.arg(&dir).arg("--json").arg("--strict")
|
||||||
|
.arg("--out").arg(dir.join(".marqdo"))
|
||||||
|
.output().expect("run knowledge proof-deps");
|
||||||
|
assert_eq!(output.status.code(),Some(2),
|
||||||
|
"unproven claims must fail strict audit: stdout={} stderr={}",
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr));
|
||||||
|
let report:serde_json::Value=serde_json::from_slice(&output.stdout).unwrap();
|
||||||
|
assert_eq!(report["audit_passes"],false);
|
||||||
|
assert_eq!(report["verified_claims"][0]["status"],"unverified");
|
||||||
|
assert_eq!(report["proof_completion"],"not_established_by_dependency_analysis");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn altered_theorem_conclusion_cannot_reuse_a_matching_function_name() {
|
||||||
|
let dir=root("altered-claim");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let c=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let mut fake=report(&file,Verdict::Proved,"lean",None);
|
||||||
|
fake.functions[0].claims[0].conclusion="结果 = 999".into();
|
||||||
|
let linkage=link_report(&c,&file,&fake,&dir);
|
||||||
|
assert!(linkage["claims"].as_array().unwrap().is_empty());
|
||||||
|
assert_eq!(linkage["unresolved"][0]["reason"],"theorem_declaration_missing_or_changed");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dependency_change_invalidates_caller_proof_even_if_caller_source_is_unchanged() {
|
||||||
|
let dir=root("transitive");
|
||||||
|
let lib=dir.join("rates.mq.md");
|
||||||
|
let app=dir.join("main.mq.md");
|
||||||
|
fs::write(&lib,"# rates\n\n## lookup\n\n*2*\n").unwrap();
|
||||||
|
fs::write(&app,r#"---
|
||||||
|
import:
|
||||||
|
rates: rates.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| rule | 结果 = 6 | | auto |
|
||||||
|
|
||||||
|
**tax = [计算税额](rates.rates.lookup())**
|
||||||
|
*tax*
|
||||||
|
"#).unwrap();
|
||||||
|
let before=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let owner=before.semantics.artifacts.iter()
|
||||||
|
.find(|a|a.display_name=="main.compute").unwrap();
|
||||||
|
assert!(!owner.dependencies.is_empty(),
|
||||||
|
"imported call must be a bound dependency; check full class path");
|
||||||
|
let old_closure=owner.hashes.closure.clone();
|
||||||
|
let receipt=link_report(&before,&app,&report(&app,Verdict::Checked,"trace",None),&dir);
|
||||||
|
assert_eq!(receipt["claims"].as_array().unwrap().len(),1,
|
||||||
|
"function identity must resolve exactly");
|
||||||
|
let proof=dir.join(".marqdo/prove/first");
|
||||||
|
fs::create_dir_all(&proof).unwrap();
|
||||||
|
fs::write(proof.join("knowledge-links.json"),
|
||||||
|
serde_json::to_vec(&receipt).unwrap()).unwrap();
|
||||||
|
fs::write(&lib,"# rates\n\n## lookup\n\n*3*\n").unwrap();
|
||||||
|
let after=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let revised=after.semantics.artifacts.iter()
|
||||||
|
.find(|a|a.display_name=="main.compute").unwrap();
|
||||||
|
assert_ne!(old_closure,revised.hashes.closure,
|
||||||
|
"callee implementation changes must invalidate caller closure");
|
||||||
|
let index=index_links(&dir.join(".marqdo/prove"),&after.semantics);
|
||||||
|
assert_eq!(index["claims"][0]["status"],"stale");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn complete_knowledge_publish_contains_anchors_refs_and_proof_receipts() {
|
||||||
|
let dir=root("publish");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n[查看知识](#@演算)\n[查看定理](#@rule)\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let out=dir.join(".marqdo");
|
||||||
|
marqdo::knowledge::write_knowledge(marqdo::knowledge::KnowledgeOptions{
|
||||||
|
path:dir.clone(),out_dir:out.clone()
|
||||||
|
}).unwrap();
|
||||||
|
let anchors:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("anchors.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(anchors["anchors"].as_array().unwrap().len(),1);
|
||||||
|
let refs:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("refs.json")).unwrap()).unwrap();
|
||||||
|
assert!(refs["refs"].as_array().unwrap().iter()
|
||||||
|
.any(|r|r["label"]=="查看知识" && r["resolution"]=="anchor"));
|
||||||
|
let claims:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("claims.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(claims["claims"].as_array().unwrap().len(),1);
|
||||||
|
assert_eq!(claims["claims"][0]["verification"],"declared_unverified");
|
||||||
|
assert!(refs["refs"].as_array().unwrap().iter()
|
||||||
|
.any(|r|r["label"]=="查看定理" && r["resolution"]=="claim"));
|
||||||
|
let index:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("proof-index.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(index["claims"].as_array().unwrap().len(),0);
|
||||||
|
let generated=fs::read_to_string(out.join("CURRENT")).unwrap();
|
||||||
|
assert!(out.join("generations").join(generated.trim())
|
||||||
|
.join("anchors.json").is_file());
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fake_lean_status_with_no_matching_certificate_cannot_be_proved() {
|
||||||
|
let dir=root("forge");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let compiled=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let lean=LeanInfo{
|
||||||
|
toolchain:"Lean 4.35".into(),library_sha256:"lib".into(),
|
||||||
|
module_sha256:"module".into(),cache:"miss"
|
||||||
|
};
|
||||||
|
let receipt=link_report(&compiled,&file,
|
||||||
|
&report(&file,Verdict::Proved,"lean",Some(lean)),&dir);
|
||||||
|
assert_eq!(receipt["claims"][0]["status"],"unverified");
|
||||||
|
assert_eq!(receipt["claims"][0]["certificate_digest"],serde_json::Value::Null);
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn real_prove_pipeline_emits_function_bound_knowledge_sidecar_without_lean() {
|
||||||
|
let dir=root("pipeline");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 无外部操作 | 长度(轨迹) = 0 | | auto |
|
||||||
|
|
||||||
|
**x = [演算](2 * 3)**
|
||||||
|
*x*
|
||||||
|
"#).unwrap();
|
||||||
|
let out=dir.join(".marqdo/prove/manual");
|
||||||
|
let opts=marqdo::prove::ProveOptions {
|
||||||
|
emit_dir:Some(out.clone()),judge:false,..Default::default()
|
||||||
|
};
|
||||||
|
let report=marqdo::prove::prove_path(&file,&opts).unwrap();
|
||||||
|
assert!(report.functions.iter().any(|f|!f.claims.is_empty()));
|
||||||
|
let linkage:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(out.join("knowledge-links.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(linkage["schema_version"],1);
|
||||||
|
assert_eq!(linkage["claims"][0]["claim_id"],"无外部操作");
|
||||||
|
assert_eq!(linkage["claims"][0]["proof_scope"],"function");
|
||||||
|
assert_ne!(linkage["claims"][0]["status"],"proved");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stale_duplicate_claims_are_never_selected_by_position() {
|
||||||
|
let dir=root("duplicate");
|
||||||
|
let file=dir.join("main.mq.md");
|
||||||
|
fs::write(&file,"# main\n\n## compute\n\n| 定理 | 结论 | 前提 | 策略 |\n|---|---|---|---|\n| rule | 结果 = 6 | | auto |\n\n**x = [演算](2 * 3)**\n*x*\n").unwrap();
|
||||||
|
let compiled=compile_project(&CompileOptions::for_path(&dir).unwrap()).unwrap();
|
||||||
|
let receipt=link_report(&compiled,&file,&report(&file,Verdict::Checked,"trace",None),&dir);
|
||||||
|
for name in ["a","b"] {
|
||||||
|
let out=dir.join(".marqdo/prove").join(name);
|
||||||
|
fs::create_dir_all(&out).unwrap();
|
||||||
|
fs::write(out.join("knowledge-links.json"),serde_json::to_vec(&receipt).unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
let index=index_links(&dir.join(".marqdo/prove"),&compiled.semantics);
|
||||||
|
assert_eq!(index["claims"][0]["status"],"ambiguous");
|
||||||
|
assert_eq!(index["claims"][1]["status"],"ambiguous");
|
||||||
|
assert_eq!(index["claims"][0]["usable"],false);
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
@@ -226,6 +226,712 @@ fn g1_cache_hit_skips_judging() {
|
|||||||
let _ = fs::remove_file(&log);
|
let _ = fs::remove_file(&log);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Source-transparent, leaf-pure imported call is verified with real Lean.
|
||||||
|
#[test]
|
||||||
|
fn modular_pure_leaf_import_proved_by_real_lean() {
|
||||||
|
if !toolchain_available() {
|
||||||
|
skip_or_fail("modular_pure_leaf_import_proved_by_real_lean");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let scratch=Scratch::new("modular-pure-import");
|
||||||
|
scratch.write("rates.mq.md",r#"# rates
|
||||||
|
|
||||||
|
## lookup
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#);
|
||||||
|
scratch.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
rates: rates.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| 返回值正确 | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
**tax = [查询](rates.rates.lookup())**
|
||||||
|
*tax*
|
||||||
|
"#);
|
||||||
|
let out=scratch.marqdo().args(["prove","main.mq.md","--json"]).output()
|
||||||
|
.expect("prove pure imported leaf");
|
||||||
|
let result:serde_json::Value=serde_json::from_slice(&out.stdout)
|
||||||
|
.unwrap_or_else(|_| panic!("stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&out.stderr),
|
||||||
|
String::from_utf8_lossy(&out.stdout)));
|
||||||
|
assert_eq!(result["status"],"proved",
|
||||||
|
"imported pure leaf must be proved by real Lean: {result}");
|
||||||
|
let ops=&result["functions"][0]["ops"];
|
||||||
|
assert!(ops.as_array().is_some_and(|a|a.is_empty()),
|
||||||
|
"pure leaf import cannot be treated as an opaque environment op: {ops}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pure cross-module parameter substitution is checked by real Lean, not JSON status.
|
||||||
|
#[test]
|
||||||
|
fn modular_pure_leaf_import_with_argument_proved_by_real_lean(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("modular_pure_leaf_import_with_argument_proved_by_real_lean");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let scratch=Scratch::new("modular-parameterized");
|
||||||
|
scratch.write("numbers.mq.md",r#"# numbers
|
||||||
|
|
||||||
|
## increment
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
*`n` + 1*
|
||||||
|
"#);
|
||||||
|
scratch.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
numbers: numbers.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## compute
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| 参数绑定正确 | 结果 = 4 | auto |
|
||||||
|
|
||||||
|
**value = [加一](numbers.numbers.increment(3))**
|
||||||
|
*value*
|
||||||
|
"#);
|
||||||
|
let out=scratch.marqdo().args(["prove","main.mq.md","--json"])
|
||||||
|
.output().expect("prove imported parameterized leaf");
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&out.stdout)
|
||||||
|
.unwrap_or_else(|_|panic!("stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&out.stderr),
|
||||||
|
String::from_utf8_lossy(&out.stdout)));
|
||||||
|
assert_eq!(json["status"],"proved",
|
||||||
|
"parameter substitution across file boundary must be Lean proved: {json}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Real inter-module certificate + closed actual-argument bridge, checked by
|
||||||
|
/// a second Lean invocation. Graph status is not itself a caller theorem.
|
||||||
|
#[test]
|
||||||
|
fn modular_closed_callsite_proof_uses_real_lean_kernel(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("modular_closed_callsite_proof_uses_real_lean_kernel");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("modular-closed-vc");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# math
|
||||||
|
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| constant | 结果 = 2 | n > 0 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#);
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## caller
|
||||||
|
|
||||||
|
**x = [获得数字](math.math.exact(3))**
|
||||||
|
*x*
|
||||||
|
"#);
|
||||||
|
let proof=s.marqdo().args(["prove","math.mq.md","--json"])
|
||||||
|
.output().expect("prove imported contract");
|
||||||
|
assert!(proof.status.success(),
|
||||||
|
"callee proof failed: {}",String::from_utf8_lossy(&proof.stdout));
|
||||||
|
let result=s.marqdo().args([
|
||||||
|
"knowledge","proof-deps","--verify","--json","."
|
||||||
|
]).output().expect("verify modular goals");
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&result.stdout)
|
||||||
|
.unwrap_or_else(|_|panic!("{}",
|
||||||
|
String::from_utf8_lossy(&result.stderr)));
|
||||||
|
assert_eq!(json["lean_preconditions_verified"],1,
|
||||||
|
"no kernel checked callsite: {json}");
|
||||||
|
assert!(json["lean_receipts_replayed"].as_u64().unwrap_or(0)>=1,
|
||||||
|
"callee theorem must be replayed by Lean, not trusted from JSON: {json}");
|
||||||
|
let call=json["obligations"].as_array().unwrap().iter()
|
||||||
|
.find(|o|o["call_site"]=="math.math.exact").unwrap();
|
||||||
|
assert_eq!(call["contracts"][0]["call_precondition_status"],"lean_kernel_verified");
|
||||||
|
assert_eq!(call["contracts"][0]["status"],"available_as_contract");
|
||||||
|
assert_eq!(json["proof_completion"],"not_established_by_dependency_analysis");
|
||||||
|
assert!(s.dir.join(".marqdo/modular/closed-goals.lean").exists());
|
||||||
|
// A proved callee cannot authorize a call with an invalid actual.
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## caller
|
||||||
|
|
||||||
|
**x = [无效调用](math.math.exact(0))**
|
||||||
|
*x*
|
||||||
|
"#);
|
||||||
|
let invalid=s.marqdo().args([
|
||||||
|
"knowledge","proof-deps","--verify","--json","--strict","."
|
||||||
|
]).output().expect("reject false contract premise");
|
||||||
|
assert_eq!(invalid.status.code(),Some(2),
|
||||||
|
"false instantiated precondition must fail closed");
|
||||||
|
let denied:serde_json::Value=serde_json::from_slice(&invalid.stdout).unwrap();
|
||||||
|
assert_eq!(denied["lean_preconditions_verified"],0);
|
||||||
|
assert!(denied["obligations"].as_array().unwrap().iter()
|
||||||
|
.any(|o|o["contracts"].as_array().is_some_and(|contracts|
|
||||||
|
contracts.iter().any(|c|
|
||||||
|
c["call_precondition_status"]=="refuted_closed_precondition"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Two independent Lean modules: the caller imports only the proved callee
|
||||||
|
/// theorem. The certificate explicitly limits its scope to pure Int forwarders.
|
||||||
|
#[test]
|
||||||
|
fn composition_emits_independently_replayable_caller_certificate(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("composition_emits_independently_replayable_caller_certificate");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("composed-replay-int");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# math
|
||||||
|
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| fixed | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#);
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## forward
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| same | 结果 = 2 | auto |
|
||||||
|
|
||||||
|
**v = [调用](math.math.exact(`n`))**
|
||||||
|
*v*
|
||||||
|
"#);
|
||||||
|
let result=s.marqdo().args([
|
||||||
|
"knowledge","compose","--strict","--json","."
|
||||||
|
]).output().expect("compose independent theorem");
|
||||||
|
assert_eq!(result.status.code(),Some(0),
|
||||||
|
"stderr={} stdout={}",String::from_utf8_lossy(&result.stderr),
|
||||||
|
String::from_utf8_lossy(&result.stdout));
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&result.stdout).unwrap();
|
||||||
|
let successful=json["results"].as_array().unwrap().iter()
|
||||||
|
.find(|row|row["status"]=="lean_kernel_proved_model")
|
||||||
|
.expect("independent callee+caller proof");
|
||||||
|
let file=std::path::PathBuf::from(successful["artifact"].as_str().unwrap());
|
||||||
|
let receipt:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(s.dir.join(file)).unwrap()).unwrap();
|
||||||
|
assert_eq!(receipt["scope"],
|
||||||
|
"number_contract_int_model_pure_forwarder_constant_result");
|
||||||
|
assert_eq!(receipt["full_marqdo_runtime_semantics_proved"],
|
||||||
|
serde_json::Value::Null);
|
||||||
|
let folder=s.dir.join(successful["artifact"].as_str().unwrap())
|
||||||
|
.parent().unwrap().to_path_buf();
|
||||||
|
let caller=fs::read_to_string(folder.join("CallerModule.lean")).unwrap();
|
||||||
|
assert!(caller.contains("import CalleeModule"));
|
||||||
|
assert!(caller.contains("using (callee_contract"));
|
||||||
|
assert!(!caller.contains("sorry"));
|
||||||
|
// Replay is tied to currently compiled Marqdo source, not just a copied
|
||||||
|
// certificate or an arbitrary Lean theorem with the same display name.
|
||||||
|
let cert=successful["artifact"].as_str().unwrap();
|
||||||
|
let replay=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("independent proof replay");
|
||||||
|
assert!(replay.status.success(),
|
||||||
|
"replay stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&replay.stderr),
|
||||||
|
String::from_utf8_lossy(&replay.stdout));
|
||||||
|
let verified:serde_json::Value=serde_json::from_slice(&replay.stdout).unwrap();
|
||||||
|
assert_eq!(verified["status"],"lean_kernel_replayed");
|
||||||
|
assert_eq!(verified["full_marqdo_runtime_semantics_proved"],false);
|
||||||
|
|
||||||
|
let original=fs::read_to_string(s.dir.join("math.mq.md")).unwrap();
|
||||||
|
fs::write(s.dir.join("math.mq.md"),original.replace("*2*","*3*")).unwrap();
|
||||||
|
let changed=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("reject stale source");
|
||||||
|
assert!(!changed.status.success(),
|
||||||
|
"old composed proof must not survive callee source change");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Projection of an imported symbolic parameter is proved in two distinct
|
||||||
|
/// Lean modules. The caller imports ONLY the callee theorem and its interface.
|
||||||
|
#[test]
|
||||||
|
fn projection_composition_proves_symbolic_caller_and_replays_from_source(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("projection_composition_proves_symbolic_caller_and_replays_from_source");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("composed-replay-projection");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
# math
|
||||||
|
|
||||||
|
## identity
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| exact | 结果 = n | auto |
|
||||||
|
|
||||||
|
*`n`*
|
||||||
|
"#);
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
# main
|
||||||
|
|
||||||
|
## forward
|
||||||
|
+ `input`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| input | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| forwarded | 结果 = input | auto |
|
||||||
|
|
||||||
|
**value = [调用](math.math.identity(`input`))**
|
||||||
|
*value*
|
||||||
|
"#);
|
||||||
|
let out=s.marqdo().args(["knowledge","compose","--strict","--json","."])
|
||||||
|
.output().expect("compose symbolic projection");
|
||||||
|
assert!(out.status.success(),"stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&out.stderr),
|
||||||
|
String::from_utf8_lossy(&out.stdout));
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&out.stdout).unwrap();
|
||||||
|
let proved=json["results"].as_array().unwrap().iter()
|
||||||
|
.find(|r|r["status"]=="lean_kernel_proved_model"&&
|
||||||
|
r["scope"]=="number_contract_int_model_pure_forwarder_parameter_projection")
|
||||||
|
.unwrap_or_else(||panic!("missing parameterized caller theorem: {json}"));
|
||||||
|
let cert=proved["artifact"].as_str().unwrap();
|
||||||
|
let dir=s.dir.join(cert).parent().unwrap().to_path_buf();
|
||||||
|
let caller=fs::read_to_string(dir.join("CallerModule.lean")).unwrap();
|
||||||
|
let callee=fs::read_to_string(dir.join("CalleeModule.lean")).unwrap();
|
||||||
|
assert!(callee.contains("callee_contract"));
|
||||||
|
assert!(caller.contains("import CalleeModule"));
|
||||||
|
assert!(caller.contains("using (callee_contract"));
|
||||||
|
assert!(caller.contains("= v0"),"caller conclusion must be symbolic");
|
||||||
|
assert!(!caller.contains("sorry"));
|
||||||
|
let replay=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("replay parameterized theorem");
|
||||||
|
assert!(replay.status.success(),"{} {}",
|
||||||
|
String::from_utf8_lossy(&replay.stdout),
|
||||||
|
String::from_utf8_lossy(&replay.stderr));
|
||||||
|
let report:serde_json::Value=serde_json::from_slice(&replay.stdout).unwrap();
|
||||||
|
assert_eq!(report["status"],"lean_kernel_replayed");
|
||||||
|
assert_eq!(report["full_marqdo_runtime_semantics_proved"],false);
|
||||||
|
let original=fs::read_to_string(s.dir.join("math.mq.md")).unwrap();
|
||||||
|
fs::write(s.dir.join("math.mq.md"),original.replace("*`n`*","*0*")).unwrap();
|
||||||
|
let stale=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("replay changed projection");
|
||||||
|
assert!(!stale.status.success(),"modified callee cannot retain proof");
|
||||||
|
fs::write(s.dir.join("math.mq.md"),original).unwrap();
|
||||||
|
let main=fs::read_to_string(s.dir.join("main.mq.md")).unwrap();
|
||||||
|
fs::write(s.dir.join("main.mq.md"),
|
||||||
|
main.replace("结果 = input","结果 = 999")).unwrap();
|
||||||
|
let invalid=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("replay changed caller claim");
|
||||||
|
assert!(!invalid.status.success(),"unsupported caller conclusion cannot inherit proof");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A source-derived arithmetic theorem is imported by a caller without
|
||||||
|
/// inlining the callee body. False or stale contracts never become axioms.
|
||||||
|
#[test]
|
||||||
|
fn pure_expression_composition_proves_and_replays_real_lean(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("pure_expression_composition_proves_and_replays_real_lean");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("composed-pure-expr");
|
||||||
|
let callee=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
# math
|
||||||
|
## increment
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| plus | 结果 = n + 1 | auto |
|
||||||
|
|
||||||
|
*`n` + 1*
|
||||||
|
"#;
|
||||||
|
s.write("math.mq.md",callee);
|
||||||
|
let caller=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
# main
|
||||||
|
## forward
|
||||||
|
+ `input`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| input | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| inc | 结果 = input + 1 | auto |
|
||||||
|
|
||||||
|
**v = [递增](math.math.increment(`input`))**
|
||||||
|
*v*
|
||||||
|
"#;
|
||||||
|
s.write("main.mq.md",caller);
|
||||||
|
let out=s.marqdo().args(["knowledge","compose","--strict","--json","."])
|
||||||
|
.output().expect("compose pure expression");
|
||||||
|
assert!(out.status.success(),"{} {}",
|
||||||
|
String::from_utf8_lossy(&out.stdout),
|
||||||
|
String::from_utf8_lossy(&out.stderr));
|
||||||
|
let report:serde_json::Value=serde_json::from_slice(&out.stdout).unwrap();
|
||||||
|
let proved=report["results"].as_array().unwrap().iter().find(|r|
|
||||||
|
r["scope"]=="number_contract_int_model_pure_expression_forwarder"
|
||||||
|
&&r["status"]=="lean_kernel_proved_model")
|
||||||
|
.unwrap_or_else(||panic!("no checked arithmetic composition: {report}"));
|
||||||
|
let cert=proved["artifact"].as_str().unwrap();
|
||||||
|
let dir=s.dir.join(cert).parent().unwrap().to_path_buf();
|
||||||
|
let callee_lean=fs::read_to_string(dir.join("CalleeModule.lean")).unwrap();
|
||||||
|
let caller_lean=fs::read_to_string(dir.join("CallerModule.lean")).unwrap();
|
||||||
|
assert!(callee_lean.contains("(v0 + (1 : Int))"));
|
||||||
|
assert!(caller_lean.starts_with("import CalleeModule"));
|
||||||
|
assert!(caller_lean.contains("using (callee_contract"));
|
||||||
|
assert!(!caller_lean.contains("sorry"));
|
||||||
|
let replay=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("replay arithmetic certificate");
|
||||||
|
assert!(replay.status.success(),"{} {}",
|
||||||
|
String::from_utf8_lossy(&replay.stdout),
|
||||||
|
String::from_utf8_lossy(&replay.stderr));
|
||||||
|
let record:serde_json::Value=serde_json::from_slice(&replay.stdout).unwrap();
|
||||||
|
assert_eq!(record["status"],"lean_kernel_replayed");
|
||||||
|
assert_eq!(record["full_marqdo_runtime_semantics_proved"],false);
|
||||||
|
s.write("math.mq.md",&callee.replace("结果 = n + 1","结果 = n + 2"));
|
||||||
|
let stale=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("reject forged arithmetic contract");
|
||||||
|
assert!(!stale.status.success(),"changed theorem declaration cannot be replayed");
|
||||||
|
s.write("math.mq.md",callee);
|
||||||
|
s.write("main.mq.md",&caller.replace("结果 = input + 1",
|
||||||
|
"结果 = input + 2"));
|
||||||
|
let false_caller=s.marqdo().args(["knowledge","replay",cert,"--json","."])
|
||||||
|
.output().expect("reject false caller claim");
|
||||||
|
assert!(!false_caller.status.success(),"caller mismatch cannot inherit callee proof");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stronger symbolic branch guard implies the callee requires clause in
|
||||||
|
/// the Lean Int model. It does NOT prove dynamic Marqdo Number semantics.
|
||||||
|
#[test]
|
||||||
|
fn symbolic_path_implication_uses_real_lean_without_runtime_promotion() {
|
||||||
|
if !toolchain_available() {
|
||||||
|
skip_or_fail("symbolic_path_implication_uses_real_lean_without_runtime_promotion");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("modular-symbolic-omega");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
|
||||||
|
# math
|
||||||
|
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| constant | 结果 = 2 | n > 0 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#);
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
|
||||||
|
# main
|
||||||
|
|
||||||
|
## guarded
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
1. `n` > 10
|
||||||
|
**x = [带条件调用](math.math.exact(`n`))**
|
||||||
|
2. *
|
||||||
|
**x = 0**
|
||||||
|
|
||||||
|
*x*
|
||||||
|
"#);
|
||||||
|
let proof=s.marqdo().args(["prove","math.mq.md","--json"])
|
||||||
|
.output().expect("prove callee first");
|
||||||
|
assert!(proof.status.success(),
|
||||||
|
"callee must be proved: {}",String::from_utf8_lossy(&proof.stdout));
|
||||||
|
let out=s.marqdo().args([
|
||||||
|
"knowledge","proof-deps","--verify","--json","."
|
||||||
|
]).output().expect("prove conditional Int path");
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&out.stdout)
|
||||||
|
.unwrap_or_else(|_|panic!("stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&out.stderr),
|
||||||
|
String::from_utf8_lossy(&out.stdout)));
|
||||||
|
assert!(json["symbolic_path_lean_model_proved"].as_u64().unwrap_or(0)>=1,
|
||||||
|
"Lean must discharge n > 10 entails n > 0: {json}");
|
||||||
|
assert_eq!(json["symbolic_proof_scope"],
|
||||||
|
"integer_path_model_not_runtime_equivalence");
|
||||||
|
assert_eq!(json["proof_completion"],
|
||||||
|
"not_established_by_dependency_analysis");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An arithmetic source guard is instantiated at a symbolic call site,
|
||||||
|
/// then Lean proves the linear implication (never runtime Number equivalence).
|
||||||
|
#[test]
|
||||||
|
fn arithmetic_symbolic_path_implication_uses_real_lean(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("arithmetic_symbolic_path_implication_uses_real_lean");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("symbolic-linear-path");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
# math
|
||||||
|
## exact
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 前提 | 策略 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| constant | 结果 = 2 | n > 0 | auto |
|
||||||
|
|
||||||
|
*2*
|
||||||
|
"#);
|
||||||
|
s.write("main.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
# main
|
||||||
|
## guarded
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
1. `n` + 5 > 10
|
||||||
|
**x = [条件调用](math.math.exact(`n`))**
|
||||||
|
2. *
|
||||||
|
**x = 0**
|
||||||
|
|
||||||
|
*x*
|
||||||
|
"#);
|
||||||
|
let callee=s.marqdo().args(["prove","math.mq.md","--json"])
|
||||||
|
.output().expect("verify source callee");
|
||||||
|
assert!(callee.status.success(),
|
||||||
|
"callee proof must precede callsite discharge: {}",
|
||||||
|
String::from_utf8_lossy(&callee.stdout));
|
||||||
|
let audit=s.marqdo().args(["knowledge","proof-deps","--verify","--json","."])
|
||||||
|
.output().expect("verify symbolic linear path");
|
||||||
|
let json:serde_json::Value=serde_json::from_slice(&audit.stdout)
|
||||||
|
.unwrap_or_else(|_|panic!("stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&audit.stderr),
|
||||||
|
String::from_utf8_lossy(&audit.stdout)));
|
||||||
|
assert!(json["symbolic_path_lean_model_proved"].as_u64().unwrap_or(0)>=1,
|
||||||
|
"n + 5 > 10 must imply n > 0 in kernel-checked Int model: {json}");
|
||||||
|
assert_eq!(json["symbolic_proof_scope"],
|
||||||
|
"integer_path_model_not_runtime_equivalence");
|
||||||
|
assert_eq!(json["proof_completion"],
|
||||||
|
"not_established_by_dependency_analysis");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One proof pipeline for three transitive modules, two sequential calls,
|
||||||
|
/// an exhaustive branch, and a caller inequality claim. No callee source is
|
||||||
|
/// inlined into the importing Lean module; every module has its own theorem.
|
||||||
|
#[test]
|
||||||
|
fn unified_modular_contract_proves_multicall_branch_and_transitive_dag(){
|
||||||
|
if !toolchain_available(){
|
||||||
|
skip_or_fail("unified_modular_contract_proves_multicall_branch_and_transitive_dag");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let s=Scratch::new("unified-contract-three-module");
|
||||||
|
s.write("math.mq.md",r#"---
|
||||||
|
markup: occlusion
|
||||||
|
---
|
||||||
|
# math
|
||||||
|
|
||||||
|
## increment
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| increment_post | 结果 = n + 1 | auto |
|
||||||
|
|
||||||
|
*`n` + 1*
|
||||||
|
"#);
|
||||||
|
let ops=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
---
|
||||||
|
# ops
|
||||||
|
|
||||||
|
## twice
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| twice_post | 结果 = n + 2 | auto |
|
||||||
|
|
||||||
|
**a = [第一次](math.math.increment(`n`))**
|
||||||
|
**b = [第二次](math.math.increment(`a`))**
|
||||||
|
*b*
|
||||||
|
"#;
|
||||||
|
s.write("ops.mq.md",ops);
|
||||||
|
let main=r#"---
|
||||||
|
markup: occlusion
|
||||||
|
import:
|
||||||
|
math: math.mq.md
|
||||||
|
ops: ops.mq.md
|
||||||
|
---
|
||||||
|
# main
|
||||||
|
|
||||||
|
## guarded
|
||||||
|
+ `n`
|
||||||
|
|
||||||
|
| 参数 | 类型 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| n | int | integer |
|
||||||
|
|
||||||
|
| 定理 | 结论 | 策略 |
|
||||||
|
|---|---|---|
|
||||||
|
| result_floor | 结果 ≥ 1 | auto |
|
||||||
|
|
||||||
|
1. `n` > 0
|
||||||
|
**x = [调用复合模块](ops.ops.twice(`n`))**
|
||||||
|
*x*
|
||||||
|
2. *
|
||||||
|
**y = [调用叶模块](math.math.increment(0))**
|
||||||
|
*y*
|
||||||
|
"#;
|
||||||
|
s.write("main.mq.md",main);
|
||||||
|
let output=s.marqdo().args(["knowledge","compose","--strict","--json","."])
|
||||||
|
.output().expect("compose uniform DAG");
|
||||||
|
assert!(output.status.success(),"stderr={} stdout={}",
|
||||||
|
String::from_utf8_lossy(&output.stderr),
|
||||||
|
String::from_utf8_lossy(&output.stdout));
|
||||||
|
let report:serde_json::Value=serde_json::from_slice(&output.stdout).unwrap();
|
||||||
|
let record=report["results"].as_array().unwrap().iter().find(|row|
|
||||||
|
row["scope"]=="pure_number_int_model_sequential_branch_dag"
|
||||||
|
&&row["status"]=="lean_kernel_proved_model"
|
||||||
|
&&row["evidence"]["grade"]=="model_proved"
|
||||||
|
&&row["artifact"].as_str().is_some_and(|p|{
|
||||||
|
let path=s.dir.join(p);
|
||||||
|
let cert:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(path).unwrap_or_default()).unwrap_or_default();
|
||||||
|
cert["modules"].as_array().is_some_and(|nodes|nodes.len()==3)
|
||||||
|
})).unwrap_or_else(||panic!("three-module caller theorem not proved: {report}"));
|
||||||
|
let certificate=record["artifact"].as_str().unwrap();
|
||||||
|
let folder=s.dir.join(certificate).parent().unwrap().to_path_buf();
|
||||||
|
let receipt:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(s.dir.join(certificate)).unwrap()).unwrap();
|
||||||
|
let modules=receipt["modules"].as_array().unwrap();
|
||||||
|
assert_eq!(modules.len(),3);
|
||||||
|
let caller_name=modules[2]["module"].as_str().unwrap();
|
||||||
|
let caller=fs::read_to_string(folder.join(format!("{caller_name}.lean"))).unwrap();
|
||||||
|
assert!(caller.contains("import M"));
|
||||||
|
assert!(caller.contains("have hc"));
|
||||||
|
assert!(caller.contains("by_cases"));
|
||||||
|
assert!(!caller.contains("sorry"));
|
||||||
|
assert_eq!(receipt["full_marqdo_runtime_semantics_proved"],false);
|
||||||
|
let replay=s.marqdo().args(["knowledge","replay",certificate,"--json","."])
|
||||||
|
.output().expect("replay unified proof");
|
||||||
|
assert!(replay.status.success(),"stdout={} stderr={}",
|
||||||
|
String::from_utf8_lossy(&replay.stdout),
|
||||||
|
String::from_utf8_lossy(&replay.stderr));
|
||||||
|
let replayed:serde_json::Value=serde_json::from_slice(&replay.stdout).unwrap();
|
||||||
|
assert_eq!(replayed["status"],"lean_kernel_replayed");
|
||||||
|
assert_eq!(replayed["evidence"]["grade"],"model_proved");
|
||||||
|
|
||||||
|
s.write("ops.mq.md",&ops.replace("结果 = n + 2","结果 = n + 3"));
|
||||||
|
let stale=s.marqdo().args(["knowledge","replay",certificate,"--json","."])
|
||||||
|
.output().expect("reject changed intermediate proof contract");
|
||||||
|
assert!(!stale.status.success(),"stale transitive dependency must fail");
|
||||||
|
|
||||||
|
s.write("ops.mq.md",ops);
|
||||||
|
s.write("main.mq.md",&main.replace("结果 ≥ 1","结果 ≥ 100"));
|
||||||
|
let wrong=s.marqdo().args(["knowledge","compose","--strict","--json","."])
|
||||||
|
.output().expect("reject invalid caller theorem");
|
||||||
|
let output_json:serde_json::Value=serde_json::from_slice(&wrong.stdout)
|
||||||
|
.unwrap_or_default();
|
||||||
|
assert!(!output_json["results"].as_array().into_iter().flat_map(|a|a.iter())
|
||||||
|
.any(|r|r["scope"]=="pure_number_int_model_sequential_branch_dag"
|
||||||
|
&&r["status"]=="lean_kernel_proved_model"
|
||||||
|
&&r["identity"]==receipt["identity"]));
|
||||||
|
}
|
||||||
|
|
||||||
/// G2:真证书命中(用真 lean 跑一次后,证书生效;第二次 cache: hit 且快)。
|
/// G2:真证书命中(用真 lean 跑一次后,证书生效;第二次 cache: hit 且快)。
|
||||||
#[test]
|
#[test]
|
||||||
fn g2_certificate_hit_after_real_run() {
|
fn g2_certificate_hit_after_real_run() {
|
||||||
@@ -241,6 +947,24 @@ fn g2_certificate_hit_after_real_run() {
|
|||||||
let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
|
let json: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
|
||||||
assert_eq!(json["status"], "proved", "真定理必须 proved:{json}");
|
assert_eq!(json["status"], "proved", "真定理必须 proved:{json}");
|
||||||
assert_eq!(json["lean"]["cache"], "miss");
|
assert_eq!(json["lean"]["cache"], "miss");
|
||||||
|
let proof_id = json["artifact_id"].as_str().unwrap().rsplit('/').next().unwrap();
|
||||||
|
let link_path = s.dir.join(".marqdo/prove").join(proof_id).join("knowledge-links.json");
|
||||||
|
let linkage: serde_json::Value = serde_json::from_slice(
|
||||||
|
&fs::read(&link_path).expect("real Lean proof must emit a knowledge linkage"))
|
||||||
|
.expect("knowledge linkage JSON");
|
||||||
|
assert_eq!(linkage["claims"][0]["status"], "proved",
|
||||||
|
"only verified Lean receipts should carry proved: {linkage}");
|
||||||
|
assert_eq!(linkage["claims"][0]["proof_scope"], "function");
|
||||||
|
assert!(linkage["claims"][0]["certificate_digest"].as_str().is_some());
|
||||||
|
let publish=s.marqdo().args([
|
||||||
|
"knowledge","台账.mq.md","--out",".marqdo"
|
||||||
|
]).output().expect("publish verified knowledge");
|
||||||
|
assert!(publish.status.success(),"knowledge compile failed: {}",
|
||||||
|
String::from_utf8_lossy(&publish.stderr));
|
||||||
|
let proof_index: serde_json::Value = serde_json::from_slice(
|
||||||
|
&fs::read(s.dir.join(".marqdo/proof-index.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(proof_index["claims"][0]["status"],"proved");
|
||||||
|
assert_eq!(proof_index["claims"][0]["usable"],true);
|
||||||
|
|
||||||
// 第二次:命中证书。
|
// 第二次:命中证书。
|
||||||
let out2 = s.marqdo().arg("prove").arg("台账.mq.md").arg("--json").output().expect("second prove");
|
let out2 = s.marqdo().arg("prove").arg("台账.mq.md").arg("--json").output().expect("second prove");
|
||||||
@@ -248,6 +972,23 @@ fn g2_certificate_hit_after_real_run() {
|
|||||||
assert_eq!(json2["status"], "proved");
|
assert_eq!(json2["status"], "proved");
|
||||||
assert_eq!(json2["lean"]["cache"], "hit", "第二次必须命中证书缓存");
|
assert_eq!(json2["lean"]["cache"], "hit", "第二次必须命中证书缓存");
|
||||||
assert!(json2["duration_ms"].as_u64().unwrap() < 5000, "命中后必须快");
|
assert!(json2["duration_ms"].as_u64().unwrap() < 5000, "命中后必须快");
|
||||||
|
|
||||||
|
// Even a genuine local certificate ceases to be usable if the generated
|
||||||
|
// Lean source has been edited; a matching JSON hash is not enough.
|
||||||
|
let generated=s.dir.join(".marqdo/prove").join(proof_id).join("Generated");
|
||||||
|
let lean_file=fs::read_dir(&generated).unwrap().map(|e|e.unwrap().path())
|
||||||
|
.find(|p|p.extension().is_some_and(|ext|ext=="lean")).unwrap();
|
||||||
|
let mut modified=fs::read_to_string(&lean_file).unwrap();
|
||||||
|
modified.push_str("\n-- local tampering\n");
|
||||||
|
fs::write(&lean_file,modified).unwrap();
|
||||||
|
let republish=s.marqdo().args([
|
||||||
|
"knowledge","台账.mq.md","--out",".marqdo"
|
||||||
|
]).output().unwrap();
|
||||||
|
assert!(republish.status.success(),"{}",String::from_utf8_lossy(&republish.stderr));
|
||||||
|
let stale:serde_json::Value=serde_json::from_slice(
|
||||||
|
&fs::read(s.dir.join(".marqdo/proof-index.json")).unwrap()).unwrap();
|
||||||
|
assert_eq!(stale["claims"][0]["usable"],false,
|
||||||
|
"modified generated module cannot reuse genuine Lean receipt: {stale}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// G2b:--no-cache 绕过证书。
|
/// G2b:--no-cache 绕过证书。
|
||||||
|
|||||||
Reference in new issue
Block a user