diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..11078b9 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,70 @@ +name: Pages (no proof, no publish) + +# The verify job is the proof checker for the site itself. The deploy job +# needs it, so a broken claim graph cannot reach GitHub Pages: tier +# inflation, a cycle, a JS/Python disagreement, a surviving planted bug, +# or a non-reproducible build all stop publication. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: {} + +concurrency: + group: pages-${{ github.ref }} + cancel-in-progress: false + +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + - name: Python checker, three modes + run: | + python3 -I -B tools/verify.py --write-certificate + python3 -I -O -B tools/verify.py + python3 -I -B -W error tools/verify.py + - name: Certificate on disk matches a fresh one + run: git diff --exit-code -- docs/data/certificate.json + - name: Planted-bug suite (all corruptions must be rejected) + run: python3 -I -B tools/run_mutations.py + - name: JavaScript checker agrees with the Python certificate + run: node --test "test/*.test.mjs" + - name: Deterministic build, twice, byte-identical + run: | + python3 -I -B tools/build.py --verify + cp docs/index.html /tmp/index.first.html + cp docs/data/certificate.json /tmp/certificate.first.json + python3 -I -B tools/build.py --verify + cmp /tmp/index.first.html docs/index.html + cmp /tmp/certificate.first.json docs/data/certificate.json + git diff --exit-code -- docs/index.html docs/data/certificate.json + - uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b # v4 + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && vars.PAGES_ENABLED == 'true' + with: + path: docs + + deploy: + needs: verify + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && vars.PAGES_ENABLED == 'true' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 diff --git a/README.md b/README.md index 13415b0..a199c98 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,53 @@ -repo for the formal verification MDE -a formal verification domain for models to operate within +repo for the formal verification MDE +a formal verification domain for models to operate within goal is to have them apply concepts to unlock scientific/mathematic progress, similar to the way it has been done in [f0](https://github.com/Foundation-0) blueprint: [# mcproof](https://github.com/siliconcordat/mde/issues/4) + +## The site is a proof + +The GitHub Pages site in `docs/` is written as a formal derivation. Every +claim on it is one record in `docs/data/claims.json`, with a kind (axiom, +definition, lemma, theorem, obligation, hazard guard), a certainty tier +(`OPEN` to `PROVEN`), its dependencies, and its evidence. Tiers are never +typed into the page by hand. Two checkers that share no code recompute +them from the tier rules in `docs/data/RULES.md`: + +- `tools/verify.py` (Python) writes `docs/data/certificate.json`. +- `docs/assets/proof-core.js` (JavaScript) runs under Node in CI and + again in the visitor's browser, where it rehashes `claims.json` and + compares its verdict with the certificate. + +The main claim, Theorem T0, computes to `CONJECTURE` while obligations +O1 to O5 are open. The checkers cap it there, so the site cannot upgrade +its own headline. The page figure, stats, colours, and background weave +are all deterministic functions of the claim graph and its SHA-256. + +CI is the gate: the Pages workflow runs the Python checker three ways, +rejects planted corruptions of the graph (`tools/run_mutations.py`), +checks the JavaScript checker against the certificate and runs checker +parity tests (`node --test "test/*.test.mjs"`), and builds the page twice +to prove the output is byte-identical. Upload and deploy run only on +`main` when the repository variable `PAGES_ENABLED` is set to `true` +(Settings → Secrets and variables → Actions → Variables); until then +verify still runs on every push but Pages is not published. No proof, no +publish. + +`tools/build.py --verify` rebuilds prerendered regions from +`claims.json`; the workflow's `git diff` step is what catches edits +outside those regions. + +Work on it locally: + +```sh +python3 -I -B tools/build.py --verify # rebuild docs/index.html +python3 -m http.server -d docs 8000 # then open http://localhost:8000 +``` + +Design lineage: the record-keeping discipline and instrument framing of +[Foundation0](https://fdn0.org), and the style-as-a-point design language +of [Eido](https://github.com/Moissanite-Labs/weft-eido) by Moissanite +Labs. The simplex mixer, circular hue blending, and `data-eido-skip` +condense refusal on proof blocks follow Eido's published modules and +guides. diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/docs/404.html b/docs/404.html new file mode 100644 index 0000000..f0c3466 --- /dev/null +++ b/docs/404.html @@ -0,0 +1,26 @@ + + + + + + +Not derivable · mcproof + + + + + +
+ +

This page is not derivable.

+

The address you asked for is not in the claim graph, and this site does not invent pages outside it. In proof notation: ⊥, no derivation exists.

+

Return to the axioms · Read the graph itself

