Skip to content

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

JavaScript

Keep the comp away from raster entry captures (#910)

Paul Bakaus353ef42e2a0e
diff --git a/crates/browser/src/cdp.rs b/crates/browser/src/cdp.rs
index 56a52ba81..22b257e5e 100644
--- a/crates/browser/src/cdp.rs
+++ b/crates/browser/src/cdp.rs
@@ -1323,6 +1323,16 @@ impl<'a> Page<'a> {
for candidate in retained {
if !candidates.contains(candidate) { candidates.push(candidate.clone()); }
}
+ self.native_pseudo_boxes(world, &candidates)
+ }
+
+ /// Native layout boxes of the named generated boxes (`{index, pseudo}`,
+ /// `pseudo` without colons, `index` in querySelectorAll order): the bounds
+ /// of the border quad, transforms included, in viewport pixels. A generated
+ /// box with no layout box of its own reports `box: null`; one that is not
+ /// generated at all is not listed.
+ pub fn native_pseudo_boxes(&mut self, world: &IsolatedWorld, candidates: &[Value]) -> CdpResult<Value> {
+ self.validate_world(world)?;
if candidates.len()>256 {return Err(CdpError::new("capture pseudo image candidates exceed bound"));}
if candidates.is_empty() {return Ok(json!([]));}
let tree = self.send("DOM.getDocument", json!({"depth":-1}))?;
diff --git a/crates/cli/src/asset_capture.rs b/crates/cli/src/asset_capture.rs
index a884d2add..26992f52c 100644
--- a/crates/cli/src/asset_capture.rs
+++ b/crates/cli/src/asset_capture.rs
@@ -17,15 +17,24 @@ use std::{
pub struct CdpAssetRenderer {
env: HashMap<String, String>,
+ raster_coverage: Option<Value>,
clock_ms: Option<f64>,
}
impl CdpAssetRenderer {
pub fn from_process_env() -> Self {
Self {
env: impeccable_common::process_env(),
+ raster_coverage: None,
clock_ms: None,
}
}
+ /// Also measure the share of the viewport images paint outside `exclude`
+ /// (`{boxes, paths}`, see `raster_coverage.js`) on the settled page, before
+ /// any intervention, and record it as `rasterCoverage` on every receipt.
+ pub fn measuring_raster_coverage(mut self, exclude: Value) -> Self {
+ self.raster_coverage = Some(exclude);
+ self
+ }
/// 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);
@@ -193,15 +202,28 @@ impl AssetRenderer for CdpAssetRenderer {
"(()=>{{globalThis[{key}]?.restore();delete globalThis[{key}];return true;}})()"
),
);
+ // Measured on the restored page and bound to the graded frame: the
+ // viewport must show the baseline pixels before and after, so a page
+ // that changes later cannot report an earlier, smaller coverage.
+ let coverage = match (&self.raster_coverage, &result) {
+ (Some(exclude), Ok(captures)) => Some(
+ coverage_on_baseline(&mut capture, &requests[0], exclude, captures)
+ .unwrap_or_else(|reason| json!({"unavailable": reason})),
+ ),
+ _ => None,
+ };
drop(capture);
page.close();
- result
+ result.map(|captures| (captures, coverage))
})();
browser.close();
- result.map(|captures| {
+ result.map(|(captures, coverage)| {
captures
.into_iter()
.map(|mut capture| {
+ if let Some(coverage) = &coverage {
+ capture.receipt["rasterCoverage"] = coverage.clone();
+ }
capture.receipt["browser"] = browser_version.clone();
capture.receipt["rasterization"] = json!("software");
capture.receipt["partialRaster"] = json!(false);
@@ -213,6 +235,41 @@ impl AssetRenderer for CdpAssetRenderer {
})
}
}
+fn coverage_on_baseline(
+ page: &mut CapturePage<'_, '_>,
+ r: &AssetCaptureRequest,
+ exclude: &Value,
+ captures: &[AssetCapture],
+) -> Result<Value, String> {
+ let baseline = captures
+ .iter()
+ .flat_map(|c| c.images.iter())
+ .find(|i| i.name == "baseline.png")
+ .ok_or("no settled baseline frame")?;
+ let baseline = png_io::decode_png(&baseline.png)
+ .map_err(|e| format!("baseline decode: {e:?}"))?
+ .image;
+ let (_, before) = screenshot(page, r)?;
+ page.check_budget()?;
+ let coverage = measure_raster_coverage(page.page, &page.world, exclude)?;
+ let (_, after) = screenshot(page, r)?;
+ if before.data != baseline.data || after.data != baseline.data {
+ return Err("the page no longer shows the captured frame".into());
+ }
+ Ok(coverage)
+}
+/// Run `raster_coverage.js` with `exclude` (`null` for none) on the page as it
+/// stands. A pseudo-element has no client rect, so the native layout boxes of
+/// every generated `::before`/`::after` that could paint a `url()` are read
+/// first and handed to the measurement, which places each one there.
+pub(crate) fn measure_raster_coverage(page: &mut Page<'_>, world: &IsolatedWorld, exclude: &Value) -> Result<Value, String> {
+ const CANDIDATES: &str = "[...document.querySelectorAll('*')].flatMap((el,index)=>['before','after'].filter(p=>{const s=getComputedStyle(el,'::'+p);return s.content!=='none'&&s.content!=='normal'&&s.display!=='none'&&[s.content,s.backgroundImage,s.borderImageSource,s.maskImage,s.webkitMaskImage,s.clipPath,s.filter].some(v=>typeof v==='string'&&v.includes('url('))}).map(pseudo=>({index,pseudo})))";
+ let candidates = page.evaluate_value_in_world(world, CANDIDATES).map_err(|e| e.message)?;
+ let candidates = candidates.as_array().ok_or("pseudo-element candidates unavailable")?;
+ let pseudos = page.native_pseudo_boxes(world, candidates).map_err(|e| e.message)?;
+ page.evaluate_value_in_world(world, &format!("({})({exclude},{pseudos})", include_str!("raster_coverage.js")))
+ .map_err(|e| e.message)
+}
struct CapturePage<'p, 'b> {
page: &'p mut Page<'b>,
world: IsolatedWorld,
diff --git a/crates/cli/src/capture_service.rs b/crates/cli/src/capture_service.rs
index 61334adf9..c8ed9e96a 100644
--- a/crates/cli/src/capture_service.rs
+++ b/crates/cli/src/capture_service.rs
@@ -539,14 +539,19 @@ fn parse_capture(
"native capture method does not match a spec with raster regions".into()
});
}
- if text_only {
- if !matches!(report["dependencyPolicy"].as_str(), Some("hero-review-manifest" | "static-inventory")) {
- return Err("invalid native capture dependency policy".into());
- }
- let served = report["servedToPage"].as_array().ok_or("missing native capture page inventory")?;
- if served.iter().any(|f| f["path"] == r.spec.as_str() || f["path"] == r.reference.as_str()) {
- return Err("native capture served a bound input to the page".into());
- }
+ if text_only
+ && !matches!(report["dependencyPolicy"].as_str(), Some("hero-review-manifest" | "static-inventory"))
+ {
+ return Err("invalid native capture dependency policy".into());
+ }
+ // Either kind: the page is never served the spec or the comp, by its list
+ // of served files or by the input manifest's own served flags.
+ let served = report["servedToPage"].as_array().ok_or("missing native capture page inventory")?;
+ let bound = |f: &Value| f["path"] == r.spec.as_str() || f["path"] == r.reference.as_str();
+ if served.iter().any(bound)
+ || report["manifest"]["files"].as_array().into_iter().flatten().any(|f| bound(f) && f["served"] != false)
+ {
+ return Err("native capture served a bound input to the page".into());
}
let expected = if stage == "hero" {
vec!["hero"]
@@ -568,11 +573,15 @@ fn parse_capture(
.decode(f["png"].as_str().ok_or("missing frame PNG")?)
.map_err(|e| e.to_string())?;
let receipts = f["regions"].as_array().ok_or("invalid native capture regions")?;
+ // Every frame proves images stayed under the share limit: anywhere
+ // for a text-only spec, outside the declared raster regions otherwise.
+ let share = report["frameProofs"][name]["rasterCoverage"]["share"].as_f64();
+ if !share.is_some_and(|s| (0. ..TEXT_ONLY_RASTER_SHARE_MAX).contains(&s)) {
+ return Err("invalid native capture regions".into());
+ }
if text_only {
- // No raster region, so nothing to measure: the frame's evidence is
- // its proof, which must show images stayed under the share limit.
- let share = report["frameProofs"][name]["rasterCoverage"]["share"].as_f64();
- if !receipts.is_empty() || !share.is_some_and(|s| (0. ..TEXT_ONLY_RASTER_SHARE_MAX).contains(&s)) {
+ // No raster region, so nothing to measure: the frame's evidence is its proof.
+ if !receipts.is_empty() {
return Err("invalid native capture regions".into());
}
} else {
@@ -759,12 +768,12 @@ mod parse_tests {
let canonical = std::fs::canonicalize(&dir).unwrap();
let mut report = json!({"stage":"hero","artifact":"index.html",
"captureService":{"id":"h-1","registeredRoot":canonical},
- "manifest":{"files":[{"path":SPEC,"sha256":capture_sha256(&spec)}]}});
+ "manifest":{"files":[{"path":SPEC,"sha256":capture_sha256(&spec),"served":false},{"path":"comp.png","sha256":"0","served":false}]},
+ "servedToPage":[{"path":"index.html"}],
+ "frameProofs":{"hero":{"rasterCoverage":{"share":0.01}},"desktop":{"rasterCoverage":{"share":0.01}},"mobile":{"rasterCoverage":{"share":0.01}}}});
if raster == 0 {
report["captureMethod"] = json!("assembled-page-viewport");
report["dependencyPolicy"] = json!("static-inventory");
- report["servedToPage"] = json!([{"path":"index.html"}]);
- report["frameProofs"] = json!({"hero":{"rasterCoverage":{"share":0.01}}});
}
(Root(dir), request, report)
}
@@ -819,6 +828,19 @@ mod parse_tests {
assert!(parse(&request, &report, frame(receipts(2))).is_ok());
let e = parse(&request, &report, frame(vec![])).unwrap_err();
assert_eq!(e, "invalid native capture regions");
+ // The page is never served the comp, and every frame proves images
+ // outside the raster regions stayed under the limit.
+ for (pointer, value) in [
+ ("/frameProofs/hero/rasterCoverage/share", json!(0.15)),
+ ("/frameProofs/hero", json!(null)),
+ ("/servedToPage", json!([{"path":"index.html"},{"path":"comp.png"}])),
+ ("/servedToPage", json!(null)),
+ ("/manifest/files/1/served", json!(true)),
+ ] {
+ let mut broken = report.clone();
+ *broken.pointer_mut(pointer).unwrap() = value;
+ assert!(parse(&request, &broken, frame(receipts(2))).is_err(), "{pointer}");
+ }
// Claiming the text-only method does not excuse a raster spec.
let mut claimed = report.clone();
claimed["captureMethod"] = json!("assembled-page-viewport");
diff --git a/crates/cli/src/capture_snapshot.rs b/crates/cli/src/capture_snapshot.rs
index 4a1815361..0867009f2 100644
--- a/crates/cli/src/capture_snapshot.rs
+++ b/crates/cli/src/capture_snapshot.rs
@@ -15,7 +15,7 @@ use std::{
net::{TcpListener, TcpStream},
path::{Component, Path, PathBuf},
sync::{
- Arc,
+ Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
thread::{self, JoinHandle},
@@ -41,7 +41,19 @@ pub struct HtmlSnapshot {
files: BTreeMap<String, Vec<u8>>,
manifest: Value,
digest: String,
+ /// Every well-formed path a page asked this snapshot's servers for, served
+ /// or not. Entry capture reads it to refuse a page that
+ /// asks for a bound input it is never served (the comp) or loads a copy.
+ requested: Mutex<RequestLog>,
}
+/// Distinct requested paths, bounded. A page that asks for more than the bound
+/// cannot hide a request past it: the log reports the overflow instead.
+#[derive(Default)]
+struct RequestLog {
+ paths: BTreeSet<String>,
+ overflowed: bool,
+}
+const MAX_LOGGED_REQUESTS: usize = 4096;
impl HtmlSnapshot {
pub fn freeze(selection: SnapshotSelection) -> Result<Self, String> {
let root = fs::canonicalize(&selection.root).map_err(|e| format!("snapshot root: {e}"))?;
@@ -93,6 +105,7 @@ impl HtmlSnapshot {
files,
manifest,
digest,
+ requested: Mutex::new(RequestLog::default()),
};
snapshot.verify_current()?;
Ok(snapshot)
@@ -255,6 +268,18 @@ impl HtmlSnapshot {
pub fn bytes(&self, name: &str) -> Option<&[u8]> {
self.files.get(name).map(Vec::as_slice)
}
+ /// Whether the page may be served this path (bound-only inputs are not).
+ pub fn is_served(&self, name: &str) -> bool {
+ self.served.contains(name)
+ }
+ /// The distinct paths pages asked for since the last call, emptying the log.
+ pub fn take_requested(&self) -> Result<Vec<String>, String> {
+ let log = std::mem::take(&mut *self.requested.lock().unwrap_or_else(|e| e.into_inner()));
+ if log.overflowed {
+ return Err(format!("the page requested more than {MAX_LOGGED_REQUESTS} distinct paths"));
+ }
+ Ok(log.paths.into_iter().collect())
+ }
pub fn verify_current(&self) -> Result<(), String> {
for (name, bytes) in &self.files {
if read_input(&self.root, name)? != *bytes {
@@ -265,27 +290,7 @@ impl HtmlSnapshot {
}
/// Strict origin-form routes. Decode percent-encoded UTF-8, but never separators.
pub fn serve_path(&self, target: &str) -> Option<String> {
- let raw = target.strip_prefix('/')?.split('?').next()?;
- let mut bytes = Vec::new();
- let input = raw.as_bytes();
- let mut i = 0;
- while i < input.len() {
- if input[i] == b'%' {
- let hex = std::str::from_utf8(input.get(i + 1..i + 3)?).ok()?;
- let byte = u8::from_str_radix(hex, 16).ok()?;
- if matches!(byte, b'/' | b'\\' | 0) {
- return None;
- }
- bytes.push(byte);
- i += 3;
- } else {
- bytes.push(input[i]);
- i += 1;
- }
- }
- let name = String::from_utf8(bytes).ok()?;
- valid_relative(&name).ok()?;
- self.served.contains(&name).then_some(name)
+ decode_target(target).filter(|name| self.served.contains(name))
}
pub fn serve(self: &Arc<Self>) -> Result<SnapshotServer, String> {
let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
@@ -323,6 +328,29 @@ impl HtmlSnapshot {
})
}
}
+fn decode_target(target: &str) -> Option<String> {
+ let raw = target.strip_prefix('/')?.split('?').next()?;
+ let mut bytes = Vec::new();
+ let input = raw.as_bytes();
+ let mut i = 0;
+ while i < input.len() {
+ if input[i] == b'%' {
+ let hex = std::str::from_utf8(input.get(i + 1..i + 3)?).ok()?;
+ let byte = u8::from_str_radix(hex, 16).ok()?;
+ if matches!(byte, b'/' | b'\\' | 0) {
+ return None;
+ }
+ bytes.push(byte);
+ i += 3;
+ } else {
+ bytes.push(input[i]);
+ i += 1;
+ }
+ }
+ let name = String::from_utf8(bytes).ok()?;
+ valid_relative(&name).ok()?;
+ Some(name)
+}
fn valid_relative(name: &str) -> Result<(), String> {
if name.is_empty()
|| name.contains(['\\', '\0', '?', '#', ':'])
@@ -488,11 +516,16 @@ fn respond(
&& protocol == Some("HTTP/1.1")
&& first.next().is_none()
&& hosts == [host];
- let route = if valid {
- target.and_then(|t| snapshot.serve_path(t))
- } else {
- None
- };
+ let asked = if valid { target.and_then(decode_target) } else { None };
+ if let Some(name) = &asked {
+ let mut log = snapshot.requested.lock().unwrap_or_else(|e| e.into_inner());
+ if log.paths.len() < MAX_LOGGED_REQUESTS || log.paths.contains(name) {
+ log.paths.insert(name.clone());
+ } else {
+ log.overflowed = true;
+ }
+ }
+ let route = asked.filter(|name| snapshot.served.contains(name));
let (status, kind, body) = match route.as_deref() {
Some(name) => ("200 OK", mime(name).unwrap(), snapshot.bytes(name).unwrap()),
None => ("404 Not Found", "text/plain", b"Not found".as_slice()),
diff --git a/crates/cli/src/component_capture.rs b/crates/cli/src/component_capture.rs
index cba9135d8..6d4a1c92c 100644
--- a/crates/cli/src/component_capture.rs
+++ b/crates/cli/src/component_capture.rs
@@ -96,7 +96,7 @@ pub(crate) fn render_page(
let dom=page.evaluate_value_in_world(&world,&inspect).map_err(|e|e.message)?;
// Only the entry capture asks; review proofs keep their shape.
let raster_coverage = if measure_raster {
- Some(page.evaluate_value_in_world(&world, &format!("({})()", include_str!("raster_coverage.js"))).map_err(|e| e.message)?)
+ Some(crate::asset_capture::measure_raster_coverage(&mut page, &world, &Value::Null)?)
} else { None };
let urls = page.observed_response_urls().map_err(|e| e.message)?;
let evidence = page.response_evidence(&urls).map_err(|e| e.message)?;
diff --git a/crates/cli/src/entry_capture.rs b/crates/cli/src/entry_capture.rs
index aeae7de3f..5574e5d4d 100644
--- a/crates/cli/src/entry_capture.rs
+++ b/crates/cli/src/entry_capture.rs
@@ -22,7 +22,8 @@ pub struct CdpEntryRenderer;
/// raster region. Logos, avatars and icons sit well under it (a 200x60 logo is
/// about 1% of a 1440x900 viewport; a row of twelve 40px avatars under 2%); a
/// chart, photo or copied comp that carries real weight in the comparison sits
-/// well over it.
+/// well over it. A spec with raster regions gets the same limit for what images
+/// paint outside those regions.
pub const TEXT_ONLY_RASTER_SHARE_MAX: f64 = 0.15;
/// The frozen inputs a capture was drawn from. A text-only capture also binds
/// the hero review manifest whose dependency list chose what the page may load.
@@ -67,8 +68,8 @@ impl CaptureClock {
}
}
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.
+ /// `forbidden` holds approved images (a reviewed screenshot) that the page
+ /// must not load or embed; the bound comp is always forbidden.
pub fn capture_forbidding(
&self,
request: &EntryRequest,
@@ -87,11 +88,18 @@ impl CdpEntryRenderer {
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)?;
+ // Spec and comp are bound (hashed and re-verified) but never served: a
+ // page graded against the comp must not be able to show it.
+ let inventory = static_inventory(&request.root)?;
+ let served: Vec<String> = inventory
+ .iter()
+ .filter(|p| **p != request.spec && **p != request.reference)
+ .cloned()
+ .collect();
let snapshot = Arc::new(HtmlSnapshot::freeze(SnapshotSelection {
root: request.root.clone(),
entry: request.artifact.clone(),
- served: served.clone(),
+ served,
bound: vec![request.spec.clone(), request.reference.clone()],
})?);
let spec: Value =
@@ -130,10 +138,31 @@ impl CdpEntryRenderer {
],
};
if ids.is_empty() {
- return capture_text_only(request, snapshot, &served, &frames, forbidden, clock);
+ return capture_text_only(request, snapshot, &inventory, &frames, forbidden, clock);
+ }
+ let comp = snapshot.bytes(&request.reference).ok_or("reference is not bound to snapshot")?;
+ let mut forbidden: Vec<&[u8]> = forbidden.to_vec();
+ forbidden.push(comp);
+ // Each raster region's plate path and its box in comp pixels.
+ let mut plates = Vec::new();
+ let mut boxes = Vec::new();
+ for region in spec["regions"].as_array().into_iter().flatten().filter(|r| r["medium"] == "raster") {
+ let id = region["id"].as_str().unwrap_or("raster");
+ let plate = region["plate"].as_str().ok_or_else(|| format!("raster region {id} has no plate"))?;
+ if plate == request.reference || plate == request.spec {
+ return Err(format!("raster region {id} names the approved comp ({plate}) as its plate. A plate is the region's own artwork, never the comp."));
+ }
+ if let Some(reason) = snapshot.bytes(plate).and_then(|bytes| forbidden_content(plate, bytes, &forbidden)) {
+ return Err(format!("raster region {id}'s plate {plate} {reason}. A plate is the region's own artwork, never the comp."));
+ }
+ plates.push(plate.to_string());
+ boxes.push(region["px"].clone());
}
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.","clock":clock.json()}),
+ 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.",
+ "integrityScope":"the comp and approved screenshots are never served to the page; images outside the declared raster regions cover under 15% of each frame",
+ "servedToPage":snapshot.manifest()["files"].as_array().into_iter().flatten().filter(|f| f["served"] == true).map(|f| json!({"path":f["path"],"sha256":f["sha256"]})).collect::<Vec<_>>(),
+ "frameProofs":{},"clock":clock.json()}),
frames: vec![],
};
for (name, viewport) in frames {
@@ -144,13 +173,37 @@ impl CdpEntryRenderer {
} else {
&ids[..]
};
- let regions = snapshot.capture_regions_at_viewport(
- &mut CdpAssetRenderer::from_process_env().pinned_at(clock.epoch_ms),
+ // Images outside the declared raster regions contradict the spec as
+ // they would on a page that declares none; that is what catches a
+ // re-encoded comp the byte checks cannot see. Hero and desktop keep
+ // the comp's layout, so the region boxes (scaled to the frame width)
+ // are excluded. Mobile reflows away from them, so there the declared
+ // plates are excluded wherever they land.
+ let exclude = if name == "mobile" {
+ json!({"paths": plates})
+ } else {
+ let scale = viewport.map(|v| v[0] as f64 / width).unwrap_or(1.);
+ let scaled: Vec<Value> = boxes
+ .iter()
+ .map(|b| {
+ let v = |k: &str| b[k].as_f64().unwrap_or(0.) * scale;
+ json!({"x":v("x"),"y":v("y"),"w":v("w"),"h":v("h")})
+ })
+ .collect();
+ json!({"boxes": scaled})
+ };
+ snapshot.take_requested()?;
+ let captured = snapshot.capture_regions_at_viewport(
+ &mut CdpAssetRenderer::from_process_env().pinned_at(clock.epoch_ms).measuring_raster_coverage(exclude),
&request.spec,
selected,
true,
viewport,
- )?;
+ );
+ // Judge what the page asked for before anything else, so a capture
+ // that failed because the comp was withheld says why.
+ check_requests(name, &snapshot, request, &forbidden)?;
+ let mut regions = captured?;
if regions.iter().any(|r| {
r.receipt["stableCapture"] != true || r.receipt["batchStabilityVerified"] != true
}) {
@@ -177,6 +230,23 @@ impl CdpEntryRenderer {
"{name} native capture did not retain a stable bound document: {details}"
));
}
+ let coverage = regions
+ .first()
+ .map(|r| r.receipt["rasterCoverage"].clone())
+ .ok_or("raster coverage was not measured")?;
+ if !coverage["share"].is_number() {
+ return Err(format!("{name} raster coverage was not measured: {}", coverage["unavailable"].as_str().unwrap_or("no measurement")));
+ }
+ for region in &mut regions {
+ if let Some(receipt) = region.receipt.as_object_mut() {
+ receipt.remove("rasterCoverage");
+ }
+ }
+ let share = coverage["share"].as_f64().unwrap_or(1.);
+ if share >= TEXT_ONLY_RASTER_SHARE_MAX {
+ return Err(format!("{name} raster capture refused: images outside the declared raster regions cover {}% of the viewport (limit {}%): {}. The spec declares every raster in the first viewport as a raster region: declare this image as one (comp-spec --regions), or remove it and draw that area in code.", (share * 100.).round(), (TEXT_ONLY_RASTER_SHARE_MAX * 100.) as u32, largest_images(&coverage)));
+ }
+ evidence.report["frameProofs"][name] = json!({"rasterCoverage": coverage});
let png = regions[0]
.images
.iter()
@@ -305,10 +375,7 @@ fn capture_text_only(
let coverage = &proof["rasterCoverage"];
let share = coverage["share"].as_f64().ok_or("raster coverage was not measured")?;
if share >= TEXT_ONLY_RASTER_SHARE_MAX {
- let largest = coverage["largest"].as_array().into_iter().flatten().take(3)
- .map(|i| format!("{} ({}% of the viewport)", i["what"].as_str().unwrap_or("image"), (i["share"].as_f64().unwrap_or(0.) * 100.).round()))
- .collect::<Vec<_>>().join(", ");
- return Err(format!("{name} text-only capture refused: images cover {}% of the viewport (limit {}%): {largest}. The spec declares no raster region, so a large image contradicts it: declare the image as a raster region in the spec (comp-spec --regions), or remove it and draw that area in code.", (share * 100.).round(), (TEXT_ONLY_RASTER_SHARE_MAX * 100.) as u32));
+ return Err(format!("{name} text-only capture refused: images cover {}% of the viewport (limit {}%): {}. The spec declares no raster region, so a large image contradicts it: declare the image as a raster region in the spec (comp-spec --regions), or remove it and draw that area in code.", (share * 100.).round(), (TEXT_ONLY_RASTER_SHARE_MAX * 100.) as u32, largest_images(coverage)));
}
evidence.report["frameProofs"][name] = proof;
evidence.frames.push(FrameEvidence {
@@ -360,6 +427,43 @@ fn declared_dependencies(
Ok((Some(deps), Some((path, bytes))))
}
+/// The largest images a coverage measurement names, for a refusal.
+fn largest_images(coverage: &Value) -> String {
+ coverage["largest"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .take(3)
+ .map(|i| format!("{} ({}% of the viewport)", i["what"].as_str().unwrap_or("image"), (i["share"].as_f64().unwrap_or(0.) * 100.).round()))
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+/// Refuse a raster frame whose page asked for a bound input it is never served
+/// (the spec or the comp), or loaded a file that is, or inlines, a forbidden
+/// image. Only files the page requested are judged, so an unused backup of the
+/// comp elsewhere in the project does not block an honest page.
+fn check_requests(
+ name: &str,
+ snapshot: &HtmlSnapshot,
+ request: &EntryRequest,
+ forbidden: &[&[u8]],
+) -> Result<(), String> {
+ for path in snapshot.take_requested().map_err(|e| format!("{name} raster capture refused: {e}"))? {
+ if path == request.reference || path == request.spec {
+ return Err(format!("{name} raster capture refused: the page loads the approved comp ({path}). Show the declared plates and draw the rest of the first viewport in code."));
+ }
+ if !snapshot.is_served(&path) {
+ continue;
+ }
+ let bytes = snapshot.bytes(&path).ok_or("requested file is not in the frozen inputs")?;
+ if let Some(reason) = forbidden_content(&path, bytes, forbidden) {
+ return Err(format!("{name} raster capture refused: the page loads {path}, which {reason}. Show the declared plates and draw the rest of the first viewport in code."));
+ }
+ }
+ Ok(())
+}
+
/// Whether a served file is, or inlines as base64, one of the forbidden images.
fn forbidden_content(name: &str, bytes: &[u8], forbidden: &[&[u8]]) -> Option<&'static str> {
use base64::Engine;
diff --git a/crates/cli/src/raster_coverage.js b/crates/cli/src/raster_coverage.js
index c743dc68b..7a473385f 100644
--- a/crates/cli/src/raster_coverage.js
+++ b/crates/cli/src/raster_coverage.js
@@ -17,12 +17,29 @@
// contain: paint on its containing-block chain), and an element under an
// ancestor with opacity 0 paints nothing. The union is taken on a 4px grid so
// tiled or overlapping pieces add up once.
-() => {
+//
+// `exclude` (optional) is what a spec with raster regions declares: `boxes`
+// are the regions' viewport rectangles, whose grid cells (by cell centre) are
+// left out of the count, and `paths` are the declared plates (project paths),
+// whose images are not counted at all. A piece reached through an SVG
+// definition is never treated as a declared plate. With neither, every image
+// counts. `pseudos` are the native layout boxes of the generated
+// ::before/::after boxes (`native_pseudo_boxes` over CDP), where each counts.
+(exclude, pseudos) => {
const W = innerWidth, H = innerHeight, cell = 4;
const cols = Math.ceil(W / cell), rows = Math.ceil(H / cell);
const grid = new Uint8Array(cols * rows);
const items = [];
const page = location.href.split('#')[0];
+ const boxes = (exclude && exclude.boxes) || [];
+ // Native layout boxes of generated ::before/::after, by host index in
+ // querySelectorAll order and pseudo name (`{index, pseudo, box}`).
+ const native = new Map((pseudos || []).filter(q => q.box).map(q => [q.index + q.pseudo, q.box]));
+ // A resource is named by origin and path: the snapshot server ignores the
+ // query string, and a fragment never reaches it, so `art.png?v=2` is the plate.
+ const resource = u => u.origin + u.pathname;
+ const plates = new Set(((exclude && exclude.paths) || []).map(p => resource(new URL(p, location.origin + '/'))));
+ const outside = (x, y) => !boxes.some(b => x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h);
const refs = v => typeof v === 'string' ? [...v.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)].map(m => m[2]) : [];
// The id a same-document fragment reference names, or null for any other
// reference. Chromium may report url(#id) resolved against the page URL.
@@ -75,6 +92,17 @@
const id = fragment(ref);
return id == null || rasterDef(id, seen);
});
+ // The images a value draws from, for matching against declared plates: each
+ // reference that leaves the document as its resource, an unparsable one or a
+ // fragment naming a raster definition as null (never a declared plate), and a
+ // fragment naming a vector definition not at all.
+ const srcsOf = v => refs(v).flatMap(ref => {
+ const id = fragment(ref);
+ if (id != null) return rasterDef(id) ? [null] : [];
+ try { return [resource(new URL(ref, page))]; } catch { return [null]; }
+ });
+ // A piece drawn only from declared plates is the spec's own raster.
+ const declared = srcs => plates.size > 0 && srcs.length > 0 && srcs.every(u => u && plates.has(u));
const px = v => /^-?[\d.]+px$/.test(v) ? parseFloat(v) : null;
const intersect = (a, b) => ({ left: Math.max(a.left, b.left), top: Math.max(a.top, b.top), right: Math.min(a.right, b.right), bottom: Math.min(a.bottom, b.bottom) });
const createsFixedBlock = s => s.transform !== 'none' || s.perspective !== 'none' || s.filter !== 'none'
@@ -103,12 +131,22 @@
for (let a = el; a; a = a.parentElement) if (parseFloat(getComputedStyle(a).opacity) === 0) return true;
return false;
};
- const mark = (from, mode, r, what) => {
+ const mark = (from, mode, r, what, srcs) => {
+ if (srcs && declared(srcs)) return;
r = intersect(clipped(from, mode, r), { left: 0, top: 0, right: W, bottom: H });
if (r.right <= r.left || r.bottom <= r.top) return;
- items.push({ what, box: { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.right - r.left), h: Math.round(r.bottom - r.top) }, share: (r.right - r.left) * (r.bottom - r.top) / (W * H) });
+ let own = 0;
for (let y = Math.floor(r.top / cell); y < Math.ceil(r.bottom / cell); y++)
- for (let x = Math.floor(r.left / cell); x < Math.ceil(r.right / cell); x++) grid[y * cols + x] = 1;
+ for (let x = Math.floor(r.left / cell); x < Math.ceil(r.right / cell); x++) {
+ if (!outside((x + 0.5) * cell, (y + 0.5) * cell)) continue;
+ grid[y * cols + x] = 1;
+ own++;
+ }
+ if (!own) return;
+ // Without exclusion boxes a piece's share is its painted area; with them,
+ // the share of the viewport it paints outside the declared regions.
+ const share = boxes.length ? own / (cols * rows) : (r.right - r.left) * (r.bottom - r.top) / (W * H);
+ items.push({ what, box: { x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.right - r.left), h: Math.round(r.bottom - r.top) }, share });
};
const name = el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.classList.length ? '.' + [...el.classList].slice(0, 2).join('.') : '');
const box = r => ({ left: r.left, top: r.top, right: r.right, bottom: r.bottom });
@@ -176,17 +214,18 @@
}
return (px(s.strokeWidth) ?? 1) * k / 2;
};
- for (const el of document.querySelectorAll('*')) {
+ for (const [index, el] of [...document.querySelectorAll('*')].entries()) {
const s = getComputedStyle(el);
if (s.display === 'none' || s.visibility !== 'visible' || transparent(el)) continue;
const r = el.getBoundingClientRect();
const tag = el.tagName.toLowerCase();
- const at = (rect, what) => mark(el.parentElement, s.position, rect, what);
- if (tag === 'img' || tag === 'video' || (tag === 'input' && el.type === 'image')) at(picture(el, s, r), name(el));
- if (tag === 'image') at(box(r), name(el));
- if (url(s.backgroundImage)) at(background(s, r), name(el) + ' background');
- if (url(s.borderImageSource) || url(s.maskImage) || url(s.webkitMaskImage)) at(box(r), name(el) + ' border/mask image');
- if (url(s.listStyleImage) && s.display === 'list-item') at(box(r), name(el) + ' list marker');
+ const at = (rect, what, srcs) => mark(el.parentElement, s.position, rect, what, srcs);
+ const src = v => { try { return v ? [resource(new URL(v, page))] : []; } catch { return [null]; } };
+ if (tag === 'img' || tag === 'video' || (tag === 'input' && el.type === 'image')) at(picture(el, s, r), name(el), src(el.currentSrc || el.src));
+ if (tag === 'image') at(box(r), name(el), src(el.href && el.href.baseVal));
+ if (url(s.backgroundImage)) at(background(s, r), name(el) + ' background', srcsOf(s.backgroundImage));
+ if (url(s.borderImageSource) || url(s.maskImage) || url(s.webkitMaskImage)) at(box(r), name(el) + ' border/mask image', [s.borderImageSource, s.maskImage, s.webkitMaskImage].flatMap(srcsOf));
+ if (url(s.listStyleImage) && s.display === 'list-item') at(box(r), name(el) + ' list marker', srcsOf(s.listStyleImage));
// SVG paint servers, clips, filters, markers and use references reach a
// definition whose own <image> has no box, so this element's painted area
// counts when that definition holds raster content. A vector definition
@@ -213,22 +252,23 @@
const own = url(ps.content) || url(ps.backgroundImage) || url(ps.borderImageSource) || url(ps.maskImage) || url(ps.webkitMaskImage) || url(ps.clipPath);
const filtered = url(ps.filter);
if (!own && !filtered) continue;
- // A pseudo-element has no client rect. With a used pixel size, count that
- // size (at the viewport origin when fixed, else at the host's corner);
- // without one, count the host box. Its clipping chain starts at the host.
- // A raster filter paints its filter region around that box instead.
+ // A pseudo-element has no client rect, so it counts at its native layout
+ // box (the caller reads it over CDP; offsets, size and transforms all
+ // applied). One with no layout box of its own (display: contents lays
+ // its generated content out in the host's flow) counts the host box.
+ // Its clipping chain starts at the host. A raster filter paints its
+ // filter region around that box instead.
const mode = ps.position === 'fixed' || ps.position === 'absolute' ? ps.position : 'static';
- const w = px(ps.width), h = px(ps.height);
- let pr = box(r);
- if (w != null && h != null) {
- const left = mode === 'fixed' ? (px(ps.left) ?? 0) : r.left, top = mode === 'fixed' ? (px(ps.top) ?? 0) : r.top;
- pr = { left, top, right: left + w, bottom: top + h };
- }
- if (own) mark(el, mode, pr, name(el) + p);
+ const srcs = [ps.content, ps.backgroundImage, ps.borderImageSource, ps.maskImage, ps.webkitMaskImage, ps.clipPath].flatMap(srcsOf);
+ const laid = native.get(index + p);
+ const pr = laid ? { left: laid.x, top: laid.y, right: laid.x + laid.w, bottom: laid.y + laid.h } : box(r);
+ if (own) mark(el, mode, pr, name(el) + p, srcs);
if (filtered) mark(el, mode, region(ps.filter, pr), name(el) + p + ' filter');
}
}
const covered = grid.reduce((n, v) => n + v, 0);
items.sort((a, b) => b.share - a.share);
- return { share: covered / (cols * rows), cell, largest: items.slice(0, 5), measure: 'painted-box-union-v3' };
+ const result = { share: covered / (cols * rows), cell, largest: items.slice(0, 5), measure: 'painted-box-union-v3' };
+ if (exclude) result.excluded = { boxes, paths: exclude.paths || [] };
+ return result;
}
diff --git a/crates/cli/tests/entry_capture.rs b/crates/cli/tests/entry_capture.rs
index ee8838fac..eefb0dbb0 100644
--- a/crates/cli/tests/entry_capture.rs
+++ b/crates/cli/tests/entry_capture.rs
@@ -11,9 +11,18 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
static NEXT: AtomicUsize = AtomicUsize::new(0);
-struct Fixture(PathBuf);
+const ART: &str = "<img src='assets/art.png'>";
+const STYLE: &str = "<!doctype html><style>body{margin:0;background:white}img{position:absolute;left:10vw;top:10vw;width:40vw;height:40vw}</style>";
+struct Fixture(PathBuf, &'static str);
impl Fixture {
fn new() -> Self {
+ Self::with_comp(".impeccable/comp.png")
+ }
+ /// The comp at a project path the static inventory would otherwise serve.
+ fn visible() -> Self {
+ Self::with_comp("comp.png")
+ }
+ fn with_comp(comp_path: &'static str) -> Self {
let p = std::env::temp_dir().join(format!(
"native-entry-{}-{}-{}",
std::process::id(),
@@ -26,26 +35,41 @@ impl Fixture {
fs::create_dir_all(p.join("assets")).unwrap();
fs::create_dir_all(p.join(".impeccable")).unwrap();
fs::create_dir_all(p.join("node_modules")).unwrap();
- fs::write(p.join("index.html"),"<!doctype html><style>body{margin:0;background:white}img{position:absolute;left:10vw;top:10vw;width:40vw;height:40vw}</style><img src='assets/art.png'>").unwrap();
+ fs::write(p.join("index.html"), format!("{STYLE}{ART}")).unwrap();
let png =
png_io::encode_png(&raster::create_image(32, 32, [231, 60, 30, 255]), &[]).unwrap();
fs::write(p.join("assets/art.png"), &png).unwrap();
- fs::write(p.join(".impeccable/comp.png"), png).unwrap();
- fs::write(p.join(".impeccable/spec.json"),br#"{"comp":".impeccable/comp.png","compSize":{"width":200,"height":200},"regions":[{"id":"art","medium":"raster","kind":"plate","plate":"assets/art.png","px":{"x":20,"y":20,"w":80,"h":80}}]}"#).unwrap();
+ // The comp: white with the artwork where its region sits.
+ let mut comp = raster::create_image(200, 200, [255, 255, 255, 255]);
+ for y in 20..100 {
+ for x in 20..100 {
+ comp.data[(y * 200 + x) * 4..(y * 200 + x) * 4 + 4].copy_from_slice(&[231, 60, 30, 255]);
+ }
+ }
+ fs::write(p.join(comp_path), png_io::encode_png(&comp, &[]).unwrap()).unwrap();
+ let spec = format!(r#"{{"comp":"{comp_path}","compSize":{{"width":200,"height":200}},"regions":[{{"id":"art","medium":"raster","kind":"plate","plate":"assets/art.png","px":{{"x":20,"y":20,"w":80,"h":80}}}}]}}"#);
+ fs::write(p.join(".impeccable/spec.json"), spec).unwrap();
fs::write(p.join(".env"), "private").unwrap();
fs::write(p.join("node_modules/secret.js"), "private").unwrap();
fs::write(p.join("source.ts"), "not a browser script").unwrap();
- Self(p)
+ Self(p, comp_path)
}
fn request(&self, stage: EntryStage) -> EntryRequest {
EntryRequest {
root: self.0.clone(),
artifact: "index.html".into(),
spec: ".impeccable/spec.json".into(),
- reference: ".impeccable/comp.png".into(),
+ reference: self.1.into(),
stage,
}
}
+ fn comp(&self) -> Vec<u8> {
+ fs::read(self.0.join(self.1)).unwrap()
+ }
+ /// The honest page plus `extra` markup.
+ fn page(&self, extra: &str) {
+ fs::write(self.0.join("index.html"), format!("{STYLE}{ART}{extra}")).unwrap();
+ }
}
impl Drop for Fixture {
fn drop(&mut self) {
@@ -99,6 +123,198 @@ fn entry_renderer_returns_fresh_hero_and_responsive_pixels_with_live_input_guard
}
}
+fn browser_available() -> bool {
+ if impeccable_browser::discovery::find_browser(&std::env::vars().collect()).is_err() {
+ eprintln!("skip: browser unavailable");
+ return false;
+ }
+ true
+}
+
+fn refusal(renderer: &dyn EntryRenderer, f: &Fixture, stage: EntryStage) -> String {
+ match renderer.capture_entry(&f.request(stage)) {
+ Ok(_) => panic!("capture should be refused"),
+ // Normalize separators so a Windows path in a message still matches.
+ Err(e) => e.replace('\\', "/"),
+ }
+}
+
+/// The issue #893 cheat: a raster page paints the comp behind its plates, so
+/// the gate would grade the reference against itself. The comp is never served.
+#[test]
+fn raster_page_that_requests_the_comp_is_refused() {
+ if !browser_available() {
+ return;
+ }
+ for f in [Fixture::visible(), Fixture::new()] {
+ let comp = f.1;
+ f.page(&format!("<img src=\"{comp}\" style=\"left:0;top:0;width:100vw;height:100vh;opacity:.5\">"));
+ for stage in [EntryStage::Hero, EntryStage::Responsive] {
+ let e = refusal(&CdpEntryRenderer, &f, stage);
+ assert!(e.contains(&format!("loads the approved comp ({comp})")), "{e}");
+ }
+ // A stylesheet background asks for it the same way.
+ f.page(&format!("<div style=\"position:absolute;inset:0;z-index:-1;background:url('{comp}')\"></div>"));
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("loads the approved comp"), "{e}");
+ }
+}
+
+#[test]
+fn raster_page_that_loads_a_copy_of_the_comp_is_refused() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::visible();
+ let comp = f.comp();
+ // A byte copy under another name, as an image or a CSS background.
+ fs::write(f.0.join("assets/backdrop.png"), &comp).unwrap();
+ f.page("<img src=\"assets/backdrop.png\" style=\"left:0;top:0;width:100vw;height:100vh;z-index:-1\">");
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("assets/backdrop.png") && e.contains("copy of the approved reference"), "{e}");
+ f.page("<div style=\"position:absolute;inset:0;z-index:-1;background:url(assets/backdrop.png)\"></div>");
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("assets/backdrop.png") && e.contains("copy of the approved reference"), "{e}");
+ fs::remove_file(f.0.join("assets/backdrop.png")).unwrap();
+ // A data URI of it in a stylesheet, wrapped across lines.
+ use base64::Engine;
+ let encoded = base64::engine::general_purpose::STANDARD.encode(&comp);
+ let wrapped = encoded.as_bytes().chunks(76).map(|c| std::str::from_utf8(c).unwrap()).collect::<Vec<_>>().join("\n ");
+ fs::write(f.0.join("assets/site.css"), format!(".backdrop{{position:absolute;inset:0;z-index:-1;background:url(\"data:image/png;base64,\n {wrapped}\")}}")).unwrap();
+ f.page("<link rel=stylesheet href=\"assets/site.css\"><div class=backdrop></div>");
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("assets/site.css") && e.contains("data URI"), "{e}");
+ fs::remove_file(f.0.join("assets/site.css")).unwrap();
+ // Re-encoded, the bytes differ; painted outside the declared region it
+ // still contradicts the spec.
+ let image = png_io::decode_png(&comp).unwrap().image;
+ let reencoded = png_io::encode_png(&image, &[("Comment".into(), "re-encoded".into())]).unwrap();
+ assert_ne!(reencoded, comp);
+ fs::write(f.0.join("assets/backdrop.png"), reencoded).unwrap();
+ f.page("<img src=\"assets/backdrop.png\" style=\"left:0;top:0;width:100vw;height:100vh;z-index:-1\">");
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("images outside the declared raster regions cover") && e.contains("comp-spec --regions"), "{e}");
+}
+
+#[test]
+fn a_plate_that_is_the_comp_is_refused_before_capture() {
+ let f = Fixture::visible();
+ fs::write(f.0.join("assets/art.png"), f.comp()).unwrap();
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("assets/art.png") && e.contains("never the comp"), "{e}");
+ let spec = fs::read_to_string(f.0.join(".impeccable/spec.json")).unwrap().replace("assets/art.png", "comp.png");
+ fs::write(f.0.join(".impeccable/spec.json"), spec).unwrap();
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("names the approved comp"), "{e}");
+}
+
+#[test]
+fn honest_raster_page_with_the_comp_in_the_project_still_passes() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::visible();
+ // An unused backup of the comp and a small logo do not block it.
+ fs::create_dir_all(f.0.join("backup")).unwrap();
+ fs::write(f.0.join("backup/comp-old.png"), f.comp()).unwrap();
+ let logo = png_io::encode_png(&raster::create_image(8, 8, [20, 20, 20, 255]), &[]).unwrap();
+ fs::write(f.0.join("assets/logo.png"), logo).unwrap();
+ f.page("<img src=\"assets/logo.png\" style=\"left:auto;right:4px;top:4px;width:8px;height:8px\">");
+ for stage in [EntryStage::Hero, EntryStage::Responsive] {
+ let captured = CdpEntryRenderer.capture_entry(&f.request(stage)).unwrap();
+ let report = &captured.evidence().report;
+ let served: Vec<_> = report["servedToPage"].as_array().unwrap().iter().filter_map(|f| f["path"].as_str()).collect();
+ assert!(served.contains(&"assets/art.png") && !served.contains(&"comp.png"), "{served:?}");
+ let comp = report["manifest"]["files"].as_array().unwrap().iter().find(|f| f["path"] == "comp.png").unwrap();
+ assert_eq!(comp["served"], false);
+ for frame in &captured.evidence().frames {
+ let share = report["frameProofs"][&frame.name]["rasterCoverage"]["share"].as_f64().unwrap();
+ assert!(share < 0.05, "{}: {share}", frame.name);
+ assert!(frame.regions.iter().all(|r| r.receipt["stableCapture"] == true && r.receipt.get("rasterCoverage").is_none()));
+ }
+ captured.verify_current().unwrap();
+ // The comp is bound though never served: changing it invalidates the capture.
+ let before = f.comp();
+ fs::write(f.0.join("comp.png"), b"changed").unwrap();
+ assert!(captured.verify_current().is_err());
+ fs::write(f.0.join("comp.png"), before).unwrap();
+ }
+}
+
+/// A `::before` counts where it paints, not at its host's corner: a plate placed
+/// by offsets (or a transform) inside its declared region passes, and an
+/// undeclared image pushed outside the region from a host inside it is refused.
+#[test]
+fn pseudo_element_images_count_at_their_painted_box() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::visible();
+ // The hero frame is 200x200 with the art region at 20..100 on both axes.
+ let host = "<div class=h style='position:absolute;left:20px;top:120px;width:80px;height:60px'></div>";
+ for place in ["left:0;top:-100px", "left:0;top:0;transform:translateY(-100px)"] {
+ f.page(&format!("{host}<style>.h::before{{content:'';position:absolute;{place};width:80px;height:80px;background:url(assets/art.png) 0 0/100% 100%}}</style>"));
+ let captured = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap();
+ let share = captured.evidence().report["frameProofs"]["hero"]["rasterCoverage"]["share"].as_f64().unwrap();
+ assert!(share < 0.01, "{place}: {share}");
+ }
+ let other = png_io::encode_png(&raster::create_image(32, 32, [20, 90, 200, 255]), &[]).unwrap();
+ fs::write(f.0.join("assets/other.png"), other).unwrap();
+ f.page("<div class=h style='position:absolute;left:20px;top:20px;width:80px;height:80px'></div><style>.h::before{content:'';position:absolute;left:-20px;top:100px;width:100px;height:80px;background:url(assets/other.png) 0 0/100% 100%}</style>");
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Hero);
+ assert!(e.contains("outside the declared raster regions cover 20%") && e.contains("div.h::before"), "{e}");
+}
+
+/// Mobile reflows away from the comp, so a declared plate counts nowhere there,
+/// whatever its query string and whether it paints as an image or a pseudo-element.
+#[test]
+fn mobile_excludes_declared_plates_however_they_are_referenced() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::visible();
+ let big = "<style>@media (max-width:500px){img,.art::before{width:80vw;height:80vw}}</style>";
+ for page in [
+ format!("{STYLE}{big}<img src='assets/art.png?v=2'>"),
+ format!("{STYLE}{big}<div class=art></div><style>.art::before{{content:'';position:absolute;left:10vw;top:10vw;width:40vw;height:40vw;background:url(assets/art.png?v=2) 0 0/100% 100%}}</style>"),
+ ] {
+ fs::write(f.0.join("index.html"), &page).unwrap();
+ let captured = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Responsive)).unwrap();
+ let share = captured.evidence().report["frameProofs"]["mobile"]["rasterCoverage"]["share"].as_f64().unwrap();
+ assert!(share < 0.01, "{page}: {share}");
+ }
+ // An undeclared image of the same size still counts on mobile.
+ let other = png_io::encode_png(&raster::create_image(32, 32, [20, 90, 200, 255]), &[]).unwrap();
+ fs::write(f.0.join("assets/other.png"), other).unwrap();
+ f.page(&format!("{big}<style>.m{{display:none}}@media (max-width:500px){{.m{{display:block}}}}</style><img class=m src='assets/other.png' style='left:0;top:60vw;width:80vw;height:80vw'>"));
+ let e = refusal(&CdpEntryRenderer, &f, EntryStage::Responsive);
+ assert!(e.contains("mobile raster capture refused") && e.contains("outside the declared raster regions"), "{e}");
+}
+
+#[test]
+fn host_capture_service_refuses_a_raster_page_that_shows_the_comp() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::visible();
+ let service = capture_service::CaptureService::start(&f.0, None);
+ let remote = service.renderer();
+ // Honest: crosses the transport with its coverage proofs.
+ for stage in [EntryStage::Hero, EntryStage::Responsive] {
+ let captured = remote.capture_entry(&f.request(stage)).unwrap();
+ assert!(captured.evidence().report["servedToPage"].as_array().unwrap().iter().all(|s| s["path"] != "comp.png"));
+ captured.verify_current().unwrap();
+ }
+ // Showing the comp by path or by copy is refused by the service.
+ f.page("<img src=\"comp.png\" style=\"left:0;top:0;width:100vw;height:100vh;opacity:.5\">");
+ let e = refusal(&remote, &f, EntryStage::Hero);
+ assert!(e.contains("loads the approved comp (comp.png)"), "{e}");
+ fs::write(f.0.join("assets/backdrop.png"), f.comp()).unwrap();
+ f.page("<img src=\"assets/backdrop.png\" style=\"left:0;top:0;width:100vw;height:100vh;z-index:-1\">");
+ let e = refusal(&remote, &f, EntryStage::Responsive);
+ assert!(e.contains("assets/backdrop.png") && e.contains("copy of the approved reference"), "{e}");
+}
+
#[test]
fn host_capture_service_keeps_one_receipt_per_raster_region() {
if impeccable_browser::discovery::find_browser(&std::env::vars().collect()).is_err() {
diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rs
index a8782fa22..a303c4e2c 100644
--- a/crates/comp-verbs/src/build_phase.rs
+++ b/crates/comp-verbs/src/build_phase.rs
@@ -1494,7 +1494,7 @@ fn finish_native_capture(io: &Io, out_dir: &str, gate: &mut Gate, native: &Nativ
// No raster region, so no presence or placement check ran; say so.
json!({"directory":native.directory,"inputs":inputs,"integrityScope":"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","adequateVisibility":"not-established-by-integrity-checks-alone"})
} else {
- json!({"directory":native.directory,"inputs":inputs,"integrityScope":"rendered presence and minimum frame placement; existing visual scores unchanged","framePolicy":"central-half-with-1px-quantization-tolerance","adequateVisibility":"not-established-by-integrity-checks-alone"})
+ json!({"directory":native.directory,"inputs":inputs,"integrityScope":"rendered presence and minimum frame placement; the comp and approved screenshots are never served to the page; existing visual scores unchanged","framePolicy":"central-half-with-1px-quantization-tolerance","adequateVisibility":"not-established-by-integrity-checks-alone"})
};
report["gate"]["ok"] = json!(gate.ok);
report["gate"]["reasons"] = json!(gate.reasons);
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 704b7bde6..3afe96a12 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -2032,11 +2032,13 @@ Assembly acceptance closes component and assembly reviews for this journey. The
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, its type readings and a `missing` verdict against the comp turned into advisories marked `accepted in the first-viewport review` (a missing one reads `region <id> is missing (...): the comp shows material the build does not; the first viewport the user accepted lacks it too, so the acceptance covers it`). The user judged that first viewport by eye without the region, so its absence is settled; a region the approved screenshot shows and the current capture lacks does not render as accepted and still blocks as missing, so a region removed after the acceptance blocks. 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. A missing plate (or image or texture) region that the approved screenshot lacks too cannot be cleared by restoring what the user accepted, so its reason adds the question for the user: place the plate at its box (the page then no longer matches the accepted screenshot and the readings apply again), or keep the first viewport without it, which downgrades the comp and is recorded only by quoting their words in `advance --force --reason` (the reason gives an example `force` accepts). Force closes the whole gate, so the force route is offered only when nothing but such plates blocks; while any other reason blocks, the reason says to clear the others first and ask once the plate is all that blocks. Only `plate`, `image` and `texture` regions get this question; a missing `band` keeps the plain missing reason. 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, except a `text`, `control` or `chrome` region that renders as accepted in the comparison below: the accepted first viewport lacks it too, so its missing or displaced reason becomes an advisory marked `accepted in the first-viewport review` ending `the first viewport the user accepted lacks it too, so the acceptance covers it`, and its id is listed in `humanTextReview.acceptedRegions`. 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, naming what stays advisory while the capture matches (including a text, control or chrome region the accepted screenshot also lacks) and that a plate the accepted screenshot itself lacks is a question for the user, spelled out in its reason.
-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. The browser's own tab-icon request (Chrome fetches `/favicon.ico`, or a `<link rel=icon>` target, after the load event) is not a page load: it paints nothing in the viewport, so it is neither checked as a dependency nor counted as the page changing during 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.
+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. The browser's own tab-icon request (Chrome fetches `/favicon.ico`, or a `<link rel=icon>` target, after the load event) is not a page load: it paints nothing in the viewport, so it is neither checked as a dependency nor counted as the page changing during 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 `::before` or `::after` counts at its native layout box (read over CDP, so its offsets, size and transform apply), or at its host's box when it has no layout box of its own (`display: contents` lays its generated content out in the host). 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.
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.
+Specs with at least one raster region take the raster capture, which measures each declared plate's rendered presence by intervening on it. Its page gets the same guarantee: the spec and comp are frozen and hashed with the other inputs (and re-verified, so editing the comp invalidates the capture) but are never served, so the input manifest marks them `"served": false` and `inputs.json` lists what the page may load as `servedToPage`. The page gets the static inventory minus those two files. Before the browser opens, a raster region whose `plate` is the comp's path, or whose plate file is a byte copy of the comp or of the approved review screenshot, is refused (`raster region <id> names the approved comp (<path>) as its plate` or `raster region <id>'s plate <path> is a copy of the approved reference`). After each frame the capture reads every path the page asked the snapshot server for, served or not. A request for the comp or the spec refuses the frame with `<frame> raster capture refused: the page loads the approved comp (<path>). Show the declared plates and draw the rest of the first viewport in code.`, and a loaded file that is a byte copy of the comp or of the approved screenshot, or an HTML, CSS, JS or SVG file that inlines either as a base64 data URI (whitespace ignored), refuses it with `the page loads <path>, which is a copy of the approved reference` (or `embeds the approved reference as a data URI`). As on the text-only path, a copy the page never loads does not block it. Byte checks cannot see a re-encoded copy, so each frame also measures the area images paint with the text-only measurement, leaving out what the spec declares: in `hero` and `desktop`, the grid cells inside every raster region's box (comp pixels scaled to the frame width); in `mobile`, which reflows away from the comp's positions, every image drawn only from a declared plate, wherever it lands and whatever surface paints it (an `img`, a background or a `::before`/`::after`), matched by path with any query string or fragment ignored, as the snapshot server ignores them. The mobile frame is not compared with the comp, so this exclusion cannot help a page pass a comparison. When images paint 15% or more of the frame outside those exclusions, the capture is refused with `<frame> raster capture refused: images outside the declared raster regions cover <n>% of the viewport (limit 15%)`, the largest images, and an instruction to declare the image as a raster region (`comp-spec --regions`) or draw that area in code. The measurement is taken after the raster observations, on the restored page, and is kept only when the viewport shows exactly the graded frame's pixels before and after it (otherwise the frame is refused as unmeasured). It is recorded per frame as `frameProofs.<frame>.rasterCoverage` (with the exclusions under `excluded`), not in the region receipts. The report's `nativeCapture.integrityScope` reads `rendered presence and minimum frame placement; the comp and approved screenshots are never served to the page; existing visual scores unchanged`, and the capture's own `inputs.integrityScope` states both guarantees.
+
+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. Either kind needs a `servedToPage` list that names neither the spec nor the comp, an input manifest that does not mark either as served, and a `frameProofs` entry per frame whose `rasterCoverage.share` is under the 15% limit. 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`.
diff --git a/docs/NATIVE-CAPTURE.md b/docs/NATIVE-CAPTURE.md
index afc2aa955..a74a3bd12 100644
--- a/docs/NATIVE-CAPTURE.md
+++ b/docs/NATIVE-CAPTURE.md
@@ -2,7 +2,7 @@
Responsive comparison blocks contradicted control regions as well as contradicted text. A passing whole-page score cannot excuse a contradicted declared control. This check still depends on the spec declaring that control separately; it does not establish that the region map is complete or sufficiently granular.
-The opt-in native HTML gate freezes the current entry, allowed static dependencies, spec and approved reference. It captures raster observations in an isolated browser world and verifies the original inputs before accepting them. Saved screenshots and JSON are audit output, not substitutes for capture. The existing build-phase checks retain their copy, geometry, text, presence and fidelity policies.
+The opt-in native HTML gate freezes the current entry, allowed static dependencies, spec and approved reference. The spec and reference are hashed and re-verified but never served to the page, so a page cannot show the comp it is graded against: a request for it, a loaded byte copy of it or of the approved review screenshot, or a data URI of either refuses the capture, and images painting 15% or more of a frame outside the declared raster regions refuse it too. It captures raster observations in an isolated browser world and verifies the original inputs before accepting them. Saved screenshots and JSON are audit output, not substitutes for capture. The existing build-phase checks retain their copy, geometry, text, presence and fidelity policies.
Some host sandboxes cannot start Chromium's nested sandbox. `capture-server <registered-project> <ready-file>` provides the same `CdpEntryRenderer` outside that filesystem sandbox while keeping Chromium's own sandbox enabled. The host chooses the project and exact engine binary before the builder starts. Requests cannot select a different root, URL, shell command, executable or arbitrary skill verb. Normal build-phase execution remains in-process when no transport is configured.
@@ -10,7 +10,7 @@ The service binds loopback and requires the host-generated `IMPECCABLE_CAPTURE_C
A capability authenticates callers, not arbitrary responses from a builder-selected endpoint. An adapter using this transport must retain its own service process and port, check that process before and after audit requests, and audit through that private reference. The audit compares saved frame PNGs, observation JSON and input reports against host-held capture objects, then rechecks current source bytes. The final responsive snapshot is the current-input boundary; hero legitimately predates later sections. The adapter must verify exported HTML, assets and native evidence against the returned manifest and hashes. A missing or failed host audit invalidates transport provenance. Do not use a client response or a workspace-authored audit file alone as qualification evidence.
-A first viewport with no raster region is captured as an assembled-page viewport and its frames carry no region receipts. The client accepts an empty receipt list only when the spec it froze declares no raster region and the report says `captureMethod: assembled-page-viewport`, with a coverage proof per frame, a known dependency policy and a served list that excludes the spec and comp. The spec decides the kind, so a raster capture without receipts, or a text-only claim for a raster spec, still fails closed. A raster frame must carry one receipt per measured raster region, at most 32, the batch bound the in-process capture already enforces. The audit endpoint checks text-only frames like raster ones, with `[]` as their saved observations.
+A first viewport with no raster region is captured as an assembled-page viewport and its frames carry no region receipts. The client accepts an empty receipt list only when the spec it froze declares no raster region and the report says `captureMethod: assembled-page-viewport`, with a coverage proof per frame, a known dependency policy and a served list that excludes the spec and comp. The spec decides the kind, so a raster capture without receipts, or a text-only claim for a raster spec, still fails closed. Raster captures carry the same served list and per-frame coverage proofs, measured outside the declared raster regions, and the client checks them the same way. A raster frame must carry one receipt per measured raster region, at most 32, the batch bound the in-process capture already enforces. The audit endpoint checks text-only frames like raster ones, with `[]` as their saved observations.
The eval adapter records `nativeCaptureTransport: host-service-v1` as a separate comparison axis. It retains a host audit outside the builder-writable workspace and fails the worker contract on a bad audit. This transport does not introduce a judge, creative instructions, extra repair advice, or a new pass threshold. Other optional browser features, including font-match's documented catalog fallback, retain their existing behavior.