The design language that makes your AI harness better at design.
JavaScript
Capture code-only first viewports for the native hero gate (#892)
Paul Bakaus8c419c73a70f
diff --git a/crates/cli/src/component_capture.rs b/crates/cli/src/component_capture.rsindex 992e576db..f53e22939 100644--- a/crates/cli/src/component_capture.rs+++ b/crates/cli/src/component_capture.rs@@ -54,7 +54,8 @@ fn crop_viewport(png: &[u8], width: u32, height: u32, clip: [f64; 4]) -> Result<&image, rect.x as f64, rect.y as f64, rect.w as f64, rect.h as f64,), &[])}-fn render_page(+#[allow(clippy::too_many_arguments)]+pub(crate) fn render_page(browser: &mut Browser,snapshot: Arc<HtmlSnapshot>,width: u32,@@ -63,6 +64,7 @@ fn render_page(isolation: Option<&Value>,assembled: bool,check_fonts: bool,+ measure_raster: bool,) -> Result<(Vec<u8>, Value), String> {let server = if assembled { snapshot.serve_assembled()? } else { snapshot.serve()? };let url = server.entry_url();@@ -86,6 +88,10 @@ fn render_page(return {html:document.documentElement.outerHTML,svg:document.querySelectorAll('svg').length,images:document.images.length,controls:document.querySelectorAll('button,input,select,textarea,a[href]').length};})()"#.replace("ASSEMBLED", if assembled { "true" } else { "false" });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)?)+ } else { None };let urls = page.observed_response_urls().map_err(|e| e.message)?;let evidence = page.response_evidence(&urls).map_err(|e| e.message)?;if evidence.truncated@@ -189,6 +195,9 @@ fn render_page(proof["capturedDomSha256"] = json!(hash(captured_dom.as_str().unwrap().as_bytes()));}proof["fonts"] = fonts;+ if let Some(coverage) = raster_coverage {+ proof["rasterCoverage"] = coverage;+ }if assembled {proof["kind"] = json!("assembled-page");proof["scriptPolicy"] = json!("pinned-local-and-inline; network-api-and-workers-disabled");@@ -299,7 +308,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) {+ let captured = match render_page(&mut browser, snapshot, width, height, &c["box"], isolation.as_ref(), assembled, check_fonts, false) {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.rsindex b65ce0ddd..660aded86 100644--- a/crates/cli/src/entry_capture.rs+++ b/crates/cli/src/entry_capture.rs@@ -2,16 +2,33 @@use crate::{asset_capture::CdpAssetRenderer,capture_snapshot::{HtmlSnapshot, SnapshotSelection},+ component_capture::render_page,};+use impeccable_browser::{cdp::Browser, discovery, html_snapshot::HtmlSnapshot as PageSnapshot};+use impeccable_comp_verbs::asset_capture::capture_sha256;use impeccable_comp_verbs::entry_capture::{CapturedEntry, EntryEvidence, EntryRenderer, EntryRequest, EntryStage, FrameEvidence,};use serde_json::{Value, json};-use std::{fs, path::Path, sync::Arc};+use std::{+ collections::BTreeMap,+ fs,+ path::{Path, PathBuf},+ sync::Arc,+};pub struct CdpEntryRenderer;+/// Largest share of a frame that images may cover when the spec declares no+/// 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.+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.struct FrozenEntry {snapshot: Arc<HtmlSnapshot>,+ manifest: Option<(PathBuf, Vec<u8>)>,evidence: EntryEvidence,}impl CapturedEntry for FrozenEntry {@@ -19,17 +36,34 @@ impl CapturedEntry for FrozenEntry {&self.evidence}fn verify_current(&self) -> Result<(), String> {- self.snapshot.verify_current()+ self.snapshot.verify_current()?;+ if let Some((path, bytes)) = &self.manifest {+ if fs::read(path).ok().as_ref() != Some(bytes) {+ return Err("capture input changed: .impeccable/review/hero.json".into());+ }+ }+ Ok(())}}impl EntryRenderer for CdpEntryRenderer {fn capture_entry(&self, request: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {+ self.capture_forbidding(request, &[])+ }+}+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.+ pub fn capture_forbidding(+ &self,+ request: &EntryRequest,+ forbidden: &[&[u8]],+ ) -> Result<Box<dyn CapturedEntry>, String> {// The shared gate chooses the entry/spec/reference, never a caller URL.let served = static_inventory(&request.root)?;let snapshot = Arc::new(HtmlSnapshot::freeze(SnapshotSelection {root: request.root.clone(),entry: request.artifact.clone(),- served,+ served: served.clone(),bound: vec![request.spec.clone(), request.reference.clone()],})?);let spec: Value =@@ -45,9 +79,6 @@ impl EntryRenderer for CdpEntryRenderer {.filter(|r| r["medium"] == "raster").map(|r| r["id"].as_str().ok_or("raster region missing id")).collect::<Result<_, _>>()?;- if ids.is_empty() {- return Err("native raster capture requires at least one raster region; text-only capture is not supported yet".into());- }let width = spec["compSize"]["width"].as_f64().ok_or("missing reference width")?;@@ -70,6 +101,9 @@ impl EntryRenderer for CdpEntryRenderer {),],};+ if ids.is_empty() {+ return capture_text_only(request, snapshot, &served, &frames, forbidden);+ }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."}),frames: vec![],@@ -129,8 +163,198 @@ impl EntryRenderer for CdpEntryRenderer {});}snapshot.verify_current()?;- Ok(Box::new(FrozenEntry { snapshot, evidence }))+ Ok(Box::new(FrozenEntry {+ snapshot,+ manifest: None,+ evidence,+ }))+ }+}++/// A first viewport with no raster region has no asset to intervene on, so the+/// asset adapter has nothing to measure. Capture each frame the way the+/// assembled-page review captures the page it shows the user (same snapshot+/// transport, pinned local scripts, verified dependencies, font check and+/// double-screenshot stability), so an approved review screenshot and the gate's+/// frame come from one capture method. Frames carry no region receipts: there is+/// no rendered-presence check to run without artwork.+///+/// The page is served what the review serves: the entry plus the dependencies the+/// hero review manifest declares for it, or, before any review names this entry,+/// the static inventory. Either way the bound spec and comp are never served, and+/// a page that loads or embeds the comp (or an approved screenshot) is refused,+/// so the comparison cannot be satisfied by showing the reference itself.+fn capture_text_only(+ request: &EntryRequest,+ raster: Arc<HtmlSnapshot>,+ inventory: &[String],+ frames: &[(&str, Option<[u32; 2]>)],+ forbidden: &[&[u8]],+) -> 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())?;+ let size = |k: &str| {+ spec["compSize"][k]+ .as_u64()+ .and_then(|v| u32::try_from(v).ok())+ .filter(|v| *v > 0)+ .ok_or_else(|| format!("missing reference {k}"))+ };+ let (width, height) = (size("width")?, size("height")?);+ let comp = raster.bytes(&request.reference).ok_or("reference is not bound to snapshot")?;+ let mut forbidden: Vec<&[u8]> = forbidden.to_vec();+ forbidden.push(comp);+ let (declared, manifest) = declared_dependencies(&request.root, &request.artifact)?;+ let policy = if declared.is_some() { "hero-review-manifest" } else { "static-inventory" };+ let names: Vec<String> = match &declared {+ Some(deps) => {+ let mut names = vec![request.artifact.clone()];+ for dep in deps {+ if !inventory.contains(dep) {+ return Err(format!("hero review dependency {dep} is not a static browser file in the project (hidden, package or source-only paths are never served)"));+ }+ names.push(dep.clone());+ }+ names+ }+ None => inventory.to_vec(),+ };+ // Reuse the bytes the first snapshot froze; nothing is read from disk twice.+ let mut files = BTreeMap::new();+ for name in names {+ if name == request.spec || name == request.reference {+ continue;+ }+ let bytes = raster.bytes(&name).ok_or_else(|| format!("{name} is not in the frozen inputs"))?;+ // Served files are checked when the page loads them (below), under either+ // policy: a file that never reaches the page cannot show the reference.+ files.insert(name, bytes.to_vec());+ }+ let page = Arc::new(PageSnapshot::from_pinned(request.artifact.clone(), files)?);+ let env = impeccable_common::process_env();+ let exe = discovery::find_browser(&env).map_err(|e| format!("browser unavailable: {e:?}"))?;+ let mut browser = Browser::launch(&exe, &[], false).map_err(|e| e.message)?;+ 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":{}}),+ frames: vec![],+ };+ for &(name, viewport) in frames {+ let [w, h] = viewport.unwrap_or([width, height]);+ let (png, proof) = render_page(+ &mut browser,+ page.clone(),+ w,+ h,+ &json!({"x":0,"y":0,"w":1,"h":1}),+ None,+ true,+ true,+ true,+ )+ .map_err(|e| {+ // Both the network check and the image-decode check name the path+ // the page asked for; the comp is never served, so either fires.+ let asked = format!("/{}", request.reference);+ if e.split(|c: char| c.is_whitespace() || c == ',').any(|t| t.trim_end_matches('.') == asked) {+ format!("{name} text-only capture refused: the page loads the approved comp ({}). Draw the first viewport in code.", request.reference)+ } else {+ format!("{name} text-only capture failed: {e}")+ }+ })?;+ for path in proof["observedDependencies"].as_object().into_iter().flatten().map(|(p, _)| p) {+ let bytes = page.bytes(path).ok_or("observed dependency is not in the page snapshot")?;+ if let Some(reason) = forbidden_content(path, bytes, &forbidden) {+ return Err(format!("{name} text-only capture refused: the page loads {path}, which {reason}. Draw the first viewport in code."));+ }+ }+ // Byte checks cannot see a re-encoded copy. The spec says every raster+ // in this viewport is a raster region and it declares none, so a large+ // image contradicts the spec whatever its bytes are.+ 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));+ }+ evidence.report["frameProofs"][name] = proof;+ evidence.frames.push(FrameEvidence {+ name: name.into(),+ png,+ regions: vec![],+ });+ }+ Ok(evidence)+ })();+ browser.close();+ let mut evidence = result?;+ if let Some((_, bytes)) = &manifest {+ evidence.report["reviewManifestSha256"] = json!(capture_sha256(bytes));+ }+ let entry = FrozenEntry { snapshot: raster, manifest, evidence };+ entry.verify_current()?;+ Ok(Box::new(entry))+}++/// The dependency list the hero review manifest declares for this entry, when it+/// names one: the same closure the assembled-page review pins and serves.+fn declared_dependencies(+ root: &Path,+ artifact: &str,+) -> Result<(Option<Vec<String>>, Option<(PathBuf, Vec<u8>)>), String> {+ let path = root.join(".impeccable").join("review").join("hero.json");+ let Ok(bytes) = fs::read(&path) else {+ return Ok((None, None));+ };+ let Ok(manifest) = serde_json::from_slice::<Value>(&bytes) else {+ return Ok((None, None));+ };+ let pages: Vec<&Value> = manifest["components"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|c| c["preview"]["kind"] == "page" && c["preview"]["path"] == artifact)+ .collect();+ if manifest["stage"] != "hero" || pages.len() != 1 {+ return Ok((None, None));+ }+ let deps = pages[0]["dependencies"]+ .as_array()+ .ok_or("hero review manifest: the page component has no dependencies list")?+ .iter()+ .map(|d| d.as_str().map(|s| s.replace('\\', "/")).ok_or("hero review manifest: dependencies must be paths"))+ .collect::<Result<Vec<_>, _>>()?;+ Ok((Some(deps), Some((path, bytes))))+}++/// 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;+ let text = matches!(+ Path::new(name).extension().and_then(|x| x.to_str()).map(str::to_ascii_lowercase).as_deref(),+ Some("html" | "htm" | "css" | "js" | "mjs" | "svg")+ )+ .then(|| String::from_utf8_lossy(bytes));+ // Line breaks and spaces inside a data URI do not change the image it decodes to.+ let text = text.map(|t| t.chars().filter(|c| !c.is_whitespace()).collect::<String>());+ for image in forbidden {+ if bytes == *image {+ return Some("is a copy of the approved reference");+ }+ // A data URI of the image carries its base64 from the first byte, so a+ // leading run of it identifies the embed.+ if let Some(text) = &text {+ let encoded = base64::engine::general_purpose::STANDARD.encode(image);+ let probe = &encoded[..encoded.len().min(512)];+ if probe.len() >= 64 && text.contains(probe) {+ return Some("embeds the approved reference as a data URI");+ }+ }}+ None}/// Enumerate only static browser files. Never serve hidden state, source-onlydiff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rsindex 357f4502d..723203485 100644--- a/crates/cli/src/lib.rs+++ b/crates/cli/src/lib.rs@@ -3,6 +3,8 @@ pub mod asset_capture;pub mod capture_snapshot;+pub mod component_capture;+pub mod entry_capture;pub mod capture_service;diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rsindex ad61cba66..c18f073cb 100644--- a/crates/cli/src/main.rs+++ b/crates/cli/src/main.rs@@ -12,7 +12,6 @@ use std::io::Write;use impeccable_common::Io;mod font_render;-mod component_capture;pub const VERSION: &str = env!("CARGO_PKG_VERSION");@@ -67,7 +66,7 @@ fn run(args: &[String], io: &mut Io) -> i32 {"concept-seed" => impeccable_context::run_concept_seed(rest, io),"generate-image" => impeccable_context::run_generate_image(rest, io),"serve-question" => impeccable_context::run_serve_question(rest, io),- "component-review" => impeccable_context::component_review::run_with_capturer(rest, io, Some(&mut component_capture::NativeComponentCapturer)),+ "component-review" => impeccable_context::component_review::run_with_capturer(rest, io, Some(&mut impeccable::component_capture::NativeComponentCapturer)),// comp-fidelity verbs (crates/comp-verbs over crates/comp)"comp-spec" => impeccable_comp_verbs::run_comp_spec(rest, io),"comp-diff" => impeccable_comp_verbs::run_comp_diff(rest, io),diff --git a/crates/cli/src/raster_coverage.js b/crates/cli/src/raster_coverage.jsnew file mode 100644index 000000000..e2c358dcc--- /dev/null+++ b/crates/cli/src/raster_coverage.js@@ -0,0 +1,123 @@+// Share of the viewport that raster images paint, measured from rendered boxes.+// Counts <img> (any source, data URIs included), <video>, <input type=image>,+// SVG <image>, and elements or ::before/::after pseudo-elements that paint a+// url() image (background, border, mask, list marker or generated content).+// Gradients and same-document fragment references (url(#mask), a pattern or+// mask drawn in SVG) are code and do not count. A no-repeat background with an+// explicit pixel size counts at that size; object-fit contain/scale-down counts+// the letterboxed picture, not its box. Every box is clipped by the ancestors+// that clip it (overflow or 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.+() => {+ 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];+ // True when the value references at least one image that is not a fragment of+ // this document. Chromium may report url(#id) resolved against the page URL.+ const url = v => {+ if (typeof v !== 'string') return false;+ for (const m of v.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)) {+ const ref = m[2];+ if (ref.startsWith('#')) continue;+ try {+ const u = new URL(ref, page);+ if (u.hash && u.href.split('#')[0] === page) continue;+ } catch { /* an unparsable reference is counted, never waived */ }+ return true;+ }+ return false;+ };+ 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'+ || /transform|perspective|filter/.test(s.willChange) || /paint|layout|strict|content/.test(s.contain);+ const clips = s => s.overflowX !== 'visible' || s.overflowY !== 'visible' || /paint|strict|content/.test(s.contain);+ // Clip by the ancestors that actually clip the box: an absolutely positioned+ // box escapes overflow below its containing block, and a fixed one escapes+ // everything but a transform-like containing block. Never clip by an ancestor+ // that does not contain the box, or a hidden-overflow wrapper would let a+ // full-viewport image through.+ const clipped = (from, mode, r) => {+ for (let a = from; a && a !== document.documentElement; a = a.parentElement) {+ const s = getComputedStyle(a);+ const contains = mode === 'fixed' ? createsFixedBlock(s)+ : mode === 'absolute' ? (s.position !== 'static' || createsFixedBlock(s)) : true;+ if (!contains) continue;+ if (clips(s)) {+ const b = a.getBoundingClientRect();+ r = intersect(r, { left: b.left + a.clientLeft, top: b.top + a.clientTop, right: b.left + a.clientLeft + a.clientWidth, bottom: b.top + a.clientTop + a.clientHeight });+ }+ mode = s.position === 'fixed' || s.position === 'absolute' ? s.position : 'static';+ }+ return r;+ };+ const transparent = el => {+ for (let a = el; a; a = a.parentElement) if (parseFloat(getComputedStyle(a).opacity) === 0) return true;+ return false;+ };+ const mark = (from, mode, r, what) => {+ 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) });+ 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;+ };+ 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 });+ const background = (s, r) => {+ const size = (s.backgroundSize || '').split(' ').map(px);+ const norepeat = /^no-repeat( no-repeat)?$/.test(s.backgroundRepeat || '');+ if (norepeat && size.length === 2 && size[0] != null && size[1] != null) {+ const [x, y] = (s.backgroundPosition || '0px 0px').split(' ').map(v => px(v) ?? 0);+ return { left: r.left + x, top: r.top + y, right: r.left + x + size[0], bottom: r.top + y + size[1] };+ }+ return box(r);+ };+ // The painted picture of a replaced element: object-fit contain and+ // scale-down letterbox it inside the content box.+ const picture = (el, s, r) => {+ const c = { left: r.left + (px(s.borderLeftWidth) ?? 0) + (px(s.paddingLeft) ?? 0), top: r.top + (px(s.borderTopWidth) ?? 0) + (px(s.paddingTop) ?? 0),+ right: r.right - (px(s.borderRightWidth) ?? 0) - (px(s.paddingRight) ?? 0), bottom: r.bottom - (px(s.borderBottomWidth) ?? 0) - (px(s.paddingBottom) ?? 0) };+ const nw = el.naturalWidth || el.videoWidth || 0, nh = el.naturalHeight || el.videoHeight || 0;+ if (!['contain', 'scale-down'].includes(s.objectFit) || !nw || !nh) return c;+ const cw = c.right - c.left, ch = c.bottom - c.top;+ let k = Math.min(cw / nw, ch / nh);+ if (s.objectFit === 'scale-down') k = Math.min(k, 1);+ const w = nw * k, h = nh * k;+ const [ox, oy] = (s.objectPosition || '50% 50%').split(' ');+ const at = (v, free) => v?.endsWith('%') ? free * parseFloat(v) / 100 : (px(v) ?? free / 2);+ const x = c.left + at(ox, cw - w), y = c.top + at(oy, ch - h);+ return { left: x, top: y, right: x + w, bottom: y + h };+ };+ for (const el of document.querySelectorAll('*')) {+ 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');+ for (const p of ['::before', '::after']) {+ const ps = getComputedStyle(el, p);+ if (!ps || ps.content === 'none' || ps.content === 'normal' || ps.display === 'none' || ps.visibility !== 'visible' || parseFloat(ps.opacity) === 0) continue;+ if (!(url(ps.content) || url(ps.backgroundImage) || url(ps.borderImageSource) || url(ps.maskImage) || url(ps.webkitMaskImage))) 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.+ const mode = ps.position === 'fixed' || ps.position === 'absolute' ? ps.position : 'static';+ const w = px(ps.width), h = px(ps.height);+ if (w == null || h == null) { mark(el, mode, box(r), name(el) + p); continue; }+ const left = mode === 'fixed' ? (px(ps.left) ?? 0) : r.left, top = mode === 'fixed' ? (px(ps.top) ?? 0) : r.top;+ mark(el, mode, { left, top, right: left + w, bottom: top + h }, name(el) + p);+ }+ }+ 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-v2' };+}diff --git a/crates/cli/src/reviewed_entry.rs b/crates/cli/src/reviewed_entry.rsindex c99bf8375..04499c340 100644--- a/crates/cli/src/reviewed_entry.rs+++ b/crates/cli/src/reviewed_entry.rs@@ -135,11 +135,13 @@ fn reference(session: &Path, r: &EntryRequest) -> Result<ApprovedReference, Stri}impl EntryRenderer for ReviewedEntryRenderer {fn capture_entry(&self, r: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {- let source = CdpEntryRenderer.capture_entry(r)?;let candidate = self.session.as_ref().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 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.rsnew file mode 100644index 000000000..fadc1663b--- /dev/null+++ b/crates/cli/tests/text_only_entry.rs@@ -0,0 +1,422 @@+//! A first viewport built entirely in code (no raster region) through the real+//! browser: native capture, the hero gate's readings, and an accepted review.+use impeccable::entry_capture::CdpEntryRenderer;+use impeccable::reviewed_entry::ReviewedEntryRenderer;+use impeccable_comp::{png_io, raster};+use impeccable_common::Io;+use impeccable_comp_verbs::asset_capture::capture_sha256;+use impeccable_comp_verbs::build_phase;+use impeccable_comp_verbs::entry_capture::{EntryRenderer, EntryRequest, EntryStage};+use serde_json::{Value, json};+use std::{+ fs,+ path::PathBuf,+ collections::HashMap,+ sync::atomic::{AtomicUsize, Ordering},+ time::{SystemTime, UNIX_EPOCH},+};++static NEXT: AtomicUsize = AtomicUsize::new(0);+const SPEC: &str = ".impeccable/build/spec.json";+const PAGE: &str = "<!doctype html><style>html,body{margin:0;background:#f4f4f0;font:16px/1.2 sans-serif}\+header{position:absolute;left:16px;top:16px;width:208px;height:24px;background:#181c24}\+h1{position:absolute;left:16px;top:64px;width:208px;height:40px;margin:0;background:#1e5ac8}</style>\+<header></header><h1></h1>";++struct Fixture {+ dir: PathBuf,+ project: PathBuf,+ home: PathBuf,+}+impl Fixture {+ fn new() -> Self {+ let dir = std::env::temp_dir().join(format!(+ "text-only-entry-{}-{}-{}",+ std::process::id(),+ SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(),+ NEXT.fetch_add(1, Ordering::Relaxed)+ ));+ let project = dir.join("project");+ let home = dir.join("home");+ fs::create_dir_all(project.join(".impeccable/build")).unwrap();+ fs::create_dir_all(project.join(".impeccable/review")).unwrap();+ fs::create_dir_all(&home).unwrap();+ fs::write(project.join("index.html"), PAGE).unwrap();+ let comp = png_io::encode_png(&raster::create_image(240, 160, [244, 244, 240, 255]), &[]).unwrap();+ fs::write(project.join("comp.png"), comp).unwrap();+ let spec = json!({"comp":"comp.png","compSize":{"width":240,"height":160},"regions":[+ {"id":"topbar","kind":"text","medium":"semantic","note":"dark top bar with the product name","type":{},+ "box":{"x":16./240.,"y":0.1,"w":208./240.,"h":0.15},"px":{"x":16,"y":16,"w":208,"h":24}},+ {"id":"headline","kind":"text","medium":"semantic","note":"blue headline block","type":{},+ "box":{"x":16./240.,"y":0.4,"w":208./240.,"h":0.25},"px":{"x":16,"y":64,"w":208,"h":40}}]});+ fs::write(project.join(SPEC), serde_json::to_vec_pretty(&spec).unwrap()).unwrap();+ Self { dir, project, home }+ }+ fn request(&self, stage: EntryStage) -> EntryRequest {+ EntryRequest {+ root: self.project.clone(),+ artifact: "index.html".into(),+ spec: SPEC.into(),+ reference: "comp.png".into(),+ stage,+ }+ }+ /// `build-phase` in process, the way the binary wires it for a standalone+ /// native build. Only the verb's own environment names the temporary home;+ /// the browser launches from the real process environment.+ fn run(&self, args: &[&str]) -> (i32, String) {+ let env = HashMap::from([+ ("HOME".to_string(), self.home.display().to_string()),+ ("USERPROFILE".to_string(), self.home.display().to_string()),+ ("IMPECCABLE_NATIVE_CAPTURE".to_string(), "1".to_string()),+ ]);+ let (mut io, captured) = Io::captured("", self.project.clone(), env);+ let renderer = ReviewedEntryRenderer::local(&self.project, io.home().as_deref());+ let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();+ let code = build_phase::run_with_renderer(&argv, &mut io, &build_phase::no_organic_scan, Some(&renderer));+ drop(io);+ let text = format!(+ "{}{}",+ String::from_utf8_lossy(&captured.stdout.borrow()),+ String::from_utf8_lossy(&captured.stderr.borrow())+ );+ (code, text)+ }+ fn record_hero(&self) -> (bool, String, Value) {+ let (code, text) = self.run(&["record", "hero", "--min", "0.95"]);+ let report = fs::read(self.project.join(".impeccable/review/diff/hero/report.json"))+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .unwrap_or(Value::Null);+ (code == 0, text, report)+ }+ /// The local review store entry for an approved assembled first viewport,+ /// in the shape the component-review capture writes.+ fn approve(&self, screenshot: &[u8]) {+ fs::write(self.project.join(".impeccable/review/hero.json"), br#"{"id":"hero"}"#).unwrap();+ let project = self.project.canonicalize().unwrap();+ let key = capture_sha256(format!("{}\0hero", project.display()).as_bytes());+ let session = self.home.join(".impeccable/component-reviews").join(key);+ fs::create_dir_all(session.join("blobs")).unwrap();+ let png = capture_sha256(screenshot);+ fs::write(session.join("blobs").join(&png), screenshot).unwrap();+ let sources = json!({+ "index.html": capture_sha256(&fs::read(self.project.join("index.html")).unwrap()),+ "comp.png": capture_sha256(&fs::read(self.project.join("comp.png")).unwrap()),+ });+ let capture = json!({"schema":"native-component-previews-v1","components":[{"views":{"preview":{"kind":"assembled-page","entry":"index.html","viewport":{"width":240,"height":160,"dpr":1},"screenshotSha256":png}}}]});+ let state = json!({"sources":sources,"files":{"preview.png":png},"capture":capture,+ "packet":{"stage":"hero","id":"hero","revision":"rev","comp":{"width":240,"height":160,"url":"/files/rev/comp.png"},+ "components":[{"box":{"x":0,"y":0,"w":1,"h":1},"preview":{"sourceKind":"page","url":"/files/rev/preview.png"}}]},+ "receipt":{"visualDecision":"approved","captureVerified":true,"capture":capture,"submission":{"requestId":"hero","packetRevision":"rev"}}});+ fs::write(session.join("current.json"), serde_json::to_vec(&state).unwrap()).unwrap();+ }+}+impl Drop for Fixture {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.dir);+ }+}++fn browser_available() -> bool {+ if impeccable_browser::discovery::find_browser(&std::env::vars().collect()).is_err() {+ eprintln!("skip: browser unavailable");+ return false;+ }+ true+}++#[test]+fn text_only_entry_captures_every_frame_without_region_receipts() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ for stage in [EntryStage::Hero, EntryStage::Responsive] {+ let captured = CdpEntryRenderer.capture_entry(&f.request(stage)).unwrap();+ captured.verify_current().unwrap();+ let evidence = captured.evidence();+ assert_eq!(evidence.report["captureMethod"], "assembled-page-viewport");+ let names: Vec<_> = evidence.frames.iter().map(|f| f.name.as_str()).collect();+ match stage {+ EntryStage::Hero => assert_eq!(names, ["hero"]),+ EntryStage::Responsive => assert_eq!(names, ["desktop", "mobile"]),+ }+ for frame in &evidence.frames {+ assert!(frame.regions.is_empty());+ let image = png_io::decode_png(&frame.png).unwrap().image;+ let expected = match frame.name.as_str() {+ "hero" => (240, 160),+ "desktop" => (1440, 960),+ "mobile" => (390, 844),+ _ => unreachable!(),+ };+ assert_eq!((image.width, image.height), expected);+ assert_eq!(evidence.report["frameProofs"][&frame.name]["kind"], "assembled-page");+ if frame.name == "hero" {+ // The headline block is drawn where the page puts it.+ let p = (80 * image.width + 120) * 4;+ assert_eq!(&image.data[p..p + 3], &[0x1e, 0x5a, 0xc8]);+ }+ }+ // Any bound input that changes invalidates the capture.+ fs::write(f.project.join("index.html"), format!("{PAGE}<p>edited</p>")).unwrap();+ assert!(captured.verify_current().is_err());+ fs::write(f.project.join("index.html"), PAGE).unwrap();+ }+}++#[test]+fn hero_gate_reads_a_text_only_first_viewport_and_honours_an_accepted_review() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ // Comp and build both set the top bar and headline as lettering, the comp in+ // horizontal strokes and the build in vertical ones, so the build's text+ // regions read as contradicted while no ink is invented.+ let strokes = |angle: &str| PAGE+ .replace("background:#181c24", &format!("background:repeating-linear-gradient({angle},#181c24 0 2px,#f4f4f0 2px 4px)"))+ .replace("background:#1e5ac8", &format!("background:repeating-linear-gradient({angle},#1e5ac8 0 2px,#f4f4f0 2px 4px)"));+ fs::write(f.project.join("index.html"), strokes("180deg")).unwrap();+ let comp = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap().evidence().frames[0].png.clone();+ fs::write(f.project.join("comp.png"), comp).unwrap();+ let lettered = strokes("90deg");+ fs::write(f.project.join("index.html"), &lettered).unwrap();+ let hero = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap().evidence().frames[0].png.clone();+ let (code, text) = f.run(&["start", "--comp", "comp.png", "--artifact", "index.html"]);+ assert_eq!(code, 0, "{text}");++ // The gate measures the page and fails on its readings, not on capture.+ let (ok, text, report) = f.record_hero();+ assert!(!ok, "{text}");+ assert!(!text.contains("capture unavailable"), "{text}");+ assert!(report["regions"].as_array().is_some_and(|r| r.iter().any(|r| r["id"] == "headline")), "{report}");+ assert_eq!(report["nativeCapture"]["inputs"]["captureMethod"], "assembled-page-viewport");++ // The same page accepted by the user in the first-viewport review binds by+ // pixels and ends the numeric fight; the material gates still ran.+ f.approve(&hero);+ let (ok, text, report) = f.record_hero();+ assert!(ok, "{text}");+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], true, "{report}");+ assert_eq!(report["nativeCapture"]["inputs"]["humanTextReview"]["schema"], "human-assembled-reference-v1");++ // A visible change after acceptance lapses it again.+ fs::write(f.project.join("index.html"), lettered.replace("top:64px", "top:112px")).unwrap();+ let (ok, text, report) = f.record_hero();+ assert!(!ok, "{text}");+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], false, "{report}");+}++#[test]+fn reviewed_renderer_binds_an_approved_text_only_viewport() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ let hero = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap().evidence().frames[0].png.clone();+ f.approve(&hero);+ let renderer = ReviewedEntryRenderer::local(&f.project, Some(&f.home));+ let captured = renderer.capture_entry(&f.request(EntryStage::Hero)).unwrap();+ let approved = captured.approved_reference().expect("approved viewport binds");+ assert_eq!(approved.proof["schema"], "human-assembled-reference-v1");+ // Same capture method, same page: the approved pixels are the current frame's.+ let a = png_io::decode_png(&approved.png).unwrap().image;+ let b = png_io::decode_png(&captured.evidence().frames[0].png).unwrap().image;+ assert_eq!((a.width, a.height, &a.data), (b.width, b.height, &b.data));+ captured.verify_current().unwrap();+}++fn refusal(f: &Fixture) -> String {+ match CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)) {+ Ok(_) => panic!("capture should be refused"),+ Err(e) => e,+ }+}++#[test]+fn text_only_page_cannot_show_the_comp_instead_of_drawing_it() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ let comp = fs::read(f.project.join("comp.png")).unwrap();+ // The bound comp is never served: an <img> of it is refused, not matched.+ fs::write(f.project.join("index.html"), "<!doctype html><style>body{margin:0}</style><img src=\"comp.png\" style=\"display:block\">").unwrap();+ let e = refusal(&f);+ assert!(e.contains("loads the approved comp"), "{e}");+ // A byte copy at another path is refused before the browser opens.+ fs::create_dir_all(f.project.join("assets")).unwrap();+ fs::write(f.project.join("assets/copy.png"), &comp).unwrap();+ fs::write(f.project.join("index.html"), "<!doctype html><img src=\"assets/copy.png\">").unwrap();+ let e = refusal(&f);+ assert!(e.contains("assets/copy.png") && e.contains("copy of the approved reference"), "{e}");+ fs::remove_file(f.project.join("assets/copy.png")).unwrap();+ // So is the comp inlined as a data URI.+ use base64::Engine;+ let uri = base64::engine::general_purpose::STANDARD.encode(&comp);+ fs::write(f.project.join("index.html"), format!("<!doctype html><img src=\"data:image/png;base64,{uri}\">")).unwrap();+ let e = refusal(&f);+ assert!(e.contains("index.html") && e.contains("data URI"), "{e}");+}++#[test]+fn text_only_page_cannot_show_the_approved_screenshot() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ let hero = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap().evidence().frames[0].png.clone();+ f.approve(&hero);+ fs::create_dir_all(f.project.join("assets")).unwrap();+ fs::write(f.project.join("assets/shot.png"), &hero).unwrap();+ fs::write(f.project.join("index.html"), "<!doctype html><style>body{margin:0}img{display:block}</style><img src=\"assets/shot.png\">").unwrap();+ let renderer = ReviewedEntryRenderer::local(&f.project, Some(&f.home));+ let e = match renderer.capture_entry(&f.request(EntryStage::Hero)) {+ Ok(_) => panic!("a page showing the approved screenshot must be refused"),+ Err(e) => e,+ };+ assert!(e.contains("assets/shot.png") && e.contains("approved reference"), "{e}");+}++#[test]+fn text_only_page_is_served_the_hero_review_dependencies() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ fs::write(f.project.join("style.css"), "h1{outline:0}").unwrap();+ fs::write(f.project.join("extra.js"), "document.body.dataset.extra='1';").unwrap();+ let manifest = |deps: &[&str]| {+ json!({"schemaVersion":2,"stage":"hero","id":"hero","title":"Hero","comp":{"path":"comp.png","width":240,"height":160},+ "components":[{"id":"page","name":"Page","box":{"x":0,"y":0,"w":1,"h":1},"preview":{"kind":"page","path":"index.html"},"dependencies":deps}]})+ };+ fs::write(f.project.join("index.html"), format!("{PAGE}<link rel=stylesheet href=\"style.css\"><script src=\"extra.js\"></script>")).unwrap();+ // Before any review names the entry, the static inventory is served.+ let captured = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap();+ assert_eq!(captured.evidence().report["dependencyPolicy"], "static-inventory");+ // The review declared only the stylesheet: the script is undeclared, as in the review.+ fs::write(f.project.join(".impeccable/review/hero.json"), serde_json::to_vec(&manifest(&["style.css"])).unwrap()).unwrap();+ let e = refusal(&f);+ assert!(e.contains("undeclared dependency: /extra.js"), "{e}");+ // Declared, it loads; the manifest is bound to the capture.+ fs::write(f.project.join(".impeccable/review/hero.json"), serde_json::to_vec(&manifest(&["style.css", "extra.js"])).unwrap()).unwrap();+ let captured = CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).unwrap();+ assert_eq!(captured.evidence().report["dependencyPolicy"], "hero-review-manifest");+ let served: Vec<_> = captured.evidence().report["servedToPage"].as_array().unwrap().iter().filter_map(|f| f["path"].as_str()).collect();+ assert_eq!(served, ["extra.js", "index.html", "style.css"]);+ captured.verify_current().unwrap();+ fs::write(f.project.join(".impeccable/review/hero.json"), serde_json::to_vec(&manifest(&["style.css"])).unwrap()).unwrap();+ assert!(captured.verify_current().is_err());+ // A declared dependency outside the static inventory is never served.+ fs::write(f.project.join(".impeccable/review/hero.json"), serde_json::to_vec(&manifest(&[".env"])).unwrap()).unwrap();+ let e = refusal(&f);+ assert!(e.contains(".env") && e.contains("never served"), "{e}");+}++fn capture_with(f: &Fixture, html: &str) -> Result<(), String> {+ fs::write(f.project.join("index.html"), html).unwrap();+ CdpEntryRenderer.capture_entry(&f.request(EntryStage::Hero)).map(|_| ())+}++#[test]+fn unused_backup_of_the_comp_does_not_block_an_honest_page() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ fs::create_dir_all(f.project.join("backup")).unwrap();+ fs::copy(f.project.join("comp.png"), f.project.join("backup/comp-old.png")).unwrap();+ capture_with(&f, PAGE).unwrap();+ // Loading that same backup is refused.+ let e = capture_with(&f, &format!("{PAGE}<img src=\"backup/comp-old.png\" style=\"width:8px\">")).unwrap_err();+ assert!(e.contains("backup/comp-old.png") && e.contains("copy of the approved reference"), "{e}");+}++#[test]+fn wrapped_data_uri_of_the_comp_is_refused() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ use base64::Engine;+ let encoded = base64::engine::general_purpose::STANDARD.encode(fs::read(f.project.join("comp.png")).unwrap());+ let wrapped = encoded.as_bytes().chunks(76).map(|c| std::str::from_utf8(c).unwrap()).collect::<Vec<_>>().join("\n ");+ let e = capture_with(&f, &format!("<!doctype html><img style=\"width:8px\" src=\"data:image/png;base64,\n {wrapped}\">")).unwrap_err();+ assert!(e.contains("index.html") && e.contains("data URI"), "{e}");+}++#[test]+fn large_images_contradict_a_spec_without_raster_regions_but_logos_do_not() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ fs::create_dir_all(f.project.join("assets")).unwrap();+ // The comp re-encoded (same pixels, different bytes) evades every byte check,+ // so the coverage rule is what refuses it.+ let comp = png_io::decode_png(&fs::read(f.project.join("comp.png")).unwrap()).unwrap().image;+ let reencoded = png_io::encode_png(&comp, &[("Comment".into(), "re-encoded".into())]).unwrap();+ assert_ne!(reencoded, fs::read(f.project.join("comp.png")).unwrap());+ fs::write(f.project.join("assets/reencoded.png"), reencoded).unwrap();+ let e = capture_with(&f, "<!doctype html><style>body{margin:0}img{display:block;width:240px;height:160px}</style><img src=\"assets/reencoded.png\">").unwrap_err();+ assert!(e.contains("images cover 100% of the viewport") && e.contains("declares no raster region"), "{e}");+ // A chart exported as an image is a raster region, not code.+ let chart = png_io::encode_png(&raster::create_image(120, 80, [30, 90, 200, 255]), &[]).unwrap();+ fs::write(f.project.join("assets/chart.png"), chart).unwrap();+ let e = capture_with(&f, &format!("{PAGE}<img src=\"assets/chart.png\" style=\"position:absolute;left:100px;top:40px;width:120px;height:80px\">")).unwrap_err();+ assert!(e.contains("img") && e.contains("25%") && e.contains("declare the image as a raster region"), "{e}");+ // As a CSS background it is the same material.+ let e = capture_with(&f, &format!("{PAGE}<div style=\"position:absolute;left:100px;top:40px;width:120px;height:80px;background:url(assets/chart.png)\"></div>")).unwrap_err();+ assert!(e.contains("background"), "{e}");+ // A small logo is fine.+ let logo = png_io::encode_png(&raster::create_image(16, 16, [200, 60, 30, 255]), &[]).unwrap();+ fs::write(f.project.join("assets/logo.png"), logo).unwrap();+ capture_with(&f, &format!("{PAGE}<img src=\"assets/logo.png\" style=\"position:absolute;right:8px;top:8px;width:16px;height:16px\">")).unwrap();+}++#[test]+fn coverage_counts_only_the_image_area_that_is_painted() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ fs::create_dir_all(f.project.join("assets")).unwrap();+ let big = png_io::encode_png(&raster::create_image(240, 160, [30, 90, 200, 255]), &[]).unwrap();+ fs::write(f.project.join("assets/big.png"), big).unwrap();+ let wide = png_io::encode_png(&raster::create_image(240, 8, [30, 90, 200, 255]), &[]).unwrap();+ fs::write(f.project.join("assets/wide.png"), wide).unwrap();+ let icon = png_io::encode_png(&raster::create_image(16, 16, [30, 90, 200, 255]), &[]).unwrap();+ fs::write(f.project.join("assets/icon.png"), icon).unwrap();+ let full = "style=\"display:block;width:240px;height:160px\"";+ // Clipped to a 12px strip by its overflow parent: 7.5% painted.+ capture_with(&f, &format!("{PAGE}<div style=\"position:absolute;left:0;top:140px;width:240px;height:12px;overflow:hidden\"><img src=\"assets/big.png\" {full}></div>")).unwrap();+ // An absolutely positioned image escapes a static overflow wrapper, so it is not clipped by it.+ let e = capture_with(&f, &format!("{PAGE}<div style=\"width:10px;height:10px;overflow:hidden\"><img src=\"assets/big.png\" style=\"position:absolute;left:0;top:0;width:240px;height:160px\"></div>")).unwrap_err();+ assert!(e.contains("images cover 100%"), "{e}");+ // Under a transparent ancestor, or hidden, it paints nothing.+ capture_with(&f, &format!("{PAGE}<div style=\"opacity:0\"><img src=\"assets/big.png\" {full}></div>")).unwrap();+ capture_with(&f, &format!("{PAGE}<img src=\"assets/big.png\" style=\"visibility:hidden;position:absolute;left:0;top:0;width:240px;height:160px\">")).unwrap();+ // Letterboxed: only the picture counts, not its box.+ capture_with(&f, &format!("{PAGE}<img src=\"assets/wide.png\" style=\"position:absolute;left:0;top:0;width:240px;height:160px;object-fit:contain\">")).unwrap();+ capture_with(&f, &format!("{PAGE}<img src=\"assets/icon.png\" style=\"position:absolute;left:0;top:0;width:240px;height:160px;object-fit:scale-down\">")).unwrap();+ // Stretched (the default fill), the same picture covers the frame.+ let e = capture_with(&f, &format!("{PAGE}<img src=\"assets/wide.png\" style=\"position:absolute;left:0;top:0;width:240px;height:160px\">")).unwrap_err();+ assert!(e.contains("images cover 100%"), "{e}");+}++#[test]+fn svg_fragment_masks_and_patterns_are_code_not_raster() {+ if !browser_available() {+ return;+ }+ let f = Fixture::new();+ let svg = "<svg width=\"0\" height=\"0\" style=\"position:absolute\"><defs>\+ <mask id=\"m\" maskContentUnits=\"objectBoundingBox\"><rect width=\"1\" height=\"1\" fill=\"white\"/></mask>\+ <pattern id=\"p\" width=\"8\" height=\"8\" patternUnits=\"userSpaceOnUse\"><rect width=\"4\" height=\"4\" fill=\"#1e5ac8\"/></pattern></defs></svg>";+ let masked = format!("{svg}<div style=\"position:absolute;left:0;top:0;width:240px;height:160px;background:#181c24;mask-image:url(#m);-webkit-mask-image:url(#m)\"></div>");+ capture_with(&f, &format!("{PAGE}{masked}")).unwrap();+ let patterned = format!("{svg}<svg style=\"position:absolute;left:0;top:0\" width=\"240\" height=\"160\"><rect width=\"240\" height=\"160\" fill=\"url(#p)\"/></svg>");+ capture_with(&f, &format!("{PAGE}{patterned}")).unwrap();+}diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rsindex fdc2660b8..bd3862df5 100644--- a/crates/comp-verbs/src/build_phase.rs+++ b/crates/comp-verbs/src/build_phase.rs@@ -1429,7 +1429,13 @@ fn finish_native_capture(io: &Io, out_dir: &str, gate: &mut Gate, native: &Nativreturn;}};- report["nativeCapture"] = json!({"directory":native.directory,"inputs":native.capture.evidence().report,"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"});+ let inputs = &native.capture.evidence().report;+ report["nativeCapture"] = if inputs["captureMethod"] == "assembled-page-viewport" {+ // 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"})+ };report["gate"]["ok"] = json!(gate.ok);report["gate"]["reasons"] = json!(gate.reasons);report["gate"]["unscopedReasons"] = json!(diff --git a/crates/comp-verbs/src/build_phase/integrity_tests.rs b/crates/comp-verbs/src/build_phase/integrity_tests.rsindex 91d2e96ff..fd406465c 100644--- a/crates/comp-verbs/src/build_phase/integrity_tests.rs+++ b/crates/comp-verbs/src/build_phase/integrity_tests.rs@@ -951,11 +951,11 @@ impl CapturedEntry for ReviewedCapture {fn verify_current(&self) -> Result<(), String> { Ok(()) }}/// Stands in for the reviewed native renderer: `approved` is what the user accepted.-struct ReviewedRenderer { hero: Vec<u8>, approved: Option<Vec<u8>> }+struct ReviewedRenderer { hero: Vec<u8>, approved: Option<Vec<u8>>, report: Value }impl EntryRenderer for ReviewedRenderer {fn capture_entry(&self, _: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {let frame = crate::entry_capture::FrameEvidence { name: "hero".into(), png: self.hero.clone(), regions: vec![] };- Ok(Box::new(ReviewedCapture(crate::entry_capture::EntryEvidence { report: json!({}), frames: vec![frame] },+ Ok(Box::new(ReviewedCapture(crate::entry_capture::EntryEvidence { report: self.report.clone(), frames: vec![frame] },self.approved.clone().map(|png| crate::entry_capture::ApprovedReference { png, proof: json!({"schema": "test-review"}) }))))}}@@ -996,7 +996,7 @@ fn run_reviewed_hero_min(capture: &Image, approved: Option<&Image>, html: &str,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","capturePolicy":"native-html-v1","plates":{"art":receipt},"phases":{"hero":{}}});- let renderer = ReviewedRenderer { hero: png(capture), approved: approved.map(png) };+ let renderer = ReviewedRenderer { hero: png(capture), approved: approved.map(png), report: json!({}) };let gate = gate_hero(&io, &mut state, "unused.png", min, "diff", Some("index.html"), &no_organic_scan, Some(&renderer));let report = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();(gate, report)@@ -1141,3 +1141,69 @@ fn responsive_does_not_relitigate_an_accepted_first_viewport_score() {assert!(lapsed.reasons.iter().any(|r| r.starts_with("the desktop capture no longer matches the first viewport the user accepted") && r.ends_with("Restore what the user accepted; until then the readings apply.")), "{:?}", lapsed.reasons);assert!(!lapsed.reasons.iter().any(|r| r.contains("does not survive a common desktop width")), "{:?}", lapsed.reasons);}++/// A code-led first viewport (an Operate dashboard's header, headline and a+/// control) with no raster region: the native renderer returns frames without+/// region receipts, and the gate reads the same text and control regions.+fn text_only_hero(restyled: bool) -> Image {+ let mut img = r::create_image(240, 160, [244, 244, 240, 255]);+ r::fill_rect(&mut img, 16., 16., 120., 28., [24., 28., 36., 255.]);+ if restyled {+ for x in (18..134).step_by(3) { r::fill_rect(&mut img, x as f64, 18., 1., 24., [240., 240., 240., 255.]); }+ } else {+ for y in (18..42).step_by(3) { r::fill_rect(&mut img, 20., y as f64, 112., 1., [240., 240., 240., 255.]); }+ }+ r::fill_rect(&mut img, 160., 116., 64., 24., [30., 90., 200., 255.]);+ img+}++fn run_text_only_hero(capture: &Image, approved: Option<&Image>) -> (Gate, Value) {+ let ws = Workspace::new();+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();+ ws.write("comp.png", &png(&text_only_hero(false)));+ ws.write("index.html", b"<main><h1>Revenue</h1><button>Export</button></main>");+ let spec = json!({"comp":"comp.png","compSize":{"width":240,"height":160},"regions":[+ {"id":"headline","kind":"text","medium":"semantic","note":"striped headline lettering","type":{},+ "box":{"x":0.0667,"y":0.1,"w":0.5,"h":0.175},"px":{"x":16,"y":16,"w":120,"h":28}},+ {"id":"export","kind":"control","medium":"semantic","note":"blue export button",+ "box":{"x":0.6667,"y":0.725,"w":0.2667,"h":0.15},"px":{"x":160,"y":116,"w":64,"h":24}}]});+ ws.write(SPEC_PATH, util::json_pretty(&spec).as_bytes());+ let io = ws.io();+ let mut state = json!({"comp":"comp.png","capturePolicy":"native-html-v1","phases":{"hero":{}}});+ let renderer = ReviewedRenderer { hero: png(capture), approved: approved.map(png), report: json!({"captureMethod":"assembled-page-viewport"}) };+ let gate = gate_hero(&io, &mut state, "unused.png", HERO_MIN, "diff", Some("index.html"), &no_organic_scan, Some(&renderer));+ let report = serde_json::from_slice(&std::fs::read(ws.path.join("diff/report.json")).unwrap()).unwrap();+ (gate, report)+}++#[test]+fn text_only_first_viewport_gets_region_readings_from_the_native_frame() {+ // The comp itself: the gate measures and passes with no raster region at all.+ let (gate, report) = run_text_only_hero(&text_only_hero(false), None);+ assert!(gate.ok, "{:?}", gate.reasons);+ assert!(gate.score.is_some_and(|s| s >= HERO_MIN), "{:?}", gate.score);+ let ids: Vec<_> = report["regions"].as_array().unwrap().iter().filter_map(|r| r["id"].as_str()).collect();+ assert!(ids.contains(&"headline") && ids.contains(&"export"), "{ids:?}");+ // No raster region: the report must not claim the presence checks ran.+ let scope = report["nativeCapture"]["integrityScope"].as_str().unwrap();+ assert!(scope.contains("no raster presence") && !scope.starts_with("rendered presence"), "{scope}");+ assert!(report["nativeCapture"]["framePolicy"].is_null(), "{report}");+ // A restyled headline is read as a text reading, not as a capture failure.+ let (gate, _) = run_text_only_hero(&text_only_hero(true), None);+ assert!(!gate.ok);+ assert!(gate.reasons.iter().any(|r| r.contains("headline (text) is contradicted")), "{:?}", gate.reasons);+ assert!(!gate.reasons.iter().any(|r| r.contains("capture unavailable")), "{:?}", gate.reasons);+}++#[test]+fn accepted_review_of_a_text_only_first_viewport_lets_it_pass() {+ let current = text_only_hero(true);+ let (gate, report) = run_text_only_hero(¤t, Some(¤t));+ assert!(gate.ok, "{:?}", gate.reasons);+ assert!(gate.advisories.iter().any(|a| a.contains("first viewport accepted") || a.contains("accepted in the first-viewport review")), "{:?}", gate.advisories);+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], true, "{report}");+ // A stale approval (a different rendering) still waives nothing.+ let (gate, report) = run_text_only_hero(¤t, Some(&text_only_hero(false)));+ assert!(!gate.ok);+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], false, "{report}");+}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex d26bec646..9219ec70e 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -1956,6 +1956,8 @@ Assembly acceptance closes component and assembly reviews for this journey. TheThe 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.+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 or pattern) are code and do not count. 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.+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`.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.diff --git a/docs/PLAN-REVIEW.md b/docs/PLAN-REVIEW.mdindex 9e4bbf4ab..77acb9d96 100644--- a/docs/PLAN-REVIEW.md+++ b/docs/PLAN-REVIEW.md@@ -77,6 +77,8 @@ The first-viewport review is unchanged in form. Two rule changes:- After three failed hero attempts, the gate's message says to present the first-viewport review instead of continuing to iterate. When a first viewport is already accepted, it says to restore what the user accepted instead.- An accepted first-viewport review for the current capture ends the numeric fight: the overall bar, the palette check and every numeric reading become advisories, in the hero gate and in the responsive and finish rechecks of the same viewport. Only material vetoes stay hard: a missing or unreferenced plate, an SVG illustration, an organic clip, a clipped plate, invented ink, and failed rendered presence. The approval binds to the capture: the approved screenshot has to match the current hero frame (overall at least 95%, nothing missing or contradicted), so a stale approval waives nothing. The binding is visual, not by source bytes: sections, motion and responsive work edit shared CSS freely, and the waiver holds while the first viewport still looks like the accepted screenshot. When it visibly changes, the gate says the first viewport differs from what the user accepted and asks to restore it (the readings apply until then) instead of quoting a raw score. It never asks for a new first-viewport review once one is accepted: the review store hands back the accepted session, so that request would loop. The three-failure message follows the same rule. A tiled ground whose repeats cannot land on the comp's positions is the case this exists for.+A first viewport with no raster region (every region drawn in code, the usual case for Operate screens) is captured the way the assembled-page review captures the page, from the dependencies the hero review manifest declares for it (the static inventory before one exists), so the gate reads it, and an accepted review of it binds and ends the numeric fight like any other. The page is never served the comp, and a page that shows the comp or the approved screenshot, by path, by copy or as a data URI, is refused rather than matched. Since the spec declares no raster region, images may paint less than 15% of the viewport, measured on what is actually painted: clipped, hidden and letterboxed images count only their visible picture, and SVG masks and patterns are code (logos and icons pass); a larger image, re-encoded comp or honest chart alike, is refused with a message to declare it as a raster region or draw it in code. Before, the native hero capture refused such a page outright, which left an accepted review unable to bind and the run stuck at the hero.+## Painted-pixel flag (`comp-spec`)For every `text`, `control` and `chrome` region, containers included, `comp-spec` measures the comp crop with pixels inside raster regions left out, and adds `flags: [{"id":"painted-pixels","message":...}]` when it looks painted. It is a flag, not a refusal, and `codeDrawn` does not suppress it.