+
+ + diff --git a/docs/assets/favicon.svg b/docs/assets/favicon.svg new file mode 100644 index 0000000..cded7fa --- /dev/null +++ b/docs/assets/favicon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/docs/assets/og.png b/docs/assets/og.png new file mode 100644 index 0000000..651d574 Binary files /dev/null and b/docs/assets/og.png differ diff --git a/docs/assets/proof-core.js b/docs/assets/proof-core.js new file mode 100644 index 0000000..259786e --- /dev/null +++ b/docs/assets/proof-core.js @@ -0,0 +1,190 @@ +/* mcproof proof core: pure functions, no DOM, no clock, no randomness. + Implements docs/data/RULES.md. Tested in Node (test/proof-core.test.mjs) + and run live in the browser by site.js. Input is the parsed claims.json. */ + +export const TIER_RANK = { OPEN: 0, CONJECTURE: 1, KNOWN: 2, VERIFIED: 3, PROVEN: 4 }; +export const KINDS = ["axiom", "definition", "lemma", "theorem", "obligation", "hazard"]; +export const SECTIONS = ["axioms", "definitions", "baseline", "theorem", "obligations", "hazards"]; +/** R2-URL: same rule as tools/verify.py url_ok (docs/data/RULES.md). */ +const HOST_RE = /^[A-Za-z0-9.-]+(:[0-9]+)?$/; +const HTTPS_TAIL_RE = /^(\/[A-Za-z0-9_./:@%?&=-]*)?([?#][A-Za-z0-9_./:@%?&=-]*)?$/; +const REL_URL_RE = /^[A-Za-z0-9_./-]+$/; + +export function urlOk(u) { + if (typeof u !== "string" || !u) return false; + if (u.startsWith("//")) return false; + if (u.startsWith("https://")) { + const rest = u.slice(8); + if (!rest) return false; + let authEnd = rest.length; + for (const sep of ["/", "?", "#"]) { + const i = rest.indexOf(sep); + if (i !== -1) authEnd = Math.min(authEnd, i); + } + const authority = rest.slice(0, authEnd); + if (!authority || !HOST_RE.test(authority)) return false; + const tail = rest.slice(authEnd); + if (tail && !HTTPS_TAIL_RE.test(tail)) return false; + return true; + } + if (u.split("/").includes("..")) return false; + return REL_URL_RE.test(u); +} +const URL_OK = urlOk; +const ASCII_WS = new Set("\t\n\v\f\r "); + +/** R-Text: same rule as tools/verify.py has_text / is_blank_text. */ +export function isBlankText(s) { + if (typeof s !== "string" || s.length === 0) return true; + for (const c of s) { + if (!ASCII_WS.has(c)) return false; + } + return true; +} + +export function hasText(s) { + return typeof s === "string" && !isBlankText(s); +} + +export function checkGraph(doc) { + const errors = []; + const claims = doc && Array.isArray(doc.claims) ? doc.claims : null; + if (!claims || claims.length === 0) return { ok: false, errors: ["claims: missing, not a list, or empty (R1)"], computed: Object.create(null), order: [], openObligations: [] }; + const byId = new Map(); + for (const c of claims) { + if (!c || typeof c.id !== "string" || !c.id) { errors.push("claim with missing id (R1)"); continue; } + if (byId.has(c.id)) errors.push(`${c.id}: duplicate id`); + if (typeof c.kind !== "string" || !KINDS.includes(c.kind)) errors.push(`${c.id}: unknown kind ${JSON.stringify(c.kind)} (R1)`); + if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(c.id)) errors.push(`${c.id}: id must match ^[A-Za-z][A-Za-z0-9_-]*$ (R1)`); + if (!hasText(c.title)) errors.push(`${c.id}: missing title (R1)`); + if (!hasText(c.statement)) errors.push(`${c.id}: missing statement (R1)`); + if (typeof c.section !== "string" || !SECTIONS.includes(c.section)) errors.push(`${c.id}: unknown section ${JSON.stringify(c.section)} (R1)`); + if (typeof c.asserted_tier !== "string" || !Object.hasOwn(TIER_RANK, c.asserted_tier)) errors.push(`${c.id}: unknown tier ${JSON.stringify(c.asserted_tier)} (R1)`); + if (!Array.isArray(c.depends_on)) errors.push(`${c.id}: depends_on is not a list`); + if (Object.hasOwn(c, "evidence") && !Array.isArray(c.evidence)) errors.push(`${c.id}: evidence is not a list (R2)`); + byId.set(c.id, c); + } + for (const c of claims) { + if (!c || typeof c.id !== "string" || !byId.has(c.id)) continue; + for (const d of Array.isArray(c.depends_on) ? c.depends_on : []) { + if (!byId.has(d)) errors.push(`${c.id}: depends on missing claim ${JSON.stringify(d)} (R1)`); + } + if (Object.hasOwn(c, "evidence") && !Array.isArray(c.evidence)) continue; + const ev = Array.isArray(c.evidence) ? c.evidence : []; + for (const e of ev) { + if (!e || typeof e !== "object" || !hasText(e.label) || !URL_OK(e.url)) { + errors.push(`${c.id}: evidence must be {label, https-or-relative url} (R2)`); + } + } + for (const d of Array.isArray(c.depends_on) ? c.depends_on : []) { + if (typeof d !== "string") errors.push(`${c.id}: depends_on entries must be strings (R1)`); + } + if ((c.asserted_tier === "VERIFIED" || c.asserted_tier === "PROVEN") && ev.length === 0) { + errors.push(`${c.id}: asserted ${c.asserted_tier} with no evidence (R2)`); + } + if (c.kind === "obligation" && c.asserted_tier === "OPEN" && ev.length > 0) { + errors.push(`${c.id}: OPEN obligation carries evidence (R2)`); + } + } + // Topological order, deterministic: Kahn with lexicographic tie-break. + const indeg = new Map(), dependents = new Map(); + for (const id of byId.keys()) { indeg.set(id, 0); dependents.set(id, []); } + for (const c of byId.values()) { + for (const d of Array.isArray(c.depends_on) ? c.depends_on : []) { + if (byId.has(d)) { indeg.set(c.id, indeg.get(c.id) + 1); dependents.get(d).push(c.id); } + } + } + const ready = [...byId.keys()].filter((id) => indeg.get(id) === 0).sort(); + const order = []; + while (ready.length) { + const id = ready.shift(); + order.push(id); + for (const nxt of dependents.get(id).slice().sort()) { + indeg.set(nxt, indeg.get(nxt) - 1); + if (indeg.get(nxt) === 0) { ready.push(nxt); ready.sort(); } + } + } + if (order.length !== byId.size) errors.push("dependency graph has a cycle (R1)"); + + const computed = Object.create(null); + for (const id of order) { + const c = byId.get(id); + const tierKey = c.asserted_tier; + const asserted = typeof tierKey === "string" ? TIER_RANK[tierKey] : undefined; + if (asserted === undefined) { computed[id] = "OPEN"; continue; } + let allowed = asserted; + if (c.kind !== "axiom" && c.kind !== "definition") { + const depTiers = (Array.isArray(c.depends_on) ? c.depends_on : []) + .filter((d) => byId.has(d)).map((d) => ({ id: d, tier: computed[d], rank: TIER_RANK[computed[d]] })); + if (depTiers.some((d) => d.rank <= 1)) allowed = Math.min(allowed, 1); + if (tierKey === "PROVEN") { + const weak = depTiers.filter((d) => { + const k = byId.get(d.id).kind; + return !(d.rank >= 3 || k === "axiom" || k === "definition"); + }); + if (weak.length) allowed = Math.min(allowed, 3); + } + } + if (asserted > allowed) { + errors.push(`${id}: asserted ${tierKey} exceeds allowed tier (R3)`); + computed[id] = "OPEN"; + } else { + computed[id] = tierKey; + } + } + const open = order.filter((id) => byId.get(id).kind === "obligation" && computed[id] === "OPEN"); + return { ok: errors.length === 0, errors, computed, order, openObligations: open }; +} + +/* Deterministic layout of the proof DAG: layer = longest path from a root. + Same graph, same coordinates, on every machine. */ +export function layoutGraph(doc, order) { + const byId = new Map(doc.claims.map((c) => [c.id, c])); + const layer = {}; + for (const id of order) { + const deps = (byId.get(id).depends_on || []).filter((d) => byId.has(d)); + layer[id] = deps.length ? Math.max(...deps.map((d) => layer[d])) + 1 : 0; + } + const rows = new Map(); + for (const id of order) { + if (!rows.has(layer[id])) rows.set(layer[id], []); + rows.get(layer[id]).push(id); + } + const pos = {}; + for (const [lv, ids] of rows) ids.forEach((id, i) => { pos[id] = { layer: lv, index: i, rowSize: ids.length }; }); + return { pos, layers: rows.size }; +} + +/* Seeded PRNG (mulberry32) so the decorative weave is a function of the + graph hash, never of the clock. Seed from the first 8 hex chars of a hash. */ +export function seededRand(seedHex) { + let a = parseInt(String(seedHex).slice(0, 8), 16) >>> 0; + if (!Number.isFinite(a)) a = 0; + return function () { + a |= 0; a = (a + 0x6D2B79F5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/* Style as a point in space, after Eido's aesthetic mixer: linear tokens + average linearly, hue averages on the circle so 0.95 and 0.05 stay red. */ +export function mixPresets(presets, weights) { + const out = {}; + let hx = 0, hy = 0, total = 0; + for (const [name, w] of Object.entries(weights)) { + const p = presets[name]; + if (!p || !(w > 0)) continue; + total += w; + for (const [k, v] of Object.entries(p)) { + if (k === "hue") { hx += w * Math.cos(v * 2 * Math.PI); hy += w * Math.sin(v * 2 * Math.PI); } + else out[k] = (out[k] || 0) + w * v; + } + } + if (total === 0) return out; + for (const k of Object.keys(out)) out[k] /= total; + let hue = Math.atan2(hy, hx) / (2 * Math.PI); + out.hue = ((hue % 1) + 1) % 1; + return out; +} diff --git a/docs/assets/site.css b/docs/assets/site.css new file mode 100644 index 0000000..b22b3ad --- /dev/null +++ b/docs/assets/site.css @@ -0,0 +1,227 @@ +/* mcproof. One stylesheet, no build step. + Lineage: Foundation0 (fdn0.org) paper/navy, gold for the human strand, + cyan for the digital; Eido (Moissanite Labs) one OKLCH palette turned by + a single hue. The style point sets --hue (turns), --density, --rounding + and --contrast from docs/assets/site.js. Dark follows the OS unless the + visitor picks a theme. All text/background pairs hold at every hue + because lightness and chroma never move, only the hue angle. */ + +:root { + color-scheme: light; + --hue: 0.55; /* turns; JS overrides from the graph hash */ + --density: 1; /* spacing multiplier */ + --rounding: 0.35; /* 0 square .. 1 round */ + --contrast: 0; /* -0.04 soft .. 0.04 hard, shifts ink lightness */ + --h-angle: calc(var(--hue) * 360deg); + --radius: calc(var(--rounding) * 14px); + --pad: calc(20px * var(--density)); + + --bg: oklch(0.955 0.014 var(--h-angle)); + --bg-1: oklch(0.978 0.009 var(--h-angle)); + --bg-2: oklch(0.925 0.018 var(--h-angle)); + --ink: oklch(calc(0.24 - var(--contrast)) 0.045 var(--h-angle)); + --ink-2: oklch(calc(0.40 - var(--contrast)) 0.035 var(--h-angle)); + --ink-3: oklch(0.52 0.028 var(--h-angle)); + --line: oklch(0.84 0.02 var(--h-angle)); + --acc: oklch(0.48 0.11 var(--h-angle)); /* the digital strand */ + --acc-hi: oklch(0.40 0.11 var(--h-angle)); + --bio: oklch(0.50 0.11 75deg); /* the human strand, gold: never hue-shifted */ + --ok: oklch(0.48 0.12 155deg); + --warn: oklch(0.55 0.13 60deg); + --bad: oklch(0.50 0.17 25deg); + --header-bg: oklch(0.955 0.014 var(--h-angle) / 0.9); + --shadow: 0 18px 40px -28px oklch(0.24 0.045 var(--h-angle) / 0.35); + + --f-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --f-serif: "Iowan Old Style", "Palatino Linotype", Palatino, Charter, Georgia, serif; + --f-mono: ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; + --fs-base: 17px; + --fs-lede: clamp(18px, 1vw + 14px, 21px); + --fs-h2: clamp(26px, 2.4vw + 16px, 38px); + --fs-h1: clamp(34px, 4.2vw + 18px, 58px); + --max: 1180px; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + color-scheme: dark; + --bg: oklch(0.165 0.022 var(--h-angle)); + --bg-1: oklch(0.205 0.024 var(--h-angle)); + --bg-2: oklch(0.25 0.026 var(--h-angle)); + --ink: oklch(calc(0.92 + var(--contrast)) 0.016 var(--h-angle)); + --ink-2: oklch(calc(0.78 + var(--contrast)) 0.02 var(--h-angle)); + --ink-3: oklch(0.64 0.022 var(--h-angle)); + --line: oklch(0.34 0.026 var(--h-angle)); + --acc: oklch(0.78 0.09 var(--h-angle)); + --acc-hi: oklch(0.86 0.08 var(--h-angle)); + --bio: oklch(0.78 0.10 80deg); + --ok: oklch(0.78 0.11 160deg); + --warn: oklch(0.80 0.11 75deg); + --bad: oklch(0.74 0.14 25deg); + --header-bg: oklch(0.165 0.022 var(--h-angle) / 0.9); + --shadow: 0 18px 40px -28px rgb(0 0 0 / 0.7); + } +} +:root[data-theme="dark"] { + color-scheme: dark; + --bg: oklch(0.165 0.022 var(--h-angle)); --bg-1: oklch(0.205 0.024 var(--h-angle)); + --bg-2: oklch(0.25 0.026 var(--h-angle)); + --ink: oklch(calc(0.92 + var(--contrast)) 0.016 var(--h-angle)); + --ink-2: oklch(calc(0.78 + var(--contrast)) 0.02 var(--h-angle)); + --ink-3: oklch(0.64 0.022 var(--h-angle)); --line: oklch(0.34 0.026 var(--h-angle)); + --acc: oklch(0.78 0.09 var(--h-angle)); --acc-hi: oklch(0.86 0.08 var(--h-angle)); + --bio: oklch(0.78 0.10 80deg); --ok: oklch(0.78 0.11 160deg); + --warn: oklch(0.80 0.11 75deg); --bad: oklch(0.74 0.14 25deg); + --header-bg: oklch(0.165 0.022 var(--h-angle) / 0.9); + --shadow: 0 18px 40px -28px rgb(0 0 0 / 0.7); +} + +*, *::before, *::after { box-sizing: border-box; } +html { scroll-behavior: smooth; scroll-padding-top: 84px; -webkit-text-size-adjust: 100%; } +:root[data-motion="off"] { scroll-behavior: auto; } +@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } } +body { + margin: 0; background: var(--bg); color: var(--ink-2); + font: 400 var(--fs-base)/1.62 var(--f-sans); + text-rendering: optimizeLegibility; overflow-x: hidden; +} +.wrap { max-width: var(--max); margin: 0 auto; padding-inline: max(18px, 4vw); } +a { color: var(--acc); text-decoration-color: color-mix(in oklch, var(--acc) 55%, transparent); text-underline-offset: 0.2em; } +a:hover { color: var(--acc-hi); } +:focus-visible { outline: 2px solid var(--bio); outline-offset: 2px; } +::selection { background: color-mix(in oklch, var(--acc) 30%, transparent); } +.skip { position: absolute; left: -9999px; top: 0; background: var(--ink); color: var(--bg); padding: 10px 16px; z-index: 60; } +.skip:focus { left: 8px; top: 8px; } +h1, h2, h3 { color: var(--ink); font-family: var(--f-serif); font-weight: 600; line-height: 1.14; margin: 0; } +h2 { font-size: var(--fs-h2); letter-spacing: -0.01em; } +.lede { font-size: var(--fs-lede); line-height: 1.5; color: var(--ink-2); max-width: 46em; } +.fine { font-size: 13.5px; color: var(--ink-3); } +.turnstile { font-family: var(--f-serif); color: var(--acc); } + +/* header */ +.site-head { position: sticky; top: 0; z-index: 50; background: var(--header-bg); backdrop-filter: blur(10px); border-bottom: 1px solid var(--line); } +.site-head .wrap { display: flex; align-items: center; gap: 18px; min-height: 60px; } +.brand { font: 600 20px var(--f-serif); color: var(--ink); text-decoration: none; display: flex; gap: 8px; align-items: baseline; } +.brand .turnstile { font-size: 22px; } +.nav { display: flex; gap: 16px; margin-left: auto; font-size: 14.5px; } +.nav a { color: var(--ink-2); text-decoration: none; } +.nav a:hover { color: var(--ink); } +.tools { display: flex; gap: 6px; } +.tbtn { + font: 500 13px var(--f-mono); color: var(--ink-2); background: var(--bg-1); + border: 1px solid var(--line); border-radius: calc(var(--radius) * 0.6); + padding: 6px 10px; cursor: pointer; +} +.tbtn:hover { color: var(--ink); border-color: var(--ink-3); } +.tbtn[aria-pressed="true"] { background: var(--ink); color: var(--bg); border-color: var(--ink); } +@media (max-width: 860px) { .nav { display: none; } } + +/* hero */ +.hero { position: relative; padding: calc(var(--pad) * 2.2) 0 calc(var(--pad) * 1.6); overflow: hidden; } +#weave { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0.5; pointer-events: none; } +.hero-grid { position: relative; display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); gap: calc(var(--pad) * 1.8); align-items: start; } +@media (max-width: 960px) { .hero-grid { grid-template-columns: 1fr; } } +.kicker { font: 600 12.5px var(--f-mono); letter-spacing: 0.12em; text-transform: uppercase; color: var(--bio); margin: 0 0 14px; } +.hero h1 { font-size: var(--fs-h1); letter-spacing: -0.015em; } +.cta { display: flex; gap: 10px; flex-wrap: wrap; margin: 22px 0; } +.btn { font: 600 15px var(--f-sans); padding: 10px 18px; border-radius: var(--radius); border: 1px solid var(--line); color: var(--ink); background: var(--bg-1); text-decoration: none; } +.btn.primary { background: var(--ink); color: var(--bg); border-color: var(--ink); } +.btn:hover { border-color: var(--ink-3); } +.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 14px; margin: 26px 0 14px; } +.stats .stat dt { font: 500 11.5px var(--f-mono); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-3); } +.stats .stat dd { margin: 2px 0 0; font: 600 26px var(--f-serif); color: var(--ink); } +.prov { display: flex; gap: 8px; flex-wrap: wrap; } +.chip { font: 500 12px var(--f-mono); color: var(--ink-2); border: 1px solid var(--line); background: var(--bg-1); padding: 4px 9px; border-radius: 999px; text-decoration: none; } +a.chip:hover { color: var(--ink); } +.seal-hash { overflow-wrap: anywhere; } + +/* framed figures, after f0's instrument frames */ +.frame { position: relative; background: var(--bg-1); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); padding: calc(var(--pad) * 1.4) var(--pad) var(--pad); margin: 0; } +.corner { position: absolute; top: 10px; font: 600 11px var(--f-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); } +.corner.tl { left: 14px; } .corner.tr { right: 14px; } +.dag canvas { width: 100%; height: auto; display: block; } +.dag figcaption, .noscript-note { font-size: 13.5px; color: var(--ink-3); margin-top: 10px; line-height: 1.5; } + +/* sections */ +.sec { padding: calc(var(--pad) * 2.4) 0; border-top: 1px solid var(--line); } +.sec.alt { background: var(--bg-1); } +.sec-head { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 12px; } +.sec-label { font: 600 13px var(--f-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-2); margin: 0; } +.sec-label b { color: var(--acc); font-weight: 700; } +.sec-label i { font-style: normal; color: var(--ink-3); margin: 0 7px; } +.sec h2 { margin-bottom: 14px; max-width: 22em; } + +/* verdict panel */ +.verdict { border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg-1); padding: var(--pad); margin: 18px 0 22px; } +.sec.alt .verdict, .sec .verdict { background: var(--bg); } +.verdict-line { font-size: 19px; color: var(--ink); margin: 0 0 8px; } +.qed { font-family: var(--f-serif); font-size: 24px; color: var(--ok); } +.verdict[data-state="fail"] { border-color: var(--bad); } +.verdict[data-state="fail"] .qed { color: var(--bad); } +.verdict-facts { margin: 8px 0; padding-left: 20px; font-size: 15px; } +.verdict-facts .bad-item { color: var(--bad); font-family: var(--f-mono); font-size: 13.5px; } +.verdict-actions { display: flex; gap: 8px; flex-wrap: wrap; margin: 12px 0 0; } + +/* Eido simplex mixer */ +.mixer { display: grid; grid-template-columns: minmax(0, 1fr) 240px; gap: calc(var(--pad) * 1.4); align-items: center; } +@media (max-width: 760px) { .mixer { grid-template-columns: 1fr; } } +.mixer h3 { font-size: 21px; margin-bottom: 8px; } +#simplex { width: 240px; max-width: 100%; justify-self: center; touch-action: none; cursor: pointer; } +#simplex .tri { fill: color-mix(in oklch, var(--acc) 10%, var(--bg-1)); stroke: var(--line); } +#simplex text { font: 600 11px var(--f-mono); fill: var(--ink-3); } +#simplex [data-simplex-dot] { fill: var(--bio); stroke: var(--bg-1); stroke-width: 2; } +.mixer-out { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; font: 500 12.5px var(--f-mono); color: var(--ink-3); } + +/* claims: the proof itself */ +.claims { display: grid; gap: 0; margin-top: 20px; border-top: 1px solid var(--line); } +.claim { padding: calc(var(--pad) * 0.9) 2px; border-bottom: 1px solid var(--line); scroll-margin-top: 84px; } +.claim header { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: center; } +.claim .cid { font: 700 12.5px var(--f-mono); letter-spacing: 0.09em; text-transform: uppercase; color: var(--ink-3); } +.claim[data-kind="theorem"] .cid { color: var(--acc-hi); } +.claim[data-kind="obligation"] .cid { color: var(--bad); } +.claim[data-kind="axiom"] .cid { color: var(--bio); } +.claim h3 { font-size: 20px; margin: 6px 0 6px; } +.claim p { margin: 0 0 8px; max-width: 52em; } +.tier { display: inline-flex; gap: 7px; align-items: center; font: 600 12px var(--f-mono); letter-spacing: 0.07em; text-transform: uppercase; color: var(--ink-2); } +.ladder { display: inline-flex; gap: 2px; } +.ladder i { width: 5px; height: 12px; background: var(--line); border-radius: 1px; } +.ladder[data-r="1"] i:nth-child(-n+1), .ladder[data-r="2"] i:nth-child(-n+2), +.ladder[data-r="4"] i:nth-child(-n+4), .ladder[data-r="5"] i:nth-child(-n+5) { background: var(--acc); } +.claim[data-tier="VERIFIED"] .ladder i, .claim[data-tier="PROVEN"] .ladder i { } +.claim[data-tier="VERIFIED"] .ladder i:nth-child(-n+4) { background: var(--ok); } +.claim[data-tier="CONJECTURE"] .ladder i:nth-child(-n+1) { background: var(--warn); } +.claim[data-tier="OPEN"] .tier { color: var(--bad); } +.deps, .evid { font-size: 13.5px; color: var(--ink-3); } +.deps span, .evid span { font: 600 11px var(--f-mono); letter-spacing: 0.09em; text-transform: uppercase; margin-right: 7px; } +.evid { display: flex; gap: 4px; align-items: baseline; flex-wrap: wrap; } +.evid ul { display: inline; margin: 0; padding: 0; list-style: none; } +.evid li { display: inline; } +.evid li + li::before { content: " · "; color: var(--ink-3); } +.claim:target { background: color-mix(in oklch, var(--acc) 8%, transparent); } +.claim.live-fail { outline: 1px solid var(--bad); outline-offset: -1px; } +.theorem-sec .claim[data-claim="T0"] { border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg-1); padding: var(--pad); margin-bottom: 14px; } + +/* gates table */ +.gates { margin-top: 26px; } +.gates-cap { color: var(--ink-2); margin-bottom: 12px; max-width: 52em; } +.table-wrap { overflow-x: auto; } +table { border-collapse: collapse; width: 100%; font-size: 14.5px; } +th, td { text-align: left; padding: 8px 12px 8px 0; border-bottom: 1px solid var(--line); vertical-align: top; } +th { font: 600 11.5px var(--f-mono); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-3); } +td:first-child { color: var(--ink); font-weight: 600; white-space: nowrap; } + +/* boundary, verify, footer */ +.boundary-grid { display: grid; grid-template-columns: 1fr 1fr; gap: calc(var(--pad) * 2); } +@media (max-width: 820px) { .boundary-grid { grid-template-columns: 1fr; } } +.boundary-list { padding-left: 20px; display: grid; gap: 10px; margin: 14px 0 0; } +.code { background: var(--ink); color: oklch(0.92 0.02 var(--h-angle)); border-radius: var(--radius); padding: 18px; overflow-x: auto; font: 13px/1.7 var(--f-mono); } +.agent-box { border: 1px solid var(--line); border-radius: var(--radius); background: var(--bg-1); padding: var(--pad); margin-top: 24px; max-width: 52em; } +.agent-box .c-k { font: 700 12px var(--f-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--bio); margin: 0 0 8px; } +.ab-prompt { font-family: var(--f-mono); font-size: 13px; background: var(--bg); border: 1px solid var(--line); border-radius: calc(var(--radius) * 0.6); padding: 10px 12px; overflow-wrap: anywhere; } +.site-foot { border-top: 1px solid var(--line); padding: 26px 0 40px; font-size: 14.5px; } +.site-foot p { margin: 4px 0; } + +[data-condensed-note] { font-size: 12.5px; color: var(--bad); font-family: var(--f-mono); } +.claim.condense-refused { animation: none; } +:root[data-motion="on"] .claim.condense-refused { animation: refused 0.45s ease; } +@keyframes refused { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } } +@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } } diff --git a/docs/assets/site.js b/docs/assets/site.js new file mode 100644 index 0000000..24243e7 --- /dev/null +++ b/docs/assets/site.js @@ -0,0 +1,333 @@ +/* mcproof site runtime. Everything visual is a function of data/claims.json: + the verdict, the claim tiers, the DAG figure, the weave, and the first + position of the style point. No clock-based randomness anywhere. */ +import { checkGraph, layoutGraph, mixPresets, seededRand } from "./proof-core.js"; + +const root = document.documentElement; +const $ = (s, el = document) => el.querySelector(s); +const $$ = (s, el = document) => [...el.querySelectorAll(s)]; +const motionOn = () => root.getAttribute("data-motion") !== "off"; + +let DOC = null, CERT = null, LIVE = null; // parsed claims, certificate, live result + +async function sha256Hex(text) { + const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); + return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +function cssVar(name) { + return getComputedStyle(root).getPropertyValue(name).trim(); +} + +/* ---------- the live proof ---------- */ +function renderVerdict(result, hashOk, certOk) { + const box = $("[data-verdict]"), text = $("[data-verdict-text]"), facts = $("[data-verdict-facts]"); + const qed = $("[data-qed]"); + facts.textContent = ""; + const add = (msg, cls) => { const li = document.createElement("li"); li.textContent = msg; if (cls) li.className = cls; facts.append(li); }; + if (result.ok && hashOk && certOk) { + box.dataset.state = "pass"; qed.textContent = "∎"; + text.textContent = "Q.E.D. for this page: the claim graph checks, and it is the graph CI certified."; + add(`${Object.keys(result.computed).length} claims recomputed in this tab; tiers match docs/data/certificate.json claim by claim.`); + add(`claims.json SHA-256 in this tab matches the certificate (${CERT.claims_sha256.slice(0, 16)}…).`); + add(`Open obligations: ${result.openObligations.join(", ")}. Theorem T0 therefore computes to ${result.computed.T0}, and cannot rise until they close.`); + } else { + box.dataset.state = "fail"; qed.textContent = "✗"; + text.textContent = "Proof refused. The checker rejects this graph, and so would CI: this page could not publish in this state."; + for (const e of result.errors) add(e, "bad-item"); + if (!hashOk) add("claims.json hash differs from the certificate.", "bad-item"); + if (!certOk) add("computed tiers differ from the certificate.", "bad-item"); + } + // Mirror computed tiers onto the printed claims. + for (const el of $$("[data-claim]")) { + const t = result.computed[el.dataset.claim]; + el.classList.toggle("live-fail", Boolean(t && el.dataset.tier !== t)); + if (t) el.dataset.tier = t; + } + const foot = $("[data-foot-seal]"); + if (foot) foot.textContent = result.ok && hashOk && certOk + ? `Live check in this tab: pass, graph sha256:${CERT.graph_sha256.slice(0, 16)}….` + : "Live check in this tab: fail, see the proof state panel."; +} + +function runCheck(doc, rawText) { + const result = checkGraph(doc); + LIVE = result; + const done = (hashOk) => { + const certOk = CERT && JSON.stringify( + Object.fromEntries(Object.entries(result.computed).sort())) === + JSON.stringify(Object.fromEntries(Object.entries(CERT.computed_tiers).sort())); + renderVerdict(result, hashOk, certOk); + drawDag(doc, result); + }; + if (rawText && CERT && window.crypto?.subtle) { + sha256Hex(rawText).then((h) => done(h === CERT.claims_sha256)).catch(() => done(false)); + } else { + done(false); // no hash available (tampered copy or insecure context): fail closed (A2) + } + return result; +} + +/* ---------- the Derivation figure ---------- */ +const TIER_COLOR = () => ({ + PROVEN: cssVar("--ok"), VERIFIED: cssVar("--ok"), KNOWN: cssVar("--acc"), + CONJECTURE: cssVar("--warn"), OPEN: cssVar("--bad"), +}); +let dagNodes = []; +function drawDag(doc, result) { + const canvas = $("#dag-canvas"); + if (!canvas || !result.order.length) return; + const { pos, layers } = layoutGraph(doc, result.order); + const byId = new Map(doc.claims.map((c) => [c.id, c])); + const W = 900, H = 640, dpr = Math.min(window.devicePixelRatio || 1, 2); + canvas.width = W * dpr; canvas.height = H * dpr; + canvas.style.aspectRatio = `${W} / ${H}`; + const ctx = canvas.getContext("2d"); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + const colors = TIER_COLOR(), ink = cssVar("--ink"), ink3 = cssVar("--ink-3"), line = cssVar("--line"); + const xy = (id) => { + const p = pos[id]; + return { x: 46 + (W - 92) * (layers <= 1 ? 0 : p.layer / (layers - 1)), + y: 30 + (H - 60) * (p.rowSize <= 1 ? 0.5 : p.index / (p.rowSize - 1)) }; + }; + dagNodes = result.order.map((id) => ({ id, ...xy(id), tier: result.computed[id], title: byId.get(id).title })); + ctx.lineWidth = 1; + for (const c of doc.claims) { + for (const d of c.depends_on || []) { + if (!pos[d] || !pos[c.id]) continue; + const a = xy(d), b = xy(c.id); + ctx.strokeStyle = line; + ctx.beginPath(); + ctx.moveTo(a.x, a.y); + ctx.bezierCurveTo(a.x + 34, a.y, b.x - 34, b.y, b.x, b.y); + ctx.stroke(); + } + } + ctx.font = "600 11px ui-monospace, Menlo, monospace"; + ctx.textAlign = "center"; + dagNodes.forEach((n, i) => { + ctx.beginPath(); + ctx.arc(n.x, n.y, n.id === "T0" ? 13 : 9, 0, Math.PI * 2); + ctx.fillStyle = colors[n.tier] || ink3; + ctx.fill(); + ctx.fillStyle = ink; + // Alternate label side in dense layers so ids never overlap. + const dy = n.id === "T0" ? -19 : (i % 2 === 0 ? -15 : 22); + ctx.fillText(n.id, n.x, n.y + dy); + }); + const out = $("[data-dag-readout]"); + if (out) out.textContent = `${dagNodes.length} claims · ${layers} layers deep`; + canvas.onpointermove = (ev) => { + const r = canvas.getBoundingClientRect(); + const x = (ev.clientX - r.left) * (W / r.width), y = (ev.clientY - r.top) * (H / r.height); + const hit = dagNodes.find((n) => (n.x - x) ** 2 + (n.y - y) ** 2 < 15 ** 2); + canvas.style.cursor = hit ? "pointer" : "default"; + if (out) out.textContent = hit ? `${hit.id} · ${hit.tier} · ${hit.title}` : `${dagNodes.length} claims · ${layers} layers deep`; + canvas.onclick = hit ? () => document.getElementById(`claim-${hit.id}`)?.scrollIntoView({ behavior: motionOn() ? "smooth" : "auto" }) : null; + }; +} + +/* ---------- the weave: harmonics seeded by the graph hash (after Eido's loom) ---------- */ +let weave = null; +function startWeave(seedHex) { + const canvas = $("#weave"); + if (!canvas) return; + const rand = seededRand(seedHex || "0"); + const threads = Array.from({ length: 22 }, (_, i) => ({ + base: i / 21, a1: 4 + rand() * 9, f1: 1.3 + rand() * 2.2, p1: rand() * Math.PI * 2, + a2: 2 + rand() * 5, f2: 3.1 + rand() * 3.4, p2: rand() * Math.PI * 2, + })); + const frame = (t) => { + const r = canvas.parentElement.getBoundingClientRect(); + const dpr = Math.min(window.devicePixelRatio || 1, 2); + if (canvas.width !== Math.round(r.width * dpr)) { canvas.width = r.width * dpr; canvas.height = r.height * dpr; } + const ctx = canvas.getContext("2d"); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, r.width, r.height); + ctx.strokeStyle = cssVar("--acc"); + ctx.globalAlpha = 0.16; + ctx.lineWidth = 1; + for (const th of threads) { + ctx.beginPath(); + for (let x = 0; x <= r.width; x += 6) { + const u = x / r.width; + const y = th.base * r.height + + Math.sin(u * th.f1 * Math.PI * 2 + th.p1 + t) * th.a1 + + Math.sin(u * th.f2 * Math.PI * 2 + th.p2 - t * 0.6) * th.a2; + x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); + } + ctx.stroke(); + } + ctx.globalAlpha = 1; + }; + if (weave) cancelAnimationFrame(weave.raf); + weave = { raf: 0 }; + if (!motionOn()) { frame(0); return; } + const t0 = performance.now(); + const tick = () => { frame((performance.now() - t0) / 2400); weave.raf = requestAnimationFrame(tick); }; + tick(); +} + +/* ---------- style as a point in space (Eido) ---------- */ +const PRESETS = { + formal: { hue: 0.58, density: 0.86, rounding: 0.06, contrast: 0.03 }, + loom: { hue: 0.47, density: 1.04, rounding: 0.5, contrast: 0.0 }, + radiant: { hue: 0.12, density: 1.18, rounding: 0.92, contrast: -0.02 }, +}; +const VERT = { formal: [110, 14], loom: [14, 178], radiant: [206, 178] }; +let proofPoint = { formal: 1 / 3, loom: 1 / 3, radiant: 1 / 3 }; +let point = { ...proofPoint }; + +function applyPoint(w, why) { + point = { ...w }; + const s = mixPresets(PRESETS, w); + root.style.setProperty("--hue", String(s.hue)); + root.style.setProperty("--density", String(s.density)); + root.style.setProperty("--rounding", String(s.rounding)); + root.style.setProperty("--contrast", String(s.contrast)); + const dot = $("[data-simplex-dot]"); + if (dot) { + dot.setAttribute("cx", String(w.formal * VERT.formal[0] + w.loom * VERT.loom[0] + w.radiant * VERT.radiant[0])); + dot.setAttribute("cy", String(w.formal * VERT.formal[1] + w.loom * VERT.loom[1] + w.radiant * VERT.radiant[1])); + } + const label = `Formal ${Math.round(w.formal * 100)}%, Loom ${Math.round(w.loom * 100)}%, Radiant ${Math.round(w.radiant * 100)}%`; + const out = $("[data-mixer-out]"); + if (out) out.textContent = why ? `${label} (${why})` : label; + const sx = $("#simplex"); if (sx) { sx.setAttribute("aria-valuetext", label); sx.setAttribute("aria-valuenow", String(Math.round(w.formal * 100))); } + if (DOC && LIVE) drawDag(DOC, LIVE); +} + +function barycentric(x, y) { + const [ax, ay] = VERT.formal, [bx, by] = VERT.loom, [cx, cy] = VERT.radiant; + const den = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy); + let a = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / den; + let b = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / den; + let c = 1 - a - b; + a = Math.max(0, a); b = Math.max(0, b); c = Math.max(0, c); + const s = a + b + c || 1; + return { formal: a / s, loom: b / s, radiant: c / s }; +} + +function setupSimplex() { + const svg = $("#simplex"); + if (!svg) return; + const move = (ev) => { + const r = svg.getBoundingClientRect(); + applyPoint(barycentric((ev.clientX - r.left) * (220 / r.width), (ev.clientY - r.top) * (200 / r.height)), "your point"); + }; + svg.addEventListener("pointerdown", (ev) => { svg.setPointerCapture(ev.pointerId); move(ev); }); + svg.addEventListener("pointermove", (ev) => { if (ev.buttons) move(ev); }); + svg.addEventListener("keydown", (ev) => { + const step = 0.06, w = { ...point }; + if (ev.key === "ArrowUp") { w.formal += step; w.loom -= step / 2; w.radiant -= step / 2; } + else if (ev.key === "ArrowLeft") { w.loom += step; w.formal -= step / 2; w.radiant -= step / 2; } + else if (ev.key === "ArrowRight") { w.radiant += step; w.formal -= step / 2; w.loom -= step / 2; } + else if (ev.key === "ArrowDown") { w.formal -= step; w.loom += step / 2; w.radiant += step / 2; } + else return; + ev.preventDefault(); + for (const k of Object.keys(w)) w[k] = Math.max(0, w[k]); + const s = w.formal + w.loom + w.radiant || 1; + applyPoint({ formal: w.formal / s, loom: w.loom / s, radiant: w.radiant / s }, "your point"); + }); + $("[data-mixer-reset]")?.addEventListener("click", () => applyPoint(proofPoint, "the proof point, from the graph hash")); +} + +/* ---------- header tools ---------- */ +function setupTools() { + const themeBtn = $("[data-theme-toggle]"); + themeBtn?.addEventListener("click", () => { + const dark = root.getAttribute("data-theme") === "dark" || + (!root.getAttribute("data-theme") && matchMedia("(prefers-color-scheme: dark)").matches); + const next = dark ? "light" : "dark"; + root.setAttribute("data-theme", next); + try { localStorage.setItem("mcproof-theme", next); } catch { /* private mode */ } + if (DOC && LIVE) drawDag(DOC, LIVE); + if (CERT) startWeave(CERT.graph_sha256); + }); + const motionBtn = $("[data-motion-toggle]"); + const syncMotion = () => motionBtn?.setAttribute("aria-pressed", String(motionOn())); + syncMotion(); + motionBtn?.addEventListener("click", () => { + const next = motionOn() ? "off" : "on"; + root.setAttribute("data-motion", next); + root.setAttribute("data-motion-pref", next); + try { localStorage.setItem("mcproof-motion", next); } catch { /* private mode */ } + syncMotion(); + if (CERT) startWeave(CERT.graph_sha256); + }); + // Tamper demo: Hazard-grade corruption, in memory only. + const tamper = $("[data-tamper]"), restore = $("[data-restore]"), note = $("[data-tamper-note]"); + tamper?.addEventListener("click", () => { + const bad = structuredClone(DOC); + bad.claims.find((c) => c.id === "O1").depends_on.push("T0"); + runCheck(bad, null); + tamper.hidden = true; restore.hidden = false; note.hidden = false; + }); + restore?.addEventListener("click", () => { + init(); + tamper.hidden = false; restore.hidden = true; note.hidden = true; + }); + // Copy the agent line. + $$("[data-copy]").forEach((btn) => btn.addEventListener("click", async () => { + const src = document.getElementById(btn.dataset.copy); + const said = btn.parentElement?.querySelector(".ab-said"); + try { await navigator.clipboard.writeText(src.textContent.trim()); if (said) said.textContent = "Copied."; } + catch { if (said) said.textContent = "Copy failed: select the line by hand."; } + })); + setupCondense(); +} + +/* Condense plain prose; refuse proof blocks (Hazard H7, data-eido-skip). */ +function setupCondense() { + const btn = $("[data-condense-toggle]"); + if (!btn) return; + const originals = new Map(); + let condensed = null, on = false; + btn.addEventListener("click", async () => { + if (!condensed) { + try { condensed = await (await fetch("condensed.json")).json(); } + catch { btn.textContent = "Condense (unavailable)"; return; } + } + on = !on; + btn.setAttribute("aria-pressed", String(on)); + for (const el of $$("[data-condense]")) { + if (el.closest("[data-eido-skip]")) continue; + if (!originals.has(el)) originals.set(el, el.innerHTML); + if (on && typeof condensed[el.dataset.condense] === "string") el.textContent = condensed[el.dataset.condense]; + else el.innerHTML = originals.get(el); + } + for (const el of $$("[data-eido-skip]")) { + el.classList.remove("condense-refused"); + if (on) { void el.offsetWidth; el.classList.add("condense-refused"); } + } + btn.textContent = on ? "Condense (proof blocks refused)" : "Condense"; + }); +} + +/* ---------- boot ---------- */ +async function init() { + const text = $("[data-verdict-text]"); + try { + const [claimsRes, certRes] = await Promise.all([fetch("data/claims.json"), fetch("data/certificate.json")]); + const raw = await claimsRes.text(); + DOC = JSON.parse(raw); + CERT = await certRes.json(); + runCheck(DOC, raw); + // The proof point: first three bytes of the graph hash, normalised. + const b = [0, 2, 4].map((i) => parseInt(CERT.graph_sha256.slice(i, i + 2), 16) + 32); + const sum = b[0] + b[1] + b[2]; + proofPoint = { formal: b[0] / sum, loom: b[1] / sum, radiant: b[2] / sum }; + applyPoint(proofPoint, "the proof point, from the graph hash"); + startWeave(CERT.graph_sha256); + } catch (err) { + const box = $("[data-verdict]"); if (box) box.dataset.state = "fail"; + const qed = $("[data-qed]"); if (qed) qed.textContent = "✗"; + if (text) text.textContent = `Proof refused in this tab: could not load the claim graph (${err.name}). The printed claims below were baked at build time, but this tab cannot certify them.`; + } +} +setupSimplex(); +setupTools(); +applyPoint(proofPoint, "loading"); +init(); +let resizeT; +addEventListener("resize", () => { clearTimeout(resizeT); resizeT = setTimeout(() => { if (DOC && LIVE) drawDag(DOC, LIVE); if (CERT) startWeave(CERT.graph_sha256); }, 200); }); diff --git a/docs/condensed.json b/docs/condensed.json new file mode 100644 index 0000000..704ba2b --- /dev/null +++ b/docs/condensed.json @@ -0,0 +1,10 @@ +{ + "lede": "mcproof is a domain where models produce proofs and checkers, judged by deterministic programs. Models propose. They never approve.", + "howto": "This page is a proof: numbered claims, tiers and evidence, recomputed by two independent checkers. Break the graph and the seal turns red.", + "mixer": "Colour comes from Eido: style as a draggable point. Its first position derives from the claim graph hash.", + "axioms": "Four stated commitments. Disagree with them by name.", + "baseline": "Specs, oracles and layers 2 to 5 exist and were run. The end-to-end claim is T0, still a conjecture.", + "obligations": "Five open goals stand between the baseline and T0. While any is open, T0 stays CONJECTURE.", + "hazards": "Seven seams where proof, prose and style could corrupt each other, each with its guard.", + "verify": "Run the gates yourself: two checkers, twelve planted bugs, a byte-identical rebuild. No proof, no publish." +} diff --git a/docs/data/RULES.md b/docs/data/RULES.md new file mode 100644 index 0000000..5b20d3e --- /dev/null +++ b/docs/data/RULES.md @@ -0,0 +1,55 @@ +# Tier rules for the mcproof claim graph + +Both checkers implement exactly these rules and nothing else: +`tools/verify.py` (Python, run in CI) and `docs/assets/proof-core.js` +(JavaScript, run in CI under Node and again in your browser). They share +no code. A disagreement fails the build. Duplicate JSON keys are +rejected when Python loads `claims.json`; the browser's `JSON.parse` +keeps the last value for a repeated key, so CI fails first. + +Tiers, weakest to strongest: `OPEN < CONJECTURE < KNOWN < VERIFIED < PROVEN`. + +- **R1 Shape.** Claim ids are unique and match `^[A-Za-z][A-Za-z0-9_-]*$` + (so `__proto__` and friends can never be ids). Every claim has a + non-empty title, statement, and a known section (**R-Text**). Every + `depends_on` entry is a string naming an existing claim. The list is + non-empty and the dependency graph has no cycle. +- **R2 Evidence.** `evidence`, when present, must be a list. A claim + asserted `VERIFIED` or `PROVEN` carries at least one evidence link. + Every evidence entry is an object with a non-empty label (**R-Text**) and a URL + that passes **R2-URL** (checked with a full-string match, not a prefix): + - `https://` only (not `http://`). After the scheme, the **authority** + (characters before the first `/`, `?`, or `#`, or end) must match + `^[A-Za-z0-9.-]+(:[0-9]+)?$` using ASCII rules only (no Unicode + whitespace or other non-ASCII in the host). Bare `https://` or + `https:///` is invalid. Anything after the authority, if present, + must match + `^(/[A-Za-z0-9_./:@%?&=-]*)?([?#][A-Za-z0-9_./:@%?&=-]*)?$` (ASCII). + - or a non-empty relative path whose entire string matches + `^[A-Za-z0-9_./-]+$` (ASCII), does not start with `//`, does not + use `..` as a path segment, and is not another scheme such as + `javascript:` or `data:`. + An `obligation` asserted `OPEN` carries none. + String fields (`kind`, `asserted_tier`, `section`) must be strings + before they are validated; wrong types fail R1 or R2, never crash. +- **R-Text (shared).** Title, statement, and evidence label count as + blank only if the value is missing, not a string, or every character + is ASCII whitespace: tab, newline, vertical tab, form feed, carriage + return, and space (`\t\n\v\f\r `). Any other character, including + Unicode whitespace or BOM, makes the field non-blank. Do not use + `str.strip`, `isspace`, `\s`, or `trim()` for this test. +- **R3 No tier inflation.** Compute each claim's allowed tier: + - `axiom` and `definition`: allowed equals asserted (they are the + stated trust base, listed under "What you must trust"). + - Any other kind: allowed starts at asserted, then: + - if any dependency computes to `OPEN` or `CONJECTURE`, allowed is + capped at `CONJECTURE`; + - `PROVEN` additionally requires every dependency to compute to + `VERIFIED` or `PROVEN`, or to be an axiom or definition. + - The claim passes only if asserted is no stronger than allowed. +- **R4 Computed tier.** A passing claim's computed tier is its asserted + tier. A failing claim computes to `OPEN` and is reported by name. +- **R5 Certificate.** The certificate records the SHA-256 of the exact + bytes of `claims.json`, each claim's computed tier, and the list of + open obligations. It contains no timestamp, so rebuilding from the + same file gives the same certificate byte for byte. diff --git a/docs/data/certificate.json b/docs/data/certificate.json new file mode 100644 index 0000000..d08eb87 --- /dev/null +++ b/docs/data/certificate.json @@ -0,0 +1,44 @@ +{ + "checker": "tools/verify.py", + "claim_count": 26, + "claims_sha256": "b473432464387ac7a07c7454b826999373b902ebacf6e315335c845ce4d785b8", + "computed_tiers": { + "A1": "KNOWN", + "A2": "KNOWN", + "A3": "KNOWN", + "A4": "KNOWN", + "D1": "KNOWN", + "D2": "KNOWN", + "D3": "KNOWN", + "H1": "KNOWN", + "H2": "KNOWN", + "H3": "KNOWN", + "H4": "KNOWN", + "H5": "KNOWN", + "H6": "KNOWN", + "H7": "KNOWN", + "L1": "VERIFIED", + "L2": "VERIFIED", + "L3": "VERIFIED", + "L4": "VERIFIED", + "L5": "VERIFIED", + "O1": "OPEN", + "O2": "OPEN", + "O3": "OPEN", + "O4": "OPEN", + "O5": "OPEN", + "T0": "CONJECTURE", + "T1": "VERIFIED" + }, + "graph_sha256": "8db78bc6bcc6904281320d851cff6554c1eaeeb91fc961f6a1d45ada9266da3a", + "open_obligations": [ + "O1", + "O2", + "O3", + "O4", + "O5" + ], + "rules": "docs/data/RULES.md", + "schema": "mcproof/certificate/v1", + "verdict": "CHECKED" +} diff --git a/docs/data/claims.json b/docs/data/claims.json new file mode 100644 index 0000000..eab784b --- /dev/null +++ b/docs/data/claims.json @@ -0,0 +1,410 @@ +{ + "schema": "mcproof/claims/v1", + "title": "The mcproof claim graph", + "note": "Every factual claim on the site is one record here. Status is never typed in by hand: tools/verify.py and docs/assets/proof-core.js each recompute it from depends_on and the tier rules in docs/data/RULES.md. If the two disagree, CI fails and the site does not publish.", + "tiers": [ + "OPEN", + "CONJECTURE", + "KNOWN", + "VERIFIED", + "PROVEN" + ], + "claims": [ + { + "id": "A1", + "kind": "axiom", + "section": "axioms", + "title": "Model weights never hold authority", + "statement": "A trained adapter may carry habits. It may never carry the right to approve a spec, admit a proof, or overrule a checker. Approval stays with named people; enforcement stays with programs anyone can rerun.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "Blueprint, three-tier placement", + "url": "https://github.com/siliconcordat/mde/issues/4" + } + ] + }, + { + "id": "A2", + "kind": "axiom", + "section": "axioms", + "title": "When in doubt, refuse", + "statement": "Every gate in the stack fails closed. A stale manifest, a forged certificate, or a contested rule stops the load instead of guessing. A refusal is a valid result; a silent pass is not.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "Blueprint, hard vetoes", + "url": "https://github.com/siliconcordat/mde/issues/4" + } + ] + }, + { + "id": "A3", + "kind": "axiom", + "section": "axioms", + "title": "Exact arithmetic in exact checkers", + "statement": "A checker for exact mathematics uses integers and fractions only. No floating point value may decide whether an exact claim passes, because rounding can turn a false claim true.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "finite-state-proofs verify.py, the reference checker", + "url": "https://github.com/Foundation-0/finite-state-proofs/blob/main/verify.py" + } + ] + }, + { + "id": "A4", + "kind": "axiom", + "section": "axioms", + "title": "Say what is not proved", + "statement": "Every formal write-up states what it does not prove and what a reader must trust without proof. A result with no stated boundary is treated as a claim with no stated scope, and does not pass the bar.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "The verified bar, Proven-Commons/mission", + "url": "https://github.com/Proven-Commons/mission/blob/main/playbook/verified-bar.md" + } + ] + }, + { + "id": "D1", + "kind": "definition", + "section": "definitions", + "title": "A zone is a span of text with one set of rules", + "statement": "A Multi-Domain Editing (MDE) zone marks a span, such as a proof block or a JSON record, and names which rules govern it. Precedence runs formal proof, then condensed JSON, then interface code, then ordinary code, then prose.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "zone-manifest.v0.1.json", + "url": "https://github.com/siliconcordat/mde/blob/main/schemas/zone-manifest.v0.1.json" + } + ] + }, + { + "id": "D2", + "kind": "definition", + "section": "definitions", + "title": "Five words for how sure we are", + "statement": "OPEN means nobody has discharged it yet. CONJECTURE means stated, not proved. KNOWN means established prior work or a stated axiom. VERIFIED means a named checker was run and passed. PROVEN means a proof checker accepted a complete proof with no escape hatches.", + "asserted_tier": "KNOWN", + "depends_on": [], + "evidence": [ + { + "label": "Foundation-0 REPO-STANDARD.md", + "url": "https://github.com/Foundation-0/.github/blob/main/REPO-STANDARD.md" + } + ] + }, + { + "id": "D3", + "kind": "definition", + "section": "definitions", + "title": "A deterministic oracle gives the same answer every run", + "statement": "An oracle here is a program, never a language model, whose verdict on the same input is byte-identical on every run: a Lean build, an auditor script, a schema check. If a verdict can drift between runs, it cannot gate anything.", + "asserted_tier": "KNOWN", + "depends_on": [ + "A3" + ], + "evidence": [ + { + "label": "Blueprint, oracle catalog", + "url": "https://github.com/siliconcordat/mde/issues/4" + } + ] + }, + { + "id": "L1", + "kind": "lemma", + "section": "baseline", + "title": "The source specs and oracles exist and are public", + "statement": "About 32.7k tokens of formal-verification source specs sit in public repositories, with working oracles: the soko auditors, bar/check.py, and f0/scripts/gate.py. The formal-claims-audit ledger holds zero verdicts so far, and its reviewer list is empty.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "D3" + ], + "evidence": [ + { + "label": "soko auditors", + "url": "https://github.com/ahrazzle/soko" + }, + { + "label": "f0 claim gate", + "url": "https://github.com/Foundation-0/f0/blob/main/scripts/gate.py" + }, + { + "label": "18-package Lean v4.35.0 anthology", + "url": "https://github.com/Foundation-0/proven-commons" + } + ] + }, + { + "id": "L2", + "kind": "lemma", + "section": "baseline", + "title": "Layer 5 classifies zones and audits generated code", + "statement": "The mde tool carries a canonical zone manifest (sha256 4e00656c...) and a native guard that rejects bare asserts, silent exception swallows, and duplicate JSON keys in generated verifiers.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "D1", + "D3" + ], + "evidence": [ + { + "label": "siliconcordat/mde at 52ce0178", + "url": "https://github.com/siliconcordat/mde/commit/52ce0178854a67490eb718544961ba6cff710f22" + } + ] + }, + { + "id": "L3", + "kind": "lemma", + "section": "baseline", + "title": "Layer 4 routes proof spans to the proof adapter only", + "statement": "The exo router sends a formal_proof span to the formal-verification adapter at weight 1.0 and to the prose and style packs at 0.0. Unit tests cover all seven cross-domain interference rules.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "D1" + ], + "evidence": [ + { + "label": "siliconcordat/exo at 9d52aa1f", + "url": "https://github.com/siliconcordat/exo/commit/9d52aa1f28272753ddf83dbe02864d05989b74d2" + } + ] + }, + { + "id": "L4", + "kind": "lemma", + "section": "baseline", + "title": "Layer 3 loads adapters through four fail-closed stages", + "statement": "The warp-modeld daemon checks binding, an integer certificate, a shadow load with verifier-owned canaries, and a constant-time kill switch, in that order. It was live-verified against llama-server with 54 of 54 tests passing.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "A2", + "D3" + ], + "evidence": [ + { + "label": "siliconcordat/warp at 28f56549", + "url": "https://github.com/siliconcordat/warp/commit/28f56549a8bb59b723281afa31831df0824e7dec" + } + ] + }, + { + "id": "L5", + "kind": "lemma", + "section": "baseline", + "title": "Layer 2 compiles adapters you can rebuild byte for byte", + "statement": "The weft compiler solves its edit in CPU float64, packs it into a checked container, and certifies the packed result with integer arithmetic. Experiments E1 to E7 cover composition, tamper rejection, packing, and a live server load. The composition runs so far are synthetic.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "A2", + "A3" + ], + "evidence": [ + { + "label": "siliconcordat/weft at 3d66f07e", + "url": "https://github.com/siliconcordat/weft/commit/3d66f07e5ee67863a7e6c1029e7473c9c8c11b08" + } + ] + }, + { + "id": "O1", + "kind": "obligation", + "section": "obligations", + "title": "Freeze a 240-prompt test set with a private holdout", + "statement": "Assemble 240 prompts in four families (Lean proofs, exact checkers, claim-tier traps, mixed-zone documents), split 96 compile, 48 validation, 96 untouched private holdout, and pin every record by SHA-256. Status: open pull requests in this repository (#3, #6) contain a candidate corpus with recomputing sums, but nothing is merged to main and the private split is not in this public repo, so the obligation stays open. Discharge: the frozen manifest merged, with its sums recomputing from a fresh clone.", + "asserted_tier": "OPEN", + "depends_on": [ + "L1" + ], + "evidence": [] + }, + { + "id": "O2", + "kind": "obligation", + "section": "obligations", + "title": "Compile a real 1.7B to 4B adapter and score it live", + "statement": "Build the formal-verification adapter for a real open checkpoint and score it against the Lean compiler and the soko, bar, and f0 oracles, with the bare model and the full-spec prompt as matched arms. Status: pull request #3 reports such runs and a negative result (0 of 96 on the holdout across arms) in committed receipts that this page has not rerun and that are not merged. Discharge: scored runs merged with enough artifacts for an independent rerun.", + "asserted_tier": "OPEN", + "depends_on": [ + "O1", + "L5" + ], + "evidence": [] + }, + { + "id": "O3", + "kind": "obligation", + "section": "obligations", + "title": "Meet the pre-registered pass and kill criteria", + "statement": "Pass means at least 50 percent fewer oracle failures than the bare model on the private holdout, at least 80 percent of the full-spec ceiling, all safety canaries green, and zero corrupted proof blocks. Status: pull request #3 records a kill verdict against its own candidate (REJECTED for negative efficacy), disclosed in its verification report; the obligation therefore stays open for a future candidate, and the negative result stands on the record. Discharge: the scored table merged, published either way, with gates unchanged.", + "asserted_tier": "OPEN", + "depends_on": [ + "O2", + "L4" + ], + "evidence": [] + }, + { + "id": "O4", + "kind": "obligation", + "section": "obligations", + "title": "Compose with prose and style packs without interference", + "statement": "Run the proof adapter beside a prose pack and the Eido style system under gates T-C1 to T-C5: solo gains kept, zones isolated, base ability retained, order-invariant composition, and a serving budget. Discharge: all five gates scored on a real checkpoint.", + "asserted_tier": "OPEN", + "depends_on": [ + "O3", + "L3" + ], + "evidence": [] + }, + { + "id": "O5", + "kind": "obligation", + "section": "obligations", + "title": "Seat the human bar", + "statement": "Name spec reviewers in bar/reviewers.toml and record the first verdicts in formal-claims-audit. Until then the human tier of the system is specified but unstaffed, and no library counts as admitted. Discharge: a non-empty reviewer list and at least one recorded verdict.", + "asserted_tier": "OPEN", + "depends_on": [ + "A1" + ], + "evidence": [] + }, + { + "id": "T0", + "kind": "theorem", + "section": "theorem", + "title": "A model can work inside a formal domain it cannot talk its way out of", + "statement": "A model fitted with the formal-verification adapter, mounted through layers 2 to 5, produces proofs and checkers that pass deterministic oracles at rates the bare model does not reach, while every authority stays outside the weights. This is the claim mcproof exists to test. It is not proved, and this site will not call it proved until O1 to O4 are discharged.", + "asserted_tier": "CONJECTURE", + "depends_on": [ + "L1", + "L2", + "L3", + "L4", + "L5", + "O1", + "O2", + "O3", + "O4" + ], + "evidence": [ + { + "label": "Blueprint issue, siliconcordat/mde#4", + "url": "https://github.com/siliconcordat/mde/issues/4" + } + ] + }, + { + "id": "T1", + "kind": "theorem", + "section": "theorem", + "title": "This page checks its own claims", + "statement": "The claim graph behind this page is acyclic, every tier on it follows the tier rules, and two checkers that share no code (one Python, one JavaScript running in your browser) recompute the same verdict from the same file. The panel below shows the live result. Break the graph with the tamper button and the verdict turns red.", + "asserted_tier": "VERIFIED", + "depends_on": [ + "D2", + "D3" + ], + "evidence": [ + { + "label": "docs/data/certificate.json, generated by tools/verify.py", + "url": "data/certificate.json" + } + ] + }, + { + "id": "H1", + "kind": "hazard", + "section": "hazards", + "title": "A style rule against negative clauses could strip the honesty sections", + "statement": "Guard: inside a formal_proof zone the prose pack weight is 0.0 and negative disclaimers are explicitly allowed, so What is not proved survives every style pass.", + "asserted_tier": "KNOWN", + "depends_on": [ + "A4", + "D1" + ], + "evidence": [] + }, + { + "id": "H2", + "kind": "hazard", + "section": "hazards", + "title": "Readability rules could rewrite axioms and commit hashes", + "statement": "Guard: protect_axioms and protect_sha_digests pin exact identifiers. A 40-character verdict hash is never shortened to please a style rule.", + "asserted_tier": "KNOWN", + "depends_on": [ + "D1" + ], + "evidence": [] + }, + { + "id": "H3", + "kind": "hazard", + "section": "hazards", + "title": "Two vocabularies for certainty could blur into each other", + "statement": "Guard: claim-tier words are locked per repository by policy, outside the weights. Tested and deployed never silently become VERIFIED or PROVEN.", + "asserted_tier": "KNOWN", + "depends_on": [ + "D2" + ], + "evidence": [] + }, + { + "id": "H4", + "kind": "hazard", + "section": "hazards", + "title": "Prose grammar rules could mangle terse machine records", + "statement": "Guard: a condensed_json zone with no formal claims zeroes the prose pack, so grammar rules never reach inside a data record.", + "asserted_tier": "KNOWN", + "depends_on": [ + "D1" + ], + "evidence": [] + }, + { + "id": "H5", + "kind": "hazard", + "section": "hazards", + "title": "Two delivery styles could each claim the same page", + "statement": "Guard: a contested delivery choice fails closed with ContestedPreferenceError until a human-written precedence override names the winner.", + "asserted_tier": "KNOWN", + "depends_on": [ + "A1", + "A2" + ], + "evidence": [] + }, + { + "id": "H6", + "kind": "hazard", + "section": "hazards", + "title": "A floating-point picture could pose as an exact result", + "statement": "Guard: research pages forbid floats inside exact verifiers and require every illustrative figure to carry an illustrative tag and a link to its certificate.", + "asserted_tier": "KNOWN", + "depends_on": [ + "A3" + ], + "evidence": [] + }, + { + "id": "H7", + "kind": "hazard", + "section": "hazards", + "title": "Automatic shortening could cut the hedges off a claim", + "statement": "Guard: condensing refuses any block marked data-eido-skip. On this page the condense switch shortens plain prose and visibly refuses every proof block. Try it in the header.", + "asserted_tier": "KNOWN", + "depends_on": [ + "A4", + "D1" + ], + "evidence": [] + } + ] +} diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..d740a3b --- /dev/null +++ b/docs/index.html @@ -0,0 +1,377 @@ + + + + + +mcproof · a formal domain models cannot talk their way out of + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ mcproof + +
+ + + +
+
+
+ +
+ +
+ +
+
+

Proven Commons · the formal verification MDE

+

A domain a model cannot talk its way out of.

+

mcproof gives AI models a working domain where results are proofs and checkers, judged by programs that give the same answer every run. A model may propose. It may never approve its own work. The goal is the one Foundation-0 set: put models to work on open science and mathematics, with every step on the record and checkable.

+

This page is written as a proof. Each claim below is a numbered record with a kind (axiom, lemma, obligation), a certainty tier, the claims it uses, and its evidence. Nothing here is labelled by hand: two checkers that share no code recompute every tier from one data file, once in CI before this page could publish, and once in your browser as you read. If the graph breaks, the seal turns red.

+ +
claims in the graph
26
verified lemmas (the baseline)
5
open obligations
5
main theorem T0
Conjecture
+
+ live from data/claims.json + certificate.json + claims sha256:b473432464387ac7… graph sha256:8db78bc6bcc69042… +
+
+ +
+ The Derivation // claim graph + drawn from claims.json + +
One node per claim on this page, one edge per “uses”. Position is computed from the graph alone, so the figure is identical on every visit. Colour is the computed tier: green verified, plain known, amber conjecture, red still open. Point at a node to find its claim below.
+ +
+
+
+ +
+
+

⊢//Proof state of this page

recomputed in your browser
+

Checked as you read.

+
+

∎ Reading data/claims.json and recomputing every tier…

+
    +

    + + +

    + +
    +
    +
    +

    Style is a point, and the point is pinned to the proof

    +

    The page takes its colour from Eido, the design language of ML Weft, where a style is a point in a continuous space rather than a fixed theme. Drag the point in the triangle: Formal, Loom, and Radiant blend with barycentric weights, and hue blends on the circle so red plus red never turns cyan. On load, the point sits where the claim graph puts it: its first position is derived from the graph hash, so the page looks the way its own proof says it should. Moving it is yours to do, and yours to undo with the reset.

    +

    weights derive from the graph hash on load +

    +
    + + + Formal + Loom + Radiant + + +
    +
    +
    + +
    +
    +

    00//Axioms

    the trust base, stated not proved
    +

    Four rules everything else stands on.

    +

    An axiom here is a design commitment, not a discovered fact. Each one is listed so a reader can disagree with it by name. The checkers treat axioms as given, and the section What you must trust repeats them without decoration.

    +
    +
    +
    Axiom A1Known
    +

    Model weights never hold authority

    +

    A trained adapter may carry habits. It may never carry the right to approve a spec, admit a proof, or overrule a checker. Approval stays with named people; enforcement stays with programs anyone can rerun.

    +
    +
    +
    Axiom A2Known
    +

    When in doubt, refuse

    +

    Every gate in the stack fails closed. A stale manifest, a forged certificate, or a contested rule stops the load instead of guessing. A refusal is a valid result; a silent pass is not.

    +
    +
    +
    Axiom A3Known
    +

    Exact arithmetic in exact checkers

    +

    A checker for exact mathematics uses integers and fractions only. No floating point value may decide whether an exact claim passes, because rounding can turn a false claim true.

    +
    +
    +
    Axiom A4Known
    +

    Say what is not proved

    +

    Every formal write-up states what it does not prove and what a reader must trust without proof. A result with no stated boundary is treated as a claim with no stated scope, and does not pass the bar.

    +
    +
    +
    +
    + +
    +
    +

    01//Definitions

    +

    Words, pinned down.

    +
    +
    +
    Definition D1Known
    +

    A zone is a span of text with one set of rules

    +

    A Multi-Domain Editing (MDE) zone marks a span, such as a proof block or a JSON record, and names which rules govern it. Precedence runs formal proof, then condensed JSON, then interface code, then ordinary code, then prose.

    +
    +
    +
    Definition D2Known
    +

    Five words for how sure we are

    +

    OPEN means nobody has discharged it yet. CONJECTURE means stated, not proved. KNOWN means established prior work or a stated axiom. VERIFIED means a named checker was run and passed. PROVEN means a proof checker accepted a complete proof with no escape hatches.

    +
    +
    +
    Definition D3Known
    +

    A deterministic oracle gives the same answer every run

    +

    An oracle here is a program, never a language model, whose verdict on the same input is byte-identical on every run: a Lean build, an auditor script, a schema check. If a verdict can drift between runs, it cannot gate anything.

    +

    Uses A3

    +
    +
    +
    + +
    +
    +

    02//Lemmas: the verified baseline

    source: blueprint issue, commits pinned
    +

    What already stands, layer by layer.

    +

    Five pieces exist today and have been run: the source specs with their oracles, and layers 2 to 5 of the stack that compiles, loads, routes, and audits model adapters. Each lemma names its commit. VERIFIED here means the blueprint records a checker run against that artifact; it does not mean the end-to-end claim holds. That claim is T0, and it is still a conjecture.

    +
    +
    +
    Lemma L1Verified
    +

    The source specs and oracles exist and are public

    +

    About 32.7k tokens of formal-verification source specs sit in public repositories, with working oracles: the soko auditors, bar/check.py, and f0/scripts/gate.py. The formal-claims-audit ledger holds zero verdicts so far, and its reviewer list is empty.

    +

    Uses D3

    +
    +
    Lemma L2Verified
    +

    Layer 5 classifies zones and audits generated code

    +

    The mde tool carries a canonical zone manifest (sha256 4e00656c...) and a native guard that rejects bare asserts, silent exception swallows, and duplicate JSON keys in generated verifiers.

    +

    Uses D1, D3

    +
    +
    Lemma L3Verified
    +

    Layer 4 routes proof spans to the proof adapter only

    +

    The exo router sends a formal_proof span to the formal-verification adapter at weight 1.0 and to the prose and style packs at 0.0. Unit tests cover all seven cross-domain interference rules.

    +

    Uses D1

    +
    +
    Lemma L4Verified
    +

    Layer 3 loads adapters through four fail-closed stages

    +

    The warp-modeld daemon checks binding, an integer certificate, a shadow load with verifier-owned canaries, and a constant-time kill switch, in that order. It was live-verified against llama-server with 54 of 54 tests passing.

    +

    Uses A2, D3

    +
    +
    Lemma L5Verified
    +

    Layer 2 compiles adapters you can rebuild byte for byte

    +

    The weft compiler solves its edit in CPU float64, packs it into a checked container, and certifies the packed result with integer arithmetic. Experiments E1 to E7 cover composition, tamper rejection, packing, and a live server load. The composition runs so far are synthetic.

    +

    Uses A2, A3

    +
    +
    +
    + +
    +
    +

    03//Theorems

    +

    One conjecture worth testing. One theorem about this page.

    +
    +
    +
    Theorem T0Conjecture
    +

    A model can work inside a formal domain it cannot talk its way out of

    +

    A model fitted with the formal-verification adapter, mounted through layers 2 to 5, produces proofs and checkers that pass deterministic oracles at rates the bare model does not reach, while every authority stays outside the weights. This is the claim mcproof exists to test. It is not proved, and this site will not call it proved until O1 to O4 are discharged.

    +

    Uses L1, L2, L3, L4, L5, O1, O2, O3, O4

    +
    +
    Theorem T1Verified
    +

    This page checks its own claims

    +

    The claim graph behind this page is acyclic, every tier on it follows the tier rules, and two checkers that share no code (one Python, one JavaScript running in your browser) recompute the same verdict from the same file. The panel below shows the live result. Break the graph with the tamper button and the verdict turns red.

    +

    Uses D2, D3

    +
    +
    +
    +
    +
    +

    04//Obligations

    open until discharged, in the open
    +

    The proof obligations, still open.

    +

    In a proof assistant, an unfinished proof lists its remaining goals. Same here: five obligations stand between the verified baseline and Theorem T0. Each states what would discharge it. The checkers cap T0 at CONJECTURE while any of them is open, so this page cannot quietly upgrade itself.

    +
    +
    +
    Obligation O1Open
    +

    Freeze a 240-prompt test set with a private holdout

    +

    Assemble 240 prompts in four families (Lean proofs, exact checkers, claim-tier traps, mixed-zone documents), split 96 compile, 48 validation, 96 untouched private holdout, and pin every record by SHA-256. Status: open pull requests in this repository (#3, #6) contain a candidate corpus with recomputing sums, but nothing is merged to main and the private split is not in this public repo, so the obligation stays open. Discharge: the frozen manifest merged, with its sums recomputing from a fresh clone.

    +

    Uses L1

    +
    +
    Obligation O2Open
    +

    Compile a real 1.7B to 4B adapter and score it live

    +

    Build the formal-verification adapter for a real open checkpoint and score it against the Lean compiler and the soko, bar, and f0 oracles, with the bare model and the full-spec prompt as matched arms. Status: pull request #3 reports such runs and a negative result (0 of 96 on the holdout across arms) in committed receipts that this page has not rerun and that are not merged. Discharge: scored runs merged with enough artifacts for an independent rerun.

    +

    Uses O1, L5

    +
    +
    Obligation O3Open
    +

    Meet the pre-registered pass and kill criteria

    +

    Pass means at least 50 percent fewer oracle failures than the bare model on the private holdout, at least 80 percent of the full-spec ceiling, all safety canaries green, and zero corrupted proof blocks. Status: pull request #3 records a kill verdict against its own candidate (REJECTED for negative efficacy), disclosed in its verification report; the obligation therefore stays open for a future candidate, and the negative result stands on the record. Discharge: the scored table merged, published either way, with gates unchanged.

    +

    Uses O2, L4

    +
    +
    Obligation O4Open
    +

    Compose with prose and style packs without interference

    +

    Run the proof adapter beside a prose pack and the Eido style system under gates T-C1 to T-C5: solo gains kept, zones isolated, base ability retained, order-invariant composition, and a serving budget. Discharge: all five gates scored on a real checkpoint.

    +

    Uses O3, L3

    +
    +
    Obligation O5Open
    +

    Seat the human bar

    +

    Name spec reviewers in bar/reviewers.toml and record the first verdicts in formal-claims-audit. Until then the human tier of the system is specified but unstaffed, and no library counts as admitted. Discharge: a non-empty reviewer list and at least one recorded verdict.

    +

    Uses A1

    +
    +
    +
    Pass and kill criteria for O3, registered before any adapter is compiled. A miss is published as a negative result. The gates do not move after the runs.
    +
    + + + + + + + + + + + + + +
    GateMeasurePass
    Primary gainOracle failures on 96 private holdoutsat least 50% fewer than the bare model
    Ceiling ratioHoldout pass rate vs the full-spec promptat least 80% of it
    Token savingsSpec tokens injected per turnat least 90% fewer
    Safety canariesVerifier-owned canary prompts8 of 8
    General retention100 untouched coding, maths, refusal promptsdrop of at most 1.0 point
    Mixed integrity30 mixed prose and proof prompts0 corrupted proof blocks
    RebuildIndependent rebuild of the adapter bytes0-byte difference
    Tamper defenceForged or stale or sabotaged adapters100% rejected
    RollbackOutput drift after the kill switchexactly 0.0
    +
    +

    Source: the blueprint issue, phase 5. siliconcordat/mde#4.

    +
    +
    +
    + +
    +
    +

    05//Hazard guards

    counterexamples, each with its guard
    +

    Seven ways the domains could corrupt each other.

    +

    Put a proof domain beside a prose domain and a style domain and the seams are where things break: a style rule edits a proof, a summary trims a disclaimer. Each known seam is recorded as a hazard with the guard that closes it. Precedence when rules collide: human authority, then repository policy, then the specialist pack inside its own zone, then the base prose pack.

    +
    +
    +
    Hazard guard H1Known
    +

    A style rule against negative clauses could strip the honesty sections

    +

    Guard: inside a formal_proof zone the prose pack weight is 0.0 and negative disclaimers are explicitly allowed, so What is not proved survives every style pass.

    +

    Uses A4, D1

    +
    +
    Hazard guard H2Known
    +

    Readability rules could rewrite axioms and commit hashes

    +

    Guard: protect_axioms and protect_sha_digests pin exact identifiers. A 40-character verdict hash is never shortened to please a style rule.

    +

    Uses D1

    +
    +
    Hazard guard H3Known
    +

    Two vocabularies for certainty could blur into each other

    +

    Guard: claim-tier words are locked per repository by policy, outside the weights. Tested and deployed never silently become VERIFIED or PROVEN.

    +

    Uses D2

    +
    +
    Hazard guard H4Known
    +

    Prose grammar rules could mangle terse machine records

    +

    Guard: a condensed_json zone with no formal claims zeroes the prose pack, so grammar rules never reach inside a data record.

    +

    Uses D1

    +
    +
    Hazard guard H5Known
    +

    Two delivery styles could each claim the same page

    +

    Guard: a contested delivery choice fails closed with ContestedPreferenceError until a human-written precedence override names the winner.

    +

    Uses A1, A2

    +
    +
    Hazard guard H6Known
    +

    A floating-point picture could pose as an exact result

    +

    Guard: research pages forbid floats inside exact verifiers and require every illustrative figure to carry an illustrative tag and a link to its certificate.

    +

    Uses A3

    +
    +
    Hazard guard H7Known
    +

    Automatic shortening could cut the hedges off a claim

    +

    Guard: condensing refuses any block marked data-eido-skip. On this page the condense switch shortens plain prose and visibly refuses every proof block. Try it in the header.

    +

    Uses A4, D1

    +
    +
    +
    + +
    +
    +
    +

    06//Boundary

    +

    What is not proved.

    +
      +
    • Theorem T0. No end-to-end run on a real checkpoint exists yet; composition evidence so far is synthetic.
    • +
    • That a compiled adapter can carry deep proof search, as opposed to surface habits such as exact arithmetic and honest tiers. The blueprint records this as the likely failure line in advance.
    • +
    • Any admission to the Proven Commons bar. The reviewer list is empty and the verdict ledger holds zero verdicts (Obligation O5).
    • +
    • The lemmas rest on runs recorded in the blueprint issue. They were not rerun for this page; the commits are pinned so anyone can rerun them.
    • +
    • This page proves a property of its own claim graph (T1), nothing about any model.
    • +
    +
    +
    +

    What you must trust.

    +
      +
    • Axioms A1 to A4. They are commitments, and the system is only as good as they are.
    • +
    • The oracles themselves: the Lean toolchain, and the auditor scripts named in L1. A bug in an oracle is a bug in every verdict it gates.
    • +
    • For this page: your browser's SHA-256, and that the two checkers in the repository are the ones CI ran. Both are short and readable.
    • +
    • GitHub, to serve the files the repository holds. The certificate lets you detect any difference, but not prevent it.
    • +
    +
    +
    +
    + +
    +
    +

    07//Verify

    no proof, no publish
    +

    Do not take this page's word for it.

    +

    Clone the repository and run the same gates CI runs. The Python checker runs three ways, including with optimisations and warnings as errors. The JavaScript checker runs under Node and must agree with the Python certificate claim by claim. Seventeen planted corruptions of the graph must all be rejected. The page is then built twice and the two builds must be byte-identical. Only if all of that passes does the publish job run.

    +
    git clone https://github.com/Proven-Commons/mcproof
    +cd mcproof
    +python3 -I -B   tools/verify.py --write-certificate
    +python3 -I -O -B tools/verify.py
    +python3 -I -B -W error tools/verify.py
    +python3 -I -B tools/run_mutations.py     # 17 planted bugs, all must be rejected
    +node --test "test/*.test.mjs"            # JS checker vs the Python certificate
    +python3 -I -B tools/build.py --verify    # deterministic prerender
    +

    To add or change a claim, edit docs/data/claims.json, keep the tier rules in RULES.md, and rerun the gates. The page text, the figure, the stats, and the seal all rebuild from that one file.

    + +
    +
    + + +
    + + diff --git a/test/checker-parity.test.mjs b/test/checker-parity.test.mjs new file mode 100644 index 0000000..0565f8c --- /dev/null +++ b/test/checker-parity.test.mjs @@ -0,0 +1,265 @@ +// Python and JavaScript checkers must agree on every malformed graph (docs/data/RULES.md T1). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync, mkdtempSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { checkGraph } from "../docs/assets/proof-core.js"; + +/** R-Text expectation helper (must match RULES.md / both checkers). */ +const ASCII_WS = new Set("\t\n\v\f\r "); +function isBlankText(s) { + if (typeof s !== "string" || s.length === 0) return true; + for (const c of s) { + if (!ASCII_WS.has(c)) return false; + } + return true; +} + +const claims = JSON.parse(readFileSync(new URL("../docs/data/claims.json", import.meta.url), "utf8")); +const ROOT = new URL("..", import.meta.url).pathname; +const VERIFY = ["python3", "-I", "-B", join(ROOT, "tools/verify.py"), "--claims"]; + +function ruleIdsFromErrors(errors) { + const ids = new Set(); + for (const e of errors) { + for (const m of String(e).matchAll(/\(R[123]\)/g)) ids.add(m[0].slice(1, -1)); + } + return [...ids].sort(); +} + +function ruleIdsFromPython(stderr) { + const ids = new Set(); + for (const m of stderr.matchAll(/\(R[123]\)/g)) ids.add(m[0].slice(1, -1)); + return [...ids].sort(); +} + +function pyCheck(doc) { + const dir = mkdtempSync(join(tmpdir(), "mcproof-parity-")); + const path = join(dir, "claims.json"); + writeFileSync(path, JSON.stringify(doc)); + const r = spawnSync(VERIFY[0], [...VERIFY.slice(1), path], { encoding: "utf8" }); + return { ok: r.status === 0, stderr: r.stderr || "", stdout: r.stdout || "" }; +} + +function jsCheck(doc) { + const r = checkGraph(doc); + return { ok: r.ok, errors: r.errors, ruleIds: ruleIdsFromErrors(r.errors) }; +} + +function assertParity(name, doc, { expectOk = false, expectRules = null } = {}) { + const py = pyCheck(doc); + const js = jsCheck(doc); + assert.equal(py.ok, js.ok, `${name}: accept/reject mismatch py=${py.ok} js=${js.ok}`); + if (expectOk !== undefined && expectOk !== null) { + assert.equal(js.ok, expectOk, name); + } + if (!js.ok) { + const pyRules = ruleIdsFromPython(py.stderr); + assert.deepEqual(pyRules, js.ruleIds, `${name}: rule id mismatch py=${pyRules} js=${js.ruleIds}`); + if (expectRules) { + for (const rid of expectRules) { + assert.ok(js.ruleIds.includes(rid), `${name}: expected ${rid} in ${js.ruleIds}`); + } + } + } +} + +test("both checkers accept the live claims.json", () => { + assertParity("live graph", claims, { expectOk: true }); +}); + +const parityCases = [ + { + name: "empty evidence URL (MC18-01)", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence.push({ label: "empty", url: "" }); }, + expectRules: ["R2"], + }, + { + name: "kind as list (MC18-01)", + mutate: (d) => { d.claims.find((c) => c.id === "A1").kind = ["axiom"]; }, + expectRules: ["R1"], + }, + { + name: "bare https evidence (MC18-01)", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence.push({ label: "bare", url: "https://" }); }, + expectRules: ["R2"], + }, + { + name: "dotdot relative evidence (MC18-01)", + mutate: (d) => { + d.claims.find((c) => c.id === "L1").evidence.push({ label: "traversal", url: "../../../../etc/passwd" }); + }, + expectRules: ["R2"], + }, + { + name: "non-list evidence (MC18-01)", + mutate: (d) => { d.claims.find((c) => c.id === "O1").evidence = "not-a-list"; }, + expectRules: ["R2"], + }, + { + name: "relative url trailing newline", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence.push({ label: "nl", url: "docs/x\n" }); }, + expectRules: ["R2"], + }, + { + name: "https host vertical tab", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence.push({ label: "vt", url: "https://a\u000bb/x" }); }, + expectRules: ["R2"], + }, + { + name: "claim id as list", + mutate: (d) => { d.claims.find((c) => c.id === "A1").id = []; }, + expectRules: ["R1"], + }, + { + name: "claim id as object", + mutate: (d) => { d.claims.find((c) => c.id === "A1").id = {}; }, + expectRules: ["R1"], + }, + { + name: "evidence label BOM only (R-Text)", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence[0].label = "\uFEFF"; }, + expectOk: true, + }, + { + name: "evidence label FS only (R-Text)", + mutate: (d) => { d.claims.find((c) => c.id === "L1").evidence[0].label = "\u001C"; }, + expectOk: true, + }, +]; + +for (const { name, mutate, expectRules, expectOk } of parityCases) { + const reject = expectOk !== true; + test(`parity ${reject ? "reject" : "accept"}: ${name}`, () => { + const doc = structuredClone(claims); + mutate(doc); + assertParity(name, doc, { + expectOk: reject ? false : true, + expectRules: reject ? expectRules : null, + }); + }); +} + +const BLANK_FUZZ_CHARS = (() => { + const out = []; + for (let cp = 0x1c; cp <= 0x1f; cp++) out.push(String.fromCodePoint(cp)); + out.push( + "\x85", "\xa0", "\u1680", + ...Array.from({ length: 12 }, (_, i) => String.fromCodePoint(0x2000 + i)), + "\u2028", "\u2029", "\u202f", "\u205f", "\u3000", "\ufeff", + "\t", "\n", "\v", "\f", "\r", " ", + ); + return out; +})(); + +const TEXT_FIELDS = [ + { field: "title", cid: "A1", rule: "R1", set: (doc, v) => { doc.claims.find((c) => c.id === "A1").title = v; } }, + { field: "statement", cid: "A1", rule: "R1", set: (doc, v) => { doc.claims.find((c) => c.id === "A1").statement = v; } }, + { + field: "label", cid: "L1", rule: "R2", + set: (doc, v) => { doc.claims.find((c) => c.id === "L1").evidence[0].label = v; }, + }, +]; + +for (const ch of BLANK_FUZZ_CHARS) { + const tag = `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`; + for (const { field, rule, set } of TEXT_FIELDS) { + for (const mode of ["whole", "padded"]) { + const value = mode === "whole" ? ch : `${ch}x${ch}`; + const expectOk = !isBlankText(value); + test(`parity R-Text ${field} ${tag} ${mode}`, () => { + const doc = structuredClone(claims); + set(doc, value); + assertParity(`${field} ${tag} ${mode}`, doc, { + expectOk, + expectRules: expectOk ? null : [rule], + }); + }); + } + } +} + +const FIELDS = [ + "kind", + "asserted_tier", + "section", + "title", + "statement", + "depends_on", + "evidence", +]; +const BAD = [ + ["null", null], + ["number", 42], + ["list", ["x"]], + ["object", { x: 1 }], +]; + +const TYPE_TARGET = { evidence: "L1", depends_on: "A1" }; +const defaultTarget = (field) => TYPE_TARGET[field] || "A1"; + +for (const field of FIELDS) { + for (const [label, value] of BAD) { + test(`parity wrong type ${field}=${label}`, () => { + const doc = structuredClone(claims); + const c = doc.claims.find((x) => x.id === defaultTarget(field)); + c[field] = value; + assertParity(`${field}=${label}`, doc, { expectOk: false }); + }); + } + if (field === "evidence") continue; + test(`parity missing ${field}`, () => { + const doc = structuredClone(claims); + delete doc.claims.find((x) => x.id === defaultTarget(field))[field]; + assertParity(`missing ${field}`, doc, { expectOk: false }); + }); +} + +const TRICKY_CHARS = (() => { + const out = []; + for (let i = 0; i <= 31; i++) out.push(String.fromCharCode(i)); + out.push(String.fromCharCode(127), "\u00a0", "\u2028", "\uFEFF", "\uFF0F"); + return out; +})(); + +const URL_INJECT = [ + { name: "relative", mk: (ch) => `docs/path${ch}` }, + { name: "host", mk: (ch) => `https://host${ch}.example/x` }, + { name: "path", mk: (ch) => `https://a/x${ch}` }, +]; +const STRING_FIELDS = [ + ["kind", "A1", (ch, base) => `${base}${ch}`], + ["section", "A1", (ch, base) => `${base}${ch}`], + ["asserted_tier", "A1", (ch, base) => `${base}${ch}`], +]; + +for (const ch of TRICKY_CHARS) { + const label = `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`; + for (const { name, mk } of URL_INJECT) { + test(`parity fuzz url ${label} in ${name}`, () => { + const doc = structuredClone(claims); + const url = mk(ch); + doc.claims.find((c) => c.id === "L1").evidence.push({ label: "fuzz", url }); + assertParity(`url ${label} ${JSON.stringify(url)}`, doc, { expectOk: false, expectRules: ["R2"] }); + }); + } + for (const [field, cid, build] of STRING_FIELDS) { + const base = field === "kind" ? "axiom" : field === "section" ? "axioms" : "KNOWN"; + test(`parity fuzz ${field} ${label}`, () => { + const doc = structuredClone(claims); + doc.claims.find((c) => c.id === cid)[field] = build(ch, base); + assertParity(`${field} ${label}`, doc, { expectOk: false, expectRules: ["R1"] }); + }); + } +} + +test("Python rejects missing claims file without traceback", () => { + const r = spawnSync("python3", ["-I", "-B", join(ROOT, "tools/verify.py"), "--claims", "/no/such/claims.json"], { + encoding: "utf8", + }); + assert.notEqual(r.status, 0); + assert.match(r.stderr, /FAIL:/); + assert.doesNotMatch(r.stderr, /Traceback/); +}); \ No newline at end of file diff --git a/test/proof-core.test.mjs b/test/proof-core.test.mjs new file mode 100644 index 0000000..1c24800 --- /dev/null +++ b/test/proof-core.test.mjs @@ -0,0 +1,83 @@ +// Node tests for the browser checker. Run: node --test test/ +// The load-bearing case: given the real claims.json, the JavaScript checker +// must agree with the Python certificate claim by claim. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { checkGraph, layoutGraph, mixPresets, seededRand } from "../docs/assets/proof-core.js"; + +const claims = JSON.parse(readFileSync(new URL("../docs/data/claims.json", import.meta.url), "utf8")); +const cert = JSON.parse(readFileSync(new URL("../docs/data/certificate.json", import.meta.url), "utf8")); + +test("JS checker accepts the real graph", () => { + const r = checkGraph(claims); + assert.deepEqual(r.errors, []); + assert.equal(r.ok, true); +}); + +test("JS computed tiers equal the Python certificate", () => { + const r = checkGraph(claims); + assert.deepEqual({ ...r.computed }, cert.computed_tiers); + assert.deepEqual([...r.openObligations].sort(), cert.open_obligations); +}); + +test("T0 stays a conjecture while obligations are open", () => { + const r = checkGraph(claims); + assert.equal(r.computed.T0, "CONJECTURE"); +}); + +test("tier inflation is rejected", () => { + const bad = structuredClone(claims); + bad.claims.find((c) => c.id === "T0").asserted_tier = "PROVEN"; + const r = checkGraph(bad); + assert.equal(r.ok, false); + assert.match(r.errors.join(" "), /T0.*R3/); +}); + +test("cycle is rejected", () => { + const bad = structuredClone(claims); + bad.claims.find((c) => c.id === "O1").depends_on.push("T0"); + assert.equal(checkGraph(bad).ok, false); +}); + +test("layout is deterministic and layered after dependencies", () => { + const r = checkGraph(claims); + const a = layoutGraph(claims, r.order); + const b = layoutGraph(claims, r.order); + assert.deepEqual(a, b); + for (const c of claims.claims) { + for (const d of c.depends_on) assert.ok(a.pos[d].layer < a.pos[c.id].layer, `${d} before ${c.id}`); + } +}); + +test("hue mixes on the circle: red plus red stays red", () => { + const m = mixPresets( + { a: { hue: 0.95, density: 0.2 }, b: { hue: 0.05, density: 0.4 } }, + { a: 0.5, b: 0.5 }); + assert.ok(m.hue < 0.02 || m.hue > 0.98, `hue ${m.hue} should be red, not cyan`); + assert.ok(Math.abs(m.density - 0.3) < 1e-9); +}); + +test("seeded randomness repeats exactly", () => { + const r1 = seededRand("4e00656c"), r2 = seededRand("4e00656c"); + assert.deepEqual([r1(), r1(), r1()], [r2(), r2(), r2()]); +}); + +test("prototype names are not tiers or ids", () => { + const a = structuredClone(claims); + a.claims.find((c) => c.id === "L1").asserted_tier = "constructor"; + assert.equal(checkGraph(a).ok, false); + const b = structuredClone(claims); + b.claims.push({ id: "__proto__", kind: "lemma", section: "baseline", title: "x", statement: "x", + asserted_tier: "KNOWN", depends_on: [], evidence: [] }); + assert.equal(checkGraph(b).ok, false); +}); + +test("dangerous evidence URLs and missing titles are rejected", () => { + const a = structuredClone(claims); + a.claims.find((c) => c.id === "L1").evidence.push({ label: "x", url: "javascript:alert(1)" }); + assert.equal(checkGraph(a).ok, false); + const b = structuredClone(claims); + delete b.claims.find((c) => c.id === "L1").title; + assert.equal(checkGraph(b).ok, false); +}); diff --git a/tools/build.py b/tools/build.py new file mode 100644 index 0000000..90814f4 --- /dev/null +++ b/tools/build.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Deterministic prerender: bake claims.json into docs/index.html. + +Replaces the regions between ... +markers with HTML computed from docs/data/claims.json and the certificate +from tools/verify.py. No timestamps, no environment reads: the same input +gives the same bytes. CI builds twice and diffs to prove it. + +Run tools/verify.py --write-certificate first (or pass --verify to do both). +""" +import html +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools")) +import verify as checker # noqa: E402 + +KIND_WORD = {"axiom": "Axiom", "definition": "Definition", "lemma": "Lemma", + "theorem": "Theorem", "obligation": "Obligation", "hazard": "Hazard guard"} +TIER_WORD = {"OPEN": "Open", "CONJECTURE": "Conjecture", "KNOWN": "Known", + "VERIFIED": "Verified", "PROVEN": "Proven"} +TIER_RUNG = {"OPEN": 0, "CONJECTURE": 1, "KNOWN": 2, "VERIFIED": 4, "PROVEN": 5} +SECTIONS = ["axioms", "definitions", "baseline", "theorem", "obligations", "hazards"] + + +def esc(s): + return html.escape(str(s), quote=True) + + +def ladder(tier): + rung = TIER_RUNG[tier] + cells = "".join("" for _ in range(5)) + return f'' + + +def claim_html(c, computed, by_id): + tier = computed[c["id"]] + deps = [d for d in c["depends_on"] if d in by_id] + dep_html = "" + if deps: + links = ", ".join(f'{esc(d)}' for d in deps) + dep_html = f'

    Uses {links}

    ' + ev_html = "" + ev = c.get("evidence") if isinstance(c.get("evidence"), list) else [] + if ev: + items = "".join( + f'
  • {esc(e.get("label", "source"))}
  • ' + for e in ev if isinstance(e, dict)) + ev_html = f'
    Evidence
    ' + return ( + f'
    \n' + f'
    {esc(KIND_WORD[c["kind"]])} {esc(c["id"])}' + f'{ladder(tier)}{esc(TIER_WORD[tier])}
    \n' + f'

    {esc(c["title"])}

    \n

    {esc(c["statement"])}

    \n{dep_html}{ev_html}
    ' + ) + + +def replace_region(text, name, body): + open_m = f"" + close_m = f"" + if open_m not in text or close_m not in text: + raise SystemExit(f"FAIL: prerender markers for {name!r} not found in index.html") + head, rest = text.split(open_m, 1) + _, tail = rest.split(close_m, 1) + return head + open_m + body + close_m + tail + + +def main(argv): + do_verify = "--verify" in argv + claims_path = ROOT / "docs" / "data" / "claims.json" + raw, doc = checker.load(claims_path) + errors, computed, open_obligations = checker.check(doc) + if errors: + checker.fail(errors) + cert_bytes = checker.certificate(raw, computed, open_obligations) + if do_verify: + (ROOT / "docs" / "data" / "certificate.json").write_bytes(cert_bytes) + cert = json.loads(cert_bytes.decode("utf-8")) + claims = doc["claims"] + by_id = {c["id"]: c for c in claims} + index = ROOT / "docs" / "index.html" + text = index.read_text(encoding="utf-8") + + for section in SECTIONS: + body = "\n".join(claim_html(c, computed, by_id) for c in claims if c.get("section") == section) + text = replace_region(text, f"claims-{section}", "\n" + body + "\n") + + verified_lemmas = sum(1 for c in claims + if c.get("kind") == "lemma" and computed.get(c["id"]) == "VERIFIED") + stats = ( + f'
    claims in the graph
    {len(claims)}
    ' + f'
    verified lemmas (the baseline)
    {verified_lemmas}
    ' + f'
    open obligations
    {len(open_obligations)}
    ' + f'
    main theorem T0
    {TIER_WORD[computed.get("T0", "OPEN")]}
    ' + ) + text = replace_region(text, "stats", stats) + seal = ( + f'claims sha256:{cert["claims_sha256"][:16]}… ' + f'graph sha256:{cert["graph_sha256"][:16]}…' + ) + text = replace_region(text, "seal", seal) + index.write_text(text, encoding="utf-8") + print(f"OK prerendered {len(claims)} claims, open={len(open_obligations)}, " + f"T0={computed.get('T0')}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/tools/run_mutations.py b/tools/run_mutations.py new file mode 100644 index 0000000..af17dc7 --- /dev/null +++ b/tools/run_mutations.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Planted-bug suite: corrupt the claim graph many ways and require +tools/verify.py to reject every corruption. Modeled on the f0 gate +corruption suite. A checker that passes a corrupted graph is the bug. +""" +import copy +import json +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SRC = ROOT / "docs" / "data" / "claims.json" +VERIFY = [sys.executable, "-I", "-B", str(ROOT / "tools" / "verify.py"), "--claims"] + + +def mutations(doc): + def m(name, fn): + d = copy.deepcopy(doc) + fn(d) + return name, d + yield m("inflate T0 to PROVEN", lambda d: claim(d, "T0").update(asserted_tier="PROVEN")) + yield m("inflate T0 to VERIFIED", lambda d: claim(d, "T0").update(asserted_tier="VERIFIED")) + yield m("strip evidence from L1", lambda d: claim(d, "L1").update(evidence=[])) + yield m("cycle O1->T0", lambda d: claim(d, "O1")["depends_on"].append("T0")) + yield m("missing dependency", lambda d: claim(d, "L2")["depends_on"].append("ZZ9")) + yield m("duplicate id", lambda d: d["claims"].append(copy.deepcopy(d["claims"][0]))) + yield m("unknown tier", lambda d: claim(d, "L3").update(asserted_tier="CERTAIN")) + yield m("unknown kind", lambda d: claim(d, "L4").update(kind="fact")) + yield m("evidence on OPEN obligation", lambda d: claim(d, "O1").update( + evidence=[{"label": "x", "url": "https://example.invalid"}])) + yield m("self dependency", lambda d: claim(d, "D3")["depends_on"].append("D3")) + yield m("PROVEN over a merely KNOWN dependency", lambda d: d["claims"].append({ + "id": "X1", "kind": "lemma", "section": "baseline", "title": "x", "statement": "x", + "asserted_tier": "PROVEN", "depends_on": ["H3"], + "evidence": [{"label": "x", "url": "https://example.invalid"}]})) + yield m("empty claim list entry", lambda d: d["claims"].append({})) + yield m("javascript: evidence URL", lambda d: claim(d, "L1")["evidence"].append( + {"label": "x", "url": "javascript:alert(1)"})) + yield m("evidence with no label", lambda d: claim(d, "L1")["evidence"].append({"url": "https://example.invalid"})) + yield m("missing title", lambda d: claim(d, "L1").pop("title")) + yield m("unknown section vanishes claim", lambda d: claim(d, "L1").update(section="appendix")) + yield m("prototype-name tier", lambda d: claim(d, "L1").update(asserted_tier="constructor")) + yield m("empty evidence URL", lambda d: claim(d, "L1")["evidence"].append({"label": "empty", "url": ""})) + yield m("kind as list", lambda d: claim(d, "A1").update(kind=["axiom"])) + yield m("bare https evidence", lambda d: claim(d, "L1")["evidence"].append({"label": "bare", "url": "https://"})) + yield m("dotdot relative evidence", lambda d: claim(d, "L1")["evidence"].append( + {"label": "traversal", "url": "../../../../etc/passwd"})) + yield m("non-list evidence", lambda d: claim(d, "O1").update(evidence="not-a-list")) + yield m("relative url trailing newline", lambda d: claim(d, "L1")["evidence"].append( + {"label": "nl", "url": "docs/x\n"})) + yield m("https host carriage return", lambda d: claim(d, "L1")["evidence"].append( + {"label": "cr", "url": "https://a\rb/x"})) + yield m("claim id as list", lambda d: claim(d, "A1").update(id=[])) + + +def claim(doc, cid): + for c in doc["claims"]: + if c.get("id") == cid: + return c + raise KeyError(cid) + + +def main(): + doc = json.loads(SRC.read_text(encoding="utf-8")) + cases = list(mutations(doc)) + killed = 0 + with tempfile.TemporaryDirectory() as td: + for name, mutated in cases: + p = Path(td) / "claims.json" + p.write_text(json.dumps(mutated), encoding="utf-8") + r = subprocess.run(VERIFY + [str(p)], capture_output=True, text=True) + dead = r.returncode != 0 + killed += 1 if dead else 0 + print(f"{'killed ' if dead else 'SURVIVED'} {name}") + print(f"{killed}/{len(cases)} corruptions rejected") + if killed != len(cases): + print("FAIL: a corrupted graph passed the checker", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/verify.py b/tools/verify.py new file mode 100644 index 0000000..6033428 --- /dev/null +++ b/tools/verify.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +"""Independent checker for the mcproof claim graph (docs/data/RULES.md). + +Shares no code with docs/assets/proof-core.js. No floats decide any +verdict; tier ranks are ints. Safe under python3 -O (no bare assert +carries a verdict; failures raise SystemExit with a message). + +Usage: + python3 tools/verify.py [--claims PATH] [--write-certificate] +Exit 0 and print CERTIFICATE sha256 on success; exit 1 listing every +error on failure. +""" +import hashlib +import json +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +RANK = {"OPEN": 0, "CONJECTURE": 1, "KNOWN": 2, "VERIFIED": 3, "PROVEN": 4} +KINDS = {"axiom", "definition", "lemma", "theorem", "obligation", "hazard"} +SECTIONS = {"axioms", "definitions", "baseline", "theorem", "obligations", "hazards"} +ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$") +HOST_RE = re.compile(r"^[A-Za-z0-9.-]+(:[0-9]+)?$", re.ASCII) +HTTPS_TAIL_RE = re.compile(r"^(/[A-Za-z0-9_./:@%?&=-]*)?([?#][A-Za-z0-9_./:@%?&=-]*)?$", re.ASCII) +REL_URL_RE = re.compile(r"^[A-Za-z0-9_./-]+$", re.ASCII) +ASCII_WS = frozenset("\t\n\v\f\r ") + + +def is_blank_text(s): + """R-Text: same rule as proof-core.js isBlankText.""" + if not isinstance(s, str) or not s: + return True + return all(c in ASCII_WS for c in s) + + +def has_text(s): + return isinstance(s, str) and not is_blank_text(s) + + +def url_ok(url): + """R2-URL: same rule as docs/assets/proof-core.js urlOk.""" + if not isinstance(url, str) or not url: + return False + if url.startswith("//"): + return False + if url.startswith("https://"): + rest = url[8:] + if not rest: + return False + auth_end = len(rest) + for sep in "/?#": + i = rest.find(sep) + if i != -1: + auth_end = min(auth_end, i) + authority = rest[:auth_end] + if not authority or not HOST_RE.fullmatch(authority): + return False + tail = rest[auth_end:] + if tail and not HTTPS_TAIL_RE.fullmatch(tail): + return False + return True + if ".." in url.split("/"): + return False + return REL_URL_RE.fullmatch(url) is not None + + +def fail(errors): + for e in errors: + print(f"ERROR {e}", file=sys.stderr) + print(f"FAIL: {len(errors)} error(s)", file=sys.stderr) + raise SystemExit(1) + + +def load(path): + try: + raw = path.read_bytes() + except OSError as exc: + fail([f"{path}: cannot read ({exc.__class__.__name__})"]) + def no_dupes(pairs): + seen = {} + for k, v in pairs: + if k in seen: + raise ValueError(f"duplicate JSON key {k!r}") + seen[k] = v + return seen + try: + doc = json.loads(raw.decode("utf-8"), object_pairs_hook=no_dupes) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + fail([f"{path.name}: not valid UTF-8 JSON ({exc.__class__.__name__})"]) + return raw, doc + + +def check(doc): + errors = [] + claims = doc.get("claims") if isinstance(doc, dict) else None + if not isinstance(claims, list) or not claims: + return ["claims: missing, not a list, or empty (R1)"], {}, [] + by_id = {} + for c in claims: + if not isinstance(c, dict) or not isinstance(c.get("id"), str) or not c.get("id"): + errors.append("claim with missing id (R1)") + continue + cid = c["id"] + if cid in by_id: + errors.append(f"{cid}: duplicate id") + kind = c.get("kind") + if not isinstance(kind, str) or kind not in KINDS: + errors.append(f"{cid}: unknown kind {kind!r} (R1)") + tier = c.get("asserted_tier") + if not isinstance(tier, str) or tier not in RANK: + errors.append(f"{cid}: unknown tier {tier!r} (R1)") + if not ID_RE.match(cid): + errors.append(f"{cid}: id must match ^[A-Za-z][A-Za-z0-9_-]*$ (R1)") + if not has_text(c.get("title")): + errors.append(f"{cid}: missing title (R1)") + if not has_text(c.get("statement")): + errors.append(f"{cid}: missing statement (R1)") + section = c.get("section") + if not isinstance(section, str) or section not in SECTIONS: + errors.append(f"{cid}: unknown section {section!r} (R1)") + if not isinstance(c.get("depends_on"), list): + errors.append(f"{cid}: depends_on is not a list") + if "evidence" in c and not isinstance(c.get("evidence"), list): + errors.append(f"{cid}: evidence is not a list (R2)") + by_id[cid] = c + for c in claims: + cid_raw = c.get("id") if isinstance(c, dict) else None + if not isinstance(c, dict) or not isinstance(cid_raw, str) or cid_raw not in by_id: + continue + cid = cid_raw + deps = c["depends_on"] if isinstance(c.get("depends_on"), list) else [] + for d in deps: + if not isinstance(d, str): + errors.append(f"{cid}: depends_on entries must be strings (R1)") + elif d not in by_id: + errors.append(f"{cid}: depends on missing claim {d!r} (R1)") + if "evidence" in c and not isinstance(c.get("evidence"), list): + continue + ev = c["evidence"] if isinstance(c.get("evidence"), list) else [] + for e in ev: + if not isinstance(e, dict): + errors.append(f"{cid}: evidence must be {{label, https-or-relative url}} (R2)") + continue + label = e.get("label") + url = e.get("url") + if not (has_text(label) and url_ok(url)): + errors.append(f"{cid}: evidence must be {{label, https-or-relative url}} (R2)") + if c.get("asserted_tier") in ("VERIFIED", "PROVEN") and not ev: + errors.append(f"{cid}: asserted {c['asserted_tier']} with no evidence (R2)") + if c.get("kind") == "obligation" and c.get("asserted_tier") == "OPEN" and ev: + errors.append(f"{cid}: OPEN obligation carries evidence (R2)") + # Kahn topological order, lexicographic tie-break (deterministic). + indeg = {i: 0 for i in by_id} + dependents = {i: [] for i in by_id} + for c in by_id.values(): + for d in c["depends_on"] if isinstance(c.get("depends_on"), list) else []: + if isinstance(d, str) and d in by_id: + indeg[c["id"]] += 1 + dependents[d].append(c["id"]) + ready = sorted(i for i, n in indeg.items() if n == 0) + order = [] + while ready: + nid = ready.pop(0) + order.append(nid) + for nxt in sorted(dependents[nid]): + indeg[nxt] -= 1 + if indeg[nxt] == 0: + ready.append(nxt) + ready.sort() + if len(order) != len(by_id): + errors.append("dependency graph has a cycle (R1)") + computed = {} + for cid in order: + c = by_id[cid] + tier = c.get("asserted_tier") + if not isinstance(tier, str) or tier not in RANK: + computed[cid] = "OPEN" + continue + allowed = RANK[tier] + if c.get("kind") not in ("axiom", "definition"): + deps = [d for d in c["depends_on"] if isinstance(d, str) and d in by_id] if isinstance(c.get("depends_on"), list) else [] + if any(RANK[computed[d]] <= 1 for d in deps): + allowed = min(allowed, 1) + if tier == "PROVEN": + weak = [d for d in deps + if not (RANK[computed[d]] >= 3 or by_id[d].get("kind") in ("axiom", "definition"))] + if weak: + allowed = min(allowed, 3) + if RANK[tier] > allowed: + errors.append(f"{cid}: asserted {tier} exceeds allowed tier (R3)") + computed[cid] = "OPEN" + else: + computed[cid] = tier + open_obligations = [i for i in order if by_id[i].get("kind") == "obligation" and computed.get(i) == "OPEN"] + return errors, computed, open_obligations + + +def certificate(raw, computed, open_obligations): + lines = [f"{cid}>{computed[cid]}" for cid in sorted(computed)] + graph_hash = hashlib.sha256(("\n".join(lines) + "\n").encode("utf-8")).hexdigest() + cert = { + "schema": "mcproof/certificate/v1", + "claims_sha256": hashlib.sha256(raw).hexdigest(), + "graph_sha256": graph_hash, + "claim_count": len(computed), + "computed_tiers": {cid: computed[cid] for cid in sorted(computed)}, + "open_obligations": sorted(open_obligations), + "verdict": "CHECKED", + "rules": "docs/data/RULES.md", + "checker": "tools/verify.py", + } + return (json.dumps(cert, indent=2, sort_keys=True) + "\n").encode("utf-8") + + +def main(argv): + claims_path = ROOT / "docs" / "data" / "claims.json" + write = False + i = 1 + while i < len(argv): + if argv[i] == "--claims" and i + 1 < len(argv): + claims_path = Path(argv[i + 1]) + i += 2 + elif argv[i] == "--write-certificate": + write = True + i += 1 + else: + fail([f"unknown argument {argv[i]!r}"]) + if claims_path.is_dir(): + fail([f"{claims_path}: is a directory"]) + raw, doc = load(claims_path) + errors, computed, open_obligations = check(doc) + if errors: + fail(errors) + cert_bytes = certificate(raw, computed, open_obligations) + if write: + out = ROOT / "docs" / "data" / "certificate.json" + out.write_bytes(cert_bytes) + print(f"wrote {out.relative_to(ROOT)}") + print(f"OK claims={len(computed)} open_obligations={len(open_obligations)}") + print(f"CERTIFICATE sha256:{hashlib.sha256(cert_bytes).hexdigest()}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) \ No newline at end of file