diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f89e5d0 --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..03bb46f --- /dev/null +++ b/Cargo.toml @@ -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 diff --git a/lean/MarqdoProof.lean b/lean/MarqdoProof.lean new file mode 100644 index 0000000..118bee5 --- /dev/null +++ b/lean/MarqdoProof.lean @@ -0,0 +1,3 @@ +module + +public import MarqdoProof.Basic diff --git a/lean/MarqdoProof/ArtTest.lean b/lean/MarqdoProof/ArtTest.lean new file mode 100644 index 0000000..7efb41c --- /dev/null +++ b/lean/MarqdoProof/ArtTest.lean @@ -0,0 +1,3 @@ +module +public import MarqdoProof.ArtTest.Dep +public import MarqdoProof.ArtTest.Target diff --git a/lean/MarqdoProof/ArtTest/Dep.lean b/lean/MarqdoProof/ArtTest/Dep.lean new file mode 100644 index 0000000..2ef3717 --- /dev/null +++ b/lean/MarqdoProof/ArtTest/Dep.lean @@ -0,0 +1,5 @@ +module + +public import MarqdoProof.Basic + +public theorem art_dep_sq (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x] diff --git a/lean/MarqdoProof/ArtTest/Target.lean b/lean/MarqdoProof/ArtTest/Target.lean new file mode 100644 index 0000000..87cb1b6 --- /dev/null +++ b/lean/MarqdoProof/ArtTest/Target.lean @@ -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 diff --git a/lean/MarqdoProof/Basic.lean b/lean/MarqdoProof/Basic.lean new file mode 100644 index 0000000..8cc69b5 --- /dev/null +++ b/lean/MarqdoProof/Basic.lean @@ -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. +-/ diff --git a/lean/MarqdoProof/DepTest.lean b/lean/MarqdoProof/DepTest.lean new file mode 100644 index 0000000..1835d9a --- /dev/null +++ b/lean/MarqdoProof/DepTest.lean @@ -0,0 +1,3 @@ +module +public import MarqdoProof.DepTest.Dep +public import MarqdoProof.DepTest.Use diff --git a/lean/MarqdoProof/DepTest/Dep.lean b/lean/MarqdoProof/DepTest/Dep.lean new file mode 100644 index 0000000..5eca0a9 --- /dev/null +++ b/lean/MarqdoProof/DepTest/Dep.lean @@ -0,0 +1,5 @@ +module + +public import MarqdoProof.Basic + +public theorem dep_square (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x] diff --git a/lean/MarqdoProof/DepTest/Use.lean b/lean/MarqdoProof/DepTest/Use.lean new file mode 100644 index 0000000..d91a1ab --- /dev/null +++ b/lean/MarqdoProof/DepTest/Use.lean @@ -0,0 +1,5 @@ +module + +public import MarqdoProof.DepTest.Dep + +public theorem use_square (x : Int) : x * x ≥ 0 := dep_square x diff --git a/lean/lake-manifest.json b/lean/lake-manifest.json new file mode 100644 index 0000000..0e8f52f --- /dev/null +++ b/lean/lake-manifest.json @@ -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} diff --git a/lean/lakefile.toml b/lean/lakefile.toml new file mode 100644 index 0000000..d6703a1 --- /dev/null +++ b/lean/lakefile.toml @@ -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" diff --git a/lean/lean-toolchain b/lean/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 diff --git a/src/analysis.rs b/src/analysis.rs new file mode 100644 index 0000000..8e32dd4 --- /dev/null +++ b/src/analysis.rs @@ -0,0 +1 @@ +//! Upstream `marqdo check --emit` integration and strict Analysis validation. diff --git a/src/certificate.rs b/src/certificate.rs new file mode 100644 index 0000000..29cdf6d --- /dev/null +++ b/src/certificate.rs @@ -0,0 +1 @@ +//! Content-addressed proof bundles, manifests and replay (docs/DEVELOPMENT.md §8). diff --git a/src/document.rs b/src/document.rs new file mode 100644 index 0000000..217e5d9 --- /dev/null +++ b/src/document.rs @@ -0,0 +1 @@ +//! Proof-unit selection from the public document AST (docs/DEVELOPMENT.md §3). diff --git a/src/formula.rs b/src/formula.rs new file mode 100644 index 0000000..fddc535 --- /dev/null +++ b/src/formula.rs @@ -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. diff --git a/src/lean.rs b/src/lean.rs new file mode 100644 index 0000000..4183f7e --- /dev/null +++ b/src/lean.rs @@ -0,0 +1 @@ +//! Fixed Lean 4 + Mathlib backend invocation and trusted source generation. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..698083c --- /dev/null +++ b/src/lib.rs @@ -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, + pub hint: Option, +} + +impl Diagnostic { + pub fn error(code: &'static str, message: impl Into) -> Self { + Self { + severity: Severity::Error, + code, + message: message.into(), + span: None, + hint: None, + } + } + + pub fn warning(code: &'static str, message: impl Into) -> 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) -> 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, +} + +impl Failure { + pub fn new(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + hint: None, + } + } + + pub fn with_hint(mut self, hint: impl Into) -> 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 = std::result::Result; + +/// 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 +} diff --git a/src/linker.rs b/src/linker.rs new file mode 100644 index 0000000..25a79fe --- /dev/null +++ b/src/linker.rs @@ -0,0 +1 @@ +//! Controlled multi-entry catalog, exact link resolution and dependency DAG. diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..c7ab35a --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +//! `marqdo-prove` executable: argument handling, presentation and exit codes. + +fn main() { + std::process::exit(2); +} diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..0187715 --- /dev/null +++ b/src/model.rs @@ -0,0 +1 @@ +//! Finite exact-integer program model mapping (docs/DEVELOPMENT.md §7). diff --git a/src/prove.rs b/src/prove.rs new file mode 100644 index 0000000..f22e06a --- /dev/null +++ b/src/prove.rs @@ -0,0 +1 @@ +//! Single orchestration of `check` and `replay`.