The design language that makes your AI harness better at design.
JavaScript
Keep the approved comp a fixed reference every gate verifies (#936)
Paul Bakaus4bc74df2e34c
diff --git a/crates/comp-verbs/src/approved_comp.rs b/crates/comp-verbs/src/approved_comp.rsnew file mode 100644index 000000000..a68d5a10c--- /dev/null+++ b/crates/comp-verbs/src/approved_comp.rs@@ -0,0 +1,371 @@+//! The approved comp as a fixed reference.+//!+//! Every comp-led gate measures against the comp the user approved. The comp+//! sits at an editable path under `.impeccable/mocks/`, so an agent can edit it+//! (composite its own plates into it, regenerate it) until the reference matches+//! the work, and then re-run `comp-spec` to move the spec's `compSha256` along+//! with it. This module keeps the approved pixels out of reach of that loop:+//!+//! - when a comp is approved (`build-phase start --comp`, the comps gate+//! closing, or the first spec written for the build's comp) the engine keeps a+//! byte copy at `.impeccable/build/approved-comp.<ext>` and records its pixel+//! hash (the same identity `comp-spec` writes as `compSha256`) in+//! `.impeccable/build/approved-comp.json`;+//! - every entry point that measures against the comp calls [`issue`] first and+//! refuses, without measuring, when the comp's pixels no longer match;+//! - `build-phase restore-comp` puts the kept copy back.+//!+//! Gates refuse rather than silently measure against the copy: the agent, the+//! crop and font tools, the comp-diff verb and the finish reviewer all read the+//! editable path, so the only consistent reference is an editable path that+//! holds the approved pixels. A silent swap would score plates and code against+//! one image while the agent keeps looking at another.++use std::path::{Path, PathBuf};++use impeccable_common::Io;+use impeccable_comp::png_io;+use impeccable_comp::raster::Image;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};++use crate::comp_spec::{BUILD_DIR, SPEC_PATH};++pub const RECORD_PATH: &str = ".impeccable/build/approved-comp.json";+const COPY_STEM: &str = "approved-comp";++/// The comp identity `comp-spec` records as `compSha256`: dimensions plus+/// decoded RGBA, so a metadata-only rewrite (embed-prompt) keeps the identity.+pub fn pixel_sha256(img: &Image) -> String {+ let mut hasher = Sha256::new();+ hasher.update(img.width.to_le_bytes());+ hasher.update(img.height.to_le_bytes());+ hasher.update(&img.data);+ format!("{:x}", hasher.finalize())+}++fn resolve(io: &Io, p: &str) -> PathBuf {+ let path = Path::new(p);+ if path.is_absolute() { path.to_path_buf() } else { io.cwd.join(path) }+}++pub fn same_file(io: &Io, a: &str, b: &str) -> bool {+ let (a, b) = (resolve(io, a), resolve(io, b));+ match (a.canonicalize(), b.canonicalize()) {+ (Ok(x), Ok(y)) => x == y,+ _ => a.components().eq(b.components()),+ }+}++/// The comp as comp-spec, the record and every check see it: decoded from the+/// file's own bytes, never from the sibling PNG cache `load_raster` keeps for a+/// WebP or JPEG source (an edit to the source never refreshes it).+pub fn decode_comp(bytes: &[u8]) -> Option<Image> {+ png_io::decode_source(bytes).ok()+}++fn bytes_pixel_sha256(bytes: &[u8]) -> Option<String> {+ decode_comp(bytes).map(|img| pixel_sha256(&img))+}++/// The pixel hash of the file at `comp`, or `None` when it is missing or not a+/// decodable image (the callers' own unreadable-comp handling speaks then).+pub fn file_pixel_sha256(io: &Io, comp: &str) -> Option<String> {+ bytes_pixel_sha256(&std::fs::read(resolve(io, comp)).ok()?)+}++fn load_record(io: &Io) -> Option<Value> {+ let raw = std::fs::read_to_string(resolve(io, RECORD_PATH)).ok()?;+ serde_json::from_str::<Value>(&raw).ok().filter(|r| r["comp"].is_string() && r["pixelSha256"].is_string())+}++/// The record for `comp`, when the engine kept one for that file.+fn record_for(io: &Io, comp: &str) -> Option<Value> {+ load_record(io).filter(|r| same_file(io, r["comp"].as_str().unwrap_or(""), comp))+}++/// Keep a byte copy of `comp` as the approved reference and record its hash.+/// `Ok(None)` when the file cannot be read or decoded (nothing to keep);+/// `Err` when the copy or record cannot be written, which approval refuses on.+pub fn keep(io: &Io, comp: &str) -> Result<Option<Value>, String> {+ let Ok(bytes) = std::fs::read(resolve(io, comp)) else { return Ok(None) };+ let Some(pixels) = bytes_pixel_sha256(&bytes) else { return Ok(None) };+ let ext = Path::new(comp).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase)+ .filter(|e| e.chars().all(|c| c.is_ascii_alphanumeric())).unwrap_or_else(|| "png".into());+ let copy = format!("{BUILD_DIR}/{COPY_STEM}.{ext}");+ let failed = |what: &str, e: std::io::Error| format!("cannot keep the approved comp: writing {what} failed ({e})");+ std::fs::create_dir_all(resolve(io, BUILD_DIR)).map_err(|e| failed(BUILD_DIR, e))?;+ std::fs::write(resolve(io, ©), &bytes).map_err(|e| failed(©, e))?;+ let record = json!({+ "comp": comp,+ "pixelSha256": pixels,+ "fileSha256": format!("{:x}", Sha256::digest(&bytes)),+ "copy": copy,+ "at": crate::util::iso_now(),+ });+ std::fs::write(resolve(io, RECORD_PATH), crate::util::json_pretty(&record)).map_err(|e| failed(RECORD_PATH, e))?;+ Ok(Some(record))+}++/// Forget the kept reference (a build restarted on a new comp round).+pub fn forget(io: &Io) {+ let _ = std::fs::remove_file(resolve(io, RECORD_PATH));+}++/// Whether the kept copy still decodes to the recorded hash.+fn copy_intact(io: &Io, record: &Value) -> Option<String> {+ let copy = record["copy"].as_str()?;+ (file_pixel_sha256(io, copy).as_deref() == record["pixelSha256"].as_str()).then(|| copy.to_string())+}++const FIXED: &str = "The approved comp is the fixed reference every gate measures against; never edit it, composite into it, or regenerate it.";++fn remedy(io: &Io, record: Option<&Value>, s: &str) -> String {+ match record.and_then(|r| copy_intact(io, r)) {+ Some(copy) => format!("Restore it with {s} build-phase restore-comp (the engine kept the approved copy at {copy}), then regenerate the plates or change the page code until they match the unchanged comp."),+ None => "No intact engine copy exists for this build: restore the approved file from its original source, then regenerate the plates or change the page code until they match the unchanged comp.".to_string(),+ }+}++fn changed_message(io: &Io, comp: &str, expected: &str, actual: Option<&str>, record: Option<&Value>, s: &str) -> String {+ let found = match actual {+ Some(actual) => format!("has changed since approval: expected pixel sha256 {expected}, found {actual}"),+ None => format!("is missing or not a decodable image: expected pixel sha256 {expected}"),+ };+ format!("the approved comp {comp} {found}. {FIXED} Nothing was measured against the changed file. {}", remedy(io, record, s))+}++/// The refusal owed before anything measures against the spec's comp, or+/// `None` when the comp still holds the approved pixels (or has no recorded+/// identity at all: no comp, or a legacy spec with neither a record nor a+/// `compSha256`). It writes nothing; [`build_issue`] keeps a build's first copy.+/// [`issue`] for the spec read from `spec_path`: the build's own spec gets+/// [`build_issue`], any other spec only the pixel check for the comp it names.+pub fn issue_at(io: &Io, spec: &Value, spec_path: &str, s: &str) -> Option<String> {+ if same_file(io, spec_path, SPEC_PATH) { build_issue(io, spec, s) } else { issue(io, spec, s) }+}++/// [`issue`] for the build's own spec (`.impeccable/build/spec.json`): it must+/// also measure the recorded approved comp, not another file (a composite+/// saved under a new name and re-specced is not the build's reference).+pub fn build_issue(io: &Io, spec: &Value, s: &str) -> Option<String> {+ let comp = spec.get("comp").and_then(Value::as_str)?;+ if record_for(io, comp).is_none() {+ if let Some(other) = load_record(io) {+ let approved = other["comp"].as_str().unwrap_or("");+ return Some(format!(+ "{SPEC_PATH} measures {comp}, but the approved comp is {approved}. {FIXED} Re-run {s} comp-spec --comp {approved} --regions <regions file> on the approved comp; a comp the user newly approves is saved under a new file name and started with {s} build-phase start --reset --comp <new file>."+ ));+ }+ }+ let why = issue(io, spec, s);+ // A build with no kept copy yet gets one here, from its own spec only and+ // only once the comp matches it; never from a spec at another path.+ if why.is_none() && load_record(io).is_none() && spec.get("compSha256").and_then(Value::as_str).is_some() {+ let _ = keep(io, comp);+ }+ why+}++pub fn issue(io: &Io, spec: &Value, s: &str) -> Option<String> {+ let comp = spec.get("comp").and_then(Value::as_str)?;+ let spec_hash = spec.get("compSha256").and_then(Value::as_str);+ let record = record_for(io, comp);+ if record.is_none() && spec_hash.is_none() { return None; }+ let actual = file_pixel_sha256(io, comp);+ match record {+ Some(record) => {+ let expected = record["pixelSha256"].as_str().unwrap_or("");+ if actual.as_deref() != Some(expected) {+ return Some(changed_message(io, comp, expected, actual.as_deref(), Some(&record), s));+ }+ match spec_hash {+ Some(hash) if hash != expected => Some(format!(+ "{SPEC_PATH} was measured on an image that is not the approved comp (spec compSha256 {hash}, approved {expected}): re-measuring an edited comp does not move the reference. {FIXED} Re-run {s} comp-spec --comp {comp} --regions <regions file> on the approved comp, then regenerate the plates or change the page code until they match it."+ )),+ _ => None,+ }+ }+ None => {+ let expected = spec_hash?;+ if actual.as_deref() != Some(expected) {+ return Some(changed_message(io, comp, expected, actual.as_deref(), None, s));+ }+ None+ }+ }+}++/// The refusal for a comparison against `comp` with no spec that names it:+/// only a record kept for that file can say what its pixels should be.+pub fn issue_for_comp(io: &Io, comp: &str, s: &str) -> Option<String> {+ let record = record_for(io, comp)?;+ let expected = record["pixelSha256"].as_str().unwrap_or("");+ let actual = file_pixel_sha256(io, comp);+ (actual.as_deref() != Some(expected)).then(|| changed_message(io, comp, expected, actual.as_deref(), Some(&record), s))+}++/// `comp-spec --regions` on the build's comp: refuse to re-measure a comp whose+/// pixels differ from the approved ones, and keep the reference when the build+/// has none yet. `actual` is the pixel hash of the comp comp-spec read and+/// `previous` the spec it is about to replace: a build that predates the record+/// is checked against that spec's `compSha256` before its pixels are kept. A+/// comp no build state names (a mapping-only run) is not guarded.+pub fn spec_refusal(io: &Io, comp: &str, actual: &str, previous: Option<&Value>, s: &str) -> Option<String> {+ let state = std::fs::read_to_string(resolve(io, &format!("{BUILD_DIR}/state.json"))).ok()+ .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())?;+ if !state["comp"].as_str().is_some_and(|c| same_file(io, c, comp)) { return None; }+ if let Some(record) = record_for(io, comp) {+ let expected = record["pixelSha256"].as_str().unwrap_or("");+ return (actual != expected).then(|| changed_message(io, comp, expected, Some(actual), Some(&record), s));+ }+ let measured = previous.filter(|p| p["comp"].as_str().is_some_and(|c| same_file(io, c, comp)))+ .and_then(|p| p["compSha256"].as_str());+ if let Some(expected) = measured.filter(|h| *h != actual) {+ return Some(changed_message(io, comp, expected, Some(actual), None, s));+ }+ keep(io, comp).err().map(|e| format!("{e}; the build cannot fix its reference, so nothing was measured. Make {BUILD_DIR} writable and re-run."))+}++/// `build-phase start --reset --comp` on the file the engine kept as approved,+/// now holding other pixels: a newly approved comp gets a new file name, so+/// reusing the approved name for different pixels is refused.+pub fn restart_refusal(io: &Io, comp: &str, s: &str) -> Option<String> {+ let record = record_for(io, comp)?;+ let expected = record["pixelSha256"].as_str().unwrap_or("");+ let actual = file_pixel_sha256(io, comp)?;+ (actual != expected).then(|| format!(+ "{} A comp the user newly approves is saved under a new file name and started with {s} build-phase start --reset --comp <new file>.",+ changed_message(io, comp, expected, Some(&actual), Some(&record), s)+ ))+}++/// `build-phase restore-comp`: put the kept copy back at the comp path. The+/// edited file is moved under the build directory (never into the mocks, where+/// the comps gate would count it as a comp). Returns the message and exit code.+pub fn restore(io: &Io) -> (String, i32) {+ let Some(record) = load_record(io) else {+ return (format!("build-phase: restore-comp found no approved copy ({RECORD_PATH} is missing): restore the approved comp from its original source.\n"), 1);+ };+ let comp = record["comp"].as_str().unwrap_or("").to_string();+ let expected = record["pixelSha256"].as_str().unwrap_or("").to_string();+ let Some(copy) = copy_intact(io, &record) else {+ return (format!("build-phase: restore-comp refused: the kept copy {} no longer decodes to the approved pixel sha256 {expected}; restore the approved comp from its original source.\n", record["copy"].as_str().unwrap_or("(none)")), 2);+ };+ let current = file_pixel_sha256(io, &comp);+ if current.as_deref() == Some(expected.as_str()) {+ return (format!("comp {comp} already holds the approved pixels (sha256 {expected}); nothing restored\n"), 0);+ }+ let mut aside = None;+ if let Ok(edited) = std::fs::read(resolve(io, &comp)) {+ let tag = current.as_deref().map(|h| &h[..12]).unwrap_or("unreadable");+ let ext = Path::new(&comp).extension().and_then(|e| e.to_str()).unwrap_or("png");+ let path = format!("{BUILD_DIR}/edited-comp-{tag}.{ext}");+ if std::fs::write(resolve(io, &path), edited).is_err() {+ return (format!("build-phase: restore-comp could not keep the edited file at {path}; nothing restored\n"), 1);+ }+ aside = Some(path);+ }+ let bytes = match std::fs::read(resolve(io, ©)) { Ok(b) => b, Err(e) => return (format!("build-phase: restore-comp cannot read {copy}: {e}\n"), 1) };+ if let Some(parent) = resolve(io, &comp).parent() { let _ = std::fs::create_dir_all(parent); }+ if let Err(e) = std::fs::write(resolve(io, &comp), bytes) {+ return (format!("build-phase: restore-comp cannot write {comp}: {e}\n"), 1);+ }+ let kept = aside.map(|p| format!(" The edited file is kept at {p} as evidence, not as a comp.")).unwrap_or_default();+ (format!("RESTORED {comp} from {copy} (pixel sha256 {expected}).{kept} Re-run the step that refused; plates and page code built against the edited comp now have to match the approved one.\n"), 0)+}++#[cfg(test)]+mod tests {+ use super::*;+ use impeccable_comp::raster as r;++ fn ws() -> (Io, PathBuf) {+ static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+ let dir = std::env::temp_dir().join(format!("impeccable-approved-comp-{}-{}", std::process::id(),+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join(".impeccable/mocks")).unwrap();+ let (io, _) = Io::captured("", dir.clone(), Default::default());+ (io, dir)+ }++ fn png(color: [u8; 4]) -> Vec<u8> {+ png_io::encode_png(&r::create_image(8, 8, color), &[]).unwrap()+ }++ const COMP: &str = ".impeccable/mocks/comp-1.png";++ #[test]+ fn unchanged_comp_passes_and_a_metadata_rewrite_keeps_the_identity() {+ let (io, dir) = ws();+ std::fs::write(dir.join(COMP), png([10, 20, 30, 255])).unwrap();+ let record = keep(&io, COMP).unwrap().unwrap();+ let spec = json!({"comp": COMP, "compSha256": record["pixelSha256"]});+ assert_eq!(issue(&io, &spec, "impeccable"), None);+ let tagged = png_io::encode_png(&r::create_image(8, 8, [10, 20, 30, 255]), &[("prompt".into(), "x".into())]).unwrap();+ std::fs::write(dir.join(COMP), tagged).unwrap();+ assert_eq!(issue(&io, &spec, "impeccable"), None);+ }++ #[test]+ fn an_edited_comp_is_refused_with_both_hashes_and_restored_from_the_copy() {+ let (io, dir) = ws();+ std::fs::write(dir.join(COMP), png([10, 20, 30, 255])).unwrap();+ let record = keep(&io, COMP).unwrap().unwrap();+ let expected = record["pixelSha256"].as_str().unwrap().to_string();+ let spec = json!({"comp": COMP, "compSha256": expected});+ std::fs::write(dir.join(COMP), png([200, 20, 30, 255])).unwrap();+ let actual = file_pixel_sha256(&io, COMP).unwrap();+ let why = issue(&io, &spec, "impeccable").unwrap();+ assert!(why.contains(&expected) && why.contains(&actual), "{why}");+ assert!(why.contains("never edit it, composite into it, or regenerate it"), "{why}");+ assert!(why.contains("impeccable build-phase restore-comp"), "{why}");+ let (message, code) = restore(&io);+ assert_eq!(code, 0, "{message}");+ assert_eq!(file_pixel_sha256(&io, COMP).unwrap(), expected);+ assert!(dir.join(format!(".impeccable/build/edited-comp-{}.png", &actual[..12])).exists());+ assert_eq!(issue(&io, &spec, "impeccable"), None);+ assert_eq!(restore(&io).1, 0);+ }++ #[test]+ fn a_spec_remeasured_on_an_edited_comp_does_not_move_the_reference() {+ let (io, dir) = ws();+ std::fs::write(dir.join(COMP), png([10, 20, 30, 255])).unwrap();+ let record = keep(&io, COMP).unwrap().unwrap();+ let spec = json!({"comp": COMP, "compSha256": "0".repeat(64)});+ let why = issue(&io, &spec, "impeccable").unwrap();+ assert!(why.contains("not the approved comp") && why.contains(record["pixelSha256"].as_str().unwrap()), "{why}");+ }++ #[test]+ fn a_legacy_build_keeps_its_copy_on_first_check_and_refuses_without_one() {+ let (io, dir) = ws();+ std::fs::write(dir.join(COMP), png([10, 20, 30, 255])).unwrap();+ let hash = file_pixel_sha256(&io, COMP).unwrap();+ let spec = json!({"comp": COMP, "compSha256": hash});+ assert_eq!(issue(&io, &spec, "impeccable"), None);+ assert!(!dir.join(RECORD_PATH).exists(), "a spec at another path never pins the reference");+ assert_eq!(build_issue(&io, &spec, "impeccable"), None);+ assert!(dir.join(RECORD_PATH).exists() && dir.join(".impeccable/build/approved-comp.png").exists());+ forget(&io);+ std::fs::write(dir.join(COMP), png([1, 2, 3, 255])).unwrap();+ let why = issue(&io, &spec, "impeccable").unwrap();+ assert!(why.contains("No intact engine copy"), "{why}");+ assert_eq!(restore(&io).1, 1);+ // No recorded identity at all: nothing to check against.+ assert_eq!(issue(&io, &json!({"comp": COMP}), "impeccable"), None);+ }++ #[test]+ fn a_damaged_copy_is_never_restored() {+ let (io, dir) = ws();+ std::fs::write(dir.join(COMP), png([10, 20, 30, 255])).unwrap();+ keep(&io, COMP).unwrap().unwrap();+ std::fs::write(dir.join(".impeccable/build/approved-comp.png"), png([9, 9, 9, 255])).unwrap();+ std::fs::write(dir.join(COMP), png([200, 20, 30, 255])).unwrap();+ assert_eq!(restore(&io).1, 2);+ assert_eq!(file_pixel_sha256(&io, COMP), Some(pixel_sha256(&r::create_image(8, 8, [200, 20, 30, 255]))));+ }+}diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rsindex 824b7dcbc..2bea1f794 100644--- a/crates/comp-verbs/src/build_phase.rs+++ b/crates/comp-verbs/src/build_phase.rs@@ -57,7 +57,7 @@ fn abs(io: &Io, p: &str) -> PathBuf {}}-fn self_cmd(io: &Io) -> String {+pub(crate) fn self_cmd(io: &Io) -> String {let value = io.env.get("IMPECCABLE_SELF").filter(|v| !v.is_empty()).cloned().unwrap_or_else(|| "impeccable".to_string());// The skill launcher exports a raw filename; the npm shim exports a// command prefix such as `npx impeccable`. Quote only a complete filename,@@ -171,6 +171,8 @@ struct Gate {// plates: per-plate rowsplates: Option<Vec<Value>>,error: bool,+ // a failure no quoted --force may waive (the approved comp cannot be kept)+ unforceable: bool,}impl Gate {@@ -198,6 +200,7 @@ impl Gate {approved: None,plates: None,error: false,+ unforceable: false,}}/// The subset stored on the phase (JS: `const { plates, ...gateRecord } = gate`).@@ -325,6 +328,13 @@ fn gate_comps(io: &Io) -> Gate {g}+/// The approved-comp refusal for the measured spec, when there is one. Every+/// entry point that measures against the comp runs this before measuring.+fn comp_refusal(io: &Io) -> Option<String> {+ let spec = load_spec(&abs(io, SPEC_PATH))?;+ crate::approved_comp::build_issue(io, &spec, &self_cmd(io))+}+fn spec_regions(spec: &Value) -> Vec<Value> {spec.get("regions").and_then(Value::as_array).cloned().unwrap_or_default()}@@ -337,6 +347,7 @@ fn gate_spec(io: &Io, state: &Value) -> Gate {"no spec at {SPEC_PATH}: run comp-spec.mjs --comp {comp} --grid, name the regions, then --regions regions.json")]);};+ if let Some(why) = crate::approved_comp::build_issue(io, &spec, &s) { return Gate::fail(vec![why]); }if spec["draft"] == true { return Gate::fail(vec!["automatic region draft is not a measured element map; refine it with comp-spec --regions".into()]); }if let Some(issue) = crate::comp_spec::region_source_issue(io,&spec) { return Gate::fail(vec![issue]); }let regions = spec_regions(&spec);@@ -514,6 +525,11 @@ fn gate_plates(io: &Io) -> Gate {fn gate_plates_for(io: &Io, spec: &Value, only_id: Option<&str>) -> Gate {let s = self_cmd(io);+ if let Some(why) = crate::approved_comp::build_issue(io, spec, &s) {+ let mut gate = Gate::fail(vec![why]);+ gate.plates = Some(vec![]);+ return gate;+ }if let Some(issue) = crate::comp_spec::region_source_issue(io,spec) { return Gate::fail(vec![issue]); }let regions = spec_regions(&spec);let raster_regions: Vec<Value> = regions.iter().filter(|r| r.get("medium").and_then(Value::as_str) == Some("raster")@@ -1480,6 +1496,11 @@ fn gate_hero(if let Err(e) = unavailable_report(io, out_dir, &pending, "hero") {return Gate::fail(vec![format!("cannot persist hero gate evidence: {e}")]);}+ if let Some(why) = comp_refusal(io) {+ let gate = Gate::fail(vec![why]);+ let _ = unavailable_report(io, out_dir, &gate, "hero");+ return gate;+ }let native = match prepare_native_capture(io, state, artifact, renderer, EntryStage::Hero) {Ok(value) => value,Err(gate) => {@@ -2357,6 +2378,11 @@ fn gate_responsive(io: &Io, state: &mut Value, min: f64, out_dir: &str, rendererif let Err(e) = unavailable_report(io, out_dir, &pending, "responsive") {return Gate::fail(vec![format!("cannot persist responsive gate evidence: {e}")]);}+ if let Some(why) = comp_refusal(io) {+ let gate = Gate::fail(vec![why]);+ let _ = unavailable_report(io, out_dir, &gate, "responsive");+ return gate;+ }let native=match prepare_native_capture(io,state,None,renderer,EntryStage::Responsive) {Ok(value)=>value,Err(gate)=>{let _=unavailable_report(io,out_dir,&gate,"responsive");return gate;}};let mut gate = gate_responsive_inner(io, state, min, out_dir, native.as_ref());if gate.ok && native.is_none() {@@ -2627,7 +2653,21 @@ struct GateOpts {fn run_gate(io: &Io, state: &mut Value, phase: &str, opts: &GateOpts, organic_scan: OrganicScan, renderer: Option<&dyn EntryRenderer>) -> Gate {match phase {- "comps" => gate_comps(io),+ "comps" => {+ let mut gate = gate_comps(io);+ // The approval fixes the reference: keep the engine's own copy now+ // (a quoted --force closes on the approved comp too), and refuse to+ // close on an approval that cannot be kept.+ if let Some(approved) = gate.approved.clone() {+ let failure = match crate::approved_comp::keep(io, &approved) {+ Ok(Some(_)) => None,+ Ok(None) => Some(format!("the approved comp {approved} is not a decodable PNG, WebP or JPEG image, so it cannot be kept as the fixed reference; approve a readable comp")),+ Err(e) => Some(format!("{e}; make {BUILD_DIR} writable and advance again")),+ };+ if let Some(why) = failure { gate.ok = false; gate.unforceable = true; gate.reasons.push(why); }+ }+ gate+ }"spec" => gate_spec(io, state),"plates" => gate_plates(io),"hero" => {@@ -2636,7 +2676,8 @@ fn run_gate(io: &Io, state: &mut Value, phase: &str, opts: &GateOpts, organic_scgate_hero(io, state, &build_path, min, ".impeccable/review/diff/hero", opts.artifact.as_deref(), organic_scan, renderer)}"responsive" => gate_responsive(io, state, opts.min.unwrap_or(RESPONSIVE_MIN), ".impeccable/review/diff/desktop", renderer),- _ => Gate::ok("no mechanical gate".into()),+ // No measurement here, but the build still stands on the approved comp.+ _ => match comp_refusal(io) { Some(why) => Gate::fail(vec![why]), None => Gate::ok("no mechanical gate".into()) },}}@@ -2748,6 +2789,14 @@ fn advance(io: &Io, state: &mut Value, force: bool, reason: Option<&str>, opts:// the plates closed reopens the plan review before the hero can close.if let Some(why) = hero_plan_review_refusal(io, state) { gate.ok = false; gate.reasons.push(why); }}+ if !gate.ok && force && gate.unforceable {+ if let Some(p) = state.pointer_mut(&format!("/phases/{phase}")).and_then(|p| p.as_object_mut()) {+ p.insert("status".into(), json!("open"));+ }+ let mut reasons = gate.reasons.clone();+ reasons.push("--force refused: a quoted downgrade can relax the comp round, but never close it on an approved comp the engine cannot keep as the fixed reference; fix the reason above and advance again".into());+ return AdvanceResult { ok: false, phase, next: None, reasons, worst_crops: gate.worst_crops, advisories: gate.advisories, side_by_side: gate.side_by_side, forced: false, gate_summary: gate.summary };+ }if !gate.ok && force && !force_allowed(reason) {if let Some(p) = state.pointer_mut(&format!("/phases/{phase}")).and_then(|p| p.as_object_mut()) {p.insert("status".into(), json!("open"));@@ -3232,7 +3281,7 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,rlet cmd = argv.first().map(String::as_str);if cmd.is_none() || flag(argv, "help") {io.out("CANDIDATE CHECK: build-phase check-plate <region-id> --candidate <png> [--json] validates a separate file with the normal plate gate; never replaces the selected asset, records approval, or advances the phase.\n");- io.err("usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word>\n");+ io.err("usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n");return 1;}let cmd = cmd.unwrap();@@ -3266,6 +3315,11 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r}return if gate.ok { 0 } else { 2 };}+ if cmd == "restore-comp" {+ let (message, code) = crate::approved_comp::restore(io);+ if code == 0 { io.out(&message); } else { io.err(&message); }+ return code;+ }if cmd == "completion" {let state = load_state(io);let session_id = arg(argv, "session-id").or_else(|| io.env("IMPECCABLE_SESSION_ID"))@@ -3312,6 +3366,20 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,rreturn 0;}}+ match comp {+ Some(c) => {+ if let Some(why) = crate::approved_comp::restart_refusal(io, c, &self_cmd(io)) {+ io.err(&format!("build-phase: start refused: {why}\n"));+ return 2;+ }+ if let Err(e) = crate::approved_comp::keep(io, c) {+ io.err(&format!("build-phase: start refused: {e}; make {BUILD_DIR} writable and start again\n"));+ return 1;+ }+ }+ // A new comp round: the comp it approves is kept when the comps gate closes.+ None => crate::approved_comp::forget(io),+ }let mut state = new_state(comp, breakpoint.as_deref(), arg(argv, "artifact"), direction);if io.env("IMPECCABLE_NATIVE_CAPTURE")==Some("1") {state["capturePolicy"]=json!("native-html-v1");}// Session identity is transport metadata, never guessed from a project@@ -3478,6 +3546,12 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,rreturn 1;}let disposition = disposition.unwrap();+ if disposition == "ship" {+ if let Some(why) = comp_refusal(io) {+ io.err(&format!("build-phase: finish --disposition ship refused: {why}\n"));+ return 2;+ }+ }let open_before = crate::completion::open_phases(&state, false);if disposition == "ship" && !open_before.is_empty() {let phase = state.get("phase").and_then(Value::as_str).unwrap_or("");diff --git a/crates/comp-verbs/src/build_phase/integrity_tests.rs b/crates/comp-verbs/src/build_phase/integrity_tests.rsindex e5cf844c5..7dcbc39aa 100644--- a/crates/comp-verbs/src/build_phase/integrity_tests.rs+++ b/crates/comp-verbs/src/build_phase/integrity_tests.rs@@ -1620,6 +1620,212 @@ fn review_next_says_ship_rechecks_and_a_later_edit_needs_ship_again() {assert!(screenshots.contains("ship refuses while the frontend files differ from the responsive screenshots"), "{screenshots}");}+// ---- approved comp as a fixed reference ------------------------------------++const APPROVED: &str = ".impeccable/mocks/comp-1.png";++fn approved_comp_image() -> Image {+ let mut comp = r::create_image(300, 100, [20, 70, 110, 255]);+ r::fill_rect(&mut comp, 0., 61., 301., 40., [240., 180., 10., 255.]);+ comp+}++fn captured(ws: &Workspace) -> (Io, impeccable_common::Captured) {+ Io::captured("", ws.path.clone(), Default::default())+}++fn out_err(c: &impeccable_common::Captured) -> String {+ format!("{}{}", String::from_utf8_lossy(&c.stdout.borrow()), String::from_utf8_lossy(&c.stderr.borrow()))+}++/// A comp-led build started on an approved comp, measured by comp-spec.+fn approved_build() -> Workspace {+ let ws = Workspace::new();+ ws.write(APPROVED, &png_io::encode_png(&approved_comp_image(), &[]).unwrap());+ ws.write("regions.json", br#"{"allowUncovered":true,"regions":[{"id":"photo","kind":"image","note":"Wide photograph of the workshop","bleed":true,"plate":"assets/plates/photo.png","pixelBox":{"x":0,"y":0,"w":300,"h":61}}]}"#);+ let mut io = ws.io();+ assert_eq!(run(&["start", "--comp", APPROVED, "--artifact", "index.html"].map(String::from), &mut io, &no_organic_scan), 0);+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_spec::run(&["--comp", APPROVED, "--regions", "regions.json"].map(String::from), &mut io), 0, "{}", out_err(&c));+ ws+}++/// The tamper from the eval: generated pixels composited into the approved comp.+fn composite_into_comp(ws: &Workspace) {+ let mut edited = approved_comp_image();+ r::fill_rect(&mut edited, 40., 10., 120., 40., [200., 30., 30., 255.]);+ ws.write(APPROVED, &png_io::encode_png(&edited, &[]).unwrap());+}++#[test]+fn approval_keeps_a_copy_and_the_spec_binds_the_same_pixels() {+ let ws = approved_build();+ let record: Value = serde_json::from_slice(&std::fs::read(ws.path.join(crate::approved_comp::RECORD_PATH)).unwrap()).unwrap();+ let spec = load_spec(&ws.path.join(SPEC_PATH)).unwrap();+ assert_eq!(record["pixelSha256"], spec["compSha256"]);+ assert_eq!(std::fs::read(ws.path.join(".impeccable/build/approved-comp.png")).unwrap(), std::fs::read(ws.path.join(APPROVED)).unwrap());+ // A metadata-only rewrite (embed-prompt) is not an edit.+ ws.write(APPROVED, &png_io::encode_png(&approved_comp_image(), &[("prompt".into(), "comp prompt".into())]).unwrap());+ let io = ws.io();+ assert_eq!(comp_refusal(&io), None);+ let mut state = load_state(&io).unwrap();+ assert!(run_gate(&io, &mut state, "sections", &GateOpts { build_path: None, min: None, artifact: None }, &no_organic_scan, None).ok);+}++#[test]+fn every_comp_measuring_entry_point_refuses_an_edited_comp() {+ let ws = approved_build();+ let spec_before = std::fs::read(ws.path.join(SPEC_PATH)).unwrap();+ let expected = load_spec(&ws.path.join(SPEC_PATH)).unwrap()["compSha256"].as_str().unwrap().to_string();+ composite_into_comp(&ws);+ let actual = crate::approved_comp::file_pixel_sha256(&ws.io(), APPROVED).unwrap();+ let refused = |text: &str| {+ assert!(text.contains("has changed since approval"), "{text}");+ assert!(text.contains(&format!("expected pixel sha256 {expected}, found {actual}")), "{text}");+ assert!(text.contains("never edit it, composite into it, or regenerate it"), "{text}");+ assert!(text.contains("build-phase restore-comp"), "{text}");+ };+ let io = ws.io();+ let mut state = load_state(&io).unwrap();+ let opts = GateOpts { build_path: None, min: None, artifact: None };+ // spec, plates, hero, sections, motion, responsive: each refuses before measuring.+ for phase in ["spec", "plates", "hero", "sections", "motion", "responsive"] {+ let gate = run_gate(&io, &mut state, phase, &opts, &no_organic_scan, None);+ assert!(!gate.ok, "{phase}");+ assert_eq!(gate.reasons.len(), 1, "{phase}: {:?}", gate.reasons);+ refused(&gate.reasons[0]);+ }+ // advance (the spec phase is open after start --comp)+ let (mut io, c) = captured(&ws);+ assert_eq!(run(&["advance"].map(String::from), &mut io, &no_organic_scan), 2);+ refused(&out_err(&c));+ // check-plate+ ws.write("cand.png", &png_io::encode_png(&r::create_image(600, 122, [9, 9, 9, 255]), &[]).unwrap());+ let (mut io, c) = captured(&ws);+ assert_eq!(run(&["check-plate", "photo", "--candidate", "cand.png"].map(String::from), &mut io, &no_organic_scan), 2);+ refused(&out_err(&c));+ // finish ship+ let (mut io, c) = captured(&ws);+ assert_eq!(run(&["finish", "--disposition", "ship"].map(String::from), &mut io, &no_organic_scan), 2);+ refused(&out_err(&c));+ // comp-spec: no re-measure of the edited comp, no crop from it+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_spec::run(&["--comp", APPROVED, "--regions", "regions.json"].map(String::from), &mut io), 2);+ refused(&out_err(&c));+ assert_eq!(std::fs::read(ws.path.join(SPEC_PATH)).unwrap(), spec_before, "the spec keeps the approved identity");+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_spec::run(&["--crop", "photo", "--out", "crop.png"].map(String::from), &mut io), 2);+ refused(&out_err(&c));+ assert!(!ws.path.join("crop.png").exists());+ // comp-diff against the build's comp+ ws.write("build.png", &png_io::encode_png(&approved_comp_image(), &[]).unwrap());+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_diff::run(&["--comp", APPROVED, "--build", "build.png", "--spec", SPEC_PATH, "--no-files"].map(String::from), &mut io), 2);+ refused(&out_err(&c));+ // restarting on the approved file name does not re-approve the edit+ let (mut io, c) = captured(&ws);+ assert_eq!(run(&["start", "--reset", "--comp", APPROVED].map(String::from), &mut io, &no_organic_scan), 2);+ assert!(out_err(&c).contains("saved under a new file name"), "{}", out_err(&c));+}++#[test]+fn font_match_and_a_spec_less_comp_diff_refuse_an_edited_comp_too() {+ let ws = approved_build();+ composite_into_comp(&ws);+ let (mut io, c) = captured(&ws);+ let mut renderer = crate::font_match::NoRenderer;+ assert_eq!(crate::font_match::run(&["--measure", "photo"].map(String::from), &mut io, &mut renderer), 2);+ assert!(out_err(&c).contains("has changed since approval"), "{}", out_err(&c));+ ws.write("build.png", &png_io::encode_png(&approved_comp_image(), &[]).unwrap());+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_diff::run(&["--comp", APPROVED, "--build", "build.png", "--no-files"].map(String::from), &mut io), 2);+ assert!(out_err(&c).contains("has changed since approval"), "{}", out_err(&c));+ // A missing comp is refused, not waved through by the gates that do not read it.+ std::fs::remove_file(ws.path.join(APPROVED)).unwrap();+ let why = comp_refusal(&ws.io()).unwrap();+ assert!(why.contains("is missing or not a decodable image") && why.contains("build-phase restore-comp"), "{why}");+}++#[test]+fn a_build_that_predates_the_copy_cannot_remeasure_an_edited_comp() {+ let ws = approved_build();+ crate::approved_comp::forget(&ws.io());+ composite_into_comp(&ws);+ let (mut io, c) = captured(&ws);+ assert_eq!(crate::comp_spec::run(&["--comp", APPROVED, "--regions", "regions.json"].map(String::from), &mut io), 2);+ assert!(out_err(&c).contains("No intact engine copy"), "{}", out_err(&c));+ assert!(!ws.path.join(crate::approved_comp::RECORD_PATH).exists(), "the edited pixels are not adopted");+}++#[test]+fn a_spec_for_another_comp_never_replaces_the_build_record() {+ let ws = approved_build();+ let record = std::fs::read(ws.path.join(crate::approved_comp::RECORD_PATH)).unwrap();+ ws.write("other.png", &png_io::encode_png(&r::create_image(300, 100, [1, 2, 3, 255]), &[]).unwrap());+ let io = ws.io();+ let other = json!({"comp": "other.png", "compSha256": crate::approved_comp::file_pixel_sha256(&io, "other.png")});+ // An independent spec for another file is not the build's business ...+ assert_eq!(crate::approved_comp::issue_at(&io, &other, "other-spec.json", "impeccable"), None);+ // ... but the build's spec measured on another file is refused.+ let why = crate::approved_comp::issue_at(&io, &other, SPEC_PATH, "impeccable").unwrap();+ assert!(why.contains("measures other.png, but the approved comp is .impeccable/mocks/comp-1.png"), "{why}");+ assert_eq!(std::fs::read(ws.path.join(crate::approved_comp::RECORD_PATH)).unwrap(), record);+ let mut state = load_state(&io).unwrap();+ ws.write(SPEC_PATH, util::json_pretty(&json!({"comp":"other.png","compSha256":other["compSha256"],"regions":[]})).as_bytes());+ let gate = run_gate(&io, &mut state, "plates", &GateOpts { build_path: None, min: None, artifact: None }, &no_organic_scan, None);+ assert!(!gate.ok && gate.reasons[0].contains("but the approved comp is"), "{:?}", gate.reasons);+}++#[test]+fn restore_comp_puts_the_approved_pixels_back_and_the_gates_measure_again() {+ let ws = approved_build();+ let approved_bytes = std::fs::read(ws.path.join(APPROVED)).unwrap();+ composite_into_comp(&ws);+ let (mut io, c) = captured(&ws);+ assert_eq!(run(&["restore-comp"].map(String::from), &mut io, &no_organic_scan), 0);+ assert!(out_err(&c).starts_with(&format!("RESTORED {APPROVED} from .impeccable/build/approved-comp.png")), "{}", out_err(&c));+ assert_eq!(std::fs::read(ws.path.join(APPROVED)).unwrap(), approved_bytes);+ let kept: Vec<_> = std::fs::read_dir(ws.path.join(BUILD_DIR)).unwrap().filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.starts_with("edited-comp-")).collect();+ assert_eq!(kept.len(), 1, "the edited file is kept as evidence outside the mocks");+ let io = ws.io();+ assert_eq!(comp_refusal(&io), None);+ let spec = load_spec(&ws.path.join(SPEC_PATH)).unwrap();+ let gate = gate_plates_for(&io, &spec, None);+ assert!(gate.reasons.iter().all(|r| !r.contains("since approval")), "{:?}", gate.reasons);+ assert!(gate.reasons.iter().any(|r| r.contains("plate missing for photo")), "plates are measured again: {:?}", gate.reasons);+}++#[test]+fn comps_gate_keeps_the_approved_comp_and_a_new_round_forgets_it() {+ let ws = Workspace::new();+ let mut io = ws.io();+ assert_eq!(run(&["start", "--direction", "seed", "--artifact", "index.html"].map(String::from), &mut io, &no_organic_scan), 0);+ for (i, color) in [[20u8, 70, 110, 255], [90, 20, 20, 255], [10, 90, 10, 255]].iter().enumerate() {+ let file = format!(".impeccable/mocks/comp-{}.png", i + 1);+ ws.write(&file, &png_io::encode_png(&r::create_image(40, 20, *color), &[]).unwrap());+ ws.write(&format!("{file}.json"), format!(r#"{{"prompt":"comp {i}","approved":{}}}"#, i == 0).as_bytes());+ }+ assert_eq!(run(&["advance"].map(String::from), &mut io, &no_organic_scan), 0);+ let record: Value = serde_json::from_slice(&std::fs::read(ws.path.join(crate::approved_comp::RECORD_PATH)).unwrap()).unwrap();+ assert_eq!(record["comp"], APPROVED);+ assert_eq!(record["pixelSha256"].as_str(), crate::approved_comp::file_pixel_sha256(&io, APPROVED).as_deref());+ assert_eq!(run(&["start", "--reset", "--direction", "other"].map(String::from), &mut io, &no_organic_scan), 0);+ assert!(!ws.path.join(crate::approved_comp::RECORD_PATH).exists());+ // An approved comp that cannot be decoded cannot become the fixed reference.+ ws.write(APPROVED, b"not an image");+ let gate = run_gate(&io, &mut load_state(&io).unwrap(), "comps", &GateOpts { build_path: None, min: None, artifact: None }, &no_organic_scan, None);+ assert!(!gate.ok && gate.reasons.iter().any(|r| r.contains("is not a decodable PNG, WebP or JPEG image")), "{:?}", gate.reasons);+ // ... and a quoted downgrade cannot force the comps phase closed over it.+ let (mut io, c) = captured(&ws);+ let force = ["advance", "--force", "--reason", "The user said \"Ignore the comp fidelity requirement; ship this version.\""].map(String::from);+ assert_eq!(run(&force, &mut io, &no_organic_scan), 2);+ assert!(out_err(&c).contains("never close it on an approved comp the engine cannot keep"), "{}", out_err(&c));+ let state = load_state(&io).unwrap();+ assert_eq!(state["phase"], "comps");+ assert!(state["phases"]["comps"]["forced"].is_null());+}+/// The code-led first viewport with a lettered export control (`export`), or/// with that control left out of the page.fn lettered_text_only_hero(restyled: bool, export: bool) -> Image {diff --git a/crates/comp-verbs/src/comp_diff.rs b/crates/comp-verbs/src/comp_diff.rsindex 8cccba3d2..dddcd0973 100644--- a/crates/comp-verbs/src/comp_diff.rs+++ b/crates/comp-verbs/src/comp_diff.rs@@ -729,6 +729,17 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {}}}+ // Measuring against the build's comp: refuse while it differs from the+ // approved pixels, so a reading never comes from an edited reference.+ let s = crate::build_phase::self_cmd(io);+ let refusal = match spec.as_ref().filter(|sp| sp["comp"].as_str().is_some_and(|c| crate::approved_comp::same_file(io, c, comp_path))) {+ Some(sp) => crate::approved_comp::issue_at(io, sp, spec_path.unwrap_or(""), &s),+ None => crate::approved_comp::issue_for_comp(io, comp_path, &s),+ };+ if let Some(why) = refusal {+ io.err(&format!("comp-diff: {why}\n"));+ return 2;+ }let default_out = {let d = Path::new(build_path).parent().map(|p| p.to_path_buf()).unwrap_or_default();d.join("diff").to_string_lossy().replace('\\', "/")diff --git a/crates/comp-verbs/src/comp_spec.rs b/crates/comp-verbs/src/comp_spec.rsindex 942b4d7a6..0960a73d3 100644--- a/crates/comp-verbs/src/comp_spec.rs+++ b/crates/comp-verbs/src/comp_spec.rs@@ -1169,6 +1169,10 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {return 1;};let comp_file = spec.get("comp").and_then(Value::as_str).unwrap_or("");+ if let Some(why) = crate::approved_comp::issue_at(io, &spec, &spec_path, &crate::build_phase::self_cmd(io)) {+ io.err(&format!("comp-spec: {why}\n"));+ return 2;+ }let comp = match png_io::load_raster(&resolve(io, comp_file)) {Ok((d, _)) => d.image,Err(e) => {@@ -1222,8 +1226,12 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {io.err("usage: comp-spec.mjs --comp <png> (--grid | --regions <json> | --auto) [--spec out.json]\n comp-spec.mjs --print | --crop <id> [--out file] [--scale n] | --plate-prompt <id>\n");return 1;};- let comp = match png_io::load_raster(&resolve(io, comp_path)) {- Ok((d, _)) => d.image,+ // Decode the comp's own bytes first: load_raster may read a stale sibling+ // PNG cache for a WebP or JPEG source, and the spec must measure (and+ // identify) the pixels the approved-comp record identifies.+ let own = std::fs::read(resolve(io, comp_path)).ok().and_then(|b| crate::approved_comp::decode_comp(&b));+ let comp = match own.map(Ok).unwrap_or_else(|| png_io::load_raster(&resolve(io, comp_path)).map(|(d, _)| d.image)) {+ Ok(img) => img,Err(e) => {io.err(&format!("comp-spec: cannot read {comp_path}: {e}\n"));return 1;@@ -1338,15 +1346,18 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {let spec_out = resolve(io, &spec_path);// Bind cached font evidence to the decoded reference, including dimensions.// Legacy specs without this identity are deliberately remeasured once.- let mut hasher = Sha256::new();- hasher.update(comp.width.to_le_bytes());- hasher.update(comp.height.to_le_bytes());- hasher.update(&comp.data);- spec["compSha256"] = json!(format!("{:x}", hasher.finalize()));+ let comp_hash = crate::approved_comp::pixel_sha256(&comp);+ let previous = std::fs::read(&spec_out).ok().and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok());+ // The approved comp is the fixed reference: re-measuring an edited copy of+ // the build's comp would move the spec's identity along with the edit.+ if let Some(why) = crate::approved_comp::spec_refusal(io, comp_path, &comp_hash, previous.as_ref(), &crate::build_phase::self_cmd(io)) {+ io.err(&format!("comp-spec: {why}\n"));+ return 2;+ }+ spec["compSha256"] = json!(comp_hash);spec["regionsSource"] = regions_source;- if let Some(previous) = std::fs::read(&spec_out).ok()- .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) {- preserve_typography(&mut spec, &previous);+ if let Some(previous) = &previous {+ preserve_typography(&mut spec, previous);}if let Some(parent) = spec_out.parent() {let _ = std::fs::create_dir_all(parent);diff --git a/crates/comp-verbs/src/font_match.rs b/crates/comp-verbs/src/font_match.rsindex c8de0adc5..cbf44107a 100644--- a/crates/comp-verbs/src/font_match.rs+++ b/crates/comp-verbs/src/font_match.rs@@ -449,6 +449,11 @@ pub fn run(argv: &[String], io: &mut Io, renderer: &mut dyn FontRenderer) -> i32return 1;};let comp_file = spec_val.get("comp").and_then(Value::as_str).unwrap_or("").to_string();+ // Type read off an edited comp would land in the spec as approved evidence.+ if let Some(why) = crate::approved_comp::issue_at(io, spec_val, &spec_path, &crate::build_phase::self_cmd(io)) {+ io.err(&format!("font-match: {why}\n"));+ return 2;+ }let comp = match png_io::load_raster(&resolve(io, &comp_file)) {Ok((d, _)) => d.image,Err(e) => {diff --git a/crates/comp-verbs/src/lib.rs b/crates/comp-verbs/src/lib.rsindex 065cb9389..31c507737 100644--- a/crates/comp-verbs/src/lib.rs+++ b/crates/comp-verbs/src/lib.rs@@ -14,6 +14,7 @@//! its catalog (`IMPECCABLE_CATALOG_DIR`, then the skill's shipped copy); it is//! never committed to the engine repo. See [`font_match`].+pub mod approved_comp;pub mod build_phase;pub mod completion;pub mod comp_diff;diff --git a/crates/comp/src/png_io.rs b/crates/comp/src/png_io.rsindex 4ebe0400a..0978401da 100644--- a/crates/comp/src/png_io.rs+++ b/crates/comp/src/png_io.rs@@ -155,6 +155,18 @@ pub fn load_raster(file: &std::path::Path) -> Result<(Decoded, std::path::PathBuOk((Decoded { image: img, text: HashMap::new() }, cache))}+/// Decode an image from its own bytes, any format `load_raster` reads, without+/// consulting or writing the sibling PNG cache (which an edit to a WebP or+/// JPEG source never refreshes).+pub fn decode_source(bytes: &[u8]) -> Result<Image, String> {+ if is_png(bytes) {+ return Ok(decode_png(bytes)?.image);+ }+ let rgba = image::load_from_memory(bytes).map_err(|e| format!("not a decodable image: {e}"))?.to_rgba8();+ let (width, height) = (rgba.width() as usize, rgba.height() as usize);+ Ok(Image { width, height, data: rgba.into_raw() })+}+/// Decode a static review image from its pinned bytes, without consulting or/// writing sibling conversion caches. Keep the original file as review evidence.pub fn decode_review_image(bytes: &[u8]) -> Result<(Image, &'static str), String> {diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex 897ab05b3..fd8c5d3ba 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -468,12 +468,14 @@ Ported from the former `skill/scripts/{comp-spec,comp-diff,font-match,build-phas- **`comp-spec`** — turns an approved comp into a measured build spec. `--schema` prints the region-map JSON schema without reading or writing a project. `--comp <png> --regions <json> --inspect-map` writes reference-only crops, overlay and report in a new directory; exit 2 means diagnosed hard errors, exit 1 means command/input failure. Masked assets also produce paginated, comp-derived `comparison-N.png` sheets (six original/checker pairs per image, matched scale and aspect ratio), listed by `COMPARE` lines and the JSON `comparisonSheets` array. Every affected instance is retained; sheets do not change matcher inputs or approvals. Partial foreground masks are warnings naming the excluding regions and remain in the inspector’s main inspection queue even with zero hard errors. The CLI summary counts them separately; they do not imply an asset failure or visual approval. Code rectangles exclude their full overlap, so separate text elements need separate bounds. Mapping metadata (`parentId`, `reviewGroup`) survives measurement. Review groups must contain peer code regions of one kind and container status; mixed groups and grouped raster assets are refused both at measurement and at component-review preparation. `--comp <png> --grid` writes `.impeccable/build/comp-grid.png` (10x10 labeled grid) and prints PALETTE/BANDS/NEXT; `--comp <png> --regions <json>` measures regions into `.impeccable/build/spec.json` (region box, sampled palette, medium, aspect, detail energy, plate path for raster kinds) and prints the spec; `--comp <png> --auto [--out <draft.json>]` writes approximate bands to a new draft file (default `.impeccable/build/regions.draft.json`), without modifying the measured spec or build state; `--print` prints the compact spec; `--crop <id> [--out f] [--scale n] [--raw]` writes a reference crop; `--plate-prompt <id>` prints the regeneration prompt. `--spec <path>` overrides the spec path (default `.impeccable/build/spec.json`). Validation refusals (stderr, exit 1) are the JS strings verbatim: a region with no id / duplicate id / no note (bands included) / a missing or unknown kind, a `box` that is not numeric, leaves the 0..1 frame, or rounds below one comp pixel, a code-kind region whose note names painted material, a code region over 25% of the comp, a grid span that is not `<colrow>:<colrow>`, uncovered ink cells without `allowUncovered`. Every `text`, `control` and `chrome` region (containers included) gets `surface: {flat, rules}` and, when any 64px window of its comp crop reads as painted (pixels inside raster regions left out), `flags: [{"id":"painted-pixels","message":...}]` plus a `FLAG <id> painted-pixels: <message> <agent advice>` line in the printed spec; docs/PLAN-REVIEW.md defines both readings. The flag is never a refusal, and `codeDrawn` does not suppress it. A raster region whose note names a frame and then the view it opens onto gets `flags: [{"id":"baked-composite","message":...}]` and its own `FLAG` line (docs/PLAN-REVIEW.md). Apart from these additions, spec.json is byte-identical to the JS output.Automatic drafts require decomposition into actual visible elements before measurement; a draft flag blocks accidental submission, and existing draft files are never overwritten. Successful `--regions` measurements record the source path and SHA-256. Spec and plate gates reject changed or missing source files, so a failed region edit cannot silently reuse the previous measurements. Legacy specs without source metadata remain readable.Region inputs support three coordinate representations: inclusive `grid` cells, normalized `box: {x,y,w,h}`, or `pixelBox: {x,y,w,h}` in whole original-comp pixels. Pixel boxes cannot be combined with the other formats and must be positive-sized and contained in the comp; they avoid snapping an asset boundary to a neighbouring grid cell. Foreground UI excluded from a plate reference is excluded at the same aligned coordinates from the candidate during scoring; unmasked asset bytes still undergo provenance checks.-- **`comp-diff`** — `--comp <png> --build <png> [--spec spec.json] [--out-dir dir] [--align top|stretch|cover] [--label name] [--threshold t] [--json] [--no-files]`. Scores structure / color / detail / bands and per-region verdicts (`match`/`drift`/`missing`/`contradicted`); writes `side-by-side.png`, `heatmap.png`, `regions/<id>.png`, and `report.json` under `--out-dir` (unless `--no-files`); prints the text summary or, with `--json`, the report. Exit 0 measured, 1 usage/unreadable input, 3 below `--threshold`. The JSON report and text summary are byte-identical to the JS.+- **`comp-diff`** — `--comp <png> --build <png> [--spec spec.json] [--out-dir dir] [--align top|stretch|cover] [--label name] [--threshold t] [--json] [--no-files]`. Scores structure / color / detail / bands and per-region verdicts (`match`/`drift`/`missing`/`contradicted`); writes `side-by-side.png`, `heatmap.png`, `regions/<id>.png`, and `report.json` under `--out-dir` (unless `--no-files`); prints the text summary or, with `--json`, the report. Exit 0 measured, 1 usage/unreadable input, 2 the approved comp changed (see the fixed-reference paragraph under `build-phase`), 3 below `--threshold`. The JSON report and text summary are byte-identical to the JS.- **`font-match`** — `--measure <text-region-id>` fingerprints the comp crop of a text region (cap height, width/weight class, shape vector), records it on the region's `type` block in the spec, and prints the MEASURE line (pure; byte-identical to the JS). `--rank <id> [--candidates "Family:700,…"] [--text "…"] [--transform …] [--category …]` additionally renders candidate faces in a headless browser and ranks them by fingerprint distance, writing a stamped `chosen` face onto the region and a proof sheet under `.impeccable/build/font-match/`. **Browser**: an installed Chrome discovered and driven over CDP (the same browser the URL engine uses; the JS used Playwright/Puppeteer). With no browser resolvable, the catalog's nearest face is recorded (source `catalog`, estimated size) or, with no catalog either, the MEASURE line stands — matching the JS fallbacks; the sha1 `chosen` stamp is byte-identical. Screenshots vary by Chrome version, so the rendered ranking is not byte-stable.- **`font-index` catalog (paid moat)** — resolved at run time, never committed to the engine repo: `IMPECCABLE_CATALOG_DIR/font-index.json` first, then the skill's shipped `IMPECCABLE_SKILL_DIR/scripts/data/font-index.json`; absent → the built-in per-width shortlist stands in (the JS degraded path).-- **`build-phase`** — the comp-led build state machine at `.impeccable/build/state.json`. `start --comp <png> | --direction <key>` (opens the phases; reads comp dimensions for the breakpoint), `status [--json]`, `advance [--force --reason "…"]` (runs the current phase's gate; exit 2 on gate failure, state unchanged), `record hero --build <png>`, `scaffold`, `note "<text>"`, `finish --disposition ship|fix|rebuild|recapture`. Phases and gates (`comps`, `spec`, `plates`, `hero`, `sections`, `motion`, `responsive`, `review`) are unchanged from the JS; the hero/responsive gates call comp-diff in-process (the JS spawned it). The organic-clip-path CSS scan is the engine's own rule (`organic-clip-path`), injected into the gate; The spec gate (re-run by hero and responsive) also refuses unknown kinds, noteless bands, sub-pixel regions, and a band-only map. `--force` is refused unless `--reason` quotes the user downgrading the comp (the JS `forceAllowed` logic verbatim).+- **`build-phase`** — the comp-led build state machine at `.impeccable/build/state.json`. `start --comp <png> | --direction <key>` (opens the phases; reads comp dimensions for the breakpoint), `status [--json]`, `advance [--force --reason "…"]` (runs the current phase's gate; exit 2 on gate failure, state unchanged), `record hero --build <png>`, `scaffold`, `note "<text>"`, `finish --disposition ship|fix|rebuild|recapture`, `restore-comp`. Phases and gates (`comps`, `spec`, `plates`, `hero`, `sections`, `motion`, `responsive`, `review`) are unchanged from the JS; the hero/responsive gates call comp-diff in-process (the JS spawned it). The organic-clip-path CSS scan is the engine's own rule (`organic-clip-path`), injected into the gate; The spec gate (re-run by hero and responsive) also refuses unknown kinds, noteless bands, sub-pixel regions, and a band-only map. `--force` is refused unless `--reason` quotes the user downgrading the comp (the JS `forceAllowed` logic verbatim).- `build-phase check-plate <region-id> --candidate <png> [--json]` runs the normal plate gate on a separate candidate, retaining the full spec for reference exclusions. Exit 0 means pass, 2 means gate failure, 1 means invalid input. It does not write files, select an asset, record an approval, or advance build state. JSON includes `ok`, `region`, `candidate`, `reasons`, `plates`, and `stateChanged: false`.+ `build-phase check-plate <region-id> --candidate <png> [--json]` runs the normal plate gate on a separate candidate, retaining the full spec for reference exclusions. Exit 0 means pass, 2 means gate failure, 1 means invalid input. It does not write files (apart from the approved-comp copy a build that predates it gets on its first check), select an asset, record an approval, or advance build state. JSON includes `ok`, `region`, `candidate`, `reasons`, `plates`, and `stateChanged: false`.++ **The approved comp is a fixed reference (engine addition).** When a comp is approved (`build-phase start --comp <png>`, the comps gate closing on the approved sidecar, or, for a build that has neither, the first `comp-spec --regions` on the comp `state.json` names), the engine copies its bytes to `.impeccable/build/approved-comp.<ext>` and writes `.impeccable/build/approved-comp.json` (`comp`, `pixelSha256`, `fileSha256`, `copy`, `at`). `pixelSha256` is the identity `comp-spec` writes as `compSha256` (SHA-256 of width, height and decoded RGBA, so a metadata-only rewrite such as `embed-prompt` is not an edit); it is decoded from the file's own bytes, never a sibling PNG cache, and `comp-spec` now measures and hashes that same decode of the comp's own bytes (`png_io::decode_source`: PNG, WebP, JPEG or GIF from the file's own bytes, never the sibling PNG cache `load_raster` keeps; the record and every check use the same decode, so a comp comp-spec can measure is never locked out and a stale cache never stands in for an edited source). Before anything measures against the comp, every entry point compares the comp's current pixels with that record (or, for a build that predates the record, with the spec's `compSha256`; the build's own spec then keeps the copy when they agree and no record exists, a spec at another path never does): the spec, plates, hero, sections, motion and responsive gates (so `advance`, `record hero`, `check-plate`, and the hero, responsive and plate revalidations), `finish --disposition ship`, `comp-spec --crop`, `comp-spec --comp <build comp> --regions` while a build state names that comp, `font-match --measure` / `--rank`, and `comp-diff` (against the spec's `compSha256` and the record when its `--spec` measures the `--comp` it was given, otherwise against the record kept for that `--comp`, if any). A missing or undecodable comp with a recorded identity is refused the same way, the hash clause reading `is missing or not a decodable image: expected pixel sha256 <approved>`. The build's own spec (`.impeccable/build/spec.json`, which every build-phase check reads, and `comp-spec --crop` / `font-match` / `comp-diff` when they are given that path) must measure the recorded comp: one that measures another file (a composite saved under a new name and re-specced) is refused with `.impeccable/build/spec.json measures <comp>, but the approved comp is <approved>.`, the fixed-reference sentence, and the instruction to re-run `comp-spec --regions` on the approved comp or start a new build on a newly approved file. A spec at another path is checked only against its own comp's record and `compSha256`, so independent crops stay possible, and the first-check keep never replaces a record kept for another comp. For a build that predates the record, `comp-spec --regions` compares the comp with the `compSha256` of the spec it is about to replace and refuses on a mismatch instead of adopting the edited pixels. When the copy or record cannot be written, approval refuses: `start --comp` exits 1 (`build-phase: start refused: cannot keep the approved comp: writing <path> failed (...)`), the comps gate stays open with that reason (also when the approved comp is not a decodable PNG, WebP or JPEG, and also under a quoted `--force`, which keeps the copy before closing; a quoted `--force` never waives this reason, and `advance` adds `--force refused: a quoted downgrade can relax the comp round, but never close it on an approved comp the engine cannot keep as the fixed reference; fix the reason above and advance again`), and `comp-spec --regions` exits 2. A mismatch is refused before any measurement (gate reason, or stderr with exit 2 for the verbs) with: `the approved comp <comp> has changed since approval: expected pixel sha256 <approved>, found <current>. The approved comp is the fixed reference every gate measures against; never edit it, composite into it, or regenerate it. Nothing was measured against the changed file. Restore it with <IMPECCABLE> build-phase restore-comp (the engine kept the approved copy at <copy>), then regenerate the plates or change the page code until they match the unchanged comp.` When no intact copy exists the last two sentences read `No intact engine copy exists for this build: restore the approved file from its original source, then regenerate the plates or change the page code until they match the unchanged comp.` A spec whose `compSha256` differs from the record (re-measured on an edited comp) is refused with `.impeccable/build/spec.json was measured on an image that is not the approved comp (spec compSha256 <spec>, approved <approved>): re-measuring an edited comp does not move the reference.` followed by the fixed-reference sentence and the instruction to re-run `comp-spec --regions` on the approved comp. `build-phase start --reset --comp <png>` naming the recorded comp while its pixels differ is refused (exit 2, `build-phase: start refused: ...`), adding that a newly approved comp is saved under a new file name; `start --direction` forgets the record, since its comp round approves a new comp. `build-phase restore-comp` (no state needed) verifies the copy against `pixelSha256`, moves the edited file to `.impeccable/build/edited-comp-<first 12 hex of its pixel hash>.<ext>` (outside `.impeccable/mocks/`, where the comps gate would count it), writes the copy back, and prints `RESTORED <comp> from <copy> (pixel sha256 <hash>). The edited file is kept at <path> as evidence, not as a comp. Re-run the step that refused; plates and page code built against the edited comp now have to match the approved one.` (exit 0; `comp <comp> already holds the approved pixels (sha256 <hash>); nothing restored` when nothing changed). It exits 1 when no record exists and 2 when the copy no longer matches the record. Gates measure against the editable path once it holds the approved pixels again, rather than silently against the copy, because the crop and font tools, `comp-diff` and the finish reviewer all read that path.`build-phase finish --disposition ship` binds the finish to the page it checked. Under native capture (`capturePolicy: "native-html-v1"` or `IMPECCABLE_NATIVE_CAPTURE=1`) ship first re-runs the responsive gate with a fresh native capture of the current files (an input that changes while that capture runs fails it, reopens responsive and records `fix`), then records `finish.artifactSha256` and `finish.captureInputs`, the `{path, sha256}` rows of the manifest that capture bound (`.impeccable/review/native/responsive/inputs.json`: the entry, the static files the capture froze, the spec and the comp). When that manifest is missing or unreadable, ship is refused (exit 2, `finish` recorded as `fix` with reason `final native capture manifest unavailable`) rather than recorded with entry-only binding. Under the screenshot policy ship refuses while the frontend files differ from the responsive screenshots and records `finish.artifactInputsSha256`; no `captureInputs` is recorded. `build-phase completion` reports `status: "changed-after-finish"` when the entry or any recorded capture input differs from what finish bound (a deleted file counts as changed, the entry included, so a deleted entry reads `changed-after-finish` rather than `unverified`), and lists the changed paths, entry first, in `changedSinceFinish`. Printed `NEXT` lines: in the review phase, `Spawn the finish reviewer ... --disposition <word>. Make every fix before ship: <recheck>, and any edit after it, a fix for a hook finding included, needs ship recorded again.`; after a ship that still covers the page, `Finish is recorded for the current entry. Any later edit to a file the final check bound (the page, what it loads, the spec, the comp), a fix for a hook finding included, voids it: run <IMPECCABLE> build-phase finish --disposition ship again before you stop; <recheck>.`; after one that no longer does, `A file the final check bound changed after finish (<up to six changed paths>), so the recorded ship no longer covers the build. Repeat final review if the change goes beyond a fix it asked for, then run <IMPECCABLE> build-phase finish --disposition ship again; <recheck>.` `<recheck>` is `ship re-captures the current files natively and must pass the responsive gate again` under native capture and `ship refuses while the frontend files differ from the responsive screenshots, so recapture desktop and mobile and advance responsive first` otherwise.diff --git a/skill/reference/new-work.md b/skill/reference/new-work.mdindex 334b37fea..72bdaa89e 100644--- a/skill/reference/new-work.md+++ b/skill/reference/new-work.md@@ -112,7 +112,7 @@ The comp-led path is a frontier-tier job: it asks the builder to hold a measured1. **spec.** Measure the comp: `impeccable comp-spec --comp <comp> --grid` writes a coordinate grid over the comp; open it, name every salient region by grid span in a regions file (text and control regions narrow to an ink cluster only when it retains at least 95% of the span’s contrasting pixels; inspect the resulting crop, especially for compound controls and multiline text; `snap: false` keeps the span, and an explicit `box` is taken as drawn) (kind `plate` / `image` / `texture` for anything painted: every illustration, photograph, figure, product object, and material texture; `text` / `control` / `chrome` for what code draws; every region carries a `note` saying what the comp shows there, which the plate prompt and the gate messages read), and run `impeccable comp-spec --comp <comp> --regions <file>`. The spec carries each region's box, sampled palette, and medium; `impeccable comp-spec --print` is the build's reference from here on. Type is measured, not guessed: `impeccable font-match --measure <text region>` reads the comp's cap height, width class, and weight off the pixels, and `impeccable font-match --rank <region> --text "..."` takes its candidates from a fingerprint index of the Google Fonts catalog (the nearest faces to the crop's shape) plus any names you pass with `--candidates`, renders them at that cap height with the region's words, and ranks them by fingerprint distance (its `USE` line is the CSS); with no browser resolvable it records the catalog's nearest face and says the size is estimated, which is still the choice to build on. Do not install a browser to rank, and never write a `chosen` face into the spec by hand: the gate accepts only what font-match wrote. The spec gate refuses to close until the lead text region is measured and ranked. A region note that describes painted material (a diagram, drawing, photograph, texture) under a code kind is refused at the spec: reclassify it as a plate, or reword the note if code really draws it. The script refuses a regions file that leaves comp ink unnamed: what is never named can never be missing. It also refuses a `text` / `control` / `chrome` region larger than a quarter of the comp: that is a column, not an element. Name each element inside it (`container: true` only when it truly is one undivided element). Anything drawn is a plate: an inline SVG past an icon's budget (a diagram, notation, leader lines with arrows, a "quick approximation" of the artwork) is refused at the hero; icon-sized SVG (under 64px, a few paths) is fine, and a chart the page draws from data at runtime is a chart, not an illustration. Callout lines and arrows that annotate a drawing belong to that drawing's plate, with only their labels set as text. Split regions by what varies independently, as [region-map.md](region-map.md) sets out; a framed view is a frame plate over its own image region. A crop of the comp is never a plate (the plates gate refuses a resample of the comp region); the crop is the reference the plate is generated from. A plate region's box has to hold its whole artwork with a margin: the spec measures the artwork's contact with the box edges and refuses a box that cuts through it (`bleed: true` only when the page really crops it there), because a plate placed with `object-fit: cover` on such a box shows the artwork minus the side the box lost. Anything not in the spec does not exist on the page: no borders, rules, containers, or chrome the comp does not show. Only three concessions exist: fonts (the closest obtainable face), icon glyphs (close enough, exact if the user chose an icon library; this covers the pictogram only, never a control's chrome, so a chevron, an arrow, a dropdown's border and fill, a button's shape are the comp's), and genuine defects in the comp such as spelling errors. <!-- rule:skill-comp-spec -->Inspect the proposed map before producing assets: `impeccable comp-spec --comp <comp> --regions <file> --inspect-map` writes a numbered overlay, exact crops, foreground-mask previews, and a consolidated report without changing the spec or build state. Inspect boundaries and excluded pixels together; an empty reference needs corrected geometry. `parentId` names an enclosing `container`; it never removes regions or approves assets. The report diagnoses geometry, not semantic completeness.-2. **plates.** Every raster region ships as a plate: an illustration, photo, or figure regenerated at asset resolution from its comp crop, UI text removed, at its `plate` path (isolated ink, figures, or objects use native transparent PNG so they sit on the page's own ground; photos and textures stay opaque); a texture (paper, cloth, grain) is a clean patch of the comp region mirror-tiled to size, generated only when no clean patch exists. `impeccable comp-spec --crop <id>` writes the reference; save `impeccable comp-spec --plate-prompt <id> --background transparent` to a prompt file for a cutout, or use `--background opaque` otherwise. Prefer the harness-native image tool with that crop and prompt, then `impeccable embed-prompt <plate> --prompt-file <prompt.txt>`. The API fallback is `impeccable generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high --background transparent` (use `--background opaque` for full-frame assets); create the output directory first. Verify actual alpha, white foregrounds, fine edges, and clear holes on light and dark grounds; do not chroma-key native output. The plates gate scores the assets against the comp; also inspect placement and scale visually. With parallel subagents, spawn the shipped asset producer (`impeccable-asset-producer`; `impeccable_asset_producer` in codex; `/impeccable-asset-producer` in Cursor; on GitHub Copilot say "Use the impeccable-asset-producer agent") with the spec path and let it produce them all; without subagents, produce them here. A crop of the comp is a reference, never a shipping pixel. The gate checks every plate exists, is at least 1.5x the region's size, and reads as the region. Page code waits for this gate: a page written before its plates exist is a page that draws its material in CSS. A single-file deliverable changes nothing here: the plate is produced the same way and inlined as a data URI. `--force` exists for one case only, the user downgrading the comp's authority in words you quote in `--reason`; the script refuses every other reason. <!-- rule:skill-plates-before-page --> Score the plates before the review opens: once `build-phase advance` reports nothing but the pending review, run the plan and asset review in [component-review.md](component-review.md), where the user checks the plates and which regions code draws. A plate replaced after they accept needs a new round. No page code is written before they accept it; `build-phase advance` refuses until they do. <!-- rule:skill-human-component-review -->+2. **plates.** Every raster region ships as a plate: an illustration, photo, or figure regenerated at asset resolution from its comp crop, UI text removed, at its `plate` path (isolated ink, figures, or objects use native transparent PNG so they sit on the page's own ground; photos and textures stay opaque); a texture (paper, cloth, grain) is a clean patch of the comp region mirror-tiled to size, generated only when no clean patch exists. `impeccable comp-spec --crop <id>` writes the reference; save `impeccable comp-spec --plate-prompt <id> --background transparent` to a prompt file for a cutout, or use `--background opaque` otherwise. Prefer the harness-native image tool with that crop and prompt, then `impeccable embed-prompt <plate> --prompt-file <prompt.txt>`. The API fallback is `impeccable generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high --background transparent` (use `--background opaque` for full-frame assets); create the output directory first. Verify actual alpha, white foregrounds, fine edges, and clear holes on light and dark grounds; do not chroma-key native output. The plates gate scores the assets against the comp; also inspect placement and scale visually. With parallel subagents, spawn the shipped asset producer (`impeccable-asset-producer`; `impeccable_asset_producer` in codex; `/impeccable-asset-producer` in Cursor; on GitHub Copilot say "Use the impeccable-asset-producer agent") with the spec path and let it produce them all; without subagents, produce them here. A crop of the comp is a reference, never a shipping pixel. The approved comp is a fixed reference: never edit it, composite into it, or regenerate it, and never copy a crop of it in as a plate (the crop is only the reference you generate from). The gate checks every plate exists, is at least 1.5x the region's size, and reads as the region. Page code waits for this gate: a page written before its plates exist is a page that draws its material in CSS. A single-file deliverable changes nothing here: the plate is produced the same way and inlined as a data URI. `--force` exists for one case only, the user downgrading the comp's authority in words you quote in `--reason`; the script refuses every other reason. <!-- rule:skill-plates-before-page --> Score the plates before the review opens: once `build-phase advance` reports nothing but the pending review, run the plan and asset review in [component-review.md](component-review.md), where the user checks the plates and which regions code draws. A plate replaced after they accept needs a new round. No page code is written before they accept it; `build-phase advance` refuses until they do. <!-- rule:skill-human-component-review -->3. **hero.** `impeccable build-phase scaffold` first: it writes the measured layout as CSS custom properties (`.impeccable/build/scaffold/layout.css`: `--r-<id>-x/y/w/h` in % of the comp, plus cap height, font-size, family, and weight where measured) and a reference page (`hero-reference.html`) with every region at its box and every plate placed. Bind the numbers to your own semantic structure, an element per region; the reference is a check on positions, never the page, and overlapping boxes are overlapping boxes. Then build only the first viewport, at the comp's own dimensions, the comp's words copied verbatim (the user approved that comp with those words; rewording is a stated decision after the hero passes, never a silent one inside it), every text region sized from its measured cap height and set in its ranked face (served from the project: put the face's font files beside the page and load them with `@font-face`, never a hosted font stylesheet such as fonts.googleapis.com or a font data URI, because the first-viewport capture allows fonts only from the page's own files and refuses any other host as an external dependency), plates first: place every plate at its spec box (`object-fit: cover`, an `<img>`, a background image, or an inlined data URI named for it) before any text or control, capture into `.impeccable/review/hero-repro.png`, run `impeccable build-phase record hero` once so you see the plate regions read as match before any text exists, then lay the semantic layer over the plates from the spec's palette and boxes and advance. The gate first refuses while any plate is unreferenced by the source, then runs `impeccable comp-diff`, writes `.impeccable/review/diff/hero/` (side-by-side, heatmap, one paired crop per region, `report.json`; `raw-report.json` preserves the uninterpreted measurements). The report and crop labels use the gate's verdicts; `gate.reasons` lists the remaining blockers even when a region is called drift. An accepted plate is revalidated if its file, measured region, or comp changes. The gate passes at 72% overall with no hard veto outstanding (a missing region, a contradicted plate or text block, an SVG illustration, a clipped plate, invented ink block at any score); above the bar, the numeric readings become advisories printed with the pass, and the polish pass before responsive is where they get fixed: the gate also reads each text region's cap height, line count, weight, ink colour, and position against the comp, each chrome strip's height off its rule, and the frame for ink where the comp is calm (a kicker, an extra nav item, a divider), and says each miss as a number ("cap height 78px in the build, 103px in the comp"); those numbers are the edit. When it fails, open the region crops it lists, in order, before editing: a region scored `missing` needs its material, `contradicted` needs its structure re-derived from the spec box, `drift` is where size and spacing edits belong; repeated attempts do not clear unresolved blockers. After three failed attempts, present the first-viewport review from [component-review.md](component-review.md) instead of iterating. Once the user accepts a first viewport, the overall bar, the palette check and every numeric reading are advisories while the capture still matches it; a missing or unreferenced plate, an SVG illustration, an organic clip, a clipped plate, invented ink and failed rendered presence still block. When the capture drifts from what they accepted, restore it: that review is closed and is never requested again. This is where the run's ambition is won or lost, and a retry here costs minutes where a rebuild verdict at the finish costs the run. <!-- rule:skill-hero-gate -->4. **sections.** Build the rest of the surface inside the spec's system: the same corner language, line weights, and palette, and nothing the comp never shows. Where the comp does not cover a region, it inherits the recorded system.diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.mdindex 19456d337..9562cbbbf 100644--- a/tests/oracle/DELTAS.md+++ b/tests/oracle/DELTAS.md@@ -328,3 +328,13 @@ New cases, recorded from the binary and reviewed by hand:The challenger instruction in direction-scope concept-seed output says what counts as a challenger's clothes. It read `A donation transfers ambition and system discipline, never the challenger's clothes; one world owns the page.` and now reads `A donation transfers ambition and system discipline, never the challenger's clothes. A component treatment, such as a button's shadow or a display face, is clothes, not discipline; one world owns the page.` The lines after it rewrap; their words are unchanged. A gallery run had filed a declined challenger's hard offset shadow on the primary button as a discipline raise.- `seed-direction-local`, `-reroll`, `-unscoped`, `-count-5`, `-operate`, `seed-direction-env-key`, `seed-mode-rules-persuade`, `-experience`, `-missing-file`, `-missing-section`: that sentence only, reviewed by hand. Exit status, stderr and files are unchanged.++## Recorded 2026-10-04: the approved comp is a fixed reference++A comp-led run composited its generated plates into the approved comp, copied those crops in as the plates, and re-ran `comp-spec` so the spec's `compSha256` followed the edit; the plates gate then measured the work against itself. The engine now keeps a copy of the approved comp (`.impeccable/build/approved-comp.<ext>` plus `approved-comp.json`) when a comp is approved, and every entry point that measures against the comp refuses, before measuring, while its pixels differ from that record. `build-phase restore-comp` puts the copy back.++- `build-phase-usage`: the usage line ends `| finish --disposition <word> | restore-comp`. Nothing else in the case moved.++New case, recorded from the binary and reviewed by hand:++- `build-phase-approved-comp-edited`: `start --comp` and `comp-spec --regions` keep the copy (the snapshotted `approved-comp.json` holds the same pixel hash the spec records); after `build.png` is copied over the comp, `advance` fails the spec gate with the single `the approved comp comp.png has changed since approval: expected pixel sha256 <approved>, found <current>. ...` reason, and a re-run of `comp-spec --regions` and a `comp-diff` against the spec's comp exit 2 with the same message on stderr; `restore-comp` prints `RESTORED comp.png from .impeccable/build/approved-comp.png ...` and names `.impeccable/build/edited-comp-<hash>.png`; the next `advance` measures again and fails on the spec gate's own type reading.diff --git a/tests/oracle/cases/comp.mjs b/tests/oracle/cases/comp.mjsindex b6a77216a..e8dda3722 100644--- a/tests/oracle/cases/comp.mjs+++ b/tests/oracle/cases/comp.mjs@@ -88,6 +88,25 @@ const cases = [},{ id: 'build-phase-usage', verb: 'build-phase', workspace: WS, args: [], env: env() },+ // The approved comp is a fixed reference: start keeps a copy, comp-spec binds+ // the same pixels, and once the comp is edited (build.png copied over it, the+ // shape of compositing plates into it) the gate, a re-measure and comp-diff+ // all refuse before measuring. restore-comp puts the approved pixels back and+ // the spec gate measures again (its own readings, not the refusal).+ {+ id: 'build-phase-approved-comp-edited', verb: 'build-phase', workspace: WS,+ files: ['.impeccable/build/approved-comp.json'], env: env(),+ steps: [+ { args: ['start', '--comp', 'comp.png'] },+ { verb: 'comp-spec', args: ['--comp', 'comp.png', '--regions', 'regions.json'] },+ { setup: (ws) => fs.copyFileSync(path.join(ws, 'build.png'), path.join(ws, 'comp.png')), args: ['advance'] },+ { verb: 'comp-spec', args: ['--comp', 'comp.png', '--regions', 'regions.json'] },+ { verb: 'comp-diff', args: ['--comp', 'comp.png', '--build', 'build.png', '--spec', '.impeccable/build/spec.json', '--no-files'] },+ { args: ['restore-comp'] },+ { args: ['advance'] },+ ],+ },+// build-phase responsive (workspace comp-responsive: a menu column ending in a// sign-off line; spec.json and a state at the responsive phase are staged// under .impeccable/build/, which git ignores in fixtures). A desktop capture whosediff --git a/tests/oracle/golden/build-phase-approved-comp-edited.json b/tests/oracle/golden/build-phase-approved-comp-edited.jsonnew file mode 100644index 000000000..e12760e63--- /dev/null+++ b/tests/oracle/golden/build-phase-approved-comp-edited.json@@ -0,0 +1,49 @@+{+ "steps": [+ {+ "stdout": "BUILD-PHASE SPEC comp comp.png breakpoint 768x512\n comps skipped \n spec open \n plates pending \n hero pending \n sections pending \n motion pending \n responsive pending \n review pending \nNEXT Measure the comp: impeccable comp-spec --comp comp.png --grid, open .impeccable/build/comp-grid.png, write regions.json (every illustration, photo, texture as its own plate region; every text block its own text region), run impeccable comp-spec --comp comp.png --regions regions.json. Then measure the type: impeccable font-match --measure <id> for each text region (cap height, width class, weight class) and impeccable font-match --rank <lead text region> --text \"<its first words>\" to choose the headline face by metrics (the USE line is the CSS; with no browser it records the catalog's nearest face, which is the choice; do not install one, and do not write a chosen face into the spec by hand). Then impeccable build-phase advance.\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "WROTE .impeccable/build/spec.json\nSPEC comp comp.png 768x512 landscape\nPALETTE #f7e8e8(69%) #182838(14%) #9a9aa5(7%) #c5c5d1(7%) #7c7c82(4%)\nBANDS 6% 9% 14% 18% 20% 24% 47% 51% 54% 58% 60% 64% 66% 69% 72% 75% 78% 81% 84% 88% 91% 98%\nREGION top chrome semantic box x0% y0% w100% h20% (768x102px, 7.5294:1) palette #f5e7e8 #182838 #bdbdc8 # top masthead band area\nREGION art plate raster box x40% y20% w60% h30% (461x154px, 2.9935:1) palette #e6dfe5 #a2a2ad #7f7f88 plate assets/plates/art.png # an exploded illustration drawing\nREGION body text semantic box x0% y50% w40% h40% (307x205px, 1.4976:1) palette #f8e8e8 #182838 #787878 # a paragraph of body text content\nPLATES 1 to produce: art\nRULE anything not in this list does not exist on the page: no borders, rules, chrome, or containers the comp does not show. Every raster region ships as its plate, never as CSS.\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "GATE SPEC FAILED (state unchanged)\n - the approved comp comp.png has changed since approval: expected pixel sha256 4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e, found d1a3b9afdc27007e973dc2578d240b8b11253a482c6ecd1d19cc4fdf1d8590ac. The approved comp is the fixed reference every gate measures against; never edit it, composite into it, or regenerate it. Nothing was measured against the changed file. Restore it with impeccable build-phase restore-comp (the engine kept the approved copy at .impeccable/build/approved-comp.png), then regenerate the plates or change the page code until they match the unchanged comp.\n",+ "stderr": "",+ "exit": 2,+ "signal": null+ },+ {+ "stdout": "",+ "stderr": "comp-spec: the approved comp comp.png has changed since approval: expected pixel sha256 4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e, found d1a3b9afdc27007e973dc2578d240b8b11253a482c6ecd1d19cc4fdf1d8590ac. The approved comp is the fixed reference every gate measures against; never edit it, composite into it, or regenerate it. Nothing was measured against the changed file. Restore it with impeccable build-phase restore-comp (the engine kept the approved copy at .impeccable/build/approved-comp.png), then regenerate the plates or change the page code until they match the unchanged comp.\n",+ "exit": 2,+ "signal": null+ },+ {+ "stdout": "",+ "stderr": "comp-diff: the approved comp comp.png has changed since approval: expected pixel sha256 4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e, found d1a3b9afdc27007e973dc2578d240b8b11253a482c6ecd1d19cc4fdf1d8590ac. The approved comp is the fixed reference every gate measures against; never edit it, composite into it, or regenerate it. Nothing was measured against the changed file. Restore it with impeccable build-phase restore-comp (the engine kept the approved copy at .impeccable/build/approved-comp.png), then regenerate the plates or change the page code until they match the unchanged comp.\n",+ "exit": 2,+ "signal": null+ },+ {+ "stdout": "RESTORED comp.png from .impeccable/build/approved-comp.png (pixel sha256 4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e). The edited file is kept at .impeccable/build/edited-comp-d1a3b9afdc27.png as evidence, not as a comp. Re-run the step that refused; plates and page code built against the edited comp now have to match the approved one.\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "GATE SPEC FAILED (state unchanged)\n - measure the type before closing the spec: impeccable font-match --measure <id> for each text region (body); the region with the largest cap height is the lead and gets --rank.\n",+ "stderr": "",+ "exit": 2,+ "signal": null+ }+ ],+ "files": {+ ".impeccable/build/approved-comp.json": "{\n \"comp\": \"comp.png\",\n \"pixelSha256\": \"4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e\",\n \"fileSha256\": \"b4dd0dcead73188eb9a4043e70f9050c8a397182d3dfbad6f4be4f06a6a1db64\",\n \"copy\": \".impeccable/build/approved-comp.png\",\n \"at\": \"<ISO>\"\n}"+ }+}diff --git a/tests/oracle/golden/build-phase-usage.json b/tests/oracle/golden/build-phase-usage.jsonindex 6adf29c6b..27c00d614 100644--- a/tests/oracle/golden/build-phase-usage.json+++ b/tests/oracle/golden/build-phase-usage.json@@ -1,6 +1,6 @@{"stdout": "CANDIDATE CHECK: build-phase check-plate <region-id> --candidate <png> [--json] validates a separate file with the normal plate gate; never replaces the selected asset, records approval, or advances the phase.\n",- "stderr": "usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word>\n",+ "stderr": "usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n","exit": 1,"signal": null,"files": {}