diff --git a/.github/workflows/studio.yml b/.github/workflows/studio.yml
index 0780033d..c08dc88c 100644
--- a/.github/workflows/studio.yml
+++ b/.github/workflows/studio.yml
@@ -10,9 +10,9 @@ on:
# shell serves (tools/v2_engine.mjs): a change there must be held to the Engine gate too.
push:
branches: [main]
- paths: ["studio/**", ".github/workflows/studio.yml", "v2/shell/**", "v2/loop/**", "v2/probe-payment/data/**", "v2/probe-payment/src/**", "v2/hosted-check/**"]
+ paths: ["studio/**", "app/src/RuleJudge.lex.tex", "app/src/WorkProtocol.lex.tex", "app/src/CompositionProtocol.lex.tex", "app/src/WorkOwnership.lex.tex", "app/src/FeatureComposition.lex.tex", "app/language/**", "app/lexlean.lock", "prismpm.lock", ".github/workflows/studio.yml", "v2/shell/**", "v2/loop/**", "v2/probe-payment/data/**", "v2/probe-payment/src/**", "v2/hosted-check/**"]
pull_request:
- paths: ["studio/**", ".github/workflows/studio.yml", "v2/shell/**", "v2/loop/**", "v2/probe-payment/data/**", "v2/probe-payment/src/**", "v2/hosted-check/**"]
+ paths: ["studio/**", "app/src/RuleJudge.lex.tex", "app/src/WorkProtocol.lex.tex", "app/src/CompositionProtocol.lex.tex", "app/src/WorkOwnership.lex.tex", "app/src/FeatureComposition.lex.tex", "app/language/**", "app/lexlean.lock", "prismpm.lock", ".github/workflows/studio.yml", "v2/shell/**", "v2/loop/**", "v2/probe-payment/data/**", "v2/probe-payment/src/**", "v2/hosted-check/**"]
permissions:
contents: read
@@ -75,6 +75,40 @@ jobs:
"$image" sh -c 'mkdir -p /tmp/home && lexlean fmt --check && lexlean lock --check && lexlean check'
mkdir -p .experience-checked
printf '%s\n' "$image" >.experience-checked/sdk
+ # The rule judge studio/proof proves sound is written there as LexLean writes RuleJudge in Lean. Kept by
+ # its address: every module RuleJudge's build reads, the project's lexicons and lock, the SDK, and the
+ # copy in Regions.lean.
+ - name: The rule judge Lean proves sound is the Lean LexLean writes for RuleJudge, kept by its address
+ id: rule_judge
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: .rule-judge-checked
+ key: rule-judge-lean-v1-${{ hashFiles('app/src/RuleJudge.lex.tex', 'app/src/WorkProtocol.lex.tex', 'app/src/CompositionProtocol.lex.tex', 'app/src/WorkOwnership.lex.tex', 'app/src/FeatureComposition.lex.tex', 'app/language/**', 'app/lexlean.toml', 'app/lexlean.lock', 'prismpm.lock', 'studio/proof/PrismLive/Regions.lean') }}
+ - name: Every RuleJudge definition in studio/proof is LexLean's own Lean for it, line for line
+ if: steps.rule_judge.outputs.cache-hit != 'true'
+ working-directory: ${{ github.workspace }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ image=$(sed -n 's/.*"sdk_image":"\([^"]*\)".*/\1/p' prismpm.lock)
+ [[ $image =~ ^[a-z0-9.-]+(:[0-9]{1,5})?/[a-z0-9./_-]+@sha256:[0-9a-f]{64}$ ]] || { echo 'prismpm.lock does not select an immutable SDK image' >&2; exit 64; }
+ cp -r app "$RUNNER_TEMP/app" && rm -rf "$RUNNER_TEMP/app/.lexlean"
+ docker run --rm --user "$(id -u):$(id -g)" --tmpfs /tmp:rw,exec,nosuid,size=1g --volume "$RUNNER_TEMP/app:/w" --workdir /w \
+ --env HOME=/tmp/home --entrypoint lexlean "$image" build src/RuleJudge.lex.tex
+ python3 - "$RUNNER_TEMP/app/.lexlean/build" studio/proof/PrismLive/Regions.lean <<'PY'
+ import glob, re, sys
+ build, regions = sys.argv[1:]
+ [mods] = glob.glob(build + "/*/modules/PrismForgeKernel")
+ text = open(regions).read()
+ for mod, names in {"WorkProtocol": ["word"], "RuleJudge": ["ruleOpHolds", "ruleCondsHold", "ruleSpan", "rulesEnd", "ruleOutcome", "ruleInBounds"]}.items():
+ blocks = open(f"{mods}/{mod}.lean").read().split("\n\n")
+ for n in names:
+ [b] = [b for b in blocks if re.match(r"@\[expose\] public def " + n + r"\b", b)]
+ if b.replace("@[expose] public def", "def", 1).strip() not in text:
+ sys.exit(f"{mod}.{n} in studio/proof/PrismLive/Regions.lean is not the Lean LexLean writes for it")
+ print("every RuleJudge definition studio/proof proves sound is LexLean's own")
+ PY
+ mkdir -p .rule-judge-checked && printf '%s\n' "$image" >.rule-judge-checked/sdk
- name: Verify the canonical PR concurrency boundary
run: python3 tools/studio_concurrency_projection.py --check
- name: The authored model is what the author script writes
@@ -270,7 +304,39 @@ jobs:
node tools/live_proof.mjs --check
export PATH="$HOME/.elan/bin:$PATH"
cd proof && lake build && lake env lean PrismLive/Axioms.lean | tee axioms.txt
- test "$(grep -c 'depends on axioms: \[propext, Quot.sound\]' axioms.txt)" = 2
+ test "$(grep -c 'depends on axioms: \[propext, Quot.sound\]' axioms.txt)" = 3
+ # The exporter is fixed by the commit shell/kernel/lean/manifest.json names, built with the toolchain
+ # studio/proof pins: those two are everything the cached binary depends on.
+ - name: Cache the Lean exporter the in-tab library is written with
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: ~/.cache/lean4export
+ key: lean4export-86e4a339507466921dc8c5417c8cb1de1ce7df60-${{ hashFiles('studio/proof/lean-toolchain') }}
+ - name: The in-tab library is studio/proof's export, byte for byte, and the pinned kernel judges it whole
+ if: ${{ !cancelled() && steps.shell_closure.conclusion == 'success' && steps.corpus.conclusion == 'success' }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ export PATH="$HOME/.elan/bin:$PATH"
+ ex=$HOME/.cache/lean4export commit=$(node -p 'require("./shell/kernel/lean/manifest.json").exporter.commit')
+ if [[ ! -x $ex/.lake/build/bin/lean4export ]]; then
+ rm -rf "$ex" && git clone -q https://github.com/leanprover/lean4export "$ex" && git -C "$ex" checkout -q "$commit"
+ cp proof/lean-toolchain "$ex/lean-toolchain" && (cd "$ex" && lake build)
+ fi
+ mapfile -t roots < <(node -p 'require("./shell/kernel/lean/manifest.json").exporter.roots.join("\n")')
+ (cd proof && LEAN_PATH="$PWD/.lake/build/lib/lean:$(lean --print-prefix)/lib/lean" "$ex/.lake/build/bin/lean4export" PrismLive.Regions -- "${roots[@]}") > "$RUNNER_TEMP/library.ndjson"
+ node --input-type=module -e '
+ import fs from "node:fs"; import zlib from "node:zlib"; import { createHash } from "node:crypto";
+ const dir = "shell/kernel/lean/", m = JSON.parse(fs.readFileSync(dir + "manifest.json")), sha = (b) => createHash("sha256").update(b).digest("hex");
+ const [glue, wasm, library] = [m.glue, m.wasm, m.library].map((f) => { const b = zlib.gunzipSync(fs.readFileSync(dir + f.file)); if (sha(b) !== f.sha256 || b.length !== f.bytes) throw new Error(f.file + " is not the pinned bytes"); return b; });
+ if (!library.equals(fs.readFileSync(process.argv[1]))) throw new Error("the library is not what studio/proof exports: rebuild it");
+ fs.writeFileSync(process.env.RUNNER_TEMP + "/lean-kernel.mjs", glue);
+ const lines = [], k = await (await import(process.env.RUNNER_TEMP + "/lean-kernel.mjs")).default({ instantiateWasm: (i, done) => { WebAssembly.instantiate(wasm, i).then((r) => done(r.instance, r.module)); return {}; }, print: (s) => lines.push(s), printErr: (s) => lines.push(s) });
+ k.FS.writeFile("/l.ndjson", library);
+ const b = m.binding, said = k.ccall("check_whole", "number", ["string"], ["/l.ndjson"]) === 0 && lines.at(-1);
+ if (said !== `Accepted ${b.declarations} declarations (${b.sentToTheKernel} sent to the kernel).` || b.kernel !== m.wasm.sha256 || b.loader !== m.glue.sha256 || b.library !== m.library.sha256) throw new Error("the binding is not what the kernel says: " + said);
+ console.log("the pinned kernel judged the library whole: " + said);
+ ' "$RUNNER_TEMP/library.ndjson"
- name: A published app's card draws what its live preview draws
if: ${{ !cancelled() && steps.shell_closure.conclusion == 'success' && steps.corpus.conclusion == 'success' }}
run: node tools/published_preview.mjs --check
diff --git a/README.md b/README.md
index 6b446508..34717fe3 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ AI can take you from prompt to production in minutes. What it can't tell you is
Prism AI Foundry adds the step that settles it: **formal verification**. Every rule your app promises is proved mathematically, for every possible input, before it can go live. Not tested. Proved.
-Building and previewing run in your browser, with no install and no sign-in. Publishing happens on your device too: the app becomes a holo, named by its contents, that you share as a file or a link. One step still leaves the browser today: Lean proves the rules on a hosted verifier. Proving in the browser alone is in progress.
+Building and previewing run in your browser, with no install and no sign-in. Publishing happens on your device too: the app becomes a holo, named by its contents, that you share as a file or a link. Proving does too: Lean's kernel, compiled to WebAssembly, proves an app's rules in your tab, and no server takes part. An app that keeps state between requests is still proved on a hosted verifier.
(back to top)
diff --git a/crates/conformance/tests/live_lexlean.rs b/crates/conformance/tests/live_lexlean.rs
index 89ca2ea2..9fb5178f 100644
--- a/crates/conformance/tests/live_lexlean.rs
+++ b/crates/conformance/tests/live_lexlean.rs
@@ -20,7 +20,7 @@ fn read(path: &str) -> String {
}
/// The studio workflow builds the proofs and refuses any axiom beyond propext and
-/// Quot.sound for both theorems, so the claim is checked where it is made.
+/// Quot.sound for all three theorems, so the claim is checked where it is made.
fn built_and_axioms_checked(theorem: &str) {
let workflow = read(".github/workflows/studio.yml");
assert!(
@@ -28,8 +28,8 @@ fn built_and_axioms_checked(theorem: &str) {
"the studio workflow no longer builds the proofs and prints their axioms"
);
assert!(
- workflow.contains(r#"depends on axioms: \[propext, Quot.sound\]' axioms.txt)" = 2"#),
- "the studio workflow no longer requires exactly propext and Quot.sound of both theorems"
+ workflow.contains(r#"depends on axioms: \[propext, Quot.sound\]' axioms.txt)" = 3"#),
+ "the studio workflow no longer requires exactly propext and Quot.sound of all three theorems"
);
let axioms = read("studio/proof/PrismLive/Axioms.lean");
assert!(
diff --git a/crates/conformance/tests/proof_reuse.rs b/crates/conformance/tests/proof_reuse.rs
index fee35feb..04c3aaf1 100644
--- a/crates/conformance/tests/proof_reuse.rs
+++ b/crates/conformance/tests/proof_reuse.rs
@@ -22,8 +22,8 @@ fn proof_reuse_fa_85() {
String::from_utf8_lossy(&output.stderr)
);
for required in [
- "# tests 16",
- "# pass 16",
+ "# tests 12",
+ "# pass 12",
"# fail 0",
"# cancelled 0",
"# skipped 0",
diff --git a/studio/proof/PrismLive/Axioms.lean b/studio/proof/PrismLive/Axioms.lean
index 9cf6c890..c6411c16 100644
--- a/studio/proof/PrismLive/Axioms.lean
+++ b/studio/proof/PrismLive/Axioms.lean
@@ -4,3 +4,4 @@ import PrismLive.VerdantRegions
-- The gate reads these lines: each must name only the axioms below, and no sorryAx.
#print axioms PrismLive.Kernel.regionCheck_sound
#print axioms VerdantR.all_hold
+#print axioms PrismLive.Kernel.ruleJudge_sound
diff --git a/studio/proof/PrismLive/Regions.lean b/studio/proof/PrismLive/Regions.lean
index 6850e73f..ff98c995 100644
--- a/studio/proof/PrismLive/Regions.lean
+++ b/studio/proof/PrismLive/Regions.lean
@@ -469,3 +469,274 @@ theorem regionCheck_sound (B : Box) (rules : List Rule) (props : List Property)
end PrismLive.Kernel
+
+/-! ## The rule judge a published app runs
+
+A published rule app answers through the Forge kernel's `RuleJudge` (app/src/RuleJudge.lex.tex), compiled by
+LexLean. The definitions below are the Lean LexLean writes for it, line for line (`lexlean build`), with the two
+runtime functions they call stated as LexLean's runtime states them for lists of numbers. CI compares each line with
+LexLean's output again. `ruleJudge_sound` then speaks about the judge the published app runs: if `wordsCheck` holds
+on the app's words, no in-bounds request the guest answers breaks the guarantee. -/
+
+namespace LexLeanRuntime
+def multiply (left right : Nat) : Nat := left * right
+def listIndex : List Nat → Nat → Option Nat
+ | [], _ => none
+ | head :: _, 0 => some head
+ | _ :: tail, index + 1 => listIndex tail index
+def index (value : List Nat) (offset : Nat) : Option Nat := listIndex value offset
+end LexLeanRuntime
+
+namespace PrismForgeKernel.WorkProtocol
+def word (words : List (Nat)) (offset : Nat) : Nat := (match (LexLeanRuntime.index (words) (offset) : Option (Nat)) with | Option.none => 0 | Option.some value => value)
+end PrismForgeKernel.WorkProtocol
+
+namespace PrismForgeKernel.RuleJudge
+
+def ruleOpHolds (op : Nat) (bound : Nat) (value : Nat) : Bool := (if (Nat.beq (op) (0)) then (Nat.blt (value) (bound)) else (if (Nat.beq (op) (1)) then (Nat.ble (value) (bound)) else (if (Nat.beq (op) (2)) then (Nat.blt (bound) (value)) else (if (Nat.beq (op) (3)) then (Nat.ble (bound) (value)) else (if (Nat.beq (op) (4)) then (Nat.beq (value) (bound)) else (!(Nat.beq (value) (bound))))))))
+
+def ruleCondsHold : (words : List (Nat)) -> («at» : Nat) -> (count : Nat) -> (base : Nat) -> Bool
+ | _words, _at, Nat.zero, _base => true
+ | words, «at», Nat.succ less, base => (if ruleOpHolds (PrismForgeKernel.WorkProtocol.word (words) ((«at» + 1))) (PrismForgeKernel.WorkProtocol.word (words) ((«at» + 2))) (PrismForgeKernel.WorkProtocol.word (words) ((base + PrismForgeKernel.WorkProtocol.word (words) («at»)))) then ruleCondsHold (words) ((«at» + 3)) (less) (base) else false)
+
+def ruleSpan (words : List (Nat)) («at» : Nat) : Nat := ((«at» + 2) + (LexLeanRuntime.multiply (3) (PrismForgeKernel.WorkProtocol.word (words) («at»)) : Nat))
+
+def rulesEnd : (words : List (Nat)) -> («at» : Nat) -> (count : Nat) -> Nat
+ | _words, «at», Nat.zero => «at»
+ | words, «at», Nat.succ less => rulesEnd (words) (ruleSpan (words) («at»)) (less)
+
+def ruleOutcome : (words : List (Nat)) -> («at» : Nat) -> (count : Nat) -> (otherwise : Nat) -> (base : Nat) -> Nat
+ | _words, _at, Nat.zero, otherwise, _base => otherwise
+ | words, «at», Nat.succ less, otherwise, base => (if ruleCondsHold (words) ((«at» + 2)) (PrismForgeKernel.WorkProtocol.word (words) («at»)) (base) then PrismForgeKernel.WorkProtocol.word (words) ((«at» + 1)) else ruleOutcome (words) (ruleSpan (words) («at»)) (less) (otherwise) (base))
+
+def ruleInBounds : (words : List (Nat)) -> (field : Nat) -> (count : Nat) -> (base : Nat) -> Bool
+ | _words, _field, Nat.zero, _base => true
+ | words, field, Nat.succ less, base => (if ((Nat.ble (PrismForgeKernel.WorkProtocol.word (words) ((2 + (LexLeanRuntime.multiply (2) (field) : Nat)))) (PrismForgeKernel.WorkProtocol.word (words) ((base + field)))) && (Nat.ble (PrismForgeKernel.WorkProtocol.word (words) ((base + field))) (PrismForgeKernel.WorkProtocol.word (words) ((3 + (LexLeanRuntime.multiply (2) (field) : Nat)))))) then ruleInBounds (words) ((field + 1)) (less) (base) else false)
+
+end PrismForgeKernel.RuleJudge
+
+namespace PrismLive.Kernel
+open PrismForgeKernel.WorkProtocol PrismForgeKernel.RuleJudge LexLeanRuntime
+
+/-- The conditions of a rule, as the words state them: field, operator, bound. -/
+def condsOf (w : List Nat) : Nat → Nat → List Cond
+ | _, 0 => []
+ | a, k + 1 => ⟨word w a, word w (a + 1), word w (a + 2)⟩ :: condsOf w (a + 3) k
+
+/-- The rules, as the words state them: conditions, then outcome. -/
+def rulesOf (w : List Nat) : Nat → Nat → List Rule
+ | _, 0 => []
+ | a, k + 1 => ⟨condsOf w (a + 2) (word w a), word w (a + 1)⟩ :: rulesOf w (ruleSpan w a) k
+
+/-- Each field's least and greatest value. -/
+def boundsOf (w : List Nat) : Nat → Nat → Box
+ | _, 0 => []
+ | f, k + 1 => (word w (2 + multiply 2 f), word w (3 + multiply 2 f)) :: boundsOf w (f + 1) k
+
+/-- A rule's conditions as boxes: `is not` (any operator past 4) is below or above. -/
+def splitConds : List Cond → List (List Cond)
+ | [] => [[]]
+ | c :: cs =>
+ if c.op < 5 then (splitConds cs).map (c :: ·)
+ else (splitConds cs).map (⟨c.field, 0, c.value⟩ :: ·) ++ (splitConds cs).map (⟨c.field, 2, c.value⟩ :: ·)
+
+/-- The same rules with every `is not` split, in order: the first match answers the same. -/
+def expand : List Rule → List Rule
+ | [] => []
+ | r :: rs => (splitConds r.when).map (fun cs => ⟨cs, r.outcome⟩) ++ expand rs
+
+/-- What the tab has Lean's kernel evaluate for one guarantee of an app whose words, before the request, are `P`. -/
+def wordsCheck (P : List Nat) (p : Property) : Bool :=
+ let n := word P 1
+ let start := 4 + multiply 2 n
+ (rulesEnd P start (word P (3 + multiply 2 n)) == P.length) &&
+ regionCheck (boundsOf P 0 n) (expand (rulesOf P start (word P (3 + multiply 2 n)))) [p] (word P (2 + multiply 2 n))
+
+/-! ### The words read the same with the request after them -/
+
+theorem listIndex_append_lt : ∀ (P x : List Nat) (i : Nat), i < P.length → listIndex (P ++ x) i = listIndex P i
+ | [], _, _, h => absurd h (by simp)
+ | _ :: _, _, 0, _ => rfl
+ | _ :: P, x, i + 1, h => listIndex_append_lt P x i (by simp at h; omega)
+
+theorem word_append_lt (P x : List Nat) (i : Nat) (h : i < P.length) : word (P ++ x) i = word P i := by
+ simp only [word, index, listIndex_append_lt P x i h]
+
+theorem listIndex_append_len : ∀ (P x : List Nat) (f : Nat), listIndex (P ++ x) (P.length + f) = listIndex x f
+ | [], _, _ => by simp
+ | _ :: P, x, f => by
+ have := listIndex_append_len P x f
+ simp only [List.cons_append, List.length_cons, show P.length + 1 + f = (P.length + f) + 1 by omega, listIndex]
+ exact this
+
+theorem listIndex_get : ∀ (x : List Nat) (f : Nat), (match listIndex x f with | none => 0 | some v => v) = get x f
+ | [], _ => rfl
+ | _ :: _, 0 => rfl
+ | _ :: x, f + 1 => listIndex_get x f
+
+theorem word_append_len (P x : List Nat) (f : Nat) : word (P ++ x) (P.length + f) = get x f := by
+ simp only [word, index, listIndex_append_len]; exact listIndex_get x f
+
+theorem le_ruleSpan (w : List Nat) (a : Nat) : a + 2 ≤ ruleSpan w a := by
+ simp only [ruleSpan, multiply]; omega
+
+theorem le_rulesEnd (w : List Nat) : ∀ (a k : Nat), a ≤ rulesEnd w a k
+ | a, 0 => by simp [rulesEnd]
+ | a, k + 1 => by
+ simp only [rulesEnd]
+ have := le_rulesEnd w (ruleSpan w a) k; have := le_ruleSpan w a; omega
+
+theorem condsOf_append (P x : List Nat) : ∀ (a k : Nat), a + 3 * k ≤ P.length → condsOf (P ++ x) a k = condsOf P a k
+ | _, 0, _ => rfl
+ | a, k + 1, h => by
+ simp only [condsOf, word_append_lt P x a (by omega), word_append_lt P x (a + 1) (by omega),
+ word_append_lt P x (a + 2) (by omega), condsOf_append P x (a + 3) k (by omega)]
+
+theorem boundsOf_append (P x : List Nat) : ∀ (f k : Nat), 2 + 2 * (f + k) ≤ P.length →
+ boundsOf (P ++ x) f k = boundsOf P f k
+ | _, 0, _ => rfl
+ | f, k + 1, h => by
+ simp only [boundsOf, multiply, word_append_lt P x (2 + 2 * f) (by omega), word_append_lt P x (3 + 2 * f) (by omega),
+ boundsOf_append P x (f + 1) k (by omega)]
+
+theorem ruleSpan_append (P x : List Nat) (a : Nat) (h : a < P.length) : ruleSpan (P ++ x) a = ruleSpan P a := by
+ simp only [ruleSpan, word_append_lt P x a h]
+
+theorem rules_append (P x : List Nat) : ∀ (a k : Nat), rulesEnd P a k ≤ P.length →
+ rulesEnd (P ++ x) a k = rulesEnd P a k ∧ rulesOf (P ++ x) a k = rulesOf P a k
+ | _, 0, _ => ⟨rfl, rfl⟩
+ | a, k + 1, h => by
+ simp only [rulesEnd] at h
+ have hs := le_ruleSpan P a
+ have he := le_rulesEnd P (ruleSpan P a) k
+ have ha : a < P.length := by omega
+ have ih := rules_append P x (ruleSpan P a) k h
+ refine ⟨by simp only [rulesEnd, ruleSpan_append P x a ha, ih.1], ?_⟩
+ have hsp : ruleSpan P a = a + 2 + 3 * word P a := by simp [ruleSpan, multiply]
+ have hc : (a + 2) + 3 * word P a ≤ P.length := by omega
+ simp only [rulesOf, ruleSpan_append P x a ha, ih.2, word_append_lt P x a ha,
+ word_append_lt P x (a + 1) (by omega), condsOf_append P x (a + 2) (word P a) hc]
+
+/-! ### The guest's judge is the first-match judge -/
+
+theorem ruleOpHolds_eq (op c v : Nat) : ruleOpHolds op c v = opHolds op c v := by
+ unfold ruleOpHolds opHolds
+ have bl : ∀ a b, Nat.blt a b = Decidable.decide (a < b) := fun a b => Bool.eq_iff_iff.mpr (by simp [Nat.blt_eq])
+ have le : ∀ a b, Nat.ble a b = Decidable.decide (a ≤ b) := fun a b => Bool.eq_iff_iff.mpr (by simp [Nat.ble_eq])
+ have eq : ∀ a b, Nat.beq a b = Decidable.decide (a = b) := fun a b => Bool.eq_iff_iff.mpr (by simp [Nat.beq_eq])
+ simp only [bl, le, eq]
+ by_cases h0 : op = 0 <;> by_cases h1 : op = 1 <;> by_cases h2 : op = 2 <;> by_cases h3 : op = 3 <;>
+ by_cases h4 : op = 4 <;> simp [h0, h1, h2, h3, h4] <;> omega
+
+theorem ruleCondsHold_eq (w x : List Nat) (base : Nat) (hx : ∀ f, word w (base + f) = get x f) :
+ ∀ (a k : Nat), ruleCondsHold w a k base = allHold (condsOf w a k) x
+ | _, 0 => rfl
+ | a, k + 1 => by
+ simp only [ruleCondsHold, condsOf, allHold, condHolds, ruleOpHolds_eq, hx, ruleCondsHold_eq w x base hx (a + 3) k]
+ rfl
+
+theorem ruleOutcome_eq (w x : List Nat) (base d : Nat) (hx : ∀ f, word w (base + f) = get x f) :
+ ∀ (a k : Nat), ruleOutcome w a k d base = judge (rulesOf w a k) d x
+ | _, 0 => rfl
+ | a, k + 1 => by
+ simp only [ruleOutcome, rulesOf, judge, ruleCondsHold_eq w x base hx, ruleOutcome_eq w x base d hx (ruleSpan w a) k]
+
+theorem get_of_drop : ∀ (x : List Nat) (f v : Nat) (vs : List Nat), x.drop f = v :: vs → get x f = v ∧ vs = x.drop (f + 1)
+ | [], _, _, _, h => by simp at h
+ | y :: ys, 0, v, vs, h => by simp at h; simp [get, h.1, h.2]
+ | _ :: ys, f + 1, v, vs, h => get_of_drop ys f v vs (by simpa using h)
+
+theorem ruleInBounds_eq (w x : List Nat) (base : Nat) (hx : ∀ f, word w (base + f) = get x f) :
+ ∀ (x' : List Nat) (f k : Nat), x' = x.drop f → x'.length = k →
+ ruleInBounds w f k base = inBox (boundsOf w f k) x'
+ | [], _, 0, _, _ => rfl
+ | v :: vs, f, k + 1, hd, hl => by
+ have hv := get_of_drop x f v vs hd.symm
+ simp only [ruleInBounds, boundsOf, inBox_cons, hx, hv.1,
+ ruleInBounds_eq w x base hx vs (f + 1) k hv.2 (by simpa using hl)]
+ have le : ∀ a b, Nat.ble a b = Decidable.decide (a ≤ b) := fun a b => Bool.eq_iff_iff.mpr (by simp [Nat.ble_eq])
+ simp only [le]
+ cases Decidable.decide (word w (2 + multiply 2 f) ≤ v) <;> cases Decidable.decide (v ≤ word w (3 + multiply 2 f)) <;> rfl
+ | [], _, _ + 1, _, hl => absurd hl (Nat.succ_ne_zero _).symm
+ | _ :: _, _, 0, _, hl => absurd hl (by simp)
+
+/-! ### Splitting `is not` keeps the first match -/
+
+theorem allHold_cons' (c : Cond) (cs : List Cond) (x : List Nat) :
+ allHold (c :: cs) x = (condHolds c x && allHold cs x) := by
+ simp only [allHold]; cases condHolds c x <;> rfl
+
+theorem any_map_cons (c : Cond) (x : List Nat) : ∀ L : List (List Cond),
+ (L.map (c :: ·)).any (fun ds => allHold ds x) = (condHolds c x && L.any (fun ds => allHold ds x))
+ | [] => by simp
+ | d :: L => by
+ simp only [List.map_cons, List.any_cons, any_map_cons c x L, allHold_cons']
+ cases condHolds c x <;> simp
+
+theorem allHold_split : ∀ (cs : List Cond) (x : List Nat), allHold cs x = (splitConds cs).any (fun ds => allHold ds x)
+ | [], x => by simp [splitConds, allHold]
+ | c :: cs, x => by
+ have ih := allHold_split cs x
+ by_cases h : c.op < 5
+ · simp only [splitConds, h, if_true, any_map_cons, allHold_cons', ih]
+ · simp only [splitConds, h, if_false, List.any_append, any_map_cons, allHold_cons', ← ih]
+ have hne : condHolds c x = (condHolds ⟨c.field, 0, c.value⟩ x || condHolds ⟨c.field, 2, c.value⟩ x) := by
+ unfold condHolds opHolds; simp only
+ have h0 : c.op ≠ 0 := by omega
+ have h1 : c.op ≠ 1 := by omega
+ have h2 : c.op ≠ 2 := by omega
+ have h3 : c.op ≠ 3 := by omega
+ have h4 : c.op ≠ 4 := by omega
+ simp only [h0, h1, h2, h3, h4, if_false]
+ by_cases e : get x c.field = c.value <;> simp [e] <;> omega
+ rw [hne]; cases condHolds ⟨c.field, 0, c.value⟩ x <;> cases condHolds ⟨c.field, 2, c.value⟩ x <;> simp
+
+theorem judge_block (o d : Nat) (x : List Nat) (rs : List Rule) :
+ ∀ css : List (List Cond), judge (css.map (fun cs => ⟨cs, o⟩) ++ rs) d x =
+ if css.any (fun cs => allHold cs x) then o else judge rs d x
+ | [] => by simp
+ | cs :: css => by
+ simp only [List.map_cons, List.cons_append, judge, List.any_cons, judge_block o d x rs css]
+ by_cases h : allHold cs x = true <;> simp [h]
+
+theorem judge_expand (d : Nat) (x : List Nat) : ∀ rs : List Rule, judge (expand rs) d x = judge rs d x
+ | [] => rfl
+ | r :: rs => by
+ simp only [expand, judge_block, judge, judge_expand d x rs, ← allHold_split]
+
+/-! ### Soundness of the published judge -/
+
+/-- If `wordsCheck` holds on an app's words `P`, then for every request `x` the guest takes (the words are `P`
+followed by `x`, `ruleDecide`'s length test passes, and `ruleInBounds` holds), the outcome the guest answers,
+`ruleOutcome`, does not break `p`. -/
+theorem ruleJudge_sound (P : List Nat) (p : Property) (hc : wordsCheck P p = true) (x : List Nat)
+ (hlen : rulesEnd (P ++ x) (4 + multiply 2 (word (P ++ x) 1)) (word (P ++ x) (3 + multiply 2 (word (P ++ x) 1)))
+ + word (P ++ x) 1 = (P ++ x).length)
+ (hin : ruleInBounds (P ++ x) 0 (word (P ++ x) 1)
+ (rulesEnd (P ++ x) (4 + multiply 2 (word (P ++ x) 1)) (word (P ++ x) (3 + multiply 2 (word (P ++ x) 1)))) = true) :
+ breaksWith p x (ruleOutcome (P ++ x) (4 + multiply 2 (word (P ++ x) 1))
+ (word (P ++ x) (3 + multiply 2 (word (P ++ x) 1))) (word (P ++ x) (2 + multiply 2 (word (P ++ x) 1)))
+ (rulesEnd (P ++ x) (4 + multiply 2 (word (P ++ x) 1)) (word (P ++ x) (3 + multiply 2 (word (P ++ x) 1))))) = false := by
+ simp only [wordsCheck, Bool.and_eq_true, beq_iff_eq] at hc
+ obtain ⟨hend, hreg⟩ := hc
+ -- The header words are before the rules, so they read the same with the request after them.
+ have hstart : 4 + 2 * word P 1 ≤ P.length := by
+ have := le_rulesEnd P (4 + multiply 2 (word P 1)) (word P (3 + multiply 2 (word P 1)))
+ rw [hend] at this; simpa [multiply] using this
+ have h1 : word (P ++ x) 1 = word P 1 := word_append_lt P x 1 (by omega)
+ have h2 : word (P ++ x) (2 + multiply 2 (word P 1)) = word P (2 + multiply 2 (word P 1)) :=
+ word_append_lt P x _ (by simp only [multiply]; omega)
+ have h3 : word (P ++ x) (3 + multiply 2 (word P 1)) = word P (3 + multiply 2 (word P 1)) :=
+ word_append_lt P x _ (by simp only [multiply]; omega)
+ rw [h1, h3] at hlen hin ⊢; rw [h2]
+ obtain ⟨he, hr⟩ := rules_append P x _ _ (Nat.le_of_eq hend)
+ rw [he, hend] at hlen hin ⊢
+ have hx : ∀ f, word (P ++ x) (P.length + f) = get x f := word_append_len P x
+ have hxl : x.length = word P 1 := by simp at hlen; omega
+ rw [ruleOutcome_eq _ x _ _ hx, hr, ← judge_expand]
+ have hbox : inBox (boundsOf P 0 (word P 1)) x = true := by
+ rw [ruleInBounds_eq _ x _ hx x 0 _ rfl hxl, boundsOf_append P x 0 _ (by omega)] at hin
+ exact hin
+ exact regionCheck_sound _ _ _ _ hreg p (by simp) x hbox
+
+end PrismLive.Kernel
diff --git a/studio/shell/host.js b/studio/shell/host.js
index aeec0a41..83d61fc4 100644
--- a/studio/shell/host.js
+++ b/studio/shell/host.js
@@ -1385,19 +1385,15 @@ async function rulesAfterTurn(appId, text, written = [], options = {}) {
async function rewordPhase(phase) {
try { return await nextPhase(phase, "reword"); } catch (e) { return null; }
}
-// Lean proves the rules on the hosted verifier; the kernel moves the phase on its attestation or its
-// refusal. A proof whose logic changed meanwhile is dropped: it is about other rules. A reword meanwhile
-// keeps it, since the logic kappa is the same. Resolves the prover's result, or null when the logic
-// changed under it.
+// Lean's kernel proves the rules in this tab (prism.prove), and the kernel moves the phase on the Forge kernel
+// guest's verdict. A proof whose logic changed meanwhile is dropped: it is about other rules. A reword meanwhile
+// keeps it, since the logic kappa is the same. Resolves the prover's result, or null when the logic changed under it.
async function proveRules(appId, logicKey, onWait, options = {}) {
const state = await rulesOf(appId);
const reservation = options.expectedState || state;
if (!sameRuleReservation(state, reservation) || (state.logicKappa || state.specKappa) !== logicKey) return null;
let submitted = false;
- // Proof records live under their theorem address in "refs"; prism/proof-reuse.mjs decides whether one
- // may stand for a proof.
- const proofStore = { get: (key) => get("refs", key), put: (key, value) => put("refs", key, value) };
- const result = await prism.prove(reservation.spec, { onWait, store: proofStore, beforeSubmit: () => { options.beforeSubmit?.(); submitted = true; } }).catch((e) => {
+ const result = await prism.prove(reservation.spec, { guest: kernelReady, beforeSubmit: () => { options.beforeSubmit?.(); submitted = true; } }).catch((e) => {
if (options.beforeSubmit && !submitted) throw e;
return { ok: false, error: String((e && e.message) || e) };
});
@@ -1641,13 +1637,10 @@ handlers.set("prism:status", async ({ appId }) => (await rulesOf(appId)) || null
// own card (shell/live/card-files.mjs); the card asks the kernel "rule " with the spec's words and the
// request's, so the answer shown is the kernel guest's, after every acceptance vector replayed in this tab.
// A rule that compares two fields has no rule words yet, so such an app is refused, never guessed.
-const OPS = { "<": 0, "<=": 1, ">": 2, ">=": 3, is: 4, "=": 4, "is not": 5, "!=": 5 };
function ruleWords(spec) {
const hex = (n) => { if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) throw new Error("a bound outside 32 bits"); return [0, 8, 16, 24].map((k) => ((n >>> k) & 255).toString(16).padStart(2, "0")).join(""); };
- const outcomes = [...new Set([spec.otherwise, ...spec.rules.map((r) => r.then)])], at = (n) => spec.fields.findIndex((f) => f.name === n);
- const value = (c) => { const f = spec.fields[at(c.field)]; if (!f || typeof c.value === "object" || !(c.op in OPS)) throw new Error("a condition the rule judge does not take"); return f.kind === "choice" ? f.values.indexOf(c.value) : Number(c.value); };
- const words = [1, spec.fields.length, ...spec.fields.flatMap((f) => (f.kind === "choice" ? [0, f.values.length - 1] : [f.min ?? 0, f.max ?? 0xffffffff])), outcomes.indexOf(spec.otherwise), spec.rules.length, ...spec.rules.flatMap((r) => [r.when.length, outcomes.indexOf(r.then), ...r.when.flatMap((c) => [at(c.field), OPS[c.op], value(c)])])];
- return { words: words.map(hex).join(""), outcomes, choices: spec.fields.map((f) => (f.kind === "choice" ? f.values : null)) };
+ const w = prism.ruleWordsOf(spec);
+ return { words: w.words.map(hex).join(""), outcomes: w.outcomes, choices: w.choices };
}
const START = (w) => `import { load } from "./vendor/prism-code/src/browser.mjs";import start from "./card.mjs";const W=${JSON.stringify(w)},e=new TextEncoder(),d=new TextDecoder(),h=(n)=>[0,8,16,24].map((k)=>((n>>>k)&255).toString(16).padStart(2,"0")).join("");
const ask=(k)=>async(b)=>{const r=d.decode(await k.dispatch(e.encode("rule "+W.words+d.decode(b).split(" ").map((v,i)=>h(W.choices[i]?W.choices[i].indexOf(v):Number(v))).join(""))));if(!r.startsWith("ok "))throw new Error(r);return e.encode(W.outcomes[parseInt(r.slice(11,19).match(/../g).reverse().join(""),16)]);};
diff --git a/studio/shell/kernel/lean/lean-kernel.mjs.gz b/studio/shell/kernel/lean/lean-kernel.mjs.gz
new file mode 100644
index 00000000..3db9969e
Binary files /dev/null and b/studio/shell/kernel/lean/lean-kernel.mjs.gz differ
diff --git a/studio/shell/kernel/lean/lean-kernel.wasm.gz b/studio/shell/kernel/lean/lean-kernel.wasm.gz
new file mode 100644
index 00000000..abe0ae40
Binary files /dev/null and b/studio/shell/kernel/lean/lean-kernel.wasm.gz differ
diff --git a/studio/shell/kernel/lean/library.ndjson.gz b/studio/shell/kernel/lean/library.ndjson.gz
new file mode 100644
index 00000000..10579deb
Binary files /dev/null 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
new file mode 100644
index 00000000..aed51354
--- /dev/null
+++ b/studio/shell/kernel/lean/manifest.json
@@ -0,0 +1,48 @@
+{
+ "schema": "prism/in-tab-kernel/1",
+ "lean": {
+ "version": "4.32.1",
+ "commit": "f054605aea4b840552cca2e725580bffd1e1b704"
+ },
+ "exporter": {
+ "repository": "https://github.com/leanprover/lean4export",
+ "commit": "86e4a339507466921dc8c5417c8cb1de1ce7df60",
+ "module": "PrismLive.Regions",
+ "roots": [
+ "PrismLive.Kernel.ruleJudge_sound",
+ "PrismLive.Kernel.wordsCheck",
+ "PrismLive.Kernel.Property.mk",
+ "PrismLive.Kernel.Cond.mk",
+ "Eq.refl",
+ "Bool.true",
+ "Bool.false",
+ "List.nil",
+ "List.cons"
+ ]
+ },
+ "glue": {
+ "file": "lean-kernel.mjs.gz",
+ "sha256": "3f482f95c28fb0c74027552d6c4519f8916e48cd1d5b0bd202f318ca8c027a4a",
+ "bytes": 62458
+ },
+ "wasm": {
+ "file": "lean-kernel.wasm.gz",
+ "sha256": "4b48480b9c03ae4aa3bf1a37256b59bff2d41d6cf452a2f8aa9de41a28ccd118",
+ "bytes": 2235906
+ },
+ "library": {
+ "file": "library.ndjson.gz",
+ "sha256": "691abbcc02f300effdabe36eeb48b5eb0859d73047631200231393a96cfcc5d1",
+ "bytes": 7754251
+ },
+ "binding": {
+ "schema": "prism/in-tab-library-binding/1",
+ "lean": "f054605aea4b840552cca2e725580bffd1e1b704",
+ "kernel": "4b48480b9c03ae4aa3bf1a37256b59bff2d41d6cf452a2f8aa9de41a28ccd118",
+ "loader": "3f482f95c28fb0c74027552d6c4519f8916e48cd1d5b0bd202f318ca8c027a4a",
+ "library": "691abbcc02f300effdabe36eeb48b5eb0859d73047631200231393a96cfcc5d1",
+ "declarations": 2097,
+ "sentToTheKernel": 1916,
+ "judgedBy": "check_whole, every declaration, in this kernel"
+ }
+}
diff --git a/studio/shell/prism.js b/studio/shell/prism.js
index 4a30a729..76754ce4 100644
--- a/studio/shell/prism.js
+++ b/studio/shell/prism.js
@@ -1,8 +1,8 @@
// Proved rules for the apps Forge builds. An app that decides something (a tier, an eligibility, a
// grade) carries a Prism spec, prism/spec/1, beside its code. This module does what prism-code does
// with it, in the tab: checks it (prism/spec.mjs, prism-code's checker), renders its LexLean model
-// (prism/render.mjs, prism-code's renderer), and asks Lean to prove every guarantee on the hosted
-// verifier, the same call `prism_prove` makes. It also writes the app's rule module,
+// (prism/render.mjs, prism-code's renderer), and has Lean's kernel prove every guarantee in this tab
+// (`prove`, below). It also writes the app's rule module,
// src/lib/prism.ts: the spec as data and one small interpreter, replayed against every acceptance
// vector before it is written. What Lean proves is the rules; the module is tested against them.
import { SpecError, validateSpec, unreachableRules, counterexample, describeConditions, requestLimits, decodeRequest, respond } from "./prism/spec.mjs";
@@ -23,7 +23,8 @@ import { tableKernel } from "./live/table.mjs";
import { PROMPT_RULES, facetLine, parsePromptTag, facetsOf } from "./prism/builder/route.mjs";
// The app's prompt parts, read and projected where the rules are (host.js rulesAfterTurn).
export { parsePromptTag, facetsOf };
-import { KEY_PREFIX, REFUSAL, trustDescriptor, sameVerifier, attests, reuseSentence, addresses, admit, headersOf, record as reuseRecord, theoremsOf, without } from "./prism/proof-reuse.mjs";
+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
@@ -381,7 +382,7 @@ function checkLarge(input, notes) {
if (prismAnswer(spec, text) !== v.response) failed++;
}
if (failed) issues.push(`The rule module disagrees with ${failed} of ${vectors.length} acceptance vectors. This is a Forge bug.`);
- notes.push(`${spec.rules.length} rules, more than prism-code's ${PROVE_RULES_MAX}: every guarantee was checked by ${how}. Lean proves at most ${PROVE_RULES_MAX} rules until LexLean proves them locally (UOR-Foundation/PrismPM#605).`);
+ notes.push(`${spec.rules.length} rules, more than prism-code's ${PROVE_RULES_MAX}: every guarantee was checked by ${how}.`);
return { ok: issues.length === 0, spec, issues, notes, vectors: vectors.length, module: issues.length ? null : moduleSource(spec, vectors.length) };
}
@@ -445,18 +446,6 @@ async function shellText(path) {
if (!r.ok) throw new Error(path + " answered " + r.status);
return (await r.text()).replace(/\r\n/g, "\n");
}
-export async function projectFiles(spec, axioms = {}) {
- const n = names(spec);
- const files = [
- { path: "src/Foundation/Bytes.lex.tex", content: await shellText("./prism/lex/Foundation/Bytes.lex.tex") },
- { path: "src/Foundation/View/Text/V1/Model.lex.tex", content: await shellText("./prism/lex/Foundation/View/Text/V1/Model.lex.tex") },
- { path: `src/${n.module}.lex.tex`, content: renderModel(spec, { axioms, specAddress: sealOf(spec) }) },
- ];
- const proofs = renderProofs(spec, { axioms });
- if (proofs) files.push({ path: `src/${n.proofs}.lex.tex`, content: proofs });
- return files;
-}
-
let rpcId = 0;
const meta = (tasks) => ({
"io.modelcontextprotocol/protocolVersion": PROTOCOL,
@@ -486,11 +475,162 @@ async function rpc(method, name, params) {
}
const callTool = (tool, args, tasks = false) => rpc("tools/call", tool, { name: tool, arguments: args, _meta: meta(tasks) });
-/** Ask Lean to prove the spec's guarantees. Resolves { ok, record, seconds } or { ok: false, error }. */
-export async function prove(spec, { onWait = () => {}, beforeSubmit = () => {}, store = null } = {}) {
- const result = await proveFiles(async (axioms) => { const files = await projectFiles(spec, axioms); return { files, entrypoints: files.map((f) => f.path) }; }, { onWait, beforeSubmit, store, before: () => { if (spec.rules.length > PROVE_RULES_MAX) throw new Error(`These ${spec.rules.length} rules are checked on every request, but Lean proves at most ${PROVE_RULES_MAX} rules today: its proofs are one theorem per guarantee over the whole rule chain. Proving more waits for local proofs in LexLean (UOR-Foundation/PrismPM#605).`); } });
- if (result.ok) { const { seconds, ...rest } = result.record; result.record = { ...rest, properties: spec.properties.map((p) => p.id), seconds }; }
- return result;
+// ---- 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
+// every app, that RuleJudge as LexLean compiles it answers no in-bounds request that breaks a guarantee
+// `wordsCheck` passes (studio/proof/PrismLive/Regions.lean, `ruleJudge_sound`). An app's proof is then that theorem
+// applied to its words: Lean's kernel, compiled to WebAssembly and run in a worker with that library resident,
+// evaluates `wordsCheck` and judges the term. Nothing is sent anywhere, and the Forge kernel guest gives the verdict
+// (InTabKernel.verdictCode) from what the tab derived.
+const OPS = { "<": 0, "<=": 1, ">": 2, ">=": 3, is: 4, "=": 4, "is not": 5, "!=": 5 };
+/** The words RuleJudge decides an app's requests with, before the request's own: what a published app sends. */
+export function ruleWordsOf(spec) {
+ const outcomes = [...new Set([spec.otherwise, ...spec.rules.map((r) => r.then)])], at = (n) => spec.fields.findIndex((f) => f.name === n);
+ const cond = (c) => { const f = spec.fields[at(c.field)]; if (!f || typeof c.value === "object" || !(c.op in OPS)) throw new Error("it compares two fields, and the rule judge compares a field with a value"); return [at(c.field), OPS[c.op], f.kind === "choice" ? f.values.indexOf(c.value) : Number(c.value)]; };
+ const words = [1, spec.fields.length, ...spec.fields.flatMap((f) => (f.kind === "choice" ? [0, f.values.length - 1] : [f.min ?? 0, f.max ?? 0xffffffff])), outcomes.indexOf(spec.otherwise), spec.rules.length, ...spec.rules.flatMap((r) => [r.when.length, outcomes.indexOf(r.then), ...r.when.flatMap(cond)])];
+ // A guarantee about an answer no rule gives names the next number: no rule answers it.
+ const guarantees = spec.properties.map((p) => ({ always: p.kind === "always", when: p.when.map(cond), outcome: outcomes.includes(p.then) ? outcomes.indexOf(p.then) : outcomes.length }));
+ return { words, outcomes, guarantees, choices: spec.fields.map((f) => (f.kind === "choice" ? f.values : null)) };
+}
+const AXIOMS = ["propext", "Quot.sound"];
+const sha256Hex = async (bytes) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");
+function leanWorker(self) {
+ const enc = new TextEncoder(), dec = new TextDecoder();
+ const sha256 = async (b) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", b))].map((x) => x.toString(16).padStart(2, "0")).join("");
+ const said = [];
+ let m = null, lib = null, at = null;
+ const run = (entry, bytes) => {
+ said.length = 0; m.FS.writeFile("/in.ndjson", bytes);
+ let exit;
+ try { exit = m.ccall(entry, "number", ["string"], ["/in.ndjson"]); } catch (e) { exit = 3; said.push("trap: " + (e && e.message ? e.message : e)); }
+ m.FS.unlink("/in.ndjson");
+ const axioms = {}, rest = [];
+ for (const line of said) { const a = /^axioms ([^:]+): ?(.*)$/.exec(line); if (a) axioms[a[1]] = a[2] ? a[2].split(", ") : []; else rest.push(line); }
+ return { exit, axioms: exit === 0 ? axioms : {}, output: rest.join("\n").slice(-400) };
+ };
+ // The library's names, terms and levels by index (lean4export's format), so a suffix names what it already holds.
+ const read = (text) => {
+ const t = { names: [""], name: new Map([["", 0]]), expr: [], exprAt: new Map(), level: new Map(), types: new Map(), next: [1, 0, 1] };
+ for (const line of text.split("\n")) {
+ if (!line) continue;
+ const o = JSON.parse(line);
+ if ("in" in o) { const pre = t.names[(o.str || o.num).pre]; const full = (pre ? pre + "." : "") + (o.str ? o.str.str : o.num.i); t.names[o.in] = full; t.name.set(full, o.in); t.next[0] = Math.max(t.next[0], o.in + 1); }
+ else if ("il" in o) { const { il, ...node } = o; t.level.set(JSON.stringify(node), il); t.next[2] = Math.max(t.next[2], il + 1); }
+ else if ("ie" in o) { const { ie, ...node } = o; t.expr[ie] = node; t.exprAt.set(JSON.stringify(node), ie); t.next[1] = Math.max(t.next[1], ie + 1); }
+ else if (o.thm || o.def) { const d = o.thm || o.def; t.types.set(d.name, d.type); }
+ }
+ 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) => {
+ 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; };
+ const node = (e) => lib.expr[e] ?? ownExpr[e];
+ const name = (full) => { let pre = 0, path = ""; for (const part of full.split(".")) { path = path ? path + "." + part : part; const have = lib.name.get(path) ?? own.get(path); if (have !== undefined) { pre = have; continue; } const n = nextName++; own.set(path, n); out.push(JSON.stringify({ in: n, str: { pre, str: part } })); pre = n; } return pre; };
+ const known = (full) => { const n = lib.name.get(full); if (n === undefined) throw new Error("the library does not hold " + full); return n; };
+ const C = (full, us = []) => term({ const: { name: known(full), us } });
+ const app = (f, ...args) => args.reduce((fn, arg) => term({ app: { arg, fn } }), f);
+ const nat = (n) => term({ natVal: String(n) });
+ 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: [] } }); };
+ // A theorem's statement with its first binders taken by closed terms.
+ const instantiate = (type, args) => {
+ let body = type;
+ for (let k = 0; k < args.length; k++) body = node(body).forallE.body;
+ const memo = new Map(), go = (e, depth) => {
+ const key = e + ":" + depth; if (memo.has(key)) return memo.get(key);
+ const x = node(e); let r = e;
+ if ("bvar" in x) r = x.bvar < depth ? e : x.bvar - depth < args.length ? args[args.length - 1 - (x.bvar - depth)] : term({ bvar: x.bvar - args.length });
+ else if (x.app) r = term({ app: { arg: go(x.app.arg, depth), fn: go(x.app.fn, depth) } });
+ else if (x.forallE) r = term({ forallE: { ...x.forallE, type: go(x.forallE.type, depth), body: go(x.forallE.body, depth + 1) } });
+ else if (x.lam) r = term({ lam: { ...x.lam, type: go(x.lam.type, depth), body: go(x.lam.body, depth + 1) } });
+ else if (x.letE) r = term({ letE: { ...x.letE, type: go(x.letE.type, depth), value: go(x.letE.value, depth), body: go(x.letE.body, depth + 1) } });
+ else if (x.proj) r = term({ proj: { ...x.proj, struct: go(x.proj.struct, depth) } });
+ memo.set(key, r); return r;
+ };
+ return go(body, 0);
+ };
+ const K = "PrismLive.Kernel.", Nat = C("Nat"), Bool = C("Bool"), at = "Tab.g" + i + ".";
+ const cond = ([field, op, value]) => app(C(K + "Cond.mk"), nat(field), nat(op), nat(value));
+ const P = declare("def", at + "words", app(C("List", [0]), Nat), list(Nat, words.map(nat)));
+ const p = declare("def", at + "guarantee", C(K + "Property"), app(C(K + "Property.mk"), C(g.always ? "Bool.true" : "Bool.false"), list(C(K + "Cond"), g.when.map(cond)), nat(g.outcome)));
+ const T = C("Bool.true");
+ const checked = declare("thm", at + "checked", app(C("Eq", [one]), Bool, app(C(K + "wordsCheck"), P, p), T), app(C("Eq.refl", [one]), Bool, T));
+ declare("thm", at + "holds", instantiate(lib.types.get(known(K + "ruleJudge_sound")), [P, p, checked]), app(C(K + "ruleJudge_sound"), P, p, checked));
+ return out.join("\n") + "\n";
+ };
+ async function open({ manifest, glue, wasm, library }) {
+ const [g, w, l] = await Promise.all([sha256(glue), sha256(wasm), sha256(library)]), b = manifest.binding;
+ if (g !== manifest.glue.sha256 || w !== manifest.wasm.sha256 || l !== manifest.library.sha256) return { ok: false, refusal: "the kernel, its loader or its library is not the pinned one" };
+ // The library is entered unchecked: sound only for one this kernel has judged whole (the binding).
+ if (!b || b.kernel !== w || b.loader !== g || b.library !== l) return { ok: false, refusal: "no record that this kernel judged this library whole" };
+ const url = URL.createObjectURL(new Blob([glue], { type: "text/javascript" }));
+ try { m = await (await import(url)).default({ instantiateWasm: (imports, done) => { WebAssembly.instantiate(wasm, imports).then((r) => done(r.instance, r.module)); return {}; }, print: (s) => said.push(s), printErr: (s) => said.push(s) }); } finally { URL.revokeObjectURL(url); }
+ if (m.ccall("checker_ready", "number", [], []) !== 0) return { ok: false, refusal: "the kernel did not start" };
+ const bytes = new Uint8Array(library), loaded = run("load_library", bytes);
+ if (loaded.exit !== 0) return { ok: false, refusal: "the kernel refused the library: " + loaded.output };
+ lib = read(dec.decode(bytes)); at = { kernel: w, library: l };
+ return { ok: true };
+ }
+ async function prove({ id, words, guarantees }) {
+ const texts = guarantees.map((g, i) => suffix(i, words, g));
+ const judged = texts.map((t, i) => { const r = run("check_suffix", enc.encode(t)); return { accepted: r.exit === 0, axioms: r.axioms["Tab.g" + i + ".holds"] || null, output: r.output }; });
+ 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 };
+ }
+ self.onmessage = async ({ data }) => {
+ try { self.postMessage(data.op === "open" ? { op: "open", ...(await open(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) }); }
+ };
+}
+// One worker for the page, opened on first use from the pinned files (kernel/lean/manifest.json). Each is shipped
+// gzipped and named by the SHA-256 of its bytes; the worker checks every address before the kernel runs.
+let lean = null;
+async function openLean() {
+ const LEAN = new URL("./kernel/lean/", import.meta.url);
+ const bytes = async (file) => { const r = await fetch(new URL(file, LEAN)); if (!r.ok) throw new Error(file + " answered " + r.status); const b = new Uint8Array(await r.arrayBuffer()); return b[0] === 0x1f && b[1] === 0x8b ? new Response(new Blob([b]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer() : b.buffer; };
+ const manifest = await (await fetch(new URL("manifest.json", LEAN))).json();
+ const [glue, wasm, library] = await Promise.all([manifest.glue, manifest.wasm, manifest.library].map((f) => bytes(f.file)));
+ const worker = new Worker(URL.createObjectURL(new Blob(["(" + leanWorker + ")(self)"], { type: "text/javascript" })), { type: "module" });
+ let id = 0;
+ const ask = (message) => new Promise((resolve, reject) => {
+ const mine = message.op === "open" ? undefined : ++id;
+ const on = ({ data }) => { if (data.op === message.op && data.id === mine) { worker.removeEventListener("message", on); resolve(data); } };
+ worker.addEventListener("message", on);
+ worker.addEventListener("error", (e) => reject(new Error("the proof worker failed: " + (e.message || "it did not start"))), { once: true });
+ worker.postMessage({ ...message, id: mine });
+ });
+ 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 }) };
+}
+/** 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 = () => {} } = {}) {
+ const t0 = Date.now(), no = (error) => ({ ok: false, error });
+ let read;
+ try { read = ruleWordsOf(spec); } catch (e) { return no("Lean's kernel in this tab cannot read these rules: " + e.message); }
+ let k, r;
+ try { k = await (lean ||= openLean()); beforeSubmit(); r = await k.prove(read.words, read.guarantees); }
+ catch (e) { lean = null; return no(String((e && e.message) || e)); }
+ 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);
+ const statement = await sha256Hex(enc.encode(JSON.stringify(["prism/in-tab-statement/3", read.words, read.guarantees])));
+ const verdict = await verdictWithGuest(guest, {
+ version: 1, hasBytes: 1, libraryPinned: word(k.manifest.library.sha256), libraryDerived: word(r.evidence.library),
+ // The proof is written here, not fetched: its one address is the worker's.
+ 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(r.evidence.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 = spec.properties.filter((_, i) => !r.judged[i].accepted).map((p) => p.id);
+ 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, properties: spec.properties.map((p) => p.id), seconds } };
}
/**
* Proves LexLean files on the hosted verifier: every theorem through Lean and leanchecker, each with
@@ -695,15 +835,14 @@ export function card(state) {
if (facets) lines.push("", facets);
if (state.notes && state.notes.length) lines.push("", ...state.notes.map((n) => "*" + n + "*"));
if (state.issues && state.issues.length) lines.push("", "Not checked:", ...state.issues.map((i) => "- " + i), "", "Ask me to fix the rules.");
- else if (state.phase === "checked" && spec.rules.length > PROVE_RULES_MAX) lines.push("", `Checked on every request: ${(state.notes || []).find((n) => /checked by/.test(n)) || ""}`, "", `Lean proving waits: it proves at most ${PROVE_RULES_MAX} rules until LexLean proves them locally (UOR-Foundation/PrismPM#605).`);
- else if (state.phase === "checked") lines.push("", `Checked: consistent, ${spec.examples.length} examples pass, ${state.vectors} acceptance vectors replayed through the app's rule module.`, "", "Reply **approve** to have Lean prove the guarantees. The rules go to the hosted verifier, unlisted.");
+ else if (state.phase === "checked") lines.push("", `Checked: consistent, ${spec.examples.length} examples pass, ${state.vectors} acceptance vectors replayed through the app's rule module.`, "", "Reply **approve** to have Lean's kernel prove the guarantees in this tab. Nothing is sent anywhere.");
return lines.join("\n");
}
export function provingMessage(spec) {
- return `Proving ${spec.properties.length} guarantee${spec.properties.length === 1 ? "" : "s"} with Lean on the hosted verifier, usually two to four minutes. The preview keeps working meanwhile.`;
+ return `Proving ${spec.properties.length} guarantee${spec.properties.length === 1 ? "" : "s"} in this tab with Lean's kernel. Nothing is sent anywhere.`;
}
export function proofMessage(spec, result) {
- if (result.ok) return `**Proved by Lean.** ${spec.properties.length} of ${spec.properties.length} guarantee${spec.properties.length === 1 ? "" : "s"} hold for every request, in ${result.seconds} s.${reuseSentence(spec.properties.length, result.record.reused)} Attestation \`${result.record.attestation_id.slice(0, 16)}…\`. Publishing now carries the rules and this proof.`;
+ if (result.ok) return `**Proved in this tab by Lean's kernel.** ${spec.properties.length} of ${spec.properties.length} guarantee${spec.properties.length === 1 ? " holds" : "s hold"} for every request the published app answers, in ${result.seconds} s. Lean ${result.record.lean.version}, kernel \`${result.record.kernel.slice(7, 19)}…\`, library \`${result.record.library.slice(7, 19)}…\`. No server took part.`;
return `**Not proved.** ${result.error}. The rules are back to checked: ask me to change them, or reply **approve** to try again.`;
}
export { requestLimits };
diff --git a/studio/tools/build_source_browser.mjs b/studio/tools/build_source_browser.mjs
index 165869a3..ce673b74 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", "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", "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)));
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/current_main_integration.test.mjs b/studio/tools/current_main_integration.test.mjs
index 72b2253d..90f71d7f 100644
--- a/studio/tools/current_main_integration.test.mjs
+++ b/studio/tools/current_main_integration.test.mjs
@@ -71,7 +71,7 @@ test("proof completion follows matching logic and refuses a competing commit", a
const state = { ...proved(), phase: "proving" }, latest = { ...state, specKappa: "reworded" }; let reads = 0, refreshed = 0, audits = 0;
const prove = fn("proveRules", '// "approve"', {
rulesOf: async () => ++reads === 1 ? state : latest,
- prism: { prove: async () => ({ ok: true, record: state.proof }) }, nextPhase: async () => "proved",
+ kernelReady: null, prism: { prove: async () => ({ ok: true, record: state.proof }) }, nextPhase: async () => "proved",
saveRules: async (_, value, expected) => { assert.equal(expected, latest); assert.equal(value.specKappa, "reworded"); return accepted; },
put: async (_, __, value) => { assert.equal(value.resource, state.logicKappa); audits++; }, refreshLive: async () => refreshed++, now: () => "now",
});
@@ -127,7 +127,7 @@ test("proof completion retries a matching reword CAS without rerunning the prove
let reads = 0, saves = 0, proofs = 0;
const prove = fn("proveRules", '// "approve"', {
rulesOf: async () => ++reads <= 2 ? state : reword,
- prism: { prove: async () => { proofs++; return { ok: true, record: { id: "settled" } }; } },
+ kernelReady: null, prism: { prove: async () => { proofs++; return { ok: true, record: { id: "settled" } }; } },
nextPhase: async () => "proved", saveRules: async (_, next, expected) => {
saves++; if (saves === 1) return false;
assert.equal(expected, reword); assert.equal(next.specKappa, "new"); assert.equal(next.proof.id, "settled"); return true;
@@ -141,7 +141,7 @@ test("proof completion stops retrying when the competing edit changes semantics"
let reads = 0, saves = 0;
const prove = fn("proveRules", '// "approve"', {
rulesOf: async () => ++reads <= 2 ? state : { ...state, logicKappa: "different" },
- prism: { prove: async () => ({ ok: true, record: { id: "old-proof" } }) },
+ kernelReady: null, prism: { prove: async () => ({ ok: true, record: { id: "old-proof" } }) },
nextPhase: async () => "proved", saveRules: async () => { saves++; return false; },
put() { assert.fail("changed semantics must not accept old proof"); }, now: () => "now",
});
diff --git a/studio/tools/generation_patch_browser.mjs b/studio/tools/generation_patch_browser.mjs
index 43149840..ed4d5306 100644
--- a/studio/tools/generation_patch_browser.mjs
+++ b/studio/tools/generation_patch_browser.mjs
@@ -7,7 +7,7 @@ const host = fs.readFileSync(new URL("../shell/host.js", import.meta.url), "utf8
const apply = host.slice(host.indexOf("async function applyPrismTags("), host.indexOf("window.__chat ="));
const rules = host.slice(host.indexOf("async function rulesAfterTurn("), host.indexOf("// Lean proves"));
const proof = host.slice(host.indexOf("async function proveRules("), host.indexOf('// "approve"'));
-const hostModule = `import { sameRuleReservation } from "/rules-source.mjs";\nimport { retiredApplicationPaths, isStatefulModule } from "/application-shape.mjs";\nconst appShape = {SOURCE_PATH:"prism/App.lex.tex",isAppShape:isStatefulModule};\nimport { copyGenerationInput, assertCanonicalGeneration } from "/canonical-generation.mjs";\nimport * as lexlean from "/live/lexlean.mjs";\nexport function hostAdapters(env) { const { coreReady, dbReady, core, kappa, applyStoredProjectPatch, assertGenerationActive, captureProjectSource, prism, live, rulesOf, rulesSnapshotOf, saveRules, nextPhase, now, enc, put, refreshLive, forgetApplicationFrames } = env; ${apply}\n${rules}\n${proof}\nreturn { applyPrismTags, rulesAfterTurn, proveRules }; }`;
+const hostModule = `import { sameRuleReservation } from "/rules-source.mjs";\nimport { retiredApplicationPaths, isStatefulModule } from "/application-shape.mjs";\nconst appShape = {SOURCE_PATH:"prism/App.lex.tex",isAppShape:isStatefulModule};\nimport { copyGenerationInput, assertCanonicalGeneration } from "/canonical-generation.mjs";\nimport * as lexlean from "/live/lexlean.mjs";\nexport function hostAdapters(env) { const { coreReady, kernelReady, dbReady, core, kappa, applyStoredProjectPatch, assertGenerationActive, captureProjectSource, prism, live, rulesOf, rulesSnapshotOf, saveRules, nextPhase, now, enc, put, refreshLive, forgetApplicationFrames } = env; ${apply}\n${rules}\n${proof}\nreturn { applyPrismTags, rulesAfterTurn, proveRules }; }`;
const sources = new Map([
["/browser-chat-modes.mjs", fs.readFileSync(new URL("../shell/browser-chat-modes.mjs", import.meta.url))],
["/chat-mode-catalog.mjs", fs.readFileSync(new URL("../shell/chat-mode-catalog.mjs", import.meta.url))],
diff --git a/studio/tools/large_module_presentation_browser.mjs b/studio/tools/large_module_presentation_browser.mjs
index d12497cd..38c274e7 100644
--- a/studio/tools/large_module_presentation_browser.mjs
+++ b/studio/tools/large_module_presentation_browser.mjs
@@ -44,9 +44,7 @@ try {
assert.equal(await get(page,'files',appId+':prism/'+initial.name+'.lex.tex'),initial.source);
const status=await page.evaluate(appId=>window.__prism.rulesOf(appId),appId);
assert.equal(status.phase,'checked');assert.equal(status.proof,null);assert.equal(status.spec.rules.length,verdant.rules.length);
- assert.ok(status.notes.some(note=>note.includes('Lean proves at most 24 rules')));
- const proofRefusal=await page.evaluate(async spec=>{try{await(await import('./prism.js')).prove(spec);return null;}catch(error){return error.message;}},verdant);
- assert.match(proofRefusal,/Lean proves at most 24 rules/);
+ assert.ok(!status.notes.some(note=>note.includes('Lean proves at most')),'the tab proves every rule; no rule cap remains');
const custom={...verdant,purpose:'My complete garden',view:{blocks:[{kind:'heading',text:'My complete garden'},{kind:'answer'}]},meanings:{[verdant.outcomes[0]]:'Garden response'}};
await apply(''+JSON.stringify(custom)+'');
const edited=structuredClone(verdant);edited.rules.push({...structuredClone(edited.rules[0]),id:'rule'+(edited.rules.length+1)});
diff --git a/studio/tools/live_lexlean.mjs b/studio/tools/live_lexlean.mjs
index 5524f476..438ae62e 100644
--- a/studio/tools/live_lexlean.mjs
+++ b/studio/tools/live_lexlean.mjs
@@ -183,15 +183,12 @@ let rsvpSourceSame = false;
if (rsvpSource) { const a = logicOf(rsvp), b = logicOf(lex.readLexLean(rsvpSource.source)), t = K.build(a); rsvpSourceSame = true; for (let r = 0; r < t.size && rsvpSourceSame; r++) { const l = K.requestOf(t, r); if (prismAnswer(a, l) !== prismAnswer(b, l)) rsvpSourceSame = false; } }
claim("every app: a spec's canonical source decides as the spec does", !!rsvpSource && /^[A-Z]\w*$/.test(rsvpSource.name) && rsvpSourceSame, rsvpSource ? `prism/${rsvpSource.name}.lex.tex` : "no canonicalSource");
-// over prism-code's 24 rules: checked by obligations, never offered for proof
+// over prism-code's 24 rules: checked by obligations
const big = prism.checkSpec(spec);
claim("cap: an app over 24 rules is checked by its obligations", big.ok === true && !!big.module && (big.notes || []).some((n) => /obligations/.test(n)), big.ok ? (big.notes || []).join(" ") : (big.issues || []).join(" "));
const bigBroken = structuredClone(spec); bigBroken.rules[1].when.find((c) => c.field === "proximity").value = 60;
const bb = prism.checkSpec(bigBroken);
claim("cap: a broken app over 24 rules is refused with its counterexample", bb.ok === false && (bb.issues || []).some((i) => /does not hold/.test(i)), (bb.issues || []).join(" "));
-let proveWord = "";
-try { await prism.prove(spec); } catch (e) { proveWord = e.message; }
-claim("cap: proving an app over 24 rules is refused, and says why", /24 rules/.test(proveWord) && /605/.test(proveWord), proveWord);
// What real models got wrong (Haiku and Sonnet on Foundry's prompt, four apps each): the reader names the
// mistake so the model can fix it, and reads what is unambiguous. Each case is the prompt's own example,
diff --git a/studio/tools/proof_approval_cancellation.test.mjs b/studio/tools/proof_approval_cancellation.test.mjs
index 1157371d..bceb07e2 100644
--- a/studio/tools/proof_approval_cancellation.test.mjs
+++ b/studio/tools/proof_approval_cancellation.test.mjs
@@ -34,7 +34,7 @@ function lifecycleHarness({shape='app',refreshFails=false,libraryFails=false,pro
if(completionRace==='reword'){state={...state,specKappa:'reworded-spec',spec:{...state.spec,title:'new wording'}};revision++;}
return proofOk?{ok:true,record:{attestation_id:'attestation'},axioms:{}}:{ok:false,error:'Old proof refused'};
};
- const environment={Map,JSON,Promise,AbortController,sameRuleReservation,crypto:{randomUUID:()=> 'unique-attempt'},assertGenerationActive,now:()=> 'now',
+ const environment={kernelReady:null,Map,JSON,Promise,AbortController,sameRuleReservation,crypto:{randomUUID:()=> 'unique-attempt'},assertGenerationActive,now:()=> 'now',
appStateOf:async()=>snapshot(),rulesOf:async()=>structuredClone(state),nextPhase:async(_phase,event)=>event==='approve'?'proving':event==='attest'?'proved':'checked',
saveAppFiles:async(_app,writes,source,update)=>{
if(rollbackRace && update.expected.phase==='proving' && update.state.phase==='checked'){
diff --git a/studio/tools/proof_reuse.test.mjs b/studio/tools/proof_reuse.test.mjs
index e276654c..e424a949 100644
--- a/studio/tools/proof_reuse.test.mjs
+++ b/studio/tools/proof_reuse.test.mjs
@@ -90,54 +90,6 @@ async function withVerifier(v, fn) {
}
const theoremsSent = (files) => [...files.map((f) => f.content).join("\n").matchAll(/theorem\{\s*name: (\w+),/g)].map((m) => m[1]);
-test("a decision app's first proof sends every guarantee and files one record per theorem address", async () => {
- const v = fakeVerifier(), store = memoryStore();
- const result = await withVerifier(v, () => prism.prove(SPEC, { store }));
- assert.equal(result.ok, true, result.error);
- assert.equal(v.verifies.length, 2, "one axiom correction round, then the verified run");
- assert.equal(theoremsSent(v.verifies[1]).length, 3);
- assert.equal(result.record.proved, 3);
- assert.equal(result.record.reused, 0);
- assert.equal(store.m.size, 3);
- for (const key of store.m.keys()) assert.ok(key.startsWith(KEY_PREFIX));
- assert.deepEqual(result.record.theorems.map((g) => g.refusal), [REFUSAL.absent, REFUSAL.absent, REFUSAL.absent]);
-});
-
-test("an unchanged decision app is proved with no Lean run, under the axiom sets Lean observed", async () => {
- const v = fakeVerifier(), store = memoryStore();
- const first = await withVerifier(v, () => prism.prove(SPEC, { store }));
- const runs = v.verifies.length, drafts = v.calls.filter((c) => c === "lexlean_draft_write").length;
- let submitted = 0;
- const again = await withVerifier(v, () => prism.prove(specOf(RAW), { store, beforeSubmit: () => submitted++ }));
- assert.equal(again.ok, true, again.error);
- assert.equal(v.verifies.length, runs, "no verify call");
- assert.equal(v.calls.filter((c) => c === "lexlean_draft_write").length, drafts, "no source sent");
- assert.equal(submitted, 1, "the caller is told the proof was committed to");
- assert.equal(again.record.reused, 3);
- assert.equal(again.record.proved, 0);
- assert.equal(again.record.attestation_id, first.record.attestation_id);
- assert.deepEqual(again.axioms, first.axioms);
- assert.match(prism.proofMessage(SPEC, again), /none was proved again/);
-});
-
-test("changing one guarantee sends only its theorem, with the cached axiom sets, in one run", async () => {
- const v = fakeVerifier(), store = memoryStore();
- await withVerifier(v, () => prism.prove(SPEC, { store }));
- const edited = structuredClone(RAW);
- edited.properties[1].when[1].value = 4;
- const spec = specOf(edited);
- const runs = v.verifies.length;
- const result = await withVerifier(v, () => prism.prove(spec, { store }));
- assert.equal(result.ok, true, result.error);
- assert.equal(v.verifies.length, runs + 1, "no axiom correction round");
- assert.deepEqual(theoremsSent(v.verifies.at(-1)), [names(spec).properties[spec.properties[1].id].theorem]);
- assert.deepEqual(result.record.theorems.map((g) => g.reused), [true, false, true]);
- assert.equal(result.record.reused, 2);
- assert.equal(result.record.proved, 1);
- assert.equal(result.record.attestations.length, 2);
- assert.match(prism.proofMessage(spec, result), /2 were proved before.*Lean proved the other 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 }));
@@ -213,51 +165,12 @@ test("a record is refused unless its address, verifier, bytes and attestation al
assert.equal((await check(entry, { found: async () => false })).refusal, REFUSAL.attestation);
});
-test("a refused or unreadable record means proving again, never a failure", async () => {
- const v = fakeVerifier(), store = memoryStore();
- await withVerifier(v, () => prism.prove(SPEC, { store }));
- const [key, entry] = [...store.m.entries()][0];
- store.m.set(key, { ...entry, files: entry.files.map((f, i) => (i ? f : { ...f, content: f.content + " " })) });
- const runs = v.verifies.length;
- const tampered = await withVerifier(v, () => prism.prove(SPEC, { store }));
- assert.equal(tampered.ok, true, tampered.error);
- assert.equal(v.verifies.length, runs + 1);
- assert.equal(tampered.record.proved, 1);
- assert.equal(tampered.record.theorems.find((g) => g.theorem === entry.theorem).refusal, REFUSAL.bytes);
- v.forget = true;
- const forgotten = await withVerifier(v, () => prism.prove(SPEC, { store }));
- assert.equal(forgotten.ok, true, forgotten.error);
- assert.equal(forgotten.record.proved, 3, "attestations the verifier no longer finds are not believed");
- const silent = fakeVerifier();
- const answer = silent.fetch;
- silent.fetch = async (url, init) => (init && JSON.parse(init.body).params.name === "lexlean_attestation" ? new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, error: { message: "unavailable" } })) : answer(url, init));
- const unanswered = await withVerifier(silent, () => prism.prove(SPEC, { store }));
- assert.equal(unanswered.ok, true, "a lookup the verifier does not answer means proving everything");
- assert.equal(theoremsSent(silent.verifies.at(-1)).length, 3);
- const broken = { get: async () => { throw new Error("storage refused"); }, put: async () => { throw new Error("storage refused"); } };
- const unreadable = await withVerifier(fakeVerifier(), () => prism.prove(SPEC, { store: broken }));
- assert.equal(unreadable.ok, true, unreadable.error);
- assert.equal(unreadable.record.proved, 3);
-});
-
-test("the host proves both kinds of app with a store over its refs records", async () => {
+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 start = host.indexOf("async function proveRules(");
- const source = host.slice(start, host.indexOf("\n}\n", start) + 3) + "\nproveRules";
- const rule = { phase: "proving", specKappa: "k", spec: SPEC };
- const touched = [];
- const proveRules = vm.runInNewContext(source, {
- rulesOf: async () => rule, sameRuleReservation: (a, b) => a === b, nextPhase: async () => "proved", saveRules: async () => true, now: () => "now",
- put: async (...a) => { touched.push(["put", ...a]); }, get: async (...a) => { touched.push(["get", ...a]); return undefined; }, refreshLive: async () => {}, refreshRules: async () => {},
- prism: { prove: async (_, opts) => { await opts.store.get("x"); await opts.store.put("y", 1); return { ok: true, record: {} }; } },
- });
- await proveRules(1, "k", () => {});
- assert.deepEqual(touched.slice(0, 2), [["get", "refs", "x"], ["put", "refs", "y", 1]]);
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();
diff --git a/studio/tools/rules_source.test.mjs b/studio/tools/rules_source.test.mjs
index cd95fa50..d30aaca2 100644
--- a/studio/tools/rules_source.test.mjs
+++ b/studio/tools/rules_source.test.mjs
@@ -18,7 +18,7 @@ test("proof completion checks the current source-bound state and its expected pr
const proving = { ...rule, phase: "proving" };
for (const latest of [null, proving]) {
let calls = 0, checkedPrior = false;
- const prove = operation("proveRules", '// "approve"', { rulesOf: async () => ++calls === 1 ? proving : latest, prism: { prove: async () => ({ ok: true, record: { id: "receipt" } }) }, nextPhase: async () => "proved", saveRules: async (_, state, prior) => { checkedPrior = true; assert.equal(prior, proving); assert.equal(state.phase, "proved"); return false; }, now: () => "now", put() { assert.fail("stale proof must not be recorded as accepted"); } });
+ const prove = operation("proveRules", '// "approve"', { rulesOf: async () => ++calls === 1 ? proving : latest, kernelReady: null, prism: { prove: async () => ({ ok: true, record: { id: "receipt" } }) }, nextPhase: async () => "proved", saveRules: async (_, state, prior) => { checkedPrior = true; assert.equal(prior, proving); assert.equal(state.phase, "proved"); return false; }, now: () => "now", put() { assert.fail("stale proof must not be recorded as accepted"); } });
assert.equal(await prove(1, proving.specKappa), null);
assert.equal(checkedPrior, latest !== null);
}
diff --git a/v2/in-tab-check/REPORT.md b/v2/in-tab-check/REPORT.md
index 03649df9..cd089bda 100644
--- a/v2/in-tab-check/REPORT.md
+++ b/v2/in-tab-check/REPORT.md
@@ -1,5 +1,7 @@
# LexLean's check, in the tab
+> The scripts and crate this report ran are no longer in the tree: they are at commit d2a1a71 (`git show d2a1a71:v2/in-tab-check/`). Foundry now proves rule apps in the tab with Lean's kernel instead (studio/shell/prism.js `prove`).
+
Result: LexLean's own `check` runs in a browser worker with no server. It is the pinned LexLean 0.3.0, compiled to WebAssembly from the commit the SDK image names, with a patch of 59 added lines. On all 17 corpus files it gives the image's verdict, codes, messages, lines and columns, and it writes the image's lock file byte for byte. An edited spec gets its verdict in about 50 ms, against 500 to 1,000 ms on the hosted route. The verdict is "checked", never "proved".
It is an experiment, not something to ship today: it needs a patched LexLean, and Foundry ships no fork. What it would take is in section 7.
diff --git a/v2/in-tab-check/agree.mjs b/v2/in-tab-check/agree.mjs
deleted file mode 100644
index 0da94c6f..00000000
--- a/v2/in-tab-check/agree.mjs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Checks every corpus case with the in-tab checker (here in Node, the same files a worker runs) and compares it with
-// the SDK image's recorded result. Run directly, it prints the table and writes agreement.json.
-import { readFileSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { load } from "./checker.mjs";
-import { cases } from "../hosted-check/corpus.mjs";
-
-const here = dirname(fileURLToPath(import.meta.url));
-export const manifest = (variant = "") => JSON.parse(readFileSync(join(here, `checker${variant}.json`), "utf8"));
-export const image = () => JSON.parse(readFileSync(join(here, "..", "hosted-check", "image-results.json"), "utf8"));
-export function checkerBytes(variant = "") {
- try { return readFileSync(join(here, "dist", `lexlean-tab${variant}.wasm`)); }
- catch { throw new Error(`v2/in-tab-check/dist/lexlean-tab${variant}.wasm is absent: build it with "bash v2/in-tab-check/build.sh" (it is not committed)`); }
-}
-export const fromDisk = ({ variant = "", ...options } = {}) => load({ wasm: checkerBytes(variant), pack: readFileSync(join(here, "pack.json")), manifest: manifest(variant), ...options });
-const key = (d) => `${d.code} ${d.path}:${d.line}:${d.column}-${d.endLine}:${d.endColumn} ${d.message}`;
-
-export async function compareAll(checker, scope = "author") {
- const want = image(), rows = [];
- for (const c of cases()) {
- const got = await checker.check(c.spec, { extras: c.extras, scope });
- const w = want.cases[c.id];
- const a = w.diagnostics.map(key).sort(), b = got.diagnostics.map(key).sort();
- rows.push({
- id: c.id, image: w.ok, tab: got.ok, verdictAgrees: w.ok === got.ok,
- imageCodes: w.diagnostics.map((d) => d.code), tabCodes: got.diagnostics.map((d) => d.code),
- identical: JSON.stringify(a) === JSON.stringify(b),
- differences: { imageOnly: a.filter((x) => !b.includes(x)), tabOnly: b.filter((x) => !a.includes(x)) },
- ms: Math.round(got.ms.total * 10) / 10,
- });
- }
- return rows;
-}
-
-if (process.argv[1] === fileURLToPath(import.meta.url)) {
- const variant = process.argv[2] ?? "";
- const checker = await fromDisk({ variant });
- console.log(JSON.stringify(checker.by), JSON.stringify(checker.loadMs), `warm ${checker.warm().toFixed(0)} ms`);
- const all = await compareAll(checker, "all"), rows = await compareAll(checker, "author");
- for (const r of rows) { const a = all.find((x) => x.id === r.id); r.msAll = a.ms; r.identicalAll = a.identical && a.verdictAgrees; }
- writeFileSync(join(here, `agreement${variant}.json`), JSON.stringify({ by: checker.by, image: image().image, imageVersion: image().version, rows }, null, 1) + "\n");
- for (const r of rows) console.log(`${r.id.padEnd(34)} image ${r.image ? "accept" : "refuse"} tab ${r.tab ? "accept" : "refuse"} ${r.verdictAgrees ? "agree" : "DISAGREE"} ${r.identical ? "identical" : "DIFF " + JSON.stringify(r.differences)} ${r.imageCodes.join(",")} ${r.ms} ms (scope all: ${r.identicalAll ? "identical" : "DIFF"}, ${r.msAll} ms)`);
-}
diff --git a/v2/in-tab-check/bench.html b/v2/in-tab-check/bench.html
deleted file mode 100644
index 9894fd74..00000000
--- a/v2/in-tab-check/bench.html
+++ /dev/null
@@ -1,102 +0,0 @@
-
-
-
-In-tab check: measurements
-
-In-tab check: measurements
-starting
-
-
diff --git a/v2/in-tab-check/build.sh b/v2/in-tab-check/build.sh
deleted file mode 100644
index 2e923e68..00000000
--- a/v2/in-tab-check/build.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env bash
-# Builds dist/lexlean-tab.wasm and dist/lexlean-tab-lean.wasm from their source: PrismPM at the commit the SDK image
-# names, its vendored LexLean with the patches in upstream/ applied, and the wrapper in crate/. Run on Linux or in WSL
-# with Rust 1.97.1 and the wasm32-wasip1 target. An experiment: Foundry ships no fork, so this stands only until
-# upstream takes the patches. The bytes depend on the work directory's path (it is in panic messages), so the recorded
-# addresses are reproduced only with the default one.
-# bash v2/in-tab-check/build.sh
-set -euo pipefail
-here=$(cd "$(dirname "$0")" && pwd)
-work=$HOME/itc
-commit=35e9f01d5415ed4b0b64c152238f291546957ec4
-# The stack LexLean's own plan gives the compile thread for max_scope_depth = 1024 (config.rs: 16 MiB + 1024 * 64 KiB).
-export RUSTFLAGS="-C link-arg=-zstack-size=83886080"
-# The language-1.2 compiler-semantics ID the lean build carries: the one in the lock the SDK image wrote.
-semantics=$(sed -n 's/^compiler_semantics = "\([0-9a-f]\{64\}\)"$/\1/p' "$here/../probe-payment/lexlean.lock")
-
-mkdir -p "$work" "$here/dist"
-if [ ! -d "$work/PrismPM/.git" ]; then git clone -q https://github.com/UOR-Foundation/PrismPM.git "$work/PrismPM"; fi
-git -C "$work/PrismPM" checkout -q -f "$commit"
-mkdir -p "$work/tab"
-cp -r "$here/crate/." "$work/tab/"
-sed -i "s#^lexlean = .*#lexlean = { path = \"$work/PrismPM/vendor/lexlean\" }#" "$work/tab/Cargo.toml"
-
-git -C "$work/PrismPM" apply "$here/upstream/wasm-check.patch"
-( cd "$work/tab" && cargo +1.97.1 build --release --locked --target wasm32-wasip1 )
-cp "$work/tab/target/wasm32-wasip1/release/lexlean_tab.wasm" "$here/dist/lexlean-tab.wasm"
-
-git -C "$work/PrismPM" apply "$here/upstream/lean-embed.patch"
-( cd "$work/tab" && LEXLEAN_CHECK_ONLY_SEMANTICS_1_2=$semantics cargo +1.97.1 build --release --locked --target wasm32-wasip1 )
-cp "$work/tab/target/wasm32-wasip1/release/lexlean_tab.wasm" "$here/dist/lexlean-tab-lean.wasm"
-
-sha256sum "$here/dist/lexlean-tab.wasm" "$here/dist/lexlean-tab-lean.wasm"
-echo "now run: node v2/in-tab-check/make-manifest.mjs --check (or --write after a deliberate change)"
diff --git a/v2/in-tab-check/checker.mjs b/v2/in-tab-check/checker.mjs
deleted file mode 100644
index fdcb1add..00000000
--- a/v2/in-tab-check/checker.mjs
+++ /dev/null
@@ -1,172 +0,0 @@
-// The in-tab checker: LexLean's own check, run as WebAssembly over a file system held in memory. No rule lives here.
-// This file assembles the project the SDK image would see, runs `lexlean lock` and `lexlean check --all` in it, and
-// reads back the result. It needs no network once it holds the checker's bytes, and it is given none.
-//
-// Addresses are Hologram content addresses on the sha256 axis ("sha256:"): the browser hashes natively, at about
-// a gigabyte a second, where BLAKE3 in script takes two seconds for these bytes.
-import { open, tree, listing } from "./wasi.mjs";
-
-const enc = new TextEncoder();
-const fail = (code, message) => Object.assign(new Error(message), { code });
-const hex = (buffer) => [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
-
-export async function address(bytes) {
- return "sha256:" + hex(await crypto.subtle.digest("SHA-256", typeof bytes === "string" ? enc.encode(bytes) : bytes));
-}
-
-// The address of a computation: a domain, then each part with its length, so no two lists of parts share a preimage.
-export async function derive(domain, parts) {
- const chunks = [enc.encode(domain)];
- for (const part of parts) { const b = enc.encode(part); chunks.push(enc.encode(`\0${b.length}\0`), b); }
- const all = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
- let at = 0;
- for (const c of chunks) { all.set(c, at); at += c.length; }
- return address(all);
-}
-
-const moduleName = (source) => source.match(/^\\begin\{lexlean\}\{([^}\n]+)\}/m)?.[1] ?? "App";
-const modulePath = (name) => `src/${name.split(".").join("/")}.lex.tex`;
-const shape = (d) => ({
- code: d.code, severity: d.severity, message: d.message, path: d.primary?.path,
- line: d.primary?.line_start, column: d.primary?.column_start, endLine: d.primary?.line_end, endColumn: d.primary?.column_end,
- byteStart: d.primary?.byte_start, byteEnd: d.primary?.byte_end,
-});
-
-// manifest: { checker: address, pack: address, lexlean: { version, semantics } }. wasm and pack are bytes.
-// Refuses bytes whose address is not the manifest's, and a checker that does not report the manifest's compiler.
-// store, when given, is { get(key), put(key, value) } over strings and may be asynchronous; it is never trusted.
-export async function load({ wasm, pack, manifest, store = null, recycleBytes = 1 << 30 }) {
- const t0 = performance.now();
- const [wasmAddress, packAddress] = await Promise.all([address(wasm), address(pack)]);
- if (wasmAddress !== manifest.checker) throw fail("ITC_ADDRESS", `the checker's bytes are ${wasmAddress}, not ${manifest.checker}`);
- if (packAddress !== manifest.pack) throw fail("ITC_ADDRESS", `the library pack is ${packAddress}, not ${manifest.pack}`);
- const tHash = performance.now();
- const module = await WebAssembly.compile(wasm);
- const tCompile = performance.now();
- const fixed = JSON.parse(new TextDecoder().decode(pack)).files;
- const base = Object.entries(fixed).map(([path, text]) => [path, enc.encode(text)]);
- let instance = open(module);
- const tOpen = performance.now();
-
- const call = (name, args, files) => {
- if (instance.memoryBytes() > recycleBytes) instance = open(module);
- let r;
- try { r = instance.call(name, { args: ["lexlean", ...args], root: tree(files) }); }
- catch (e) { instance = open(module); throw e; }
- if (r.trap) { instance = open(module); throw fail("ITC_TRAP", `the checker stopped: ${r.trap.message}`); }
- return r;
- };
-
- // The checker says what it is. A build of another LexLean is refused here, whatever its address.
- const said = call("run", ["--version"], new Map()).stdout;
- const reported = { version: said.match(/^lexlean (\S+)/m)?.[1], semantics: said.match(/^compiler-semantics (\S+)/m)?.[1] };
- if (reported.version !== manifest.lexlean.version || reported.semantics !== manifest.lexlean.semantics) {
- throw fail("ITC_VERSION", `the checker reports lexlean ${reported.version} (${reported.semantics}); the manifest names ${manifest.lexlean.version} (${manifest.lexlean.semantics})`);
- }
- const by = { route: "in-tab", checker: wasmAddress, pack: packAddress, lexlean: reported.version, semantics: reported.semantics };
- const tVersion = performance.now();
- const locks = new Map(), memo = new Map();
-
- const project = (spec, extras) => {
- const own = [spec, ...extras].map((source) => ({ name: moduleName(source), source }));
- const files = new Map(base.map(([path, bytes]) => [`/${path}`, bytes]));
- for (const m of own) files.set(`/${modulePath(m.name)}`, enc.encode(m.source));
- const toml = fixed["lexlean.toml"].replace(/^entrypoints = .*$/m, `entrypoints = ["${modulePath(own[0].name)}"]`);
- files.set("/lexlean.toml", enc.encode(toml));
- return { own, files, toml };
- };
-
- // One uncached check: lock (once per configuration), check, and on a pass the data form of each of the author's modules.
- // scope "author" names the author's modules, so LexLean checks them and all they import; scope "all" is
- // `check --all`, which also checks the library modules nothing imports. The library is fixed by the pack's address
- // and passes `check --all` on its own (test.mjs holds that), so the two differ only in time.
- const compute = (spec, extras, scope) => {
- const { own, files, toml } = project(spec, extras), ms = {};
- let t = performance.now(), checked;
- for (let attempt = 0; ; attempt++) {
- if (!locks.has(toml)) {
- const locked = call("run", ["--project", "/lexlean.toml", "--diagnostic-format", "json", "lock"], files);
- if (locked.code !== 0) { checked = locked; break; }
- locks.set(toml, listing(locked.root).get("/lexlean.lock").slice());
- ms.lock = performance.now() - t; t = performance.now();
- }
- files.set("/lexlean.lock", locks.get(toml));
- const selection = scope === "all" ? ["--all"] : own.map((m) => modulePath(m.name));
- checked = call("run", ["--project", "/lexlean.toml", "--diagnostic-format", "json", "check", ...selection], files);
- // A lock LexLean calls stale is made again, once; it is LexLean that decides.
- if (attempt === 0 && /"code":"LLC0102"/.test(checked.stdout)) { locks.delete(toml); continue; }
- break;
- }
- ms.check = performance.now() - t; t = performance.now();
- let result;
- try { result = JSON.parse(checked.stdout); } catch { throw fail("ITC_OUTPUT", `the checker wrote no result (exit ${checked.code}): ${checked.stderr.slice(0, 200)}`); }
- const out = { ok: result.success === true, exit: checked.code, diagnostics: result.diagnostics.map(shape) };
- if (out.ok) {
- out.data = {};
- for (const m of own) {
- const r = call("data", [`/${modulePath(m.name)}`], files);
- const text = r.code === 0 ? r.stdout.match(/\\semanticdata\{([\s\S]*)\}\n\\end\{semanticmodule\}/)?.[1] : null;
- if (!text) throw fail("ITC_DATA", `no data form for ${m.name} (exit ${r.code})`);
- out.data[m.name] = JSON.parse(text);
- }
- ms.data = performance.now() - t;
- }
- return { out, ms };
- };
-
- return {
- by,
- loadMs: { hash: tHash - t0, compile: tCompile - tHash, instantiate: tOpen - tCompile, version: tVersion - tOpen },
- memoryBytes: () => instance.memoryBytes(),
- // Computes the compiler's identity for language 1.2 ahead of the first check.
- warm() { const t = performance.now(); call("warm", [], new Map()); return performance.now() - t; },
- // The lock LexLean writes for a spec's project, as text.
- lock(spec, { extras = [] } = {}) {
- const { files } = project(spec, extras);
- const locked = call("run", ["--project", "/lexlean.toml", "--diagnostic-format", "json", "lock"], files);
- return new TextDecoder().decode(listing(locked.root).get("/lexlean.lock"));
- },
- // `check --all` on the pack alone: the library and lexicon with no module of an author's.
- library() {
- const files = new Map(base.map(([path, bytes]) => [`/${path}`, bytes]));
- files.set("/lexlean.toml", enc.encode(fixed["lexlean.toml"].replace(/^entrypoints = .*$/m, 'entrypoints = ["src/Foundation/Bytes.lex.tex"]')));
- const locked = call("run", ["--project", "/lexlean.toml", "--diagnostic-format", "json", "lock"], files);
- files.set("/lexlean.lock", listing(locked.root).get("/lexlean.lock").slice());
- return JSON.parse(call("run", ["--project", "/lexlean.toml", "--diagnostic-format", "json", "check", "--all"], files).stdout);
- },
- // The data form of one library module, by LexLean's own reader.
- libraryData(name) {
- const r = call("data", [`/${modulePath(name)}`], new Map(base.map(([path, bytes]) => [`/${path}`, bytes])));
- if (r.code !== 0) throw fail("ITC_DATA", `no data form for ${name} (exit ${r.code})`);
- return JSON.parse(r.stdout.match(/\\semanticdata\{([\s\S]*)\}\n\\end\{semanticmodule\}/)[1]);
- },
- // Returns { ok, diagnostics, data?, by, cached, ms }. A result is reused only under the address of everything that
- // produced it: the checker, the pack and every module's text. A stored result that does not hash to what was
- // recorded with it is dropped and the check is run.
- async check(spec, { extras = [], scope = "author" } = {}) {
- if (scope !== "author" && scope !== "all") throw fail("ITC_SCOPE", `unknown scope ${scope}`);
- const started = performance.now();
- const key = await derive("foundry/in-tab-check/result/1", [wasmAddress, packAddress, scope, spec, ...extras]);
- const keyed = performance.now();
- let text = memo.get(key), cached = text ? "memory" : false;
- if (!text && store) {
- const kept = await store.get(key);
- if (kept) {
- try {
- const entry = JSON.parse(kept);
- if (entry.key === key && (await address(entry.value)) === entry.value_address) { text = entry.value; cached = "store"; }
- } catch { /* a damaged entry is the same as none */ }
- }
- }
- let ms = {};
- if (!text) {
- const fresh = compute(spec, extras, scope);
- ms = fresh.ms;
- text = JSON.stringify(fresh.out);
- if (store) await store.put(key, JSON.stringify({ key, value: text, value_address: await address(text) }));
- }
- memo.set(key, text);
- return { ...JSON.parse(text), by, cached, key, ms: { ...ms, key: keyed - started, total: performance.now() - started } };
- },
- };
-}
diff --git a/v2/in-tab-check/client.mjs b/v2/in-tab-check/client.mjs
deleted file mode 100644
index 32755d54..00000000
--- a/v2/in-tab-check/client.mjs
+++ /dev/null
@@ -1,62 +0,0 @@
-// The page's side: get the checker's bytes by address, hand them to the worker, and answer `check(spec)` in the tab
-// when the worker is ready and through the hosted service when it is not. Every answer says which one gave it.
-const fail = (code, message) => Object.assign(new Error(message), { code });
-
-// bytesOf(name, address) returns an ArrayBuffer for a manifest entry; the worker refuses bytes that do not match.
-// hosted(spec, options) is the hosted route (v2/hosted-check/check.mjs), or null for none.
-// makeWorker() returns a Worker-like object (postMessage, onmessage, onerror).
-export function createClient({ makeWorker, manifest, bytesOf, hosted = null, onState = () => {} }) {
- let worker = null, ready = null, state = "idle", next = 0;
- const waiting = new Map();
- const set = (s, detail) => { state = s; onState(s, detail); };
- const ask = (message, transfer = []) => new Promise((resolve, reject) => {
- const id = ++next;
- waiting.set(id, { resolve, reject });
- worker.postMessage({ id, ...message }, transfer);
- });
- const start = () => {
- if (ready) return ready;
- set("loading");
- ready = (async () => {
- const [wasm, pack] = await Promise.all([bytesOf("checker", manifest.checker), bytesOf("pack", manifest.pack)]);
- worker = makeWorker();
- worker.onmessage = ({ data }) => {
- const w = waiting.get(data.id);
- waiting.delete(data.id);
- if (data.error) w?.reject(fail(data.error.code, data.error.message)); else w?.resolve(data);
- };
- worker.onerror = (e) => { for (const w of waiting.values()) w.reject(fail("ITC_WORKER", e.message ?? "the worker failed")); waiting.clear(); };
- const loaded = await ask({ type: "load", wasm, pack, manifest }, [wasm, pack]);
- const warmed = await ask({ type: "warm" });
- set("ready", { by: loaded.by, loadMs: loaded.loadMs, warmMs: warmed.ms });
- return loaded;
- })().catch((e) => { set("unavailable", { code: e.code ?? "ITC_LOAD", message: e.message }); throw e; });
- return ready;
- };
- return {
- start,
- ask: (message) => ask(message),
- state: () => state,
- // In the tab when it is ready. Otherwise the hosted service answers this one while the tab's checker loads,
- // unless `only: "in-tab"` asks to wait for it. Nothing moves to the hosted route silently: such an answer names
- // that route and why the tab did not give it.
- async check(spec, { extras = [], only = null } = {}) {
- let why;
- if (state === "ready" || only === "in-tab") {
- try {
- await start();
- return (await ask({ type: "check", spec, extras })).result;
- } catch (e) {
- if (only === "in-tab" || !hosted) throw e;
- why = { code: e.code ?? "ITC_INTERNAL", message: e.message };
- }
- } else {
- start().catch(() => {});
- why = { code: state === "unavailable" ? "ITC_UNAVAILABLE" : "ITC_NOT_LOADED", message: `the checker in this tab is ${state}` };
- }
- if (!hosted) throw fail(why.code, why.message);
- const r = await hosted(spec, { extras });
- return { ...r, by: { route: "hosted", instead: why }, cached: false };
- },
- };
-}
diff --git a/v2/in-tab-check/crate/Cargo.lock b/v2/in-tab-check/crate/Cargo.lock
deleted file mode 100644
index cd73e2fc..00000000
--- a/v2/in-tab-check/crate/Cargo.lock
+++ /dev/null
@@ -1,676 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-version = 4
-
-[[package]]
-name = "anstream"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
-dependencies = [
- "anstyle",
- "anstyle-parse",
- "anstyle-query",
- "anstyle-wincon",
- "colorchoice",
- "is_terminal_polyfill",
- "utf8parse",
-]
-
-[[package]]
-name = "anstyle"
-version = "1.0.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
-
-[[package]]
-name = "anstyle-parse"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
-dependencies = [
- "utf8parse",
-]
-
-[[package]]
-name = "anstyle-query"
-version = "1.1.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
-dependencies = [
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "anstyle-wincon"
-version = "3.0.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
-dependencies = [
- "anstyle",
- "once_cell_polyfill",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "bitflags"
-version = "2.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
-
-[[package]]
-name = "block-buffer"
-version = "0.10.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
-dependencies = [
- "generic-array",
-]
-
-[[package]]
-name = "camino"
-version = "1.2.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb1307f12aa967b5a58416e87b3653360e0fd614a016b6e970db08fecbb1b80d"
-
-[[package]]
-name = "cfg-if"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
-
-[[package]]
-name = "clap"
-version = "4.6.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
-dependencies = [
- "clap_builder",
- "clap_derive",
-]
-
-[[package]]
-name = "clap_builder"
-version = "4.6.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
-dependencies = [
- "anstream",
- "anstyle",
- "clap_lex",
- "strsim",
-]
-
-[[package]]
-name = "clap_derive"
-version = "4.6.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
-dependencies = [
- "heck",
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "clap_lex"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
-
-[[package]]
-name = "colorchoice"
-version = "1.0.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
-
-[[package]]
-name = "cpufeatures"
-version = "0.2.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "crypto-common"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
-dependencies = [
- "generic-array",
- "typenum",
-]
-
-[[package]]
-name = "digest"
-version = "0.10.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
-dependencies = [
- "block-buffer",
- "crypto-common",
-]
-
-[[package]]
-name = "equivalent"
-version = "1.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
-
-[[package]]
-name = "errno"
-version = "0.3.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
-dependencies = [
- "libc",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "fastrand"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
-
-[[package]]
-name = "fs4"
-version = "0.13.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
-dependencies = [
- "rustix",
- "windows-sys 0.59.0",
-]
-
-[[package]]
-name = "generic-array"
-version = "0.14.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
-dependencies = [
- "typenum",
- "version_check",
-]
-
-[[package]]
-name = "getrandom"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
-dependencies = [
- "cfg-if",
- "libc",
- "r-efi",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.17.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
-
-[[package]]
-name = "heck"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
-
-[[package]]
-name = "indexmap"
-version = "2.14.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
-dependencies = [
- "equivalent",
- "hashbrown",
-]
-
-[[package]]
-name = "is_terminal_polyfill"
-version = "1.70.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
-
-[[package]]
-name = "itoa"
-version = "1.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
-
-[[package]]
-name = "lexlean"
-version = "0.3.0"
-dependencies = [
- "camino",
- "clap",
- "fs4",
- "rustix",
- "same-file",
- "semver",
- "serde",
- "serde_json",
- "sha2",
- "signal-hook",
- "tempfile",
- "toml",
- "unicode-normalization",
- "walkdir",
-]
-
-[[package]]
-name = "lexlean-tab"
-version = "0.0.0"
-dependencies = [
- "camino",
- "lexlean",
-]
-
-[[package]]
-name = "libc"
-version = "0.2.189"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
-
-[[package]]
-name = "linux-raw-sys"
-version = "0.12.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
-
-[[package]]
-name = "memchr"
-version = "2.8.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
-
-[[package]]
-name = "once_cell"
-version = "1.21.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
-
-[[package]]
-name = "once_cell_polyfill"
-version = "1.70.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.107"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
-dependencies = [
- "unicode-ident",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.47"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "r-efi"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
-
-[[package]]
-name = "rustix"
-version = "1.1.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
-dependencies = [
- "bitflags",
- "errno",
- "libc",
- "linux-raw-sys",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "same-file"
-version = "1.0.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
-dependencies = [
- "winapi-util",
-]
-
-[[package]]
-name = "semver"
-version = "1.0.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
-
-[[package]]
-name = "serde"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
-dependencies = [
- "serde_core",
- "serde_derive",
-]
-
-[[package]]
-name = "serde_core"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.229"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde_json"
-version = "1.0.151"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
-dependencies = [
- "itoa",
- "memchr",
- "serde",
- "serde_core",
- "zmij",
-]
-
-[[package]]
-name = "serde_spanned"
-version = "0.6.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "sha2"
-version = "0.10.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
-dependencies = [
- "cfg-if",
- "cpufeatures",
- "digest",
-]
-
-[[package]]
-name = "signal-hook"
-version = "0.3.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
-dependencies = [
- "libc",
- "signal-hook-registry",
-]
-
-[[package]]
-name = "signal-hook-registry"
-version = "1.4.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
-dependencies = [
- "errno",
- "libc",
-]
-
-[[package]]
-name = "strsim"
-version = "0.11.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
-
-[[package]]
-name = "syn"
-version = "3.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
-
-[[package]]
-name = "tempfile"
-version = "3.27.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
-dependencies = [
- "fastrand",
- "getrandom",
- "once_cell",
- "rustix",
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "tinyvec"
-version = "1.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
-dependencies = [
- "tinyvec_macros",
-]
-
-[[package]]
-name = "tinyvec_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
-
-[[package]]
-name = "toml"
-version = "0.8.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
-dependencies = [
- "serde",
- "serde_spanned",
- "toml_datetime",
- "toml_edit",
-]
-
-[[package]]
-name = "toml_datetime"
-version = "0.6.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
-dependencies = [
- "serde",
-]
-
-[[package]]
-name = "toml_edit"
-version = "0.22.27"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
-dependencies = [
- "indexmap",
- "serde",
- "serde_spanned",
- "toml_datetime",
- "toml_write",
- "winnow",
-]
-
-[[package]]
-name = "toml_write"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
-
-[[package]]
-name = "typenum"
-version = "1.20.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
-
-[[package]]
-name = "unicode-ident"
-version = "1.0.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
-
-[[package]]
-name = "unicode-normalization"
-version = "0.1.25"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
-dependencies = [
- "tinyvec",
-]
-
-[[package]]
-name = "utf8parse"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
-
-[[package]]
-name = "version_check"
-version = "0.9.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
-
-[[package]]
-name = "walkdir"
-version = "2.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
-dependencies = [
- "same-file",
- "winapi-util",
-]
-
-[[package]]
-name = "winapi-util"
-version = "0.1.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
-dependencies = [
- "windows-sys 0.61.2",
-]
-
-[[package]]
-name = "windows-link"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
-
-[[package]]
-name = "windows-sys"
-version = "0.59.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
-dependencies = [
- "windows-targets",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.61.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
-dependencies = [
- "windows-link",
-]
-
-[[package]]
-name = "windows-targets"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
-dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_gnullvm",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
-]
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
-
-[[package]]
-name = "windows_i686_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.52.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
-
-[[package]]
-name = "winnow"
-version = "0.7.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "zmij"
-version = "1.0.23"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/v2/in-tab-check/crate/Cargo.toml b/v2/in-tab-check/crate/Cargo.toml
deleted file mode 100644
index 5fe834f1..00000000
--- a/v2/in-tab-check/crate/Cargo.toml
+++ /dev/null
@@ -1,22 +0,0 @@
-# The in-tab checker: LexLean's own command-line entry, linked as a WebAssembly library whose instance stays alive
-# between checks. It holds no rule of its own. `lexlean` is the pinned crate with upstream/wasm-check.patch applied.
-[package]
-name = "lexlean-tab"
-version = "0.0.0"
-edition = "2021"
-publish = false
-
-[lib]
-crate-type = ["cdylib"]
-
-[dependencies]
-lexlean = { path = "../../../../lexlean" }
-camino = "1.2"
-
-[profile.release]
-# Full link-time optimisation was not used: it needs more memory than the build machine had free.
-opt-level = 3
-panic = "abort"
-strip = true
-
-[workspace]
diff --git a/v2/in-tab-check/crate/src/lib.rs b/v2/in-tab-check/crate/src/lib.rs
deleted file mode 100644
index 7df2349a..00000000
--- a/v2/in-tab-check/crate/src/lib.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-//! LexLean's command line as a WebAssembly library. `run` is `lexlean::cli::run` with the arguments the host
-//! supplies; `data` is `lexlean::identity_bytes`. Nothing here decides anything about a spec.
-// An exported symbol is the one thing here the compiler calls unsafe: the three names below are this library's whole
-// surface, and no other unsafe code is allowed.
-#![deny(unsafe_op_in_unsafe_fn)]
-#![allow(unsafe_code)]
-
-use std::io::Write;
-
-/// Runs one LexLean command with the host's arguments and returns its documented exit code.
-#[export_name = "run"]
-pub extern "C" fn run() -> i32 {
- let arguments: Vec = std::env::args().collect();
- let mut stdout = std::io::stdout();
- let mut stderr = std::io::stderr();
- let code = lexlean::cli::run(
- &arguments,
- camino::Utf8Path::new("/"),
- &mut stdout,
- &mut stderr,
- );
- let _ = stdout.flush();
- let _ = stderr.flush();
- code
-}
-
-/// Writes the data form of the source named by the one argument to standard output: 0 when the source holds a
-/// module in the notation, 1 when it holds none or one that is not well formed, 2 when it cannot be read.
-#[export_name = "data"]
-pub extern "C" fn data() -> i32 {
- let Some(path) = std::env::args().nth(1) else {
- return 2;
- };
- let Ok(bytes) = std::fs::read(&path) else {
- return 2;
- };
- match lexlean::identity_bytes(&path, &bytes) {
- std::borrow::Cow::Owned(data) => {
- let mut stdout = std::io::stdout();
- let written = stdout.write_all(&data).and_then(|()| stdout.flush());
- i32::from(written.is_err()) * 2
- }
- std::borrow::Cow::Borrowed(_) => 1,
- }
-}
-
-/// Computes the compiler-semantics ID of language 1.2 once, so the first check does not wait for it.
-#[export_name = "warm"]
-pub extern "C" fn warm() -> i32 {
- let _ = lexlean::compiler_semantics_id_for(lexlean::LANGUAGE_1_2);
- 0
-}
diff --git a/v2/in-tab-check/make-manifest.mjs b/v2/in-tab-check/make-manifest.mjs
deleted file mode 100644
index d076291f..00000000
--- a/v2/in-tab-check/make-manifest.mjs
+++ /dev/null
@@ -1,63 +0,0 @@
-// checker.json names the checker a tab may run: the address of its bytes, the address of the library pack, and the
-// LexLean it must report. The LexLean identity is copied from what the SDK image said of itself
-// (v2/hosted-check/image-results.json), never from the built binary, so a build of another LexLean cannot name itself.
-// checker-lean.json is the same for the lean checker: the same source built with upstream/lean-embed.patch as well,
-// which leaves out the bytes of the preservation library and carries the language-1.2 identity the image's lock records.
-// node make-manifest.mjs --write records the files in dist/ as the checkers
-// node make-manifest.mjs --check fails unless dist/ and pack.json hold the ones recorded
-import { createHash } from "node:crypto";
-import { readFileSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { gzipSync, brotliCompressSync } from "node:zlib";
-
-const here = dirname(fileURLToPath(import.meta.url));
-const read = (...p) => readFileSync(join(here, ...p));
-const address = (bytes) => "sha256:" + createHash("sha256").update(bytes).digest("hex");
-export const variants = ["", "-lean"];
-
-export function describe(variant = "") {
- const wasm = read("dist", `lexlean-tab${variant}.wasm`), pack = read("pack.json");
- const image = JSON.parse(read("..", "hosted-check", "image-results.json"));
- return {
- spec: "foundry/in-tab-checker/1",
- checker: address(wasm),
- checker_bytes: wasm.length,
- checker_gzip_bytes: gzipSync(wasm, { level: 9 }).length,
- checker_brotli_bytes: brotliCompressSync(wasm).length,
- pack: address(pack),
- pack_bytes: pack.length,
- pack_gzip_bytes: gzipSync(pack, { level: 9 }).length,
- lexlean: { version: image.version.match(/^lexlean (\S+)/m)[1], semantics: image.version.match(/^compiler-semantics (\S+)/m)[1] },
- source: {
- repository: "https://github.com/UOR-Foundation/PrismPM",
- commit: "35e9f01d5415ed4b0b64c152238f291546957ec4",
- crate: "vendor/lexlean",
- patches: ["wasm-check.patch", ...(variant ? ["lean-embed.patch"] : [])].map((p) => address(read("upstream", p))),
- // The identity the lean build carries instead of computing: the one in the lock the image wrote.
- ...(variant ? { semantics_1_2: read("..", "probe-payment", "lexlean.lock").toString().match(/^compiler_semantics = "([0-9a-f]{64})"/m)[1] } : {}),
- wrapper: address(Buffer.concat([read("crate", "Cargo.toml"), read("crate", "Cargo.lock"), read("crate", "src", "lib.rs")])),
- build: address(read("build.sh")),
- rust: "1.97.1",
- target: "wasm32-wasip1",
- },
- image: image.image,
- };
-}
-
-if (process.argv[1] === fileURLToPath(import.meta.url)) {
- let failed = false;
- for (const variant of variants) {
- const now = describe(variant), name = `checker${variant}.json`;
- if (process.argv.includes("--write")) {
- writeFileSync(join(here, name), JSON.stringify(now, null, 1) + "\n");
- console.log(`${name}: ${now.checker}, ${now.checker_bytes} bytes (${now.checker_gzip_bytes} gzip, ${now.checker_brotli_bytes} brotli)`);
- } else {
- const kept = JSON.parse(read(name));
- const differing = Object.keys(now).filter((k) => JSON.stringify(now[k]) !== JSON.stringify(kept[k]));
- if (differing.length) { console.error(`${name} does not describe these files: ${differing.join(", ")} differ`); failed = true; }
- else console.log(`${name} describes the built checker and its sources`);
- }
- }
- if (failed) process.exit(1);
-}
diff --git a/v2/in-tab-check/make-pack.mjs b/v2/in-tab-check/make-pack.mjs
deleted file mode 100644
index 8621997d..00000000
--- a/v2/in-tab-check/make-pack.mjs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Builds pack.json: every file a check needs besides the author's modules. The project files and the library come
-// from v2/probe-payment, whose library copies are byte for byte the SDK image's (v2/hosted-check/image-results.json).
-import { readFileSync, readdirSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const here = dirname(fileURLToPath(import.meta.url));
-const from = join(here, "..", "probe-payment");
-const files = {};
-const walk = (rel) => {
- for (const e of readdirSync(join(from, rel), { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
- const path = `${rel}/${e.name}`;
- if (e.isDirectory()) walk(path);
- else files[path] = readFileSync(join(from, path), "utf8");
- }
-};
-for (const f of ["lakefile.toml", "lake-manifest.json", "lean-toolchain", "lexlean.toml"]) files[f] = readFileSync(join(from, f), "utf8");
-walk("language");
-walk("src/Foundation");
-for (const [path, text] of Object.entries(files)) if (text.includes("\r")) throw new Error(`${path} has a carriage return; the image's copy has none`);
-const image = readFileSync(join(here, "..", "..", "prismpm.lock"), "utf8").match(/"sdk_image":"([^"]+)"/)[1];
-writeFileSync(join(here, "pack.json"), JSON.stringify({ spec: "foundry/in-tab-check-pack/1", image, files }) + "\n");
-console.log(`pack.json: ${Object.keys(files).length} files`);
diff --git a/v2/in-tab-check/serve.mjs b/v2/in-tab-check/serve.mjs
deleted file mode 100644
index 1227c08a..00000000
--- a/v2/in-tab-check/serve.mjs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Development only: a static server for v2/ that sends the headers a static host or the service worker would.
-// The worker's own response carries a policy with no connection allowed, so the checker cannot reach a network.
-import { createServer } from "node:http";
-import { readFile } from "node:fs/promises";
-import { extname, join, normalize, sep } from "node:path";
-import { fileURLToPath } from "node:url";
-import { gzipSync } from "node:zlib";
-
-const root = fileURLToPath(new URL("..", import.meta.url));
-const types = { ".html": "text/html; charset=utf-8", ".mjs": "text/javascript", ".json": "application/json", ".wasm": "application/wasm", ".tex": "text/plain; charset=utf-8" };
-const port = Number(process.env.PORT || 4231);
-const zipped = new Map();
-
-createServer(async (req, res) => {
- const path = decodeURIComponent(new URL(req.url, "http://x").pathname);
- const file = normalize(join(root, path));
- if (!file.startsWith(root.endsWith(sep) ? root : root + sep)) { res.writeHead(403); return res.end(); }
- try {
- let body = await readFile(file);
- const headers = { "content-type": types[extname(file)] || "application/octet-stream", "cache-control": "no-store", "cross-origin-opener-policy": "same-origin", "cross-origin-embedder-policy": "require-corp" };
- if (path.endsWith("/in-tab-check/worker.mjs")) headers["content-security-policy"] = "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'none'";
- if (/\bgzip\b/.test(req.headers["accept-encoding"] ?? "") && /\.(wasm|json|mjs)$/.test(file)) {
- if (!zipped.has(file)) zipped.set(file, gzipSync(body, { level: 9 }));
- body = zipped.get(file);
- headers["content-encoding"] = "gzip";
- }
- res.writeHead(200, headers);
- res.end(body);
- } catch { res.writeHead(404); res.end("not found"); }
-}).listen(port, "127.0.0.1", () => console.log(`http://127.0.0.1:${port}/in-tab-check/bench.html`));
diff --git a/v2/in-tab-check/test.mjs b/v2/in-tab-check/test.mjs
deleted file mode 100644
index 08ae703e..00000000
--- a/v2/in-tab-check/test.mjs
+++ /dev/null
@@ -1,189 +0,0 @@
-// node --test v2/in-tab-check/test.mjs
-// Needs dist/lexlean-tab.wasm (bash v2/in-tab-check/build.sh). A missing checker fails these tests; none is skipped.
-import nodeTest from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { load, address, derive } from "./checker.mjs";
-import { open, tree } from "./wasi.mjs";
-import { createClient } from "./client.mjs";
-import { describe, variants } from "./make-manifest.mjs";
-import { compareAll, fromDisk as fromDiskOf, manifest as manifestOf, image, checkerBytes } from "./agree.mjs";
-import { cases } from "../hosted-check/corpus.mjs";
-
-const here = dirname(fileURLToPath(import.meta.url));
-const pack = readFileSync(join(here, "pack.json"));
-const guests = cases().find((c) => c.id === "guests-2").spec;
-
-// Every test runs on both checkers: the full build and the lean one.
-for (const variant of variants) {
-const wasm = checkerBytes(variant), manifest = () => manifestOf(variant);
-const fromDisk = (options = {}) => fromDiskOf({ variant, ...options });
-const checker = await fromDisk();
-const test = (name, fn) => nodeTest(`${variant ? "lean" : "full"}: ${name}`, fn);
-
-test("checker.json describes the built checker, the pack, the patch, the wrapper and the build script", () => {
- assert.deepEqual(describe(variant), manifest());
-});
-
-test("the lock it writes is byte for byte the lock the image wrote for the same project", () => {
- const c = cases().find((x) => x.id === "payment");
- assert.equal(checker.lock(c.spec, { extras: c.extras }), readFileSync(join(here, "..", "probe-payment", "lexlean.lock"), "utf8"));
-});
-
-test("the manifest's LexLean is the SDK image's, and the checker reports the same", () => {
- const said = image().version;
- assert.equal(manifest().image, image().image);
- // The image is the one the repository's SDK lock selects: when the SDK moves, this fails until the checker is rebuilt.
- assert.equal(manifest().image, readFileSync(join(here, "..", "..", "prismpm.lock"), "utf8").match(/"sdk_image":"([^"]+)"/)[1]);
- assert.equal(`lexlean ${checker.by.lexlean}`, said.split("\n")[0]);
- assert.equal(`compiler-semantics ${checker.by.semantics}`, said.split("\n")[2]);
-});
-
-test("the pack's library and lexicon are the files the image was run on", () => {
- const files = JSON.parse(pack).files;
- for (const line of image().library) {
- const [same, name] = line.split(" ");
- assert.equal(same, "same");
- if (name !== "prism.arch") assert.equal(files[`src/${name}`], readFileSync(join(here, "..", "probe-payment", "src", name), "utf8"));
- }
- assert.equal(Object.keys(files).filter((p) => p.startsWith("language/prism.arch/entries/")).length, 141);
-});
-
-test("the module imports the 25 file-system calls and nothing else", () => {
- const imports = WebAssembly.Module.imports(new WebAssembly.Module(wasm));
- assert.ok(imports.every((i) => i.module === "wasi_snapshot_preview1" && i.kind === "function"));
- assert.ok(!imports.some((i) => /^sock_|^poll_/.test(i.name)), "no socket or poll call");
- assert.deepEqual(WebAssembly.Module.exports(new WebAssembly.Module(wasm)).filter((e) => e.kind === "function").map((e) => e.name).sort(), ["data", "run", "warm"]);
-});
-
-test("the library alone passes `check --all`, so naming only the author's modules leaves nothing unchecked", () => {
- const r = checker.library();
- assert.equal(r.success, true);
- assert.deepEqual(r.modules, image().library.filter((l) => l.endsWith(".lex.tex")).map((l) => l.split(" ")[1].replace(".lex.tex", "").split("/").join(".")).sort());
-});
-
-for (const scope of ["author", "all"]) test(`verdict, codes, messages, lines and columns equal the image's on every corpus file (scope ${scope})`, async () => {
- const rows = await compareAll(checker, scope);
- assert.equal(rows.length, 17);
- assert.deepEqual(Object.keys(image().cases).sort(), rows.map((r) => r.id).sort());
- for (const r of rows) {
- assert.ok(r.verdictAgrees, `${r.id}: image ${r.image}, tab ${r.tab}`);
- assert.ok(r.identical, `${r.id}: ${JSON.stringify(r.differences)}`);
- }
- assert.ok(rows.some((r) => r.image) && rows.some((r) => !r.image), "the corpus holds both verdicts");
-});
-
-test("a second checker gives the same bytes for every result: nothing depends on the instance or the clock", async () => {
- const other = await fromDisk();
- for (const c of cases()) {
- const a = await checker.check(c.spec, { extras: c.extras }), b = await other.check(c.spec, { extras: c.extras });
- assert.equal(b.cached, false);
- assert.equal(JSON.stringify({ ok: a.ok, d: a.diagnostics, data: a.data }), JSON.stringify({ ok: b.ok, d: b.diagnostics, data: b.data }), c.id);
- }
-});
-
-test("the data form is LexLean's and equals the one the hosted service gave for the same module", async () => {
- const c = cases().find((x) => x.id === "payment");
- const r = await checker.check(c.spec, { extras: c.extras });
- for (const name of ["Payment", "PaymentApproval"]) {
- const kept = JSON.parse(readFileSync(join(here, "..", "probe-payment", "data", `${name}.json`), "utf8"));
- assert.deepEqual(r.data[name], kept, name);
- }
- const kept = JSON.parse(readFileSync(join(here, "..", "probe-payment", "data", "Foundation", "Bytes.json"), "utf8"));
- assert.deepEqual(checker.libraryData("Foundation.Bytes"), kept);
-});
-
-test("bytes that are not the manifest's are refused before they run", async () => {
- const bad = Buffer.from(wasm);
- bad[bad.length - 1] ^= 1;
- await assert.rejects(load({ wasm: bad, pack, manifest: manifest() }), { code: "ITC_ADDRESS" });
- await assert.rejects(load({ wasm, pack: Buffer.concat([pack, Buffer.from(" ")]), manifest: manifest() }), { code: "ITC_ADDRESS" });
-});
-
-test("a checker that reports another LexLean is refused even when its address is the manifest's", async () => {
- const other = { ...manifest(), lexlean: { version: "0.4.0", semantics: manifest().lexlean.semantics } };
- await assert.rejects(load({ wasm, pack, manifest: other }), { code: "ITC_VERSION" });
- const semantics = { ...manifest(), lexlean: { version: manifest().lexlean.version, semantics: "0".repeat(64) } };
- await assert.rejects(load({ wasm, pack, manifest: semantics }), { code: "ITC_VERSION" });
-});
-
-test("a module that asks for a call the host does not give is refused by name", () => {
- // (module (import "env" "fetch" (func)))
- const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 2, 13, 1, 3, 101, 110, 118, 5, 102, 101, 116, 99, 104, 0, 0]);
- assert.throws(() => open(new WebAssembly.Module(bytes)), { code: "ITC_IMPORT" });
-});
-
-test("a result is reused only under the address of everything that made it, and a stored one is verified on read", async () => {
- const kept = new Map();
- const store = { get: async (k) => kept.get(k), put: async (k, v) => { kept.set(k, v); } };
- const first = await fromDisk({ store });
- const a = await first.check(guests);
- assert.equal(a.cached, false);
- assert.equal((await first.check(guests)).cached, "memory");
- const second = await fromDisk({ store });
- const b = await second.check(guests);
- assert.equal(b.cached, "store");
- assert.deepEqual(b.diagnostics, a.diagnostics);
- assert.equal((await second.check(guests + "\n")).cached, false, "one more byte is another address");
- // A stored verdict turned from refused to accepted does not hash to what was recorded, so it is not believed.
- const broken = cases().find((c) => c.id === "broken/wrong-type").spec;
- const third = await fromDisk({ store });
- const refused = await third.check(broken);
- assert.equal(refused.ok, false);
- const entry = JSON.parse(kept.get(refused.key));
- entry.value = JSON.stringify({ ok: true, exit: 0, diagnostics: [], data: {} });
- kept.set(refused.key, JSON.stringify(entry));
- const fourth = await fromDisk({ store });
- const again = await fourth.check(broken);
- assert.equal(again.cached, false);
- assert.equal(again.ok, false);
- // An entry filed under another key is not believed either.
- kept.set(a.key, kept.get(refused.key));
- assert.equal((await (await fromDisk({ store })).check(guests)).ok, true);
-});
-
-test("addresses are Hologram labels on the sha256 axis, and a derived address frames its parts", async () => {
- assert.equal(await address("abc"), "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
- assert.notEqual(await derive("d", ["ab", "c"]), await derive("d", ["a", "bc"]));
- assert.notEqual(await derive("d", ["ab"]), await derive("d", ["a", "b"]));
-});
-
-test("a trap ends the instance and the next check gets a new one", async () => {
- const instance = open(new WebAssembly.Module(wasm));
- // A descriptor the host never gave: the host answers with an error, LexLean reports it, nothing traps.
- const r = instance.call("run", { args: ["lexlean", "--project", "/absent/lexlean.toml", "--diagnostic-format", "json", "check", "--all"], root: tree({}) });
- assert.equal(JSON.parse(r.stdout).success, false);
- assert.equal(r.trap, null);
- assert.equal((await checker.check(guests)).ok, true);
-});
-
-test("the client answers in the tab when ready, through the hosted route while loading, and says which", async () => {
- const worker = () => {
- const w = { onmessage: null, postMessage: (m) => w.handle(m).catch((e) => w.onmessage({ data: { id: m.id, error: { code: e.code, message: e.message } } })), handle: async (m) => {
- if (m.type === "load") { w.checker = await load({ wasm: m.wasm, pack: m.pack, manifest: m.manifest }); w.onmessage({ data: { id: m.id, by: w.checker.by, loadMs: w.checker.loadMs } }); }
- else if (m.type === "warm") w.onmessage({ data: { id: m.id, ms: w.checker.warm() } });
- else w.onmessage({ data: { id: m.id, result: await w.checker.check(m.spec, { extras: m.extras }) } });
- } };
- return w;
- };
- const bytesOf = async (name) => (name === "checker" ? wasm : pack);
- let hostedCalls = 0;
- const hosted = async () => { hostedCalls++; return { ok: true, diagnostics: [] }; };
- const client = createClient({ makeWorker: worker, manifest: manifest(), bytesOf, hosted });
- const early = await client.check(guests);
- assert.equal(early.by.route, "hosted");
- assert.equal(early.by.instead.code, "ITC_NOT_LOADED");
- await client.start();
- const later = await client.check(guests);
- assert.equal(later.by.route, "in-tab");
- assert.equal(later.by.checker, manifest().checker);
- assert.equal(hostedCalls, 1);
- // With bytes that are not the manifest's the tab's checker never becomes ready, and the answer says so.
- const wrong = createClient({ makeWorker: worker, manifest: manifest(), bytesOf: async () => pack, hosted });
- await assert.rejects(wrong.start(), { code: "ITC_ADDRESS" });
- assert.equal((await wrong.check(guests)).by.instead.code, "ITC_UNAVAILABLE");
- await assert.rejects(wrong.check(guests, { only: "in-tab" }), { code: "ITC_ADDRESS" });
-});
-}
diff --git a/v2/in-tab-check/wasi.mjs b/v2/in-tab-check/wasi.mjs
deleted file mode 100644
index c3efcd56..00000000
--- a/v2/in-tab-check/wasi.mjs
+++ /dev/null
@@ -1,278 +0,0 @@
-// A WASI preview 1 host over a file system held in memory. It gives a WebAssembly module the 25 calls LexLean's
-// binary imports and nothing else: no network, no clock beyond a counter, no host file. Each call gets its own file
-// tree, descriptors and output; the instance is kept, so what LexLean computes once per process is computed once.
-// Runs unchanged in a worker and in Node.
-
-const E = { ok: 0, badf: 8, exist: 20, inval: 28, isdir: 31, noent: 44, nosys: 52, notdir: 54, notempty: 55, notsup: 58 };
-const DIR = 3, FILE = 4, CHAR = 2;
-const enc = new TextEncoder(), dec = new TextDecoder();
-
-class Exit extends Error { constructor(code) { super(`exit ${code}`); this.code = code; } }
-
-let serial = 1;
-const dir = () => ({ ino: serial++, entries: new Map() });
-const file = (data = new Uint8Array(0)) => ({ ino: serial++, data, size: data.length });
-
-// files: Map or object of absolute path -> Uint8Array | string. Returns the root directory node.
-export function tree(files) {
- const root = dir();
- for (const [path, value] of files instanceof Map ? files : Object.entries(files)) {
- const parts = path.split("/").filter(Boolean);
- let at = root;
- for (const name of parts.slice(0, -1)) {
- if (!at.entries.has(name)) at.entries.set(name, dir());
- at = at.entries.get(name);
- }
- at.entries.set(parts.at(-1), file(typeof value === "string" ? enc.encode(value) : value));
- }
- return root;
-}
-
-// Every regular file under a node, as path -> bytes.
-export function listing(node, prefix = "", out = new Map()) {
- for (const [name, child] of node.entries) {
- if (child.entries) listing(child, `${prefix}/${name}`, out);
- else out.set(`${prefix}/${name}`, child.data.subarray(0, child.size));
- }
- return out;
-}
-
-// Instantiates a compiled module. Returns { call(name, { args, root }), memoryBytes() }; call returns
-// { code, trap, stdout, stderr, root, calls }. A module with `_start` is a command: call("_start") runs it once.
-export function open(module) {
- let memory;
- const view = () => new DataView(memory.buffer);
- const bytes = () => new Uint8Array(memory.buffer);
- let out, fds, nextFd, tick, seed, calls, argv, envp, stdin;
- const begin = ({ args = [], env = {}, root = dir(), input = new Uint8Array(0) }) => {
- out = { 1: [], 2: [] };
- fds = new Map([[0, { stdin: 0 }], [1, { out: 1 }], [2, { out: 2 }], [3, { node: root }]]);
- nextFd = 4; tick = 0n; seed = 0x9e3779b9; calls = {}; stdin = input;
- argv = strings(args); envp = strings(Object.entries(env).map(([k, v]) => `${k}=${v}`));
- return root;
- };
-
- const text = (ptr, len) => dec.decode(bytes().subarray(ptr, ptr + len));
- // Resolves a path below a directory handle. Returns { parent, name, node } or an error number.
- const resolve = (fd, ptr, len) => {
- const base = fds.get(fd);
- if (!base?.node) return E.badf;
- if (!base.node.entries) return E.notdir;
- const stack = [base.node];
- const parts = text(ptr, len).split("/").filter((p) => p && p !== ".");
- if (!parts.length) return { parent: null, name: "", node: base.node };
- for (let i = 0; i < parts.length; i++) {
- const top = stack.at(-1);
- if (parts[i] === "..") { if (stack.length === 1) return E.noent; stack.pop(); continue; }
- if (!top.entries) return E.notdir;
- if (i === parts.length - 1) return { parent: top, name: parts[i], node: top.entries.get(parts[i]) };
- const next = top.entries.get(parts[i]);
- if (!next) return E.noent;
- stack.push(next);
- }
- return { parent: null, name: "", node: stack.at(-1) };
- };
- const stat = (ptr, node) => {
- const v = view();
- for (let i = 0; i < 64; i += 8) v.setBigUint64(ptr + i, 0n, true);
- v.setBigUint64(ptr + 8, BigInt(node.ino ?? 0), true);
- v.setUint8(ptr + 16, node.entries ? DIR : node.data ? FILE : CHAR);
- v.setBigUint64(ptr + 24, 1n, true);
- v.setBigUint64(ptr + 32, BigInt(node.size ?? 0), true);
- };
- const iovecs = (ptr, count) => {
- const v = view(), list = [];
- for (let i = 0; i < count; i++) list.push([v.getUint32(ptr + 8 * i, true), v.getUint32(ptr + 8 * i + 4, true)]);
- return list;
- };
- const strings = (list) => list.map((s) => enc.encode(s + "\0"));
- const sizes = (get) => (countPtr, sizePtr) => {
- const v = view(), list = get();
- v.setUint32(countPtr, list.length, true);
- v.setUint32(sizePtr, list.reduce((n, s) => n + s.length, 0), true);
- return E.ok;
- };
- const fill = (get) => (tablePtr, bufPtr) => {
- for (const s of get()) { view().setUint32(tablePtr, bufPtr, true); bytes().set(s, bufPtr); tablePtr += 4; bufPtr += s.length; }
- return E.ok;
- };
-
- const wasi = {
- args_sizes_get: sizes(() => argv), args_get: fill(() => argv),
- environ_sizes_get: sizes(() => envp), environ_get: fill(() => envp),
- // Time is a counter: a check must not depend on when it ran, and a worker without a clock cannot time anything else.
- clock_time_get: (_id, _precision, ptr) => { tick += 1000000n; view().setBigUint64(ptr, tick, true); return E.ok; },
- // A fixed sequence, so hash-map order and temporary names repeat exactly from run to run.
- random_get: (ptr, len) => {
- const b = bytes();
- for (let i = 0; i < len; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; b[ptr + i] = seed & 255; }
- return E.ok;
- },
- sched_yield: () => E.ok,
- proc_exit: (code) => { throw new Exit(code); },
- fd_close: (fd) => (fds.delete(fd) ? E.ok : E.badf),
- fd_sync: (fd) => (fds.has(fd) ? E.ok : E.badf),
- fd_fdstat_get: (fd, ptr) => {
- const h = fds.get(fd);
- if (!h) return E.badf;
- const v = view();
- v.setUint8(ptr, h.node ? (h.node.entries ? DIR : FILE) : CHAR);
- v.setUint16(ptr + 2, h.append ? 1 : 0, true);
- v.setBigUint64(ptr + 8, 0xffffffffffffffffn, true);
- v.setBigUint64(ptr + 16, 0xffffffffffffffffn, true);
- return E.ok;
- },
- fd_filestat_get: (fd, ptr) => { const h = fds.get(fd); if (!h) return E.badf; stat(ptr, h.node ?? {}); return E.ok; },
- fd_prestat_get: (fd, ptr) => {
- if (fd !== 3) return E.badf;
- view().setUint8(ptr, 0); view().setUint32(ptr + 4, 1, true);
- return E.ok;
- },
- fd_prestat_dir_name: (fd, ptr) => { if (fd !== 3) return E.badf; bytes()[ptr] = 47; return E.ok; },
- fd_read: (fd, iovs, count, donePtr) => {
- const h = fds.get(fd);
- if (!h) return E.badf;
- if (h.node?.entries) return E.isdir;
- const source = h.node ? h.node.data.subarray(0, h.node.size) : h.stdin !== undefined ? stdin : null;
- if (!source) return E.badf;
- let done = 0, at = h.node ? h.at : h.stdin;
- for (const [ptr, len] of iovecs(iovs, count)) {
- const piece = source.subarray(at, at + len);
- bytes().set(piece, ptr);
- at += piece.length; done += piece.length;
- if (piece.length < len) break;
- }
- if (h.node) h.at = at; else h.stdin = at;
- view().setUint32(donePtr, done, true);
- return E.ok;
- },
- fd_write: (fd, iovs, count, donePtr) => {
- const h = fds.get(fd);
- if (!h) return E.badf;
- let done = 0;
- for (const [ptr, len] of iovecs(iovs, count)) {
- const piece = bytes().slice(ptr, ptr + len);
- if (h.out) out[h.out].push(piece);
- else if (h.node?.data) {
- const node = h.node, at = h.append ? node.size : h.at;
- if (at + len > node.data.length) { const grown = new Uint8Array(Math.max(2 * node.data.length, at + len, 256)); grown.set(node.data.subarray(0, node.size)); node.data = grown; }
- node.data.set(piece, at);
- node.size = Math.max(node.size, at + len);
- h.at = at + len;
- } else return E.badf;
- done += len;
- }
- view().setUint32(donePtr, done, true);
- return E.ok;
- },
- fd_readdir: (fd, buf, bufLen, cookie, usedPtr) => {
- const h = fds.get(fd);
- if (!h?.node?.entries) return E.badf;
- const names = [...h.node.entries.keys()].sort();
- let used = 0;
- for (let i = Number(cookie); i < names.length && used < bufLen; i++) {
- const child = h.node.entries.get(names[i]), name = enc.encode(names[i]);
- const entry = new Uint8Array(24 + name.length), v = new DataView(entry.buffer);
- v.setBigUint64(0, BigInt(i + 1), true);
- v.setBigUint64(8, BigInt(child.ino), true);
- v.setUint32(16, name.length, true);
- v.setUint8(20, child.entries ? DIR : FILE);
- entry.set(name, 24);
- const take = Math.min(entry.length, bufLen - used);
- bytes().set(entry.subarray(0, take), buf + used);
- used += take;
- }
- view().setUint32(usedPtr, used, true);
- return E.ok;
- },
- path_filestat_get: (fd, _flags, ptr, len, statPtr) => {
- const r = resolve(fd, ptr, len);
- if (typeof r === "number") return r;
- if (!r.node) return E.noent;
- stat(statPtr, r.node);
- return E.ok;
- },
- path_open: (fd, _dirflags, ptr, len, oflags, _rights, _inheriting, fdflags, fdPtr) => {
- const r = resolve(fd, ptr, len);
- if (typeof r === "number") return r;
- let node = r.node;
- if (node && (oflags & 1) && (oflags & 4)) return E.exist;
- if (!node) {
- if (!(oflags & 1) || !r.parent) return E.noent;
- node = file();
- r.parent.entries.set(r.name, node);
- }
- if ((oflags & 2) && !node.entries) return E.notdir;
- if ((oflags & 8) && node.data) node.size = 0;
- fds.set(nextFd, { node, at: 0, append: !!(fdflags & 1) });
- view().setUint32(fdPtr, nextFd++, true);
- return E.ok;
- },
- path_create_directory: (fd, ptr, len) => {
- const r = resolve(fd, ptr, len);
- if (typeof r === "number") return r;
- if (r.node) return E.exist;
- if (!r.parent) return E.noent;
- r.parent.entries.set(r.name, dir());
- return E.ok;
- },
- path_unlink_file: (fd, ptr, len) => {
- const r = resolve(fd, ptr, len);
- if (typeof r === "number") return r;
- if (!r.node) return E.noent;
- if (r.node.entries) return E.isdir;
- r.parent.entries.delete(r.name);
- return E.ok;
- },
- path_remove_directory: (fd, ptr, len) => {
- const r = resolve(fd, ptr, len);
- if (typeof r === "number") return r;
- if (!r.node) return E.noent;
- if (!r.node.entries) return E.notdir;
- if (r.node.entries.size) return E.notempty;
- if (!r.parent) return E.inval;
- r.parent.entries.delete(r.name);
- return E.ok;
- },
- path_rename: (fd, ptr, len, toFd, toPtr, toLen) => {
- const from = resolve(fd, ptr, len), to = resolve(toFd, toPtr, toLen);
- if (typeof from === "number") return from;
- if (typeof to === "number") return to;
- if (!from.node) return E.noent;
- if (!from.parent || !to.parent) return E.inval;
- if (to.node?.entries?.size) return E.notempty;
- from.parent.entries.delete(from.name);
- to.parent.entries.set(to.name, from.node);
- return E.ok;
- },
- // This file system has no symbolic or hard links: nothing is one, and none can be made.
- path_readlink: (fd, ptr, len) => { const r = resolve(fd, ptr, len); return typeof r === "number" ? r : r.node ? E.inval : E.noent; },
- path_link: () => E.notsup,
- };
- const counted = Object.fromEntries(Object.entries(wasi).map(([name, fn]) => [name, (...a) => { calls[name] = (calls[name] ?? 0) + 1; return fn(...a); }]));
- // A module that asks for a call not listed here is refused at instantiation, by name.
- for (const want of WebAssembly.Module.imports(module)) {
- if (want.module !== "wasi_snapshot_preview1" || !(want.name in wasi)) throw Object.assign(new Error(`the module imports ${want.module}.${want.name}, which this host does not provide`), { code: "ITC_IMPORT" });
- }
- begin({});
- const instance = new WebAssembly.Instance(module, { wasi_snapshot_preview1: counted });
- memory = instance.exports.memory;
- instance.exports._initialize?.();
- const join = (parts) => { const all = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of parts) { all.set(p, at); at += p.length; } return dec.decode(all); };
- let dead = null;
- return {
- memoryBytes: () => memory.buffer.byteLength,
- call(name, options = {}) {
- // After a trap the instance's memory is in no known state, so it answers nothing more.
- if (dead) throw Object.assign(new Error(`the instance trapped earlier: ${dead.message}`), { code: "ITC_DEAD" });
- const root = begin(options);
- let code = 0, trap = null;
- try { code = instance.exports[name]() ?? 0; } catch (e) { if (e instanceof Exit) code = e.code; else { trap = dead = e; code = -1; } }
- if (name === "_start") dead ??= new Error("a command runs once");
- return { code, trap, stdout: join(out[1]), stderr: join(out[2]), root, calls };
- },
- };
-}
-
-// Runs a command module once, in a new instance.
-export const run = (module, options) => open(module).call("_start", options);
diff --git a/v2/in-tab-check/worker.mjs b/v2/in-tab-check/worker.mjs
deleted file mode 100644
index 3d7651d6..00000000
--- a/v2/in-tab-check/worker.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-// The checker's worker. It is handed bytes and answers checks; it fetches nothing. The page that starts it serves this
-// file with a policy that forbids every connection, and the WebAssembly module imports no call that could make one.
-import { load } from "./checker.mjs";
-
-let checker = null;
-const failure = (e) => ({ error: { code: e.code ?? "ITC_INTERNAL", message: e.message } });
-
-self.onmessage = async ({ data: m }) => {
- try {
- if (m.type === "load") {
- checker = await load({ wasm: m.wasm, pack: m.pack, manifest: m.manifest });
- self.postMessage({ id: m.id, by: checker.by, loadMs: checker.loadMs });
- } else if (!checker) {
- self.postMessage({ id: m.id, ...failure(Object.assign(new Error("the checker is not loaded"), { code: "ITC_NOT_LOADED" })) });
- } else if (m.type === "warm") {
- self.postMessage({ id: m.id, ms: checker.warm(), memoryBytes: checker.memoryBytes() });
- } else if (m.type === "check") {
- const result = await checker.check(m.spec, { extras: m.extras ?? [] });
- self.postMessage({ id: m.id, result, memoryBytes: checker.memoryBytes() });
- } else if (m.type === "probe") {
- // Evidence for the report: what this worker can reach.
- let network;
- try { await fetch(m.url); network = "reached"; } catch (e) { network = `refused: ${e.message}`; }
- self.postMessage({ id: m.id, network, isolated: self.crossOriginIsolated });
- }
- } catch (e) { self.postMessage({ id: m.id, ...failure(e) }); }
-};