From 5cd6cfd7e250c1685d37d9a43159930fa1568c30 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 00:28:36 +0000 Subject: [PATCH] feat: only Prism is implemented (audit-prism), and re-pin the frame audit-prism, the template's shrink-only ratchet (UOR-Foundation/template#91), joins xtask validate: a new non-Prism file, or net growth in non-Prism lines over the commit's first parent, is refused. It starts here, at 22,053 lines in 106 files. The frame re-pins to template 0851bb4, whose frame list includes frame/ and identity/, so frame.lock binds them byte for byte and they count as Prism's. Only frame-sync.mjs and the lock change; the files were already identical. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Asa3LcnA6wEZHWvFUkLyK --- TEMPLATE-VERIFICATION.md | 1 + bootstrap/frame-sync.mjs | 45 +++- frame.lock | 142 ++++++++++- xtask/src/audit.rs | 501 +++++++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 3 + 5 files changed, 685 insertions(+), 7 deletions(-) diff --git a/TEMPLATE-VERIFICATION.md b/TEMPLATE-VERIFICATION.md index b8b127e..408e92e 100644 --- a/TEMPLATE-VERIFICATION.md +++ b/TEMPLATE-VERIFICATION.md @@ -29,6 +29,7 @@ or test is added without the other two. | --- | --- | --- | | `check-model` | `CONFORMANCE.md` disagrees with the register | rejected | | `audit-deferral` | a deferral marker in a crate and in the gate's own source | both rejected | +| `audit-prism` | a new non-Prism file, or net growth in non-Prism lines over the first parent (the template's planted defects, UOR-Foundation/template#91) | both rejected; installed here at 22,053 lines in 106 files, with `frame/` and `identity/` bound by `frame.lock` since the re-pin to `0851bb4` | | honesty meta-gate | an ID with no test | rejected | | `prismpm check` (threat model) | the `ThreatMapping` of `Security::threatStaleCatalog` removed | rejected (PP2019) | | `prismpm check` (facet records) | `Architecture::stakeholderPrismModeler` given index 3 instead of 2 | rejected (PP4004) | diff --git a/bootstrap/frame-sync.mjs b/bootstrap/frame-sync.mjs index bb3f442..864f80b 100644 --- a/bootstrap/frame-sync.mjs +++ b/bootstrap/frame-sync.mjs @@ -33,7 +33,9 @@ const SPEC = "prism/frame-lock/1"; const RAW = (process.env.PRISM_TEMPLATE_RAW ?? `https://raw.githubusercontent.com/${TEMPLATE}`).replace(/\/$/, ""); // Every file of the frame. A lock must list exactly these, so dropping one -// from the lock cannot take it out of the gate. +// from the lock cannot take it out of the gate. The frame's panels (frame/) +// and the Prism id it signs in with (identity/) are the frame too: an app +// takes them from the template by the same pin and edits none of them. const FRAME = [ "bootstrap/frame-sync.mjs", "bootstrap/icons.py", @@ -44,6 +46,40 @@ const FRAME = [ "bootstrap/screens.mjs", "bootstrap/weight.mjs", "bootstrap/worker-runtime.mjs", + "frame/backdrops/0wFwSZn6I-I-thumb.jpg", + "frame/backdrops/0wFwSZn6I-I.jpg", + "frame/backdrops/9wH624ALFQA-thumb.jpg", + "frame/backdrops/9wH624ALFQA.jpg", + "frame/backdrops/E0AHdsENmDg-thumb.jpg", + "frame/backdrops/E0AHdsENmDg.jpg", + "frame/backdrops/Q1p7bh3SHj8-thumb.jpg", + "frame/backdrops/Q1p7bh3SHj8.jpg", + "frame/backdrops/RF4p4rTM-2s-thumb.jpg", + "frame/backdrops/RF4p4rTM-2s.jpg", + "frame/backdrops/cZgVpseeazg-thumb.jpg", + "frame/backdrops/cZgVpseeazg.jpg", + "frame/backdrops/oMcTmNHclZI-thumb.jpg", + "frame/backdrops/oMcTmNHclZI.jpg", + "frame/backdrops/qtRF_RxCAo0-thumb.jpg", + "frame/backdrops/qtRF_RxCAo0.jpg", + "frame/backdrops/t7EL2iG3jMc-thumb.jpg", + "frame/backdrops/t7EL2iG3jMc.jpg", + "frame/frame.css", + "frame/frame.mjs", + "frame/panels.css", + "frame/panels.mjs", + "frame/publish.mjs", + "frame/unsplash/.gitignore", + "frame/unsplash/README.md", + "frame/unsplash/worker.mjs", + "frame/unsplash/wrangler.toml", + "identity/PROTOCOL.md", + "identity/README.md", + "identity/dev.mjs", + "identity/prism-id.mjs", + "identity/stitch-sync.mjs", + "identity/stitch.lock", + "identity/test.mjs", "lighthouserc.json", "site/app.mjs", "site/guest-worker.mjs", @@ -108,9 +144,10 @@ function frameOf(source) { const list = source.match(/^const FRAME = \[([\s\S]*?)\];/m)?.[1]; return list ? [...list.matchAll(/"([^"]+)"/g)].map((m) => m[1]) : null; } -// A frame file is a page file or a page gate: under bootstrap/ or site/, or -// lighthouserc.json, and never outside the repository. -const framePath = (path) => /^(?:(?:bootstrap|site)\/[\w.-]+(?:\/[\w.-]+)*|lighthouserc\.json)$/.test(path) && !path.split("/").includes(".."); +// A frame file is a page file, a page gate, a frame panel or the Prism id: +// under bootstrap/, site/, frame/ or identity/, or lighthouserc.json, and +// never outside the repository. +const framePath = (path) => /^(?:(?:bootstrap|site|frame|identity)\/[\w.-]+(?:\/[\w.-]+)*|lighthouserc\.json)$/.test(path) && !path.split("/").includes(".."); // The target is judged by its own frame, not this one: a newer template may // add a frame file this script has never heard of. Its frame-sync.mjs must be diff --git a/frame.lock b/frame.lock index 197f495..d904eed 100644 --- a/frame.lock +++ b/frame.lock @@ -2,13 +2,13 @@ "spec": "prism/frame-lock/1", "source": { "repository": "UOR-Foundation/template", - "commit": "33296e024ef791b69930eddf95c759c2902279cb", - "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/33296e024ef791b69930eddf95c759c2902279cb/" + "commit": "0851bb41138041f0f75118135fd8a342109c2d73", + "raw": "https://raw.githubusercontent.com/UOR-Foundation/template/0851bb41138041f0f75118135fd8a342109c2d73/" }, "files": [ { "path": "bootstrap/frame-sync.mjs", - "sha256": "5d874908a8f5813b6f7c1004ec0e73ec03584139bf7ac8ffabb2ad5c0eeee7af" + "sha256": "b321f177db28da08326cd90cdc522f02bac960fffc5ca187bc3d81d6492881e5" }, { "path": "bootstrap/icons.py", @@ -42,6 +42,142 @@ "path": "bootstrap/worker-runtime.mjs", "sha256": "0f9fbb6ec4db48fb7f7c4b779a0494e95d5411e868b36e1e163e5173fcc34557" }, + { + "path": "frame/backdrops/0wFwSZn6I-I-thumb.jpg", + "sha256": "c8961c9ccbbd9bdaee0a88f2027377381212b14644ff2bee70c6007459eac71d" + }, + { + "path": "frame/backdrops/0wFwSZn6I-I.jpg", + "sha256": "d616103b46592c280e76d9d695badb8032d6c03f68b5c303ce1e0bd65165b0e8" + }, + { + "path": "frame/backdrops/9wH624ALFQA-thumb.jpg", + "sha256": "6b39d5ba401eff06271c185cca078a395bf6fa4836f253ec074fd4c149cd4a66" + }, + { + "path": "frame/backdrops/9wH624ALFQA.jpg", + "sha256": "ba35adf7f14f9a37838c6cb35f81795f8030f8a7bb0f992f28502e03d5c6e82c" + }, + { + "path": "frame/backdrops/E0AHdsENmDg-thumb.jpg", + "sha256": "e2cd6180c72ddb1d9e1f7838204c94e79ae127b11ba625447b7a70b6bbb0773a" + }, + { + "path": "frame/backdrops/E0AHdsENmDg.jpg", + "sha256": "e43adbb89d2ec19ca6ef570f6bfae4ac6daf39a31348a9c73d5edee573a588f1" + }, + { + "path": "frame/backdrops/Q1p7bh3SHj8-thumb.jpg", + "sha256": "234cbde53f0217585749554b772df6e613bba795dfec18347e1f00f8f33fa3f9" + }, + { + "path": "frame/backdrops/Q1p7bh3SHj8.jpg", + "sha256": "99e71e2c73a4b3e19fb98108f9dce81f8c81b71cb0c8de3e2afc9649f744f881" + }, + { + "path": "frame/backdrops/RF4p4rTM-2s-thumb.jpg", + "sha256": "ed50607638da713b855be09e3c99cb051bf6d87c1cab1d147888412bbde22e20" + }, + { + "path": "frame/backdrops/RF4p4rTM-2s.jpg", + "sha256": "e007bac1d872fb541d27181442500d371b27d39aea3fc48db7f757f77a1caa05" + }, + { + "path": "frame/backdrops/cZgVpseeazg-thumb.jpg", + "sha256": "8f107db205151bab41e10df89d7fffe9a13caab11c775d623e2e108f6f04c25e" + }, + { + "path": "frame/backdrops/cZgVpseeazg.jpg", + "sha256": "b061c0f02fbded1a50a006ad4d8ecd4af0718e042dbbef6326d92cf7dc80a00f" + }, + { + "path": "frame/backdrops/oMcTmNHclZI-thumb.jpg", + "sha256": "5de0d7fa4c32c83bea4360602ef751cd0f97d1fa46f77f4e3010bb237ed4aa5a" + }, + { + "path": "frame/backdrops/oMcTmNHclZI.jpg", + "sha256": "413274ffeb758961fa77f0eec0d9c71526a0cb54333edb92f17e5896b1e8bbec" + }, + { + "path": "frame/backdrops/qtRF_RxCAo0-thumb.jpg", + "sha256": "4bd016b2ad3a6119d08139e61346081ad18781fba39df7a8026f5f31333dbaa3" + }, + { + "path": "frame/backdrops/qtRF_RxCAo0.jpg", + "sha256": "be36adbed5035b15a41206d64812754dae4c246324af525059372385dedc18b7" + }, + { + "path": "frame/backdrops/t7EL2iG3jMc-thumb.jpg", + "sha256": "db1465c0d30a65e5d4279a4644dc1d6a488c378b4bb43fcde714f6fbb251af7f" + }, + { + "path": "frame/backdrops/t7EL2iG3jMc.jpg", + "sha256": "6f59cde71fb09b6a5faa92b1f9a77c0a300c0e4f9e6469574e54e14e85801d29" + }, + { + "path": "frame/frame.css", + "sha256": "c7470fdcbdb0ca9c6e2a634b6ec4ba9f1ed87c39b737f91e082b8c6466ab91f4" + }, + { + "path": "frame/frame.mjs", + "sha256": "208994058dcc6c70a91d590c345cb4956eda3532096f298f0a21f809f11672c1" + }, + { + "path": "frame/panels.css", + "sha256": "9b6bcd85303139ddaac9b2cbde7b7d3ef61d34da336874774073124b2560d8ce" + }, + { + "path": "frame/panels.mjs", + "sha256": "f2db1617f0a6d14e4447c54bafc7aeb45c7cb152b0f5a0b27b5615f8ce8d7b92" + }, + { + "path": "frame/publish.mjs", + "sha256": "faaaca350d15e0a0fb90311f810f1cf322ec790d6e0739c90489caa5cd857dd9" + }, + { + "path": "frame/unsplash/.gitignore", + "sha256": "f7041b5e6a86198e0b2dc26f8c45a303e4b75ccfd783928d935f6212ace66b49" + }, + { + "path": "frame/unsplash/README.md", + "sha256": "1cc50248e5565a8c57be54bc98caa62b243c0032de1ba69e6df8be379a17ed1c" + }, + { + "path": "frame/unsplash/worker.mjs", + "sha256": "fe0b48820ecf03c6ee440dd5bc647e16a81f70e27fc7b09890429309f067b1de" + }, + { + "path": "frame/unsplash/wrangler.toml", + "sha256": "90969e5589949ba52a523733d2178ca711f2794094bda8d65b105d3590865b1f" + }, + { + "path": "identity/PROTOCOL.md", + "sha256": "1e3a042a4a100683e0df5bc8210c367785e844feb63cd561d591979733e7ff82" + }, + { + "path": "identity/README.md", + "sha256": "351d9387fbc8fac0123f13a2e03e03aba8a4c0aed8e38f6040973bec4246fef1" + }, + { + "path": "identity/dev.mjs", + "sha256": "422bb2f4eba2f7aef47d6ffab1dabd1699c92eef0883e9c651f8e0a3f63beac0" + }, + { + "path": "identity/prism-id.mjs", + "sha256": "68482230e97b35a042295ec003687e745b34ba92275f0fc6a671bc1510f6d0d0" + }, + { + "path": "identity/stitch-sync.mjs", + "sha256": "65f88ef47fc11ab4d9adcac1488169cf169d1bc69e80f5406e90e71ae367f4a1" + }, + { + "path": "identity/stitch.lock", + "sha256": "0ecf5b500675c268d486bbd111246f2087ce0ec79c57540fe635089c6d7a3d0c" + }, + { + "path": "identity/test.mjs", + "sha256": "21cb6924014c80f378abf5d07720a203c7e62aa99ffd38e05f6d8376153317f9" + }, { "path": "lighthouserc.json", "sha256": "85aa0f6219cb8396b34f5b461c1d4d7b149e4cc1674cbd2f0100c5b5e16636d9" diff --git a/xtask/src/audit.rs b/xtask/src/audit.rs index 651622a..da732c9 100644 --- a/xtask/src/audit.rs +++ b/xtask/src/audit.rs @@ -265,3 +265,504 @@ fn gather_all(dir: &Path, out: &mut Vec) -> Result<(), Fail> { } Ok(()) } + +/// Only Prism is implemented here. +/// +/// This product is a Prism model: behavior is written in LexLean (`*.lex.tex`), checked by Lean and +/// built by PrismPM. Everything else that executes, hand-written Rust, TypeScript, JavaScript, +/// Python, shell, CSS or HTML, is non-Prism implementation, and it may only shrink. This is the +/// shrink-only ratchet of `afflom/rule30` (Python may not grow) and `afflom/verdant-resonance` +/// (hand-written modules may not grow), applied to every non-Prism language at once. +/// +/// The ceiling is the commit's first parent, measured, not a recorded number: on a pull request +/// or merge queue run the checked-out commit is a merge whose first parent is the base branch, +/// and on main it is the previous main. So a removal tightens the ceiling the moment it merges, +/// with no baseline file to regenerate, and a ceiling cannot be raised by editing one. +/// +/// Refused: a non-Prism file the parent does not have (author it in LexLean instead), and any +/// net growth in non-Prism lines. Lines are non-blank and outside comments, so explaining a +/// decision costs nothing. Prism output that a Prism lock binds byte for byte is Prism's own +/// and is not counted: the frame `frame.lock` pins to the template, and the Prism id +/// `identity/stitch.lock` generates from stitch's model. A bound file whose bytes differ from its +/// lock is counted. +pub mod prism { + use std::collections::BTreeMap; + use std::io::{BufRead, BufReader, Read, Write}; + use std::path::Path; + use std::process::{Command, Stdio}; + + use sha2::{Digest, Sha256}; + + use crate::Fail; + + /// Non-Prism implementation, by extension, with the comment syntax its lines are counted under. + const LANGUAGES: [(&str, Comments); 20] = [ + ("rs", Comments::C), + ("ts", Comments::C), + ("tsx", Comments::C), + ("mts", Comments::C), + ("cts", Comments::C), + ("js", Comments::C), + ("mjs", Comments::C), + ("cjs", Comments::C), + ("jsx", Comments::C), + ("css", Comments::C), + ("scss", Comments::C), + ("c", Comments::C), + ("h", Comments::C), + ("cpp", Comments::C), + ("html", Comments::Html), + ("py", Comments::Hash), + ("sh", Comments::Hash), + ("bash", Comments::Hash), + ("awk", Comments::Hash), + ("lean", Comments::Lean), + ]; + + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + enum Comments { + /// `//` lines and `/* */` blocks. + C, + /// `#` lines. + Hash, + /// `--` lines and `/- -/` blocks. + Lean, + /// `` blocks. + Html, + } + + fn language(path: &str) -> Option { + let name = path.rsplit('/').next().unwrap_or(path); + let (_, extension) = name.rsplit_once('.')?; + LANGUAGES + .iter() + .find(|(e, _)| *e == extension) + .map(|(_, c)| *c) + } + + /// Non-blank lines outside comments. A line that starts inside a block comment and ends it + /// counts only if code follows the close. + fn count_lines(text: &str, comments: Comments) -> usize { + let (line, open, close) = match comments { + Comments::C => (Some("//"), Some("/*"), Some("*/")), + Comments::Hash => (Some("#"), None, None), + Comments::Lean => (Some("--"), Some("/-"), Some("-/")), + Comments::Html => (None, Some("")), + }; + let mut in_block = false; + let mut count = 0; + for raw in text.lines() { + let mut rest = raw.trim(); + if in_block { + match close.and_then(|c| rest.find(c).map(|i| i + c.len())) { + Some(end) => { + in_block = false; + rest = rest[end..].trim(); + } + None => continue, + } + } + while let (Some(o), Some(c)) = (open, close) { + let Some(after) = rest.strip_prefix(o) else { + break; + }; + match after.find(c) { + Some(end) => rest = after[end + c.len()..].trim(), + None => { + in_block = true; + rest = ""; + } + } + } + if rest.is_empty() || line.is_some_and(|l| rest.starts_with(l)) { + continue; + } + count += 1; + } + count + } + + /// The locks that bind Prism output: each `files` entry and the `output` entry name a path + /// and the digest its bytes must have. + const PRISM_LOCKS: [&str; 2] = ["frame.lock", "identity/stitch.lock"]; + + /// How a commit's `xtask/src/audit.rs` shows it runs this gate. + const GATE: &[u8] = b"pub mod prism {"; + + /// Paths the Prism locks bind, with the digest each must have. `read` answers a lock's text, + /// or `None` where the tree has no such lock. + fn bound( + mut read: impl FnMut(&str) -> Result, Fail>, + ) -> Result, Fail> { + let mut out = BTreeMap::new(); + for name in PRISM_LOCKS { + let Some(text) = read(name)? else { + continue; + }; + let lock: serde_json::Value = serde_json::from_str(&text)?; + // A lock binds output only when it names where the output comes from. The template's + // own frame.lock has no source: there the frame is the template's implementation. + let upstream = lock["source"]["repository"] + .as_str() + .or(lock["repository"].as_str()); + if upstream.is_none_or(str::is_empty) { + continue; + } + let files = lock["files"].as_array().into_iter().flatten(); + for entry in files.chain(lock.get("output")) { + let (Some(path), Some(sha256)) = (entry["path"].as_str(), entry["sha256"].as_str()) + else { + return Err(format!("{name}: an entry without a path and a sha256").into()); + }; + out.insert(path.to_string(), sha256.to_string()); + } + } + Ok(out) + } + + /// Non-Prism lines per file of one tree. + #[derive(Default, Debug)] + struct Measure { + files: BTreeMap, + } + + impl Measure { + fn total(&self) -> usize { + self.files.values().sum() + } + + /// Adds `path` if it is non-Prism implementation. + fn add(&mut self, path: &str, bytes: &[u8], frame: &BTreeMap) { + let Some(comments) = language(path) else { + return; + }; + if frame + .get(path) + .is_some_and(|sha256| *sha256 == hex(&Sha256::digest(bytes))) + { + return; + } + let lines = count_lines(&String::from_utf8_lossy(bytes), comments); + self.files.insert(path.to_string(), lines); + } + } + + fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() + } + + /// The ratchet itself: what `current` adds over `ceiling`, or nothing. + fn refusals(ceiling: &Measure, current: &Measure) -> Vec { + let mut out = Vec::new(); + let added: Vec<&String> = current + .files + .keys() + .filter(|path| !ceiling.files.contains_key(*path)) + .collect(); + if !added.is_empty() { + let shown: Vec<&str> = added.iter().take(20).map(|p| p.as_str()).collect(); + out.push(format!( + "{} new non-Prism file(s): {}{}. Author the behavior in LexLean (`*.lex.tex`) so PrismPM builds it.", + added.len(), + shown.join(", "), + if added.len() > shown.len() { ", ..." } else { "" } + )); + } + let (now, before) = (current.total(), ceiling.total()); + if now > before { + let mut grown: Vec<(&String, usize)> = current + .files + .iter() + .filter_map(|(path, &n)| { + let was = ceiling.files.get(path).copied().unwrap_or(0); + n.checked_sub(was).filter(|d| *d > 0).map(|d| (path, d)) + }) + .collect(); + grown.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let shown: Vec = grown + .iter() + .take(10) + .map(|(p, n)| format!("{p} +{n}")) + .collect(); + out.push(format!( + "non-Prism implementation grew by {} lines ({before} to {now}); grown: {}. It may only shrink: move the logic into the Prism model, or delete as much as you add.", + now - before, + shown.join(", ") + )); + } + out + } + + fn git(root: &Path, args: &[&str]) -> Result, Fail> { + let out = Command::new("git").current_dir(root).args(args).output()?; + if !out.status.success() { + return Err(format!( + "git {}: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ) + .into()); + } + Ok(out.stdout) + } + + /// The working tree's tracked files. + fn measure_worktree(root: &Path) -> Result { + let frame = bound(|name| match std::fs::read_to_string(root.join(name)) { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + })?; + let mut measure = Measure::default(); + for path in git(root, &["ls-files", "-z", "--cached"])?.split(|b| *b == 0) { + let path = std::str::from_utf8(path)?; + if path.is_empty() || language(path).is_none() { + continue; + } + let full = root.join(path); + // A symlink is not implementation of its own, and a path deleted but not yet staged is + // gone. + if full.is_symlink() || !full.is_file() { + continue; + } + measure.add(path, &std::fs::read(&full)?, &frame); + } + Ok(measure) + } + + /// A commit's tree, read from the object store. + fn measure_commit(root: &Path, commit: &str) -> Result { + let frame = bound( + |name| match git(root, &["show", &format!("{commit}:{name}")]) { + Ok(text) => Ok(Some(String::from_utf8(text)?)), + Err(_) => Ok(None), + }, + )?; + let listing = git(root, &["ls-tree", "-r", "-z", commit])?; + let mut blobs = Vec::new(); + for entry in listing.split(|b| *b == 0) { + let entry = std::str::from_utf8(entry)?; + let Some((meta, path)) = entry.split_once('\t') else { + continue; + }; + let fields: Vec<&str> = meta.split(' ').collect(); + if fields.len() == 3 + && fields[0] != "120000" + && fields[1] == "blob" + && language(path).is_some() + { + blobs.push((fields[2].to_string(), path.to_string())); + } + } + + let mut child = Command::new("git") + .current_dir(root) + .args(["cat-file", "--batch"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn()?; + let mut stdin = child.stdin.take().ok_or("git cat-file: no stdin")?; + let ids: Vec = blobs.iter().map(|(id, _)| id.clone()).collect(); + // Written from a thread so that a full output pipe cannot stall the request. + let writer = std::thread::spawn(move || -> std::io::Result<()> { + for id in ids { + writeln!(stdin, "{id}")?; + } + Ok(()) + }); + let mut reader = BufReader::new(child.stdout.take().ok_or("git cat-file: no stdout")?); + let mut measure = Measure::default(); + for (_, path) in &blobs { + let mut header = String::new(); + reader.read_line(&mut header)?; + let size: usize = header + .split(' ') + .nth(2) + .and_then(|s| s.trim().parse().ok()) + .ok_or_else(|| format!("git cat-file: unexpected header {header:?} for {path}"))?; + let mut bytes = vec![0; size + 1]; + reader.read_exact(&mut bytes)?; + bytes.truncate(size); + measure.add(path, &bytes, &frame); + } + writer + .join() + .map_err(|_| "git cat-file: writer panicked")??; + child.wait()?; + Ok(measure) + } + + pub fn audit(root: &Path) -> Result<(), Fail> { + let current = measure_worktree(root)?; + let parent = git(root, &["rev-parse", "--verify", "-q", "HEAD^1^{commit}"]); + let Ok(parent) = parent else { + // A shallow clone hides the parent rather than lacking one: that is a gate that cannot + // see its ceiling, and it must not pass. + if git(root, &["rev-parse", "--is-shallow-repository"])?.starts_with(b"true") { + return Err("audit-prism: the clone is shallow, so the parent commit, the ratchet's ceiling, cannot be read; check out with full history".into()); + } + println!( + "audit-prism: a root commit; non-Prism implementation is {} lines in {} files", + current.total(), + current.files.len() + ); + return Ok(()); + }; + let parent = String::from_utf8(parent)?.trim().to_string(); + // The ratchet starts at the commit that installs it: a parent without this gate set no + // ceiling. Removing the gate needs a change that deletes it, which this does not open. + let gated = git(root, &["show", &format!("{parent}:xtask/src/audit.rs")]) + .is_ok_and(|source| source.windows(GATE.len()).any(|w| w == GATE)); + if !gated { + println!( + "audit-prism: installed here; the parent ran no ratchet, so this commit sets the ceiling: {} lines in {} files", + current.total(), + current.files.len() + ); + return Ok(()); + } + let ceiling = measure_commit(root, &parent)?; + let refused = refusals(&ceiling, ¤t); + if !refused.is_empty() { + return Err(format!( + "audit-prism: only Prism may be implemented here, measured against {}:\n - {}", + &parent[..12.min(parent.len())], + refused.join("\n - ") + ) + .into()); + } + println!( + "audit-prism: non-Prism implementation is {} lines in {} files ({} lines, {} files in the parent); it only shrinks", + current.total(), + current.files.len(), + ceiling.total(), + ceiling.files.len() + ); + Ok(()) + } + + #[cfg(test)] + mod tests { + use super::*; + + fn measure(files: &[(&str, &str)]) -> Measure { + let mut m = Measure::default(); + for (path, text) in files { + m.add(path, text.as_bytes(), &BTreeMap::new()); + } + m + } + + #[test] + fn counts_code_not_comments_or_blank_lines() { + let rust = "// why\n/* a\n block */\nfn a() {}\n\n/* x */ let b = 1;\n"; + assert_eq!(count_lines(rust, Comments::C), 2); + assert_eq!( + count_lines("#!/bin/sh\n# why\necho hi\n", Comments::Hash), + 1 + ); + assert_eq!( + count_lines("/- doc\n-/\n-- x\ndef a := 1\n", Comments::Lean), + 1 + ); + assert_eq!(count_lines("\n

a

\n", Comments::Html), 1); + } + + #[test] + fn prism_and_data_are_not_counted() { + let m = measure(&[ + ("app/src/Kernel.lex.tex", "def a := 1\n"), + ("model/ids.toml", "x = 1\n"), + ("app/product.json", "{}\n"), + ("studio/a.mjs", "export {}\n"), + ]); + assert_eq!(m.files.keys().collect::>(), ["studio/a.mjs"]); + } + + #[test] + fn locks_bind_frame_files_and_generated_output() { + let frame = r#"{"source": {"repository": "UOR-Foundation/template"}, "files": [{"path": "site/app.mjs", "sha256": "aa"}]}"#; + let stitch = r#"{"repository": "afflom/stitch", "output": {"path": "identity/prism-id.mjs", "sha256": "bb"}}"#; + let locks = bound(|name| { + Ok(match name { + "frame.lock" => Some(frame.to_string()), + "identity/stitch.lock" => Some(stitch.to_string()), + _ => None, + }) + }) + .unwrap(); + assert_eq!(locks.get("site/app.mjs").map(String::as_str), Some("aa")); + assert_eq!( + locks.get("identity/prism-id.mjs").map(String::as_str), + Some("bb") + ); + let bad = r#"{"repository": "afflom/stitch", "files": [{"path": "x"}]}"#; + assert!(bound(|_| Ok(Some(bad.to_string()))).is_err()); + // The template's own frame.lock names no source, so it binds nothing. + let own = r#"{"files": [{"path": "site/app.mjs", "sha256": "aa"}]}"#; + assert!(bound(|_| Ok(Some(own.to_string()))).unwrap().is_empty()); + } + + #[test] + fn frame_counts_only_while_its_bytes_match_the_lock() { + let bytes = b"export const a = 1;\n"; + let lock = BTreeMap::from([("site/app.mjs".to_string(), hex(&Sha256::digest(bytes)))]); + let mut m = Measure::default(); + m.add("site/app.mjs", bytes, &lock); + assert!(m.files.is_empty()); + m.add("site/app.mjs", b"export const a = 2;\nlet b;\n", &lock); + assert_eq!(m.total(), 2); + } + + // The planted defects: each must be refused. + #[test] + fn refuses_a_new_non_prism_file() { + let before = measure(&[("studio/a.mjs", "a()\nb()\n")]); + let after = measure(&[("studio/a.mjs", "a()\n"), ("studio/b.ts", "b()\n")]); + let refused = refusals(&before, &after); + assert_eq!(refused.len(), 1); + assert!(refused[0].contains("studio/b.ts")); + } + + #[test] + fn refuses_net_growth() { + let before = measure(&[("studio/a.mjs", "a()\n"), ("crates/x.rs", "x();\n")]); + let after = measure(&[("studio/a.mjs", "a()\nb()\nc()\n")]); + let refused = refusals(&before, &after); + assert_eq!(refused.len(), 1); + assert!( + refused[0].contains("grew by 1 lines (2 to 3)"), + "{refused:?}" + ); + assert!(refused[0].contains("studio/a.mjs +2")); + } + + #[test] + fn names_what_grew_when_another_file_shrank() { + let before = measure(&[("studio/a.mjs", "a()\nb()\n"), ("studio/c.mjs", "c()\n")]); + let after = measure(&[ + ("studio/a.mjs", "a()\n"), + ("studio/c.mjs", "c()\nd()\ne()\nf()\n"), + ]); + let refused = refusals(&before, &after); + assert_eq!(refused.len(), 1); + assert!(refused[0].contains("studio/c.mjs +3"), "{refused:?}"); + assert!(!refused[0].contains("studio/a.mjs"), "{refused:?}"); + } + + #[test] + fn admits_shrinking_and_growth_paid_for_by_deletion() { + let before = measure(&[("studio/a.mjs", "a()\nb()\n"), ("studio/c.mjs", "c()\n")]); + let after = measure(&[("studio/a.mjs", "a()\nb()\nd()\n")]); + assert!(refusals(&before, &after).is_empty()); + assert!(refusals(&before, &measure(&[])).is_empty()); + } + + #[test] + fn a_comment_or_a_blank_line_is_free() { + let before = measure(&[("studio/a.mjs", "a()\n")]); + let after = measure(&[("studio/a.mjs", "// why a\n\na()\n")]); + assert!(refusals(&before, &after).is_empty()); + } + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index e1cfe49..b46051b 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -27,6 +27,7 @@ fn main() -> ExitCode { "audit-deferral" => audit::audit_deferral(&root), "audit-bootstrap" => bootstrap::audit(&root), "audit-dependency-updates" => bootstrap::audit_dependency_updates(&root), + "audit-prism" => audit::prism::audit(&root), "validate" => validate(&root), "new-capability" => { let args: Vec = std::env::args().skip(2).collect(); @@ -41,6 +42,7 @@ fn main() -> ExitCode { audit-deferral R4: no deferral marker, no stub, no capability behind a flag\n\ audit-bootstrap immutable SDK and least-privilege workflow trust root\n\ audit-dependency-updates SDK ownership and ordinary dependency maintenance\n\ + audit-prism only Prism is implemented: non-Prism code may only shrink\n\ validate run every gate above\n\ new-capability \n\ R3: write the register row, scenario and failing test\n\ @@ -106,6 +108,7 @@ fn validate(root: &Path) -> Result<(), Fail> { audit::audit_limits(root)?; audit::audit_deferral(root)?; bootstrap::audit(root)?; + audit::prism::audit(root)?; println!("validate: every gate passed"); Ok(()) }