Skip to content

The design language that makes your AI harness better at design.

JavaScript

Responsive gate: displaced regions, lapse reason, crops and escalation, pinned clock (#922)

Paul Bakaus0f7311d36c53
diff --git a/crates/browser/src/cdp.rs b/crates/browser/src/cdp.rs
index 9058cd5c4..617871fbf 100644
--- a/crates/browser/src/cdp.rs
+++ b/crates/browser/src/cdp.rs
@@ -1017,6 +1017,20 @@ impl<'a> Page<'a> {
true
}
+ /// Start the page's clock at `epoch_ms` for every document this page loads:
+ /// `new Date()`, `Date()`, `Date.now()` and an argument-less
+ /// `Intl.DateTimeFormat` format begin at that instant and advance in real
+ /// time, so a page that renders the current time or day renders the same
+ /// state in every capture pinned to the same instant, while code that measures
+ /// elapsed time still sees time pass. Call before navigating.
+ pub fn pin_clock(&mut self, epoch_ms: f64) -> CdpResult<()> {
+ if !epoch_ms.is_finite() {
+ return Err(CdpError::new("pinned clock must be a finite epoch"));
+ }
+ self.send("Page.addScriptToEvaluateOnNewDocument", json!({ "source": pinned_clock_script(epoch_ms) }))?;
+ Ok(())
+ }
+
/// Explicit screenshot-environment preference; never injected as page CSS.
pub fn set_reduced_motion(&mut self, reduce: bool) -> CdpResult<()> {
self.send("Emulation.setEmulatedMedia", json!({"features": [{
@@ -1640,3 +1654,14 @@ mod tests {
assert!(with.contains(&"about:blank".to_string()));
}
}
+
+/// The page-side half of [`Page::pin_clock`].
+pub fn pinned_clock_script(epoch_ms: f64) -> String {
+ format!(r#"(()=>{{const T={epoch},P=performance.now(),N=Date;const now=()=>Math.floor(T+performance.now()-P);
+const D=new Proxy(N,{{construct(t,a,nt){{return Reflect.construct(N,a.length?a:[now()],nt)}},apply(){{return new N(now()).toString()}},get(t,k,r){{return k==="now"?now:Reflect.get(t,k,r)}}}});
+Object.defineProperty(globalThis,"Date",{{value:D,writable:true,configurable:true,enumerable:false}});
+Object.defineProperty(N.prototype,"constructor",{{value:D,writable:true,configurable:true,enumerable:false}});
+const F=Intl.DateTimeFormat.prototype,g=Object.getOwnPropertyDescriptor(F,"format").get,p=F.formatToParts;
+Object.defineProperty(F,"format",{{configurable:true,get(){{const f=g.call(this);return d=>f(d===undefined?now():d)}}}});
+F.formatToParts=function(d){{return p.call(this,d===undefined?now():d)}};}})()"#, epoch = epoch_ms.floor() as i64)
+}
diff --git a/crates/cli/src/asset_capture.rs b/crates/cli/src/asset_capture.rs
index 62a5dd3b7..a884d2add 100644
--- a/crates/cli/src/asset_capture.rs
+++ b/crates/cli/src/asset_capture.rs
@@ -17,13 +17,20 @@ use std::{
pub struct CdpAssetRenderer {
env: HashMap<String, String>,
+ clock_ms: Option<f64>,
}
impl CdpAssetRenderer {
pub fn from_process_env() -> Self {
Self {
env: impeccable_common::process_env(),
+ clock_ms: None,
}
}
+ /// Pin the page's clock (see `Page::pin_clock`) for every capture this renderer makes.
+ pub fn pinned_at(mut self, epoch_ms: f64) -> Self {
+ self.clock_ms = Some(epoch_ms);
+ self
+ }
}
impl AssetRenderer for CdpAssetRenderer {
fn capture(&mut self, request: &AssetCaptureRequest) -> Result<AssetCapture, String> {
@@ -73,6 +80,9 @@ impl AssetRenderer for CdpAssetRenderer {
.map_err(|e| e.message)?;
page.set_reduced_motion(request.reduced_motion)
.map_err(|e| e.message)?;
+ if let Some(clock_ms) = self.clock_ms {
+ page.pin_clock(clock_ms).map_err(|e| e.message)?;
+ }
page.begin_response_capture().map_err(|e| e.message)?;
page.goto(&request.url, "load", Duration::from_secs(30))
.map_err(|e| e.message)?;
diff --git a/crates/cli/src/component_capture.rs b/crates/cli/src/component_capture.rs
index f53e22939..c58d39eff 100644
--- a/crates/cli/src/component_capture.rs
+++ b/crates/cli/src/component_capture.rs
@@ -11,6 +11,10 @@ use serde_json::{Value, json};
use std::{collections::BTreeMap, sync::Arc, time::Duration};
pub struct NativeComponentCapturer;
+/// Milliseconds since the epoch, for pinning a capture's clock.
+pub(crate) fn now_ms() -> f64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as f64).unwrap_or(0.)
+}
fn hash(bytes: &[u8]) -> String {
// The PNG module and review store use the same SHA-256; avoid a second hash contract.
use sha2::{Digest, Sha256};
@@ -65,6 +69,7 @@ pub(crate) fn render_page(
assembled: bool,
check_fonts: bool,
measure_raster: bool,
+ clock_ms: f64,
) -> Result<(Vec<u8>, Value), String> {
let server = if assembled { snapshot.serve_assembled()? } else { snapshot.serve()? };
let url = server.entry_url();
@@ -74,6 +79,7 @@ pub(crate) fn render_page(
page.set_viewport(Viewport { width, height })
.map_err(|e| e.message)?;
page.set_reduced_motion(true).map_err(|e| e.message)?;
+ page.pin_clock(clock_ms).map_err(|e| e.message)?;
page.begin_response_capture().map_err(|e| e.message)?;
page.goto(&url, "networkidle0", Duration::from_secs(20))
.map_err(|e| e.message)?;
@@ -195,6 +201,7 @@ pub(crate) fn render_page(
proof["capturedDomSha256"] = json!(hash(captured_dom.as_str().unwrap().as_bytes()));
}
proof["fonts"] = fonts;
+ proof["clock"] = json!({"pinnedEpochMs": clock_ms.floor() as i64, "policy": "the page's Date starts at the pinned instant and advances in real time"});
if let Some(coverage) = raster_coverage {
proof["rasterCoverage"] = coverage;
}
@@ -253,6 +260,9 @@ impl ComponentCapturer for NativeComponentCapturer {
discovery::find_browser(&env).map_err(|e| format!("browser unavailable: {e:?}"))?;
let mut browser = Browser::launch(&exe, &[], false).map_err(|e| e.message)?;
let version = browser.version().map_err(|e| e.message)?;
+ // One instant for every view of this round, recorded in each proof, so a
+ // gate capture of an approved view can render the same time of day.
+ let clock_ms = now_ms();
let result = (|| {
let mut files = BTreeMap::new();
let mut evidence = Vec::new();
@@ -308,7 +318,7 @@ impl ComponentCapturer for NativeComponentCapturer {
let (png, proof) = if let Some(saved) = cache.get(&cache_key) {
saved.clone()
} else {
- let captured = match render_page(&mut browser, snapshot, width, height, &c["box"], isolation.as_ref(), assembled, check_fonts, false) {
+ let captured = match render_page(&mut browser, snapshot, width, height, &c["box"], isolation.as_ref(), assembled, check_fonts, false, clock_ms) {
Ok(captured) => captured,
Err(error) => {
errors.push(format!("{id} {key}: {error}"));
diff --git a/crates/cli/src/entry_capture.rs b/crates/cli/src/entry_capture.rs
index 660aded86..aeae7de3f 100644
--- a/crates/cli/src/entry_capture.rs
+++ b/crates/cli/src/entry_capture.rs
@@ -50,6 +50,22 @@ impl EntryRenderer for CdpEntryRenderer {
self.capture_forbidding(request, &[])
}
}
+/// The instant a capture's clock is pinned to, and where it came from.
+#[derive(Clone, Copy)]
+pub struct CaptureClock {
+ pub epoch_ms: f64,
+ /// True when the instant is the one an approved review screenshot was captured at.
+ pub from_review: bool,
+}
+impl CaptureClock {
+ pub fn now() -> Self {
+ Self { epoch_ms: crate::component_capture::now_ms(), from_review: false }
+ }
+ fn json(&self) -> Value {
+ json!({"pinnedEpochMs": self.epoch_ms.floor() as i64, "source": if self.from_review { "approved-review" } else { "capture-start" },
+ "policy": "every frame's Date starts at the pinned instant and advances in real time"})
+ }
+}
impl CdpEntryRenderer {
/// `forbidden` holds approved images (a reviewed screenshot) that a text-only
/// page must not load or embed; the bound comp is always forbidden there.
@@ -57,6 +73,18 @@ impl CdpEntryRenderer {
&self,
request: &EntryRequest,
forbidden: &[&[u8]],
+ ) -> Result<Box<dyn CapturedEntry>, String> {
+ self.capture_at(request, forbidden, CaptureClock::now())
+ }
+
+ /// As [`Self::capture_forbidding`], with every frame's clock pinned to `clock`:
+ /// a page that renders the time or day shows the same state in each frame,
+ /// and the same state as an approved screenshot captured at that instant.
+ pub fn capture_at(
+ &self,
+ request: &EntryRequest,
+ forbidden: &[&[u8]],
+ clock: CaptureClock,
) -> Result<Box<dyn CapturedEntry>, String> {
// The shared gate chooses the entry/spec/reference, never a caller URL.
let served = static_inventory(&request.root)?;
@@ -102,10 +130,10 @@ impl CdpEntryRenderer {
],
};
if ids.is_empty() {
- return capture_text_only(request, snapshot, &served, &frames, forbidden);
+ return capture_text_only(request, snapshot, &served, &frames, forbidden, clock);
}
let mut evidence = EntryEvidence {
- report: json!({"schema":"native-entry-capture-v1","inputSnapshot":snapshot.digest(),"manifest":snapshot.manifest(),"artifact":request.artifact,"stage":match request.stage {EntryStage::Hero=>"hero",EntryStage::Responsive=>"responsive"},"scope":"Fresh static HTML rendering and scoped raster evidence. No independent aesthetic approval."}),
+ report: json!({"schema":"native-entry-capture-v1","inputSnapshot":snapshot.digest(),"manifest":snapshot.manifest(),"artifact":request.artifact,"stage":match request.stage {EntryStage::Hero=>"hero",EntryStage::Responsive=>"responsive"},"scope":"Fresh static HTML rendering and scoped raster evidence. No independent aesthetic approval.","clock":clock.json()}),
frames: vec![],
};
for (name, viewport) in frames {
@@ -117,7 +145,7 @@ impl CdpEntryRenderer {
&ids[..]
};
let regions = snapshot.capture_regions_at_viewport(
- &mut CdpAssetRenderer::from_process_env(),
+ &mut CdpAssetRenderer::from_process_env().pinned_at(clock.epoch_ms),
&request.spec,
selected,
true,
@@ -190,6 +218,7 @@ fn capture_text_only(
inventory: &[String],
frames: &[(&str, Option<[u32; 2]>)],
forbidden: &[&[u8]],
+ clock: CaptureClock,
) -> Result<Box<dyn CapturedEntry>, String> {
let spec: Value = serde_json::from_slice(raster.bytes(&request.spec).ok_or("missing bound spec")?)
.map_err(|e| e.to_string())?;
@@ -237,7 +266,7 @@ fn capture_text_only(
let result = (|| -> Result<EntryEvidence, String> {
let browser_version = browser.version().map_err(|e| e.message)?;
let mut evidence = EntryEvidence {
- report: json!({"schema":"native-entry-capture-v1","inputSnapshot":raster.digest(),"manifest":raster.manifest(),"artifact":request.artifact,"stage":match request.stage {EntryStage::Hero=>"hero",EntryStage::Responsive=>"responsive"},"scope":"Fresh static HTML rendering of a first viewport with no raster region. No independent aesthetic approval.","captureMethod":"assembled-page-viewport","integrityScope":"assembled-page viewport from frozen inputs; the comp and approved screenshots are never served; images cover under 15% of each frame; no raster presence check (no raster region)","dependencyPolicy":policy,"servedToPage":page.manifest()["files"],"browser":browser_version,"frameProofs":{}}),
+ report: json!({"schema":"native-entry-capture-v1","inputSnapshot":raster.digest(),"manifest":raster.manifest(),"artifact":request.artifact,"stage":match request.stage {EntryStage::Hero=>"hero",EntryStage::Responsive=>"responsive"},"scope":"Fresh static HTML rendering of a first viewport with no raster region. No independent aesthetic approval.","captureMethod":"assembled-page-viewport","integrityScope":"assembled-page viewport from frozen inputs; the comp and approved screenshots are never served; images cover under 15% of each frame; no raster presence check (no raster region)","dependencyPolicy":policy,"servedToPage":page.manifest()["files"],"browser":browser_version,"frameProofs":{},"clock":clock.json()}),
frames: vec![],
};
for &(name, viewport) in frames {
@@ -252,6 +281,7 @@ fn capture_text_only(
true,
true,
true,
+ clock.epoch_ms,
)
.map_err(|e| {
// Both the network check and the image-decode check name the path
diff --git a/crates/cli/src/reviewed_entry.rs b/crates/cli/src/reviewed_entry.rs
index 04499c340..ce0315ab0 100644
--- a/crates/cli/src/reviewed_entry.rs
+++ b/crates/cli/src/reviewed_entry.rs
@@ -3,7 +3,7 @@
//! shared-CSS edits keep it while the first viewport still matches. It is evidence
//! for the first viewport's scores, never a
//! replacement for native integrity, missing-region, or overall fidelity gates.
-use crate::entry_capture::CdpEntryRenderer;
+use crate::entry_capture::{CaptureClock, CdpEntryRenderer};
use impeccable_comp_verbs::asset_capture::capture_sha256;
use impeccable_comp_verbs::entry_capture::{
ApprovedReference, CapturedEntry, EntryEvidence, EntryRenderer, EntryRequest,
@@ -128,10 +128,13 @@ fn reference(session: &Path, r: &EntryRequest) -> Result<ApprovedReference, Stri
if capture_sha256(&png) != hash {
return Err("reviewed screenshot changed".into());
}
- Ok(ApprovedReference {
- png,
- proof: json!({"schema":"human-assembled-reference-v1","requestId":packet["id"],"packetRevision":packet["revision"],"sha256":hash,"scope":"First viewport accepted in an assembled-page review; valid while the current capture matches this screenshot; material gates retained"}),
- })
+ let mut proof = json!({"schema":"human-assembled-reference-v1","requestId":packet["id"],"packetRevision":packet["revision"],"sha256":hash,"scope":"First viewport accepted in an assembled-page review; valid while the current capture matches this screenshot; material gates retained"});
+ // The instant the approved screenshot's clock was pinned to (reviews captured
+ // before pinning carry none); gate captures render at the same instant.
+ if let Some(clock) = capture["clock"]["pinnedEpochMs"].as_f64().filter(|c| c.is_finite()) {
+ proof["pinnedClockMs"] = json!(clock.floor() as i64);
+ }
+ Ok(ApprovedReference { png, proof })
}
impl EntryRenderer for ReviewedEntryRenderer {
fn capture_entry(&self, r: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {
@@ -141,7 +144,9 @@ impl EntryRenderer for ReviewedEntryRenderer {
.map(|s| reference(s, r));
// A code-only page must not load or inline the screenshot the user approved.
let approved_png: Vec<&[u8]> = candidate.iter().filter_map(|c| c.as_ref().ok()).map(|a| a.png.as_slice()).collect();
- let source = CdpEntryRenderer.capture_forbidding(r, &approved_png)?;
+ let clock = candidate.iter().filter_map(|c| c.as_ref().ok()).find_map(|a| a.proof["pinnedClockMs"].as_f64())
+ .map(|epoch_ms| CaptureClock { epoch_ms, from_review: true }).unwrap_or_else(CaptureClock::now);
+ let source = CdpEntryRenderer.capture_at(r, &approved_png, clock)?;
let mut report = source.evidence().report.clone();
if let Some(Err(reason)) = &candidate {
report["humanTextReview"] = json!({"status":"not-current","reason":reason});
diff --git a/crates/cli/tests/text_only_entry.rs b/crates/cli/tests/text_only_entry.rs
index b6da93a1c..164c6379c 100644
--- a/crates/cli/tests/text_only_entry.rs
+++ b/crates/cli/tests/text_only_entry.rs
@@ -564,3 +564,38 @@ fn host_capture_service_carries_a_text_only_hero_and_binds_its_accepted_review()
}
assert_eq!(fs::read_to_string(f.project.join(".impeccable/review/native/hero/hero-observations.json")).unwrap().trim(), "[]");
}
+
+#[test]
+fn capture_clock_is_pinned_and_an_approved_review_lends_its_instant() {
+ if !browser_available() {
+ return;
+ }
+ use impeccable::entry_capture::CaptureClock;
+ let f = Fixture::new();
+ // The bars' widths follow the hour, as a page that prints "open now" does:
+ // one through `new Date()`, one through an argument-less Intl format.
+ fs::write(f.project.join("index.html"), format!("{PAGE}<script>const h=new Date().getUTCHours();const p=new Intl.DateTimeFormat('en-US',{{timeZone:'UTC',hour:'numeric',hourCycle:'h23'}}).formatToParts().find(x=>x.type==='hour').value;document.querySelector('h1').style.width=(new Date().constructor===Date&&new Date(0) instanceof Date?16+h*8:4)+'px';document.querySelector('header').style.width=(16+Number(p)*8)+'px';</script>")).unwrap();
+ let at = |hour: u64| CaptureClock { epoch_ms: (1_790_000_000_000u64 / 86_400_000 * 86_400_000 + hour * 3_600_000) as f64, from_review: false };
+ let frame = |clock: CaptureClock| {
+ let captured = CdpEntryRenderer.capture_at(&f.request(EntryStage::Hero), &[], clock).unwrap();
+ assert_eq!(captured.evidence().report["clock"]["pinnedEpochMs"].as_f64(), Some(clock.epoch_ms));
+ captured.evidence().frames[0].png.clone()
+ };
+ let (two, two_again, nine) = (frame(at(2)), frame(at(2)), frame(at(9)));
+ assert_eq!(two, two_again, "the same instant renders the same page");
+ assert_ne!(two, nine, "the pinned instant is the one the page sees");
+ // An approval captured at a pinned instant hands that instant to the gate's capture.
+ f.approve(&two);
+ let path = f.session().join("current.json");
+ let mut state: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
+ for pointer in ["/capture/components/0/views/preview", "/receipt/capture/components/0/views/preview"] {
+ state.pointer_mut(pointer).unwrap()["clock"] = json!({"pinnedEpochMs": at(2).epoch_ms as i64});
+ }
+ fs::write(&path, serde_json::to_vec(&state).unwrap()).unwrap();
+ let renderer = ReviewedEntryRenderer::local(&f.project, Some(&f.home));
+ let captured = renderer.capture_entry(&f.request(EntryStage::Hero)).unwrap();
+ let report = &captured.evidence().report;
+ assert_eq!(report["clock"]["source"], "approved-review", "{report}");
+ assert_eq!(report["clock"]["pinnedEpochMs"].as_f64(), Some(at(2).epoch_ms));
+ assert_eq!(captured.evidence().frames[0].png, two);
+}
diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rs
index bd3862df5..8734d0eff 100644
--- a/crates/comp-verbs/src/build_phase.rs
+++ b/crates/comp-verbs/src/build_phase.rs
@@ -20,6 +20,7 @@ use serde_json::{json, Map, Value};
use crate::comp_diff::{align_build, best_shift, build_report, compare, write_artifacts, write_region_artifacts, CompareResult, Score};
use crate::comp_spec::{load_spec, prepare_plate_reference, PlateReference, BUILD_DIR, SPEC_PATH};
+use crate::displacement::{Displacement, Rect as DRect};
use crate::font_match::choice_stamped;
use crate::entry_capture::{CapturedEntry, EntryRenderer, EntryRequest, EntryStage};
use crate::util::{self, arg, flag, round, to_fixed};
@@ -1638,14 +1639,27 @@ fn human_accepted_viewport(human: Option<&Value>) -> bool {
}
/// When the user accepted a first viewport that the current capture no longer
-/// matches: the reason that replaces the raw score.
+/// matches: the reason that replaces the raw score. It names the regions that
+/// changed since the acceptance (those that no longer render as accepted), or,
+/// when the drift is spread thin, the three furthest from it.
fn lapsed_viewport(human: Option<&Value>, frame: &str) -> Option<String> {
let c = &human?["comparison"];
if human_accepted_viewport(human) { return None; }
- let changed: Vec<&str> = c["regions"].as_array().into_iter().flatten()
- .filter(|r| matches!(r["verdict"].as_str(), Some("missing" | "contradicted"))).filter_map(|r| r["id"].as_str()).collect();
+ let rows: Vec<&Value> = c["regions"].as_array().into_iter().flatten().collect();
+ let mut changed: Vec<&str> = rows.iter().filter(|r| !region_still_accepted(r)).filter_map(|r| r["id"].as_str()).collect();
+ let spread = changed.is_empty();
+ if spread {
+ let mut sorted = rows.clone();
+ sorted.sort_by(|a, b| rscore(a, "overall").total_cmp(&rscore(b, "overall")));
+ changed = sorted.iter().take(3).filter_map(|r| r["id"].as_str()).collect();
+ }
Some(format!("the {frame} no longer matches the first viewport the user accepted ({}% against the approved screenshot{}), so that acceptance no longer covers the scores. Restore what the user accepted; until then the readings apply.",
- pct0(c["overall"].as_f64().unwrap_or(0.)), if changed.is_empty() { String::new() } else { format!("; changed: {}", changed.join(", ")) }))
+ pct0(c["overall"].as_f64().unwrap_or(0.)), if changed.is_empty() { String::new() } else if spread { format!("; furthest from it: {}", changed.join(", ")) } else { format!("; changed since the acceptance: {}{}", changed.iter().take(6).copied().collect::<Vec<_>>().join(", "), if changed.len() > 6 { format!(" and {} more", changed.len() - 6) } else { String::new() }) }))
+}
+
+/// A region of the approved-vs-current comparison that still renders as accepted.
+fn region_still_accepted(v: &Value) -> bool {
+ matches!(v["verdict"].as_str(), Some("match" | "drift")) && rscore(v, "structure") >= 0.75
}
/// Code regions (text, control, chrome) an accepted first-viewport review
@@ -1653,7 +1667,7 @@ fn lapsed_viewport(human: Option<&Value>, frame: &str) -> Option<String> {
fn human_accepted_regions(human: Option<&Value>, regions: &[Value]) -> std::collections::HashSet<String> {
let reviewed = human.and_then(|h| h["comparison"]["regions"].as_array()).cloned().unwrap_or_default();
regions.iter().filter(|r| matches!(r["kind"].as_str(), Some("text" | "control" | "chrome")))
- .filter(|r| reviewed.iter().any(|v| v["id"] == r["id"] && matches!(v["verdict"].as_str(), Some("match" | "drift")) && rscore(v, "structure") >= 0.75))
+ .filter(|r| reviewed.iter().any(|v| v["id"] == r["id"] && region_still_accepted(v)))
.filter_map(|r| r["id"].as_str().map(String::from)).collect()
}
@@ -2113,8 +2127,8 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
// Say why the acceptance does not hold instead of arguing the raw score.
match reasons.iter().position(|r| r.starts_with("hero overall")) {
Some(i) => { advisories.push(format!("(measured) {}", reasons[i])); reasons[i] = lapse; }
- None if reasons.iter().any(|r| !material.contains(r)) => reasons.insert(0, lapse),
- None => {}
+ None if !reasons.is_empty() => reasons.insert(0, lapse),
+ None => advisories.insert(0, format!("(advisory) {lapse}")),
}
}
if let Some(h) = human {
@@ -2258,6 +2272,34 @@ fn hero_loop_verdict(state: &mut Value, gate: &Gate, artifact_path: &str, io: &I
None
}
+/// Failed responsive attempts in a row before the gate stops asking for edits.
+/// Three, as at the hero: past that, the readings have had their chance.
+const RESPONSIVE_ATTEMPTS: usize = 3;
+
+/// The responsive gate's loop record, and the escalation once it has failed
+/// RESPONSIVE_ATTEMPTS times in a row: the same route the hero takes, so a
+/// stalled desktop width reaches the user instead of a recorded `fix`.
+fn responsive_loop_verdict(state: &mut Value, gate: &Gate, viewport_accepted: bool, s: &str) -> Option<String> {
+ let phase = state.pointer_mut("/phases/responsive")?.as_object_mut()?;
+ let mut history: Vec<Value> = phase.get("history").and_then(Value::as_array).cloned().unwrap_or_default();
+ history.push(json!({ "at": now(), "score": gate.score.map(util::num).unwrap_or(Value::Null), "worstIds": gate.worst_ids, "blockingReasons": gate.reasons }));
+ let start = history.len().saturating_sub(6);
+ phase.insert("history".into(), json!(history[start..].to_vec()));
+ if gate.ok || history.len() < RESPONSIVE_ATTEMPTS {
+ return None;
+ }
+ let recent = &history[history.len() - RESPONSIVE_ATTEMPTS..];
+ if !recent.iter().all(|h| h["blockingReasons"].as_array().is_some_and(|a| !a.is_empty())) {
+ return None;
+ }
+ let lead = format!("The responsive gate has failed {RESPONSIVE_ATTEMPTS} attempts in a row.");
+ let side = gate.side_by_side.as_deref().unwrap_or(".impeccable/review/diff/desktop/side-by-side.png");
+ if viewport_accepted {
+ return Some(format!("{lead} The user already accepted a first viewport, so that review is closed. Stop iterating: show the user {side} with the regions below, and ask them to choose between restoring those regions at desktop width and keeping the desktop first viewport as it renders. Keeping it downgrades the comp at desktop width, so it takes their words saying so, quoted in {s} build-phase advance --force --reason (for example: the user said: \"the comp does not need to match at desktop width\"); force refuses any other reason. Until they answer, this phase stays open; a finish recorded over it is an unfinished build, not a fix round."));
+ }
+ Some(format!("{lead} Stop iterating and present the first-viewport review (the assembled hero, stage hero, in component-review.md) with the current page, so the user judges the first viewport in context. An accepted review carries to desktop width while the desktop capture still matches the approved screenshot; displaced and missing regions still block. Until then this phase stays open; a finish recorded over it is an unfinished build, not a fix round."))
+}
+
fn hash_file(io: &Io, file: &str) -> Option<String> {
use sha1::{Digest, Sha1};
let data = std::fs::read(abs(io, file)).ok()?;
@@ -2314,93 +2356,202 @@ fn gate_responsive_inner(io: &Io, state: &mut Value, min: f64, out_dir: &str, na
Err(e) => return Gate::fail(vec![format!("comp-diff failed on {desktop}: {e}")]),
};
let mut regions: Vec<Value> = report.get("regions").and_then(Value::as_array).cloned().unwrap_or_default();
- let missing: Vec<Value> = regions
- .iter()
- .filter(|r| {
- if r.get("verdict").and_then(Value::as_str) != Some("missing") || r.get("kind").and_then(Value::as_str) == Some("texture") {
- return false;
- }
- let id = r.get("id").and_then(Value::as_str).unwrap_or("");
- let passed = spec.as_ref().is_some_and(|spec| spec_regions(spec).iter().any(|region|
- region.get("id").and_then(Value::as_str) == Some(id) && plate_receipt_current(io, state, spec, region)));
- let kind = r.get("kind").and_then(Value::as_str).unwrap_or("");
- if (kind == "plate" || kind == "image") && passed {
- let present = rscore_opt(r, "detailRaw").map(|v| v >= 0.3).unwrap_or(rscore(r, "detail") >= 0.3);
- if present && rscore(r, "structure") >= 0.5 {
- return false;
- }
- }
- true
- })
- .cloned().collect();
- // Keep the original scores and all missing/integrity/overall blockers.
- // A human-approved assembly can qualify a text-style contradiction only
- // when that region still matches the approved rendering at desktop width.
- let accepted_text = native.and_then(|n| n.capture.approved_reference().map(|a|(n,a)))
- .and_then(|(n,a)| hero_diff_labeled(io,&n.path("human-approved"),desktop,spec.as_ref(),&format!("{out_dir}/human-reviewed"),"human-reviewed").ok().map(|(r,_)|(r,a.proof.clone())));
- if let Some((comparison,proof))=&accepted_text {report["humanTextReview"]=json!({"proof":proof,"comparison":comparison});}
- let contradicted_direction: Vec<Value> = regions.iter().filter(|r| r.get("verdict").and_then(Value::as_str) == Some("contradicted") && matches!(r.get("kind").and_then(Value::as_str), Some("text" | "control"))).cloned().collect();
- for region in &mut regions {
- if region.get("verdict").and_then(Value::as_str) == Some("missing")
- && matches!(region.get("kind").and_then(Value::as_str), Some("plate" | "image"))
- && !missing.iter().any(|r| r.get("id") == region.get("id")) {
+ // Where a region went when it is not at its box: the comp, and the capture at
+ // the comp's width with its full height (a full-page capture keeps what lies
+ // below the first viewport; a native frame is the first viewport alone).
+ let images = load_raster(io, comp_path).ok().zip(load_raster(io, desktop).ok());
+ let frame = images.as_ref().map(|(comp, capture)| {
+ let k = capture.width as f64 / comp.width as f64;
+ let tall = r::resize(capture, comp.width as f64, round(capture.height as f64 / k));
+ (k, tall)
+ });
+ // A match that lands on another region of the same kind and size, where that
+ // region still renders as itself, is its own pixels (two identical icons), not
+ // this one moved. A neighbour that is itself gone or moved leaves its box free.
+ let same_shape: Vec<(String, String, [f64; 4])> = regions.iter().filter(|r| matches!(r["verdict"].as_str(), Some("match" | "drift")))
+ .filter_map(|r| Some((r["id"].as_str()?.to_string(), r["kind"].as_str()?.to_string(),
+ [r["x"].as_f64()?, r["y"].as_f64()?, r["w"].as_f64()?, r["h"].as_f64()?]))).collect();
+ let locate = |r: &Value| -> Option<Displacement> {
+ let ((comp, _), (_, tall)) = (images.as_ref()?, frame.as_ref()?);
+ let f = |k: &str| r[k].as_f64().unwrap_or(0.);
+ let (cw, ch) = (comp.width as f64, comp.height as f64);
+ let d = crate::displacement::find(comp, tall, ch, DRect { x: f("x") * cw, y: f("y") * ch, w: f("w") * cw, h: f("h") * ch }, r["kind"].as_str())?;
+ let moved = [f("x") + d.dx / cw, f("y") + d.dy / ch, f("w"), f("h")];
+ let lookalike = same_shape.iter().any(|(id, kind, b)| {
+ if Some(id.as_str()) == r["id"].as_str() || Some(kind.as_str()) != r["kind"].as_str() { return false; }
+ let ratio = (b[2] * b[3]) / (moved[2] * moved[3]).max(1e-9);
+ let ix = ((moved[0] + moved[2]).min(b[0] + b[2]) - moved[0].max(b[0])).max(0.);
+ let iy = ((moved[1] + moved[3]).min(b[1] + b[3]) - moved[1].max(b[1])).max(0.);
+ (0.5..=2.0).contains(&ratio) && ix * iy >= 0.5 * moved[2] * moved[3]
+ });
+ (!lookalike).then_some(d)
+ };
+ // Offsets in the capture's own pixels, the ones the agent edits.
+ let k = frame.as_ref().map(|(k, _)| *k).unwrap_or(1.);
+ let frame_size = images.as_ref().map(|(comp, capture)| format!("{}x{}", capture.width, round(comp.height as f64 * k) as i64)).unwrap_or_default();
+ let passed = |id: &str| spec.as_ref().is_some_and(|spec| spec_regions(spec).iter().any(|region|
+ region.get("id").and_then(Value::as_str) == Some(id) && plate_receipt_current(io, state, spec, region)));
+ let mut region_reasons = Map::new();
+ let mut advisories: Vec<String> = Vec::new();
+ let mut missing_reasons: Vec<(String, String)> = Vec::new();
+ for region in regions.iter_mut() {
+ let id = region["id"].as_str().unwrap_or("").to_string();
+ let kind = region["kind"].as_str().unwrap_or("").to_string();
+ let verdict = region["verdict"].as_str().unwrap_or("").to_string();
+ let plate = kind == "plate" || kind == "image";
+ if kind == "texture" || !(verdict == "missing" || (verdict == "contradicted" && matches!(kind.as_str(), "text" | "control" | "chrome"))) {
+ continue;
+ }
+ // A plate that passed its asset gate and renders at desktop width is present;
+ // where it sits is placement, which the overall bar and the native frame check guard.
+ let present_plate = plate && verdict == "missing" && passed(&id)
+ && rscore_opt(region, "detailRaw").map(|v| v >= 0.3).unwrap_or(rscore(region, "detail") >= 0.3);
+ if present_plate && rscore(region, "structure") >= 0.5 {
region["verdict"] = json!("drift");
region["verdictReason"] = json!("current plate passed asset validation and responsive rendered presence check");
+ continue;
+ }
+ match locate(region) {
+ Some(d) if d.beyond_frame() => {
+ let message = displaced_message(&id, &d, k, &frame_size);
+ region["verdict"] = json!("displaced");
+ region["verdictReason"] = json!("present, but displaced past the first viewport");
+ region["displacement"] = displacement_json(&d, k);
+ missing_reasons.push((id, message));
+ }
+ Some(d) => {
+ region["verdict"] = json!("drift");
+ region["verdictReason"] = json!("present, displaced inside the first viewport");
+ region["displacement"] = displacement_json(&d, k);
+ advisories.push(format!("(advisory, still inside the first viewport) at desktop width, region {id} sits {} than in the comp", offset_words(d.dx * k, d.dy * k)));
+ }
+ None if present_plate => {
+ region["verdict"] = json!("drift");
+ region["verdictReason"] = json!("current plate passed asset validation and renders at desktop width away from its comp box");
+ advisories.push(format!("(advisory) at desktop width, plate {id} renders but not at its comp box (structure {}%): size and position it to the spec box", pct0(rscore(region, "structure"))));
+ }
+ None if verdict == "missing" => missing_reasons.push((id.clone(), format!("at desktop width, region {id} is missing"))),
+ None => {}
}
}
- let mut region_reasons = Map::new();
let overall = report.get("overall").and_then(Value::as_f64).unwrap_or(0.0);
let mut reasons = Vec::new();
- // The same first viewport the user accepted, still rendered at desktop width: its
- // score and contradictions are not re-litigated here; missing regions still block.
- let viewport_accepted = accepted_text.as_ref().is_some_and(|(comparison, _)| human_accepted_viewport(Some(&json!({"comparison": comparison}))));
- let mut advisories: Vec<String> = Vec::new();
- if viewport_accepted { report["humanTextReview"]["viewportAccepted"] = json!(true); }
+ // The approved first viewport at the desktop frame's own size. Its regions that
+ // still render as accepted (text, control, chrome) carry their acceptance here.
+ let accepted_view = native.and_then(|n| n.capture.approved_reference().map(|a| (n, a)))
+ .and_then(|(n, a)| approved_at_frame(io, &n.path("human-approved"), desktop, spec.as_ref(), &format!("{out_dir}/human-reviewed")).ok().map(|(r, _)| (r, a.proof.clone())));
+ let review = accepted_view.as_ref().map(|(comparison, _)| json!({"comparison": comparison}));
+ let viewport_accepted = human_accepted_viewport(review.as_ref());
+ let carried = human_accepted_regions(review.as_ref(), &regions);
+ let mut lapse = lapsed_viewport(review.as_ref(), "desktop capture");
+ if let Some((comparison, proof)) = &accepted_view {
+ report["humanTextReview"] = json!({"proof": proof, "comparison": comparison, "viewportAccepted": viewport_accepted,
+ "referenceScale": "the approved screenshot resampled once to the desktop frame; the capture is compared at its own size"});
+ }
if overall < min && viewport_accepted {
advisories.push(format!("(advisory, first viewport accepted) the desktop capture scores {}% against the comp, under {}%", pct0(overall), pct0(min)));
- } else if let Some(lapse) = (overall < min).then(|| accepted_text.as_ref().and_then(|(comparison, _)| lapsed_viewport(Some(&json!({"comparison": comparison})), "desktop capture"))).flatten() {
+ } else if overall < min && lapse.is_some() {
advisories.push(format!("(measured) the desktop capture scores {}% against the comp, under {}%", pct0(overall), pct0(min)));
- reasons.push(lapse);
+ reasons.push(lapse.take().unwrap());
} else if overall < min {
let bp = state.get("breakpoint").and_then(Value::as_str).map(String::from).unwrap_or_else(|| "the comp size".into());
reasons.push(format!(
- "the desktop capture ({}; the top {} rows scaled to the comp's width are compared, a full-page capture is fine) scores {}% against the comp, under {}%: the first viewport does not survive a common desktop width. The hero passed at {bp}; the layout must hold from ~1280 up, not only at the comp's exact width (grid columns in fr / minmax, not fixed px that overflow and wrap).",
+ "the desktop capture ({}; its first viewport, the top {} rows at the comp's width, is compared) scores {}% against the comp, under {}%: the first viewport does not survive a common desktop width. The hero passed at {bp}; the layout must hold from ~1280 up, not only at the comp's exact width (grid columns in fr / minmax, not fixed px that overflow and wrap).",
report.get("buildSize").and_then(Value::as_str).unwrap_or(""),
report.get("compSize").and_then(Value::as_str).unwrap_or(""),
pct0(overall), pct0(min)
));
}
- for r in &missing {
- let id = r.get("id").and_then(Value::as_str).unwrap_or("");
- push_region_blocker(&mut reasons, &mut region_reasons, id, format!("at desktop width, region {id} is missing"));
+ for (id, message) in missing_reasons {
+ push_region_blocker(&mut reasons, &mut region_reasons, &id, message);
}
+ let contradicted_direction: Vec<Value> = regions.iter().filter(|r| r.get("verdict").and_then(Value::as_str) == Some("contradicted") && matches!(r.get("kind").and_then(Value::as_str), Some("text" | "control"))).cloned().collect();
+ let mut accepted_ids: Vec<Value> = Vec::new();
for r in &contradicted_direction {
- let accepted = r["kind"]=="text" && accepted_text.as_ref().is_some_and(|(comparison,_)| comparison["regions"].as_array().is_some_and(|reviewed| reviewed.iter().any(|region|region["id"]==r["id"] && matches!(region["verdict"].as_str(),Some("match"|"drift")) && rscore(region,"structure")>=0.75)));
- if viewport_accepted && !accepted {
- advisories.push(format!("(advisory, first viewport accepted) at desktop width, region {} ({}) is contradicted (structure {}%)", r["id"].as_str().unwrap_or(""), r["kind"].as_str().unwrap_or(""), pct0(rscore(r, "structure"))));
+ let id = r["id"].as_str().unwrap_or("");
+ let message = format!("at desktop width, region {id} ({}) is contradicted (structure {}%)", r["kind"].as_str().unwrap_or(""), pct0(rscore(r, "structure")));
+ if carried.contains(id) {
+ accepted_ids.push(json!(id));
+ advisories.push(format!("(advisory, accepted in the first-viewport review) {message}"));
continue;
}
- if accepted {
- report["humanTextReview"]["acceptedTextRegions"].as_array_mut().map(|v|v.push(r["id"].clone())).unwrap_or_else(||{report["humanTextReview"]["acceptedTextRegions"]=json!([r["id"].clone()]);});
+ if viewport_accepted {
+ advisories.push(format!("(advisory, first viewport accepted) {message}"));
continue;
}
- push_region_blocker(&mut reasons, &mut region_reasons, r.get("id").and_then(Value::as_str).unwrap_or(""), format!(
- "at desktop width, region {} ({}) is contradicted (structure {}%)",
- r.get("id").and_then(Value::as_str).unwrap_or(""),
- r.get("kind").and_then(Value::as_str).unwrap_or(""),
- pct0(rscore(r, "structure"))
- ));
+ push_region_blocker(&mut reasons, &mut region_reasons, id, message);
+ }
+ if accepted_view.is_some() { report["humanTextReview"]["acceptedRegions"] = json!(accepted_ids); }
+ // An acceptance that no longer holds is always said, not only under the bar:
+ // it is why the readings below are not advisories.
+ if let Some(lapse) = lapse {
+ if reasons.is_empty() { advisories.insert(0, format!("(advisory) {lapse}")); } else { reasons.insert(0, lapse); }
}
let mut g = if reasons.is_empty() { Gate::ok(format!("desktop {}% ({})", pct0(overall), report.get("verdict").and_then(Value::as_str).unwrap_or(""))) } else { Gate::fail(reasons) };
g.summary = Some(format!("desktop {}% ({})", pct0(overall), report.get("verdict").and_then(Value::as_str).unwrap_or("")));
g.score = Some(overall);
+ g.verdict = report.get("verdict").and_then(Value::as_str).map(String::from);
g.side_by_side = report.pointer("/files/sideBySide").and_then(Value::as_str).map(String::from);
+ // The regions to open first, worst first, as the hero gate lists them.
+ let worst: Vec<Value> = repair_regions(&regions, &region_reasons).into_iter().take(3).collect();
+ g.worst = worst.iter().map(|r| format!("{} {} {}%", r["id"].as_str().unwrap_or(""), r["verdict"].as_str().unwrap_or(""), pct0(rscore(r, "overall")))).collect();
+ g.worst_ids = worst.iter().filter_map(|r| r["id"].as_str().map(String::from)).collect();
+ g.worst_crops = worst.iter().map(|r| {
+ let id = r["id"].as_str().unwrap_or("");
+ json!({ "id": id, "verdict": r["verdict"], "score": r.get("score").cloned().unwrap_or(Value::Null), "file": format!("{out_dir}/regions/{id}.png") })
+ }).collect();
+ g.region_verdicts = regions.iter().filter_map(|r| Some((r.get("id")?.as_str()?.to_string(), json!(r.get("verdict")?.as_str()?)))).collect();
g.region_reasons = region_reasons;
g.advisories = advisories;
publish_gate_evidence(io, out_dir, &mut report, &mut measured, &regions, &mut g, "responsive");
g
}
+/// "about 64px lower", "about 12px higher and 20px to the right".
+fn offset_words(dx: f64, dy: f64) -> String {
+ let mut parts = Vec::new();
+ if dy.abs() >= 1.5 { parts.push(format!("{}px {}", dy.abs().round() as i64, if dy > 0. { "lower" } else { "higher" })); }
+ if dx.abs() >= 1.5 { parts.push(format!("{}px {}", dx.abs().round() as i64, if dx > 0. { "to the right" } else { "to the left" })); }
+ if parts.is_empty() { "in place".into() } else { format!("about {}", parts.join(" and ")) }
+}
+
+fn displacement_json(d: &Displacement, k: f64) -> Value {
+ json!({"dx": (d.dx * k).round(), "dy": (d.dy * k).round(), "visible": util::num((d.visible * 1000.).round() / 1000.), "inferred": d.inferred, "unit": "capture px"})
+}
+
+fn displaced_message(id: &str, d: &Displacement, k: f64, frame: &str) -> String {
+ let fix = "Restore it into the first viewport: size what sits above it in proportion to the viewport (the comp's own ratios), not with fixed px or a px floor that grows it at this width";
+ if d.inferred {
+ return format!("at desktop width, region {id} is displaced, not missing: the content above it in its column sits {} than in the comp, which pushes {id} out of the {frame} first viewport. {fix}.", offset_words(d.dx * k, d.dy * k));
+ }
+ let shown = (d.visible * 100.).round() as i64;
+ format!("at desktop width, region {id} is displaced, not missing: it renders {} than in the comp, and {} of it stays inside the {frame} first viewport. {fix}.",
+ offset_words(d.dx * k, d.dy * k), if shown == 0 { "none".to_string() } else { format!("{shown}%") })
+}
+
+/// The approved first viewport resampled once to the desktop frame's own size,
+/// compared with the desktop capture there. The capture under test is never
+/// resampled, so a page that scales proportionally reads as the page the user
+/// accepted (a proportional render of a real accepted page scored 98% this way;
+/// see CLI-CONTRACT.md for the measurements behind the 95% bar).
+fn approved_at_frame(io: &Io, approved_path: &str, frame_path: &str, spec: Option<&Value>, out_dir: &str) -> Result<(Value, CompareResult), String> {
+ let approved = load_raster(io, approved_path)?;
+ let frame = load_raster(io, frame_path)?;
+ let scaled = if approved.width == frame.width { approved.clone() } else {
+ r::resize(&approved, frame.width as f64, round(approved.height as f64 * frame.width as f64 / approved.width as f64))
+ };
+ let res = compare(&scaled, &frame, spec, "top", "human-reviewed", None);
+ let files = write_artifacts(&res, &scaled, &abs(io, out_dir)).map_err(|e| format!("cannot persist comparison artifacts: {e}"))?;
+ let meta = json!({
+ "label": "human-reviewed", "comp": approved_path, "build": frame_path,
+ "spec": if spec.is_some() { Value::String(SPEC_PATH.into()) } else { Value::Null },
+ "compSize": format!("{}x{}", scaled.width, scaled.height),
+ "buildSize": format!("{}x{}", frame.width, frame.height),
+ "referenceSize": format!("{}x{}", approved.width, approved.height),
+ });
+ Ok((build_report(&res, Some(&files), &meta), res))
+}
+
fn hero_diff_labeled(io: &Io, comp_path: &str, build_path: &str, spec: Option<&Value>, out_dir: &str, label: &str) -> Result<(Value, CompareResult), String> {
let comp = load_raster(io, comp_path)?;
let build = load_raster(io, build_path)?;
@@ -2562,6 +2713,12 @@ fn advance(io: &Io, state: &mut Value, force: bool, reason: Option<&str>, opts:
}
}
}
+ if phase == "responsive" && gate.score.is_some() {
+ let s = self_cmd(io);
+ if let Some(stuck) = responsive_loop_verdict(state, &gate, first_viewport_accepted(io), &s) {
+ gate.reasons.insert(0, stuck);
+ }
+ }
if !gate.ok && !force {
if let Some(p) = state.pointer_mut(&format!("/phases/{phase}")).and_then(|p| p.as_object_mut()) {
p.insert("status".into(), json!("open"));
@@ -2634,7 +2791,17 @@ fn next_instruction(io: &Io, state: &Value) -> String {
),
"sections" => format!("Build the remaining sections inside the spec system (same corner language, rules, and palette; nothing the comp does not show). The hero passed with the comp's words verbatim; from here, content beyond the comp is yours to author at full fidelity, and any change to words the comp showed is a stated decision in your report, never silent. Then {s} build-phase advance."),
"motion" => format!("Add the signature interaction, reveals, and motion. Then {s} build-phase advance."),
- "responsive" => format!("Build the other viewports (mobile first if the surface is mobile). The first viewport must hold at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-px grid that wraps 96px narrower. Settle or disable entrance motion before capturing (an element mid-animation reads as missing). Capture desktop.png (1440 wide, full page) and mobile.png (390 wide, full page) into .impeccable/review/; the gate diffs the top of desktop.png (scaled to the comp's width) against the comp. Then {s} build-phase advance."),
+ "responsive" => {
+ // The desktop frame keeps the comp's aspect at 1440 wide.
+ let frame = bp.and_then(|b| b.split_once('x')).and_then(|(w, h)| Some((w.parse::<f64>().ok()?, h.parse::<f64>().ok()?)))
+ .filter(|(w, h)| *w > 0. && *h > 0.).map(|(w, h)| format!("1440x{}", (h * 1440. / w).ceil() as i64)).unwrap_or_else(|| "1440 wide at the comp's aspect".into());
+ let compared = if state["capturePolicy"] == "native-html-v1" || io.env("IMPECCABLE_NATIVE_CAPTURE") == Some("1") {
+ format!("The gate renders the page itself, a {frame} desktop first viewport and a 390-wide mobile frame, and diffs that desktop first viewport against the comp (scaled to the comp's width); captures you save are for your own inspection.")
+ } else {
+ format!("Capture desktop.png (1440 wide, full page) and mobile.png (390 wide, full page) into .impeccable/review/; the gate diffs the first viewport of desktop.png (its top {frame}, scaled to the comp's width) against the comp.")
+ };
+ format!("Build the other viewports (mobile first if the surface is mobile). The first viewport must hold at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-px grid that wraps 96px narrower, and sizes that scale with the viewport so nothing the comp shows in the first viewport is pushed below it. Settle or disable entrance motion before capturing (an element mid-animation reads as missing). {compared} Then {s} build-phase advance. When it fails, open the region crops it lists first; after three failed attempts it names the route to the user instead of more edits.")
+ }
"review" => format!("Spawn the finish reviewer with the state file, the hero diff report, and the captures; record its disposition with {s} build-phase finish --disposition <word>."),
_ => String::new(),
}
@@ -3207,6 +3374,9 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
io.out(&format!(" {file} {id}: {verdict} {}% (structure {}%, color {}%, detail {}%)\n", pct0(sc("overall")), pct0(sc("structure")), pct0(sc("color")), pct0(sc("detail"))));
}
io.out(" A region scored missing needs its material (a plate placed, or produced), not a value change; contradicted needs its structure re-derived from the spec box; drift is where padding and size edits belong. When a thin chrome strip (masthead, breadcrumb, table header) is the worst region, check its box height in the spec against the comp first: a strip one grid row tall in the spec but 53px in the comp compares your build against ground it never had.\n");
+ if res.worst_crops.iter().any(|c| c["verdict"] == "displaced") {
+ io.out(" A region scored displaced is present but pushed out of the first viewport: restore it there by sizing what sits above it in proportion to the viewport, not by moving it alone; a px floor or fixed row height that grows at this width is the usual cause.\n");
+ }
}
for r in &res.reasons {
io.out(&format!(" - {r}\n"));
diff --git a/crates/comp-verbs/src/build_phase/integrity_tests.rs b/crates/comp-verbs/src/build_phase/integrity_tests.rs
index fd406465c..a1b8d314f 100644
--- a/crates/comp-verbs/src/build_phase/integrity_tests.rs
+++ b/crates/comp-verbs/src/build_phase/integrity_tests.rs
@@ -1095,7 +1095,7 @@ fn accepted_first_viewport_turns_the_overall_bar_into_an_advisory() {
// A stale approval (another rendering) closes nothing.
let (stale, report) = run_reviewed_hero_min(&current, Some(&reviewed_hero(false, true)), REVIEWED_PAGE, 0.999);
assert!(!stale.ok && !bar(&stale), "{:?}", stale.reasons);
- assert!(stale.reasons[0].starts_with("the hero capture no longer matches the first viewport the user accepted") && stale.reasons[0].contains("changed: headline") && stale.reasons[0].ends_with("Restore what the user accepted; until then the readings apply.") && !stale.reasons[0].contains("review"), "{:?}", stale.reasons);
+ assert!(stale.reasons[0].starts_with("the hero capture no longer matches the first viewport the user accepted") && stale.reasons[0].contains("changed since the acceptance: headline") && stale.reasons[0].ends_with("Restore what the user accepted; until then the readings apply.") && !stale.reasons[0].contains("review"), "{:?}", stale.reasons);
assert!(stale.advisories.iter().any(|a| a.starts_with("(measured) hero overall")), "the raw score is kept as a measurement: {:?}", stale.advisories);
assert_eq!(report["humanHeroReview"]["viewportAccepted"], false);
// The material veto still blocks under an accepted, below-bar viewport.
@@ -1207,3 +1207,256 @@ fn accepted_review_of_a_text_only_first_viewport_lets_it_pass() {
assert!(!gate.ok);
assert_eq!(report["humanHeroReview"]["viewportAccepted"], false, "{report}");
}
+
+/// A menu column ending in a sign-off line near the bottom of the first viewport.
+/// `push` moves the column's rows down progressively and the sign-off by the full
+/// amount, as a px floor on the menu's type does at a narrower desktop width.
+fn menu_page(push: f64, height: usize, sign_off: bool) -> Image {
+ let mut img = r::create_image(400, height, [240, 240, 236, 255]);
+ for i in 0..8 {
+ let y = 40.0 + i as f64 * 34.0 + push * (i as f64 / 8.0);
+ r::fill_rect(&mut img, 220.0, y, 120.0 + (i % 3) as f64 * 20.0, 10.0, [20.0, 20.0, 20.0, 255.0]);
+ }
+ if sign_off {
+ for k in 0..6 {
+ r::fill_rect(&mut img, 230.0 + k as f64 * 22.0, 330.0 + push, 14.0, 18.0, [20.0, 20.0, 20.0, 255.0]);
+ }
+ }
+ img
+}
+
+fn menu_workspace() -> Workspace {
+ let ws = Workspace::new();
+ ws.write("comp.png", &png_io::encode_png(&menu_page(0.0, 360, true), &[]).unwrap());
+ ws.write(SPEC_PATH, util::json_pretty(&json!({"comp":"comp.png","regions":[
+ {"id":"menu","kind":"chrome","medium":"semantic","note":"ruled menu rows","box":{"x":0.54,"y":0.1,"w":0.42,"h":0.78},"px":{"x":216,"y":36,"w":168,"h":281}},
+ {"id":"sign-off","kind":"text","medium":"semantic","note":"sign-off line","type":{},"box":{"x":0.555,"y":0.9111,"w":0.35,"h":0.0611},"px":{"x":222,"y":328,"w":140,"h":22}}]})).as_bytes());
+ ws.write(".impeccable/review/mobile.png", &png_io::encode_png(&menu_page(0.0, 360, true), &[]).unwrap());
+ ws
+}
+
+#[test]
+fn responsive_calls_a_region_pushed_below_the_first_viewport_displaced_not_missing() {
+ let ws = menu_workspace();
+ let mut state = json!({"comp":"comp.png","phases":{}});
+ // A full-page desktop capture: the sign-off is there, 40px lower, past the frame.
+ ws.write(".impeccable/review/desktop.png", &png_io::encode_png(&menu_page(40.0, 480, true), &[]).unwrap());
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ assert!(!gate.ok);
+ let reason = gate.reasons.iter().find(|r| r.contains("sign-off")).unwrap();
+ assert!(reason.contains("is displaced, not missing") && reason.contains("about 40px lower") && reason.contains("400x360 first viewport"), "{reason}");
+ assert!(!gate.reasons.iter().any(|r| r.contains("is missing")), "{:?}", gate.reasons);
+ assert_eq!(gate.worst_crops[0]["verdict"], "displaced");
+ assert_eq!(gate.worst_crops[0]["file"], "diff/regions/sign-off.png");
+ let report: Value = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();
+ let region = report["regions"].as_array().unwrap().iter().find(|r| r["id"] == "sign-off").unwrap().clone();
+ assert_eq!(region["verdict"], "displaced");
+ assert!(matches!(region["rawVerdict"].as_str(), Some("missing" | "contradicted")), "{region}");
+ assert_eq!(region["displacement"]["dy"], 40.0);
+ assert_eq!(region["blocking"], true);
+ // A native frame is the first viewport alone: the column above says where it went.
+ ws.write(".impeccable/review/desktop.png", &png_io::encode_png(&menu_page(40.0, 360, true), &[]).unwrap());
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ let reason = gate.reasons.iter().find(|r| r.contains("sign-off")).unwrap();
+ assert!(reason.contains("is displaced, not missing: the content above it in its column sits about"), "{reason}");
+ // Gone is still missing.
+ ws.write(".impeccable/review/desktop.png", &png_io::encode_png(&menu_page(0.0, 360, false), &[]).unwrap());
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ assert!(gate.reasons.iter().any(|r| r == "at desktop width, region sign-off is missing"), "{:?}", gate.reasons);
+ assert_eq!(gate.worst_crops[0]["verdict"], "missing");
+}
+
+#[test]
+fn a_missing_control_does_not_borrow_its_identical_neighbour() {
+ // Two identical icon controls 24px apart; the lower one is gone at desktop width.
+ let ws = Workspace::new();
+ let icon = |img: &mut Image, y: f64| for k in 0..3 { r::fill_rect(img, 40. + k as f64 * 10., y, 6., 14., [20., 20., 20., 255.]); };
+ let mut comp = r::create_image(200, 200, [240, 240, 236, 255]);
+ icon(&mut comp, 100.);
+ icon(&mut comp, 124.);
+ let mut desktop = r::create_image(200, 200, [240, 240, 236, 255]);
+ icon(&mut desktop, 100.);
+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();
+ ws.write("comp.png", &png(&comp));
+ ws.write(".impeccable/review/desktop.png", &png(&desktop));
+ ws.write(".impeccable/review/mobile.png", &png(&desktop));
+ ws.write(SPEC_PATH, util::json_pretty(&json!({"comp":"comp.png","regions":[
+ {"id":"first","kind":"control","medium":"semantic","note":"first icon control","box":{"x":0.19,"y":0.49,"w":0.16,"h":0.09},"px":{"x":38,"y":98,"w":32,"h":18}},
+ {"id":"second","kind":"control","medium":"semantic","note":"second icon control","box":{"x":0.19,"y":0.61,"w":0.16,"h":0.09},"px":{"x":38,"y":122,"w":32,"h":18}}]})).as_bytes());
+ let mut state = json!({"comp":"comp.png","phases":{}});
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ assert!(gate.reasons.iter().any(|r| r == "at desktop width, region second is missing"), "{:?} {:?}", gate.reasons, gate.advisories);
+ // Two distinct controls that both moved down a row: the first lands in the
+ // second's old box, which the second no longer occupies, so it is found.
+ let bars = |img: &mut Image, y: f64| r::fill_rect(img, 40., y + 12., 26., 2., [20., 20., 20., 255.]);
+ let mut comp = r::create_image(200, 200, [240, 240, 236, 255]);
+ icon(&mut comp, 100.);
+ bars(&mut comp, 124.);
+ let mut desktop = r::create_image(200, 200, [240, 240, 236, 255]);
+ icon(&mut desktop, 124.);
+ bars(&mut desktop, 148.);
+ ws.write("comp.png", &png(&comp));
+ ws.write(".impeccable/review/desktop.png", &png(&desktop));
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ let report: Value = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();
+ assert!(!gate.reasons.iter().any(|r| r.contains("region first is missing")), "{:?} {}", gate.reasons, report["regions"]);
+ assert!(gate.advisories.iter().any(|a| a.contains("region first sits about 24px lower")), "{:?}", gate.advisories);
+}
+
+#[test]
+fn responsive_reads_a_region_shifted_inside_the_first_viewport_as_drift() {
+ let ws = menu_workspace();
+ let mut state = json!({"comp":"comp.png","phases":{}});
+ let mut moved = menu_page(0.0, 360, false);
+ for k in 0..6 {
+ r::fill_rect(&mut moved, 230.0 + k as f64 * 22.0, 306.0, 14.0, 18.0, [20.0, 20.0, 20.0, 255.0]);
+ }
+ ws.write(".impeccable/review/desktop.png", &png_io::encode_png(&moved, &[]).unwrap());
+ let gate = gate_responsive(&ws.io(), &mut state, 0.1, "diff", None);
+ assert!(gate.ok, "{:?}", gate.reasons);
+ assert!(gate.advisories.iter().any(|a| a.starts_with("(advisory, still inside the first viewport) at desktop width, region sign-off sits about 24px higher")), "{:?}", gate.advisories);
+}
+
+#[test]
+fn a_present_plate_off_its_box_at_desktop_width_is_drift_not_missing() {
+ let ws = Workspace::new();
+ let comp = reviewed_hero(false, true);
+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();
+ ws.write("comp.png", &png(&comp));
+ ws.write("art.png", &png(&r::crop(&comp, 10., 10., 60., 60.)));
+ let art = json!({"id":"art","kind":"plate","medium":"raster","plate":"art.png","note":"dark printed square",
+ "box":{"x":0.05,"y":0.0833,"w":0.3,"h":0.5},"px":{"x":10,"y":10,"w":60,"h":60}});
+ let spec = json!({"comp":"comp.png","regions":[art.clone()]});
+ ws.write(SPEC_PATH, util::json_pretty(&spec).as_bytes());
+ let io = ws.io();
+ let receipt = json!({"status":"ok","score":0.9,"file":"art.png","assetHash":sha256_file(&io,"art.png"),"compHash":sha256_file(&io,"comp.png"),"regionHash":sha256_bytes(util::json_pretty(&art).as_bytes()),"referenceHash":plate_reference_hash(&spec)});
+ let mut state = json!({"comp":"comp.png","plates":{"art":receipt},"phases":{}});
+ // The plate renders 16px lower and to the right of its box: present, shifted.
+ let mut desktop = reviewed_hero(false, false);
+ r::blit(&mut desktop, &r::crop(&comp, 10., 10., 60., 60.), 26., 26.);
+ ws.write(".impeccable/review/desktop.png", &png(&desktop));
+ ws.write(".impeccable/review/mobile.png", &png(&desktop));
+ let gate = gate_responsive(&io, &mut state, 0.1, "diff", None);
+ assert!(!gate.reasons.iter().any(|r| r.contains("art is missing")), "{:?}", gate.reasons);
+ let report: Value = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();
+ assert_eq!(report["regions"][0]["verdict"], "drift", "{report}");
+ assert!(gate.advisories.iter().any(|a| a.contains("art")), "{:?}", gate.advisories);
+}
+
+/// The responsive workspace of the accepted-review tests: one striped control
+/// region and a quiet chrome strip the approved screenshot can differ in.
+fn reviewed_desktop_workspace() -> Workspace {
+ let ws = Workspace::new();
+ let comp = reviewed_hero(false, false);
+ ws.write("comp.png", &png_io::encode_png(&comp, &[]).unwrap());
+ ws.write("index.html", b"<main><h1>Headline</h1></main>");
+ ws.write(SPEC_PATH, util::json_pretty(&json!({"comp":"comp.png","regions":[
+ {"id":"headline","kind":"control","medium":"semantic","note":"striped headline lettering","box":{"x":0.6,"y":0.7,"w":0.3,"h":0.2},"px":{"x":120,"y":84,"w":60,"h":24}},
+ {"id":"strip","kind":"chrome","medium":"semantic","note":"quiet top strip","box":{"x":0.05,"y":0.05,"w":0.4,"h":0.4},"px":{"x":10,"y":6,"w":80,"h":48}}]})).as_bytes());
+ ws
+}
+
+fn run_reviewed_desktop(ws: &Workspace, current: &Image, approved: Option<&Image>, min: f64) -> (Gate, Value) {
+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();
+ let mut state = json!({"comp":"comp.png","capturePolicy":"native-html-v1","phases":{}});
+ let gate = gate_responsive(&ws.io(), &mut state, min, "diff", Some(&DesktopRenderer { desktop: png(current), approved: approved.map(png) }));
+ let report = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();
+ (gate, report)
+}
+
+#[test]
+fn a_lapsed_acceptance_is_named_even_above_the_bar() {
+ let ws = reviewed_desktop_workspace();
+ // Above the bar, but the control is contradicted and the user accepted another rendering.
+ let (gate, _) = run_reviewed_desktop(&ws, &reviewed_hero(true, false), Some(&reviewed_hero(false, false)), 0.1);
+ assert!(!gate.ok);
+ assert!(gate.reasons[0].starts_with("the desktop capture no longer matches the first viewport the user accepted") && gate.reasons[0].contains("changed since the acceptance: headline"), "{:?}", gate.reasons);
+ assert!(gate.reasons.iter().any(|r| r.contains("headline (control) is contradicted")), "{:?}", gate.reasons);
+ // Nothing else blocking: the lapse is still said, as an advisory.
+ let mut quiet = reviewed_hero(false, false);
+ r::fill_rect(&mut quiet, 14., 10., 70., 40., [30., 30., 30., 255.]);
+ let (gate, _) = run_reviewed_desktop(&ws, &reviewed_hero(false, false), Some(&quiet), 0.1);
+ assert!(gate.ok, "{:?}", gate.reasons);
+ assert!(gate.advisories[0].starts_with("(advisory) the desktop capture no longer matches the first viewport the user accepted") && gate.advisories[0].contains("strip"), "{:?}", gate.advisories);
+}
+
+#[test]
+fn an_accepted_control_carries_to_desktop_width_like_text() {
+ let ws = reviewed_desktop_workspace();
+ // The user accepted this control's restyle; the strip differs, so the viewport as a whole is not accepted.
+ let current = reviewed_hero(true, false);
+ let mut approved = current.clone();
+ r::fill_rect(&mut approved, 14., 10., 70., 40., [30., 30., 30., 255.]);
+ let (gate, report) = run_reviewed_desktop(&ws, &current, Some(&approved), 0.1);
+ assert!(!gate.reasons.iter().any(|r| r.contains("headline (control) is contradicted")), "{:?}", gate.reasons);
+ assert!(gate.advisories.iter().any(|a| a.starts_with("(advisory, accepted in the first-viewport review) at desktop width, region headline (control) is contradicted")), "{:?}", gate.advisories);
+ assert_eq!(report["humanTextReview"]["acceptedRegions"], json!(["headline"]));
+ assert_eq!(report["humanTextReview"]["viewportAccepted"], false);
+}
+
+#[test]
+fn the_approved_screenshot_is_compared_at_the_desktop_frame_size() {
+ // The user approved the first viewport at the comp's size; the desktop frame is
+ // smaller and renders the same page proportionally. Neither side is upscaled.
+ let ws = reviewed_desktop_workspace();
+ let approved = reviewed_hero(true, false);
+ let frame = r::resize(&approved, 150., 90.);
+ let (gate, report) = run_reviewed_desktop(&ws, &frame, Some(&approved), 0.999);
+ assert_eq!(report["humanTextReview"]["comparison"]["compSize"], "150x90", "{report}");
+ assert_eq!(report["humanTextReview"]["comparison"]["referenceSize"], "200x120");
+ assert_eq!(report["humanTextReview"]["viewportAccepted"], true, "{report}");
+ assert!(gate.ok, "{:?}", gate.reasons);
+}
+
+#[test]
+fn responsive_failures_print_crops_and_escalate_after_three_attempts() {
+ let ws = menu_workspace();
+ ws.write(".impeccable/review/desktop.png", &png_io::encode_png(&menu_page(40.0, 480, true), &[]).unwrap());
+ ws.write(".impeccable/build/state.json", util::json_pretty(&json!({"comp":"comp.png","phase":"responsive","phases":{"responsive":{"status":"open","attempts":0,"notes":[]}}})).as_bytes());
+ let advance = || {
+ let (mut io, out) = Io::captured("", ws.path.clone(), Default::default());
+ let code = run(&["advance".to_string(), "--min".into(), "0.1".into()], &mut io, &no_organic_scan);
+ let text = String::from_utf8(out.stdout.borrow().clone()).unwrap();
+ (code, text)
+ };
+ let (code, first) = advance();
+ assert_eq!(code, 2);
+ assert!(first.contains("LOOK FIRST") && first.contains(".impeccable/review/diff/desktop/regions/sign-off.png sign-off: displaced"), "{first}");
+ assert!(first.contains("A region scored displaced is present but pushed out of the first viewport"), "{first}");
+ assert!(!first.contains("failed 3 attempts"), "{first}");
+ advance();
+ let (_, third) = advance();
+ assert!(third.contains("- The responsive gate has failed 3 attempts in a row. Stop iterating and present the first-viewport review"), "{third}");
+ let state: Value = serde_json::from_slice(&std::fs::read(ws.path.join(".impeccable/build/state.json")).unwrap()).unwrap();
+ assert_eq!(state["phases"]["responsive"]["history"].as_array().unwrap().len(), 3);
+ assert_eq!(state["phases"]["responsive"]["status"], "open");
+}
+
+#[test]
+fn responsive_escalation_after_acceptance_routes_to_the_user_not_a_new_review() {
+ let mut state = json!({"phases":{"responsive":{}}});
+ let mut gate = Gate::fail(vec!["at desktop width, region sign-off is displaced, not missing".into()]);
+ gate.score = Some(0.8);
+ for _ in 0..2 { assert!(responsive_loop_verdict(&mut state, &gate, true, "impeccable").is_none()); }
+ let third = responsive_loop_verdict(&mut state, &gate, true, "impeccable").unwrap();
+ assert!(third.contains("already accepted a first viewport") && third.contains("impeccable build-phase advance --force --reason") && third.contains("not a fix round"), "{third}");
+ assert!(!third.contains("present the first-viewport review"), "{third}");
+ // The example it gives is a reason force accepts.
+ let example = third.split("for example: ").nth(1).unwrap().split(')').next().unwrap();
+ assert!(force_allowed(Some(example)), "{example}");
+ // A pass in between resets the run of failures.
+ let mut passed = Gate::fail(vec![]);
+ passed.ok = true;
+ passed.score = Some(0.9);
+ assert!(responsive_loop_verdict(&mut state, &passed, true, "impeccable").is_none());
+ assert!(responsive_loop_verdict(&mut state, &gate, true, "impeccable").is_none());
+}
+
+#[test]
+fn responsive_next_names_the_frame_the_gate_actually_diffs() {
+ let (io, _) = Io::captured("", std::env::temp_dir(), Default::default());
+ let native = next_instruction(&io, &json!({"phase":"responsive","breakpoint":"1536x1024","capturePolicy":"native-html-v1"}));
+ assert!(native.contains("a 1440x960 desktop first viewport") && !native.contains("desktop.png"), "{native}");
+ let saved = next_instruction(&io, &json!({"phase":"responsive","breakpoint":"1536x1024"}));
+ assert!(saved.contains("the first viewport of desktop.png (its top 1440x960"), "{saved}");
+}
diff --git a/crates/comp-verbs/src/displacement.rs b/crates/comp-verbs/src/displacement.rs
new file mode 100644
index 000000000..9792b00fc
--- /dev/null
+++ b/crates/comp-verbs/src/displacement.rs
@@ -0,0 +1,269 @@
+//! Where did a region go? A bounded search for a comp region's pixels near its
+//! box in a build capture, used by the responsive gate to tell a region that is
+//! displaced (present, but shifted, often past the first viewport) from one that
+//! is missing. Pure; no browser.
+//!
+//! The search runs on blurred luma at a working scale (each axis at most 96
+//! samples across the region), scores every offset in the window by normalized
+//! cross-correlation over the part of the region that lands inside the capture,
+//! and confirms the best offset with the full comp-diff score on that part. A
+//! region found nowhere in the window stays missing.
+
+use impeccable_comp::metrics as m;
+use impeccable_comp::raster::{self as r, Image};
+
+use crate::comp_diff::{score_pair, verdict_for, Score};
+
+/// Largest vertical displacement searched, as a share of the comp's height.
+/// Wider than any sub-pixel or rounding drift (the comparison already absorbs a
+/// global shift of 4% of the width) and narrow enough that a match is still the
+/// same element in the same place of the layout, not a lookalike further down.
+pub const MAX_DY: f64 = 0.12;
+/// Largest horizontal displacement searched, as a share of the comp's width.
+pub const MAX_DX: f64 = 0.04;
+const WORK: f64 = 96.0;
+const MIN_NCC: f64 = 0.6;
+
+#[derive(Clone)]
+pub struct Displacement {
+ /// Offset of the region's content from its comp box, in comp pixels.
+ pub dx: f64,
+ pub dy: f64,
+ /// Share of the region's box that lies inside the frame at the displaced position.
+ pub visible: f64,
+ /// True when the region's own pixels were too far out of the frame to match,
+ /// and the offset was read from the content directly above it in its column.
+ pub inferred: bool,
+ pub score: Score,
+}
+
+impl Displacement {
+ pub fn beyond_frame(&self) -> bool {
+ self.visible < 0.999
+ }
+}
+
+/// A comp-pixel rectangle, clamped to an image on use.
+#[derive(Clone, Copy)]
+pub struct Rect {
+ pub x: f64,
+ pub y: f64,
+ pub w: f64,
+ pub h: f64,
+}
+
+fn gray(img: &Image) -> m::Gray {
+ m::blur_gray(&m::to_gray(img), 1)
+}
+
+/// Normalized cross-correlation of the template against the window with the
+/// template's top-left at (ox, oy) in window samples, over the overlap only.
+/// Returns (ncc, overlap rows, overlap cols).
+fn ncc(t: &m::Gray, w: &m::Gray, ox: i64, oy: i64) -> Option<(f64, usize, usize)> {
+ let x0 = 0i64.max(-ox);
+ let y0 = 0i64.max(-oy);
+ let x1 = (t.width as i64).min(w.width as i64 - ox);
+ let y1 = (t.height as i64).min(w.height as i64 - oy);
+ if x1 <= x0 || y1 <= y0 {
+ return None;
+ }
+ let n = ((x1 - x0) * (y1 - y0)) as f64;
+ let (mut st, mut sw, mut stt, mut sww, mut stw) = (0f64, 0f64, 0f64, 0f64, 0f64);
+ for y in y0..y1 {
+ let tr = (y as usize) * t.width;
+ let wr = ((y + oy) as usize) * w.width;
+ for x in x0..x1 {
+ let a = t.data[tr + x as usize] as f64;
+ let b = w.data[wr + (x + ox) as usize] as f64;
+ st += a;
+ sw += b;
+ stt += a * a;
+ sww += b * b;
+ stw += a * b;
+ }
+ }
+ let vt = stt - st * st / n;
+ let vw = sww - sw * sw / n;
+ // A flat patch on either side has no shape to match.
+ if vt <= n * 4.0 || vw <= n * 4.0 {
+ return None;
+ }
+ Some(((stw - st * sw / n) / (vt * vw).sqrt(), (y1 - y0) as usize, (x1 - x0) as usize))
+}
+
+struct Best {
+ dx: f64,
+ dy: f64,
+ ncc: f64,
+}
+
+/// Search `region` (comp pixels) of `comp` in `build` (already scaled to the
+/// comp's width) over offsets within the bounds. `min_rows` is the share of the
+/// template's rows that must overlap the build for an offset to count.
+fn search(comp: &Image, build: &Image, region: Rect, dy_range: (f64, f64), dx_max: f64, min_rows: f64) -> Option<Best> {
+ let fx = (WORK / region.w).min(1.0);
+ let fy = (WORK / region.h).min(1.0);
+ let template = r::crop(comp, region.x, region.y, region.w, region.h);
+ let t = gray(&r::resize(&template, (template.width as f64 * fx).max(2.0), (template.height as f64 * fy).max(2.0)));
+ // The window: the region's box widened by the search bounds, clamped to the build.
+ let wx = (region.x - dx_max).max(0.0).floor();
+ let wy = (region.y + dy_range.0).max(0.0).floor();
+ let wr = (region.x + region.w + dx_max).min(build.width as f64);
+ let wb = (region.y + region.h + dy_range.1).min(build.height as f64);
+ if wr - wx < 2.0 || wb - wy < 2.0 {
+ return None;
+ }
+ let window = r::crop(build, wx, wy, wr - wx, wb - wy);
+ let w = gray(&r::resize(&window, (window.width as f64 * fx).max(2.0), (window.height as f64 * fy).max(2.0)));
+ let (sx, sy) = (t.width as f64 / template.width as f64, t.height as f64 / template.height as f64);
+ let steps = |lo: f64, hi: f64, s: f64| ((lo * s).floor() as i64, (hi * s).ceil() as i64);
+ let (ylo, yhi) = steps(dy_range.0, dy_range.1, sy);
+ let (xlo, xhi) = steps(-dx_max, dx_max, sx);
+ let need_rows = ((t.height as f64 * min_rows).ceil() as usize).max(1);
+ let mut best: Option<Best> = None;
+ for dy in ylo..=yhi {
+ for dx in xlo..=xhi {
+ // Template origin in window samples.
+ let ox = ((region.x - wx) * sx).round() as i64 + dx;
+ let oy = ((region.y - wy) * sy).round() as i64 + dy;
+ let Some((score, rows, cols)) = ncc(&t, &w, ox, oy) else { continue };
+ if rows < need_rows || cols * 2 < t.width {
+ continue;
+ }
+ if best.as_ref().is_none_or(|b| score > b.ncc + 1e-9) {
+ best = Some(Best { dx: dx as f64 / sx, dy: dy as f64 / sy, ncc: score });
+ }
+ }
+ }
+ best.filter(|b| b.ncc >= MIN_NCC)
+}
+
+/// The full comp-diff score of the part of `region` that, moved by (dx, dy),
+/// lands inside the build.
+fn confirm(comp: &Image, build: &Image, region: Rect, dx: f64, dy: f64, kind: Option<&str>) -> Option<Score> {
+ let top = (-(region.y + dy)).max(0.0);
+ let left = (-(region.x + dx)).max(0.0);
+ let bottom = (region.y + dy + region.h - build.height as f64).max(0.0);
+ let right = (region.x + dx + region.w - build.width as f64).max(0.0);
+ let w = region.w - left - right;
+ let h = region.h - top - bottom;
+ if w < 2.0 || h < 2.0 {
+ return None;
+ }
+ let a = r::crop(comp, region.x + left, region.y + top, w, h);
+ let b = r::crop(build, region.x + dx + left, region.y + dy + top, w, h);
+ if a.width != b.width || a.height != b.height {
+ return None;
+ }
+ let score = score_pair(&a, &b, kind);
+ matches!(verdict_for(&score, kind), "match" | "drift").then_some(score)
+}
+
+fn visible(region: Rect, dx: f64, dy: f64, frame_w: f64, frame_h: f64) -> f64 {
+ let ix = ((region.x + dx + region.w).min(frame_w) - (region.x + dx).max(0.0)).max(0.0);
+ let iy = ((region.y + dy + region.h).min(frame_h) - (region.y + dy).max(0.0)).max(0.0);
+ (ix * iy) / (region.w * region.h).max(1.0)
+}
+
+/// Find where `region` of `comp` sits in `build`, a capture scaled to the comp's
+/// width whose first `frame_h` rows are the compared first viewport (a full-page
+/// capture may run below it). Returns None when the region is in place or is not
+/// found within the bounds.
+pub fn find(comp: &Image, build: &Image, frame_h: f64, region: Rect, kind: Option<&str>) -> Option<Displacement> {
+ if region.w < 2.0 || region.h < 2.0 {
+ return None;
+ }
+ let max_dy = (comp.height as f64 * MAX_DY).round();
+ let max_dx = (comp.width as f64 * MAX_DX).round();
+ // A move under a pixel and a half at either scale is rounding, not displacement.
+ let moved = |dx: f64, dy: f64| dx.abs() >= 2.0 || dy.abs() >= 2.0;
+ let frame_w = comp.width as f64;
+ // Direct: the region's own pixels, at least a third of its rows inside the build.
+ if let Some(best) = search(comp, build, region, (-max_dy, max_dy), max_dx, 1.0 / 3.0) {
+ if moved(best.dx, best.dy) {
+ if let Some(score) = confirm(comp, build, region, best.dx, best.dy, kind) {
+ return Some(Displacement { dx: best.dx.round(), dy: best.dy.round(), visible: visible(region, best.dx, best.dy, frame_w, frame_h), inferred: false, score });
+ }
+ }
+ }
+ // Inferred: a region near the bottom of the frame whose pixels left it. Read
+ // the offset of the content directly above it in its column, searching down
+ // only, and accept it when that offset puts most of the region past the frame.
+ let context_h = region.y.min((region.h * 3.0).max(comp.height as f64 * 0.08)).floor();
+ if context_h < 4.0 || region.y + region.h + max_dy < frame_h {
+ return None;
+ }
+ let above = Rect { x: region.x, y: region.y - context_h, w: region.w, h: context_h };
+ let best = search(comp, build, above, (0.0, max_dy), max_dx, 0.5)?;
+ if best.dy < 2.0 || best.ncc < 0.7 {
+ return None;
+ }
+ let score = confirm(comp, build, above, best.dx, best.dy, None)?;
+ let shown = visible(region, best.dx, best.dy, frame_w, frame_h);
+ (shown < 0.5).then_some(Displacement { dx: best.dx.round(), dy: best.dy.round(), visible: shown, inferred: true, score })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn page(offset: f64, frame_h: usize) -> Image {
+ let mut img = r::create_image(400, frame_h, [240, 240, 236, 255]);
+ // A column of rows ending in a short line of "text" at y = 330 + offset.
+ for i in 0..8 {
+ let y = 40.0 + i as f64 * 34.0 + offset * (i as f64 / 8.0);
+ r::fill_rect(&mut img, 220.0, y, 120.0 + (i % 3) as f64 * 20.0, 10.0, [20.0, 20.0, 20.0, 255.0]);
+ }
+ let y = 330.0 + offset;
+ for k in 0..6 {
+ r::fill_rect(&mut img, 230.0 + k as f64 * 22.0, y, 14.0, 18.0, [20.0, 20.0, 20.0, 255.0]);
+ }
+ img
+ }
+
+ #[test]
+ fn a_region_moved_inside_the_frame_is_found_with_its_offset() {
+ let comp = page(0.0, 360);
+ let mut build = r::create_image(400, 360, [240, 240, 236, 255]);
+ r::blit(&mut build, &comp, 0.0, 0.0);
+ // Move only the sign-off line up by 24px.
+ r::fill_rect(&mut build, 220.0, 326.0, 180.0, 30.0, [240.0, 240.0, 236.0, 255.0]);
+ let line = r::crop(&comp, 220.0, 326.0, 180.0, 26.0);
+ r::blit(&mut build, &line, 220.0, 302.0);
+ let found = find(&comp, &build, 360.0, Rect { x: 222.0, y: 328.0, w: 140.0, h: 22.0 }, Some("text")).unwrap();
+ assert_eq!((found.dx, found.dy), (0.0, -24.0));
+ assert!(!found.beyond_frame());
+ assert!(!found.inferred);
+ }
+
+ #[test]
+ fn a_region_pushed_below_the_frame_is_read_from_its_column() {
+ let comp = page(0.0, 360);
+ // The column grows longer: every row moves down progressively, the last by 40px.
+ let build = page(40.0, 360);
+ let found = find(&comp, &build, 360.0, Rect { x: 222.0, y: 328.0, w: 140.0, h: 22.0 }, Some("text")).unwrap();
+ assert!(found.inferred, "the line is out of the frame; its column says where it went");
+ assert!(found.dy >= 25.0 && found.dy <= 45.0, "{}", found.dy);
+ assert!(found.beyond_frame());
+ }
+
+ #[test]
+ fn a_full_page_capture_finds_the_region_itself_below_the_frame() {
+ let comp = page(0.0, 360);
+ let build = page(40.0, 480);
+ let found = find(&comp, &build, 360.0, Rect { x: 222.0, y: 328.0, w: 140.0, h: 22.0 }, Some("text")).unwrap();
+ assert!(!found.inferred);
+ assert_eq!(found.dy, 40.0);
+ assert!(found.beyond_frame());
+ }
+
+ #[test]
+ fn a_region_that_is_gone_is_not_displaced() {
+ let comp = page(0.0, 360);
+ let mut build = comp.clone();
+ r::fill_rect(&mut build, 220.0, 326.0, 180.0, 34.0, [240.0, 240.0, 236.0, 255.0]);
+ assert!(find(&comp, &build, 360.0, Rect { x: 222.0, y: 328.0, w: 140.0, h: 22.0 }, Some("text")).is_none());
+ // In place: nothing to report either.
+ assert!(find(&comp, &comp, 360.0, Rect { x: 222.0, y: 328.0, w: 140.0, h: 22.0 }, Some("text")).is_none());
+ }
+}
diff --git a/crates/comp-verbs/src/lib.rs b/crates/comp-verbs/src/lib.rs
index 84fe7096c..065cb9389 100644
--- a/crates/comp-verbs/src/lib.rs
+++ b/crates/comp-verbs/src/lib.rs
@@ -18,6 +18,7 @@ pub mod build_phase;
pub mod completion;
pub mod comp_diff;
pub mod comp_spec;
+pub mod displacement;
mod map_inspection;
pub mod font_match;
mod util;
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 949cfb97b..befe49683 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -1963,10 +1963,12 @@ Assembly acceptance closes component and assembly reviews for this journey. The
### Human-reviewed text at the final comp gate
-The hero gate uses the same evidence. When the native hero capture carries an approved first-viewport review, `build-phase` compares the approved screenshot with the current hero frame; a `text`, `control` or `chrome` region that still matches it (verdict match or drift, structure at least 75%) has its contradicted verdict, control drift and ink-box readings, and its type readings turned into advisories marked `accepted in the first-viewport review`. When the approved screenshot and the current hero frame agree as a whole (overall at least 95%, no region missing or contradicted), the user has accepted this first viewport: every non-material reason (the overall bar, the palette check, every numeric reading) becomes an advisory marked `first viewport accepted`, led by an advisory that says the user accepted it. Only material vetoes still block: missing or unreferenced plates, inline SVG illustrations, organic clips, clipped plates, invented ink, a wrong capture size, and the native rendered-presence checks. The hero report records `humanHeroReview` with the proof, that comparison, `acceptedRegions` and `viewportAccepted`. The responsive gate (and so the finish recheck) applies the same rule to its desktop comparison: with the accepted viewport still rendered at desktop width, the desktop score and contradicted regions are advisories and missing regions block. When the current capture no longer matches the approved screenshot, the acceptance lapses: the gate replaces the raw overall-bar reason with one that says the hero (or desktop) capture no longer matches the first viewport the user accepted, names the changed regions, and asks to restore what the user accepted, saying the readings apply until then. It does not offer a new first-viewport review: once one is accepted the review store returns that session, so a new round cannot open. The raw score is kept as a `(measured)` advisory. After three consecutive failed hero attempts the refusal leads with an instruction to present the first-viewport review instead of iterating further; when a first viewport is already accepted (locally, or in a session the host names) it instead says the review is closed and asks to restore what the user accepted.
+The hero gate uses the same evidence. When the native hero capture carries an approved first-viewport review, `build-phase` compares the approved screenshot with the current hero frame; a `text`, `control` or `chrome` region that still matches it (verdict match or drift, structure at least 75%) has its contradicted verdict, control drift and ink-box readings, and its type readings turned into advisories marked `accepted in the first-viewport review`. When the approved screenshot and the current hero frame agree as a whole (overall at least 95%, no region missing or contradicted), the user has accepted this first viewport: every non-material reason (the overall bar, the palette check, every numeric reading) becomes an advisory marked `first viewport accepted`, led by an advisory that says the user accepted it. Only material vetoes still block: missing or unreferenced plates, inline SVG illustrations, organic clips, clipped plates, invented ink, a wrong capture size, and the native rendered-presence checks. The hero report records `humanHeroReview` with the proof, that comparison, `acceptedRegions` and `viewportAccepted`. The responsive gate (and so the finish recheck) applies the same rule to its desktop comparison: with the accepted viewport still rendered at desktop width, the desktop score and contradicted regions are advisories and missing or displaced regions block. There the approved screenshot (captured at the comp's size) is resampled once, by the engine's area resize, to the desktop frame's own size and compared with the desktop capture at that size, so the capture under test is never resampled; the comparison is recorded as `humanTextReview.comparison` with `compSize` (the frame size) and `referenceSize` (the screenshot's own). The 95% bar holds at that scale, measured on a real accepted page (a proportional layout with one 16px type floor, its clock pinned): rendered at 1440 it scores 98.5% against its approved 1536 screenshot, at 1600 97.1%; at 1280, where the floor reflows the menu, 89.9%; the capture that stalled a run after a menu change and a clock change, 83.3%. Comparing the other way (the capture upscaled to the comp's width) scored the same faithful 1440 render 97.0% and a pure resample of the approved screenshot 96.4%, about one point of margin, which is why the frame-size comparison is used. A contradicted `text` or `control` region that still renders as accepted in that comparison (match or drift, structure at least 75%; the carry set covers `text`, `control` and `chrome` regions as at the hero, but a contradicted `chrome` region never blocks at desktop width, so only text and control acceptances show here) is an advisory marked `accepted in the first-viewport review`, and its id is listed in `humanTextReview.acceptedRegions`. When the current capture no longer matches the approved screenshot, the acceptance lapses: the gate says the hero (or desktop) capture no longer matches the first viewport the user accepted, names the regions that changed since the acceptance (those that no longer render as accepted, at most six and a count of the rest; when none does, the three furthest from it), and asks to restore what the user accepted, saying the readings apply until then. Under the overall bar this reason replaces the raw overall-bar reason; above it (and at the hero, whatever the other reasons are), it leads the other blocking reasons, or, when nothing else blocks, opens the advisories as `(advisory) the ... capture no longer matches ...`, so a lapsed acceptance is always said. It does not offer a new first-viewport review: once one is accepted the review store returns that session, so a new round cannot open. The raw score is kept as a `(measured)` advisory. After three consecutive failed hero attempts the refusal leads with an instruction to present the first-viewport review instead of iterating further; when a first viewport is already accepted (locally, or in a session the host names) it instead says the review is closed and asks to restore what the user accepted.
Native entry capture covers first viewports with no raster region. When the bound spec names no `raster` region (a code-led Operate screen, for example), the renderer has no artwork to intervene on, so it captures each frame (`hero`, or `desktop` and `mobile`) the way the assembled-page review captures the page it shows the user: pinned local scripts, verified network dependencies, the primary-font check, and two identical viewport screenshots. The page's inputs come from the same frozen snapshot that bound the spec and comp; nothing is read twice. What the page is served follows the review: when `.impeccable/review/hero.json` is a `hero` manifest with one page component whose preview is this entry, the page gets exactly that entry plus the component's declared `dependencies` (a declared path outside the static inventory is refused), so a file the review would not serve fails here as an undeclared dependency too. Before any review manifest names the entry, the page gets the static inventory (every static browser file outside hidden directories and `node_modules`). In both cases the bound spec and comp are never served. The capture is refused when the page requests the comp, or when a file the page loads is a byte copy of the comp or of the approved review screenshot, or is an HTML, CSS, JS or SVG file that inlines either as a base64 data URI (whitespace inside the URI is ignored). These checks run on the files the page actually loads under both policies, so a served file the page never loads (an unused backup of the comp, or one listed in the manifest's `dependencies`) does not block the capture. Byte checks cannot see a re-encoded copy, so the spec itself is the backstop: it declares every raster in the first viewport as a raster region, and this spec declares none. Each frame therefore measures the area images paint, as a union on a 4px grid (`img`, `video`, `input type=image`, SVG `image`, and any element or `::before`/`::after` painting a `url()` background, border, mask, list marker or generated content). Gradients and same-document fragment references (`url(#id)`, an SVG mask, pattern, gradient, clip path, filter, marker or symbol) are code and do not count, unless the definition they name holds raster content: an `image`, `feImage`, `img`, `video` or `input type=image` anywhere inside it, an `href` or `url()` that leaves the document, or a fragment reference to another definition that holds raster content. An `image` inside a definition has no rendered box, so the element that references such a definition counts instead: through `mask`/`mask-image`, `clip-path`, `fill` or `use` at its box (a `use` also through the `fill` and `stroke` it passes to its clones), through `stroke` at its box widened by half the stroke width on screen (the transform's largest scale, or the stroke's own width for `vector-effect: non-scaling-stroke`), through `filter` at the filter region (the whole viewport when a region length uses a unit other than plain numbers, `px` in user space or percentages in bounding-box units, and the outermost `svg` box for an element inside an `svg`), and through a marker at the outermost `svg` box. A `::before` or `::after` with such a filter also counts its filter region. A no-repeat background with an explicit pixel size counts at that size, any other at its box; `object-fit: contain` or `scale-down` counts the letterboxed picture, not the element box. Each box is clipped by the ancestors on its containing-block chain that clip (non-visible overflow, or `contain: paint`), so an absolutely positioned or fixed image is not clipped by a wrapper it escapes; an element that is hidden, or under an ancestor with opacity 0, paints nothing. The result is clipped to the viewport, and the capture is refused when images paint 15% or more of it. The refusal names the largest images and says the spec declares no raster region, so a large image contradicts it: declare it as a raster region or remove it and draw that area in code. 15% sits well above logos, avatars and icons (a 200x60 logo is about 1% of a 1440x900 viewport, twelve 40px avatars under 2%) and well below any image that could carry the comparison; the measurement is recorded per frame as `rasterCoverage` in `frameProofs`. The manifest's bytes are bound to the capture like its other inputs. The frames carry no region receipts, so no rendered-presence or placement check runs; the hero and responsive gates read the frames with the same comparison and region readings as any other capture. `inputs.json` (and `nativeCapture.inputs` in the report) records `"captureMethod": "assembled-page-viewport"`, `dependencyPolicy` (`hero-review-manifest` or `static-inventory`), `servedToPage`, the browser version, a `frameProofs` entry per frame and, with a manifest, `reviewManifestSha256`; the report's `nativeCapture.integrityScope` reads `assembled-page viewport from frozen inputs; the comp and approved screenshots are never served to the page; no raster presence or placement check (no raster region); existing visual scores unchanged` (the capture's own `inputs.integrityScope` adds that images cover under 15% of each frame), with no `framePolicy`. The review's other limits apply: a page with a `canvas`, `iframe`, `object` or `embed`, a running animation, an external dependency, or a missing primary font is refused with that reason. Because the gate's frame and the reviewed screenshot come from one capture method, an accepted first-viewport review of a code-only page binds to the current capture like any other and ends the numeric fight as described above. Specs with at least one raster region keep the raster capture unchanged.
+Every native capture pins the page's clock. Before navigation the browser installs a script on every new document that starts `new Date()`, `Date()`, `Date.now()` and an argument-less `Intl.DateTimeFormat` `format` / `formatToParts` at a pinned instant and lets them advance in real time (`Date.prototype.constructor` is the shim, so `new Date().constructor === Date` holds), so code that measures elapsed time still sees time pass. A component-review round pins one instant for all its views and records it in each view's proof as `clock: {pinnedEpochMs, policy}`. An entry capture pins every frame to one instant, recorded in `inputs.json` as `clock: {pinnedEpochMs, source, policy}`: when the verified approved review carries a pinned instant, the capture uses it (`source: "approved-review"`, and the approval proof carries `pinnedClockMs`), so a page that prints the time or the day renders the state the user accepted; otherwise the capture's start (`source: "capture-start"`). Approvals recorded before pinning carry no instant and are compared as before.
+
Through the host capture service (`IMPECCABLE_CAPTURE_PORT` and `IMPECCABLE_CAPTURE_CAPABILITY`), the same capture crosses unchanged: the service returns each frame's receipts as `regions`, and the report with every field above plus `captureService`. The client reads the bound spec from the project, checks its SHA-256 against the spec entry in the capture's input manifest (a spec edited since the capture is refused), and lets the spec decide the kind. A spec with no `raster` region requires `"captureMethod": "assembled-page-viewport"`, an empty `regions` list in every frame, a `frameProofs` entry per frame whose `rasterCoverage.share` is under the 15% limit, a `dependencyPolicy` of `hero-review-manifest` or `static-inventory`, and a `servedToPage` list that names neither the spec nor the comp. A spec with raster regions requires any other capture method and, in each frame, exactly one receipt per raster region the in-process capture measures there (every raster region in `hero` and `desktop`, the first one in `mobile`), at most 32. 32 is the native batch bound: the in-process capture refuses a frame with more raster regions, so the service can never return more. Anything else, including a raster capture with an empty `regions` list or a text-only method claimed for a raster spec, fails with `native entry capture unavailable: invalid native capture regions` (or names the mismatched method) and the capture is released. The service's `/audit` endpoint compares the saved `<frame>-observations.json` (`[]` for a text-only frame), frame PNGs, `inputs.json` and `human-approved.png` against its own capture as for raster captures.
For native comp-led runs, a verified assembled-page review can resolve a text-style contradiction against the original comp. The renderer reads the private native review session, binds the approved screenshot (verified receipt, capture digest and blob hash) and the comp bytes, and compares the disputed text region against that human-approved rendering at the current desktop breakpoint. The original comp scores remain in the report; accepted region IDs and the review revision are recorded separately under `humanTextReview`.
@@ -1974,6 +1976,14 @@ For native comp-led runs, a verified assembled-page review can resolve a text-st
The approval is bound visually, not by page bytes: later edits to the entry, its stylesheets or its assets keep it, and every gate compares the approved screenshot with the current capture instead. It never waives missing regions, raster production/placement, or native capture checks. A changed comp, a stale receipt, a partial component capture, or a changed approved image cannot provide this evidence. A host capture service may select its private native review session with `IMPECCABLE_CAPTURE_REVIEW_SESSION` at service startup; this is not a caller-supplied capture parameter. Standalone native builds use the matching local component-review session.
+### Responsive gate: displaced regions, crops and escalation
+
+The responsive gate compares the desktop first viewport with the comp: the native desktop frame (1440 wide at the comp's aspect, 1440x960 for a 1536x1024 comp), or the top of `.impeccable/review/desktop.png` at the comp's aspect, scaled to the comp's width. A region that is not at its box is searched for before it is called missing. Every non-texture region whose verdict there is `missing`, and every `text`, `control` or `chrome` region whose verdict is `contradicted`, is looked for within 12% of the comp's height and 4% of its width of its box (blurred luma at a working scale of at most 96 samples per axis, normalized cross-correlation of at least 0.6 over the part of the region that lands in the capture, at least a third of its rows, then the full comp-diff score of that part reading match or drift). A full-page `desktop.png` is searched below the first viewport too. A match that covers at least half of another region of the same kind and similar size (area within half to double), where that region still reads match or drift at its own box, is that region's own pixels and is discarded, so a missing control never borrows an identical neighbour. When the region's own pixels left the frame (a native frame holds the first viewport alone), the content directly above it in its column (three region heights or 8% of the comp, whichever is taller) is searched downward instead, and the region counts as displaced when that offset leaves less than half of it in the frame. A displaced region that still lies wholly inside the first viewport becomes `drift` with the advisory `(advisory, still inside the first viewport) at desktop width, region <id> sits about <N>px lower than in the comp`. One that runs past the frame becomes verdict `displaced` (`rawVerdict` keeps the measurement) and blocks with `at desktop width, region <id> is displaced, not missing: it renders about <N>px lower than in the comp, and <P>% of it stays inside the <W>x<H> first viewport` (or, read from its column, `the content above it in its column sits about <N>px lower than in the comp, which pushes <id> out of the <W>x<H> first viewport`), followed by the remedy (size what sits above it in proportion to the viewport, not with fixed px or a px floor). Offsets are in the capture's own pixels and recorded as the region's `displacement` (`dx`, `dy`, `visible`, `inferred`). A region found nowhere stays `at desktop width, region <id> is missing`. A plate whose current receipt passed and that renders at desktop width (detail at least 30%) is never missing there: at structure 50% or more it is drift as before; below, it is located like any region, displaced past the frame blocks, and otherwise it is drift with an advisory that it renders away from its comp box.
+
+A failed responsive gate sets the same repair crops as the hero: the regions with blocking reasons, lowest score first, at most three, so `advance` prints the `LOOK FIRST` list (`.impeccable/review/diff/desktop/regions/<id>.png` with verdict and scores) and the remedy paragraph, plus one line for a `displaced` crop. Each `advance` from the responsive phase appends `{at, score, worstIds, blockingReasons}` to `phases.responsive.history` (last six kept). After three failed attempts in a row the refusal leads with `The responsive gate has failed 3 attempts in a row.` and the route: with no first viewport accepted, present the first-viewport review (stage hero) with the current page; with one accepted (locally or in a session the host names), show the user the desktop side-by-side with the blocking regions and ask them to choose between restoring them and keeping the desktop first viewport; keeping it downgrades the comp at desktop width and is recorded only by quoting their words saying so in `advance --force --reason` (the refusal gives an example `force` accepts). Both say the phase stays open and that a finish recorded over it is an unfinished build, not a fix round.
+
+The responsive `NEXT` line names what the gate diffs: under native capture, the gate's own desktop first viewport at 1440 wide (the frame size computed from the breakpoint) and a 390-wide mobile frame; otherwise the first viewport of `desktop.png` at that size.
+
### Visual approval carry-forward
Native component review carries a submitted approval when all displayed image
diff --git a/skill/reference/component-review.md b/skill/reference/component-review.md
index 98b6a2d89..0ee3fcfb4 100644
--- a/skill/reference/component-review.md
+++ b/skill/reference/component-review.md
@@ -27,7 +27,7 @@ Then run `plan`, `capture` and `serve` again. Unchanged decisions carry over, so
## Assemble and review
-Build the first viewport from the approved plates and plan, and run the hero gate. Human review does not waive its integrity checks. After three failed hero attempts, stop iterating and present the first-viewport review with the current build; the user's eye settles what the readings could not.
+Build the first viewport from the approved plates and plan, and run the hero gate. Human review does not waive its integrity checks. After three failed hero attempts, or three failed responsive attempts before any first viewport is accepted, stop iterating and present the first-viewport review with the current build; the user's eye settles what the readings could not.
Present a second manifest at `.impeccable/review/hero.json`. You write this one, and its shape is fixed:
diff --git a/skill/reference/new-work.md b/skill/reference/new-work.md
index 711d0069e..68e96aced 100644
--- a/skill/reference/new-work.md
+++ b/skill/reference/new-work.md
@@ -117,7 +117,7 @@ Inspect the proposed map before producing assets: `impeccable comp-spec --comp <
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.
5. **motion.** The signature interaction, reveals, and motion, orchestrated once rather than scattered.
-6. **responsive.** The other viewports, and the first viewport at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-pixel grid that wraps a hundred pixels narrower. Capture `desktop.png` (1440 wide, full page) and `mobile.png` (390 wide) into `.impeccable/review/`; the gate diffs the desktop capture against the comp and refuses a first viewport that only held at the comp's width. A comp'd surface that is mobile-first was comped portrait; the plates were produced for that frame.
+6. **responsive.** The other viewports, and the first viewport at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-pixel grid that wraps a hundred pixels narrower, and sizes in proportion to the viewport rather than px floors, so nothing the comp's first viewport shows is pushed below it and an accepted first viewport still matches at desktop width. Capture `desktop.png` (1440 wide, full page) and `mobile.png` (390 wide) into `.impeccable/review/`; the gate diffs the desktop first viewport (1440 wide at the comp's aspect; a native capture renders its own) against the comp and refuses a first viewport that only held at the comp's width. When it fails, open the crops it lists, in order: a `displaced` region is present but pushed out of the first viewport, so restore it there by resizing what sits above it, not by moving it alone. After three failed attempts the gate names the route (the first-viewport review, or the user's decision once one is accepted); take it instead of iterating or recording `fix`. A comp'd surface that is mobile-first was comped portrait; the plates were produced for that frame.
### Code-led
@@ -137,15 +137,15 @@ Preserve semantics, accessibility, performance, responsiveness, project conventi
## 7. Inspect and finish
-Inspect the surface's target sizes in one batched screenshot round: desktop and mobile on the web; on a native platform (`ios` / `android` / `adaptive`), the shipped device classes per OS, captured from the simulator or emulator the way the platform reference's Verifying the build section describes. When the harness reports the user's actual viewport (an in-app browser's size, a named resolution), add that width to the set: the width that breaks is the one the user sees first. Critique the render against the user's request and the direction contract, fix material gaps, and confirm with one final round; two rounds is the ceiling, and fixes batch between them rather than earning per-tweak screenshots. On a comp-led build, run `{{scripts_path}}/impeccable comp-diff --comp <approved comp> --build .impeccable/review/desktop.png --spec .impeccable/build/spec.json --out-dir .impeccable/review/diff/final` and read its region rows and paired crops as the critique: the side-by-side is the view the build thread never has on its own, and a region it scores missing or contradicted is a fix whatever the page looks like from memory. Never judge fidelity from one full-page thumbnail; it hides exactly the failures that matter. On a Persuade surface, verify the mode did its job: a first-time visitor should know what this is, why it matters, and what to do within seconds, in the form's own vocabulary.
+Inspect the surface's target sizes in one batched screenshot round: desktop and mobile on the web; on a native platform (`ios` / `android` / `adaptive`), the shipped device classes per OS, captured from the simulator or emulator the way the platform reference's Verifying the build section describes. When the harness reports the user's actual viewport (an in-app browser's size, a named resolution), add that width to the set: the width that breaks is the one the user sees first. Critique the render against the user's request and the direction contract, fix material gaps, and confirm with one final round; two rounds is the ceiling, and fixes batch between them rather than earning per-tweak screenshots. The ceiling bounds inspection and never closes an open build-phase gate: a gate stays open until it passes or the route it names is taken. On a comp-led build, run `{{scripts_path}}/impeccable comp-diff --comp <approved comp> --build .impeccable/review/desktop.png --spec .impeccable/build/spec.json --out-dir .impeccable/review/diff/final` and read its region rows and paired crops as the critique: the side-by-side is the view the build thread never has on its own, and a region it scores missing or contradicted is a fix whatever the page looks like from memory. Never judge fidelity from one full-page thumbnail; it hides exactly the failures that matter. On a Persuade surface, verify the mode did its job: a first-time visitor should know what this is, why it matters, and what to do within seconds, in the form's own vocabulary.
A capture is evidence only when it is valid, and you validate before you send. Settle or disable entrance motion first: an element hidden by animation timing reads as a missing element and gets fixed into a regression. Capture full-page shots from the document top. Capture the comp comparison at the comp's own pixel dimensions. Then open every file once and confirm it shows what its name claims: no black or blank regions, no wrong section behind a right filename, no half-loaded state. A malformed capture sent onward costs the whole round; the reviewer answers it with `disposition: recapture` and nothing it reviewed binds. <!-- rule:skill-capture-validity -->
-After the second inspection round the build thread's polishing is over: no further defect hunts, micro-edit scripts, or rebuilds here; whatever remains ships through the handoffs, where a fresh context does the finding better and cheaper. On the web, where this harness runs no design hook, run `{{scripts_path}}/impeccable detect --json` on the changed targets once here, fix what is mechanical, and pass the remaining findings to the reviewer; a hookless web build that skips this ships every tell the hook exists to catch. A native platform skips the detector entirely: it reads HTML and CSS and has no verdict on native code, so the reviewer's floor check is the only slop gate and the input packet says so. Capture the screenshots into `.impeccable/review/`, one file per captured viewport (on the web, `desktop.png` and `mobile.png`, plus `user-<width>.png` whenever the user's viewport joined the inspected set; on native, one per device class, such as `phone.png` and `tablet.png`, suffixed per OS on adaptive), creating that directory when the harness does not; the paths you pass the reviewer are its spec, every viewport you inspected is named required in the packet, and that directory is where it looks when a passed path is missing.
+After the second inspection round the build thread's polishing is over: no further defect hunts, micro-edit scripts, or rebuilds here (an open build-phase gate is not a defect hunt; it closes as above); whatever remains ships through the handoffs, where a fresh context does the finding better and cheaper. On the web, where this harness runs no design hook, run `{{scripts_path}}/impeccable detect --json` on the changed targets once here, fix what is mechanical, and pass the remaining findings to the reviewer; a hookless web build that skips this ships every tell the hook exists to catch. A native platform skips the detector entirely: it reads HTML and CSS and has no verdict on native code, so the reviewer's floor check is the only slop gate and the input packet says so. Capture the screenshots into `.impeccable/review/`, one file per captured viewport (on the web, `desktop.png` and `mobile.png`, plus `user-<width>.png` whenever the user's viewport joined the inspected set; on native, one per device class, such as `phone.png` and `tablet.png`, suffixed per OS on adaptive), creating that directory when the harness does not; the paths you pass the reviewer are its spec, every viewport you inspected is named required in the packet, and that directory is where it looks when a passed path is missing.
Then spawn the shipped finish reviewer, `impeccable-finish-reviewer` (`impeccable_finish_reviewer` in codex; `/impeccable-finish-reviewer` in Cursor; on GitHub Copilot say "Use the impeccable-finish-reviewer agent"), with the original request, confirmed answers, the artifact path, the screenshot paths, the direction contract, existing hook findings, the QUALITY BAR card and approved comp paths (a code-led build has no approved comp; the chosen decision comp rides in that slot as the critique reference, named as such), on a comp-led build the build state (`.impeccable/build/state.json`), the spec, and the diff directories (`.impeccable/review/diff/hero/` and `.impeccable/review/diff/final/`, whose side-by-side, heatmap, region pairs, and `report.json` are the fidelity evidence), the craft-floor reference path, and on a native platform the platform reference path(s), [ios.md](ios.md) / [android.md](android.md), both on adaptive, plus one line saying no detector ran, so the reviewer judges in the platform's conventions rather than the web's. The reviewer has no browser; screenshots you fail to pass are checks it cannot run. Never read the shipped agents' definition files before spawning; the harness loads them at spawn, and you owe only the input packet. Wait on any agent with one long timeout rather than a loop of short polls, and spend the wait on the next independent step. Verify the return carries the five contract sections (a recapture return carries one, its recapture list); on an empty or thrashed return, respawn once with the same inputs. This review never runs inside the build thread and never inherits it: spawn the reviewer fresh, with no forked conversation history (`fork_turns: 0` in codex); a reviewer that inherits your transcript inherits your framing, your optimism, and your abstractions, and everything it needs travels in the inputs above. Only a harness with no subagent capability at all substitutes a fresh in-thread pass after stepping fully out of the build context, run from [degraded/finish-reviewer.md](degraded/finish-reviewer.md), and a substituted or failed-and-replaced review is disclosed in one line at finish, never silently. <!-- rule:skill-finish-separate-reviewer -->
-Act on the disposition word; there are exactly four. **recapture**: the evidence failed, not the build. Recapture what the return names under the capture-validity rules, then run a full review over the new evidence. A review conducted on invalid evidence binds nothing, and a verdict pass may never follow it. **rebuild**: fidelity failed wholesale, not in patches. Skip the fix batch and execute the rebuild immediately: re-derive the named regions, produce the named assets, and send the result back for a fresh full review, never a verdict pass; a rebuild replaces regions wholesale, so the whole matrix runs again over the recaptures. Tell the user what is happening rather than asking permission to fix a failure. Consult the user only on a second rebuild directive, both verdicts on the table, or when rebuilding would discard content the user approved. **ship**: nothing is owed; report the verdict at its scope and continue to the documenter. **fix**: apply the material fixes in one batch, rebuild once, and recapture the same viewports over the same files. A recapture measures positions, loading, and overflow; it cannot measure whether a fix reached the quality the finding named, so send the recaptured screenshots back to the same reviewer for a verdict scoring every material fix resolved, partial, or unresolved (through the harness's agent continuation; without one, run the scoring fresh from [degraded/finish-reviewer.md](degraded/finish-reviewer.md)'s Verdict Pass). Fixes scored partial or unresolved get another batch, recapture, and verdict. Two rounds is the budget an unattended run ends at; an attended session's ceiling belongs to the user, so when the second verdict still lists open items, put the table in front of them and let them choose between shipping as it stands and funding another round. Whoever decides, stop the moment a round resolves nothing, and the reviewer's findings are the only list you work from, never your own re-opened hunt. Do not run a second detector. <!-- rule:skill-verdict-bounds-the-finish -->
+Act on the disposition word; there are exactly four. **recapture**: the evidence failed, not the build. Recapture what the return names under the capture-validity rules, then run a full review over the new evidence. A review conducted on invalid evidence binds nothing, and a verdict pass may never follow it. **rebuild**: fidelity failed wholesale, not in patches. Skip the fix batch and execute the rebuild immediately: re-derive the named regions, produce the named assets, and send the result back for a fresh full review, never a verdict pass; a rebuild replaces regions wholesale, so the whole matrix runs again over the recaptures. Tell the user what is happening rather than asking permission to fix a failure. Consult the user only on a second rebuild directive, both verdicts on the table, or when rebuilding would discard content the user approved. **ship**: nothing is owed; report the verdict at its scope and continue to the documenter. **fix**: apply the material fixes in one batch, rebuild once, and recapture the same viewports over the same files. On a comp-led build the batch keeps its gates passing: while a phase is open, rerun `{{scripts_path}}/impeccable build-phase advance` after it. Once all are closed, the final `finish --disposition ship`, recorded only on the reviewer's ship verdict, rechecks the page and reopens responsive when it no longer holds. A recapture measures positions, loading, and overflow; it cannot measure whether a fix reached the quality the finding named, so send the recaptured screenshots back to the same reviewer for a verdict scoring every material fix resolved, partial, or unresolved (through the harness's agent continuation; without one, run the scoring fresh from [degraded/finish-reviewer.md](degraded/finish-reviewer.md)'s Verdict Pass). Fixes scored partial or unresolved get another batch, recapture, and verdict. Two rounds is the budget an unattended run ends at; an attended session's ceiling belongs to the user, so when the second verdict still lists open items, put the table in front of them and let them choose between shipping as it stands and funding another round. Whoever decides, stop the moment a round resolves nothing, and the reviewer's findings are the only list you work from, never your own re-opened hunt. Do not run a second detector. <!-- rule:skill-verdict-bounds-the-finish -->
A rebuild and a fix round share one asset rule: a raster either round creates or replaces is still asset work under [visualize.md](visualize.md)'s Produce section and keeps its **provenance** like every build raster, and a raster the round abandons is deleted in the same batch. Before either round's result goes back for review or verdict, run `{{scripts_path}}/impeccable embed-prompt --scan <asset-dir...>` over the directories the artifact's rasters ship from and clear every file it reports by embedding what it is missing: the exact generation prompt for a produced raster, the origin for a sourced, stock, or pre-existing one. The scan only reads; deletion is reserved for rasters the round abandoned, never for a file the scan flagged. <!-- rule:skill-late-raster-provenance -->
@@ -153,4 +153,4 @@ Report the final verdict under the reviewer's own disposition word and at its ac
After the last correction, spawn the shipped documenter, `impeccable-documenter` (`impeccable_documenter` in codex), with the project root, artifact path, direction contract, PRODUCT.md, [document.md](document.md), and write boundary. Without subagents, load [degraded/documenter.md](degraded/documenter.md) and [document.md](document.md) before writing. Verify the outcome: new worlds and approved system changes require token-bearing DESIGN.md **and** `.impeccable/design.json`, not prose alone. Ordinary extensions compare the finished build against the incumbent system, preserve its files, and report the evidence checked; report pre-existing drift without repairing it unasked. Recheck after later edits. Finish only when review and documentation are complete. <!-- rule:skill-documenter-records-the-world -->
-On a comp-led build, record the final review disposition with `{{scripts_path}}/impeccable build-phase finish --disposition <ship|fix|rebuild|recapture>` before the final response. A refused `ship` is an unfinished build; report the outstanding phase with the verdict.
+On a comp-led build, record the final review disposition with `{{scripts_path}}/impeccable build-phase finish --disposition <ship|fix|rebuild|recapture>` before the final response. A refused `ship` is an unfinished build; report the outstanding phase with the verdict. Never record `fix` to end a run over an open gate: take the route the gate names, and when the user leaves it open, report that phase as open.
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index b495225c8..8ff625d71 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -306,3 +306,10 @@ Seed cases now set `IMPECCABLE_SKILL_DIR` to `tests/fixtures/mode-rules-skill` (
- `question-update-comps-next`, `question-wait-flip`: the NEXT line reads `it and the MODE RULES block concept-seed printed for this surface govern every card's image` where it read `its comp rules govern every card's image`.
Exit status, stderr and files are unchanged everywhere. New cases: `seed-mode-rules-persuade`, `-experience` (reads `mode-persuade.md`), `-operate`, `-read` (one per mode file, `oracle-key-5`), and `seed-mode-rules-missing-file`, `-missing-section` against `tests/fixtures/mode-rules-skill-partial` (no `mode-read.md`; a `mode-operate.md` without `## Comps`), which print the unavailable line.
+
+## Recorded 2026-10-02: responsive gate names displaced regions, prints crops, escalates
+
+New cases, recorded from the engine and reviewed by hand (no JS golden ever covered the responsive gate's printed output).
+
+- `build-phase-responsive-displaced`: a sign-off line pushed 40px below the first viewport by a growing column reads `displaced, not missing` with the offset and the visible share, the `LOOK FIRST` crop list and the displaced remedy line print, and the third failed `advance` leads with the three-attempt route to the first-viewport review.
+- `build-phase-responsive-missing`: the same region absent from the capture still reads `at desktop width, region sign-off is missing`, now with its repair crop listed.
diff --git a/tests/oracle/cases/comp.mjs b/tests/oracle/cases/comp.mjs
index b47a5c560..0f43917f5 100644
--- a/tests/oracle/cases/comp.mjs
+++ b/tests/oracle/cases/comp.mjs
@@ -87,6 +87,38 @@ const cases = [
},
{ id: 'build-phase-usage', verb: 'build-phase', workspace: WS, args: [], env: env() },
+ // 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 whose
+ // column grew pushes the sign-off 40px down past the first viewport: the gate
+ // calls it displaced, prints the repair crops, and on the third failed attempt
+ // leads with the route to the user. A capture without the line calls it missing.
+ {
+ id: 'build-phase-responsive-displaced', verb: 'build-phase', workspace: 'comp-responsive',
+ setup: (ws) => {
+ fs.mkdirSync(path.join(ws, '.impeccable/review'), { recursive: true });
+ fs.mkdirSync(path.join(ws, '.impeccable/build'), { recursive: true });
+ fs.copyFileSync(path.join(ws, 'spec.json'), path.join(ws, '.impeccable/build/spec.json'));
+ fs.copyFileSync(path.join(ws, 'state.json'), path.join(ws, '.impeccable/build/state.json'));
+ fs.copyFileSync(path.join(ws, 'desktop-pushed.png'), path.join(ws, '.impeccable/review/desktop.png'));
+ fs.copyFileSync(path.join(ws, 'mobile.png'), path.join(ws, '.impeccable/review/mobile.png'));
+ },
+ env: env(),
+ steps: [{ args: ['advance', '--min', '0.1'] }, { args: ['advance', '--min', '0.1'] }, { args: ['advance', '--min', '0.1'] }],
+ },
+ {
+ id: 'build-phase-responsive-missing', verb: 'build-phase', workspace: 'comp-responsive',
+ setup: (ws) => {
+ fs.mkdirSync(path.join(ws, '.impeccable/review'), { recursive: true });
+ fs.mkdirSync(path.join(ws, '.impeccable/build'), { recursive: true });
+ fs.copyFileSync(path.join(ws, 'spec.json'), path.join(ws, '.impeccable/build/spec.json'));
+ fs.copyFileSync(path.join(ws, 'state.json'), path.join(ws, '.impeccable/build/state.json'));
+ fs.copyFileSync(path.join(ws, 'desktop-gone.png'), path.join(ws, '.impeccable/review/desktop.png'));
+ fs.copyFileSync(path.join(ws, 'mobile.png'), path.join(ws, '.impeccable/review/mobile.png'));
+ },
+ args: ['advance', '--min', '0.1'], env: env(),
+ },
+
// component-review plan: the v3 packet derives from the measured spec. The
// spec fixture has one plate region (art), one non-container chrome (top,
// a plan item) and one text region (body, a code region).
diff --git a/tests/oracle/golden/build-phase-responsive-displaced.json b/tests/oracle/golden/build-phase-responsive-displaced.json
new file mode 100644
index 000000000..583385c64
--- /dev/null
+++ b/tests/oracle/golden/build-phase-responsive-displaced.json
@@ -0,0 +1,23 @@
+{
+ "steps": [
+ {
+ "stdout": "GATE RESPONSIVE FAILED (state unchanged)\n LOOK FIRST, in this order, before editing anything (comp on the left, your build on the right):\n .impeccable/review/diff/desktop/regions/sign-off.png sign-off: displaced 37% (structure 22%, color 99%, detail 9%)\n A region scored missing needs its material (a plate placed, or produced), not a value change; contradicted needs its structure re-derived from the spec box; drift is where padding and size edits belong. When a thin chrome strip (masthead, breadcrumb, table header) is the worst region, check its box height in the spec against the comp first: a strip one grid row tall in the spec but 53px in the comp compares your build against ground it never had.\n A region scored displaced is present but pushed out of the first viewport: restore it there by sizing what sits above it in proportion to the viewport, not by moving it alone; a px floor or fixed row height that grows at this width is the usual cause.\n - at desktop width, region sign-off is displaced, not missing: it renders about 40px lower than in the comp, and none of it stays inside the 400x360 first viewport. Restore it into the first viewport: size what sits above it in proportion to the viewport (the comp's own ratios), not with fixed px or a px floor that grows it at this width.\n then <WS>/.impeccable/review/diff/desktop/side-by-side.png for the whole viewport\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null
+ },
+ {
+ "stdout": "GATE RESPONSIVE FAILED (state unchanged)\n LOOK FIRST, in this order, before editing anything (comp on the left, your build on the right):\n .impeccable/review/diff/desktop/regions/sign-off.png sign-off: displaced 37% (structure 22%, color 99%, detail 9%)\n A region scored missing needs its material (a plate placed, or produced), not a value change; contradicted needs its structure re-derived from the spec box; drift is where padding and size edits belong. When a thin chrome strip (masthead, breadcrumb, table header) is the worst region, check its box height in the spec against the comp first: a strip one grid row tall in the spec but 53px in the comp compares your build against ground it never had.\n A region scored displaced is present but pushed out of the first viewport: restore it there by sizing what sits above it in proportion to the viewport, not by moving it alone; a px floor or fixed row height that grows at this width is the usual cause.\n - at desktop width, region sign-off is displaced, not missing: it renders about 40px lower than in the comp, and none of it stays inside the 400x360 first viewport. Restore it into the first viewport: size what sits above it in proportion to the viewport (the comp's own ratios), not with fixed px or a px floor that grows it at this width.\n then <WS>/.impeccable/review/diff/desktop/side-by-side.png for the whole viewport\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null
+ },
+ {
+ "stdout": "GATE RESPONSIVE FAILED (state unchanged)\n LOOK FIRST, in this order, before editing anything (comp on the left, your build on the right):\n .impeccable/review/diff/desktop/regions/sign-off.png sign-off: displaced 37% (structure 22%, color 99%, detail 9%)\n A region scored missing needs its material (a plate placed, or produced), not a value change; contradicted needs its structure re-derived from the spec box; drift is where padding and size edits belong. When a thin chrome strip (masthead, breadcrumb, table header) is the worst region, check its box height in the spec against the comp first: a strip one grid row tall in the spec but 53px in the comp compares your build against ground it never had.\n A region scored displaced is present but pushed out of the first viewport: restore it there by sizing what sits above it in proportion to the viewport, not by moving it alone; a px floor or fixed row height that grows at this width is the usual cause.\n - The responsive gate has failed 3 attempts in a row. Stop iterating and present the first-viewport review (the assembled hero, stage hero, in component-review.md) with the current page, so the user judges the first viewport in context. An accepted review carries to desktop width while the desktop capture still matches the approved screenshot; displaced and missing regions still block. Until then this phase stays open; a finish recorded over it is an unfinished build, not a fix round.\n - at desktop width, region sign-off is displaced, not missing: it renders about 40px lower than in the comp, and none of it stays inside the 400x360 first viewport. Restore it into the first viewport: size what sits above it in proportion to the viewport (the comp's own ratios), not with fixed px or a px floor that grows it at this width.\n then <WS>/.impeccable/review/diff/desktop/side-by-side.png for the whole viewport\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null
+ }
+ ],
+ "files": {}
+}
diff --git a/tests/oracle/golden/build-phase-responsive-missing.json b/tests/oracle/golden/build-phase-responsive-missing.json
new file mode 100644
index 000000000..a8ef20d8c
--- /dev/null
+++ b/tests/oracle/golden/build-phase-responsive-missing.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "GATE RESPONSIVE FAILED (state unchanged)\n LOOK FIRST, in this order, before editing anything (comp on the left, your build on the right):\n .impeccable/review/diff/desktop/regions/sign-off.png sign-off: missing 30% (structure 24%, color 54%, detail 0%)\n A region scored missing needs its material (a plate placed, or produced), not a value change; contradicted needs its structure re-derived from the spec box; drift is where padding and size edits belong. When a thin chrome strip (masthead, breadcrumb, table header) is the worst region, check its box height in the spec against the comp first: a strip one grid row tall in the spec but 53px in the comp compares your build against ground it never had.\n - at desktop width, region sign-off is missing\n then <WS>/.impeccable/review/diff/desktop/side-by-side.png for the whole viewport\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/workspaces/comp-responsive/comp.png b/tests/oracle/workspaces/comp-responsive/comp.png
new file mode 100644
index 000000000..d61c46009
Binary files /dev/null and b/tests/oracle/workspaces/comp-responsive/comp.png differ
diff --git a/tests/oracle/workspaces/comp-responsive/desktop-gone.png b/tests/oracle/workspaces/comp-responsive/desktop-gone.png
new file mode 100644
index 000000000..a271fe7db
Binary files /dev/null and b/tests/oracle/workspaces/comp-responsive/desktop-gone.png differ
diff --git a/tests/oracle/workspaces/comp-responsive/desktop-pushed.png b/tests/oracle/workspaces/comp-responsive/desktop-pushed.png
new file mode 100644
index 000000000..4f59cfbf8
Binary files /dev/null and b/tests/oracle/workspaces/comp-responsive/desktop-pushed.png differ
diff --git a/tests/oracle/workspaces/comp-responsive/index.html b/tests/oracle/workspaces/comp-responsive/index.html
new file mode 100644
index 000000000..e2ad9f57f
--- /dev/null
+++ b/tests/oracle/workspaces/comp-responsive/index.html
@@ -0,0 +1 @@
+<main><ul class="menu"></ul><p class="sign-off">Buon appetito!</p></main>
diff --git a/tests/oracle/workspaces/comp-responsive/mobile.png b/tests/oracle/workspaces/comp-responsive/mobile.png
new file mode 100644
index 000000000..d61c46009
Binary files /dev/null and b/tests/oracle/workspaces/comp-responsive/mobile.png differ
diff --git a/tests/oracle/workspaces/comp-responsive/spec.json b/tests/oracle/workspaces/comp-responsive/spec.json
new file mode 100644
index 000000000..74d5e0078
--- /dev/null
+++ b/tests/oracle/workspaces/comp-responsive/spec.json
@@ -0,0 +1,46 @@
+{
+ "comp": "comp.png",
+ "compSize": {
+ "width": 400,
+ "height": 360
+ },
+ "regions": [
+ {
+ "id": "menu",
+ "kind": "chrome",
+ "medium": "semantic",
+ "note": "ruled menu rows",
+ "box": {
+ "x": 0.54,
+ "y": 0.1,
+ "w": 0.42,
+ "h": 0.78
+ },
+ "px": {
+ "x": 216,
+ "y": 36,
+ "w": 168,
+ "h": 281
+ }
+ },
+ {
+ "id": "sign-off",
+ "kind": "text",
+ "medium": "semantic",
+ "note": "sign-off line",
+ "type": {},
+ "box": {
+ "x": 0.555,
+ "y": 0.9111,
+ "w": 0.35,
+ "h": 0.0611
+ },
+ "px": {
+ "x": 222,
+ "y": 328,
+ "w": 140,
+ "h": 22
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/oracle/workspaces/comp-responsive/state.json b/tests/oracle/workspaces/comp-responsive/state.json
new file mode 100644
index 000000000..9250d4a7d
--- /dev/null
+++ b/tests/oracle/workspaces/comp-responsive/state.json
@@ -0,0 +1,51 @@
+{
+ "tool": "build-phase",
+ "version": 2,
+ "comp": "comp.png",
+ "breakpoint": "400x360",
+ "artifact": "index.html",
+ "phase": "responsive",
+ "phases": {
+ "comps": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "spec": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "plates": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "hero": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "sections": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "motion": {
+ "status": "closed",
+ "attempts": 0,
+ "notes": []
+ },
+ "responsive": {
+ "status": "open",
+ "attempts": 0,
+ "notes": []
+ },
+ "review": {
+ "status": "pending",
+ "attempts": 0,
+ "notes": []
+ }
+ },
+ "finish": null
+}
\ No newline at end of file