scaffold: initial crate, module layout and shared contracts

This commit is contained in:
marqdo-prove committed 2026-11-26 09:41:54 +08:00
1 parent 8d273dacd0
commit ecaf1b756c
23 files changed
+519

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Rust build output
/target/
# Local development toolchain and scratch space (not part of the deliverable)
/.tool/
/.tmp/
# Lean build output and downloaded dependencies; see lean/lean-toolchain and
# lean/lake-manifest.json for the pinned identities.
lean/.lake/
lean/scratch/
# Generated Marqdo cache directories are per-user artifacts.
/.marqdo/
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "marqdo-prove"
version = "0.1.0"
edition = "2021"
rust-version = "1.85"
license = "Apache-2.0"
description = "Static, link-driven mathematical proof checking for Marqdo knowledge documents"
repository = "https://git.cflmy.cn/cflmy/marqdo-prove"
[[bin]]
name = "marqdo-prove"
path = "src/main.rs"
[dependencies]
libc = "0.2"
num-bigint = "0.4"
num-traits = "0.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
[profile.release]
opt-level = 2
+3
View File
@@ -0,0 +1,3 @@
module
public import MarqdoProof.Basic
+3
View File
@@ -0,0 +1,3 @@
module
public import MarqdoProof.ArtTest.Dep
public import MarqdoProof.ArtTest.Target
+5
View File
@@ -0,0 +1,5 @@
module
public import MarqdoProof.Basic
public theorem art_dep_sq (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x]
+8
View File
@@ -0,0 +1,8 @@
module
public import MarqdoProof.ArtTest.Dep
public theorem art_target_sum (x y : Int) : x * x + y * y ≥ 0 := by
have h1 := art_dep_sq x
have h2 := art_dep_sq y
omega
+17
View File
@@ -0,0 +1,17 @@
module
public import Mathlib.Data.Int.Basic
public import Mathlib.Data.Int.Lemmas
public import Mathlib.Tactic.Positivity
public import Mathlib.Tactic.Ring
public import Mathlib.Tactic.NormNum
public import Mathlib.Tactic.Linarith
/-!
Fixed base environment for `marqdo-prove`.
This module is the only trusted math import surface of the backend. It is
deliberately small: integer definitions/lemmas plus the fixed tactic set used
by the bounded search driver. Nothing in here accepts user text or user
tactics; the generator in `src/lean.rs` only emits typed expressions.
-/
+3
View File
@@ -0,0 +1,3 @@
module
public import MarqdoProof.DepTest.Dep
public import MarqdoProof.DepTest.Use
+5
View File
@@ -0,0 +1,5 @@
module
public import MarqdoProof.Basic
public theorem dep_square (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x]
+5
View File
@@ -0,0 +1,5 @@
module
public import MarqdoProof.DepTest.Dep
public theorem use_square (x : Int) : x * x ≥ 0 := dep_square x
+96
View File
@@ -0,0 +1,96 @@
{"version": "1.3.0",
"packagesDir": ".lake/packages",
"packages":
[{"url": "https://github.com/leanprover-community/mathlib4",
"type": "git",
"subDir": null,
"scope": "",
"rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
"name": "mathlib",
"manifestFile": "lake-manifest.json",
"inputRev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
"inherited": false,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/plausible",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "054b228ce0ac61d767c6e71ba73a24728f191b72",
"name": "plausible",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/LeanSearchClient",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9",
"name": "LeanSearchClient",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/import-graph",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0",
"name": "importGraph",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/ProofWidgets4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "2f0f3520daeac2d9310ff25b7a877a0e5cdaa203",
"name": "proofwidgets",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.lean"},
{"url": "https://github.com/leanprover-community/aesop",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "66ff77cf0c4c898799e4b94d14db55f7a02d0c5a",
"name": "aesop",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/quote4",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "ff055a2fcc835935e0ae607339b455a5f5896b4b",
"name": "Qq",
"manifestFile": "lake-manifest.json",
"inputRev": "master",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover-community/batteries",
"type": "git",
"subDir": null,
"scope": "leanprover-community",
"rev": "b4b25a3886a16daacaf6615c2eea7170a6e8f458",
"name": "batteries",
"manifestFile": "lake-manifest.json",
"inputRev": "main",
"inherited": true,
"configFile": "lakefile.toml"},
{"url": "https://github.com/leanprover/lean4-cli",
"type": "git",
"subDir": null,
"scope": "leanprover",
"rev": "50810f72af7618bee62fe9800dc26e806c188703",
"name": "Cli",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.36.0",
"inherited": true,
"configFile": "lakefile.toml"}],
"name": "marqdo_proof",
"lakeDir": ".lake",
"fixedToolchain": false}
+11
View File
@@ -0,0 +1,11 @@
name = "marqdo_proof"
version = "0.1.0"
defaultTargets = ["MarqdoProof"]
[[require]]
name = "mathlib"
git = "https://github.com/leanprover-community/mathlib4"
rev = "fc4f59e577feb1a4956671bc04ac18aaaf8cd842"
[[lean_lib]]
name = "MarqdoProof"
+1
View File
@@ -0,0 +1 @@
leanprover/lean4:v4.36.0
+1
View File
@@ -0,0 +1 @@
//! Upstream `marqdo check --emit` integration and strict Analysis validation.
+1
View File
@@ -0,0 +1 @@
//! Content-addressed proof bundles, manifests and replay (docs/DEVELOPMENT.md §8).
+1
View File
@@ -0,0 +1 @@
//! Proof-unit selection from the public document AST (docs/DEVELOPMENT.md §3).
+3
View File
@@ -0,0 +1,3 @@
//! Restricted integer mathematics: lexer, parser, typed AST, Lean rendering.
//!
//! Implemented in a later commit of this milestone; see docs/DEVELOPMENT.md §4.
+1
View File
@@ -0,0 +1 @@
//! Fixed Lean 4 + Mathlib backend invocation and trusted source generation.
+310
View File
@@ -0,0 +1,310 @@
//! `marqdo-prove` library: compile selected Marqdo knowledge propositions to a
//! fixed Lean 4 + Mathlib backend, verify them through an independent replay
//! path, and publish content-addressed proof bundles.
//!
//! The public surface of this crate is intentionally small: [`prove::run`] is
//! the single workflow entry point used by the executable, plus the typed
//! result/report types. Every other module is an internal component with a
//! one-directional dependency order:
//!
//! ```text
//! analysis -> document -> linker -> formula/model -> lean -> certificate
//! \-------------------/
//! prove orchestrates
//! ```
//!
//! No component may build a second Markdown parser, a second Lean kernel, or a
//! second proof-validation route. See `docs/DEVELOPMENT.md` for the normative
//! specification this code implements.
pub mod analysis;
pub mod certificate;
pub mod document;
pub mod formula;
pub mod lean;
pub mod linker;
pub mod model;
pub mod prove;
use serde::{Deserialize, Serialize};
/// Tool identity recorded in proof bundles and reported by `--version`.
pub const TOOL_NAME: &str = "marqdo-prove";
/// Version of the proof bundle contract emitted by this build.
pub const PROOF_SCHEMA: &str = "marqdo.proof";
pub const PROOF_SCHEMA_VERSION: u64 = 1;
/// Revision of the upstream `marqdo.analysis` contract this build requires.
pub const REQUIRED_ANALYSIS_REVISION: u64 = 3;
/// Revision of the upstream CLI Tool contract this build declares.
pub const REQUIRED_API_REVISION: u64 = 1;
/// Hard limits. They are finite, documented and exercised by the negative
/// tests; the defaults mirror `docs/DEVELOPMENT.md` §13.1.
pub mod limits {
pub const MAX_DOCUMENTS: usize = 128;
pub const MAX_UNITS: usize = 512;
pub const MAX_DEPTH: usize = 64;
pub const MAX_SOURCE_BYTES: u64 = 16 * 1024 * 1024;
pub const MAX_GOAL_BYTES: usize = 64 * 1024;
pub const MAX_FORMULA_TOKENS: usize = 4096;
pub const MAX_AST_DEPTH: usize = 128;
pub const MAX_INT_DIGITS: usize = 4096;
pub const MAX_VARS: usize = 16;
pub const MAX_EXPONENT: u32 = 16;
pub const MAX_LITERAL_DIGITS: usize = 4096;
/// Wall clock budget for one Lean proof-search process.
pub const PROOF_WALL_SECS: u64 = 30;
/// Wall clock budget for one whole `check`/`replay` invocation.
pub const TASK_WALL_SECS: u64 = 300;
/// Wall clock budget for one upstream `marqdo check --emit` invocation.
pub const CLI_TIMEOUT_SECS: u64 = 30;
/// Maximum accepted proof payload size.
pub const MAX_PROOF_BYTES: u64 = 128 * 1024 * 1024;
/// Maximum size of one local `.mq.md` opened while extending the catalog.
pub const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
}
/// A half-open UTF-8 byte range in a single document source.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl Span {
pub const fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
pub fn is_valid_in(&self, source: &str) -> bool {
self.start <= self.end
&& self.end <= source.len()
&& source.is_char_boundary(self.start)
&& source.is_char_boundary(self.end)
}
}
impl std::fmt::Display for Span {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.start, self.end)
}
}
/// Stable diagnostic codes. The strings are part of the user contract.
pub mod codes {
pub const DOCUMENT_GOAL_COUNT: &str = "document.goal_count";
pub const DOCUMENT_DEPENDENCIES_SHAPE: &str = "document.dependencies_shape";
pub const DOCUMENT_UNIT: &str = "document.unit";
pub const FORMULA_FREE_VARIABLE: &str = "formula.free_variable";
pub const FORMULA_UNSUPPORTED: &str = "formula.unsupported";
pub const FORMULA_SYNTAX: &str = "formula.syntax";
pub const LINK_MISSING: &str = "link.missing";
pub const LINK_AMBIGUOUS: &str = "link.ambiguous";
pub const LINK_CYCLE: &str = "link.cycle";
pub const LINK_OUTSIDE_ROOT: &str = "link.outside_root";
pub const LINK_INVALID: &str = "link.invalid";
pub const LINK_CONTEXT_CONFLICT: &str = "link.context_conflict";
pub const MODEL_UNSUPPORTED: &str = "model.unsupported";
pub const MODEL_UNBOUND_ALIAS: &str = "model.unbound_alias";
pub const PROOF_BUDGET: &str = "proof.budget";
pub const PROOF_UNTRUSTED_AXIOM: &str = "proof.untrusted_axiom";
pub const PROOF_TARGET_MISMATCH: &str = "proof.target_mismatch";
pub const PROOF_REPLAY_FAILED: &str = "proof.replay_failed";
pub const CERTIFICATE_STALE: &str = "certificate.stale";
pub const CERTIFICATE_INVALID: &str = "certificate.invalid";
pub const UPSTREAM_CONTRACT: &str = "upstream.contract";
pub const BACKEND_UNAVAILABLE: &str = "backend.unavailable";
pub const BACKEND_ISOLATION: &str = "backend.isolation";
pub const REPORT_NO_TARGETS: &str = "report.no_targets";
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Severity {
Error,
Warning,
}
impl Severity {
pub fn as_str(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
}
}
}
/// A user-facing diagnostic: stable code, owner span when known, and an action.
#[derive(Clone, Debug)]
pub struct Diagnostic {
pub severity: Severity,
pub code: &'static str,
pub message: String,
pub span: Option<Span>,
pub hint: Option<String>,
}
impl Diagnostic {
pub fn error(code: &'static str, message: impl Into<String>) -> Self {
Self {
severity: Severity::Error,
code,
message: message.into(),
span: None,
hint: None,
}
}
pub fn warning(code: &'static str, message: impl Into<String>) -> Self {
Self {
severity: Severity::Warning,
code,
message: message.into(),
span: None,
hint: None,
}
}
pub fn at(mut self, span: Span) -> Self {
self.span = Some(span);
self
}
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
}
/// Logical outcome of one requested target. `error` (engine failure) is a
/// process-level condition, not a target outcome.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Verified,
Refuted,
Unknown,
Unsupported,
Invalid,
Blocked,
}
impl Outcome {
pub fn as_str(self) -> &'static str {
match self {
Outcome::Verified => "verified",
Outcome::Refuted => "refuted",
Outcome::Unknown => "unknown",
Outcome::Unsupported => "unsupported",
Outcome::Invalid => "invalid",
Outcome::Blocked => "blocked",
}
}
}
/// Whether the stored evidence still binds the current sources/environment.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Freshness {
Current,
Stale,
Unavailable,
}
impl Freshness {
pub fn as_str(self) -> &'static str {
match self {
Freshness::Current => "current",
Freshness::Stale => "stale",
Freshness::Unavailable => "unavailable",
}
}
}
/// Scope of a verified result. `runtime` is deliberately absent: the program
/// bridge models a finite exact-integer subset, never a real runtime.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
Mathematical,
ProgramModel,
}
impl Scope {
pub fn as_str(self) -> &'static str {
match self {
Scope::Mathematical => "mathematical",
Scope::ProgramModel => "program_model",
}
}
}
/// Maximum outcome status of a whole run, used for the process exit code.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunStatus {
/// Every requested target verified, or no target at all.
Success,
/// At least one requested target was not verified.
Unverified,
/// Engineering failure: CLI/Lean/isolation/IO/upstream contract.
Failure,
}
impl RunStatus {
pub fn exit_code(self) -> i32 {
match self {
RunStatus::Success => 0,
RunStatus::Unverified => 1,
RunStatus::Failure => 2,
}
}
}
/// Failure raised by a component before a per-target outcome exists.
#[derive(Clone, Debug)]
pub struct Failure {
pub code: &'static str,
pub message: String,
pub hint: Option<String>,
}
impl Failure {
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
hint: None,
}
}
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for Failure {}
pub type Result<T> = std::result::Result<T, Failure>;
/// Lowercase hex SHA-256 of raw bytes.
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(bytes);
hex_lower(&digest)
}
fn hex_lower(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push(HEX[(byte >> 4) as usize] as char);
out.push(HEX[(byte & 0xf) as usize] as char);
}
out
}
+1
View File
@@ -0,0 +1 @@
//! Controlled multi-entry catalog, exact link resolution and dependency DAG.
+5
View File
@@ -0,0 +1,5 @@
//! `marqdo-prove` executable: argument handling, presentation and exit codes.
fn main() {
std::process::exit(2);
}
+1
View File
@@ -0,0 +1 @@
//! Finite exact-integer program model mapping (docs/DEVELOPMENT.md §7).
+1
View File
@@ -0,0 +1 @@
//! Single orchestration of `check` and `replay`.