Skip to content

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

JavaScript

Accept text-only hero captures over the host capture service (#899)

Paul Bakaus755d2df217d5
diff --git a/crates/cli/src/asset_capture.rs b/crates/cli/src/asset_capture.rs
index bc2b87087..62a5dd3b7 100644
--- a/crates/cli/src/asset_capture.rs
+++ b/crates/cli/src/asset_capture.rs
@@ -36,8 +36,11 @@ impl AssetRenderer for CdpAssetRenderer {
&mut self,
requests: &[AssetCaptureRequest],
) -> Result<Vec<AssetCapture>, String> {
- if requests.is_empty() || requests.len() > 32 {
- return Err("capture batch must contain 1 to 32 regions".into());
+ if requests.is_empty() || requests.len() > crate::capture_snapshot::MAX_CAPTURE_REGIONS {
+ return Err(format!(
+ "capture batch must contain 1 to {} regions",
+ crate::capture_snapshot::MAX_CAPTURE_REGIONS
+ ));
}
let request = &requests[0];
for item in requests {
diff --git a/crates/cli/src/capture_service.rs b/crates/cli/src/capture_service.rs
index 040644638..54b5e836a 100644
--- a/crates/cli/src/capture_service.rs
+++ b/crates/cli/src/capture_service.rs
@@ -3,7 +3,8 @@
use crate::reviewed_entry::ReviewedEntryRenderer;
use base64::Engine;
use impeccable_comp_verbs::entry_capture::{
- CapturedEntry, EntryRenderer, EntryRequest, EntryStage,
+ ApprovedReference, CapturedEntry, EntryEvidence, EntryRenderer, EntryRequest, EntryStage,
+ FrameEvidence,
};
use serde_json::{Value, json};
use std::{
@@ -447,10 +448,6 @@ impl Drop for RemoteEntry {
}
impl EntryRenderer for RemoteEntryRenderer {
fn capture_entry(&self, r: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {
- use impeccable_comp_verbs::{
- asset_capture::AssetCapture,
- entry_capture::{EntryEvidence, FrameEvidence},
- };
let stage = match r.stage {
EntryStage::Hero => "hero",
EntryStage::Responsive => "responsive",
@@ -463,66 +460,14 @@ impl EntryRenderer for RemoteEntryRenderer {
.as_str()
.ok_or("missing native capture handle")?
.to_string();
- let parsed = (|| -> Result<Box<dyn CapturedEntry>, String> {
- let root = std::fs::canonicalize(&r.root).map_err(|e| e.to_string())?;
- if result["report"]["captureService"]["registeredRoot"] != json!(root)
- || result["report"]["captureService"]["id"] != id
- || result["report"]["stage"] != stage
- || result["report"]["artifact"] != r.artifact
- {
- return Err("native capture binding mismatch".into());
- }
- let expected = if stage == "hero" {
- vec!["hero"]
- } else {
- vec!["desktop", "mobile"]
- };
- let frames = result["frames"]
- .as_array()
- .filter(|f| f.len() == expected.len())
- .ok_or("invalid native capture frames")?;
- let frames = frames
- .iter()
- .zip(expected)
- .map(|(f, name)| -> Result<FrameEvidence, String> {
- if f["name"] != name {
- return Err("invalid native capture frame name".into());
- }
- let png = base64::engine::general_purpose::STANDARD
- .decode(f["png"].as_str().ok_or("missing frame PNG")?)
- .map_err(|e| e.to_string())?;
- let regions = f["regions"]
- .as_array()
- .filter(|r| !r.is_empty() && r.len() <= 32)
- .ok_or("invalid native capture regions")?
- .iter()
- .map(|r| AssetCapture {
- receipt: r.clone(),
- images: vec![],
- })
- .collect();
- Ok(FrameEvidence {
- name: name.into(),
- png,
- regions,
- })
- })
- .collect::<Result<Vec<_>, _>>()?;
- Ok(Box::new(RemoteEntry {
- approved: if result["approvedReference"].is_null(){None}else{
- let a=&result["approvedReference"];
- let png=base64::engine::general_purpose::STANDARD.decode(a["png"].as_str().ok_or("missing reviewed PNG")?).map_err(|e|e.to_string())?;
- if a["proof"]["schema"]!="human-assembled-reference-v1" || a["proof"]["sha256"]!=impeccable_comp_verbs::asset_capture::capture_sha256(&png) || a["proof"]!=result["report"]["humanTextReview"] {return Err("invalid human reference proof".into())}
- Some(impeccable_comp_verbs::entry_capture::ApprovedReference{png,proof:a["proof"].clone()})
- },
+ let parsed = parse_capture(&result, r, stage, &id).map(|(evidence, approved)| {
+ Box::new(RemoteEntry {
+ approved,
renderer: self.clone(),
id: id.clone(),
- evidence: EntryEvidence {
- report: result["report"].clone(),
- frames,
- },
- }))
- })();
+ evidence,
+ }) as Box<dyn CapturedEntry>
+ });
if parsed.is_err() {
let _ = self.call("/release", json!({"handle":id}));
}
@@ -530,6 +475,142 @@ impl EntryRenderer for RemoteEntryRenderer {
}
}
+/// The kind of capture a spec calls for, read from the spec bytes the service
+/// froze: the raster region ids in spec order, empty for a first viewport drawn
+/// entirely in code.
+fn bound_raster_ids(report: &Value, r: &EntryRequest) -> Result<Vec<String>, String> {
+ let root = std::fs::canonicalize(&r.root).map_err(|e| e.to_string())?;
+ let bytes = std::fs::read(root.join(&r.spec)).map_err(|e| format!("cannot read bound spec: {e}"))?;
+ let frozen = report["manifest"]["files"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .find(|f| f["path"] == r.spec.as_str())
+ .ok_or("native capture did not freeze the bound spec")?;
+ if frozen["sha256"] != impeccable_comp_verbs::asset_capture::capture_sha256(&bytes) {
+ return Err("native capture binding mismatch: spec changed".into());
+ }
+ let spec: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
+ spec["regions"]
+ .as_array()
+ .ok_or("missing spec regions")?
+ .iter()
+ .filter(|g| g["medium"] == "raster")
+ .map(|g| g["id"].as_str().map(str::to_string).ok_or_else(|| "raster region missing id".to_string()))
+ .collect()
+}
+
+/// Validate a service capture against the request and the spec it froze. The
+/// spec decides the kind, not the response: a spec with raster regions needs one
+/// receipt per measured region in every frame, and a spec without any needs the
+/// assembled-page capture, whose frames carry no receipts. A raster capture
+/// that comes back with no receipts, or a text-only claim for a raster spec, is
+/// refused before build-phase sees it.
+fn parse_capture(
+ result: &Value,
+ r: &EntryRequest,
+ stage: &str,
+ id: &str,
+) -> Result<(EntryEvidence, Option<ApprovedReference>), String> {
+ use crate::{capture_snapshot::MAX_CAPTURE_REGIONS, entry_capture::TEXT_ONLY_RASTER_SHARE_MAX};
+ use impeccable_comp_verbs::asset_capture::AssetCapture;
+ let report = &result["report"];
+ let root = std::fs::canonicalize(&r.root).map_err(|e| e.to_string())?;
+ if report["captureService"]["registeredRoot"] != json!(root)
+ || report["captureService"]["id"] != id
+ || report["stage"] != stage
+ || report["artifact"] != r.artifact
+ {
+ return Err("native capture binding mismatch".into());
+ }
+ let raster = bound_raster_ids(report, r)?;
+ let text_only = raster.is_empty();
+ if text_only != (report["captureMethod"] == "assembled-page-viewport") {
+ return Err(if text_only {
+ "native capture method does not match a spec without raster regions".into()
+ } else {
+ "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());
+ }
+ }
+ let expected = if stage == "hero" {
+ vec!["hero"]
+ } else {
+ vec!["desktop", "mobile"]
+ };
+ let frames = result["frames"]
+ .as_array()
+ .filter(|f| f.len() == expected.len())
+ .ok_or("invalid native capture frames")?;
+ let frames = frames
+ .iter()
+ .zip(expected)
+ .map(|(f, name)| -> Result<FrameEvidence, String> {
+ if f["name"] != name {
+ return Err("invalid native capture frame name".into());
+ }
+ let png = base64::engine::general_purpose::STANDARD
+ .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")?;
+ 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)) {
+ return Err("invalid native capture regions".into());
+ }
+ } else {
+ // Mobile measures only the first raster region (see entry_capture).
+ let wanted = if name == "mobile" { &raster[..1] } else { &raster[..] };
+ // Every receipt must name its region: one without an id is malformed, not skipped.
+ let mut got: Vec<Option<&str>> = receipts.iter().map(|g| g["regionId"].as_str()).collect();
+ got.sort_unstable();
+ let mut want: Vec<Option<&str>> = wanted.iter().map(|w| Some(w.as_str())).collect();
+ want.sort_unstable();
+ if receipts.is_empty() || receipts.len() > MAX_CAPTURE_REGIONS || got != want {
+ return Err("invalid native capture regions".into());
+ }
+ }
+ Ok(FrameEvidence {
+ name: name.into(),
+ png,
+ regions: receipts
+ .iter()
+ .map(|g| AssetCapture {
+ receipt: g.clone(),
+ images: vec![],
+ })
+ .collect(),
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ let approved = if result["approvedReference"].is_null() {
+ None
+ } else {
+ let a = &result["approvedReference"];
+ let png = base64::engine::general_purpose::STANDARD
+ .decode(a["png"].as_str().ok_or("missing reviewed PNG")?)
+ .map_err(|e| e.to_string())?;
+ if a["proof"]["schema"] != "human-assembled-reference-v1"
+ || a["proof"]["sha256"] != impeccable_comp_verbs::asset_capture::capture_sha256(&png)
+ || a["proof"] != report["humanTextReview"]
+ {
+ return Err("invalid human reference proof".into());
+ }
+ Some(ApprovedReference { png, proof: a["proof"].clone() })
+ };
+ Ok((EntryEvidence { report: report.clone(), frames }, approved))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -625,3 +706,134 @@ mod component_boundary_tests {
assert!(require_component_review(false, "component_review").is_ok());
}
}
+
+#[cfg(test)]
+mod parse_tests {
+ use super::*;
+ use impeccable_comp_verbs::asset_capture::capture_sha256;
+ const SPEC: &str = ".impeccable/build/spec.json";
+ struct Root(PathBuf);
+ impl Drop for Root {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+ fn root(name: &str, raster: usize) -> (Root, EntryRequest, Value) {
+ let dir = std::env::temp_dir().join(format!("capsvc-parse-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join(".impeccable/build")).unwrap();
+ let mut regions = vec![json!({"id":"headline","kind":"text","medium":"semantic"})];
+ regions.extend((0..raster).map(|i| json!({"id":format!("art-{i}"),"kind":"plate","medium":"raster"})));
+ let spec = serde_json::to_vec(&json!({"comp":"comp.png","regions":regions})).unwrap();
+ std::fs::write(dir.join(SPEC), &spec).unwrap();
+ let request = EntryRequest {
+ root: dir.clone(),
+ artifact: "index.html".into(),
+ spec: SPEC.into(),
+ reference: "comp.png".into(),
+ stage: EntryStage::Hero,
+ };
+ 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)}]}});
+ 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)
+ }
+ fn frame(regions: Vec<Value>) -> Value {
+ json!({"name":"hero","png":"","regions":regions})
+ }
+ fn receipts(n: usize) -> Vec<Value> {
+ (0..n).map(|i| json!({"regionId":format!("art-{i}")})).collect()
+ }
+ /// The parsed report and per-frame receipt counts.
+ fn parse(request: &EntryRequest, report: &Value, frame: Value) -> Result<(Value, Vec<usize>), String> {
+ parse_frames(request, report, "hero", vec![frame])
+ }
+ fn parse_frames(request: &EntryRequest, report: &Value, stage: &str, frames: Vec<Value>) -> Result<(Value, Vec<usize>), String> {
+ let result = json!({"report":report,"frames":frames,"approvedReference":null});
+ parse_capture(&result, request, stage, "h-1")
+ .map(|(e, _)| (e.report, e.frames.iter().map(|f| f.regions.len()).collect()))
+ }
+ fn named(name: &str, regions: Vec<Value>) -> Value {
+ json!({"name":name,"png":"","regions":regions})
+ }
+
+ #[test]
+ fn text_only_capture_crosses_the_transport_without_receipts() {
+ let (_root, request, report) = root("text", 0);
+ let (parsed, counts) = parse(&request, &report, frame(vec![])).unwrap();
+ assert_eq!(counts, [0]);
+ assert_eq!(parsed["dependencyPolicy"], "static-inventory");
+ // Text-only frames never carry receipts, and their proofs bound images.
+ assert!(parse(&request, &report, frame(vec![json!({"regionId":"x"})])).is_err());
+ for (pointer, value) in [
+ ("/frameProofs/hero/rasterCoverage/share", json!(0.15)),
+ ("/frameProofs/hero", json!(null)),
+ ("/dependencyPolicy", json!("caller")),
+ ("/servedToPage", json!([{"path":"index.html"},{"path":"comp.png"}])),
+ ("/servedToPage", json!([{"path":SPEC}])),
+ ] {
+ let mut broken = report.clone();
+ *broken.pointer_mut(pointer).unwrap() = value;
+ assert!(parse(&request, &broken, frame(vec![])).is_err(), "{pointer}");
+ }
+ // The spec, not the response, decides the kind.
+ let mut claimed = report.clone();
+ claimed["captureMethod"] = json!("native-raster");
+ let e = parse(&request, &claimed, frame(vec![])).unwrap_err();
+ assert!(e.contains("method"), "{e}");
+ }
+
+ #[test]
+ fn raster_capture_without_receipts_still_fails_closed() {
+ let (_root, request, report) = root("raster", 2);
+ 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");
+ // Claiming the text-only method does not excuse a raster spec.
+ let mut claimed = report.clone();
+ claimed["captureMethod"] = json!("assembled-page-viewport");
+ claimed["frameProofs"] = json!({"hero":{"rasterCoverage":{"share":0.0}}});
+ claimed["dependencyPolicy"] = json!("static-inventory");
+ claimed["servedToPage"] = json!([]);
+ let e = parse(&request, &claimed, frame(vec![])).unwrap_err();
+ assert!(e.contains("method"), "{e}");
+ // Every raster region needs its own receipt; a missing one is refused.
+ assert!(parse(&request, &report, frame(receipts(1))).is_err());
+ // So is a receipt that names no region, even beside a full set.
+ let mut extra = receipts(2);
+ extra.push(json!({"regionId":null}));
+ assert!(parse(&request, &report, frame(extra)).is_err());
+ let mut twice = receipts(1);
+ twice.push(json!({"regionId":"art-0"}));
+ assert!(parse(&request, &report, frame(twice)).is_err());
+ // Responsive: desktop measures every raster region, mobile only the first.
+ let mut responsive = report.clone();
+ responsive["stage"] = json!("responsive");
+ let (_, counts) = parse_frames(&request, &responsive, "responsive", vec![named("desktop", receipts(2)), named("mobile", receipts(1))]).unwrap();
+ assert_eq!(counts, [2, 1]);
+ for (desktop, mobile) in [(receipts(1), receipts(1)), (receipts(2), receipts(2)), (receipts(2), vec![json!({"regionId":"art-1"})]), (receipts(2), vec![])] {
+ assert!(parse_frames(&request, &responsive, "responsive", vec![named("desktop", desktop), named("mobile", mobile)]).is_err());
+ }
+ // A spec edited after the capture no longer binds it.
+ std::fs::write(request.root.join(SPEC), b"{\"regions\":[]}").unwrap();
+ let e = parse(&request, &report, frame(receipts(2))).unwrap_err();
+ assert!(e.contains("spec changed"), "{e}");
+ }
+
+ #[test]
+ fn receipt_cap_is_the_native_batch_bound() {
+ use crate::capture_snapshot::MAX_CAPTURE_REGIONS;
+ let (_root, request, report) = root("cap", MAX_CAPTURE_REGIONS);
+ assert!(parse(&request, &report, frame(receipts(MAX_CAPTURE_REGIONS))).is_ok());
+ let (_root, request, report) = root("over", MAX_CAPTURE_REGIONS + 1);
+ let e = parse(&request, &report, frame(receipts(MAX_CAPTURE_REGIONS + 1))).unwrap_err();
+ assert_eq!(e, "invalid native capture regions");
+ }
+}
diff --git a/crates/cli/src/capture_snapshot.rs b/crates/cli/src/capture_snapshot.rs
index b63ee41de..c596479e3 100644
--- a/crates/cli/src/capture_snapshot.rs
+++ b/crates/cli/src/capture_snapshot.rs
@@ -2,6 +2,11 @@
//! The native caller owns the selection; private bound inputs are never HTTP routes.
use impeccable_comp_verbs::asset_capture::capture_sha256 as hash;
use serde_json::{Value, json};
+/// Most raster regions one native capture measures in a frame. The browser
+/// adapter batches a frame's regions into one document and refuses a larger
+/// batch, so no native capture, in process or through the host service, ever
+/// carries more receipts per frame than this.
+pub const MAX_CAPTURE_REGIONS: usize = 32;
use std::{
collections::{BTreeMap, BTreeSet},
fs::{self, File},
@@ -127,10 +132,10 @@ impl HtmlSnapshot {
use impeccable_comp_verbs::asset_capture::AssetCaptureRequest;
self.verify_current()?;
if region_ids.is_empty()
- || region_ids.len() > 32
+ || region_ids.len() > MAX_CAPTURE_REGIONS
|| region_ids.iter().copied().collect::<BTreeSet<_>>().len() != region_ids.len()
{
- return Err("capture requires 1 to 32 distinct regions".into());
+ return Err(format!("capture requires 1 to {MAX_CAPTURE_REGIONS} distinct regions"));
}
let spec: Value = serde_json::from_slice(
self.bytes(spec_path)
diff --git a/crates/cli/tests/entry_capture.rs b/crates/cli/tests/entry_capture.rs
index e260ee4fe..ee8838fac 100644
--- a/crates/cli/tests/entry_capture.rs
+++ b/crates/cli/tests/entry_capture.rs
@@ -1,3 +1,6 @@
+#[path = "support/capture_service.rs"]
+#[allow(dead_code)]
+mod capture_service;
use impeccable::entry_capture::{CdpEntryRenderer, static_inventory};
use impeccable_comp::{png_io, raster};
use impeccable_comp_verbs::entry_capture::{EntryRenderer, EntryRequest, EntryStage};
@@ -95,3 +98,24 @@ fn entry_renderer_returns_fresh_hero_and_responsive_pixels_with_live_input_guard
fs::write(f.0.join("assets/art.png"), before).unwrap();
}
}
+
+#[test]
+fn host_capture_service_keeps_one_receipt_per_raster_region() {
+ if impeccable_browser::discovery::find_browser(&std::env::vars().collect()).is_err() {
+ eprintln!("skip: browser unavailable");
+ return;
+ }
+ let f = Fixture::new();
+ let service = capture_service::CaptureService::start(&f.0, None);
+ let remote = service.renderer();
+ for stage in [EntryStage::Hero, EntryStage::Responsive] {
+ let captured = remote.capture_entry(&f.request(stage)).unwrap();
+ let evidence = captured.evidence();
+ assert!(evidence.report.get("captureMethod").is_none());
+ for frame in &evidence.frames {
+ let ids: Vec<_> = frame.regions.iter().map(|r| r.receipt["regionId"].clone()).collect();
+ assert_eq!(ids, [serde_json::json!("art")], "{}", frame.name);
+ }
+ captured.verify_current().unwrap();
+ }
+}
diff --git a/crates/cli/tests/support/capture_service.rs b/crates/cli/tests/support/capture_service.rs
new file mode 100644
index 000000000..0c531d89f
--- /dev/null
+++ b/crates/cli/tests/support/capture_service.rs
@@ -0,0 +1,109 @@
+//! The host capture service as NATIVE-CAPTURE.md describes it: the engine
+//! binary's `capture-server <registered-project> <ready-file>`, a host-generated
+//! capability, and a client configured only through the port and capability.
+use impeccable::capture_service::RemoteEntryRenderer;
+use impeccable_comp_verbs::asset_capture::capture_sha256;
+use serde_json::Value;
+use std::{
+ collections::HashMap,
+ io::{Read, Write},
+ net::TcpStream,
+ path::{Path, PathBuf},
+ process::{Child, Command, Stdio},
+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},
+};
+
+pub struct CaptureService {
+ child: Child,
+ dir: PathBuf,
+ pub port: u16,
+ pub key: String,
+}
+impl CaptureService {
+ /// `session` is the host-selected review session (outside the project).
+ pub fn start(project: &Path, session: Option<&Path>) -> Self {
+ let nonce = format!(
+ "{}-{}",
+ std::process::id(),
+ SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()
+ );
+ let dir = std::env::temp_dir().join(format!("capture-service-{nonce}"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let ready = dir.join("ready.json");
+ let key = capture_sha256(nonce.as_bytes());
+ let mut command = Command::new(env!("CARGO_BIN_EXE_impeccable"));
+ command
+ .arg("capture-server")
+ .arg(project)
+ .arg(&ready)
+ .env("IMPECCABLE_CAPTURE_CAPABILITY", &key)
+ .env_remove("IMPECCABLE_COMPONENT_REVIEW_PENDING")
+ .env_remove("IMPECCABLE_CAPTURE_REVIEW_SESSION")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit());
+ if let Some(session) = session {
+ command.env("IMPECCABLE_CAPTURE_REVIEW_SESSION", session);
+ }
+ let mut child = command.spawn().expect("start capture-server");
+ let started = Instant::now();
+ let port = loop {
+ if let Some(port) = std::fs::read(&ready)
+ .ok()
+ .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
+ .and_then(|v| v["port"].as_u64())
+ {
+ break port as u16;
+ }
+ let failure = match child.try_wait() {
+ Ok(Some(status)) => Some(format!("capture-server exited before it was ready: {status}")),
+ Err(e) => Some(format!("capture-server status unavailable: {e}")),
+ Ok(None) if started.elapsed() > Duration::from_secs(60) => {
+ Some("capture-server never wrote its ready file".into())
+ }
+ Ok(None) => None,
+ };
+ if let Some(failure) = failure {
+ let _ = child.kill();
+ let _ = child.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+ panic!("{failure}");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ };
+ Self { child, dir, port, key }
+ }
+ /// The client exactly as build-phase builds it from the host's environment.
+ pub fn renderer(&self) -> RemoteEntryRenderer {
+ let env = HashMap::from([
+ ("IMPECCABLE_CAPTURE_PORT".to_string(), self.port.to_string()),
+ ("IMPECCABLE_CAPTURE_CAPABILITY".to_string(), self.key.clone()),
+ ]);
+ RemoteEntryRenderer::from_env(&env).unwrap().expect("service configured")
+ }
+ /// A host request (the audit endpoint is the host adapter's, not the client's).
+ pub fn post(&self, route: &str, body: &Value) -> Value {
+ let body = serde_json::to_vec(body).unwrap();
+ let mut stream = TcpStream::connect(("127.0.0.1", self.port)).unwrap();
+ stream.set_read_timeout(Some(Duration::from_secs(150))).unwrap();
+ write!(
+ stream,
+ "POST {route} HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Capture-Key: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ self.key,
+ body.len()
+ )
+ .unwrap();
+ stream.write_all(&body).unwrap();
+ let mut bytes = Vec::new();
+ stream.read_to_end(&mut bytes).unwrap();
+ let split = bytes.windows(4).position(|w| w == b"\r\n\r\n").expect("HTTP response");
+ serde_json::from_slice(&bytes[split + 4..]).unwrap()
+ }
+}
+impl Drop for CaptureService {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ let _ = std::fs::remove_dir_all(&self.dir);
+ }
+}
diff --git a/crates/cli/tests/text_only_entry.rs b/crates/cli/tests/text_only_entry.rs
index fadc1663b..6af85c733 100644
--- a/crates/cli/tests/text_only_entry.rs
+++ b/crates/cli/tests/text_only_entry.rs
@@ -8,6 +8,10 @@ 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};
+#[path = "support/capture_service.rs"]
+#[allow(dead_code)]
+mod capture_service;
+use capture_service::CaptureService;
use std::{
fs,
path::PathBuf,
@@ -65,15 +69,18 @@ impl Fixture {
/// 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 renderer = ReviewedEntryRenderer::local(&self.project, Some(&self.home));
+ self.run_with(args, &renderer)
+ }
+ fn run_with(&self, args: &[&str], renderer: &dyn EntryRenderer) -> (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));
+ let code = build_phase::run_with_renderer(&argv, &mut io, &build_phase::no_organic_scan, Some(renderer));
drop(io);
let text = format!(
"{}{}",
@@ -83,7 +90,11 @@ impl Fixture {
(code, text)
}
fn record_hero(&self) -> (bool, String, Value) {
- let (code, text) = self.run(&["record", "hero", "--min", "0.95"]);
+ let renderer = ReviewedEntryRenderer::local(&self.project, Some(&self.home));
+ self.record_hero_with(&renderer)
+ }
+ fn record_hero_with(&self, renderer: &dyn EntryRenderer) -> (bool, String, Value) {
+ let (code, text) = self.run_with(&["record", "hero", "--min", "0.95"], renderer);
let report = fs::read(self.project.join(".impeccable/review/diff/hero/report.json"))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
@@ -92,11 +103,15 @@ impl Fixture {
}
/// 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();
+ /// Where the local review store keeps this project's first-viewport review.
+ fn session(&self) -> PathBuf {
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);
+ self.home.join(".impeccable/component-reviews").join(key)
+ }
+ fn approve(&self, screenshot: &[u8]) {
+ fs::write(self.project.join(".impeccable/review/hero.json"), br#"{"id":"hero"}"#).unwrap();
+ let session = self.session();
fs::create_dir_all(session.join("blobs")).unwrap();
let png = capture_sha256(screenshot);
fs::write(session.join("blobs").join(&png), screenshot).unwrap();
@@ -420,3 +435,64 @@ fn svg_fragment_masks_and_patterns_are_code_not_raster() {
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();
}
+
+#[test]
+fn host_capture_service_carries_a_text_only_hero_and_binds_its_accepted_review() {
+ if !browser_available() {
+ return;
+ }
+ let f = Fixture::new();
+ 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();
+ fs::write(f.project.join("index.html"), strokes("90deg")).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 host owns the service and selects the review session before the build.
+ let service = CaptureService::start(&f.project, Some(&f.session()));
+ let remote = service.renderer();
+
+ // Both stages cross the transport with receipt-free frames.
+ for (stage, names) in [(EntryStage::Hero, &["hero"][..]), (EntryStage::Responsive, &["desktop", "mobile"][..])] {
+ let captured = remote.capture_entry(&f.request(stage)).unwrap();
+ let evidence = captured.evidence();
+ assert_eq!(evidence.report["captureMethod"], "assembled-page-viewport");
+ assert_eq!(evidence.report["captureService"]["schema"], "native-capture-service-v1");
+ assert_eq!(evidence.report["dependencyPolicy"], "static-inventory");
+ assert!(evidence.report["servedToPage"].as_array().is_some_and(|s| !s.is_empty()));
+ assert_eq!(evidence.frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), names);
+ for frame in &evidence.frames {
+ assert!(frame.regions.is_empty());
+ assert!(evidence.report["frameProofs"][&frame.name]["rasterCoverage"]["share"].as_f64().is_some());
+ }
+ captured.verify_current().unwrap();
+ }
+
+ // record hero reaches the gate's readings instead of failing at capture.
+ let (ok, text, report) = f.record_hero_with(&remote);
+ assert!(!ok, "{text}");
+ assert!(!text.contains("capture unavailable") && !text.contains("invalid native capture"), "{text}");
+ assert_eq!(report["nativeCapture"]["inputs"]["captureMethod"], "assembled-page-viewport");
+ assert_eq!(report["nativeCapture"]["inputs"]["humanTextReview"]["status"], "not-current");
+
+ // The user accepts that first viewport; through the service it binds and passes.
+ f.approve(&hero);
+ let (ok, text, report) = f.record_hero_with(&remote);
+ assert!(ok, "{text}");
+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], true, "{report}");
+ assert_eq!(report["nativeCapture"]["inputs"]["humanTextReview"]["schema"], "human-assembled-reference-v1");
+
+ // The host audit matches the saved receipt-free evidence against its own capture.
+ let audit = service.post("/audit", &json!({"stage":"hero"}));
+ assert_eq!(audit["ok"], true, "{audit}");
+ let saved: Vec<_> = audit["savedEvidence"].as_array().unwrap().iter().filter_map(|e| e["path"].as_str()).collect();
+ for name in ["inputs.json", "human-approved.png", "hero.png", "hero-observations.json"] {
+ assert!(saved.contains(&format!(".impeccable/review/native/hero/{name}").as_str()), "{saved:?}");
+ }
+ assert_eq!(fs::read_to_string(f.project.join(".impeccable/review/native/hero/hero-observations.json")).unwrap().trim(), "[]");
+}
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 66b54fede..784e941bc 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -1958,6 +1958,8 @@ The hero gate uses the same evidence. When the native hero capture carries an ap
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.
+Through the host capture service (`IMPECCABLE_CAPTURE_PORT` and `IMPECCABLE_CAPTURE_CAPABILITY`), the same capture crosses unchanged: the service returns each frame's receipts as `regions`, and the report with every field above plus `captureService`. The client reads the bound spec from the project, checks its SHA-256 against the spec entry in the capture's input manifest (a spec edited since the capture is refused), and lets the spec decide the kind. A spec with no `raster` region requires `"captureMethod": "assembled-page-viewport"`, an empty `regions` list in every frame, a `frameProofs` entry per frame whose `rasterCoverage.share` is under the 15% limit, a `dependencyPolicy` of `hero-review-manifest` or `static-inventory`, and a `servedToPage` list that names neither the spec nor the comp. A spec with raster regions requires any other capture method and, in each frame, exactly one receipt per raster region the in-process capture measures there (every raster region in `hero` and `desktop`, the first one in `mobile`), at most 32. 32 is the native batch bound: the in-process capture refuses a frame with more raster regions, so the service can never return more. Anything else, including a raster capture with an empty `regions` list or a text-only method claimed for a raster spec, fails with `native entry capture unavailable: invalid native capture regions` (or names the mismatched method) and the capture is released. The service's `/audit` endpoint compares the saved `<frame>-observations.json` (`[]` for a text-only frame), frame PNGs, `inputs.json` and `human-approved.png` against its own capture as for raster captures.
+
For native comp-led runs, a verified assembled-page review can resolve a text-style contradiction against the original comp. The renderer reads the private native review session, binds the approved screenshot (verified receipt, capture digest and blob hash) and the comp bytes, and compares the disputed text region against that human-approved rendering at the current desktop breakpoint. The original comp scores remain in the report; accepted region IDs and the review revision are recorded separately under `humanTextReview`.
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/NATIVE-CAPTURE.md b/docs/NATIVE-CAPTURE.md
index cf2a00e08..afc2aa955 100644
--- a/docs/NATIVE-CAPTURE.md
+++ b/docs/NATIVE-CAPTURE.md
@@ -10,6 +10,8 @@ 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.
+
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.
Raster observations use software rasterization so temporary image suppression restores exact pixels despite GPU tile rounding. Capture-induced CSS transitions finish naturally within a bounded wait; authored styles and motion settings remain intact. DOM, geometry, document identity, response identity and exact pixel restoration still have to match.