diff --git a/CONFORMANCE.md b/CONFORMANCE.md index aaac67cc..a9ef6f65 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -423,12 +423,6 @@ model does not sanction. | --- | --- | --- | | `PM-01` | `build` | Foundry is one Prism model whose architecture, design, features, security, quality and compliance facets are projected from app/product.json and the kernel, and whose quality thresholds are the kernel's own terms | -## proof-reuse - -| ID | Level | Statement | -| --- | --- | --- | -| `FA-85` | `build` | A theorem Lean proved on the same declarations is reused instead of proved again, and only changed theorems go to Lean | - ## proposal-admission | ID | Level | Statement | diff --git a/app/product.json b/app/product.json index 457b1fc8..255445a8 100644 --- a/app/product.json +++ b/app/product.json @@ -826,17 +826,15 @@ }, { "name": "Proof", - "text": "A verdict is decided by the guest from what the tab derived, a theorem proved on the same declarations is reused, and local obligations hold on every request.", + "text": "A verdict is decided by the guest from what the tab derived, Lean's kernel in the tab judges every theorem with no server, and local obligations hold on every request.", "ids": [ - "FA-85", "FA-86", "LL-01", "LL-02" ], "calls": [ "InTabKernel::verdictCode", - "InTabKernelProtocol::dispatchVerdict", - "FoundrySpecification::proofReuseBoundary" + "InTabKernelProtocol::dispatchVerdict" ], "registry": [], "components": [ @@ -1245,11 +1243,11 @@ "text": "A proof is reused for declarations or a toolchain other than the ones Lean checked.", "control": { "name": "Proof reuse by exact inputs", - "text": "A proof is reused only under an address covering the theorem, every declaration it reaches and the exact toolchain.", + "text": "A proof stands only for the exact module bytes the kernel in the tab judged, against the pinned kernel and library; a changed module drops it.", "evidence": [ { "kind": "gate", - "reference": "FA-85 proof-reuse, cargo test in just vv" + "reference": "FA-86 in-tab-kernel-verdict, cargo test in just vv" } ] }, diff --git a/app/src/Features.lex.tex b/app/src/Features.lex.tex index f0c0554f..826beb28 100644 --- a/app/src/Features.lex.tex +++ b/app/src/Features.lex.tex @@ -1219,13 +1219,6 @@ body: "crates/conformance/tests/stateful_application_journeys.rs::stateful_application_journeys_fa_42" } -definition{ - name: testFA85, - parameters: [], - result: String, - body: "crates/conformance/tests/proof_reuse.rs::proof_reuse_fa_85" -} - definition{ name: testFA86, parameters: [], @@ -1636,7 +1629,7 @@ name: featureProof, parameters: [], result: Foundation.Arch::Feature, - body: (record Foundation.Arch::Feature {statement := "Proof (FA-85, FA-86, LL-01, LL-02): A verdict is decided by the guest from what the tab derived, a theorem proved on the same declarations is reused, and local obligations hold on every request.", calls := (cons "InTabKernel::verdictCode" (cons "InTabKernelProtocol::dispatchVerdict" (cons "FoundrySpecification::proofReuseBoundary" (nil String)))), acceptance := (cons "Features::testFA85" (cons "Features::testFA86" (cons "Features::testLL01" (cons "Features::testLL02" (nil String)))))}) + body: (record Foundation.Arch::Feature {statement := "Proof (FA-86, LL-01, LL-02): A verdict is decided by the guest from what the tab derived, Lean's kernel in the tab judges every theorem with no server, and local obligations hold on every request.", calls := (cons "InTabKernel::verdictCode" (cons "InTabKernelProtocol::dispatchVerdict" (nil String))), acceptance := (cons "Features::testFA86" (cons "Features::testLL01" (cons "Features::testLL02" (nil String))))}) } definition{ diff --git a/app/src/FoundrySpecification.lex.tex b/app/src/FoundrySpecification.lex.tex index 3208fad3..6de85de3 100644 --- a/app/src/FoundrySpecification.lex.tex +++ b/app/src/FoundrySpecification.lex.tex @@ -1313,29 +1313,5 @@ result: String, body: "Stateful app parsing and checking require explicit browser approval before source leaves for https://mcp.uor.foundation/. A standalone operation discloses its immutable exact files. A streaming generation session discloses its application, unique turn, captured source identity, current exact files, and permission for subsequent generated module prefixes, repairs and supporting LexLean library modules in that same turn. This preserves incremental previews without treating inference or network-free frame permission as hosted-source consent. It does not permit another turn, application, destination, proof, publication or arbitrary network operation. Approval remains only in document memory, is unavailable offline, and expires within five minutes including active work. The host asserts current source and turn ownership before each request and after completion; only its own successful compare-and-swap commit may advance its expected local source. Denial, Escape, stop, generation cancellation and expiry are typed private refusals. A session remembers refusal without repeatedly prompting. A modal focuses denial and renders source as text; its active stop control explains that abort cannot recall transmitted data or stop remote work. Each parse/check operation further binds its exact file set and permits only one draft write plus matching draft checks or data reads. Requests omit cookies and credentials, reject redirects, use a bounded cancellation-aware deadline, and validate private fixed response failures. Malformed or refused service responses do not become checks or proofs. Replaced, forgotten or cancelled preview work cannot publish late frames. Preview attempts are identified by requested source and permission scope together: a refused attempt suppresses repeat prompts only in that scope, while a fresh scope may retry identical source. Reselecting a previously rendered module cancels and supersedes pending different-source work before reusing its frame, so stale content cannot acquire the selected module's trust. Incomplete replacement source also supersedes pending work without relabeling the last rendered frame. This is a hosted parsing/checking permission boundary, not proof verification, retention enforcement, same-origin caller authentication or overall release acceptance." } - -inductive{ - name: ProofReuseRefusal, - type_parameters: [], - parameters: [], - constructors: [ - {name: proofReuseAbsent, fields: []}, - {name: proofReuseMalformed, fields: []}, - {name: proofReuseAddressMismatch, fields: []}, - {name: proofReuseVerifierMismatch, fields: []}, - {name: proofReuseBytesMismatch, fields: []}, - {name: proofReuseAttestationNotFound, fields: []}, - {name: proofReuseNeededByChange, fields: []}, - {name: proofReuseTrustUnavailable, fields: []}, - {name: proofReuseTrustMismatch, fields: []} - ] -} - -definition{ - name: proofReuseBoundary, - parameters: [], - result: String, - body: "A hosted proof covers theorems, and each theorem has an address: the SHA256 of length-framed fields naming the verifier (server, profile and the profile identity it reports), the local trust policy epoch, the current service trust epoch and the SHA256 addresses of Lean, Lake, leanchecker, LexLean and compiler semantics, every library file sent, each author module's header, the theorem's own declaration and every author declaration it reaches by name, transitively. A declaration of a kind other than structure, inductive, definition or theorem is reached by every theorem. Declarations are compared without their axioms member and with layout whitespace outside strings made canonical; whitespace between tokens and inside strings is kept. After a verified run, each theorem proved is filed under its address with the exact author files sent, their SHA256 digests, the axiom sets Lean observed for it and the declarations it reaches, and the attestation. A filed record stands for a theorem only when it is well formed, names that theorem, its address and verifier equal the current ones, every file hashes to its digest, the files have the current modules' paths and headers, they hold the theorem and every declaration it reaches, and the verifier still reports that exact attestation as verified under the same trust descriptor, covering every recorded file digest. A bare found result is insufficient. Otherwise the refusal is typed and the theorem is proved again; a theorem still to be proved that names a reused one returns it to the run. Reused theorems are removed from the files Lean is sent, their observed axiom sets are applied first, and when every theorem is reused Lean does not run and the result names the attestations it rests on. The reuse schema is prism/proof-reuse/2 and the local policy epoch is foundry/proof-reuse-trust/1. A fresh profile lookup must carry lexlean-mcp/proof-reuse-trust/1 with an epoch and all five toolchain addresses as lowercase SHA256 hex; the two Lean 4.32.1 executable addresses pinned by the current SDK are retired for reuse. Missing, legacy, malformed or retired trust evidence refuses reuse with proofReuseTrustUnavailable; a mismatch refuses reuse with proofReuseTrustMismatch. Every lookup is by the recorded attestation ID. The descriptor is read again before committing a reused result; a change reruns the entire proof without reuse. A newly proved record is filed only when that exact attestation and a fresh descriptor agree, never by stamping an earlier proof with a later toolchain. Unsupported service metadata falls back to full proving, without filing reusable records. This does not block fresh proofs or change their existing acceptance boundary. Records live in the browser's own store; failing reads count as absent and failing writes are dropped. Lookups send only attestation IDs and the profile name, never source. This saves proof time; it is not an independent kernel check, does not prove that the verifier's attestation lookup is sound, does not repair a verifier or establish its soundness, and does not change publication, which proves the whole app again in the SDK image." -} \end{semanticmodule} \end{lexlean} diff --git a/app/src/Security.lex.tex b/app/src/Security.lex.tex index d559235c..01acefb5 100644 --- a/app/src/Security.lex.tex +++ b/app/src/Security.lex.tex @@ -544,7 +544,7 @@ name: modeledControlProofReuseByExactInputs, parameters: [], result: Production.ThreatModel::ModeledControl, - body: (record Production.ThreatModel::ModeledControl {control := "Security::controlProofReuseByExactInputs", name := "Proof reuse by exact inputs", text := "A proof is reused only under an address covering the theorem, every declaration it reaches and the exact toolchain.", evidence := (cons (record Production.ThreatModel::Evidence {kind := (ctor Production.ThreatModel::EvidenceKind.gate), reference := "FA-85 proof-reuse, cargo test in just vv"}) (nil Production.ThreatModel::Evidence))}) + body: (record Production.ThreatModel::ModeledControl {control := "Security::controlProofReuseByExactInputs", name := "Proof reuse by exact inputs", text := "A proof stands only for the exact module bytes the kernel in the tab judged, against the pinned kernel and library; a changed module drops it.", evidence := (cons (record Production.ThreatModel::Evidence {kind := (ctor Production.ThreatModel::EvidenceKind.gate), reference := "FA-86 in-tab-kernel-verdict, cargo test in just vv"}) (nil Production.ThreatModel::Evidence))}) } definition{ diff --git a/crates/conformance/tests/proof_reuse.rs b/crates/conformance/tests/proof_reuse.rs deleted file mode 100644 index 04c3aaf1..00000000 --- a/crates/conformance/tests/proof_reuse.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! The `proof-reuse` suite: one test per scenario in `features/suites/proof-reuse.feature`. -use std::path::PathBuf; -use std::process::Command; - -/// `FA-85`: A theorem Lean proved on the same declarations is reused instead of proved again, and only changed theorems go to Lean -#[test] -fn proof_reuse_fa_85() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(2) - .expect("repository root") - .to_path_buf(); - let output = Command::new("node") - .args(["--test", "--test-reporter=tap"]) - .arg(root.join("studio/tools/proof_reuse.test.mjs")) - .output() - .expect("the locked SDK supplies Node"); - let report = String::from_utf8_lossy(&output.stdout); - assert!( - output.status.success(), - "{report}\n{}", - String::from_utf8_lossy(&output.stderr) - ); - for required in [ - "# tests 12", - "# pass 12", - "# fail 0", - "# cancelled 0", - "# skipped 0", - "# todo 0", - ] { - assert!( - report.lines().any(|line| line == required), - "incomplete oracle: {report}" - ); - } -} diff --git a/features/suites/proof-reuse.feature b/features/suites/proof-reuse.feature deleted file mode 100644 index 99cd71c6..00000000 --- a/features/suites/proof-reuse.feature +++ /dev/null @@ -1,15 +0,0 @@ -Feature: proof-reuse - - @FA-85 @build - Scenario: A theorem Lean proved on the same declarations is reused instead of proved again, and only changed theorems go to Lean - Given an app whose theorems Lean proved on the hosted verifier, with a record filed under each theorem's address and current toolchain-bound trust evidence - When the app is proved again unchanged, with one theorem edited, or with a definition some theorems reach edited - Then an unchanged app is proved with no Lean run and the axiom sets Lean observed - And only the theorems whose own or reached declarations changed are sent to Lean, in one run - And a record whose address, verifier, bytes, headers or attestation do not re-derive is refused with a typed reason and its theorem is proved again - And an unreadable or failing store never fails a proof - And a missing trust epoch, a retired toolchain, legacy records or a bare found response never authorize reuse - And changing a toolchain address or the trust epoch with an unchanged profile re-proves every theorem - And the exact attestation must cover every recorded digest under the current trust descriptor - And a verifier change during admission or a partial proof reruns the whole proof without reuse - And a completed proof is never filed under a toolchain that did not attest it diff --git a/model/ids.toml b/model/ids.toml index ddee42ad..638daeff 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -832,12 +832,6 @@ level = "build" suite = "application-shape-authority" statement = "Application shape edits and transitions retain one source-bound authority and cannot obtain proof standing from authored files" -[[id]] -id = "FA-85" -level = "build" -suite = "proof-reuse" -statement = "A theorem Lean proved on the same declarations is reused instead of proved again, and only changed theorems go to Lean" - [[id]] id = "FA-86" level = "build" diff --git a/studio/proof/PrismLive/Regions.lean b/studio/proof/PrismLive/Regions.lean index ff98c995..0c77583b 100644 --- a/studio/proof/PrismLive/Regions.lean +++ b/studio/proof/PrismLive/Regions.lean @@ -740,3 +740,56 @@ theorem ruleJudge_sound (P : List Nat) (p : Property) (hc : wordsCheck P p = tru exact regionCheck_sound _ _ _ _ hreg p (by simp) x hbox end PrismLive.Kernel + +/-! +# A stateful app's promises, for every app the app notation writes + +The notation (shell/live/notation.mjs) states five kinds of promise. Each one's proof has the same shape for +every app, so it is proved here once. The tab writes an app's own definitions and theorems as kernel terms and +proves each theorem by applying one lemma below to that app's terms; Lean's kernel, in the tab, judges it. +-/ + +namespace PrismLive.Tables + +theorem blt_self (n : Nat) : Nat.blt n n = false := by + cases h : Nat.blt n n + · rfl + · exact absurd (Nat.le_of_ble_eq_true h) (Nat.lt_irrefl n) + +/-- A press that a guard refuses leaves the state as it was, so its revision does not move. -/ +theorem refused {α : Type} (rev : α → Nat) (s t : α) (bad g : Bool) (h : bad = true → g = false) : + (bad && Nat.blt (rev s) (rev (if g = true then t else s))) = false := by + cases bad + · rfl + · simp [h rfl, blt_self] + +/-- A guard that fails fails the conjunction it starts. -/ +theorem left {a b c : Bool} (h : a = true → b = false) (ha : a = true) : (b && c) = false := by + simp [h ha] + +/-- A guard that fails fails the conjunction it ends. -/ +theorem right {a b c : Bool} (h : a = true → c = false) (ha : a = true) : (b && c) = false := by + simp [h ha] + +/-- A value outside `1..m` (an empty or too long text, an unmade choice) fails its guard. -/ +theorem outside (n m : Nat) (h : (Nat.beq n 0 || Nat.ble (m + 1) n) = true) : + (Nat.ble 1 n && Nat.ble n m) = false := by + simp only [Bool.or_eq_true, Nat.beq_eq, Nat.ble_eq] at h + cases h1 : Nat.ble 1 n <;> cases h2 : Nat.ble n m <;> simp_all [Nat.ble_eq] <;> omega + +/-- A full table fails the guard that it has room. -/ +theorem full (n m : Nat) (h : Nat.ble m n = true) : Nat.blt n m = false := by + simp only [Nat.ble_eq] at h + cases h1 : Nat.blt n m <;> simp_all [Nat.blt_eq] <;> omega + +/-- A press from an out-of-date screen leaves the state as it was, so its revision does not move. -/ +theorem stale {α : Type} (rev : α → Nat) (s x : α) (seen : Nat) : + ((Nat.blt seen (rev s) || Nat.blt (rev s) seen) && + (Nat.blt (rev (if Nat.beq seen (rev s) = true then x else s)) (rev s) || + Nat.blt (rev s) (rev (if Nat.beq seen (rev s) = true then x else s)))) = false := by + cases h : Nat.beq seen (rev s) + · simp [blt_self] + · have : seen = rev s := Nat.eq_of_beq_eq_true h + subst this; simp [Nat.blt_eq] + +end PrismLive.Tables diff --git a/studio/shell/host.js b/studio/shell/host.js index 377cb68f..084f0e09 100644 --- a/studio/shell/host.js +++ b/studio/shell/host.js @@ -715,11 +715,11 @@ function sendLive(appId) { const appApps = new Set(); // apps whose preview is a running module, not a projection const postApp = (appId, message) => { const m = { ...message, theme: themeOf() }; for (const [win, app] of liveWindows) { if (win.closed) liveWindows.delete(win); else if (app === appId) win.postMessage(m, "*"); } }; let appFrames = null; -const appFramesReady = () => appFrames || (appFrames = fetch(new URL("live/v2/Model.json", BASE)).then((r) => { if (!r.ok) throw new Error("live/v2/Model.json answered " + r.status); return r.json(); }).then((model) => appShape.appLive({ post: postApp, library: { "Foundation.View.Browser.V1.Model": model } })).catch(error => { appFrames = null; throw error; })); -// The checker for a stateful app (shell/live/v2/check.mjs), with the library source it sends. -let appLibrary = null; -const readEngine = async (p) => { const r = await fetch(new URL("live/v2/" + p, BASE)); if (!r.ok) throw new Error("live/v2/" + p + " answered " + r.status); return r.text(); }; -const checkAppModule = (module, options = {}) => appShape.checkApp(module, appLibrary || (appLibrary = appShape.checkLibrary(readEngine).catch((e) => { appLibrary = null; throw e; })), globalThis.fetch, options); +let appModelLoad = null; +const appModel = () => appModelLoad || (appModelLoad = fetch(new URL("live/v2/Model.json", BASE)).then((r) => { if (!r.ok) throw new Error("live/v2/Model.json answered " + r.status); return r.json(); }).catch((error) => { appModelLoad = null; throw error; })); +const appFramesReady = () => appFrames || (appFrames = appModel().then((model) => appShape.appLive({ post: postApp, library: { "Foundation.View.Browser.V1.Model": model } })).catch(error => { appFrames = null; throw error; })); +// The checker for a stateful app runs in this tab (shell/live/app.mjs checkApp): it reads, it runs, its theorems can be stated. +const checkAppModule = async (module) => appShape.checkApp(module, { "Foundation.View.Browser.V1.Model": await appModel() }); function pushApp(appId, module, trust = "draft", options = {}) { assertGenerationActive(options.signal); appApps.add(appId); @@ -1472,16 +1472,14 @@ async function approveApp(appId, app, options = {}) { }, }; } -// Lean proves the module on the hosted verifier; the kernel moves the phase on its attestation or its -// refusal. A proof whose module changed meanwhile is dropped: it is about other bytes. The module Lean -// verified (its axiom sets as Lean observed them) becomes the stored one. +// Lean proves the module with its kernel in this tab (prism.js proveModule); the Forge kernel moves the phase on its +// verdict. A proof whose module changed meanwhile is dropped: it is about other bytes. async function proveApp(appId, sourceKappa, source, onWait, options = {}) { const current = await appStateOf(appId); if (!current?.state || current.state.sourceKappa !== sourceKappa || current.state.phase !== "proving" || current.source !== source || (options.expectedState && JSON.stringify(current.expectedState) !== JSON.stringify(options.expectedState))) return null; - const library = await (appLibrary || (appLibrary = appShape.checkLibrary(readEngine).catch((error) => { appLibrary = null; throw error; }))); - let proved = source; + const model = await appModel(), proved = source; let submitted = false; - const result = await prism.proveFiles(async (axioms) => { proved = appShape.withAxioms(source, axioms); return appShape.proofFiles(proved, library); }, { onWait, store: { get: (key) => get("refs", key), put: (key, value) => put("refs", key, value) }, beforeSubmit: () => { options.beforeSubmit?.(); submitted = true; } }).catch((e) => { + const result = await prism.proveModule(source, appShape.semanticData(source, { theorems: true }), model.declarations, { guest: kernelReady, beforeSubmit: () => { options.beforeSubmit?.(); submitted = true; } }).catch((e) => { if (options.beforeSubmit && !submitted) throw e; return { ok: false, error: String((e && e.message) || e) }; }); @@ -1783,7 +1781,7 @@ async function chatTurn(chatId, intent) { const applied = await applyPrismTags(appId, tags, { signal: abort.signal, source: projectSource, onCommit }); let changed = applied.changed; const turn = full; - const spec = (await appAfterTurn(appId, turn, { signal: abort.signal, source: applied.source, onCommit, check: false })) || await rulesAfterTurn(appId, turn, [], { signal: abort.signal, source: applied.source, onCommit }); + const spec = (await appAfterTurn(appId, turn, { signal: abort.signal, source: applied.source, onCommit })) || await rulesAfterTurn(appId, turn, [], { signal: abort.signal, source: applied.source, onCommit }); const patchRefusals = []; for (const match of full.matchAll(/([\s\S]*?)<\/dyad-spec-patch>/g)) { assertGenerationActive(abort.signal); diff --git a/studio/shell/kernel/lean/library.ndjson.gz b/studio/shell/kernel/lean/library.ndjson.gz index 10579deb..1224157a 100644 Binary files a/studio/shell/kernel/lean/library.ndjson.gz and b/studio/shell/kernel/lean/library.ndjson.gz differ diff --git a/studio/shell/kernel/lean/manifest.json b/studio/shell/kernel/lean/manifest.json index aed51354..51c0e8f9 100644 --- a/studio/shell/kernel/lean/manifest.json +++ b/studio/shell/kernel/lean/manifest.json @@ -17,7 +17,26 @@ "Bool.true", "Bool.false", "List.nil", - "List.cons" + "List.cons", + "PrismLive.Tables.refused", + "PrismLive.Tables.left", + "PrismLive.Tables.right", + "PrismLive.Tables.outside", + "PrismLive.Tables.full", + "PrismLive.Tables.stale", + "Prod.mk", + "Prod.fst", + "Prod.snd", + "String.toUTF8", + "ByteArray.size", + "Nat.add", + "Nat.beq", + "Nat.ble", + "Nat.blt", + "Bool.and", + "Bool.or", + "ite", + "instDecidableEqBool" ] }, "glue": { @@ -32,17 +51,17 @@ }, "library": { "file": "library.ndjson.gz", - "sha256": "691abbcc02f300effdabe36eeb48b5eb0859d73047631200231393a96cfcc5d1", - "bytes": 7754251 + "sha256": "a22cb8e581310c1c4a03e120e277dd99d37c66f8159188e866f68177836aa560", + "bytes": 7834171 }, "binding": { "schema": "prism/in-tab-library-binding/1", "lean": "f054605aea4b840552cca2e725580bffd1e1b704", "kernel": "4b48480b9c03ae4aa3bf1a37256b59bff2d41d6cf452a2f8aa9de41a28ccd118", "loader": "3f482f95c28fb0c74027552d6c4519f8916e48cd1d5b0bd202f318ca8c027a4a", - "library": "691abbcc02f300effdabe36eeb48b5eb0859d73047631200231393a96cfcc5d1", - "declarations": 2097, - "sentToTheKernel": 1916, + "library": "a22cb8e581310c1c4a03e120e277dd99d37c66f8159188e866f68177836aa560", + "declarations": 2113, + "sentToTheKernel": 1932, "judgedBy": "check_whole, every declaration, in this kernel" } } diff --git a/studio/shell/live/app.mjs b/studio/shell/live/app.mjs index 5f64c486..de2e4e85 100644 --- a/studio/shell/live/app.mjs +++ b/studio/shell/live/app.mjs @@ -9,13 +9,10 @@ import { loadProject, NIL, cons } from "./v2/interp.mjs"; import { describe, fieldValue } from "./v2/render.mjs"; import * as notation from "./notation.mjs"; -import { check as hostedCheck, loadLibrary, prepare } from "./v2/check.mjs"; +import { moduleTerms } from "../prism.js"; import { isStatefulModule as isAppShape } from '../application-shape.mjs'; -import { reuseSentence } from "../prism/proof-reuse.mjs"; export { isAppShape }; -import { withHostedSourcePermission } from "../hosted-source-permission.mjs"; -const PROFILE = "prism-app"; const MODEL = "Foundation.View.Browser.V1.Model"; const OPEN = "\\begin{semanticmodule}", CLOSE = "\n\\end{semanticmodule}\n\\end{lexlean}\n"; const NEEDED = ["State", "catalogue", "initial", "view"]; @@ -24,9 +21,9 @@ const NEEDED = ["State", "catalogue", "initial", "view"]; export const STATE_PATH = "prism/app.json"; /** What the chat shows for a state. It claims no more than the state holds. */ export function card(state) { - if (state.phase === "proving") return "**App** · Lean is proving\n\nLean is checking this app's properties on the hosted verifier."; - if (state.phase === "proved") return "**App** · proved by Lean\n\nLean proved " + (state.theorems || []).length + " theorem" + ((state.theorems || []).length === 1 ? "" : "s") + " about this app. Attestation `" + String(state.proof && state.proof.attestation_id || "").slice(0, 16) + "…`. It cannot be published yet."; - if (state.phase === "checked") return "**App** · checked\n\nThe checker accepts this app's module. It is not proved yet, and it cannot be published yet."; + if (state.phase === "proving") return "**App** · Lean is proving\n\nLean's kernel is checking this app's properties in this browser."; + if (state.phase === "proved") return "**App** · proved by Lean\n\nLean's kernel, in this browser, accepted " + (state.theorems || []).length + " theorem" + ((state.theorems || []).length === 1 ? "" : "s") + " about this app. It cannot be published yet."; + if (state.phase === "checked") return "**App** · checked\n\nThis browser read and ran the app's module and can state every property it makes to Lean. It is not proved yet, and it cannot be published yet."; if (state.issues && state.issues.length) return "**App** · not checked\n\n" + state.issues.map((i) => "- " + i).join("\n") + "\n\nIt still runs in the preview as far as it can. Ask me to fix the module."; return CARD + (state.unchecked ? "\n\nIt could not be checked just now: " + state.unchecked : ""); } @@ -44,40 +41,18 @@ export function promisesOf(module) { if (!d) return []; return [...d.source.slice(d.source.indexOf("body:")).matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1].replace(/\\(.)/g, "$1")); } -/** The module with the axiom sets Lean named ({ theorem: "[a, b]" }) written into those declarations. */ -export function withAxioms(module, axioms) { - let text = String(module); - for (const [name, set] of Object.entries(axioms || {})) { - const d = splitDeclarations(text).declarations.find((x) => x.name === name); - if (!d) continue; - const fixed = /axioms:\s*\[[^\]]*\]/.test(d.source) ? d.source.replace(/axioms:\s*\[[^\]]*\]/, "axioms: " + set) : d.source.replace(/\s*\}$/, ",\n axioms: " + set + "\n}"); - text = text.replace(d.source, fixed); - } - return text; -} -/** - * The files a proof of this module is asked on, and which of them must come back verified. The - * library module goes with its title's words replaced, as for a check: the hosted lexicon lacks them. - * So the attestation is about this draft, whose declarations are the module's and the library's own. - */ -export function proofFiles(module, library) { - const prepared = prepare(String(module).trim() + "\n", { library }); - return { files: prepared.files, entrypoints: prepared.files.filter((f) => prepared.origin[f.path] === "author").map((f) => f.path) }; -} /** What the chat says while Lean works, and when it ends. */ -export const provingMessage = (count) => "Proving " + count + " propert" + (count === 1 ? "y" : "ies") + " of this app with Lean on the hosted verifier. This can take ten minutes or more. The preview keeps working meanwhile."; +export const provingMessage = (count) => "Proving " + count + " propert" + (count === 1 ? "y" : "ies") + " of this app with Lean's kernel, in this browser."; export function proofMessage(result) { if (!result.ok) { - // Lean refusing a theorem (a verification diagnostic, LLV…) is about the app. Anything else, a - // verifier that ran out of room or time or did not answer, is about the verifier, and says so. - const refused = (result.diagnostics || []).some((d) => /^LLV/.test(String(d.code || ""))); + // Lean's kernel refusing a theorem is about the app. Anything else, a kernel that did not load or run, is not. const why = String(result.error || "Lean refused the proof").replace(/\.+$/, ""); - return refused - ? "**Not proved.** Lean refused it: " + why + ". The app is back to checked. Ask me to fix the property, or to drop it." - : "**Not proved.** The verifier could not run the proof: " + why + ". This says nothing about the app. It is back to checked; reply approve to try again."; + return /^Lean's kernel refused/.test(why) + ? "**Not proved.** " + why + ". The app is back to checked. Ask me to fix the property, or to drop it." + : "**Not proved.** Lean's kernel could not run the proof: " + why + ". This says nothing about the app. It is back to checked; reply approve to try again."; } const lines = result.theorems.map((t, i) => "- " + (result.promises[i] ? result.promises[i] + "\n Lean proved: " : "Lean proved: ") + "`" + t.statement + "`"); - return "**Proved by Lean.** " + result.theorems.length + " theorem" + (result.theorems.length === 1 ? "" : "s") + " about this app, for every state, in " + result.seconds + " s." + reuseSentence(result.theorems.length, result.record.reused) + " Attestation `" + result.record.attestation_id.slice(0, 16) + "…`.\n\n" + lines.join("\n") + "\n\nA sentence can say more than its theorem: the statement is what is proved. The app cannot be published yet."; + return "**Proved by Lean.** Lean's kernel, in this browser, accepted " + result.theorems.length + " theorem" + (result.theorems.length === 1 ? "" : "s") + " about this app, for every state, in " + result.seconds + " s.\n\n" + lines.join("\n") + "\n\nA sentence can say more than its theorem: the statement is what is proved. The app cannot be published yet."; } /** One line a person or a model can act on. */ @@ -85,22 +60,22 @@ export const issueLine = (d) => (d.line ? "Line " + d.line + ": " : "") + d.mess /** What a model is asked when the checker refuses its module: its own module, the checker's words, the whole module again. */ export const repairPrompt = (issues) => "The checker refused your module:\n" + issues.map((i) => "- " + i).join("\n") + "\nWrite the whole module again, in one block, with that fixed and nothing else changed. Write nothing but the block."; -/** The library the checker sends with a module. `readText(path)` reads a file beside the checker (shell/live/v2/). */ -export const checkLibrary = (readText) => loadLibrary(readText); /** - * Checks a module on the hosted service. Resolves { ok, issues, ms }; `issues` are lines about the - * module as written. It checks; it does not prove. Rejects when the service cannot be reached. + * Checks a module in this tab: it reads, it runs (its first frame draws), and every theorem it states can be put to + * Lean's kernel as a term. Resolves { ok, issues, ms }. It checks; it does not prove. `library` holds the view model. */ -export async function checkApp(module, library, fetchImpl = globalThis.fetch, options = {}) { - const t0 = performance.now(), source = String(module).trim() + "\n", loaded = await library; - const files = prepare(source, { library: loaded }).files; - const result = await withHostedSourcePermission({ purpose: "check", files }, async (permittedFetch) => { - let failure; - try { return await hostedCheck(source, { library: loaded, fetch: async (...args) => { try { return await permittedFetch(...args); } catch (error) { failure = error; throw error; } } }); } - catch (error) { throw failure || error; } - }, options, fetchImpl); - const issues = result.ok ? [] : result.diagnostics.filter((d) => d.severity !== "warning").map(issueLine); - return { ok: !!result.ok, issues: result.ok ? [] : issues.length ? issues.slice(0, 8) : ["The checker refused the module and gave no reason."], ms: Math.round(performance.now() - t0) }; +export async function checkApp(module, library) { + const t0 = performance.now(), issues = []; + try { + const data = semanticData(module, { theorems: true }); + createApp(data, library).frame(); + const known = new Set([...data.declarations, ...Object.values(library).flatMap((m) => m.declarations || [])].map((d) => d.name)); + for (const d of data.declarations) JSON.stringify(d, (k, x) => { if (x && x.kind === "named" && !known.has(x.member.name)) issues.push(d.name + ": no type " + x.member.name); return x; }); + const terms = moduleTerms(data, Object.values(library).flatMap((m) => m.declarations || [])); + if (!terms.theorems.length && !terms.refused.length) issues.push("The module states no properties."); + for (const r of terms.refused) issues.push(r.theorem + ": " + r.reason); + } catch (e) { issues.push(String((e && e.message) || e).slice(0, 200)); } + return { ok: !issues.length, issues: issues.slice(0, 8), ms: Math.round(performance.now() - t0) }; } /** Where a stateful app's module is kept in its project. */ @@ -175,7 +150,7 @@ export function wholePrefix(module) { * left out: the preview runs definitions, and Lean proves the theorems from the source. */ const OPS = { "+": "add", "&&": "and", "||": "or", "=?": "beq", "<=?": "ble", "|::|<=\?|<\?|=\?|&&|\|\||[()[\]{},:|+=]|[A-Za-z_][\w.]*(?:::[\w.]+)?|\d+)/y; -export function semanticData(source) { +export function semanticData(source, { theorems: withTheorems = false } = {}) { const body = String(source).match(/\\begin\{semanticmodule\}([\s\S]*)\\end\{semanticmodule\}/); if (!body) throw new Error("no semantic module"); const t = []; TOKEN.lastIndex = 0; let m; @@ -209,12 +184,13 @@ export function semanticData(source) { }; const list = (item) => { const out = []; take("["); while (peek() !== "]") { out.push(item()); if (peek() === ",") next(); } take("]"); return out; }; const binder = () => { const name = next(); take(":"); return { name, type: type() }; }; - const declarations = []; + const declarations = [], theorems = []; while (i < t.length) { const kind = next(); take("{"); const d = { kind }; while (peek() !== "}") { const key = next(); take(":"); - if (kind === "theorem") { let depth = 0; while (!(depth === 0 && (peek() === "," || peek() === "}"))) { const s = next(); if ("([{".includes(s)) depth++; else if (")]}".includes(s)) depth--; } } + if (kind === "theorem" && key === "statement") d.statement = term(); + else if (kind === "theorem" && key !== "name" && key !== "parameters") { let depth = 0; while (!(depth === 0 && (peek() === "," || peek() === "}"))) { const s = next(); if ("([{".includes(s)) depth++; else if (")]}".includes(s)) depth--; } } else if (key === "name" || key === "recursive_argument") d[key] = next(); else if (key === "parameters") d.parameters = list(binder); else if (key === "type_parameters") d.type_parameters = list(next); @@ -225,9 +201,10 @@ export function semanticData(source) { if (peek() === ",") next(); } take("}"); - if (kind !== "theorem") declarations.push(d); + (kind === "theorem" ? theorems : declarations).push(d); } - return { spec: "lexlean/semantic-module/2", declarations }; + // The theorems' statements are this reader's own: LexLean's data form leaves them out. + return withTheorems ? { spec: "lexlean/semantic-module/2", declarations, theorems } : { spec: "lexlean/semantic-module/2", declarations }; } const list = (items) => items.reduceRight((tail, head) => cons(head, tail), NIL); diff --git a/studio/shell/live/v2/check.mjs b/studio/shell/live/v2/check.mjs deleted file mode 100644 index e8e85904..00000000 --- a/studio/shell/live/v2/check.mjs +++ /dev/null @@ -1,138 +0,0 @@ -// Checks a spec that imports PrismPM's library on the hosted LexLean service, from a browser tab or Node. -// -// The hosted `prism-app` profile holds 2 of the SDK's 141 prism.arch title phrases, so it refuses a module whose -// \title uses another one (LLL1004). For checking only, each such phrase inside a \title is replaced by -// "Text application model", a phrase both lexicons hold with the same category, frame, arity and features. -// Nothing outside the title's braces changes, the data form does not carry the title, and diagnostics are mapped -// back to the source as written. The verdict is "checked", never "proved": proof still runs on the real files. - -export const ENDPOINT = "https://mcp.uor.foundation/"; -export const PROFILE = "prism-app"; -export const SUBSTITUTE = "Text application model"; -// Phrases the hosted prism.arch already holds; a title made of these is sent as written. -const HOSTED_TITLES = new Set(["Text application model", "Bounded byte buffer"]); - -export const modulePath = (name) => `src/${name.split(".").join("/")}.lex.tex`; -export const moduleName = (source) => source.match(/^\s*\\begin\{lexlean\}\{([^}]+)\}/)?.[1]; -const imports = (source) => [...source.matchAll(/\\importmodule\{([^}]+)\}/g)].map((m) => m[1]); -const utf8 = (s) => new TextEncoder().encode(s).length; - -// Reads library.json and the library sources it names. `readText(path)` resolves a path relative to this folder. -export async function loadLibrary(readText) { - const manifest = JSON.parse(await readText("library.json")); - const modules = {}; - await Promise.all(Object.entries(manifest.modules).map(async ([name, path]) => { modules[name] = await readText(path); })); - return { image: manifest.image, titles: manifest.titles, modules }; -} - -// Replaces SDK-only title phrases inside the module's one-line \title. Returns the text sent and the edits made, -// each with its line, its byte offset in the original and both lengths, so positions can be mapped back. -export function retitle(source, titles) { - const m = source.match(/^\\title\{([^}\n]*)\}$/m); - if (!m) return { content: source, edits: [] }; - const sdkOnly = titles.filter((t) => !HOSTED_TITLES.has(t)).sort((a, b) => b.length - a.length); - const title = m[1], open = m.index + "\\title{".length; - const line = source.slice(0, m.index).split("\n").length; - const edits = []; - let out = "", i = 0; - while (i < title.length) { - const atWord = i === 0 || title[i - 1] === " "; - const hit = atWord && sdkOnly.find((t) => title.startsWith(t, i) && (i + t.length === title.length || title[i + t.length] === " ")); - if (hit) { - edits.push({ line, byte: utf8(source.slice(0, open + i)), column: utf8(source.slice(m.index, open + i)) + 1, from: hit.length, to: SUBSTITUTE.length }); - out += SUBSTITUTE; i += hit.length; - } else out += title[i++]; - } - return { content: source.slice(0, open) + out + source.slice(open + title.length), edits }; -} - -// Builds the files to send: the spec, any extra modules of the author's, and the library modules they import, -// transitively. Sending every imported library module also replaces the hosted profile's own copies of them. -export function prepare(spec, { library, extras = [] }) { - const own = [spec, ...extras].map((source) => ({ name: moduleName(source), source })); - for (const m of own) if (!m.name) throw Object.assign(new Error("a module has no \\begin{lexlean}{Name} line"), { code: "HC_NO_MODULE" }); - const ownNames = new Set(own.map((m) => m.name)); - const needed = new Set(), queue = own.flatMap((m) => imports(m.source)); - while (queue.length) { - const name = queue.pop(); - if (ownNames.has(name) || needed.has(name) || !(name in library.modules)) continue; - needed.add(name); queue.push(...imports(library.modules[name])); - } - const files = [], edits = {}, origin = {}; - const add = (name, source, kind) => { - const path = modulePath(name), r = retitle(source, library.titles); - files.push({ path, content: r.content }); edits[path] = r.edits; origin[path] = kind; - }; - for (const name of [...needed].sort()) add(name, library.modules[name], "library"); - for (const m of own) add(m.name, m.source, "author"); - return { files, edits, origin, entry: own[0].name, modules: own.map((m) => m.name) }; -} - -// Maps one hosted diagnostic back to the text as written. Lines never move: only the title line's text changes. -// Positions after an edit shift by its length difference; positions inside an edit point at the original phrase. -export function mapDiagnostic(d, prepared) { - const p = d.primary ?? {}; - const edits = prepared.edits[p.path] ?? []; - // `at` gives an edit's start in the original; a sent position is mapped by undoing the edits before it. - const back = (pos, list, at) => { - let shift = 0; - for (const e of list) { - const start = at(e) + shift; - if (pos >= start + e.to) shift += e.to - e.from; - else if (pos > start) return at(e) + Math.min(pos - start, e.from); - else break; - } - return pos - shift; - }; - const byte = (b) => back(b, edits, (e) => e.byte); - const column = (line, c) => back(c, edits.filter((e) => e.line === line), (e) => e.column); - return { - code: d.code, severity: d.severity, message: d.message, - origin: prepared.origin[p.path] ?? "hosted", path: p.path, - line: p.line_start, column: p.column_start == null ? undefined : column(p.line_start, p.column_start), - endLine: p.line_end, endColumn: p.column_end == null ? undefined : column(p.line_end, p.column_end), - byteStart: p.byte_start == null ? undefined : byte(p.byte_start), byteEnd: p.byte_end == null ? undefined : byte(p.byte_end), - }; -} - -let rpc = 0; -async function call(fetchFn, endpoint, name, args) { - let res; - try { - res = await fetchFn(endpoint, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++rpc, method: "tools/call", params: { name, arguments: args } }) }); - } catch (e) { throw Object.assign(new Error(`hosted service unreachable: ${e.message}`), { code: "HC_UNREACHABLE" }); } - if (!res.ok) throw Object.assign(new Error(`hosted service answered HTTP ${res.status}`), { code: "HC_HTTP" }); - const body = await res.json(); - if (body.error) { - const message = body.error.message ?? JSON.stringify(body.error); - // The service limits calls per client; a corpus run of about fifty calls, repeated, reaches it. - throw Object.assign(new Error(message), { code: /rate limit/i.test(message) ? "HC_RATE_LIMITED" : "HC_RPC" }); - } - return { payload: body.result.structuredContent ?? JSON.parse(body.result.content[0].text), refused: !!body.result.isError }; -} - -// Returns { ok, diagnostics, data, draft, ms }. `data` maps each of the author's modules to its data form, when it checked. -// `onVerdict(ok, diagnostics)` is called as soon as the verdict is known, before the data form is fetched. -export async function check(spec, { library, extras = [], endpoint = ENDPOINT, fetch: fetchFn = globalThis.fetch.bind(globalThis), onVerdict } = {}) { - const now = () => performance.now(), ms = {}; - const prepared = prepare(spec, { library, extras }); - let t = now(); - const written = await call(fetchFn, endpoint, "lexlean_draft_write", { profile: PROFILE, files: prepared.files }); - if (written.refused || !written.payload.draft) throw Object.assign(new Error(`draft refused: ${JSON.stringify(written.payload)}`), { code: "HC_DRAFT_REFUSED" }); - const draft = written.payload.draft; - ms.write = now() - t; t = now(); - const checked = (await call(fetchFn, endpoint, "lexlean_check", { project: draft, all: true })).payload; - ms.check = now() - t; - const diagnostics = (checked.diagnostics ?? []).map((d) => mapDiagnostic(d, prepared)); - onVerdict?.(!!checked.success, diagnostics); - if (!checked.success) return { ok: false, diagnostics, draft, ms }; - t = now(); - const data = {}; - await Promise.all(prepared.modules.map(async (name) => { - const r = await call(fetchFn, endpoint, "lexlean_draft_read", { draft, path: modulePath(name), view: "data" }); - if (r.refused || !r.payload.data) throw Object.assign(new Error(`data form refused for ${name}`), { code: "HC_DATA_REFUSED" }); - data[name] = r.payload.data; - })); - ms.data = now() - t; - return { ok: true, diagnostics, data, draft, entry: prepared.entry, ms }; -} diff --git a/studio/shell/live/v2/library.json b/studio/shell/live/v2/library.json deleted file mode 100644 index 3270e957..00000000 --- a/studio/shell/live/v2/library.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "image": "ghcr.io/uor-foundation/prismpm-sdk-candidate@sha256:cd3b47d7a370c4a26b8285f5e9c3bb15e639973c55505c3809ddbe55352fea58", - "titles": [ - "Application layer model", - "Architecture description model", - "Bounded byte buffer", - "Bounded integer codec", - "Browser account genesis", - "Browser account genesis wire format", - "Browser application model", - "Browser application resource budget", - "Browser credential custody", - "Browser credential custody wire format", - "Browser effect host corpus", - "Browser effect host model", - "Browser effect wire format", - "Browser network bootstrap", - "Browser network bootstrap corpus", - "Browser operation journal", - "Browser operation journal wire format", - "Browser session journal", - "Browser session journal observation", - "Browser session journal projection", - "Browser session journal recovery", - "Browser session journal reservation", - "Browser session journal reservation wire format", - "Browser session journal retention", - "Browser session journal retention wire format", - "Browser session journal wire format", - "Browser session recovery frame layout", - "Browser signed context", - "Browser signed context wire format", - "Browser source session", - "Browser source session wire format", - "Browser view design catalogue", - "Browser view design wire format", - "Browser view model", - "Browser view semantics", - "Browser view semantics wire format", - "Browser view wire format", - "Browser workspace command", - "Browser workspace command corpus", - "Browser workspace corpus", - "Browser workspace envelope", - "Browser workspace envelope corpus", - "Browser workspace journal", - "Browser workspace journal corpus", - "Browser workspace query", - "Browser workspace query corpus", - "Browser workspace reducer", - "Browser-resident system model", - "CBOR primitive codec", - "CBOR primitive codec corpus", - "Checked integer arithmetic", - "Control coverage corpus", - "Control coverage policy", - "Core WebAssembly contract", - "Elliptic curve arithmetic wire format", - "Elliptic curve field arithmetic", - "Guest runtime primitive", - "Hologram application directory", - "Hologram application manifest", - "Hologram browser wire format", - "Hologram capability request", - "Hologram container format", - "Hologram content identity", - "Hologram model validation", - "Hologram physical archive", - "Hologram portable view bundle", - "Hologram primary wire format", - "Hologram source manifest", - "Hologram wire corpus", - "Hologram wire encoding", - "Mailbox admission", - "Mailbox admission corpus", - "Native library model", - "OPM link", - "OPM link kind", - "OPM state", - "OPM thing", - "OPM thing kind", - "OPM zoom", - "Organization administration", - "Organization administration corpus", - "Organization lifecycle", - "Organization lifecycle corpus", - "Portable error outcome", - "Portable unit value", - "Portable view model", - "Prism hologram extension", - "Product quality model", - "Production interface model", - "Production operations model", - "Production runtime profile", - "Production runtime target model", - "Production system manifest validation", - "Production system model", - "Production system validation", - "Production system validation corpus", - "Production validation relation", - "Proof key for code exchange", - "Publication admission model", - "Publication admission wire format", - "Publication linkage model", - "Publication linkage wire format", - "Saved recovery code", - "Saved recovery code corpus", - "Security risk model", - "Standard library system model", - "Text application model", - "UML component", - "UML connector", - "UML lifeline", - "UML message", - "UML message kind", - "UML state", - "UML transition", - "Unicode text codec", - "View interaction model", - "View projection model", - "Workspace interaction corpus", - "Workspace interaction model", - "architectural component", - "architectural component kind", - "architectural concern", - "architectural edge", - "architectural edge kind", - "architecture model kind", - "architecture view", - "architecture view class", - "architecture viewpoint", - "architecture viewpoint class", - "design diagram", - "design view", - "feature", - "fixed standards profile", - "flat validation input", - "journey", - "normalized feature model", - "normalized hologram model", - "stakeholder", - "standards reference", - "system process", - "system state" - ], - "modules": { - "Foundation.View.Browser.V1.Model": "Model.lex.tex" - } -} diff --git a/studio/shell/prism.js b/studio/shell/prism.js index 76754ce4..436f2302 100644 --- a/studio/shell/prism.js +++ b/studio/shell/prism.js @@ -24,7 +24,6 @@ import { PROMPT_RULES, facetLine, parsePromptTag, facetsOf } from "./prism/build // The app's prompt parts, read and projected where the rules are (host.js rulesAfterTurn). export { parsePromptTag, facetsOf }; import { verdictWithGuest, verdictAddressWords, verdictAxiomSet } from "./in-tab-verdict-codec.mjs"; -import { KEY_PREFIX, REFUSAL, trustDescriptor, sameVerifier, attests, addresses, admit, headersOf, record as reuseRecord, theoremsOf, without } from "./prism/proof-reuse.mjs"; // prism-code's checker (prism/spec.mjs, byte for byte) keeps a spec to 24 rules, because its proofs are one // linear_arithmetic theorem per guarantee over the whole first-match chain. Past that, Forge checks the @@ -36,9 +35,6 @@ export const PROVE_RULES_MAX = 24; if (!globalThis.Buffer) globalThis.Buffer = { from: (bytes) => ({ toString: (encoding) => { if (encoding !== "hex") throw new Error("only hex"); return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } }) }; const enc = new TextEncoder(); -const HOSTED = "https://mcp.uor.foundation/"; -const PROTOCOL = "2026-07-28"; -const PROFILE = "prism-app"; // ---- what the model is told // The rules are written as one JSON spec (prism/spec/1), the app's only input. Forge renders the app's @@ -440,40 +436,12 @@ export function checkSpec(raw) { return { ok: issues.length === 0, spec, issues, notes, vectors: vectors.length, module: issues.length ? null : moduleSource(spec, vectors.length) }; } -// ---- the proof: the LexLean project prism-code sends, proved on the hosted verifier +// ---- shell files, as text async function shellText(path) { const r = await fetch(new URL(path, import.meta.url)); if (!r.ok) throw new Error(path + " answered " + r.status); return (await r.text()).replace(/\r\n/g, "\n"); } -let rpcId = 0; -const meta = (tasks) => ({ - "io.modelcontextprotocol/protocolVersion": PROTOCOL, - "io.modelcontextprotocol/clientInfo": { name: "hologram-forge", version: "1" }, - "io.modelcontextprotocol/clientCapabilities": tasks ? { extensions: { "io.modelcontextprotocol/tasks": {} } } : {}, -}); -function answerOf(text) { - try { return JSON.parse(text); } catch {} - let found = null; - for (const line of text.split("\n")) if (line.startsWith("data:")) { const e = JSON.parse(line.slice(5)); if ("id" in e) found = e; } - return found; -} -async function rpc(method, name, params) { - const headers = { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": PROTOCOL, "mcp-method": method }; - if (name) headers["mcp-name"] = name; - const body = JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params }); - for (let attempt = 0; ; attempt++) { - let status = 0, text = ""; - try { const r = await fetch(HOSTED, { method: "POST", headers, body }); status = r.status; text = await r.text(); } - catch (e) { if (attempt < 2) { await new Promise((r) => setTimeout(r, 10000)); continue; } throw new Error("the verifier did not answer"); } - if ([502, 503, 504].includes(status) && attempt < 2) { await new Promise((r) => setTimeout(r, 10000)); continue; } - const answer = answerOf(text); - if (!answer) throw new Error(`the verifier answered ${method} with HTTP ${status} and no message`); - if (answer.error) throw new Error(`the verifier refused ${method}: ${answer.error.message || JSON.stringify(answer.error)}`); - return answer.result; - } -} -const callTool = (tool, args, tasks = false) => rpc("tools/call", tool, { name: tool, arguments: args, _meta: meta(tasks) }); // ---- the proof of a rule app: Lean's kernel, in this tab // A rule app answers through the Forge kernel's RuleJudge, on the words `ruleWordsOf` writes. Lean proved, once for @@ -521,9 +489,8 @@ function leanWorker(self) { } return t; }; - // One guarantee's proof, written over the library: the app's words and the guarantee as data, `wordsCheck` on them - // judged by evaluation (Eq.refl true), and `ruleJudge_sound` applied to that. - const suffix = (i, words, g) => { + // What a suffix of the library is written with: names, levels and terms by index, new ones after the library's. + const writer = () => { const out = [], own = new Map(), ownExpr = [], ownAt = new Map(); let [nextName, nextExpr, nextLevel] = lib.next; const term = (node) => { const k = JSON.stringify(node), have = lib.exprAt.get(k) ?? ownAt.get(k); if (have !== undefined) return have; const e = nextExpr++; ownExpr[e] = node; ownAt.set(k, e); out.push(JSON.stringify({ ...node, ie: e })); return e; }; @@ -536,6 +503,27 @@ function leanWorker(self) { const one = lib.level.get(JSON.stringify({ succ: 0 })) ?? (() => { const l = nextLevel++; out.push(JSON.stringify({ il: l, succ: 0 })); return l; })(); const list = (T, xs) => xs.reduceRight((tail, x) => app(C("List.cons", [0]), T, x, tail), app(C("List.nil", [0]), T)); const declare = (kind, full, type, value) => { const n = name(full); out.push(JSON.stringify(kind === "def" ? { def: { all: [n], hints: { regular: 1 }, levelParams: [], name: n, safety: "safe", type, value } } : { thm: { all: [n], levelParams: [], name: n, type, value } })); return term({ const: { name: n, us: [] } }); }; + return { out, own, term, node, name, known, C, app, nat, one, list, declare }; + }; + // A stateful app's declarations, written locally nameless ({c, us} {a} {lam} {pi} {v} {n} {s}; a level is 0 or 1). + const written = (decls) => { + const { out, own, term, name, one, declare } = writer(); + const expr = (x, scope) => { + if (x.v !== undefined) { const i = scope.lastIndexOf(x.v); if (i < 0) throw new Error("unbound " + x.v); return term({ bvar: scope.length - 1 - i }); } + if (x.c) { const n = lib.name.get(x.c) ?? own.get(x.c); if (n === undefined) throw new Error("the library does not hold " + x.c); return term({ const: { name: n, us: x.us.map((u) => (u ? one : 0)) } }); } + if (x.a) { const fn = expr(x.a[0], scope); return term({ app: { arg: expr(x.a[1], scope), fn } }); } + if (x.lam || x.pi) { const [v, ty, body] = x.lam || x.pi, b = { binderInfo: "default", body: expr(body, [...scope, v]), name: name(v), type: expr(ty, scope) }; return term(x.lam ? { lam: b } : { forallE: b }); } + if (x.n !== undefined) return term({ natVal: String(x.n) }); + if (x.s !== undefined) return term({ strVal: x.s }); + throw new Error("not a term: " + JSON.stringify(x).slice(0, 80)); + }; + for (const d of decls) declare(d.kind, d.name, expr(d.type, []), expr(d.value, [])); + return out.join("\n") + "\n"; + }; + // One guarantee's proof, written over the library: the app's words and the guarantee as data, `wordsCheck` on them + // judged by evaluation (Eq.refl true), and `ruleJudge_sound` applied to that. + const suffix = (i, words, g) => { + const { out, term, node, name, known, C, app, nat, one, list, declare } = writer(); // A theorem's statement with its first binders taken by closed terms. const instantiate = (type, args) => { let body = type; @@ -581,8 +569,14 @@ function leanWorker(self) { const evidence = { ...at, bundle: await sha256(enc.encode(texts.join(""))), statement: await sha256(enc.encode(JSON.stringify(["prism/in-tab-statement/3", words, guarantees]))) }; return { op: "prove", id, judged, evidence }; } + // A stateful app's theorems, each judged with the app's definitions it reaches. + async function module({ id, defs, theorems }) { + const texts = theorems.map((t) => written([...defs, t])); + const judged = texts.map((text, i) => { const r = run("check_suffix", enc.encode(text)); return { accepted: r.exit === 0, axioms: r.axioms[theorems[i].name] || null, output: r.output }; }); + return { op: "module", id, judged, evidence: { ...at, bundle: await sha256(enc.encode(texts.join(""))) } }; + } self.onmessage = async ({ data }) => { - try { self.postMessage(data.op === "open" ? { op: "open", ...(await open(data)) } : await prove(data)); } + try { self.postMessage(data.op === "open" ? { op: "open", ...(await open(data)) } : data.op === "module" ? await module(data) : await prove(data)); } catch (e) { self.postMessage({ op: data.op, id: data.id, ok: false, refusal: "the proof worker failed: " + (e && e.message ? e.message : e) }); } }; } @@ -605,7 +599,7 @@ async function openLean() { }); const opened = await ask({ op: "open", manifest, glue, wasm, library }); if (!opened.ok) { worker.terminate(); throw new Error(opened.refusal); } - return { manifest, prove: (words, guarantees) => ask({ op: "prove", words, guarantees }) }; + return { manifest, prove: (words, guarantees) => ask({ op: "prove", words, guarantees }), module: (defs, theorems) => ask({ op: "module", defs, theorems }) }; } /** Lean's kernel proves the spec's guarantees in this tab. Resolves { ok, record, seconds, axioms } or { ok: false, error }. */ export async function prove(spec, { guest, beforeSubmit = () => {} } = {}) { @@ -632,145 +626,166 @@ export async function prove(spec, { guest, beforeSubmit = () => {} } = {}) { const seconds = Math.round((Date.now() - t0) / 100) / 10; return { ok: true, seconds, axioms: {}, record: { schema: "prism/in-tab-verification/1", verdict: verdict.verdict, verified_at: new Date().toISOString(), lean: k.manifest.lean, kernel: "sha256:" + r.evidence.kernel, library: "sha256:" + r.evidence.library, statement: "sha256:" + statement, bundle: "sha256:" + r.evidence.bundle, axioms: observed, properties: spec.properties.map((p) => p.id), seconds } }; } -/** - * Proves LexLean files on the hosted verifier: every theorem through Lean and leanchecker, each with - * its exact axioms. `filesFor(axioms)` gives { files, entrypoints } for the axiom sets Lean has named - * so far (declaration name -> "[a, b]"); a wrong set is corrected from what Lean observed and proved - * again. With `store` ({ get(key), put(key, value) }), a theorem whose address holds an admitted record - * (prism/proof-reuse.mjs) is taken out of the files and not proved again; when every theorem is, Lean - * does not run. Resolves { ok, record, seconds, axioms } or { ok: false, error }. - */ -export async function proveFiles(filesFor, { onWait = () => {}, before = () => {}, beforeSubmit = () => {}, store = null } = {}) { - before(); - const t0 = Date.now(); - const axioms = {}; - let submitted = false; - // Reuse only saves time: if deciding it fails (the verifier does not answer a lookup), prove everything. - const reuse = store ? await reusable(filesFor, safely(store)).catch(() => null) : null; - if (reuse) Object.assign(axioms, reuse.axioms); - if (reuse && reuse.theorems.length && reuse.reused.size === reuse.theorems.length) { - // Every theorem was proved before, on these exact bytes: no Lean run. The files are asked for once - // more so the caller holds the module under the axiom sets Lean observed. - await filesFor(axioms); - // A rolling deployment or revocation during lookup cannot commit a cached verdict. - if (!sameVerifier(reuse.identity, await verifier().catch(() => null))) return proveFiles(filesFor, { onWait, before, beforeSubmit }); - beforeSubmit(); - const latest = [...reuse.reused.values()].sort((a, b) => String(b.verified_at).localeCompare(String(a.verified_at)))[0]; - const seconds = Math.round((Date.now() - t0) / 1000); - return { ok: true, seconds, axioms: { ...axioms }, record: { schema: "prism/hosted-verification/2", server: HOSTED, profile: PROFILE, draft: null, entrypoints: [], verified_at: latest.verified_at, attestation_id: latest.attestation_id, attestations: [...new Set([...reuse.reused.values()].map((r) => r.attestation_id))], semantic_id: null, source_id: null, modules: [], theorems: reuse.summary(), proved: 0, reused: reuse.reused.size, seconds } }; - } - for (let round = 1; round <= 6; round++) { - const asked = await filesFor(axioms); - const entrypoints = asked.entrypoints; - const files = reuse && reuse.reused.size ? without(asked.files, entrypoints, new Set(reuse.reused.keys())) : asked.files; - if (!submitted) { beforeSubmit(); submitted = true; } - const written = await callTool("lexlean_draft_write", { profile: PROFILE, files }); - const draft = written && written.structuredContent && written.structuredContent.draft; - if (!draft || written.isError) return { ok: false, error: "the verifier did not take the draft" }; - let task = await callTool("lexlean_verify", { project: draft, files: entrypoints }, true); - if (!task || !task.taskId) return { ok: false, error: "the verifier did not start the proof" }; - const taskId = task.taskId; - while (task.status === "working") { - if (Date.now() - t0 > 15 * 60 * 1000) return { ok: false, error: "the proof did not end in 15 minutes" }; - await new Promise((r) => setTimeout(r, Math.max(1000, Math.min(task.pollIntervalMs || 5000, 10000)))); - task = await rpc("tasks/get", taskId, { taskId, _meta: meta(true) }); - onWait(Math.round((Date.now() - t0) / 1000)); - } - if (task.status !== "completed") return { ok: false, error: `the proof ended ${task.status}` }; - const state = task.result && task.result.structuredContent && task.result.structuredContent.state; - let body = null; - try { body = JSON.parse((task.result.content && task.result.content[0] && task.result.content[0].text) || "null"); } catch {} - if (state === "failed") { - const diagnostics = (body && body.diagnostics) || []; - // An axiom set the renderer guessed wrong: Lean names the set it observed, as prism-code corrects it. - const fixes = diagnostics.map((d) => /`([^`]+)` violates its (?:exact|none) axiom policy: observed (\[[^\]]*\])/.exec(d.message || "")).filter(Boolean); - if (fixes.length && fixes.length === diagnostics.length) { for (const m of fixes) axioms[m[1].split(".").pop()] = m[2]; continue; } - return { ok: false, error: (diagnostics[0] && diagnostics[0].message) || "Lean refused the proof", diagnostics }; +// ---- the proof of a stateful app: its own module, as kernel terms, in this tab +// The tab writes the app's module (its data form, live/app.mjs semanticData) as Lean terms with no elaborator: each +// structure is the right-nested product of its fields, `if` is `ite (c = true)`, the operators are Nat's and Bool's +// own functions. Each theorem is stated exactly as the module states it, over the definitions it reaches, and is proved +// by one lemma Lean proved once for every app the notation writes (studio/proof, PrismLive.Tables) applied to this +// app's terms, or by evaluation. Lean's kernel, in the worker, judges each theorem; nothing is sent anywhere. +export function moduleTerms(data, library = []) { + const fail = (why) => { throw new Error(why); }; + const C = (c, us = []) => ({ c, us }), A = (f, ...xs) => xs.reduce((g, x) => ({ a: [g, x] }), f), V = (v) => ({ v }); + const local = new Map(data.declarations.map((d) => [d.name, d])), lib = new Map(library.map((d) => [d.name, d])); + const BOOL = { kind: "bool" }, NAT = { kind: "nat" }, ONE = (n) => n.length === 1; + let fresh = 0; const v = () => "x" + fresh++; + const struct = (member) => { + const d = (member.module ? lib.get(member.name) : local.get(member.name) || lib.get(member.name)) || fail("no structure " + member.name); + if (d.kind !== "structure" || d.type_parameters?.length || !d.fields.length) fail(member.name + " is not a plain structure"); + const types = d.fields.map((f) => ty(f.type)), nest = (i) => (i === types.length - 1 ? types[i] : A(C("Prod", [0, 0]), types[i], nest(i + 1))); + return { d, types, nest }; + }; + const ty = (t) => ({ nat: () => C("Nat"), bool: () => C("Bool"), string: () => C("String"), bytes: () => C("ByteArray"), list: () => A(C("List", [0]), ty(t.element)), named: () => struct(t.member).nest(0) })[t.kind]?.() || fail("type " + t.kind); + const field = (t, name) => { const s = struct(t.member), k = s.d.fields.findIndex((f) => f.name === name); if (k < 0) fail("no field " + name); return { s, k, type: s.d.fields[k].type }; }; + const project = (t, name, x) => { + const { s, k } = field(t, name), n = s.types.length; + for (let j = 0; j < k; j++) x = A(C("Prod.snd", [0, 0]), s.types[j], s.nest(j + 1), x); + return k < n - 1 ? A(C("Prod.fst", [0, 0]), s.types[k], s.nest(k + 1), x) : x; + }; + const infer = (e, env) => { + switch (e.kind) { + case "nat": case "add": return NAT; + case "string": return { kind: "string" }; + case "bool": case "and": case "or": case "beq": case "ble": case "blt": case "eq": return BOOL; + case "var": return (env.get(e.name) || fail("unbound " + e.name)).type; + case "record": return { kind: "named", member: e.type }; + case "project": return field(infer(e.value, env), e.field).type; + case "if": return infer(e.then_value, env); + case "cons": return { kind: "list", element: infer(e.head, env) }; + case "nil": return { kind: "list", element: e.element }; + case "call": return (local.get(e.function.name) || fail("no definition " + e.function.name)).result; + case "primitive": return e.result; } - if (state !== "verified" || !body || !body.attestation_id) return { ok: false, error: "the verifier answered without an attestation" }; - const proved = new Set(body.modules || []); - const modules = entrypoints.map((p) => p.replace(/^src\//, "").replace(/\.lex\.tex$/, "").split("/").join(".")); - const absent = modules.filter((m) => !proved.has(m)); - if (absent.length) return { ok: false, error: "the verifier did not verify " + absent.join(", ") }; - const verifiedAt = new Date().toISOString(); - if (reuse && reuse.identity?.trust) { - const authorFiles = files.filter((f) => entrypoints.includes(f.path)); - const records = await Promise.all(reuse.theorems.filter((t) => !reuse.reused.has(t.id)).map((t) => reuseRecord({ theorem: t, address: reuse.address[t.id], verifier: reuse.identity, axioms, authorFiles, draft, attestationId: body.attestation_id, verifiedAt }))); - // A completed proof is filed only under the toolchain that actually attested it. - // The current gateway's bare found response cannot establish that binding. - const evidence = await attestation(body.attestation_id).catch(() => null); - const current = await verifier().catch(() => null); - const bound = sameVerifier(reuse.identity, current) && records.every((r) => attests(evidence, r.attestation_id, r.trust, r.files.map((f) => f.sha256))); - if (reuse.reused.size && !bound) return proveFiles(filesFor, { onWait, before, beforeSubmit }); - if (bound) for (const record of records) await reuse.store.put(record.address, record); + return fail("the tab cannot state " + e.kind); + }; + const reached = []; + const term = (e, env) => { + const t = (x) => term(x, env), op = { add: "Nat.add", beq: "Nat.beq", ble: "Nat.ble", blt: "Nat.blt", and: "Bool.and", or: "Bool.or" }[e.kind]; + if (op) return A(C(op), t(e.left), t(e.right)); + switch (e.kind) { + case "var": return env.get(e.name).term; + case "nat": return { n: e.value }; + case "string": return { s: e.value }; + case "bool": return C(e.value ? "Bool.true" : "Bool.false"); + case "eq": return A(C("Eq", [1]), ty(infer(e.left, env)), t(e.left), t(e.right)); + case "if": { const c = t(e.condition); return A(C("ite", [1]), ty(infer(e, env)), A(C("Eq", [1]), C("Bool"), c, C("Bool.true")), A(C("instDecidableEqBool"), c, C("Bool.true")), t(e.then_value), t(e.else_value)); } + case "record": { + const s = struct(e.type); + if (e.fields.length !== s.d.fields.length) fail("record shape"); + const vals = s.d.fields.map((f) => t((e.fields.find((x) => x.field === f.name) || fail("record without " + f.name)).value)); + const mk = (i) => (i === vals.length - 1 ? vals[i] : A(C("Prod.mk", [0, 0]), s.types[i], s.nest(i + 1), vals[i], mk(i + 1))); + return mk(0); + } + case "project": return project(infer(e.value, env), e.field, t(e.value)); + case "cons": return A(C("List.cons", [0]), ty(infer(e.head, env)), t(e.head), t(e.tail)); + case "nil": return A(C("List.nil", [0]), ty(e.element)); + case "call": reach(e.function.name); return A(C("Tab.app." + e.function.name), ...e.arguments.map(t)); + case "primitive": + if (e.arguments.length === 1 && e.operation === "length" && infer(e.arguments[0], env).kind === "bytes") return A(C("ByteArray.size"), t(e.arguments[0])); + if (e.arguments.length === 1 && e.operation === "utf8_encode") return A(C("String.toUTF8"), t(e.arguments[0])); } - const seconds = Math.round((Date.now() - t0) / 1000); - const reused = reuse ? reuse.reused : new Map(); - return { ok: true, seconds, axioms: { ...axioms }, record: { schema: "prism/hosted-verification/2", server: HOSTED, profile: PROFILE, draft, entrypoints, verified_at: verifiedAt, attestation_id: body.attestation_id, attestations: [...new Set([body.attestation_id, ...[...reused.values()].map((r) => r.attestation_id)])], semantic_id: body.semantic_id || null, source_id: body.source_id || null, modules: [...proved], theorems: reuse ? reuse.summary() : [], proved: reuse ? reuse.theorems.length - reused.size : null, reused: reused.size, seconds } }; - } - return { ok: false, error: "the axiom sets did not settle" }; -} - -// ---- reuse: theorems Lean proved before on the same bytes (prism/proof-reuse.mjs) -// The verifier's identity is part of every address: a proof made by another profile is not reused. -async function verifier() { - const answer = await callTool("lexlean_profiles", { profile: PROFILE }); - if (!answer || answer.isError) throw new Error("the verifier did not name its profile"); - const s = answer.structuredContent || {}; - const profile = s.id ? s : (Array.isArray(s.profiles) && s.profiles.length === 1 ? s.profiles[0] : null); - if (!profile || (profile.name && profile.name !== PROFILE) || typeof profile.id !== "string" || !/^[0-9a-f]{64}$/.test(profile.id)) throw new Error("the verifier did not name its profile"); - return { server: HOSTED, profile: PROFILE, profileId: profile.id, trust: trustDescriptor(profile.proof_reuse) }; -} -async function attestation(id) { - const answer = await callTool("lexlean_attestation", { by: "id", value: id }); - return answer && !answer.isError ? answer.structuredContent : null; -} -// A store that fails reads as empty and drops writes: reuse saves time, it never decides a verdict. -const safely = (store) => ({ - get: async (key) => { try { return (await store.get(KEY_PREFIX + key)) ?? null; } catch { return null; } }, - put: async (key, value) => { try { await store.put(KEY_PREFIX + key, value); } catch {} }, -}); -/** - * Which theorems of the files `filesFor({})` gives were proved before. A theorem still to be proved that - * names a reused one needs it in the file, so that one is proved again too. Sends no source: the - * verifier is asked for its current trust descriptor and each exact attestation. - */ -async function reusable(filesFor, store) { - const { files, entrypoints } = await filesFor({}); - const authors = files.filter((f) => entrypoints.includes(f.path)); - const theorems = theoremsOf(authors); - const reused = new Map(), refusals = {}, axioms = {}; - const summary = () => theorems.map((t) => ({ theorem: t.id, address: address[t.id] || null, reused: reused.has(t.id), attestation_id: reused.get(t.id)?.attestation_id ?? null, refusal: refusals[t.id] ?? null })); - let address = {}, identity = null; - if (!theorems.length) return { theorems, reused, axioms, summary, store, address, identity }; - identity = await verifier(); - if (!identity.trust) { - for (const t of theorems) refusals[t.id] = REFUSAL.trustUnavailable; - return { theorems, reused, axioms, summary, store, address, identity }; - } - address = await addresses({ files, entrypoints, verifier: identity }); - const headers = headersOf(authors); - const asked = new Map(); - const found = (id) => { - if (!asked.has(id)) asked.set(id, attestation(id)); - return asked.get(id); + return fail("the tab cannot state " + e.kind + (e.operation ? " " + e.operation : "")); + }; + // Binds parameters to terms; with no terms, to fresh variables, returned as binders. + const bind = (params, values) => { + const env = new Map(), binders = []; + params.forEach((p, i) => { if (values) env.set(p.name, { type: p.type, term: values[i] }); else { const x = v(); binders.push([x, ty(p.type)]); env.set(p.name, { type: p.type, term: V(x) }); } }); + return { env, binders }; }; - for (const t of theorems) { - const entry = await store.get(address[t.id]); - const decision = await admit({ entry, theorem: t, address: address[t.id], verifier: identity, headers, found }); - if (decision.admitted) reused.set(t.id, entry); else refusals[t.id] = decision.refusal; + const over = (binders, kind, body) => binders.reduceRight((b, [x, T]) => ({ [kind]: [x, T, b] }), body); + const defs = [], done = new Set(); + function reach(name) { + if (done.has(name)) return; done.add(name); + const d = local.get(name) || fail("no definition " + name); + if (d.kind !== "definition" || d.recursive_argument) fail(name + " is not a plain definition"); + const { env, binders } = bind(d.parameters), value = term(d.body, env); + defs.push({ kind: "def", name: "Tab.app." + name, type: over(binders, "pi", ty(d.result)), value: over(binders, "lam", value) }); } - for (let changed = true; changed; ) { - changed = false; - for (const t of theorems) if (!reused.has(t.id)) for (const d of t.reached) { - const id = `${d.path}#${d.name}`; - if (d.kind === "theorem" && reused.has(id)) { reused.delete(id); refusals[id] = REFUSAL.needed; changed = true; } + const callee = (e, env) => { const d = local.get(e.function.name); return { d, env: bind(d.parameters, e.arguments.map((a) => term(a, env))).env }; }; + const rev = (stateType, f) => { const x = v(); return { lam: [x, ty(stateType), project(stateType, f, V(x))] }; }; + const holds = (b) => A(C("Eq", [1]), C("Bool"), b, C("Bool.true")); + const mentions = (x, names) => JSON.stringify(x).match(/"v":"x\d+"/g)?.some((m) => names.includes(m)) || false; + // The proof that a guard tree is false, given h : bad = true, down to the leaf the bad case refutes. + const refute = (g, genv, bad, benv, h) => { + const badT = term(bad, benv); + if (g.kind === "and") { + const inLeft = leafIn(g.left, genv, bad, benv), side = inLeft ? g.left : g.right, h2 = v(); + return A(C(inLeft ? "PrismLive.Tables.left" : "PrismLive.Tables.right"), badT, term(g.left, genv), term(g.right, genv), { lam: [h2, holds(badT), refute(side, genv, bad, benv, V(h2))] }, h); } + if (bad.kind === "ble") return A(C("PrismLive.Tables.full"), term(bad.right, benv), term(bad.left, benv), h); + if (bad.kind === "or" && bad.right.kind === "ble" && bad.right.left.kind === "nat" && Number(bad.right.left.value) > 0) return A(C("PrismLive.Tables.outside"), term(bad.right.right, benv), { n: String(Number(bad.right.left.value) - 1) }, h); + return fail("the tab has no lemma for this guard"); + }; + const leafIn = (g, genv, bad, benv) => { + if (g.kind === "and") return leafIn(g.left, genv, bad, benv) || leafIn(g.right, genv, bad, benv); + if (bad.kind === "ble") return g.kind === "blt"; + const names = JSON.stringify(term(bad, benv)).match(/"v":"x\d+"/g) || []; + return g.kind !== "blt" && mentions(term(g, genv), names); + }; + const proof = (st, env) => { + if (st.kind === "eq" && st.right.kind === "bool" && st.right.value === false && st.left.kind === "call") { + const { d: F, env: fenv } = callee(st.left, env), b = F.body; + if (b.kind === "and" && b.right.kind === "blt" && b.right.right.kind === "project" && b.right.right.value.kind === "call") { + // bad && (rev s {} } = {}) { + const t0 = Date.now(), no = (error) => ({ ok: false, error }); + let terms; + try { terms = moduleTerms(data, library); } catch (e) { return no("Lean's kernel in this tab cannot read this module: " + e.message); } + if (terms.refused.length) return no("Lean's kernel in this tab cannot state " + terms.refused.map((r) => r.theorem + " (" + r.reason + ")").join(", ")); + if (!terms.theorems.length) return no("the module states no theorems"); + let k, r; + const failed = (e) => { lean = null; return { refusal: String((e && e.message) || e) }; }; + try { k = await (lean ||= openLean()); } catch (e) { return no(failed(e).refusal); } + beforeSubmit(); r = await k.module(terms.defs, terms.theorems).catch(failed); + if (!r.judged) return no(r.refusal || "the proof worker did not answer"); + const accepted = r.judged.every((g) => g.accepted), observed = [...new Set(r.judged.flatMap((g) => g.axioms || []))].sort(); + const word = (hex) => verdictAddressWords("sha256:" + hex), statement = await sha256Hex(enc.encode(source)); + const verdict = await verdictWithGuest(guest, { + version: 1, hasBytes: 1, libraryPinned: word(k.manifest.library.sha256), libraryDerived: word(r.evidence.library), + bundleNamed: word(r.evidence.bundle), bundleDerived: word(r.evidence.bundle), kernelPinned: word(k.manifest.wasm.sha256), kernelDerived: word(r.evidence.kernel), + specStatement: word(statement), checkedStatement: word(statement), axiomsDeclared: verdictAxiomSet(AXIOMS), axiomsObserved: verdictAxiomSet(observed), + leanRan: 1, leanAccepted: accepted ? 1 : 0, secondRan: 0, secondAccepted: 0, + }); + if (!verdict.ok) return no("the kernel guest gave no verdict (" + verdict.code + ")"); + const refused = terms.theorems.filter((_, i) => !r.judged[i].accepted).map((t) => t.name.replace("Tab.app.", "")); + if (verdict.verdict !== "proved") return no(refused.length ? "Lean's kernel refused " + refused.join(", ") : "the kernel guest said " + verdict.verdict); + const seconds = Math.round((Date.now() - t0) / 100) / 10; + return { ok: true, seconds, axioms: {}, record: { schema: "prism/in-tab-verification/1", verdict: verdict.verdict, verified_at: new Date().toISOString(), lean: k.manifest.lean, kernel: "sha256:" + r.evidence.kernel, library: "sha256:" + r.evidence.library, statement: "sha256:" + statement, bundle: "sha256:" + r.evidence.bundle, axioms: observed, theorems: terms.theorems.map((t) => t.name.replace("Tab.app.", "")), seconds } }; } - // ---- the build: the commit prism-code makes on a repository created from UOR-Foundation/template // prism-code builds an app on GitHub Actions by writing it into a template instance (journey/engine.mjs // writeTemplateApp, after journey/project.mjs writeApp); the template's pages and bootstrap workflows then diff --git a/studio/shell/prism/proof-reuse.mjs b/studio/shell/prism/proof-reuse.mjs deleted file mode 100644 index c937ea47..00000000 --- a/studio/shell/prism/proof-reuse.mjs +++ /dev/null @@ -1,247 +0,0 @@ -// FoundrySpecification.proofReuseBoundary: a theorem Lean proved before is not proved again. -// -// Whether Lean's kernel accepts a theorem depends on the verifier, the library files sent with the -// app, the headers of the app's own modules, the theorem's own text and the declarations it names, -// directly or through others. Those bytes give the theorem's address. Declarations it does not reach -// (acceptance vectors, other theorems, the view) are not part of it, so editing one guarantee leaves -// every other guarantee's address where it was. An `axioms:` member is left out of the address: it -// is the policy Lean checks, not what Lean proves, and the record carries the set Lean observed. -// -// A record filed under an address is believed only when the exact files it names hash to their -// digests, still hold the theorem and every declaration it reaches, and the verifier still finds an -// exact attestation under the current toolchain and epoch covering those digests. Otherwise the -// theorem is proved again; a refusal is never -// an error. - -export const SCHEMA = "prism/proof-reuse/2"; -export const POLICY_EPOCH = "foundry/proof-reuse-trust/1"; -const TRUST_SCHEMA = "lexlean-mcp/proof-reuse-trust/1"; -const TOOLS = ["lean", "lake", "leanchecker", "lexlean", "compilerSemantics"]; -// The two retired Lean executables in prismpm.lock (4.32.1). This is a reuse -// policy, not a claim that any other executable is sound or qualified for release. -const RETIRED_LEAN = new Set([ - "e8baaa71855a616dc351028f3ad2200051b0671f423a1696a100e809302d5550", - "79fb1d26fa5a39385d59fdc48a711a14b0710ca6480271acce99b4d177cea085", -]); -export const KEY_PREFIX = SCHEMA + ":"; - -// FoundrySpecification.ProofReuseRefusal. -export const REFUSAL = Object.freeze({ - absent: "proofReuseAbsent", - malformed: "proofReuseMalformed", - address: "proofReuseAddressMismatch", - verifier: "proofReuseVerifierMismatch", - bytes: "proofReuseBytesMismatch", - attestation: "proofReuseAttestationNotFound", - // Admitted, but a theorem being proved names it, so it goes back into the file and is proved again. - needed: "proofReuseNeededByChange", - trustUnavailable: "proofReuseTrustUnavailable", - trustMismatch: "proofReuseTrustMismatch", -}); - -const OPEN = "\\begin{semanticmodule}"; -const KNOWN = new Set(["structure", "inductive", "definition", "theorem"]); -const enc = new TextEncoder(); -const isDigest = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v); - -/** The service must explicitly bind reuse to its running toolchain and revocation epoch. */ -export function trustDescriptor(value) { - if (!value || value.schema !== TRUST_SCHEMA || !isDigest(value.epoch) - || !value.toolchain || !TOOLS.every((name) => isDigest(value.toolchain[name])) - || RETIRED_LEAN.has(value.toolchain.lean)) return null; - // Copy only the defined fields: later mutation and JSON property order do not alter identity. - return { schema: TRUST_SCHEMA, epoch: value.epoch, - toolchain: Object.fromEntries(TOOLS.map((name) => [name, value.toolchain[name]])) }; -} -export const sameTrust = (a, b) => { - const left = trustDescriptor(a), right = trustDescriptor(b); - return !!left && !!right && JSON.stringify(left) === JSON.stringify(right); -}; -export const sameVerifier = (a, b) => !!a && !!b && a.server === b.server - && a.profile === b.profile && a.profileId === b.profileId && sameTrust(a.trust, b.trust); - -/** A digest hit alone does not identify which verifier checked the file. */ -export function attests(evidence, attestationId, trust, digests) { - return !!evidence && evidence.found === true && evidence.status === "verified" - && isDigest(attestationId) && evidence.attestation_id === attestationId - && sameTrust(evidence.proof_reuse, trust) && Array.isArray(evidence.files) - && evidence.files.every(isDigest) && digests.every((digest) => evidence.files.includes(digest)); -} -const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); -export async function sha256(text) { return hex(await crypto.subtle.digest("SHA-256", enc.encode(text))); } - -// Length-framed fields, so no field can borrow bytes from its neighbour. -const framed = (fields) => fields.map((f) => `${enc.encode(f).length}:${f}`).join(""); - -/** End index (inclusive) of the bracket opened at `open`, skipping string literals; -1 if unclosed. */ -function closing(text, open) { - const pair = { "{": "}", "[": "]", "(": ")" }; - const stack = []; - for (let i = open, inString = false; i < text.length; i++) { - const c = text[i]; - if (inString) { if (c === "\\") i++; else if (c === '"') inString = false; continue; } - if (c === '"') inString = true; - else if (pair[c]) stack.push(pair[c]); - else if (c === stack.at(-1)) { stack.pop(); if (!stack.length) return i; } - } - return -1; -} - -/** The module's header (everything before its declarations) and its top-level declarations, in order. */ -export function declarationsOf(module) { - const text = String(module); - const start = text.indexOf(OPEN); - if (start < 0) return { header: null, declarations: [] }; - const declarations = []; - const head = /(^|\n)([a-z_]+)\{/g; - head.lastIndex = start + OPEN.length; - for (let m; (m = head.exec(text)); ) { - const from = m.index + m[1].length, open = from + m[2].length, end = closing(text, open); - if (end < 0) break; - const source = text.slice(from, end + 1); - declarations.push({ kind: m[2], name: /name:\s*([A-Za-z0-9_]+)/.exec(source)?.[1] ?? "", source }); - head.lastIndex = end + 1; - } - return { header: text.slice(0, start), declarations }; -} - -/** A declaration without its `axioms:` member, found at the declaration's own level, never in a string. */ -export function withoutAxioms(source) { - const open = source.indexOf("{"); - for (let i = open + 1, depth = 0, inString = false; i < source.length; i++) { - const c = source[i]; - if (inString) { if (c === "\\") i++; else if (c === '"') inString = false; continue; } - if (c === '"') { inString = true; continue; } - if ("{[(".includes(c)) { depth++; continue; } - if ("}])".includes(c)) { depth--; continue; } - if (depth === 0 && c === ",") { - const m = /^,\s*axioms:\s*\[/.exec(source.slice(i)); - if (m) { const end = closing(source, i + m[0].length - 1); return source.slice(0, i) + source.slice(end + 1); } - } - } - return source; -} - -/** - * The declaration as compared: without `axioms:`, and with layout whitespace outside strings made - * canonical (a run becomes one space; none after an opening bracket, before a closing one or before - * a comma), since the formatter re-wraps a declaration when its axioms change. Whitespace between two - * tokens is kept, so no two different declarations compare equal. - */ -export function canonical(source) { - const text = withoutAxioms(source); - let out = ""; - for (let i = 0, inString = false; i < text.length; i++) { - const c = text[i]; - if (inString) { out += c; if (c === "\\") out += text[++i] ?? ""; else if (c === '"') inString = false; continue; } - if (c === '"') { inString = true; out += c; continue; } - if (/\s/.test(c)) { - while (i + 1 < text.length && /\s/.test(text[i + 1])) i++; - const next = text[i + 1] ?? ""; - if (!"{[(".includes(out.at(-1) ?? "{") && !"}]),".includes(next)) out += " "; - continue; - } - out += c; - } - return out; -} - -const word = (name) => new RegExp(`(^|[^A-Za-z0-9_])${name}([^A-Za-z0-9_]|$)`); - -/** - * Every theorem of the author files, with what it reaches: the declarations it names, and those they - * name, to a fixed point, by whole-word match, so a declaration that might be used is included. - * A declaration of a kind other than structure, inductive, definition and theorem (an instance, say) - * can be used without being named, so it is reached by every theorem. - */ -export function theoremsOf(authorFiles) { - const all = authorFiles.flatMap((f) => declarationsOf(f.content).declarations.map((d) => ({ ...d, path: f.path, canon: canonical(d.source) }))); - return all.filter((d) => d.kind === "theorem").map((t) => { - const reached = new Set(); - const pending = [t.canon]; - for (const d of all) if (!KNOWN.has(d.kind)) { reached.add(d); pending.push(d.canon); } - while (pending.length) { - const text = pending.pop(); - for (const d of all) if (d !== t && !reached.has(d) && d.name && word(d.name).test(text)) { reached.add(d); pending.push(d.canon); } - } - return { id: `${t.path}#${t.name}`, name: t.name, path: t.path, source: t.source, canon: t.canon, reached: all.filter((d) => reached.has(d)) }; - }); -} - -/** Each author file's header, by path. */ -export const headersOf = (authorFiles) => Object.fromEntries(authorFiles.map((f) => [f.path, declarationsOf(f.content).header ?? f.content])); - -/** - * The address of every theorem: { [id]: sha256 hex }, an id being `path#name`. `files` are all the files sent, `entrypoints` - * the author files among them, `verifier` { server, profile, profileId, trust }. - */ -export async function addresses({ files, entrypoints, verifier }) { - const authors = files.filter((f) => entrypoints.includes(f.path)); - const library = files.filter((f) => !entrypoints.includes(f.path)); - const headers = headersOf(authors); - const trust = trustDescriptor(verifier.trust); - if (!trust) throw new Error(REFUSAL.trustUnavailable); - const shared = [SCHEMA, POLICY_EPOCH, verifier.server, verifier.profile, verifier.profileId, - trust.schema, trust.epoch, ...TOOLS.flatMap((name) => [name, trust.toolchain[name]]), - ...library.flatMap((f) => ["library", f.path, f.content]), - ...authors.flatMap((f) => ["header", f.path, headers[f.path]])]; - const out = {}; - for (const t of theoremsOf(authors)) out[t.id] = await sha256(framed([...shared, "theorem", t.path, t.canon, ...t.reached.flatMap((d) => ["reached", d.path, d.canon])])); - return out; -} - -/** The files with the named theorems taken out of the author files: what Lean is asked when they are reused. */ -export function without(files, entrypoints, ids) { - return files.map((f) => { - if (!entrypoints.includes(f.path)) return f; - let content = f.content; - for (const d of declarationsOf(content).declarations) if (d.kind === "theorem" && ids.has(`${f.path}#${d.name}`)) content = content.replace(d.source, ""); - return { ...f, content: content.replace(/\n{3,}/g, "\n\n").replace(/\n\n(\\end\{semanticmodule\})/, "\n$1") }; - }); -} - -/** The record filed for one theorem after a verified run: the exact author files the verifier attested. */ -export async function record({ theorem, address, verifier, axioms, authorFiles, draft, attestationId, verifiedAt }) { - const names = new Set([theorem.name, ...theorem.reached.map((d) => d.name)]); - return { - schema: SCHEMA, policyEpoch: POLICY_EPOCH, trust: trustDescriptor(verifier.trust), address, theorem: theorem.id, - server: verifier.server, profile: verifier.profile, profileId: verifier.profileId, - axioms: Object.fromEntries(Object.entries(axioms).filter(([name]) => names.has(name))), - files: await Promise.all(authorFiles.map(async (f) => ({ path: f.path, content: f.content, sha256: await sha256(f.content) }))), - draft, attestation_id: attestationId, verified_at: verifiedAt, - }; -} - -const isText = (v) => typeof v === "string" && v.length > 0; -const wellFormed = (e) => e.schema === SCHEMA && isText(e.theorem) && isDigest(e.address) && isDigest(e.attestation_id) - && e.axioms !== null && typeof e.axioms === "object" && !Array.isArray(e.axioms) - && Array.isArray(e.files) && e.files.length > 0 && e.files.every((f) => f && isText(f.path) && isText(f.content) && isDigest(f.sha256)); - -/** - * Decide whether `entry` may stand for the proof of `theorem` (from theoremsOf of the current author - * files, whose headers are `headers`). Pure except for `found(attestationId)`: current service evidence for the exact - * attestation, its toolchain and all file digests. Resolves { admitted: true } or { admitted: false, refusal }. - */ -export async function admit({ entry, theorem, address, verifier, headers, found }) { - if (entry == null) return { admitted: false, refusal: REFUSAL.absent }; - if (typeof entry !== "object" || !wellFormed(entry) || entry.theorem !== theorem.id) return { admitted: false, refusal: REFUSAL.malformed }; - if (!trustDescriptor(verifier.trust)) return { admitted: false, refusal: REFUSAL.trustUnavailable }; - if (entry.policyEpoch !== POLICY_EPOCH || !sameTrust(entry.trust, verifier.trust)) return { admitted: false, refusal: REFUSAL.trustMismatch }; - if (entry.address !== address) return { admitted: false, refusal: REFUSAL.address }; - if (entry.server !== verifier.server || entry.profile !== verifier.profile || entry.profileId !== verifier.profileId) return { admitted: false, refusal: REFUSAL.verifier }; - for (const f of entry.files) if (await sha256(f.content) !== f.sha256) return { admitted: false, refusal: REFUSAL.bytes }; - // The recorded files are this app's modules: the same paths, with the same headers. - if (entry.files.length !== Object.keys(headers).length || !entry.files.every((f) => Object.hasOwn(headers, f.path) && declarationsOf(f.content).header === headers[f.path])) return { admitted: false, refusal: REFUSAL.bytes }; - // They hold the theorem and every declaration it reaches, each in its own file, up to `axioms:`. - const held = new Map(entry.files.map((f) => [f.path, new Set(declarationsOf(f.content).declarations.map((d) => canonical(d.source)))])); - for (const d of [theorem, ...theorem.reached]) if (!held.get(d.path)?.has(d.canon)) return { admitted: false, refusal: REFUSAL.bytes }; - if (!attests(await found(entry.attestation_id), entry.attestation_id, verifier.trust, entry.files.map((f) => f.sha256))) return { admitted: false, refusal: REFUSAL.attestation }; - return { admitted: true }; -} - -/** What a proof message adds when some theorems were proved before: nothing when none were. */ -export function reuseSentence(total, reused) { - if (!reused) return ""; - if (reused >= total) return ` Lean proved ${total === 1 ? "it" : "all of them"} before on these exact declarations, so none was proved again.`; - return ` ${reused} ${reused === 1 ? "was" : "were"} proved before on these exact declarations; Lean proved the other ${total - reused}.`; -} diff --git a/studio/tools/build_source_browser.mjs b/studio/tools/build_source_browser.mjs index ce673b74..8b65428c 100644 --- a/studio/tools/build_source_browser.mjs +++ b/studio/tools/build_source_browser.mjs @@ -11,7 +11,7 @@ const sources = new Map([ ["/theme-library.mjs", fs.readFileSync(new URL("../shell/theme-library.mjs", import.meta.url))], ["/version-preview-codec.mjs", fs.readFileSync(new URL("../shell/version-preview-codec.mjs", import.meta.url))],["/blake3.mjs", fs.readFileSync(new URL("../../try/vendor/prism-code/src/blake3.mjs", import.meta.url))]]); for (const name of ["build-source", "project-lifecycle", "project-edit", "project-creation", "generation-patch", "snapshot-restore", "storage-request"]) sources.set(`/${name}.mjs`, fs.readFileSync(new URL(`../shell/${name}.mjs`, import.meta.url))); -for (const name of ["application-shape.mjs", "hosted-source-permission.mjs", "approval-queue.mjs", "live/app.mjs", "live/notation.mjs", "live/v2/interp.mjs", "live/v2/render.mjs", "live/v2/check.mjs", "canonical-build.mjs", "prism.js", "prism/spec.mjs", "prism/spec-file.mjs", "prism/render.mjs", "prism/proof-reuse.mjs", "in-tab-verdict-codec.mjs", "prism/builder/route.mjs", "prism/builder/prompt.mjs", "prism/template.mjs", "prism/sha256.mjs", "live/lexlean.mjs", "live/obligations.mjs", "live/table.mjs", "prism-code/src/blake3.mjs"]) sources.set("/" + name, fs.readFileSync(new URL("../shell/" + name, import.meta.url))); +for (const name of ["application-shape.mjs", "hosted-source-permission.mjs", "approval-queue.mjs", "live/app.mjs", "live/notation.mjs", "live/v2/interp.mjs", "live/v2/render.mjs", "canonical-build.mjs", "prism.js", "prism/spec.mjs", "prism/spec-file.mjs", "prism/render.mjs", "in-tab-verdict-codec.mjs", "prism/builder/route.mjs", "prism/builder/prompt.mjs", "prism/template.mjs", "prism/sha256.mjs", "live/lexlean.mjs", "live/obligations.mjs", "live/table.mjs", "prism-code/src/blake3.mjs"]) sources.set("/" + name, fs.readFileSync(new URL("../shell/" + name, import.meta.url))); const server = http.createServer((req, res) => { const bytes = sources.get(req.url); if (!bytes && req.url !== "/") { res.writeHead(404, {"content-type":"text/plain"}); res.end("Fixture resource is not declared"); return; } diff --git a/studio/tools/hosted_source_permission.test.mjs b/studio/tools/hosted_source_permission.test.mjs index 42a400fa..c65b57e7 100644 --- a/studio/tools/hosted_source_permission.test.mjs +++ b/studio/tools/hosted_source_permission.test.mjs @@ -1,7 +1,7 @@ import {test} from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; -import {checkApp, checkLibrary, splitDeclarations, wholePrefix} from '../shell/live/app.mjs'; +import {checkApp, splitDeclarations, wholePrefix} from '../shell/live/app.mjs'; import {authorizeHostedSource, describeHostedSource, createHostedSourceSession, withHostedSourcePermission, hostedSourceFailure, HOSTED_SOURCE_ENDPOINT} from '../shell/hosted-source-permission.mjs'; const read = path => fs.readFileSync(new URL(path, import.meta.url), 'utf8'); const module = read('../../v2/loop/answers/guests-3.verified.lex.tex'); @@ -30,12 +30,15 @@ function service() { } // A parse through the boundary itself: the preview reads its data form in the tab, so only these tests send one. const dataForm=(source,fetchImpl,opts={})=>{const sent=[{path:'src/App.lex.tex',content:source}];return withHostedSourcePermission({purpose:'parse',files:sent},async f=>{const draft=(await (await f(HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_write',{profile:'prism-app',files:sent}))).json()).result.structuredContent.draft;if(typeof draft!=='string'||!draft)throw hostedSourceFailure('hostedSourceMalformedResponse');return draft;},opts,fetchImpl);}; +// A check through the boundary, with the module and the library it imports: no shell code sends one any more. +const checkForm=(source,fetchImpl,opts={})=>{const sent=[{path:'src/App.lex.tex',content:source},{path:'src/Foundation/View/Browser/V1/Model.lex.tex',content:read('../shell/live/v2/Model.lex.tex')}];return withHostedSourcePermission({purpose:'check',files:sent},async f=>(await f(HOSTED_SOURCE_ENDPOINT,rpc('lexlean_draft_write',{profile:'prism-app',files:sent}))).json(),opts,fetchImpl);}; const rpc=(name,args)=>({method:'POST',body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name,arguments:args}})}); function session(boundary={}) {const controller=new AbortController();let current=true;const scope=createHostedSourceSession({appId:7,turnId:'turn-one',source:'blake3:'+'a'.repeat(64),signal:controller.signal,assertCurrent:async()=>current},{...options,...boundary});return {scope,controller,change:()=>{current=false;}};} test('no default hosted source transmission occurs without permission', async () => { let calls=0;await assert.rejects(dataForm('private source',async()=>{calls++;throw Error('network');}),code('hostedSourcePermissionUnavailable'));assert.equal(calls,0); - const loaded=checkLibrary(async path=>read('../shell/live/v2/'+path));await assert.rejects(checkApp(module,loaded,async()=>{calls++;throw Error('network');}),code('hostedSourcePermissionUnavailable'));assert.equal(calls,0); + await assert.rejects(checkForm('private source',async()=>{calls++;throw Error('network');}),code('hostedSourcePermissionUnavailable'));assert.equal(calls,0); + const real=globalThis.fetch;globalThis.fetch=async()=>{calls++;throw Error('network');};try{await checkApp(module,{'Foundation.View.Browser.V1.Model':JSON.parse(read('../shell/live/v2/Model.json'))});}finally{globalThis.fetch=real;}assert.equal(calls,0,'the in-tab check sends nothing'); }); test('disclosure is immutable exact source with bounded paths and a fixed destination',()=>{ const source=structuredClone(input),disclosure=describeHostedSource(source);source.files[0].content='changed';assert.equal(disclosure.files[0].content,files[0].content);assert.ok(Object.isFrozen(disclosure.files[0]));assert.equal(disclosure.endpoint,HOSTED_SOURCE_ENDPOINT); @@ -65,7 +68,7 @@ test('approved browser scope links caller and stop cancellation and cleans its c test('parser and checker require disclosed exact files and strip ambient credentials',async()=>{ const transport=service();let disclosures=[];const opts={...options,authorize:async value=>{disclosures.push(describeHostedSource(value));return approval(value);}}; await dataForm(wholePrefix(module).source,transport.fetch,opts); - await checkApp(module,checkLibrary(async path=>read('../shell/live/v2/'+path)),transport.fetch,opts); + await checkForm(module,transport.fetch,opts); assert.equal(disclosures.length,2);assert.deepEqual(disclosures.map(d=>d.purpose),['parse','check']);assert.equal(disclosures[1].files.length,2); for(const request of transport.requests){assert.equal(request.url,HOSTED_SOURCE_ENDPOINT);assert.equal(request.init.credentials,'omit');assert.equal(request.init.redirect,'error');assert.equal(request.init.headers.authorization,undefined);assert.ok(request.init.signal);} assert.deepEqual(JSON.parse(transport.requests[0].init.body).params.arguments.files,disclosures[0].files); @@ -74,7 +77,7 @@ test('one turn approval covers later prefixes repairs and checks but never a dif let approvals=0;const boundary={authorize:async value=>{approvals++;assert.equal(value.scope,'turn');assert.equal(value.appId,7);return approval(value);}},one=session(boundary),transport=service(); try { await dataForm('first prefix',transport.fetch,{session:one.scope});await dataForm('repaired module',transport.fetch,{session:one.scope}); - await checkApp(module,checkLibrary(async path=>read('../shell/live/v2/'+path)),transport.fetch,{session:one.scope});assert.equal(approvals,1); + await checkForm(module,transport.fetch,{session:one.scope});assert.equal(approvals,1); const two=session(boundary);try{await dataForm('another turn',transport.fetch,{session:two.scope});assert.equal(approvals,2);}finally{two.scope.close();} }finally{one.scope.close();} }); @@ -109,8 +112,8 @@ test('cancel and bounded deadline interrupt in flight requests even when fetch i await seen;if(action==='cancel')one.controller.abort();await rejection;one.scope.close(); } }); -test('a build turn sends no source: its preview is read in the tab, and only an approval asks to check',()=>{ +test('a build turn and its check send no source: both are read, run and stated in the tab',()=>{ const host=read('../shell/host.js'),app=read('../shell/live/app.mjs'); - assert.ok(!host.includes('createHostedSourceSession(')&&!app.includes('purpose: "parse"'));assert.ok(app.includes('withHostedSourcePermission({ purpose: "check", files }'));assert.ok(app.includes('createApp(semanticData(source), library)')); + assert.ok(!host.includes('createHostedSourceSession(')&&!app.includes('purpose: "parse"'));assert.ok(!app.includes('hosted-source-permission'));assert.ok(app.includes('createApp(semanticData(source), library)')); assert.ok(read('../../app/src/FoundrySpecification.lex.tex').includes('name: hostedSourcePermissionBoundary,'));assert.ok(read('./shell_parse.mjs').includes('"hosted-source-permission.mjs": "mjs"')); }); diff --git a/studio/tools/live_app_check.test.mjs b/studio/tools/live_app_check.test.mjs index 8f9d0004..f78f70f4 100644 --- a/studio/tools/live_app_check.test.mjs +++ b/studio/tools/live_app_check.test.mjs @@ -1,61 +1,39 @@ // Run: node --test studio/tools/live_app_check.test.mjs -// A stateful app's module is checked at the end of its turn (shell/live/app.mjs, checkApp), and what the -// chat says about it claims no more than the check found. The hosted service is asked only when -// LIVE_APP_HOSTED=1; the other claims use a stand-in that answers as the service does. +// A stateful app's module is checked at the end of its turn (shell/live/app.mjs, checkApp), in the tab: it is read +// as LexLean reads it, its first frame draws, and every theorem it states is put as a term Lean's kernel can judge. +// What the chat says about it claims no more than the check found. Nothing is sent anywhere. import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; -import { appLive, card, checkApp, checkLibrary, issueLine, repairPrompt, wholePrefix, splitDeclarations, CARD } from "../shell/live/app.mjs"; +import { appLive, card, checkApp, issueLine, repairPrompt, CARD } from "../shell/live/app.mjs"; +import { expand } from "../shell/live/notation.mjs"; -import { describeHostedSource } from "../shell/hosted-source-permission.mjs"; -// Explicit fixture authorization. No test uses implicit production consent. -const permissionOptions = { authorize: async input => ({ disclosure: describeHostedSource(input), expires: Date.now() + 10000, signal: new AbortController().signal, close() {} }), online: () => true }; const read = (path) => fs.readFileSync(new URL(path, import.meta.url), "utf8"); -const module = read("../../v2/loop/answers/guests-3.verified.lex.tex"); -const engine = (path) => Promise.resolve(read("../shell/live/v2/" + path)); -const library = () => checkLibrary(engine); -const hosted = process.env.LIVE_APP_HOSTED === "1"; - -// Answers a draft write, a check and a data read. `verdict(files)` gives the check's result. -function service(verdict) { - const sent = []; - const fetchImpl = async (url, init) => { - const request = JSON.parse(init.body), args = request.params.arguments; - let payload = {}; - if (request.params.name === "lexlean_draft_write") { sent.push(args.files); payload = { draft: "prism-app/test" }; } - else if (request.params.name === "lexlean_check") payload = verdict(sent.at(-1)); - else payload = { data: { spec: "lexlean/semantic-module/2", declarations: [] } }; - return { ok: true, status: 200, json: async () => ({ result: { structuredContent: payload } }) }; - }; - return { fetchImpl, sent }; -} - -test("the checker is sent the module as written and the one library module it imports", async () => { - const { fetchImpl, sent } = service(() => ({ success: true, diagnostics: [] })); - const verdict = await checkApp(module, library(), fetchImpl, permissionOptions); - assert.deepEqual({ ok: verdict.ok, issues: verdict.issues }, { ok: true, issues: [] }); - const paths = sent[0].map((f) => f.path).sort(); - assert.deepEqual(paths, ["src/App.lex.tex", "src/Foundation/View/Browser/V1/Model.lex.tex"]); - const app = sent[0].find((f) => f.path === "src/App.lex.tex").content; - const strip = (s) => s.replace(/\\title\{[^}]*\}/, ""); - assert.equal(strip(app), strip(module.trim() + "\n"), "nothing but the title's words differs from what the model wrote"); +const module = expand(read("notation/guests.txt")).module; +const library = { "Foundation.View.Browser.V1.Model": JSON.parse(read("../shell/live/v2/Model.json")) }; +const offline = async (fn) => { const f = globalThis.fetch; let asked = 0; globalThis.fetch = async () => { asked++; throw new Error("offline"); }; try { return { result: await fn(), asked }; } finally { globalThis.fetch = f; } }; + +test("every notation module is checked in the tab, with no request", async () => { + for (const name of ["guests", "notes", "orders", "model-reading", "model-chores", "model-feedback", "model-guests"]) { + const { result, asked } = await offline(() => checkApp(expand(read(`notation/${name}.txt`)).module, library)); + assert.deepEqual({ ok: result.ok, issues: result.issues }, { ok: true, issues: [] }, name); + assert.equal(asked, 0, name); + } }); -test("a refusal becomes lines about the module as written, and a repair request made of them", async () => { - const { fetchImpl } = service(() => ({ success: false, diagnostics: [{ code: "LLT4001", severity: "error", message: "unknown name `gests`", primary: { path: "src/App.lex.tex", line_start: 41, column_start: 9 } }] })); - const verdict = await checkApp(module, library(), fetchImpl, permissionOptions); - assert.equal(verdict.ok, false); - assert.deepEqual(verdict.issues, ["Line 41: unknown name `gests` (LLT4001)"]); - const prompt = repairPrompt(verdict.issues); +test("a planted fault is refused by name, and the refusal becomes a repair request", async () => { + const source = module.replace(/parameters: \[state : State\]/, "parameters: [state : Stat]"); + assert.notEqual(source, module, "the fault was planted"); + const bad = await checkApp(source, library); + assert.equal(bad.ok, false); + assert.ok(bad.issues.some((i) => /Stat/.test(i)), bad.issues.join("; ")); + assert.deepEqual((await checkApp(module.replace("statement: (", "statement: (nosuch "), library)).issues, ["guestsStartsEmpty: no definition nosuch"]); + assert.equal((await checkApp(module.replace("statement: (", "statement: (("), library)).ok, false, "a module that does not read is refused"); + const prompt = repairPrompt(["Line 41: unknown name `gests` (LLT4001)"]); assert.match(prompt, /Line 41: unknown name `gests`/); assert.match(prompt, /whole module again, in one block/); assert.equal(issueLine({ message: "no position" }), "no position"); -}); - -test("a refusal with no reason is still a refusal, and an unreachable service is not a verdict", async () => { - const silent = service(() => ({ success: false, diagnostics: [] })); - assert.deepEqual((await checkApp(module, library(), silent.fetchImpl, permissionOptions)).issues, ["The checker refused the module and gave no reason."]); - await assert.rejects(checkApp(module, library(), async () => { throw new Error("offline"); }, permissionOptions), { code: "hostedSourceNetworkFailed" }); + assert.equal(issueLine({ line: 3, message: "x", code: "C" }), "Line 3: x (C)"); }); test("the card says checked only for a checked state, lists what was refused, and never says proved", () => { @@ -68,35 +46,14 @@ test("the card says checked only for a checked state, lists what was refused, an const unreachable = card({ phase: "drafting", issues: [], unchecked: "offline" }); assert.ok(unreachable.startsWith(CARD) && /could not be checked just now: offline/.test(unreachable)); for (const text of [checked, refused, unreachable]) assert.ok(!/\bproved by\b|is proved|are proved/i.test(text)); + assert.ok(!/hosted|server/i.test(card({ phase: "proving" }) + card({ phase: "proved", theorems: [1] }))); }); -test("the same module under a new standing is sent again with the new badge, and asks the service nothing", async () => { - const whole = JSON.parse(read("../../v2/loop/answers/guests-3.json")); - const calls = [], posted = []; - const fetchImpl = async (url, init) => { - const request = JSON.parse(init.body); calls.push(request.params.name); - const payload = request.params.name === "lexlean_draft_write" ? { draft: "d" } : { data: { spec: whole.spec, declarations: whole.declarations.filter((d) => d.kind !== "theorem") } }; - return { ok: true, status: 200, json: async () => ({ result: { structuredContent: payload } }) }; - }; - const live = appLive({ post: (appId, m) => posted.push(m), library: { "Foundation.View.Browser.V1.Model": JSON.parse(read("../shell/live/v2/Model.json")) }, fetchImpl, permissionOptions }); +test("the same module under a new standing is drawn again with the new badge", async () => { + const posted = []; + const live = appLive({ post: (appId, m) => posted.push(m), library }); live.push(4, module, "draft"); await live.settled(4); - const asked = calls.length; live.push(4, module, "checked"); await live.settled(4); - assert.equal(calls.length, asked); assert.deepEqual(posted.map((m) => m.trust), ["draft", "checked"]); assert.deepEqual(posted[1].nodes, posted[0].nodes); }); - -test("hosted: the service accepts the model-written module and refuses a planted fault by name", { skip: !hosted }, async () => { - const good = await checkApp(module, library(), undefined, permissionOptions); - assert.deepEqual({ ok: good.ok, issues: good.issues }, { ok: true, issues: [] }); - // The fault: the helper `cleared` takes a state of a type that does not exist. - const source = module.replace(/(name: cleared,\s+parameters: \[state : )State\]/, "$1Stat]"); - assert.notEqual(source, module, "the fault was planted"); - const bad = await checkApp(source, library(), undefined, permissionOptions); - assert.equal(bad.ok, false); - // The checker names what is wrong. For a fault found while linking it gives the module's line, not - // the declaration's, so the name in the message is what a model or a person can act on. - assert.ok(bad.issues.length > 0 && /^Line \d+: /.test(bad.issues[0]) && /`Stat`/.test(bad.issues[0]), bad.issues[0]); - assert.ok(wholePrefix(source).ready && splitDeclarations(source).declarations.length > 5, "a refused module still runs as far as it can"); -}); diff --git a/studio/tools/live_app_prove.test.mjs b/studio/tools/live_app_prove.test.mjs index 7b54845b..7cc83494 100644 --- a/studio/tools/live_app_prove.test.mjs +++ b/studio/tools/live_app_prove.test.mjs @@ -1,118 +1,92 @@ // Run: node --test studio/tools/live_app_prove.test.mjs -// Proving a stateful app's module (shell/live/app.mjs with prism.js's proveFiles): what is sent to the -// verifier, how a wrong axiom set is corrected, and what the chat then says. The verifier is a -// stand-in that speaks its protocol; a real proof takes ten minutes or more and is run by hand. +// Proving a stateful app's module in the tab (shell/prism.js moduleTerms and the Lean worker's `module`): the +// module's own definitions and theorems are written as Lean kernel terms, each proof applies a lemma studio/proof +// proved once (PrismLive.Tables) or is by evaluation, and the pinned Lean kernel (shell/kernel/lean) judges them +// against the shipped library. A broken app is refused by the kernel, not by this writer. Then what the chat says. import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; -import { card, checkLibrary, promisesOf, proofFiles, proofMessage, provingMessage, theoremsOf, withAxioms } from "../shell/live/app.mjs"; -import { proveFiles } from "../shell/prism.js"; +import os from "node:os"; +import path from "node:path"; +import zlib from "node:zlib"; +import { card, promisesOf, proofMessage, provingMessage, semanticData, theoremsOf } from "../shell/live/app.mjs"; +import { expand } from "../shell/live/notation.mjs"; +import { moduleTerms } from "../shell/prism.js"; -const read = (path) => fs.readFileSync(new URL(path, import.meta.url), "utf8"); -const module = read("../../v2/loop/answers/guests-3.verified.lex.tex"); -const library = await checkLibrary((path) => Promise.resolve(read("../shell/live/v2/" + path))); +const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8"); +const library = JSON.parse(read("../shell/live/v2/Model.json")).declarations; +const moduleOf = (name) => expand(read(`notation/${name}.txt`)).module; +const module = moduleOf("guests"); +const termsOf = (source) => moduleTerms(semanticData(source, { theorems: true }), library); + +// The page's Lean worker, run here on the pinned glue, kernel and library, as the tab runs it. +const kernel = await (async () => { + const prism = read("../shell/prism.js"), dir = new URL("../shell/kernel/lean/", import.meta.url); + const leanWorker = new Function("return " + prism.slice(prism.indexOf("function leanWorker(self) {"), prism.indexOf("// One worker for the page")))(); + const manifest = JSON.parse(fs.readFileSync(new URL("manifest.json", dir))); + const [glue, wasm, lib] = [manifest.glue, manifest.wasm, manifest.library].map((f) => zlib.gunzipSync(fs.readFileSync(new URL(f.file, dir)))); + const glueFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "lean-")), "glue.mjs"); + fs.writeFileSync(glueFile, glue); + URL.createObjectURL = () => "file://" + glueFile; URL.revokeObjectURL = () => {}; + const replies = []; let wake; + const self = { postMessage: (m) => { replies.push(m); wake?.(); } }; + leanWorker(self); + const ask = async (m) => { const p = new Promise((r) => (wake = r)); await self.onmessage({ data: m }); await p; return replies.pop(); }; + await ask({ op: "open", manifest, glue, wasm, library: lib }); + return (terms) => ask({ op: "module", id: 1, defs: terms.defs, theorems: terms.theorems }); +})(); test("the theorems and the promises are read from the module, in order, word for word", () => { const theorems = theoremsOf(module), promises = promisesOf(module); - assert.deepEqual(theorems.map((t) => t.name), ["startsEmpty", "clearEmpties", "emptyIgnored", "longIgnored", "staleIgnored"]); - assert.deepEqual(theorems.map((t) => t.form), ["reflexivity", "reflexivity", "linear_arithmetic", "linear_arithmetic", "linear_arithmetic"]); + assert.deepEqual(theorems.map((t) => t.name), ["guestsStartsEmpty", "added1NeedsName", "added1NeedsMeal", "added1StopsWhenFull", "cleared2Empties", "staleIgnored"]); for (const t of theorems) assert.ok(module.includes("statement: " + t.statement + ","), t.name); assert.equal(promises.length, theorems.length); - assert.equal(promises[0], "The guest list starts empty."); - assert.deepEqual(theoremsOf(module.replace(/theorem\{[\s\S]*$/, "\\end{semanticmodule}\n\\end{lexlean}\n")), []); -}); - -test("an axiom set Lean names is written into that theorem and nowhere else", () => { - const fixed = withAxioms(module, { startsEmpty: "[propext]" }); - const before = theoremsOf(module), after = theoremsOf(fixed); - assert.deepEqual(after.map((t) => t.statement), before.map((t) => t.statement)); - assert.match(fixed, /name: startsEmpty,[\s\S]*?axioms: \[propext\]/); - const lines = (s) => s.split("\n"), changed = lines(fixed).filter((l, i) => l !== lines(module)[i]); - assert.deepEqual(changed, [" axioms: [propext]"]); - assert.equal(withAxioms(module, { noSuchTheorem: "[propext]" }), module); - assert.equal(withAxioms(fixed, { startsEmpty: "[propext]" }), fixed); -}); - -test("the proof is asked on the module and the library it imports, and must come back about the module", () => { - const { files, entrypoints } = proofFiles(module, library); - assert.deepEqual(files.map((f) => f.path).sort(), ["src/App.lex.tex", "src/Foundation/View/Browser/V1/Model.lex.tex"]); - assert.deepEqual(entrypoints, ["src/App.lex.tex"]); - const strip = (s) => s.replace(/\\title\{[^}]*\}/, ""); - assert.equal(strip(files.find((f) => f.path === "src/App.lex.tex").content), strip(module.trim() + "\n"), "the module's declarations go as written"); - assert.equal(strip(files.find((f) => f.path.endsWith("Model.lex.tex")).content), strip(read("../shell/live/v2/Model.lex.tex")), "the library's declarations go as shipped"); -}); - -// The hosted verifier's protocol, as prism.js speaks it: a draft, a verify task, then polls. -function verifier(rounds) { - const log = { drafts: [], polls: 0 }; - let round = 0; - const answer = (result) => ({ status: 200, text: async () => JSON.stringify({ jsonrpc: "2.0", id: 1, result }) }); - const fetchImpl = async (url, init) => { - const request = JSON.parse(init.body); - if (request.method === "tools/call" && request.params.name === "lexlean_draft_write") { log.drafts.push(request.params.arguments.files); return answer({ structuredContent: { draft: "prism-app/round" + round } }); } - if (request.method === "tools/call" && request.params.name === "lexlean_verify") return answer({ taskId: "t" + round, status: "working", pollIntervalMs: 1 }); - if (request.method === "tasks/get") { log.polls++; const r = rounds[round++]; return answer({ status: "completed", result: { structuredContent: { state: r.state }, content: [{ text: JSON.stringify(r.body) }] } }); } - throw new Error("unexpected request " + request.method); - }; - return { fetchImpl, log }; -} -async function withFetch(fetchImpl, work) { const real = globalThis.fetch; globalThis.fetch = fetchImpl; try { return await work(); } finally { globalThis.fetch = real; } } -const filesFor = (seen) => async (axioms) => { seen.push({ ...axioms }); return proofFiles(withAxioms(module, axioms), library); }; - -test("a proof Lean verifies is reported with its attestation", { timeout: 20000 }, async () => { - const { fetchImpl } = verifier([{ state: "verified", body: { attestation_id: "a".repeat(64), modules: ["App"], semantic_id: "s" } }]); - const result = await withFetch(fetchImpl, () => proveFiles(filesFor([]))); - assert.equal(result.ok, true); - assert.equal(result.record.attestation_id, "a".repeat(64)); - assert.deepEqual(result.record.entrypoints, ["src/App.lex.tex"]); + assert.equal(promises[0], "Guests starts empty."); + assert.deepEqual(semanticData(module, { theorems: true }).theorems.map((t) => t.name), theorems.map((t) => t.name)); + assert.equal(semanticData(module).theorems, undefined, "the data form LexLean reads is unchanged"); }); -test("a wrong axiom set is corrected from what Lean observed, and the module proved again", { timeout: 20000 }, async () => { - const seen = []; - const { fetchImpl, log } = verifier([ - { state: "failed", body: { diagnostics: [{ code: "LLV7005", message: "`PrismTextRequest.App.emptyIgnored` violates its exact axiom policy: observed [Quot.sound, propext]" }] } }, - { state: "verified", body: { attestation_id: "b".repeat(64), modules: ["App"] } }, - ]); - const result = await withFetch(fetchImpl, () => proveFiles(filesFor(seen))); - assert.equal(result.ok, true); - assert.deepEqual(seen, [{}, { emptyIgnored: "[Quot.sound, propext]" }]); - assert.equal(log.drafts.length, 2); - assert.match(log.drafts[1].find((f) => f.path === "src/App.lex.tex").content, /name: emptyIgnored,[\s\S]*?axioms: \[Quot\.sound, propext\]/); +test("Lean's kernel, in the tab, accepts every theorem of every notation app, on the shipped axioms only", { timeout: 60000 }, async () => { + for (const name of ["guests", "notes", "orders", "model-reading", "model-chores", "model-feedback", "model-guests"]) { + const terms = termsOf(moduleOf(name)); + assert.deepEqual(terms.refused, [], name); + assert.ok(terms.theorems.length >= 3 && terms.defs.every((d) => d.name.startsWith("Tab.app.")), name); + const r = await kernel(terms); + assert.ok(r.judged, name + ": " + JSON.stringify(r).slice(0, 300)); + for (const [i, j] of r.judged.entries()) { + assert.ok(j.accepted, name + " " + terms.theorems[i].name + ": " + j.output.slice(-300)); + for (const a of j.axioms) assert.ok(["propext", "Quot.sound"].includes(a), a); + } + } }); -test("a theorem Lean refuses is not proved, and a verifier that did not verify the module is not believed", { timeout: 20000 }, async () => { - const refused = verifier([{ state: "failed", body: { diagnostics: [{ code: "LLV7001", message: "the proof of `clearEmpties` does not close" }] } }]); - const a = await withFetch(refused.fetchImpl, () => proveFiles(filesFor([]))); - assert.deepEqual({ ok: a.ok, error: a.error }, { ok: false, error: "the proof of `clearEmpties` does not close" }); - const other = verifier([{ state: "verified", body: { attestation_id: "c".repeat(64), modules: ["Foundation.View.Browser.V1.Model"] } }]); - const b = await withFetch(other.fetchImpl, () => proveFiles(filesFor([]))); - assert.equal(b.ok, false); - assert.match(b.error, /did not verify App/); - const silent = verifier([{ state: "verified", body: { modules: ["App"] } }]); - assert.equal((await withFetch(silent.fetchImpl, () => proveFiles(filesFor([])))).ok, false, "no attestation, no proof"); +test("a broken app is refused by the kernel: a guard that lets an empty name in, a Clear that keeps the rows", { timeout: 60000 }, async () => { + const judged = async (from, to) => { assert.ok(module.includes(from), from); const t = termsOf(module.replace(from, to)); const r = await kernel(t); return Object.fromEntries(t.theorems.map((x, i) => [x.name.replace("Tab.app.", ""), r.judged[i].accepted])); }; + const weak = await judged("(1 <=? (prim length", "(0 <=? (prim length"); + assert.equal(weak.added1NeedsName, false); assert.equal(weak.added1NeedsMeal, true); + const kept = await judged("+ 1), guests := (nil Foundation.View.Browser.V1.Model::TableRow)", "+ 1), guests := (project state guests)"); + assert.equal(kept.cleared2Empties, false); assert.equal(kept.guestsStartsEmpty, true); }); test("what the chat says: each promise beside the exact statement proved, and never more than happened", () => { const theorems = theoremsOf(module), promises = promisesOf(module); - const proved = proofMessage({ ok: true, seconds: 742, record: { attestation_id: "d".repeat(64) }, theorems, promises }); - assert.match(proved, /^\*\*Proved by Lean\.\*\* 5 theorems/); + const proved = proofMessage({ ok: true, seconds: 0.2, record: {}, theorems, promises }); + assert.match(proved, /^\*\*Proved by Lean\.\*\* Lean's kernel, in this browser, accepted 6 theorems/); for (let i = 0; i < theorems.length; i++) assert.ok(proved.includes("- " + promises[i] + "\n Lean proved: `" + theorems[i].statement + "`"), theorems[i].name); assert.match(proved, /A sentence can say more than its theorem/); assert.match(proved, /cannot be published yet/); - const refused = proofMessage({ ok: false, error: "the proof of `clearEmpties` does not close", diagnostics: [{ code: "LLV7001" }], theorems: [], promises: [] }); - assert.match(refused, /Lean refused it/); - // The verifier failing is not the app failing, and is not blamed on a property. - const broken = proofMessage({ ok: false, error: "staging process: No space left on device (os error 28)", diagnostics: [{ code: "LLB6003" }], theorems: [], promises: [] }); - assert.match(broken, /The verifier could not run the proof/); + const refused = proofMessage({ ok: false, error: "Lean's kernel refused cleared2Empties", theorems: [], promises: [] }); + assert.match(refused, /^\*\*Not proved\.\*\* Lean's kernel refused cleared2Empties\. The app is back to checked/); + assert.match(refused, /fix the property/); + // The kernel not running is not the app failing, and is not blamed on a property. + const broken = proofMessage({ ok: false, error: "the proof worker did not answer", theorems: [], promises: [] }); + assert.match(broken, /could not run the proof/); assert.match(broken, /says nothing about the app/); - assert.ok(!/fix the property/.test(broken)); - assert.match(proofMessage({ ok: false, error: "the proof did not end in 15 minutes", theorems: [], promises: [] }), /verifier could not run/); - assert.match(refused, /^\*\*Not proved\.\*\*/); - assert.match(refused, /back to checked/); - assert.ok(!/Proved by Lean/.test(refused)); + assert.ok(!/fix the property/.test(broken) && !/Proved by Lean/.test(refused)); assert.match(provingMessage(5), /5 properties/); assert.match(provingMessage(1), /1 property /); assert.match(card({ phase: "proving" }), /Lean is proving/); - assert.match(card({ phase: "proved", theorems, proof: { attestation_id: "d".repeat(64) } }), /proved by Lean[\s\S]*5 theorems[\s\S]*cannot be published yet/); + assert.match(card({ phase: "proved", theorems }), /proved by Lean[\s\S]*6 theorems[\s\S]*cannot be published yet/); for (const phase of ["drafting", "checked", "proving"]) assert.ok(!/proved by Lean/i.test(card({ phase, issues: [] })), phase); + for (const text of [proved, refused, broken, provingMessage(2), card({ phase: "proving" })]) assert.ok(!/hosted|verifier|server/i.test(text), text); }); diff --git a/studio/tools/live_notation.test.mjs b/studio/tools/live_notation.test.mjs index 9a69b900..1f146bb2 100644 --- a/studio/tools/live_notation.test.mjs +++ b/studio/tools/live_notation.test.mjs @@ -2,23 +2,17 @@ // the canonical LexLean module they stand for. Claims held here: the same lines are always the same module; // the module is in the app shape with a theorem for every promise; lines that do not read are refused with // the line and the reason; and a chat turn written in the notation is the module to everything after it. -// The hosted checker is asked only when LIVE_APP_HOSTED=1; the data form is read and run in the tab. +// The data form is read, run and checked in the tab. // // node --test tools/live_notation.test.mjs -// LIVE_APP_HOSTED=1 node --test tools/live_notation.test.mjs import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import crypto from "node:crypto"; import { expand, parse, isNotation, PROMPT } from "../shell/live/notation.mjs"; -import { moduleFromTurn, isAppShape, splitDeclarations, wholePrefix, theoremsOf, promisesOf, moduleContext, notationRepairPrompt, notationCard, checkApp, checkLibrary, semanticData, createApp, PROMPT as APP_PROMPT } from "../shell/live/app.mjs"; - -import { describeHostedSource } from "../shell/hosted-source-permission.mjs"; -// Only the opt-in hosted fixture uses this explicit authorization. -const permissionOptions = { authorize: async input => ({ disclosure: describeHostedSource(input), expires: Date.now() + 10000, signal: new AbortController().signal, close() {} }), online: () => true }; +import { moduleFromTurn, isAppShape, splitDeclarations, wholePrefix, theoremsOf, promisesOf, moduleContext, notationRepairPrompt, notationCard, checkApp, semanticData, createApp, PROMPT as APP_PROMPT } from "../shell/live/app.mjs"; const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8"); -const hosted = process.env.LIVE_APP_HOSTED === "1"; // Each fixture, with the SHA-256 of the module it stands for. The four model-* files are what GLM 5.3 Flash // wrote through the site's relay on 2026-11-12 from these instructions; every module here passed the hosted // checker, and Lean verified each one in the locked SDK image (VERIFICATION.md, row Notation). @@ -140,10 +134,9 @@ const DATA = { "guests": "d2e7fb0a560bdc05", "notes": "22f327367fa623d4", "order const canon = (x) => JSON.stringify(x, (k, v) => (v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v)); test("every module is read in the tab as LexLean reads it, and runs: a row is added, a bad one is refused, a clear empties", async () => { const library = { "Foundation.View.Browser.V1.Model": JSON.parse(read("../shell/live/v2/Model.json")) }; - const checkLib = checkLibrary((p) => Promise.resolve(read("../shell/live/v2/" + p))); for (const name of Object.keys(FIXTURES)) { const { module } = expand(lines(name)); - if (hosted) assert.deepEqual((({ ok, issues }) => ({ ok, issues }))(await checkApp(module, checkLib, undefined, permissionOptions)), { ok: true, issues: [] }, name); + assert.deepEqual((({ ok, issues }) => ({ ok, issues }))(await checkApp(module, library)), { ok: true, issues: [] }, name); const data = semanticData(module); assert.equal(crypto.createHash("sha256").update(canon(data)).digest("hex").slice(0, 16), DATA[name], name + " is read otherwise than LexLean reads it"); const app = createApp(data, library); diff --git a/studio/tools/main_stateful_integration.test.mjs b/studio/tools/main_stateful_integration.test.mjs index b85c7693..c643bad1 100644 --- a/studio/tools/main_stateful_integration.test.mjs +++ b/studio/tools/main_stateful_integration.test.mjs @@ -17,9 +17,9 @@ function harness({phase = 'checked', race, mutate = source => source} = {}) { applicationShape: () => 'stateful', boundApplicationState: async source => source.applicationState, get: async (_store, key) => new Map(current.files).get(key.replace(/^1:/, '')), kappa: async () => 'identity', now: () => 'now', - appShape: {SOURCE_PATH: 'prism/App.lex.tex', STATE_PATH: 'prism/app.json', isAppShape: () => true, theoremsOf: () => [{}], promisesOf: () => [], provingMessage: () => 'proving', proofMessage: () => '', proofFiles: () => ({}), withAxioms: source => source}, - appLibrary: Promise.resolve({}), readEngine: async () => {}, - prism: {proveFiles: async files => {log.proofs++; await files({}); return {ok: true, record: {id: 'attestation'}};}}, + appShape: {SOURCE_PATH: 'prism/App.lex.tex', STATE_PATH: 'prism/app.json', isAppShape: () => true, theoremsOf: () => [{}], promisesOf: () => [], provingMessage: () => 'proving', proofMessage: () => '', semanticData: () => ({})}, + appModel: async () => ({declarations: []}), kernelReady: Promise.resolve({}), + prism: {proveModule: async () => {log.proofs++; return {ok: true, record: {id: 'attestation'}};}}, nextPhase: async (_phase, event) => {if (event === race) current = snapshot('competing-edit'); return event === 'approve' ? 'proving' : 'proved';}, applyStoredProjectPatch: async (_db, _app, _patch, options) => { if (options.source.reference !== current.reference) throw Object.assign(Error('source changed'), {code: 'projectEditConflict'}); diff --git a/studio/tools/proof_approval_cancellation.test.mjs b/studio/tools/proof_approval_cancellation.test.mjs index bceb07e2..98ad66e9 100644 --- a/studio/tools/proof_approval_cancellation.test.mjs +++ b/studio/tools/proof_approval_cancellation.test.mjs @@ -64,9 +64,9 @@ function lifecycleHarness({shape='app',refreshFails=false,libraryFails=false,pro } if(JSON.stringify(state)!==JSON.stringify(expected))return false;state=structuredClone(next);log.commits++;return true; }, - refreshApp:refresh,refreshLive:refresh,appLibrary:libraryFails||transientLibrary?null:Promise.resolve({}),readEngine:()=>{}, - appShape:{SOURCE_PATH:'prism/App.lex.tex',STATE_PATH:'prism/app.json',theoremsOf:()=>[{}],promisesOf:()=>[],provingMessage:()=> 'proving',proofMessage:()=> 'done',withAxioms:value=>value,proofFiles:()=>{if(proofFilesFail)throw Error('local render failed');return{files:[],entrypoints:[]};},checkLibrary:async()=>{log.libraryLoads++;if(libraryFails || (transientLibrary && log.libraryLoads===1))throw Error('library failed');return {};}}, - prism:{proveFiles:prover,prove:(spec,options)=>{log.proofSpecs.push(structuredClone(spec));return prover(null,options);},provingMessage:()=> 'proving'},put:async()=>{},enc:new TextEncoder(),kappa:async()=> 'source-id', + refreshApp:refresh,refreshLive:refresh,appModel:async()=>{log.libraryLoads++;if(libraryFails || (transientLibrary && log.libraryLoads===1))throw Error('library failed');return{declarations:[]};}, + appShape:{SOURCE_PATH:'prism/App.lex.tex',STATE_PATH:'prism/app.json',theoremsOf:()=>[{}],promisesOf:()=>[],provingMessage:()=> 'proving',proofMessage:()=> 'done',semanticData:()=>{if(proofFilesFail)throw Error('local render failed');return{};}}, + prism:{proveModule:(_source,_data,_library,options)=>prover(null,options),prove:(spec,options)=>{log.proofSpecs.push(structuredClone(spec));return prover(null,options);},provingMessage:()=> 'proving'},put:async()=>{},enc:new TextEncoder(),kappa:async()=> 'source-id', }; const api=vm.runInNewContext(mutate(['approveApp','proveApp','approveRules','proveRules'].map(functionOf).join('\n'))+';({approveApp,approveRules})',environment); return{original,log,controller,observed,wait:()=>{waiting=true;},release:()=>release(),state:()=>structuredClone(state),files:()=>new Map(files),editOther:text=>{files.set('notes.txt',text);revision++;},replace:next=>{state=structuredClone(next);revision++;},approve:()=>shape==='app'?api.approveApp(7,snapshot(),{signal:controller.signal,approvalId:'attempt-one'}):api.approveRules(7,{signal:controller.signal,approvalId:'attempt-one'})}; @@ -132,15 +132,13 @@ test('submission consumes rollback authority and proof completion remains source const before=lifecycleHarness({shape:'rules'}),approved=await before.approve();before.replace({...before.state(),specKappa:'before-start-reword',spec:{...before.state().spec,title:'new words before start'}});assert.equal((await approved.prove()).ok,true);assert.equal(before.state().phase,'proved');assert.equal(before.state().spec.title,'new words before start');assert.equal(before.log.submits,1);assert.deepEqual(before.log.proofSpecs,[before.original.spec],'submission retains the originally approved payload despite later wording'); }); -test('the production prover checks cancellation after local files resolve immediately before its first transfer',async()=>{ - const {proveFiles}=await import('../shell/prism.js');const originalFetch=globalThis.fetch;let requests=0; - globalThis.fetch=async()=>{requests++;return{status:200,text:async()=>JSON.stringify({result:{isError:true}})};}; - try{ - const controller=new AbortController();await assert.rejects(proveFiles(async()=>{controller.abort();return{files:[],entrypoints:[]};},{beforeSubmit:()=>assertGenerationActive(controller.signal)}),{code:'generationCancelled'});assert.equal(requests,0); - let admitted=0;await proveFiles(async()=>({files:[],entrypoints:[]}),{beforeSubmit:()=>admitted++});assert.equal(admitted,1);assert.equal(requests,1); - }finally{globalThis.fetch=originalFetch;} - const source=fs.readFileSync(new URL('../shell/prism.js',import.meta.url),'utf8'),start=source.indexOf('export async function proveFiles('),end=source.indexOf('\n}\n',start)+3; - const run=source.slice(start,end).replace('export ','');assert.ok(run.includes('if (!submitted) { beforeSubmit(); submitted = true; }')); - const mutant=vm.runInNewContext(run.replace('beforeSubmit(); submitted = true;','submitted = true;')+';proveFiles',{callTool:async()=>({isError:true})}); - await assert.rejects(async()=>{await assert.rejects(mutant(async()=>({files:[],entrypoints:[]}),{beforeSubmit:()=>{throw Object.assign(Error('cancelled'),{code:'generationCancelled'});}}),{code:'generationCancelled'});},{name:'AssertionError'}); +test('the in-tab prover checks cancellation immediately before it asks the kernel',async()=>{ + const source=fs.readFileSync(new URL('../shell/prism.js',import.meta.url),'utf8'),start=source.indexOf('export async function proveModule('),end=source.indexOf('\n}\n',start)+3; + const run=source.slice(start,end).replace('export ','');assert.ok(run.includes('beforeSubmit(); r = await')); + const make=(text)=>{const log={asked:0};return{log,prove:vm.runInNewContext('let lean=null;'+text+';proveModule',{Date,Set,String,moduleTerms:()=>({defs:[],theorems:[{name:'Tab.app.t'}],refused:[]}),openLean:async()=>({module:async()=>{log.asked++;return{refusal:'no kernel here'};}})})};}; + const controller=new AbortController(),cancelled=make(run); + await assert.rejects(cancelled.prove('m',{},[],{beforeSubmit:()=>{controller.abort();assertGenerationActive(controller.signal);}}),{code:'generationCancelled'});assert.equal(cancelled.log.asked,0); + let admitted=0;const admittedRun=make(run);assert.equal((await admittedRun.prove('m',{},[],{beforeSubmit:()=>admitted++})).ok,false);assert.equal(admitted,1);assert.equal(admittedRun.log.asked,1); + const mutant=make(run.replace('beforeSubmit(); r = await','r = await')); + await assert.rejects(async()=>{await assert.rejects(mutant.prove('m',{},[],{beforeSubmit:()=>{throw Object.assign(Error('cancelled'),{code:'generationCancelled'});}}),{code:'generationCancelled'});},{name:'AssertionError'}); }); diff --git a/studio/tools/proof_reuse.test.mjs b/studio/tools/proof_reuse.test.mjs deleted file mode 100644 index e424a949..00000000 --- a/studio/tools/proof_reuse.test.mjs +++ /dev/null @@ -1,283 +0,0 @@ -// FA-28: a theorem Lean proved before, on the same exact declarations, is not proved again; only the -// theorems that changed go to Lean, and when none did Lean does not run. The verifier here is a fake that -// records what it is sent and attests exactly the files it verified; everything else is the real code. -import assert from "node:assert/strict"; -import fs from "node:fs"; -import vm from "node:vm"; -import { test } from "node:test"; -import { fileURLToPath } from "node:url"; -import * as prism from "../shell/prism.js"; -import { addresses, admit, canonical, headersOf, sha256, theoremsOf, REFUSAL, KEY_PREFIX } from "../shell/prism/proof-reuse.mjs"; -import { names, renderModel } from "../shell/prism/render.mjs"; - -const RAW = { - purpose: "Parking fee: decide the fee tier for one stay.", title: "Parking Fee", - fields: [{ name: "hours", kind: "number", min: 0, max: 24 }, { name: "vehicle", kind: "choice", values: ["car", "motorcycle", "truck"] }], - outcomes: ["free", "standard", "premium"], - rules: [{ when: [{ field: "hours", op: "=", value: 0 }], then: "free" }, { when: [{ field: "vehicle", op: "is", value: "truck" }], then: "premium" }, { when: [{ field: "hours", op: ">", value: 12 }], then: "premium" }], - otherwise: "standard", - properties: [ - { kind: "never", when: [{ field: "hours", op: "=", value: 0 }], then: "premium" }, - { kind: "never", when: [{ field: "vehicle", op: "is", value: "car" }, { field: "hours", op: "<", value: 5 }], then: "premium" }, - { kind: "always", when: [{ field: "vehicle", op: "is", value: "truck" }, { field: "hours", op: ">", value: 0 }], then: "premium" }, - ], - examples: [], -}; -const specOf = (raw) => { const r = prism.checkSpec(structuredClone(raw)); assert.ok(r.ok, (r.issues || []).join("; ")); return r.spec; }; -const SPEC = specOf(RAW); -const PROFILE_ID = "a".repeat(64); -const TRUST = { schema: "lexlean-mcp/proof-reuse-trust/1", epoch: "e".repeat(64), toolchain: { lean: "1".repeat(64), lake: "2".repeat(64), leanchecker: "3".repeat(64), lexlean: "4".repeat(64), compilerSemantics: "5".repeat(64) } }; -const identity = () => ({ server: "https://mcp.uor.foundation/", profile: "prism-app", profileId: PROFILE_ID, trust: structuredClone(TRUST) }); - -// A stateful app's module, as the LexLean-module path sends it: definitions and two theorems in one file. -const MODULE = (limit = 3) => [ - "\\begin{lexlean}{App}", "\\useglossary{lexlean.std.nat@1.2.0}", "\\title{Counter}", "\\begin{semanticmodule}", - "definition{name: cap, parameters: [], result: Nat, body: 9}", "", - "definition{name: bump, parameters: [n : Nat], result: Nat, body: (if (n async () => ({ files: [{ path: "src/Library.lex.tex", content: "library bytes" }, { path: "src/App.lex.tex", content: source }], entrypoints: ["src/App.lex.tex"] }); - -// The fake's Lean observes [propext] for the first model definition of the decision app, so an unseeded -// decision proof takes one axiom correction round, as the hosted verifier does. -const observed = /definition\{\s*name: (\w+),/.exec(renderModel(SPEC))[1]; - -function fakeVerifier({ profileId = PROFILE_ID } = {}) { - const v = { calls: [], verifies: [], attested: new Set(), drafts: new Map(), forget: false, n: 0, trust: structuredClone(TRUST), evidence: new Map() }; - const reply = (id, result) => new Response(JSON.stringify({ jsonrpc: "2.0", id, result }), { headers: { "content-type": "application/json" } }); - v.fetch = async (url, init) => { - if (String(url).startsWith("file:")) return new Response(fs.readFileSync(fileURLToPath(url), "utf8")); - const { id, method, params } = JSON.parse(init.body); - assert.equal(method, "tools/call"); - const { name, arguments: args } = params; - v.calls.push(name); - if (name === "lexlean_profiles") return reply(id, { structuredContent: { profiles: [{ id: profileId, name: "prism-app", proof_reuse: v.trust }] } }); - if (name === "lexlean_attestation") { - const evidence = v.evidence.get(args.value); - return reply(id, { structuredContent: { found: !v.forget && !!evidence, ...evidence } }); - } - if (name === "lexlean_draft_write") { const draft = "spec/" + (await sha256(JSON.stringify(args.files))); v.drafts.set(draft, args.files); return reply(id, { structuredContent: { draft } }); } - if (name === "lexlean_verify") { - const files = v.drafts.get(args.project); - v.verifies.push(files); - const model = files.find((f) => f.content.includes(`name: ${observed},`)); - const block = model ? model.content.slice(model.content.indexOf(`name: ${observed},`)).split("\n}\n")[0] : "axioms: [propext]"; - const body = block.includes("axioms: [propext]") - ? { attestation_id: (++v.n).toString(16).padStart(64, "0"), modules: args.files.map((p) => p.replace(/^src\//, "").replace(/\.lex\.tex$/, "").split("/").join(".")) } - : { diagnostics: [{ message: `\`Spec.${observed}\` violates its exact axiom policy: observed [propext]` }] }; - if (body.attestation_id) { - const digests = await Promise.all(files.map((f) => sha256(f.content))); - for (const digest of digests) v.attested.add(digest); - v.evidence.set(body.attestation_id, { attestation_id: body.attestation_id, status: "verified", files: digests, proof_reuse: structuredClone(v.trust) }); - } - return reply(id, { taskId: "t" + v.verifies.length, status: "completed", result: { structuredContent: { state: body.attestation_id ? "verified" : "failed" }, content: [{ text: JSON.stringify(body) }] } }); - } - throw new Error("unexpected tool " + name); - }; - return v; -} -function memoryStore() { - const m = new Map(); - return { m, get: async (k) => m.get(k), put: async (k, val) => { m.set(k, structuredClone(val)); } }; -} -async function withVerifier(v, fn) { - const saved = globalThis.fetch; - globalThis.fetch = v.fetch; - try { return await fn(); } finally { globalThis.fetch = saved; } -} -const theoremsSent = (files) => [...files.map((f) => f.content).join("\n").matchAll(/theorem\{\s*name: (\w+),/g)].map((m) => m[1]); - -test("in a LexLean module, editing one theorem re-proves it alone; editing a definition re-proves its dependants", async () => { - const v = fakeVerifier(), store = memoryStore(); - const first = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(first.ok, true, first.error); - assert.deepEqual(theoremsSent(v.verifies.at(-1)), ["bumpBounded", "capSmall"]); - const runs = v.verifies.length; - const edited = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE(4)), { store })); - assert.equal(edited.ok, true, edited.error); - assert.equal(v.verifies.length, runs + 1); - assert.deepEqual(theoremsSent(v.verifies.at(-1)), ["capSmall"], "bumpBounded is left out of the file"); - assert.equal(edited.record.reused, 1); - // A definition only one theorem reaches does not move the other; one both reach moves both. - const relabel = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE(4).replace('"counter"', '"tally"')), { store })); - assert.equal(relabel.record.reused, 2, "label is reached by neither theorem"); - const recap = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE(4).replace("body: 9}", "body: 8}")), { store })); - assert.equal(recap.record.reused, 0, "cap is reached by both"); -}); - -test("addresses ignore axioms and layout, and move with the verifier, the library and any reached byte", async () => { - const id = identity(); - const { files, entrypoints } = await moduleFiles(MODULE())(); - const base = await addresses({ files, entrypoints, verifier: id }); - assert.equal(new Set(Object.values(base)).size, 2); - for (const changed of ["epoch", ...Object.keys(TRUST.toolchain)]) { - const verifier = identity(); - if (changed === "epoch") verifier.trust.epoch = "f".repeat(64); else verifier.trust.toolchain[changed] = "f".repeat(64); - const other = await addresses({ files, entrypoints, verifier }); - for (const key of Object.keys(base)) assert.notEqual(other[key], base[key], changed); - } - const relaid = MODULE().replace("theorem{name: bumpBounded, ", "theorem{\n name: bumpBounded,\n ").replace("proof: linear_arithmetic{definitions: [bump, cap]}}", "proof: linear_arithmetic{definitions: [bump, cap]},\n axioms: [\n Quot.sound,\n propext\n ]\n}"); - assert.deepEqual(await addresses({ files: [files[0], { ...files[1], content: relaid }], entrypoints, verifier: id }), base); - const moved = [ - await addresses({ files, entrypoints, verifier: { ...id, profileId: "b".repeat(64) } }), - await addresses({ files: [{ ...files[0], content: "other library" }, files[1]], entrypoints, verifier: id }), - await addresses({ files: [files[0], { ...files[1], content: MODULE().replace("result: Nat, body: (if", "result: Nat, body: (if") }], entrypoints, verifier: id }), - ]; - for (const other of moved.slice(0, 2)) for (const k of Object.keys(base)) assert.notEqual(other[k], base[k]); - assert.deepEqual(moved[2], base, "layout whitespace is not a byte the kernel sees"); - // A reached definition moves the address; one the theorem does not reach leaves it. - const bounded = "src/App.lex.tex#bumpBounded"; - const recapped = await addresses({ files: [files[0], { ...files[1], content: MODULE().replace("body: 9}", "body: 8}") }], entrypoints, verifier: id }); - const relabelled = await addresses({ files: [files[0], { ...files[1], content: MODULE().replace('"counter"', '"tally"') }], entrypoints, verifier: id }); - assert.notEqual(recapped[bounded], base[bounded]); - assert.equal(relabelled[bounded], base[bounded]); - assert.notEqual(canonical('definition{name: g, body: (f ab)}'), canonical('definition{name: g, body: (fa b)}')); - assert.notEqual(canonical('definition{name: g, body: "a b"}'), canonical('definition{name: g, body: "a b"}')); -}); - -test("a record is refused unless its address, verifier, bytes and attestation all re-derive", async () => { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const { files, entrypoints } = await moduleFiles(MODULE())(); - const authors = files.filter((f) => entrypoints.includes(f.path)); - const verifier = identity(); - const address = await addresses({ files, entrypoints, verifier }); - const theorem = theoremsOf(authors).find((t) => t.name === "bumpBounded"); - const entry = store.m.get(KEY_PREFIX + address[theorem.id]); - const found = async (id) => ({ found: !v.forget, ...v.evidence.get(id) }); - const check = (e, more = {}) => admit({ entry: e, theorem, address: address[theorem.id], verifier, headers: headersOf(authors), found, ...more }); - assert.deepEqual(await check(entry), { admitted: true }); - assert.equal((await check(null)).refusal, REFUSAL.absent); - assert.equal((await check(entry, { verifier: { ...verifier, trust: null } })).refusal, REFUSAL.trustUnavailable); - assert.equal((await check({ ...entry, schema: "other" })).refusal, REFUSAL.malformed); - assert.equal((await check({ ...entry, theorem: "src/App.lex.tex#capSmall" })).refusal, REFUSAL.malformed); - assert.equal((await check({ ...entry, address: "c".repeat(64) })).refusal, REFUSAL.address); - assert.equal((await check(entry, { verifier: { ...verifier, profileId: "d".repeat(64) } })).refusal, REFUSAL.verifier); - const altered = (content) => ({ ...entry, files: [{ ...entry.files[0], content }] }); - assert.equal((await check(altered(entry.files[0].content + "\n"))).refusal, REFUSAL.bytes, "content no longer matches its digest"); - const rehash = async (content) => ({ ...entry, files: [{ path: entry.files[0].path, content, sha256: await sha256(content) }] }); - assert.equal((await check(await rehash(entry.files[0].content.replace("body: 9}", "body: 8}")))).refusal, REFUSAL.bytes, "a reached definition differs"); - assert.equal((await check(await rehash(entry.files[0].content.replace("\\title{Counter}", "\\title{Other}")))).refusal, REFUSAL.bytes, "another header"); - assert.equal((await check(await rehash(entry.files[0].content + "\n"))).refusal, REFUSAL.attestation, "bytes the verifier never attested"); - assert.equal((await check(entry, { found: async () => false })).refusal, REFUSAL.attestation); -}); - -test("the host proves a stateful app with a store over its refs records", () => { - const host = fs.readFileSync(new URL("../shell/host.js", import.meta.url), "utf8").replace(/\r\n/g, "\n"); - const app = host.slice(host.indexOf("async function proveApp(")); - assert.match(app.slice(0, app.indexOf("\n}\n")), /prism\.proveFiles\([\s\S]*?store: \{ get: \(key\) => get\("refs", key\), put: \(key, value\) => put\("refs", key, value\) \}/); -}); - -test("an unsupported or malformed service trust descriptor falls back to full proving without storing records", async () => { - for (const trust of [undefined, null, {}, { ...TRUST, epoch: "" }, { ...TRUST, toolchain: {} }]) { - const v = fakeVerifier(), store = memoryStore(); - v.trust = trust; - const first = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(first.ok, true); assert.equal(again.ok, true); - assert.equal(v.verifies.length, 2); - assert.equal(again.record.reused, 0); - assert.equal(store.m.size, 0, "unbound evidence is not filed for later reuse"); - assert.ok(again.record.theorems.every((t) => t.refusal === REFUSAL.trustUnavailable)); - } -}); - -test("same-profile toolchain upgrades and trust epoch rotation invalidate reuse in a long-lived tab", async () => { - for (const changed of ["epoch", ...Object.keys(TRUST.toolchain)]) { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - if (changed === "epoch") v.trust.epoch = "f".repeat(64); else v.trust.toolchain[changed] = "f".repeat(64); - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(again.ok, true); assert.equal(again.record.reused, 0, changed); - assert.equal(v.verifies.length, 2, changed); - } -}); - -test("retired SDK Lean executable addresses cannot authorize reuse", async () => { - for (const lean of ["e8baaa71855a616dc351028f3ad2200051b0671f423a1696a100e809302d5550", "79fb1d26fa5a39385d59fdc48a711a14b0710ca6480271acce99b4d177cea085"]) { - const v = fakeVerifier(), store = memoryStore(); v.trust.toolchain.lean = lean; - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(again.record.reused, 0); assert.equal(store.m.size, 0); - } -}); - -test("bare found, wrong attestation, incomplete files, failed status and old trust evidence never authorize reuse", async () => { - for (const plant of [ - (e) => ({ found: true }), - (e) => ({ ...e, attestation_id: "0".repeat(64) }), - (e) => ({ ...e, files: [] }), - (e) => ({ ...e, status: "failed" }), - (e) => ({ ...e, proof_reuse: { ...e.proof_reuse, epoch: "0".repeat(64) } }), - ]) { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - for (const [id, e] of v.evidence) v.evidence.set(id, plant(e)); - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(again.ok, true); assert.equal(again.record.reused, 0); - assert.equal(v.verifies.length, 2); - } -}); - -test("legacy and forged-policy records are invalidated even when copied to the new address", async () => { - for (const change of [(e) => ({ ...e, schema: "prism/proof-reuse/1" }), (e) => ({ ...e, policyEpoch: "retired" }), (e) => ({ ...e, trust: { ...TRUST, epoch: "0".repeat(64) } })]) { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - for (const [key, e] of store.m) store.m.set(key, change(e)); - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(again.record.reused, 0); assert.equal(v.verifies.length, 2); - } -}); - -test("an epoch change while admitting cached records reruns the full proof", async () => { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const original = v.fetch; - let rotated = false; - v.fetch = async (url, init) => { - const result = await original(url, init); - if (init && JSON.parse(init.body).params.name === "lexlean_attestation" && !rotated) { v.trust.epoch = "f".repeat(64); rotated = true; } - return result; - }; - const again = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - assert.equal(again.ok, true); assert.equal(again.record.reused, 0); assert.equal(v.verifies.length, 2); - assert.deepEqual(theoremsSent(v.verifies.at(-1)), ["bumpBounded", "capSmall"]); -}); - -test("a proof completed by a different toolchain is not relabelled or mixed with earlier reused proofs", async () => { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const original = v.fetch; - let rotated = false; - v.fetch = async (url, init) => { - if (init && JSON.parse(init.body).params.name === "lexlean_verify" && !rotated) { v.trust.epoch = "f".repeat(64); rotated = true; } - return original(url, init); - }; - const edited = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE(4)), { store })); - assert.equal(edited.ok, true); assert.equal(edited.record.reused, 0); - assert.deepEqual(theoremsSent(v.verifies.at(-1)), ["bumpBounded", "capSmall"]); - for (const record of store.m.values()) assert.equal(record.trust.epoch, TRUST.epoch, "changed toolchain never stamped on prior records"); -}); - - -test("an epoch rotation during final attestation retrieval cannot commit a mixed verdict", async () => { - const v = fakeVerifier(), store = memoryStore(); - await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE()), { store })); - const original = v.fetch; - let rotated = false; - v.fetch = async (url, init) => { - const result = await original(url, init); - const params = init && JSON.parse(init.body).params; - if (params?.name === "lexlean_attestation" && params.arguments.value === "2".padStart(64, "0") && !rotated) { - v.trust.epoch = "f".repeat(64); rotated = true; - } - return result; - }; - const edited = await withVerifier(v, () => prism.proveFiles(moduleFiles(MODULE(4)), { store })); - assert.equal(rotated, true); assert.equal(edited.ok, true); assert.equal(edited.record.reused, 0); - assert.deepEqual(theoremsSent(v.verifies.at(-1)), ["bumpBounded", "capSmall"]); - assert.equal(store.m.size, 2, "the mixed candidate never enters the reuse store"); -}); diff --git a/studio/tools/proof_reuse_live.mjs b/studio/tools/proof_reuse_live.mjs deleted file mode 100644 index 97f96597..00000000 --- a/studio/tools/proof_reuse_live.mjs +++ /dev/null @@ -1,51 +0,0 @@ -// FA-85 against the real hosted verifier (https://mcp.uor.foundation/), not part of the gate: it sends -// the fixture's files (unlisted, not private) and takes minutes. It proves a decision app cold, again -// unchanged, and again with one guarantee edited, with one in-memory store, and prints what each run -// cost and what it reused. -// node tools/proof_reuse_live.mjs -import fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import * as prism from "../shell/prism.js"; -import { names } from "../shell/prism/render.mjs"; - -const RAW = { - purpose: "Parking fee: decide the fee tier for one stay.", title: "Parking Fee", - fields: [{ name: "hours", kind: "number", min: 0, max: 24 }, { name: "vehicle", kind: "choice", values: ["car", "motorcycle", "truck"] }], - outcomes: ["free", "standard", "premium"], - rules: [{ when: [{ field: "hours", op: "=", value: 0 }], then: "free" }, { when: [{ field: "vehicle", op: "is", value: "truck" }], then: "premium" }, { when: [{ field: "hours", op: ">", value: 12 }], then: "premium" }], - otherwise: "standard", - properties: [ - { kind: "never", when: [{ field: "hours", op: "=", value: 0 }], then: "premium" }, - { kind: "never", when: [{ field: "vehicle", op: "is", value: "car" }, { field: "hours", op: "<", value: 5 }], then: "premium" }, - { kind: "always", when: [{ field: "vehicle", op: "is", value: "truck" }, { field: "hours", op: ">", value: 0 }], then: "premium" }, - ], - examples: [], -}; -const specOf = (raw) => { const r = prism.checkSpec(structuredClone(raw)); if (!r.ok) throw new Error(r.issues.join("; ")); return r.spec; }; -const m = new Map(); -const store = { get: async (k) => m.get(k), put: async (k, v) => { m.set(k, structuredClone(v)); } }; - -// Count what reaches the verifier, by tool. -const calls = {}; -const real = globalThis.fetch; -globalThis.fetch = async (url, init) => { - // The shell reads its library modules beside itself; Node's fetch has no file: scheme. - if (String(url).startsWith("file:")) return new Response(fs.readFileSync(fileURLToPath(url), "utf8")); - if (init && init.body && String(url).startsWith("https://")) { try { const b = JSON.parse(init.body); const n = b.params?.name || b.method; calls[n] = (calls[n] || 0) + 1; } catch {} } - return real(url, init); -}; -async function step(label, spec) { - for (const k of Object.keys(calls)) delete calls[k]; - const t0 = Date.now(); - const r = await prism.prove(spec, { store }); - const ms = Date.now() - t0; - const sent = r.ok ? (r.record.theorems || []).filter((t) => !t.reused).map((t) => t.theorem.split("#")[1]) : []; - console.log(JSON.stringify({ label, ok: r.ok, error: r.error || null, ms, reused: r.ok ? r.record.reused : null, proved: r.ok ? r.record.proved : null, sent, attestation: r.ok ? r.record.attestation_id : null, refusals: r.ok ? r.record.theorems.map((t) => t.refusal) : null, calls: { ...calls } })); - return r; -} -await step("cold", specOf(RAW)); -await step("unchanged", specOf(RAW)); -const edited = structuredClone(RAW); edited.properties[1].when[1].value = 4; -const spec = specOf(edited); -console.log("edited theorem:", names(spec).properties[spec.properties[1].id].theorem); -await step("one guarantee edited", spec); diff --git a/studio/tools/v2_engine.mjs b/studio/tools/v2_engine.mjs index bb999516..72e98afd 100644 --- a/studio/tools/v2_engine.mjs +++ b/studio/tools/v2_engine.mjs @@ -13,14 +13,10 @@ const COPIES = { "studio/shell/live/v2/interp.mjs": "v2/shell/interp.mjs", "studio/shell/live/v2/render.mjs": "v2/shell/render.mjs", "studio/shell/live/v2/Model.json": "v2/probe-payment/data/Foundation/View/Browser/V1/Model.json", - "studio/shell/live/v2/check.mjs": "v2/hosted-check/check.mjs", "studio/shell/live/v2/Model.lex.tex": "v2/probe-payment/src/Foundation/View/Browser/V1/Model.lex.tex", }; // The instructions a model is given for the app shape, as a module the shell can import. const DERIVED = { "studio/shell/live/v2/rules.mjs": ["v2/loop/RULES.txt", (text) => "// Written by tools/v2_engine.mjs from v2/loop/RULES.txt. Edit that file, not this one.\nexport default " + JSON.stringify(text) + ";\n"] }; -// What the checker is told of the library: the image it was copied from, the title phrases the hosted -// lexicon lacks, and the one library module a stateful app may import, beside this file. -DERIVED["studio/shell/live/v2/library.json"] = ["v2/hosted-check/library.json", (text) => { const l = JSON.parse(text); return JSON.stringify({ image: l.image, titles: l.titles, modules: { "Foundation.View.Browser.V1.Model": "Model.lex.tex" } }, null, 1) + "\n"; }]; const mode = process.argv[2]; if (mode !== "--check" && mode !== "--write") { console.error("usage: node tools/v2_engine.mjs --check | --write"); process.exit(64); } let failed = 0; diff --git a/verification/proof-reuse-trust.md b/verification/proof-reuse-trust.md deleted file mode 100644 index 9a1c3e28..00000000 --- a/verification/proof-reuse-trust.md +++ /dev/null @@ -1,151 +0,0 @@ -# Toolchain-bound proof reuse (FA-85 hardening) - -Authority: `FoundrySpecification.proofReuseBoundary` and `ProofReuseRefusal`. -This tightens the existing FA-85 capability; its register ID and statement are unchanged. -The scenario and failing controls were committed before the implementation (`0bd1d24`). - -## Scope and current behavior - -The reuse schema is `prism/proof-reuse/2`. Its key includes the local policy epoch, the service trust -epoch, and the SHA-256 addresses of Lean, Lake, leanchecker, LexLean and compiler semantics, in -addition to the existing profile, library and declaration closure. A toolchain or epoch change moves -every address even if the profile ID does not change. The descriptor is read for each operation, -not cached for the page's lifetime. - -Every reused record must also carry those exact identities. Lookup is by its exact attestation ID, -not a digest which could resolve to another verification. The response must identify that attestation -as verified under the current descriptor and cover every recorded source digest. Bare existence is -insufficient. Before committing a reused verdict, the descriptor is read again. A change or failed -lookup reruns the entire proof without reuse. After a partial proof, attestation retrieval precedes -that final descriptor read. A completed proof is never filed by relabelling it with a later identity. - -Old records remain in the browser store but cannot be admitted. No destructive migration is needed. -The two Lean 4.32.1 executable digests in the existing `prismpm.lock` are retired for reuse. This is -not an allow-list of other toolchains and does not establish that another digest is sound. - -**Fresh-proof acceptance is unchanged.** Unsupported reuse metadata triggers full proving and no -reuse-store writes. This patch does not disable proof verification, change the SDK, alter publication, -or claim to fix a kernel. It does not re-evaluate persisted historical app badges outside a proof -request. A full fresh proof continues to trust the configured hosted verifier as before. - -## Service contract required for reuse - -This is a **proposed consumer contract**, not a claim about a deployed service feature. The service -owner must model, implement and qualify it before reuse is available. A profile response must include: - -```json -{ - "name": "prism-app", - "id": "<64 lowercase hex>", - "proof_reuse": { - "schema": "lexlean-mcp/proof-reuse-trust/1", - "epoch": "<64 lowercase hex>", - "toolchain": { - "lean": "<64 lowercase hex>", - "lake": "<64 lowercase hex>", - "leanchecker": "<64 lowercase hex>", - "lexlean": "<64 lowercase hex>", - "compilerSemantics": "<64 lowercase hex>" - } - } -} -``` - -The epoch must identify the service's current reuse policy and revocations. Tool addresses must be -computed from the running verification toolchain, not copied from a version banner or an old lock. -The attestation lookup must bind the original verification's descriptor, not stamp existing records -with today's descriptor. It must respond with structured fields `found: true`, `status: "verified"`, -`attestation_id`, `files` (an array of covered source SHA-256 digests), and `proof_reuse` (the original -verification descriptor). Any absent, malformed, mismatched or retired field prevents reuse. - -The client still trusts this HTTPS service to report its identity and evidence honestly. These -checks are not signature verification, an independent kernel check, a linearizable revocation -protocol, or a proof of service soundness. Cached axiom-map validation and extraction are unchanged; -this patch does not establish that all cached metadata is authenticated. With the current unsupported -service contract, no cached axiom map is imported. The final descriptor read establishes an observed current -epoch; a service that reuses epochs after rollback would violate this contract. - -## Observed SDK and gateway constraints, 2026-11-13 - -- Foundry main `efd525f91a62a0fc204c2a4b6c79df3963bb1318` pins - `ghcr.io/uor-foundation/prismpm-sdk-candidate@sha256:cd3b47d7a370c4a26b8285f5e9c3bb15e639973c55505c3809ddbe55352fea58`. - Both platform inventories identify Lean and leanchecker 4.32.1. -- Read-only `lexlean_profiles({profile:"prism-app"})` returned profile ID - `1cf3dece40ddac370598574170a00eca44fb5243e297e179b455801def90c2c8`, language, packages and roots. - It returned no current executable addresses or revocation epoch. `tools/list` provided no other - current-toolchain operation. -- A read-only lookup using the SHA-256 of Foundry's already-public Foundation/Bytes source returned - structured `{found:true}` and a DSSE envelope in text. Its predicate names the attestation, - build/source/semantic IDs, modules, covered file digests and verified status, but no toolchain or - trust epoch. No source was uploaded and no proof task was started for these observations. -- Gateway source at `UOR-Foundation/lexlean-mcp@64f3fcbc6206f4f20d63bef84a5382bcfa3dffbe` - documents the profile identity as lock-header compiler semantics and Lean-toolchain string plus - profile files and reviews, not running executable bytes (`PROFILES.md`, `provision.rs`). Its newer - `ATTESTATION.md` describes `attestationId` and an envelope in structured content. Those fields alone - still do not meet the proposed trust contract, and the observed deployment did not return them. - -These are observations, not a statement that the gateway's currently running Lean was measured. -A profile ID does not expose that fact. - -## Kernel risk and ownership - -[Lean issue 14576](https://github.com/leanprover/lean4/issues/14576) reports an axiom-free proof of False -through ill-typed nested-inductive projection terms. The upstream fix is -[Lean PR 14577](https://github.com/leanprover/lean4/pull/14577), which adds checks for nested inductive -parametric arguments. Its regression includes the reduced malformed-projection rejection. - -Foundry's decision route renders a restricted LexLean model; the stateful route sends author LexLean -modules through the same `proveFiles` boundary. The upstream reproduction uses Lean metaprogramming -and checked declaration construction. This review has **not** demonstrated that this reproduction is -reachable through either production Foundry input route, has not submitted it to the hosted service, -and has not tested it against the pinned SDK. A known dependency defect is not evidence of a Foundry -exploit. The generic gateway also supports core/tooling module data, so that larger input surface -requires its owner's separate reachability and regression work. - -Existing owners/work, rather than duplicate implementation: - -1. [LexLean PR 433](https://github.com/UOR-Foundation/LexLean/pull/433) owns the 4.32.1 to 4.33.1 - upgrade and its lock/export regeneration. Its recorded Atlas and full-gate blockers must be resolved. -2. [PrismPM issue 647](https://github.com/UOR-Foundation/PrismPM/issues/647), D9, tracks SDK adoption - of the repaired Lean. Foundry must consume a qualified immutable image through the SDK-owned path, - not patch the image locally or substitute a host Lean. -3. [LexLean PR 498](https://github.com/UOR-Foundation/LexLean/pull/498) owns shard toolchain-address - binding. It explicitly does not change published attestations. It does not supply this gateway contract. -4. The `lexlean-mcp` owner must expose the current identity and bind attestations to their original - identity and revocation epoch. Consumer mocks do not establish that service capability. -5. Foundry then qualifies the exact new SDK and gateway, runs the upstream malformed-term negative - control in both prescribed checking paths, performs new full proofs, and demonstrates that old - records cannot survive toolchain/epoch replacement. No release is declared repaired before that. - -## Verification of this candidate - -- `node --test studio/tools/proof_reuse.test.mjs`: 16 tests, 16 pass, no skips. -- The Rust conformance wrapper requires the exact TAP test/pass counts and zero failures, cancellations, - skips and todo results. The wrapper itself has not been executed in this environment. -- Final `node --test studio/tools/*.test.mjs`: 600 tests, 597 pass, zero fail, three existing - opt-in hosted checks skipped (19.1 seconds). -- Read-only review found a final-attestation epoch race. The descriptor read was moved after evidence - retrieval and a regression added. This is client-side admission hardening, not SDK qualification. -- `git diff --check` passes. - -Planted defects use the actual production module, run the full proof-reuse suite, then restore and -compare the file bytes. All seven listed defects exited 1, and the restored suite passed 16/16: - -| Plant | Expected rejecting control | -| --- | --- | -| Remove missing-trust admission refusal | Direct malformed-current-identity admission | -| Allow the retired Lean digests | Retired SDK executable control | -| Omit toolchain addresses from keys | Direct address-change assertions | -| Accept bare `found` | Exact attestation/coverage/status/trust controls | -| Ignore stored policy epoch/trust | Legacy and forged-policy records | -| Skip final mixed-proof epoch check | Mid-proof and final-attestation rotation controls | -| Skip all-reused epoch check | Rotation while admitting cached records | - -The first mutation run missed omission of toolchain bytes from the key and the direct missing-trust -check because other layers refused reuse. Direct address and typed-refusal assertions were added; -these are gate-quality corrections, not evidence that the surviving mutants authorized reuse. - -**Not run:** `just model-write`, the Rust wrapper, and full `just vv` inside the exact SDK. This executor -has Node but no Cargo, Just, Docker, PrismPM or Lean. `model/ids.toml`, authorities and ledger are -unchanged, so `CONFORMANCE.md` is expected to remain byte-identical, but the owning writer still needs -to be run in the SDK. CI must qualify the final candidate. No host substitution is a release pass. diff --git a/verification/proof-reuse.md b/verification/proof-reuse.md deleted file mode 100644 index 1f540832..00000000 --- a/verification/proof-reuse.md +++ /dev/null @@ -1,94 +0,0 @@ -# Proof reuse (FA-85) - -Authority: `app/src/FoundrySpecification.lex.tex::proofReuseBoundary` and `ProofReuseRefusal`. -Implementation: `studio/shell/prism/proof-reuse.mjs`, used by `proveFiles` in `studio/shell/prism.js`, -which both proof paths call (decision apps through `prove`, LexLean-module apps directly). The host passes a -store over its `refs` records on both paths. - -Order of work: the implementation and its Node suite were written before the register row; the row, -scenario and conformance test were added with `just new-capability` afterwards. R3's order was not -followed for this capability. - -## Current trust boundary - -FA-85 is hardened by [proof-reuse-trust.md](proof-reuse-trust.md). Reuse now requires a fresh, -toolchain-bound service descriptor and the exact attestation under that descriptor. Legacy records, -bare `found: true`, retired SDK Lean digests and unsupported metadata are refused for reuse. The live -service observed on 2026-11-13 does not supply this contract, so this candidate proves the entire app -and stores no reusable records there. Fresh-proof acceptance and publication are unchanged. - -The eight-test results and hosted timings below describe the original implementation, not the new -trust boundary or its current hosted performance. The new controls and qualification limits are in -the linked verification record. - -## Original implementation and measurements - - -Each theorem gets an address from the verifier's identity, the library files, the author modules' headers, -the theorem's own declaration and every author declaration it reaches by name. A verified run files one -record per proved theorem with the exact author files sent. A later proof reuses a theorem only when its -record re-derives (digests, headers, the theorem and every reached declaration held in the files) and the -verifier still reports an attestation for each file digest. Reused theorems are taken out of the files Lean -is sent; when all are reused, Lean does not run. - -What it does not do: it is not a second kernel check, it does not prove the verifier's lookup sound, a -verifier upgrade that keeps its profile identity reuses earlier proofs, and publication still proves the -whole app again in the SDK image. - -## Tested - -`node --test studio/tools/proof_reuse.test.mjs`: 8 of 8 pass, run by `crates/conformance/tests/proof_reuse.rs` -with an exact count. The verifier there is a fake that attests exactly the files it verified; the renderer, -the address, the admission and `proveFiles` are the real code. - -Planted defects, each applied to the file, the suite run, and the file restored byte for byte (SHA-256 -compared), after which 8 of 8 pass: - -| Defect | Failing tests | -| --- | --- | -| A failed reuse lookup fails the proof | 1 | -| The attestation lookup is skipped | 2 | -| The address omits reached declarations | 1 | -| The canonical form drops whitespace between tokens | 1 | -| Reused theorems are still sent to Lean | 2 | -| A store failure propagates | 1 | -| The header check is skipped | 1 | -| The host proves decision apps without a store | 1 | - -The address defect was first missed: admission still refused the stale record, so behaviour stayed safe, -but nothing tested the address itself. A direct assertion was added. The lookup defect was also first -missed, because the profile lookup is cached for the page's life; the test now fails the attestation -lookup, which runs on every decision. - -## Measured against the hosted verifier - -`node studio/tools/proof_reuse_live.mjs` (not part of the gate; sends the fixture's files, unlisted): - -Run on 2026-11-13, the parking-fee fixture with three guarantees, one in-memory store, Node 22.21 on -Windows. One run each; wall times include queueing on the shared verifier. - -| Step | Lean runs | Theorems sent | Reused | Wall time | Calls to the verifier | -| --- | --- | --- | --- | --- | --- | -| Cold | 1 | 3 | 0 | 105.4 s | profiles 1, draft 1, verify 1, task polls 16 | -| Unchanged | 0 | 0 | 3 | 1.9 s | attestation lookups 4 | -| One guarantee edited | 1 | 1 (`inv002Holds`) | 2 | 146.6 s | attestation lookups 4, draft 1, verify 1, task polls 10 | - -The unchanged case confirms the assumption the admission rests on: the hosted verifier reports an -attestation for the SHA-256 of each file it verified. The edited case sent one theorem instead of three -but took longer than the cold run: on the hosted verifier a run's cost is mostly fixed (queue, Lean start, -elaborating the model), so leaving theorems out saves Lean work, not wall time, at this size. The large -saving is when nothing the theorems depend on changed. Neither run needed an axiom correction round, so -the saving from cached axiom sets was not observed here; the Node suite covers it. - -## Gates - -`just vv` passed at c5372a3 inside `prismpm-sdk-candidate@sha256:cd3b47d7…`, from a clone on the WSL Linux -disk, in 2,782 s: fmt-check, model, template-check, lint, the workspace tests (`proof_reuse_fa_85` ok), -deny and app (`prismpm --project app verify`, attestation `6009c3b3ebea7c54c944d5c4f65437911f6b9f6490870a8fd31735e16e8a8d44`). -The only later change is this file. - -Every Studio Node suite was also run on this branch and on `main` 7b5fdb9. They differ only by -`proof_reuse` (new, 8 of 8) and `snapshot_bound_builds`, which needed the new module listed in its browser -fixture and passes 7 of 7. Six suites fail one test each on both, unchanged by this work: -backlog_workflows, browser_chat_mode_controls, command_ownership_registry, live_main_integration, -semantic_application_discovery and verified_host_bundle. They are not in `just vv`.